sqlite3.c 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.1. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqlite3.h *****************************************/
  29. /*
  30. ** 2001 September 15
  31. **
  32. ** The author disclaims copyright to this source code. In place of
  33. ** a legal notice, here is a blessing:
  34. **
  35. ** May you do good and not evil.
  36. ** May you find forgiveness for yourself and forgive others.
  37. ** May you share freely, never taking more than you give.
  38. **
  39. *************************************************************************
  40. ** This header file defines the interface that the SQLite library
  41. ** presents to client programs. If a C-function, structure, datatype,
  42. ** or constant definition does not appear in this file, then it is
  43. ** not a published API of SQLite, is subject to change without
  44. ** notice, and should not be referenced by programs that use SQLite.
  45. **
  46. ** Some of the definitions that are in this file are marked as
  47. ** "experimental". Experimental interfaces are normally new
  48. ** features recently added to SQLite. We do not anticipate changes
  49. ** to experimental interfaces but reserve the right to make minor changes
  50. ** if experience from use "in the wild" suggest such changes are prudent.
  51. **
  52. ** The official C-language API documentation for SQLite is derived
  53. ** from comments in this file. This file is the authoritative source
  54. ** on how SQLite interfaces are suppose to operate.
  55. **
  56. ** The name of this file under configuration management is "sqlite.h.in".
  57. ** The makefile makes some minor changes to this file (such as inserting
  58. ** the version number) and changes its name to "sqlite3.h" as
  59. ** part of the build process.
  60. */
  61. #ifndef _SQLITE3_H_
  62. #define _SQLITE3_H_
  63. #include <stdarg.h> /* Needed for the definition of va_list */
  64. /*
  65. ** Make sure we can call this stuff from C++.
  66. */
  67. #if 0
  68. extern "C" {
  69. #endif
  70. #include <rtconfig.h>
  71. /*
  72. ** Add the ability to override 'extern'
  73. */
  74. #ifndef SQLITE_EXTERN
  75. # define SQLITE_EXTERN extern
  76. #endif
  77. #ifndef SQLITE_API
  78. # define SQLITE_API
  79. #endif
  80. /*
  81. ** These no-op macros are used in front of interfaces to mark those
  82. ** interfaces as either deprecated or experimental. New applications
  83. ** should not use deprecated interfaces - they are support for backwards
  84. ** compatibility only. Application writers should be aware that
  85. ** experimental interfaces are subject to change in point releases.
  86. **
  87. ** These macros used to resolve to various kinds of compiler magic that
  88. ** would generate warning messages when they were used. But that
  89. ** compiler magic ended up generating such a flurry of bug reports
  90. ** that we have taken it all out and gone back to using simple
  91. ** noop macros.
  92. */
  93. #define SQLITE_DEPRECATED
  94. #define SQLITE_EXPERIMENTAL
  95. /*
  96. ** Ensure these symbols were not defined by some previous header file.
  97. */
  98. #ifdef SQLITE_VERSION
  99. # undef SQLITE_VERSION
  100. #endif
  101. #ifdef SQLITE_VERSION_NUMBER
  102. # undef SQLITE_VERSION_NUMBER
  103. #endif
  104. /*
  105. ** CAPI3REF: Compile-Time Library Version Numbers
  106. **
  107. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  108. ** evaluates to a string literal that is the SQLite version in the
  109. ** format "X.Y.Z" where X is the major version number (always 3 for
  110. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  111. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  112. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  113. ** numbers used in [SQLITE_VERSION].)^
  114. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  115. ** be larger than the release from which it is derived. Either Y will
  116. ** be held constant and Z will be incremented or else Y will be incremented
  117. ** and Z will be reset to zero.
  118. **
  119. ** Since version 3.6.18, SQLite source code has been stored in the
  120. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  121. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  122. ** a string which identifies a particular check-in of SQLite
  123. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  124. ** string contains the date and time of the check-in (UTC) and an SHA1
  125. ** hash of the entire source tree.
  126. **
  127. ** See also: [sqlite3_libversion()],
  128. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  129. ** [sqlite_version()] and [sqlite_source_id()].
  130. */
  131. #define SQLITE_VERSION "3.8.1"
  132. #define SQLITE_VERSION_NUMBER 3008001
  133. #define SQLITE_SOURCE_ID "2013-10-17 12:57:35 c78be6d786c19073b3a6730dfe3fb1be54f5657a"
  134. /*
  135. ** CAPI3REF: Run-Time Library Version Numbers
  136. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  137. **
  138. ** These interfaces provide the same information as the [SQLITE_VERSION],
  139. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  140. ** but are associated with the library instead of the header file. ^(Cautious
  141. ** programmers might include assert() statements in their application to
  142. ** verify that values returned by these interfaces match the macros in
  143. ** the header, and thus insure that the application is
  144. ** compiled with matching library and header files.
  145. **
  146. ** <blockquote><pre>
  147. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  148. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  149. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  150. ** </pre></blockquote>)^
  151. **
  152. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  153. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  154. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  155. ** function is provided for use in DLLs since DLL users usually do not have
  156. ** direct access to string constants within the DLL. ^The
  157. ** sqlite3_libversion_number() function returns an integer equal to
  158. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  159. ** a pointer to a string constant whose value is the same as the
  160. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  161. **
  162. ** See also: [sqlite_version()] and [sqlite_source_id()].
  163. */
  164. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  165. SQLITE_API const char *sqlite3_libversion(void);
  166. SQLITE_API const char *sqlite3_sourceid(void);
  167. SQLITE_API int sqlite3_libversion_number(void);
  168. /*
  169. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  170. **
  171. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  172. ** indicating whether the specified option was defined at
  173. ** compile time. ^The SQLITE_ prefix may be omitted from the
  174. ** option name passed to sqlite3_compileoption_used().
  175. **
  176. ** ^The sqlite3_compileoption_get() function allows iterating
  177. ** over the list of options that were defined at compile time by
  178. ** returning the N-th compile time option string. ^If N is out of range,
  179. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  180. ** prefix is omitted from any strings returned by
  181. ** sqlite3_compileoption_get().
  182. **
  183. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  184. ** and sqlite3_compileoption_get() may be omitted by specifying the
  185. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  186. **
  187. ** See also: SQL functions [sqlite_compileoption_used()] and
  188. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  189. */
  190. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  191. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  192. SQLITE_API const char *sqlite3_compileoption_get(int N);
  193. #endif
  194. /*
  195. ** CAPI3REF: Test To See If The Library Is Threadsafe
  196. **
  197. ** ^The sqlite3_threadsafe() function returns zero if and only if
  198. ** SQLite was compiled with mutexing code omitted due to the
  199. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  200. **
  201. ** SQLite can be compiled with or without mutexes. When
  202. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  203. ** are enabled and SQLite is threadsafe. When the
  204. ** [SQLITE_THREADSAFE] macro is 0,
  205. ** the mutexes are omitted. Without the mutexes, it is not safe
  206. ** to use SQLite concurrently from more than one thread.
  207. **
  208. ** Enabling mutexes incurs a measurable performance penalty.
  209. ** So if speed is of utmost importance, it makes sense to disable
  210. ** the mutexes. But for maximum safety, mutexes should be enabled.
  211. ** ^The default behavior is for mutexes to be enabled.
  212. **
  213. ** This interface can be used by an application to make sure that the
  214. ** version of SQLite that it is linking against was compiled with
  215. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  216. **
  217. ** This interface only reports on the compile-time mutex setting
  218. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  219. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  220. ** can be fully or partially disabled using a call to [sqlite3_config()]
  221. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  222. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  223. ** sqlite3_threadsafe() function shows only the compile-time setting of
  224. ** thread safety, not any run-time changes to that setting made by
  225. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  226. ** is unchanged by calls to sqlite3_config().)^
  227. **
  228. ** See the [threading mode] documentation for additional information.
  229. */
  230. SQLITE_API int sqlite3_threadsafe(void);
  231. /*
  232. ** CAPI3REF: Database Connection Handle
  233. ** KEYWORDS: {database connection} {database connections}
  234. **
  235. ** Each open SQLite database is represented by a pointer to an instance of
  236. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  237. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  238. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  239. ** and [sqlite3_close_v2()] are its destructors. There are many other
  240. ** interfaces (such as
  241. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  242. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  243. ** sqlite3 object.
  244. */
  245. typedef struct sqlite3 sqlite3;
  246. /*
  247. ** CAPI3REF: 64-Bit Integer Types
  248. ** KEYWORDS: sqlite_int64 sqlite_uint64
  249. **
  250. ** Because there is no cross-platform way to specify 64-bit integer types
  251. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  252. **
  253. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  254. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  255. ** compatibility only.
  256. **
  257. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  258. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  259. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  260. ** between 0 and +18446744073709551615 inclusive.
  261. */
  262. #ifdef SQLITE_INT64_TYPE
  263. typedef SQLITE_INT64_TYPE sqlite_int64;
  264. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  265. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  266. typedef __int64 sqlite_int64;
  267. typedef unsigned __int64 sqlite_uint64;
  268. #else
  269. typedef long long int sqlite_int64;
  270. typedef unsigned long long int sqlite_uint64;
  271. #endif
  272. typedef sqlite_int64 sqlite3_int64;
  273. typedef sqlite_uint64 sqlite3_uint64;
  274. /*
  275. ** If compiling for a processor that lacks floating point support,
  276. ** substitute integer for floating-point.
  277. */
  278. #ifdef SQLITE_OMIT_FLOATING_POINT
  279. # define double sqlite3_int64
  280. #endif
  281. /*
  282. ** CAPI3REF: Closing A Database Connection
  283. **
  284. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  285. ** for the [sqlite3] object.
  286. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return SQLITE_OK if
  287. ** the [sqlite3] object is successfully destroyed and all associated
  288. ** resources are deallocated.
  289. **
  290. ** ^If the database connection is associated with unfinalized prepared
  291. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  292. ** will leave the database connection open and return [SQLITE_BUSY].
  293. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  294. ** and unfinished sqlite3_backups, then the database connection becomes
  295. ** an unusable "zombie" which will automatically be deallocated when the
  296. ** last prepared statement is finalized or the last sqlite3_backup is
  297. ** finished. The sqlite3_close_v2() interface is intended for use with
  298. ** host languages that are garbage collected, and where the order in which
  299. ** destructors are called is arbitrary.
  300. **
  301. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  302. ** [sqlite3_blob_close | close] all [BLOB handles], and
  303. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  304. ** with the [sqlite3] object prior to attempting to close the object. ^If
  305. ** sqlite3_close_v2() is called on a [database connection] that still has
  306. ** outstanding [prepared statements], [BLOB handles], and/or
  307. ** [sqlite3_backup] objects then it returns SQLITE_OK but the deallocation
  308. ** of resources is deferred until all [prepared statements], [BLOB handles],
  309. ** and [sqlite3_backup] objects are also destroyed.
  310. **
  311. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  312. ** the transaction is automatically rolled back.
  313. **
  314. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  315. ** must be either a NULL
  316. ** pointer or an [sqlite3] object pointer obtained
  317. ** from [sqlite3_open()], [sqlite3_open16()], or
  318. ** [sqlite3_open_v2()], and not previously closed.
  319. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  320. ** argument is a harmless no-op.
  321. */
  322. SQLITE_API int sqlite3_close(sqlite3*);
  323. SQLITE_API int sqlite3_close_v2(sqlite3*);
  324. /*
  325. ** The type for a callback function.
  326. ** This is legacy and deprecated. It is included for historical
  327. ** compatibility and is not documented.
  328. */
  329. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  330. /*
  331. ** CAPI3REF: One-Step Query Execution Interface
  332. **
  333. ** The sqlite3_exec() interface is a convenience wrapper around
  334. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  335. ** that allows an application to run multiple statements of SQL
  336. ** without having to use a lot of C code.
  337. **
  338. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  339. ** semicolon-separate SQL statements passed into its 2nd argument,
  340. ** in the context of the [database connection] passed in as its 1st
  341. ** argument. ^If the callback function of the 3rd argument to
  342. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  343. ** coming out of the evaluated SQL statements. ^The 4th argument to
  344. ** sqlite3_exec() is relayed through to the 1st argument of each
  345. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  346. ** is NULL, then no callback is ever invoked and result rows are
  347. ** ignored.
  348. **
  349. ** ^If an error occurs while evaluating the SQL statements passed into
  350. ** sqlite3_exec(), then execution of the current statement stops and
  351. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  352. ** is not NULL then any error message is written into memory obtained
  353. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  354. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  355. ** on error message strings returned through the 5th parameter of
  356. ** of sqlite3_exec() after the error message string is no longer needed.
  357. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  358. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  359. ** NULL before returning.
  360. **
  361. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  362. ** routine returns SQLITE_ABORT without invoking the callback again and
  363. ** without running any subsequent SQL statements.
  364. **
  365. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  366. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  367. ** callback is an array of pointers to strings obtained as if from
  368. ** [sqlite3_column_text()], one for each column. ^If an element of a
  369. ** result row is NULL then the corresponding string pointer for the
  370. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  371. ** sqlite3_exec() callback is an array of pointers to strings where each
  372. ** entry represents the name of corresponding result column as obtained
  373. ** from [sqlite3_column_name()].
  374. **
  375. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  376. ** to an empty string, or a pointer that contains only whitespace and/or
  377. ** SQL comments, then no SQL statements are evaluated and the database
  378. ** is not changed.
  379. **
  380. ** Restrictions:
  381. **
  382. ** <ul>
  383. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  384. ** is a valid and open [database connection].
  385. ** <li> The application must not close [database connection] specified by
  386. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  387. ** <li> The application must not modify the SQL statement text passed into
  388. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  389. ** </ul>
  390. */
  391. SQLITE_API int sqlite3_exec(
  392. sqlite3*, /* An open database */
  393. const char *sql, /* SQL to be evaluated */
  394. int (*callback)(void*,int,char**,char**), /* Callback function */
  395. void *, /* 1st argument to callback */
  396. char **errmsg /* Error msg written here */
  397. );
  398. /*
  399. ** CAPI3REF: Result Codes
  400. ** KEYWORDS: SQLITE_OK {error code} {error codes}
  401. ** KEYWORDS: {result code} {result codes}
  402. **
  403. ** Many SQLite functions return an integer result code from the set shown
  404. ** here in order to indicate success or failure.
  405. **
  406. ** New error codes may be added in future versions of SQLite.
  407. **
  408. ** See also: [SQLITE_IOERR_READ | extended result codes],
  409. ** [sqlite3_vtab_on_conflict()] [SQLITE_ROLLBACK | result codes].
  410. */
  411. #define SQLITE_OK 0 /* Successful result */
  412. /* beginning-of-error-codes */
  413. #define SQLITE_ERROR 1 /* SQL error or missing database */
  414. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  415. #define SQLITE_PERM 3 /* Access permission denied */
  416. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  417. #define SQLITE_BUSY 5 /* The database file is locked */
  418. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  419. #define SQLITE_NOMEM 7 /* A malloc() failed */
  420. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  421. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  422. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  423. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  424. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  425. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  426. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  427. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  428. #define SQLITE_EMPTY 16 /* Database is empty */
  429. #define SQLITE_SCHEMA 17 /* The database schema changed */
  430. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  431. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  432. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  433. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  434. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  435. #define SQLITE_AUTH 23 /* Authorization denied */
  436. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  437. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  438. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  439. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  440. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  441. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  442. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  443. /* end-of-error-codes */
  444. /*
  445. ** CAPI3REF: Extended Result Codes
  446. ** KEYWORDS: {extended error code} {extended error codes}
  447. ** KEYWORDS: {extended result code} {extended result codes}
  448. **
  449. ** In its default configuration, SQLite API routines return one of 26 integer
  450. ** [SQLITE_OK | result codes]. However, experience has shown that many of
  451. ** these result codes are too coarse-grained. They do not provide as
  452. ** much information about problems as programmers might like. In an effort to
  453. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  454. ** support for additional result codes that provide more detailed information
  455. ** about errors. The extended result codes are enabled or disabled
  456. ** on a per database connection basis using the
  457. ** [sqlite3_extended_result_codes()] API.
  458. **
  459. ** Some of the available extended result codes are listed here.
  460. ** One may expect the number of extended result codes will be expand
  461. ** over time. Software that uses extended result codes should expect
  462. ** to see new result codes in future releases of SQLite.
  463. **
  464. ** The SQLITE_OK result code will never be extended. It will always
  465. ** be exactly zero.
  466. */
  467. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  468. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  469. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  470. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  471. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  472. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  473. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  474. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  475. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  476. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  477. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  478. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  479. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  480. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  481. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  482. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  483. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  484. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  485. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  486. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  487. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  488. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  489. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  490. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  491. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  492. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  493. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  494. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  495. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  496. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  497. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  498. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  499. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  500. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  501. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  502. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  503. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  504. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  505. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  506. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  507. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  508. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  509. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  510. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  511. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  512. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  513. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  514. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  515. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  516. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  517. /*
  518. ** CAPI3REF: Flags For File Open Operations
  519. **
  520. ** These bit values are intended for use in the
  521. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  522. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  523. */
  524. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  525. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  526. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  527. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  528. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  529. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  530. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  531. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  532. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  533. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  534. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  535. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  536. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  537. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  538. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  539. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  540. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  541. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  542. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  543. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  544. /* Reserved: 0x00F00000 */
  545. /*
  546. ** CAPI3REF: Device Characteristics
  547. **
  548. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  549. ** object returns an integer which is a vector of these
  550. ** bit values expressing I/O characteristics of the mass storage
  551. ** device that holds the file that the [sqlite3_io_methods]
  552. ** refers to.
  553. **
  554. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  555. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  556. ** mean that writes of blocks that are nnn bytes in size and
  557. ** are aligned to an address which is an integer multiple of
  558. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  559. ** that when data is appended to a file, the data is appended
  560. ** first then the size of the file is extended, never the other
  561. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  562. ** information is written to disk in the same order as calls
  563. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  564. ** after reboot following a crash or power loss, the only bytes in a
  565. ** file that were written at the application level might have changed
  566. ** and that adjacent bytes, even bytes within the same sector are
  567. ** guaranteed to be unchanged.
  568. */
  569. #define SQLITE_IOCAP_ATOMIC 0x00000001
  570. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  571. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  572. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  573. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  574. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  575. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  576. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  577. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  578. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  579. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  580. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  581. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  582. /*
  583. ** CAPI3REF: File Locking Levels
  584. **
  585. ** SQLite uses one of these integer values as the second
  586. ** argument to calls it makes to the xLock() and xUnlock() methods
  587. ** of an [sqlite3_io_methods] object.
  588. */
  589. #define SQLITE_LOCK_NONE 0
  590. #define SQLITE_LOCK_SHARED 1
  591. #define SQLITE_LOCK_RESERVED 2
  592. #define SQLITE_LOCK_PENDING 3
  593. #define SQLITE_LOCK_EXCLUSIVE 4
  594. /*
  595. ** CAPI3REF: Synchronization Type Flags
  596. **
  597. ** When SQLite invokes the xSync() method of an
  598. ** [sqlite3_io_methods] object it uses a combination of
  599. ** these integer values as the second argument.
  600. **
  601. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  602. ** sync operation only needs to flush data to mass storage. Inode
  603. ** information need not be flushed. If the lower four bits of the flag
  604. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  605. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  606. ** to use Mac OS X style fullsync instead of fsync().
  607. **
  608. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  609. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  610. ** settings. The [synchronous pragma] determines when calls to the
  611. ** xSync VFS method occur and applies uniformly across all platforms.
  612. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  613. ** energetic or rigorous or forceful the sync operations are and
  614. ** only make a difference on Mac OSX for the default SQLite code.
  615. ** (Third-party VFS implementations might also make the distinction
  616. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  617. ** operating systems natively supported by SQLite, only Mac OSX
  618. ** cares about the difference.)
  619. */
  620. #define SQLITE_SYNC_NORMAL 0x00002
  621. #define SQLITE_SYNC_FULL 0x00003
  622. #define SQLITE_SYNC_DATAONLY 0x00010
  623. /*
  624. ** CAPI3REF: OS Interface Open File Handle
  625. **
  626. ** An [sqlite3_file] object represents an open file in the
  627. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  628. ** implementations will
  629. ** want to subclass this object by appending additional fields
  630. ** for their own use. The pMethods entry is a pointer to an
  631. ** [sqlite3_io_methods] object that defines methods for performing
  632. ** I/O operations on the open file.
  633. */
  634. typedef struct sqlite3_file sqlite3_file;
  635. struct sqlite3_file {
  636. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  637. };
  638. /*
  639. ** CAPI3REF: OS Interface File Virtual Methods Object
  640. **
  641. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  642. ** [sqlite3_file] object (or, more commonly, a subclass of the
  643. ** [sqlite3_file] object) with a pointer to an instance of this object.
  644. ** This object defines the methods used to perform various operations
  645. ** against the open file represented by the [sqlite3_file] object.
  646. **
  647. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  648. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  649. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  650. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  651. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  652. ** to NULL.
  653. **
  654. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  655. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  656. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  657. ** flag may be ORed in to indicate that only the data of the file
  658. ** and not its inode needs to be synced.
  659. **
  660. ** The integer values to xLock() and xUnlock() are one of
  661. ** <ul>
  662. ** <li> [SQLITE_LOCK_NONE],
  663. ** <li> [SQLITE_LOCK_SHARED],
  664. ** <li> [SQLITE_LOCK_RESERVED],
  665. ** <li> [SQLITE_LOCK_PENDING], or
  666. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  667. ** </ul>
  668. ** xLock() increases the lock. xUnlock() decreases the lock.
  669. ** The xCheckReservedLock() method checks whether any database connection,
  670. ** either in this process or in some other process, is holding a RESERVED,
  671. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  672. ** if such a lock exists and false otherwise.
  673. **
  674. ** The xFileControl() method is a generic interface that allows custom
  675. ** VFS implementations to directly control an open file using the
  676. ** [sqlite3_file_control()] interface. The second "op" argument is an
  677. ** integer opcode. The third argument is a generic pointer intended to
  678. ** point to a structure that may contain arguments or space in which to
  679. ** write return values. Potential uses for xFileControl() might be
  680. ** functions to enable blocking locks with timeouts, to change the
  681. ** locking strategy (for example to use dot-file locks), to inquire
  682. ** about the status of a lock, or to break stale locks. The SQLite
  683. ** core reserves all opcodes less than 100 for its own use.
  684. ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
  685. ** Applications that define a custom xFileControl method should use opcodes
  686. ** greater than 100 to avoid conflicts. VFS implementations should
  687. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  688. ** recognize.
  689. **
  690. ** The xSectorSize() method returns the sector size of the
  691. ** device that underlies the file. The sector size is the
  692. ** minimum write that can be performed without disturbing
  693. ** other bytes in the file. The xDeviceCharacteristics()
  694. ** method returns a bit vector describing behaviors of the
  695. ** underlying device:
  696. **
  697. ** <ul>
  698. ** <li> [SQLITE_IOCAP_ATOMIC]
  699. ** <li> [SQLITE_IOCAP_ATOMIC512]
  700. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  701. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  702. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  703. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  704. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  705. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  706. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  707. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  708. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  709. ** </ul>
  710. **
  711. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  712. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  713. ** mean that writes of blocks that are nnn bytes in size and
  714. ** are aligned to an address which is an integer multiple of
  715. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  716. ** that when data is appended to a file, the data is appended
  717. ** first then the size of the file is extended, never the other
  718. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  719. ** information is written to disk in the same order as calls
  720. ** to xWrite().
  721. **
  722. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  723. ** in the unread portions of the buffer with zeros. A VFS that
  724. ** fails to zero-fill short reads might seem to work. However,
  725. ** failure to zero-fill short reads will eventually lead to
  726. ** database corruption.
  727. */
  728. typedef struct sqlite3_io_methods sqlite3_io_methods;
  729. struct sqlite3_io_methods {
  730. int iVersion;
  731. int (*xClose)(sqlite3_file*);
  732. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  733. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  734. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  735. int (*xSync)(sqlite3_file*, int flags);
  736. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  737. int (*xLock)(sqlite3_file*, int);
  738. int (*xUnlock)(sqlite3_file*, int);
  739. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  740. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  741. int (*xSectorSize)(sqlite3_file*);
  742. int (*xDeviceCharacteristics)(sqlite3_file*);
  743. /* Methods above are valid for version 1 */
  744. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  745. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  746. void (*xShmBarrier)(sqlite3_file*);
  747. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  748. /* Methods above are valid for version 2 */
  749. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  750. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  751. /* Methods above are valid for version 3 */
  752. /* Additional methods may be added in future releases */
  753. };
  754. /*
  755. ** CAPI3REF: Standard File Control Opcodes
  756. **
  757. ** These integer constants are opcodes for the xFileControl method
  758. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  759. ** interface.
  760. **
  761. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  762. ** opcode causes the xFileControl method to write the current state of
  763. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  764. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  765. ** into an integer that the pArg argument points to. This capability
  766. ** is used during testing and only needs to be supported when SQLITE_TEST
  767. ** is defined.
  768. ** <ul>
  769. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  770. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  771. ** layer a hint of how large the database file will grow to be during the
  772. ** current transaction. This hint is not guaranteed to be accurate but it
  773. ** is often close. The underlying VFS might choose to preallocate database
  774. ** file space based on this hint in order to help writes to the database
  775. ** file run faster.
  776. **
  777. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  778. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  779. ** extends and truncates the database file in chunks of a size specified
  780. ** by the user. The fourth argument to [sqlite3_file_control()] should
  781. ** point to an integer (type int) containing the new chunk-size to use
  782. ** for the nominated database. Allocating database file space in large
  783. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  784. ** improve performance on some systems.
  785. **
  786. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  787. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  788. ** to the [sqlite3_file] object associated with a particular database
  789. ** connection. See the [sqlite3_file_control()] documentation for
  790. ** additional information.
  791. **
  792. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  793. ** ^(The [SQLITE_FCNTL_SYNC_OMITTED] opcode is generated internally by
  794. ** SQLite and sent to all VFSes in place of a call to the xSync method
  795. ** when the database connection has [PRAGMA synchronous] set to OFF.)^
  796. ** Some specialized VFSes need this signal in order to operate correctly
  797. ** when [PRAGMA synchronous | PRAGMA synchronous=OFF] is set, but most
  798. ** VFSes do not need this signal and should silently ignore this opcode.
  799. ** Applications should not call [sqlite3_file_control()] with this
  800. ** opcode as doing so may disrupt the operation of the specialized VFSes
  801. ** that do require it.
  802. **
  803. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  804. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  805. ** retry counts and intervals for certain disk I/O operations for the
  806. ** windows [VFS] in order to provide robustness in the presence of
  807. ** anti-virus programs. By default, the windows VFS will retry file read,
  808. ** file write, and file delete operations up to 10 times, with a delay
  809. ** of 25 milliseconds before the first retry and with the delay increasing
  810. ** by an additional 25 milliseconds with each subsequent retry. This
  811. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  812. ** to be adjusted. The values are changed for all database connections
  813. ** within the same process. The argument is a pointer to an array of two
  814. ** integers where the first integer i the new retry count and the second
  815. ** integer is the delay. If either integer is negative, then the setting
  816. ** is not changed but instead the prior value of that setting is written
  817. ** into the array entry, allowing the current retry settings to be
  818. ** interrogated. The zDbName parameter is ignored.
  819. **
  820. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  821. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  822. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  823. ** write ahead log and shared memory files used for transaction control
  824. ** are automatically deleted when the latest connection to the database
  825. ** closes. Setting persistent WAL mode causes those files to persist after
  826. ** close. Persisting the files is useful when other processes that do not
  827. ** have write permission on the directory containing the database file want
  828. ** to read the database file, as the WAL and shared memory files must exist
  829. ** in order for the database to be readable. The fourth parameter to
  830. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  831. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  832. ** WAL mode. If the integer is -1, then it is overwritten with the current
  833. ** WAL persistence setting.
  834. **
  835. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  836. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  837. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  838. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  839. ** xDeviceCharacteristics methods. The fourth parameter to
  840. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  841. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  842. ** mode. If the integer is -1, then it is overwritten with the current
  843. ** zero-damage mode setting.
  844. **
  845. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  846. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  847. ** a write transaction to indicate that, unless it is rolled back for some
  848. ** reason, the entire database file will be overwritten by the current
  849. ** transaction. This is used by VACUUM operations.
  850. **
  851. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  852. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  853. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  854. ** final bottom-level VFS are written into memory obtained from
  855. ** [sqlite3_malloc()] and the result is stored in the char* variable
  856. ** that the fourth parameter of [sqlite3_file_control()] points to.
  857. ** The caller is responsible for freeing the memory when done. As with
  858. ** all file-control actions, there is no guarantee that this will actually
  859. ** do anything. Callers should initialize the char* variable to a NULL
  860. ** pointer in case this file-control is not implemented. This file-control
  861. ** is intended for diagnostic use only.
  862. **
  863. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  864. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  865. ** file control is sent to the open [sqlite3_file] object corresponding
  866. ** to the database file to which the pragma statement refers. ^The argument
  867. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  868. ** pointers to strings (char**) in which the second element of the array
  869. ** is the name of the pragma and the third element is the argument to the
  870. ** pragma or NULL if the pragma has no argument. ^The handler for an
  871. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  872. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  873. ** or the equivalent and that string will become the result of the pragma or
  874. ** the error message if the pragma fails. ^If the
  875. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  876. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  877. ** file control returns [SQLITE_OK], then the parser assumes that the
  878. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  879. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  880. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  881. ** that the VFS encountered an error while handling the [PRAGMA] and the
  882. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  883. ** file control occurs at the beginning of pragma statement analysis and so
  884. ** it is able to override built-in [PRAGMA] statements.
  885. **
  886. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  887. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  888. ** file-control may be invoked by SQLite on the database file handle
  889. ** shortly after it is opened in order to provide a custom VFS with access
  890. ** to the connections busy-handler callback. The argument is of type (void **)
  891. ** - an array of two (void *) values. The first (void *) actually points
  892. ** to a function of type (int (*)(void *)). In order to invoke the connections
  893. ** busy-handler, this function should be invoked with the second (void *) in
  894. ** the array as the only argument. If it returns non-zero, then the operation
  895. ** should be retried. If it returns zero, the custom VFS should abandon the
  896. ** current operation.
  897. **
  898. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  899. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  900. ** to have SQLite generate a
  901. ** temporary filename using the same algorithm that is followed to generate
  902. ** temporary filenames for TEMP tables and other internal uses. The
  903. ** argument should be a char** which will be filled with the filename
  904. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  905. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  906. **
  907. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  908. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  909. ** maximum number of bytes that will be used for memory-mapped I/O.
  910. ** The argument is a pointer to a value of type sqlite3_int64 that
  911. ** is an advisory maximum number of bytes in the file to memory map. The
  912. ** pointer is overwritten with the old value. The limit is not changed if
  913. ** the value originally pointed to is negative, and so the current limit
  914. ** can be queried by passing in a pointer to a negative number. This
  915. ** file-control is used internally to implement [PRAGMA mmap_size].
  916. **
  917. ** </ul>
  918. */
  919. #define SQLITE_FCNTL_LOCKSTATE 1
  920. #define SQLITE_GET_LOCKPROXYFILE 2
  921. #define SQLITE_SET_LOCKPROXYFILE 3
  922. #define SQLITE_LAST_ERRNO 4
  923. #define SQLITE_FCNTL_SIZE_HINT 5
  924. #define SQLITE_FCNTL_CHUNK_SIZE 6
  925. #define SQLITE_FCNTL_FILE_POINTER 7
  926. #define SQLITE_FCNTL_SYNC_OMITTED 8
  927. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  928. #define SQLITE_FCNTL_PERSIST_WAL 10
  929. #define SQLITE_FCNTL_OVERWRITE 11
  930. #define SQLITE_FCNTL_VFSNAME 12
  931. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  932. #define SQLITE_FCNTL_PRAGMA 14
  933. #define SQLITE_FCNTL_BUSYHANDLER 15
  934. #define SQLITE_FCNTL_TEMPFILENAME 16
  935. #define SQLITE_FCNTL_MMAP_SIZE 18
  936. /*
  937. ** CAPI3REF: Mutex Handle
  938. **
  939. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  940. ** abstract type for a mutex object. The SQLite core never looks
  941. ** at the internal representation of an [sqlite3_mutex]. It only
  942. ** deals with pointers to the [sqlite3_mutex] object.
  943. **
  944. ** Mutexes are created using [sqlite3_mutex_alloc()].
  945. */
  946. typedef struct sqlite3_mutex sqlite3_mutex;
  947. /*
  948. ** CAPI3REF: OS Interface Object
  949. **
  950. ** An instance of the sqlite3_vfs object defines the interface between
  951. ** the SQLite core and the underlying operating system. The "vfs"
  952. ** in the name of the object stands for "virtual file system". See
  953. ** the [VFS | VFS documentation] for further information.
  954. **
  955. ** The value of the iVersion field is initially 1 but may be larger in
  956. ** future versions of SQLite. Additional fields may be appended to this
  957. ** object when the iVersion value is increased. Note that the structure
  958. ** of the sqlite3_vfs object changes in the transaction between
  959. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  960. ** modified.
  961. **
  962. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  963. ** structure used by this VFS. mxPathname is the maximum length of
  964. ** a pathname in this VFS.
  965. **
  966. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  967. ** the pNext pointer. The [sqlite3_vfs_register()]
  968. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  969. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  970. ** searches the list. Neither the application code nor the VFS
  971. ** implementation should use the pNext pointer.
  972. **
  973. ** The pNext field is the only field in the sqlite3_vfs
  974. ** structure that SQLite will ever modify. SQLite will only access
  975. ** or modify this field while holding a particular static mutex.
  976. ** The application should never modify anything within the sqlite3_vfs
  977. ** object once the object has been registered.
  978. **
  979. ** The zName field holds the name of the VFS module. The name must
  980. ** be unique across all VFS modules.
  981. **
  982. ** [[sqlite3_vfs.xOpen]]
  983. ** ^SQLite guarantees that the zFilename parameter to xOpen
  984. ** is either a NULL pointer or string obtained
  985. ** from xFullPathname() with an optional suffix added.
  986. ** ^If a suffix is added to the zFilename parameter, it will
  987. ** consist of a single "-" character followed by no more than
  988. ** 11 alphanumeric and/or "-" characters.
  989. ** ^SQLite further guarantees that
  990. ** the string will be valid and unchanged until xClose() is
  991. ** called. Because of the previous sentence,
  992. ** the [sqlite3_file] can safely store a pointer to the
  993. ** filename if it needs to remember the filename for some reason.
  994. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  995. ** must invent its own temporary name for the file. ^Whenever the
  996. ** xFilename parameter is NULL it will also be the case that the
  997. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  998. **
  999. ** The flags argument to xOpen() includes all bits set in
  1000. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1001. ** or [sqlite3_open16()] is used, then flags includes at least
  1002. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1003. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1004. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1005. **
  1006. ** ^(SQLite will also add one of the following flags to the xOpen()
  1007. ** call, depending on the object being opened:
  1008. **
  1009. ** <ul>
  1010. ** <li> [SQLITE_OPEN_MAIN_DB]
  1011. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1012. ** <li> [SQLITE_OPEN_TEMP_DB]
  1013. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1014. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1015. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1016. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1017. ** <li> [SQLITE_OPEN_WAL]
  1018. ** </ul>)^
  1019. **
  1020. ** The file I/O implementation can use the object type flags to
  1021. ** change the way it deals with files. For example, an application
  1022. ** that does not care about crash recovery or rollback might make
  1023. ** the open of a journal file a no-op. Writes to this journal would
  1024. ** also be no-ops, and any attempt to read the journal would return
  1025. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1026. ** file will be doing page-aligned sector reads and writes in a random
  1027. ** order and set up its I/O subsystem accordingly.
  1028. **
  1029. ** SQLite might also add one of the following flags to the xOpen method:
  1030. **
  1031. ** <ul>
  1032. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1033. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1034. ** </ul>
  1035. **
  1036. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1037. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1038. ** will be set for TEMP databases and their journals, transient
  1039. ** databases, and subjournals.
  1040. **
  1041. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1042. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1043. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1044. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1045. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1046. ** be created, and that it is an error if it already exists.
  1047. ** It is <i>not</i> used to indicate the file should be opened
  1048. ** for exclusive access.
  1049. **
  1050. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1051. ** to hold the [sqlite3_file] structure passed as the third
  1052. ** argument to xOpen. The xOpen method does not have to
  1053. ** allocate the structure; it should just fill it in. Note that
  1054. ** the xOpen method must set the sqlite3_file.pMethods to either
  1055. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1056. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1057. ** element will be valid after xOpen returns regardless of the success
  1058. ** or failure of the xOpen call.
  1059. **
  1060. ** [[sqlite3_vfs.xAccess]]
  1061. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1062. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1063. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1064. ** to test whether a file is at least readable. The file can be a
  1065. ** directory.
  1066. **
  1067. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1068. ** output buffer xFullPathname. The exact size of the output buffer
  1069. ** is also passed as a parameter to both methods. If the output buffer
  1070. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1071. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1072. ** to prevent this by setting mxPathname to a sufficiently large value.
  1073. **
  1074. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1075. ** interfaces are not strictly a part of the filesystem, but they are
  1076. ** included in the VFS structure for completeness.
  1077. ** The xRandomness() function attempts to return nBytes bytes
  1078. ** of good-quality randomness into zOut. The return value is
  1079. ** the actual number of bytes of randomness obtained.
  1080. ** The xSleep() method causes the calling thread to sleep for at
  1081. ** least the number of microseconds given. ^The xCurrentTime()
  1082. ** method returns a Julian Day Number for the current date and time as
  1083. ** a floating point value.
  1084. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1085. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1086. ** a 24-hour day).
  1087. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1088. ** date and time if that method is available (if iVersion is 2 or
  1089. ** greater and the function pointer is not NULL) and will fall back
  1090. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1091. **
  1092. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1093. ** are not used by the SQLite core. These optional interfaces are provided
  1094. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1095. ** system calls with functions under its control, a test program can
  1096. ** simulate faults and error conditions that would otherwise be difficult
  1097. ** or impossible to induce. The set of system calls that can be overridden
  1098. ** varies from one VFS to another, and from one version of the same VFS to the
  1099. ** next. Applications that use these interfaces must be prepared for any
  1100. ** or all of these interfaces to be NULL or for their behavior to change
  1101. ** from one release to the next. Applications must not attempt to access
  1102. ** any of these methods if the iVersion of the VFS is less than 3.
  1103. */
  1104. typedef struct sqlite3_vfs sqlite3_vfs;
  1105. typedef void (*sqlite3_syscall_ptr)(void);
  1106. struct sqlite3_vfs {
  1107. int iVersion; /* Structure version number (currently 3) */
  1108. int szOsFile; /* Size of subclassed sqlite3_file */
  1109. int mxPathname; /* Maximum file pathname length */
  1110. sqlite3_vfs *pNext; /* Next registered VFS */
  1111. const char *zName; /* Name of this virtual file system */
  1112. void *pAppData; /* Pointer to application-specific data */
  1113. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1114. int flags, int *pOutFlags);
  1115. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1116. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1117. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1118. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1119. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1120. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1121. void (*xDlClose)(sqlite3_vfs*, void*);
  1122. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1123. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1124. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1125. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1126. /*
  1127. ** The methods above are in version 1 of the sqlite_vfs object
  1128. ** definition. Those that follow are added in version 2 or later
  1129. */
  1130. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1131. /*
  1132. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1133. ** Those below are for version 3 and greater.
  1134. */
  1135. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1136. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1137. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1138. /*
  1139. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1140. ** New fields may be appended in figure versions. The iVersion
  1141. ** value will increment whenever this happens.
  1142. */
  1143. };
  1144. /*
  1145. ** CAPI3REF: Flags for the xAccess VFS method
  1146. **
  1147. ** These integer constants can be used as the third parameter to
  1148. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1149. ** what kind of permissions the xAccess method is looking for.
  1150. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1151. ** simply checks whether the file exists.
  1152. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1153. ** checks whether the named directory is both readable and writable
  1154. ** (in other words, if files can be added, removed, and renamed within
  1155. ** the directory).
  1156. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1157. ** [temp_store_directory pragma], though this could change in a future
  1158. ** release of SQLite.
  1159. ** With SQLITE_ACCESS_READ, the xAccess method
  1160. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1161. ** currently unused, though it might be used in a future release of
  1162. ** SQLite.
  1163. */
  1164. #define SQLITE_ACCESS_EXISTS 0
  1165. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1166. #define SQLITE_ACCESS_READ 2 /* Unused */
  1167. /*
  1168. ** CAPI3REF: Flags for the xShmLock VFS method
  1169. **
  1170. ** These integer constants define the various locking operations
  1171. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1172. ** following are the only legal combinations of flags to the
  1173. ** xShmLock method:
  1174. **
  1175. ** <ul>
  1176. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1177. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1178. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1179. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1180. ** </ul>
  1181. **
  1182. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1183. ** was given no the corresponding lock.
  1184. **
  1185. ** The xShmLock method can transition between unlocked and SHARED or
  1186. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1187. ** and EXCLUSIVE.
  1188. */
  1189. #define SQLITE_SHM_UNLOCK 1
  1190. #define SQLITE_SHM_LOCK 2
  1191. #define SQLITE_SHM_SHARED 4
  1192. #define SQLITE_SHM_EXCLUSIVE 8
  1193. /*
  1194. ** CAPI3REF: Maximum xShmLock index
  1195. **
  1196. ** The xShmLock method on [sqlite3_io_methods] may use values
  1197. ** between 0 and this upper bound as its "offset" argument.
  1198. ** The SQLite core will never attempt to acquire or release a
  1199. ** lock outside of this range
  1200. */
  1201. #define SQLITE_SHM_NLOCK 8
  1202. /*
  1203. ** CAPI3REF: Initialize The SQLite Library
  1204. **
  1205. ** ^The sqlite3_initialize() routine initializes the
  1206. ** SQLite library. ^The sqlite3_shutdown() routine
  1207. ** deallocates any resources that were allocated by sqlite3_initialize().
  1208. ** These routines are designed to aid in process initialization and
  1209. ** shutdown on embedded systems. Workstation applications using
  1210. ** SQLite normally do not need to invoke either of these routines.
  1211. **
  1212. ** A call to sqlite3_initialize() is an "effective" call if it is
  1213. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1214. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1215. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1216. ** of sqlite3_initialize() does any initialization. All other calls
  1217. ** are harmless no-ops.)^
  1218. **
  1219. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1220. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1221. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1222. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1223. **
  1224. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1225. ** is not. The sqlite3_shutdown() interface must only be called from a
  1226. ** single thread. All open [database connections] must be closed and all
  1227. ** other SQLite resources must be deallocated prior to invoking
  1228. ** sqlite3_shutdown().
  1229. **
  1230. ** Among other things, ^sqlite3_initialize() will invoke
  1231. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1232. ** will invoke sqlite3_os_end().
  1233. **
  1234. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1235. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1236. ** the library (perhaps it is unable to allocate a needed resource such
  1237. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1238. **
  1239. ** ^The sqlite3_initialize() routine is called internally by many other
  1240. ** SQLite interfaces so that an application usually does not need to
  1241. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1242. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1243. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1244. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1245. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1246. ** are omitted and the application must call sqlite3_initialize() directly
  1247. ** prior to using any other SQLite interface. For maximum portability,
  1248. ** it is recommended that applications always invoke sqlite3_initialize()
  1249. ** directly prior to using any other SQLite interface. Future releases
  1250. ** of SQLite may require this. In other words, the behavior exhibited
  1251. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1252. ** default behavior in some future release of SQLite.
  1253. **
  1254. ** The sqlite3_os_init() routine does operating-system specific
  1255. ** initialization of the SQLite library. The sqlite3_os_end()
  1256. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1257. ** performed by these routines include allocation or deallocation
  1258. ** of static resources, initialization of global variables,
  1259. ** setting up a default [sqlite3_vfs] module, or setting up
  1260. ** a default configuration using [sqlite3_config()].
  1261. **
  1262. ** The application should never invoke either sqlite3_os_init()
  1263. ** or sqlite3_os_end() directly. The application should only invoke
  1264. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1265. ** interface is called automatically by sqlite3_initialize() and
  1266. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1267. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1268. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1269. ** When [custom builds | built for other platforms]
  1270. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1271. ** option) the application must supply a suitable implementation for
  1272. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1273. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1274. ** must return [SQLITE_OK] on success and some other [error code] upon
  1275. ** failure.
  1276. */
  1277. SQLITE_API int sqlite3_initialize(void);
  1278. SQLITE_API int sqlite3_shutdown(void);
  1279. SQLITE_API int sqlite3_os_init(void);
  1280. SQLITE_API int sqlite3_os_end(void);
  1281. /*
  1282. ** CAPI3REF: Configuring The SQLite Library
  1283. **
  1284. ** The sqlite3_config() interface is used to make global configuration
  1285. ** changes to SQLite in order to tune SQLite to the specific needs of
  1286. ** the application. The default configuration is recommended for most
  1287. ** applications and so this routine is usually not necessary. It is
  1288. ** provided to support rare applications with unusual needs.
  1289. **
  1290. ** The sqlite3_config() interface is not threadsafe. The application
  1291. ** must insure that no other SQLite interfaces are invoked by other
  1292. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1293. ** may only be invoked prior to library initialization using
  1294. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1295. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1296. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1297. ** Note, however, that ^sqlite3_config() can be called as part of the
  1298. ** implementation of an application-defined [sqlite3_os_init()].
  1299. **
  1300. ** The first argument to sqlite3_config() is an integer
  1301. ** [configuration option] that determines
  1302. ** what property of SQLite is to be configured. Subsequent arguments
  1303. ** vary depending on the [configuration option]
  1304. ** in the first argument.
  1305. **
  1306. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1307. ** ^If the option is unknown or SQLite is unable to set the option
  1308. ** then this routine returns a non-zero [error code].
  1309. */
  1310. SQLITE_API int sqlite3_config(int, ...);
  1311. /*
  1312. ** CAPI3REF: Configure database connections
  1313. **
  1314. ** The sqlite3_db_config() interface is used to make configuration
  1315. ** changes to a [database connection]. The interface is similar to
  1316. ** [sqlite3_config()] except that the changes apply to a single
  1317. ** [database connection] (specified in the first argument).
  1318. **
  1319. ** The second argument to sqlite3_db_config(D,V,...) is the
  1320. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1321. ** that indicates what aspect of the [database connection] is being configured.
  1322. ** Subsequent arguments vary depending on the configuration verb.
  1323. **
  1324. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1325. ** the call is considered successful.
  1326. */
  1327. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1328. /*
  1329. ** CAPI3REF: Memory Allocation Routines
  1330. **
  1331. ** An instance of this object defines the interface between SQLite
  1332. ** and low-level memory allocation routines.
  1333. **
  1334. ** This object is used in only one place in the SQLite interface.
  1335. ** A pointer to an instance of this object is the argument to
  1336. ** [sqlite3_config()] when the configuration option is
  1337. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1338. ** By creating an instance of this object
  1339. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1340. ** during configuration, an application can specify an alternative
  1341. ** memory allocation subsystem for SQLite to use for all of its
  1342. ** dynamic memory needs.
  1343. **
  1344. ** Note that SQLite comes with several [built-in memory allocators]
  1345. ** that are perfectly adequate for the overwhelming majority of applications
  1346. ** and that this object is only useful to a tiny minority of applications
  1347. ** with specialized memory allocation requirements. This object is
  1348. ** also used during testing of SQLite in order to specify an alternative
  1349. ** memory allocator that simulates memory out-of-memory conditions in
  1350. ** order to verify that SQLite recovers gracefully from such
  1351. ** conditions.
  1352. **
  1353. ** The xMalloc, xRealloc, and xFree methods must work like the
  1354. ** malloc(), realloc() and free() functions from the standard C library.
  1355. ** ^SQLite guarantees that the second argument to
  1356. ** xRealloc is always a value returned by a prior call to xRoundup.
  1357. **
  1358. ** xSize should return the allocated size of a memory allocation
  1359. ** previously obtained from xMalloc or xRealloc. The allocated size
  1360. ** is always at least as big as the requested size but may be larger.
  1361. **
  1362. ** The xRoundup method returns what would be the allocated size of
  1363. ** a memory allocation given a particular requested size. Most memory
  1364. ** allocators round up memory allocations at least to the next multiple
  1365. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1366. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1367. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1368. ** that causes the corresponding memory allocation to fail.
  1369. **
  1370. ** The xInit method initializes the memory allocator. (For example,
  1371. ** it might allocate any require mutexes or initialize internal data
  1372. ** structures. The xShutdown method is invoked (indirectly) by
  1373. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1374. ** by xInit. The pAppData pointer is used as the only parameter to
  1375. ** xInit and xShutdown.
  1376. **
  1377. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1378. ** the xInit method, so the xInit method need not be threadsafe. The
  1379. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1380. ** not need to be threadsafe either. For all other methods, SQLite
  1381. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1382. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1383. ** it is by default) and so the methods are automatically serialized.
  1384. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1385. ** methods must be threadsafe or else make their own arrangements for
  1386. ** serialization.
  1387. **
  1388. ** SQLite will never invoke xInit() more than once without an intervening
  1389. ** call to xShutdown().
  1390. */
  1391. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1392. struct sqlite3_mem_methods {
  1393. void *(*xMalloc)(int); /* Memory allocation function */
  1394. void (*xFree)(void*); /* Free a prior allocation */
  1395. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1396. int (*xSize)(void*); /* Return the size of an allocation */
  1397. int (*xRoundup)(int); /* Round up request size to allocation size */
  1398. int (*xInit)(void*); /* Initialize the memory allocator */
  1399. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1400. void *pAppData; /* Argument to xInit() and xShutdown() */
  1401. };
  1402. /*
  1403. ** CAPI3REF: Configuration Options
  1404. ** KEYWORDS: {configuration option}
  1405. **
  1406. ** These constants are the available integer configuration options that
  1407. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1408. **
  1409. ** New configuration options may be added in future releases of SQLite.
  1410. ** Existing configuration options might be discontinued. Applications
  1411. ** should check the return code from [sqlite3_config()] to make sure that
  1412. ** the call worked. The [sqlite3_config()] interface will return a
  1413. ** non-zero [error code] if a discontinued or unsupported configuration option
  1414. ** is invoked.
  1415. **
  1416. ** <dl>
  1417. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1418. ** <dd>There are no arguments to this option. ^This option sets the
  1419. ** [threading mode] to Single-thread. In other words, it disables
  1420. ** all mutexing and puts SQLite into a mode where it can only be used
  1421. ** by a single thread. ^If SQLite is compiled with
  1422. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1423. ** it is not possible to change the [threading mode] from its default
  1424. ** value of Single-thread and so [sqlite3_config()] will return
  1425. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1426. ** configuration option.</dd>
  1427. **
  1428. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1429. ** <dd>There are no arguments to this option. ^This option sets the
  1430. ** [threading mode] to Multi-thread. In other words, it disables
  1431. ** mutexing on [database connection] and [prepared statement] objects.
  1432. ** The application is responsible for serializing access to
  1433. ** [database connections] and [prepared statements]. But other mutexes
  1434. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1435. ** environment as long as no two threads attempt to use the same
  1436. ** [database connection] at the same time. ^If SQLite is compiled with
  1437. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1438. ** it is not possible to set the Multi-thread [threading mode] and
  1439. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1440. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1441. **
  1442. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1443. ** <dd>There are no arguments to this option. ^This option sets the
  1444. ** [threading mode] to Serialized. In other words, this option enables
  1445. ** all mutexes including the recursive
  1446. ** mutexes on [database connection] and [prepared statement] objects.
  1447. ** In this mode (which is the default when SQLite is compiled with
  1448. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1449. ** to [database connections] and [prepared statements] so that the
  1450. ** application is free to use the same [database connection] or the
  1451. ** same [prepared statement] in different threads at the same time.
  1452. ** ^If SQLite is compiled with
  1453. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1454. ** it is not possible to set the Serialized [threading mode] and
  1455. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1456. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1457. **
  1458. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1459. ** <dd> ^(This option takes a single argument which is a pointer to an
  1460. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1461. ** alternative low-level memory allocation routines to be used in place of
  1462. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1463. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1464. ** before the [sqlite3_config()] call returns.</dd>
  1465. **
  1466. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1467. ** <dd> ^(This option takes a single argument which is a pointer to an
  1468. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1469. ** structure is filled with the currently defined memory allocation routines.)^
  1470. ** This option can be used to overload the default memory allocation
  1471. ** routines with a wrapper that simulations memory allocation failure or
  1472. ** tracks memory usage, for example. </dd>
  1473. **
  1474. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1475. ** <dd> ^This option takes single argument of type int, interpreted as a
  1476. ** boolean, which enables or disables the collection of memory allocation
  1477. ** statistics. ^(When memory allocation statistics are disabled, the
  1478. ** following SQLite interfaces become non-operational:
  1479. ** <ul>
  1480. ** <li> [sqlite3_memory_used()]
  1481. ** <li> [sqlite3_memory_highwater()]
  1482. ** <li> [sqlite3_soft_heap_limit64()]
  1483. ** <li> [sqlite3_status()]
  1484. ** </ul>)^
  1485. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1486. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1487. ** allocation statistics are disabled by default.
  1488. ** </dd>
  1489. **
  1490. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1491. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1492. ** scratch memory. There are three arguments: A pointer an 8-byte
  1493. ** aligned memory buffer from which the scratch allocations will be
  1494. ** drawn, the size of each scratch allocation (sz),
  1495. ** and the maximum number of scratch allocations (N). The sz
  1496. ** argument must be a multiple of 16.
  1497. ** The first argument must be a pointer to an 8-byte aligned buffer
  1498. ** of at least sz*N bytes of memory.
  1499. ** ^SQLite will use no more than two scratch buffers per thread. So
  1500. ** N should be set to twice the expected maximum number of threads.
  1501. ** ^SQLite will never require a scratch buffer that is more than 6
  1502. ** times the database page size. ^If SQLite needs needs additional
  1503. ** scratch memory beyond what is provided by this configuration option, then
  1504. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1505. **
  1506. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1507. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1508. ** the database page cache with the default page cache implementation.
  1509. ** This configuration should not be used if an application-define page
  1510. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1511. ** There are three arguments to this option: A pointer to 8-byte aligned
  1512. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1513. ** The sz argument should be the size of the largest database page
  1514. ** (a power of two between 512 and 32768) plus a little extra for each
  1515. ** page header. ^The page header size is 20 to 40 bytes depending on
  1516. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1517. ** to make sz a little too large. The first
  1518. ** argument should point to an allocation of at least sz*N bytes of memory.
  1519. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1520. ** memory needs for the first N pages that it adds to cache. ^If additional
  1521. ** page cache memory is needed beyond what is provided by this option, then
  1522. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1523. ** The pointer in the first argument must
  1524. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1525. ** will be undefined.</dd>
  1526. **
  1527. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1528. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1529. ** for all of its dynamic memory allocation needs beyond those provided
  1530. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1531. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1532. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1533. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1534. ** to using its default memory allocator (the system malloc() implementation),
  1535. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1536. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1537. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1538. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1539. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1540. ** boundary or subsequent behavior of SQLite will be undefined.
  1541. ** The minimum allocation size is capped at 2**12. Reasonable values
  1542. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1543. **
  1544. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1545. ** <dd> ^(This option takes a single argument which is a pointer to an
  1546. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1547. ** alternative low-level mutex routines to be used in place
  1548. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1549. ** content of the [sqlite3_mutex_methods] structure before the call to
  1550. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1551. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1552. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1553. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1554. ** return [SQLITE_ERROR].</dd>
  1555. **
  1556. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1557. ** <dd> ^(This option takes a single argument which is a pointer to an
  1558. ** instance of the [sqlite3_mutex_methods] structure. The
  1559. ** [sqlite3_mutex_methods]
  1560. ** structure is filled with the currently defined mutex routines.)^
  1561. ** This option can be used to overload the default mutex allocation
  1562. ** routines with a wrapper used to track mutex usage for performance
  1563. ** profiling or testing, for example. ^If SQLite is compiled with
  1564. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1565. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1566. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1567. ** return [SQLITE_ERROR].</dd>
  1568. **
  1569. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1570. ** <dd> ^(This option takes two arguments that determine the default
  1571. ** memory allocation for the lookaside memory allocator on each
  1572. ** [database connection]. The first argument is the
  1573. ** size of each lookaside buffer slot and the second is the number of
  1574. ** slots allocated to each database connection.)^ ^(This option sets the
  1575. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1576. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1577. ** configuration on individual connections.)^ </dd>
  1578. **
  1579. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1580. ** <dd> ^(This option takes a single argument which is a pointer to
  1581. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1582. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1583. ** object and uses it for page cache memory allocations.</dd>
  1584. **
  1585. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1586. ** <dd> ^(This option takes a single argument which is a pointer to an
  1587. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1588. ** page cache implementation into that object.)^ </dd>
  1589. **
  1590. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1591. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1592. ** global [error log].
  1593. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1594. ** function with a call signature of void(*)(void*,int,const char*),
  1595. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1596. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1597. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1598. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1599. ** passed through as the first parameter to the application-defined logger
  1600. ** function whenever that function is invoked. ^The second parameter to
  1601. ** the logger function is a copy of the first parameter to the corresponding
  1602. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1603. ** [extended result code]. ^The third parameter passed to the logger is
  1604. ** log message after formatting via [sqlite3_snprintf()].
  1605. ** The SQLite logging interface is not reentrant; the logger function
  1606. ** supplied by the application must not invoke any SQLite interface.
  1607. ** In a multi-threaded application, the application-defined logger
  1608. ** function must be threadsafe. </dd>
  1609. **
  1610. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1611. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1612. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1613. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1614. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1615. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1616. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1617. ** connection is opened. ^If it is globally disabled, filenames are
  1618. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1619. ** database connection is opened. ^(By default, URI handling is globally
  1620. ** disabled. The default value may be changed by compiling with the
  1621. ** [SQLITE_USE_URI] symbol defined.)^
  1622. **
  1623. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1624. ** <dd>^This option takes a single integer argument which is interpreted as
  1625. ** a boolean in order to enable or disable the use of covering indices for
  1626. ** full table scans in the query optimizer. ^The default setting is determined
  1627. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1628. ** if that compile-time option is omitted.
  1629. ** The ability to disable the use of covering indices for full table scans
  1630. ** is because some incorrectly coded legacy applications might malfunction
  1631. ** when the optimization is enabled. Providing the ability to
  1632. ** disable the optimization allows the older, buggy application code to work
  1633. ** without change even with newer versions of SQLite.
  1634. **
  1635. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1636. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1637. ** <dd> These options are obsolete and should not be used by new code.
  1638. ** They are retained for backwards compatibility but are now no-ops.
  1639. ** </dd>
  1640. **
  1641. ** [[SQLITE_CONFIG_SQLLOG]]
  1642. ** <dt>SQLITE_CONFIG_SQLLOG
  1643. ** <dd>This option is only available if sqlite is compiled with the
  1644. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1645. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1646. ** The second should be of type (void*). The callback is invoked by the library
  1647. ** in three separate circumstances, identified by the value passed as the
  1648. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1649. ** passed as the second argument has just been opened. The third argument
  1650. ** points to a buffer containing the name of the main database file. If the
  1651. ** fourth parameter is 1, then the SQL statement that the third parameter
  1652. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1653. ** the connection being passed as the second parameter is being closed. The
  1654. ** third parameter is passed NULL In this case. An example of using this
  1655. ** configuration option can be seen in the "test_sqllog.c" source file in
  1656. ** the canonical SQLite source tree.</dd>
  1657. **
  1658. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1659. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1660. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1661. ** that are the default mmap size limit (the default setting for
  1662. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1663. ** ^The default setting can be overridden by each database connection using
  1664. ** either the [PRAGMA mmap_size] command, or by using the
  1665. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1666. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1667. ** exceed the compile-time maximum mmap size set by the
  1668. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1669. ** ^If either argument to this option is negative, then that argument is
  1670. ** changed to its compile-time default.
  1671. ** </dl>
  1672. */
  1673. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1674. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1675. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1676. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1677. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1678. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1679. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1680. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1681. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1682. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1683. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1684. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1685. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1686. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1687. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1688. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1689. #define SQLITE_CONFIG_URI 17 /* int */
  1690. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1691. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1692. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1693. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1694. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1695. /*
  1696. ** CAPI3REF: Database Connection Configuration Options
  1697. **
  1698. ** These constants are the available integer configuration options that
  1699. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1700. **
  1701. ** New configuration options may be added in future releases of SQLite.
  1702. ** Existing configuration options might be discontinued. Applications
  1703. ** should check the return code from [sqlite3_db_config()] to make sure that
  1704. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1705. ** non-zero [error code] if a discontinued or unsupported configuration option
  1706. ** is invoked.
  1707. **
  1708. ** <dl>
  1709. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1710. ** <dd> ^This option takes three additional arguments that determine the
  1711. ** [lookaside memory allocator] configuration for the [database connection].
  1712. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1713. ** pointer to a memory buffer to use for lookaside memory.
  1714. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1715. ** may be NULL in which case SQLite will allocate the
  1716. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1717. ** size of each lookaside buffer slot. ^The third argument is the number of
  1718. ** slots. The size of the buffer in the first argument must be greater than
  1719. ** or equal to the product of the second and third arguments. The buffer
  1720. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1721. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1722. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1723. ** configuration for a database connection can only be changed when that
  1724. ** connection is not currently using lookaside memory, or in other words
  1725. ** when the "current value" returned by
  1726. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1727. ** Any attempt to change the lookaside memory configuration when lookaside
  1728. ** memory is in use leaves the configuration unchanged and returns
  1729. ** [SQLITE_BUSY].)^</dd>
  1730. **
  1731. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1732. ** <dd> ^This option is used to enable or disable the enforcement of
  1733. ** [foreign key constraints]. There should be two additional arguments.
  1734. ** The first argument is an integer which is 0 to disable FK enforcement,
  1735. ** positive to enable FK enforcement or negative to leave FK enforcement
  1736. ** unchanged. The second parameter is a pointer to an integer into which
  1737. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1738. ** following this call. The second parameter may be a NULL pointer, in
  1739. ** which case the FK enforcement setting is not reported back. </dd>
  1740. **
  1741. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1742. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1743. ** There should be two additional arguments.
  1744. ** The first argument is an integer which is 0 to disable triggers,
  1745. ** positive to enable triggers or negative to leave the setting unchanged.
  1746. ** The second parameter is a pointer to an integer into which
  1747. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1748. ** following this call. The second parameter may be a NULL pointer, in
  1749. ** which case the trigger setting is not reported back. </dd>
  1750. **
  1751. ** </dl>
  1752. */
  1753. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1754. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1755. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1756. /*
  1757. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1758. **
  1759. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1760. ** [extended result codes] feature of SQLite. ^The extended result
  1761. ** codes are disabled by default for historical compatibility.
  1762. */
  1763. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1764. /*
  1765. ** CAPI3REF: Last Insert Rowid
  1766. **
  1767. ** ^Each entry in an SQLite table has a unique 64-bit signed
  1768. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1769. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1770. ** names are not also used by explicitly declared columns. ^If
  1771. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1772. ** is another alias for the rowid.
  1773. **
  1774. ** ^This routine returns the [rowid] of the most recent
  1775. ** successful [INSERT] into the database from the [database connection]
  1776. ** in the first argument. ^As of SQLite version 3.7.7, this routines
  1777. ** records the last insert rowid of both ordinary tables and [virtual tables].
  1778. ** ^If no successful [INSERT]s
  1779. ** have ever occurred on that database connection, zero is returned.
  1780. **
  1781. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1782. ** method, then this routine will return the [rowid] of the inserted
  1783. ** row as long as the trigger or virtual table method is running.
  1784. ** But once the trigger or virtual table method ends, the value returned
  1785. ** by this routine reverts to what it was before the trigger or virtual
  1786. ** table method began.)^
  1787. **
  1788. ** ^An [INSERT] that fails due to a constraint violation is not a
  1789. ** successful [INSERT] and does not change the value returned by this
  1790. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1791. ** and INSERT OR ABORT make no changes to the return value of this
  1792. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1793. ** encounters a constraint violation, it does not fail. The
  1794. ** INSERT continues to completion after deleting rows that caused
  1795. ** the constraint problem so INSERT OR REPLACE will always change
  1796. ** the return value of this interface.)^
  1797. **
  1798. ** ^For the purposes of this routine, an [INSERT] is considered to
  1799. ** be successful even if it is subsequently rolled back.
  1800. **
  1801. ** This function is accessible to SQL statements via the
  1802. ** [last_insert_rowid() SQL function].
  1803. **
  1804. ** If a separate thread performs a new [INSERT] on the same
  1805. ** database connection while the [sqlite3_last_insert_rowid()]
  1806. ** function is running and thus changes the last insert [rowid],
  1807. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1808. ** unpredictable and might not equal either the old or the new
  1809. ** last insert [rowid].
  1810. */
  1811. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1812. /*
  1813. ** CAPI3REF: Count The Number Of Rows Modified
  1814. **
  1815. ** ^This function returns the number of database rows that were changed
  1816. ** or inserted or deleted by the most recently completed SQL statement
  1817. ** on the [database connection] specified by the first parameter.
  1818. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1819. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1820. ** triggers or [foreign key actions] are not counted.)^ Use the
  1821. ** [sqlite3_total_changes()] function to find the total number of changes
  1822. ** including changes caused by triggers and foreign key actions.
  1823. **
  1824. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1825. ** are not counted. Only real table changes are counted.
  1826. **
  1827. ** ^(A "row change" is a change to a single row of a single table
  1828. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1829. ** are changed as side effects of [REPLACE] constraint resolution,
  1830. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1831. ** mechanisms do not count as direct row changes.)^
  1832. **
  1833. ** A "trigger context" is a scope of execution that begins and
  1834. ** ends with the script of a [CREATE TRIGGER | trigger].
  1835. ** Most SQL statements are
  1836. ** evaluated outside of any trigger. This is the "top level"
  1837. ** trigger context. If a trigger fires from the top level, a
  1838. ** new trigger context is entered for the duration of that one
  1839. ** trigger. Subtriggers create subcontexts for their duration.
  1840. **
  1841. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1842. ** not create a new trigger context.
  1843. **
  1844. ** ^This function returns the number of direct row changes in the
  1845. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1846. ** trigger context.
  1847. **
  1848. ** ^Thus, when called from the top level, this function returns the
  1849. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1850. ** that also occurred at the top level. ^(Within the body of a trigger,
  1851. ** the sqlite3_changes() interface can be called to find the number of
  1852. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1853. ** statement within the body of the same trigger.
  1854. ** However, the number returned does not include changes
  1855. ** caused by subtriggers since those have their own context.)^
  1856. **
  1857. ** See also the [sqlite3_total_changes()] interface, the
  1858. ** [count_changes pragma], and the [changes() SQL function].
  1859. **
  1860. ** If a separate thread makes changes on the same database connection
  1861. ** while [sqlite3_changes()] is running then the value returned
  1862. ** is unpredictable and not meaningful.
  1863. */
  1864. SQLITE_API int sqlite3_changes(sqlite3*);
  1865. /*
  1866. ** CAPI3REF: Total Number Of Rows Modified
  1867. **
  1868. ** ^This function returns the number of row changes caused by [INSERT],
  1869. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  1870. ** ^(The count returned by sqlite3_total_changes() includes all changes
  1871. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  1872. ** [foreign key actions]. However,
  1873. ** the count does not include changes used to implement [REPLACE] constraints,
  1874. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  1875. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  1876. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  1877. ** are counted.)^
  1878. ** ^The sqlite3_total_changes() function counts the changes as soon as
  1879. ** the statement that makes them is completed (when the statement handle
  1880. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  1881. **
  1882. ** See also the [sqlite3_changes()] interface, the
  1883. ** [count_changes pragma], and the [total_changes() SQL function].
  1884. **
  1885. ** If a separate thread makes changes on the same database connection
  1886. ** while [sqlite3_total_changes()] is running then the value
  1887. ** returned is unpredictable and not meaningful.
  1888. */
  1889. SQLITE_API int sqlite3_total_changes(sqlite3*);
  1890. /*
  1891. ** CAPI3REF: Interrupt A Long-Running Query
  1892. **
  1893. ** ^This function causes any pending database operation to abort and
  1894. ** return at its earliest opportunity. This routine is typically
  1895. ** called in response to a user action such as pressing "Cancel"
  1896. ** or Ctrl-C where the user wants a long query operation to halt
  1897. ** immediately.
  1898. **
  1899. ** ^It is safe to call this routine from a thread different from the
  1900. ** thread that is currently running the database operation. But it
  1901. ** is not safe to call this routine with a [database connection] that
  1902. ** is closed or might close before sqlite3_interrupt() returns.
  1903. **
  1904. ** ^If an SQL operation is very nearly finished at the time when
  1905. ** sqlite3_interrupt() is called, then it might not have an opportunity
  1906. ** to be interrupted and might continue to completion.
  1907. **
  1908. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  1909. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  1910. ** that is inside an explicit transaction, then the entire transaction
  1911. ** will be rolled back automatically.
  1912. **
  1913. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  1914. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  1915. ** that are started after the sqlite3_interrupt() call and before the
  1916. ** running statements reaches zero are interrupted as if they had been
  1917. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  1918. ** that are started after the running statement count reaches zero are
  1919. ** not effected by the sqlite3_interrupt().
  1920. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  1921. ** SQL statements is a no-op and has no effect on SQL statements
  1922. ** that are started after the sqlite3_interrupt() call returns.
  1923. **
  1924. ** If the database connection closes while [sqlite3_interrupt()]
  1925. ** is running then bad things will likely happen.
  1926. */
  1927. SQLITE_API void sqlite3_interrupt(sqlite3*);
  1928. /*
  1929. ** CAPI3REF: Determine If An SQL Statement Is Complete
  1930. **
  1931. ** These routines are useful during command-line input to determine if the
  1932. ** currently entered text seems to form a complete SQL statement or
  1933. ** if additional input is needed before sending the text into
  1934. ** SQLite for parsing. ^These routines return 1 if the input string
  1935. ** appears to be a complete SQL statement. ^A statement is judged to be
  1936. ** complete if it ends with a semicolon token and is not a prefix of a
  1937. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  1938. ** string literals or quoted identifier names or comments are not
  1939. ** independent tokens (they are part of the token in which they are
  1940. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  1941. ** and comments that follow the final semicolon are ignored.
  1942. **
  1943. ** ^These routines return 0 if the statement is incomplete. ^If a
  1944. ** memory allocation fails, then SQLITE_NOMEM is returned.
  1945. **
  1946. ** ^These routines do not parse the SQL statements thus
  1947. ** will not detect syntactically incorrect SQL.
  1948. **
  1949. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  1950. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  1951. ** automatically by sqlite3_complete16(). If that initialization fails,
  1952. ** then the return value from sqlite3_complete16() will be non-zero
  1953. ** regardless of whether or not the input SQL is complete.)^
  1954. **
  1955. ** The input to [sqlite3_complete()] must be a zero-terminated
  1956. ** UTF-8 string.
  1957. **
  1958. ** The input to [sqlite3_complete16()] must be a zero-terminated
  1959. ** UTF-16 string in native byte order.
  1960. */
  1961. SQLITE_API int sqlite3_complete(const char *sql);
  1962. SQLITE_API int sqlite3_complete16(const void *sql);
  1963. /*
  1964. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  1965. **
  1966. ** ^This routine sets a callback function that might be invoked whenever
  1967. ** an attempt is made to open a database table that another thread
  1968. ** or process has locked.
  1969. **
  1970. ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
  1971. ** is returned immediately upon encountering the lock. ^If the busy callback
  1972. ** is not NULL, then the callback might be invoked with two arguments.
  1973. **
  1974. ** ^The first argument to the busy handler is a copy of the void* pointer which
  1975. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  1976. ** the busy handler callback is the number of times that the busy handler has
  1977. ** been invoked for this locking event. ^If the
  1978. ** busy callback returns 0, then no additional attempts are made to
  1979. ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
  1980. ** ^If the callback returns non-zero, then another attempt
  1981. ** is made to open the database for reading and the cycle repeats.
  1982. **
  1983. ** The presence of a busy handler does not guarantee that it will be invoked
  1984. ** when there is lock contention. ^If SQLite determines that invoking the busy
  1985. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  1986. ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
  1987. ** Consider a scenario where one process is holding a read lock that
  1988. ** it is trying to promote to a reserved lock and
  1989. ** a second process is holding a reserved lock that it is trying
  1990. ** to promote to an exclusive lock. The first process cannot proceed
  1991. ** because it is blocked by the second and the second process cannot
  1992. ** proceed because it is blocked by the first. If both processes
  1993. ** invoke the busy handlers, neither will make any progress. Therefore,
  1994. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  1995. ** will induce the first process to release its read lock and allow
  1996. ** the second process to proceed.
  1997. **
  1998. ** ^The default busy callback is NULL.
  1999. **
  2000. ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
  2001. ** when SQLite is in the middle of a large transaction where all the
  2002. ** changes will not fit into the in-memory cache. SQLite will
  2003. ** already hold a RESERVED lock on the database file, but it needs
  2004. ** to promote this lock to EXCLUSIVE so that it can spill cache
  2005. ** pages into the database file without harm to concurrent
  2006. ** readers. ^If it is unable to promote the lock, then the in-memory
  2007. ** cache will be left in an inconsistent state and so the error
  2008. ** code is promoted from the relatively benign [SQLITE_BUSY] to
  2009. ** the more severe [SQLITE_IOERR_BLOCKED]. ^This error code promotion
  2010. ** forces an automatic rollback of the changes. See the
  2011. ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
  2012. ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
  2013. ** this is important.
  2014. **
  2015. ** ^(There can only be a single busy handler defined for each
  2016. ** [database connection]. Setting a new busy handler clears any
  2017. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2018. ** will also set or clear the busy handler.
  2019. **
  2020. ** The busy callback should not take any actions which modify the
  2021. ** database connection that invoked the busy handler. Any such actions
  2022. ** result in undefined behavior.
  2023. **
  2024. ** A busy handler must not close the database connection
  2025. ** or [prepared statement] that invoked the busy handler.
  2026. */
  2027. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2028. /*
  2029. ** CAPI3REF: Set A Busy Timeout
  2030. **
  2031. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2032. ** for a specified amount of time when a table is locked. ^The handler
  2033. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2034. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2035. ** the handler returns 0 which causes [sqlite3_step()] to return
  2036. ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
  2037. **
  2038. ** ^Calling this routine with an argument less than or equal to zero
  2039. ** turns off all busy handlers.
  2040. **
  2041. ** ^(There can only be a single busy handler for a particular
  2042. ** [database connection] any any given moment. If another busy handler
  2043. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2044. ** this routine, that other busy handler is cleared.)^
  2045. */
  2046. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2047. /*
  2048. ** CAPI3REF: Convenience Routines For Running Queries
  2049. **
  2050. ** This is a legacy interface that is preserved for backwards compatibility.
  2051. ** Use of this interface is not recommended.
  2052. **
  2053. ** Definition: A <b>result table</b> is memory data structure created by the
  2054. ** [sqlite3_get_table()] interface. A result table records the
  2055. ** complete query results from one or more queries.
  2056. **
  2057. ** The table conceptually has a number of rows and columns. But
  2058. ** these numbers are not part of the result table itself. These
  2059. ** numbers are obtained separately. Let N be the number of rows
  2060. ** and M be the number of columns.
  2061. **
  2062. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2063. ** There are (N+1)*M elements in the array. The first M pointers point
  2064. ** to zero-terminated strings that contain the names of the columns.
  2065. ** The remaining entries all point to query results. NULL values result
  2066. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2067. ** string representation as returned by [sqlite3_column_text()].
  2068. **
  2069. ** A result table might consist of one or more memory allocations.
  2070. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2071. ** A result table should be deallocated using [sqlite3_free_table()].
  2072. **
  2073. ** ^(As an example of the result table format, suppose a query result
  2074. ** is as follows:
  2075. **
  2076. ** <blockquote><pre>
  2077. ** Name | Age
  2078. ** -----------------------
  2079. ** Alice | 43
  2080. ** Bob | 28
  2081. ** Cindy | 21
  2082. ** </pre></blockquote>
  2083. **
  2084. ** There are two column (M==2) and three rows (N==3). Thus the
  2085. ** result table has 8 entries. Suppose the result table is stored
  2086. ** in an array names azResult. Then azResult holds this content:
  2087. **
  2088. ** <blockquote><pre>
  2089. ** azResult&#91;0] = "Name";
  2090. ** azResult&#91;1] = "Age";
  2091. ** azResult&#91;2] = "Alice";
  2092. ** azResult&#91;3] = "43";
  2093. ** azResult&#91;4] = "Bob";
  2094. ** azResult&#91;5] = "28";
  2095. ** azResult&#91;6] = "Cindy";
  2096. ** azResult&#91;7] = "21";
  2097. ** </pre></blockquote>)^
  2098. **
  2099. ** ^The sqlite3_get_table() function evaluates one or more
  2100. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2101. ** string of its 2nd parameter and returns a result table to the
  2102. ** pointer given in its 3rd parameter.
  2103. **
  2104. ** After the application has finished with the result from sqlite3_get_table(),
  2105. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2106. ** release the memory that was malloced. Because of the way the
  2107. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2108. ** function must not try to call [sqlite3_free()] directly. Only
  2109. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2110. **
  2111. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2112. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2113. ** to any internal data structures of SQLite. It uses only the public
  2114. ** interface defined here. As a consequence, errors that occur in the
  2115. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2116. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2117. ** [sqlite3_errmsg()].
  2118. */
  2119. SQLITE_API int sqlite3_get_table(
  2120. sqlite3 *db, /* An open database */
  2121. const char *zSql, /* SQL to be evaluated */
  2122. char ***pazResult, /* Results of the query */
  2123. int *pnRow, /* Number of result rows written here */
  2124. int *pnColumn, /* Number of result columns written here */
  2125. char **pzErrmsg /* Error msg written here */
  2126. );
  2127. SQLITE_API void sqlite3_free_table(char **result);
  2128. /*
  2129. ** CAPI3REF: Formatted String Printing Functions
  2130. **
  2131. ** These routines are work-alikes of the "printf()" family of functions
  2132. ** from the standard C library.
  2133. **
  2134. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2135. ** results into memory obtained from [sqlite3_malloc()].
  2136. ** The strings returned by these two routines should be
  2137. ** released by [sqlite3_free()]. ^Both routines return a
  2138. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2139. ** memory to hold the resulting string.
  2140. **
  2141. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2142. ** the standard C library. The result is written into the
  2143. ** buffer supplied as the second parameter whose size is given by
  2144. ** the first parameter. Note that the order of the
  2145. ** first two parameters is reversed from snprintf().)^ This is an
  2146. ** historical accident that cannot be fixed without breaking
  2147. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2148. ** returns a pointer to its buffer instead of the number of
  2149. ** characters actually written into the buffer.)^ We admit that
  2150. ** the number of characters written would be a more useful return
  2151. ** value but we cannot change the implementation of sqlite3_snprintf()
  2152. ** now without breaking compatibility.
  2153. **
  2154. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2155. ** guarantees that the buffer is always zero-terminated. ^The first
  2156. ** parameter "n" is the total size of the buffer, including space for
  2157. ** the zero terminator. So the longest string that can be completely
  2158. ** written will be n-1 characters.
  2159. **
  2160. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2161. **
  2162. ** These routines all implement some additional formatting
  2163. ** options that are useful for constructing SQL statements.
  2164. ** All of the usual printf() formatting options apply. In addition, there
  2165. ** is are "%q", "%Q", and "%z" options.
  2166. **
  2167. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2168. ** string from the argument list. But %q also doubles every '\'' character.
  2169. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2170. ** character it escapes that character and allows it to be inserted into
  2171. ** the string.
  2172. **
  2173. ** For example, assume the string variable zText contains text as follows:
  2174. **
  2175. ** <blockquote><pre>
  2176. ** char *zText = "It's a happy day!";
  2177. ** </pre></blockquote>
  2178. **
  2179. ** One can use this text in an SQL statement as follows:
  2180. **
  2181. ** <blockquote><pre>
  2182. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2183. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2184. ** sqlite3_free(zSQL);
  2185. ** </pre></blockquote>
  2186. **
  2187. ** Because the %q format string is used, the '\'' character in zText
  2188. ** is escaped and the SQL generated is as follows:
  2189. **
  2190. ** <blockquote><pre>
  2191. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2192. ** </pre></blockquote>
  2193. **
  2194. ** This is correct. Had we used %s instead of %q, the generated SQL
  2195. ** would have looked like this:
  2196. **
  2197. ** <blockquote><pre>
  2198. ** INSERT INTO table1 VALUES('It's a happy day!');
  2199. ** </pre></blockquote>
  2200. **
  2201. ** This second example is an SQL syntax error. As a general rule you should
  2202. ** always use %q instead of %s when inserting text into a string literal.
  2203. **
  2204. ** ^(The %Q option works like %q except it also adds single quotes around
  2205. ** the outside of the total string. Additionally, if the parameter in the
  2206. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2207. ** single quotes).)^ So, for example, one could say:
  2208. **
  2209. ** <blockquote><pre>
  2210. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2211. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2212. ** sqlite3_free(zSQL);
  2213. ** </pre></blockquote>
  2214. **
  2215. ** The code above will render a correct SQL statement in the zSQL
  2216. ** variable even if the zText variable is a NULL pointer.
  2217. **
  2218. ** ^(The "%z" formatting option works like "%s" but with the
  2219. ** addition that after the string has been read and copied into
  2220. ** the result, [sqlite3_free()] is called on the input string.)^
  2221. */
  2222. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2223. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2224. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2225. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2226. /*
  2227. ** CAPI3REF: Memory Allocation Subsystem
  2228. **
  2229. ** The SQLite core uses these three routines for all of its own
  2230. ** internal memory allocation needs. "Core" in the previous sentence
  2231. ** does not include operating-system specific VFS implementation. The
  2232. ** Windows VFS uses native malloc() and free() for some operations.
  2233. **
  2234. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2235. ** of memory at least N bytes in length, where N is the parameter.
  2236. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2237. ** memory, it returns a NULL pointer. ^If the parameter N to
  2238. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2239. ** a NULL pointer.
  2240. **
  2241. ** ^Calling sqlite3_free() with a pointer previously returned
  2242. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2243. ** that it might be reused. ^The sqlite3_free() routine is
  2244. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2245. ** to sqlite3_free() is harmless. After being freed, memory
  2246. ** should neither be read nor written. Even reading previously freed
  2247. ** memory might result in a segmentation fault or other severe error.
  2248. ** Memory corruption, a segmentation fault, or other severe error
  2249. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2250. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2251. **
  2252. ** ^(The sqlite3_realloc() interface attempts to resize a
  2253. ** prior memory allocation to be at least N bytes, where N is the
  2254. ** second parameter. The memory allocation to be resized is the first
  2255. ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
  2256. ** is a NULL pointer then its behavior is identical to calling
  2257. ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
  2258. ** ^If the second parameter to sqlite3_realloc() is zero or
  2259. ** negative then the behavior is exactly the same as calling
  2260. ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
  2261. ** ^sqlite3_realloc() returns a pointer to a memory allocation
  2262. ** of at least N bytes in size or NULL if sufficient memory is unavailable.
  2263. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2264. ** of the prior allocation are copied into the beginning of buffer returned
  2265. ** by sqlite3_realloc() and the prior allocation is freed.
  2266. ** ^If sqlite3_realloc() returns NULL, then the prior allocation
  2267. ** is not freed.
  2268. **
  2269. ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
  2270. ** is always aligned to at least an 8 byte boundary, or to a
  2271. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2272. ** option is used.
  2273. **
  2274. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2275. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2276. ** implementation of these routines to be omitted. That capability
  2277. ** is no longer provided. Only built-in memory allocators can be used.
  2278. **
  2279. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2280. ** the system malloc() and free() directly when converting
  2281. ** filenames between the UTF-8 encoding used by SQLite
  2282. ** and whatever filename encoding is used by the particular Windows
  2283. ** installation. Memory allocation errors were detected, but
  2284. ** they were reported back as [SQLITE_CANTOPEN] or
  2285. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2286. **
  2287. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2288. ** must be either NULL or else pointers obtained from a prior
  2289. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2290. ** not yet been released.
  2291. **
  2292. ** The application must not read or write any part of
  2293. ** a block of memory after it has been released using
  2294. ** [sqlite3_free()] or [sqlite3_realloc()].
  2295. */
  2296. SQLITE_API void *sqlite3_malloc(int);
  2297. SQLITE_API void *sqlite3_realloc(void*, int);
  2298. SQLITE_API void sqlite3_free(void*);
  2299. /*
  2300. ** CAPI3REF: Memory Allocator Statistics
  2301. **
  2302. ** SQLite provides these two interfaces for reporting on the status
  2303. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2304. ** routines, which form the built-in memory allocation subsystem.
  2305. **
  2306. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2307. ** of memory currently outstanding (malloced but not freed).
  2308. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2309. ** value of [sqlite3_memory_used()] since the high-water mark
  2310. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2311. ** [sqlite3_memory_highwater()] include any overhead
  2312. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2313. ** but not overhead added by the any underlying system library
  2314. ** routines that [sqlite3_malloc()] may call.
  2315. **
  2316. ** ^The memory high-water mark is reset to the current value of
  2317. ** [sqlite3_memory_used()] if and only if the parameter to
  2318. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2319. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2320. ** prior to the reset.
  2321. */
  2322. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2323. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2324. /*
  2325. ** CAPI3REF: Pseudo-Random Number Generator
  2326. **
  2327. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2328. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2329. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2330. ** the build-in random() and randomblob() SQL functions. This interface allows
  2331. ** applications to access the same PRNG for other purposes.
  2332. **
  2333. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2334. **
  2335. ** ^The first time this routine is invoked (either internally or by
  2336. ** the application) the PRNG is seeded using randomness obtained
  2337. ** from the xRandomness method of the default [sqlite3_vfs] object.
  2338. ** ^On all subsequent invocations, the pseudo-randomness is generated
  2339. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2340. ** method.
  2341. */
  2342. SQLITE_API void sqlite3_randomness(int N, void *P);
  2343. /*
  2344. ** CAPI3REF: Compile-Time Authorization Callbacks
  2345. **
  2346. ** ^This routine registers an authorizer callback with a particular
  2347. ** [database connection], supplied in the first argument.
  2348. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2349. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2350. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2351. ** points during the compilation process, as logic is being created
  2352. ** to perform various actions, the authorizer callback is invoked to
  2353. ** see if those actions are allowed. ^The authorizer callback should
  2354. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2355. ** specific action but allow the SQL statement to continue to be
  2356. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2357. ** rejected with an error. ^If the authorizer callback returns
  2358. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2359. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2360. ** the authorizer will fail with an error message.
  2361. **
  2362. ** When the callback returns [SQLITE_OK], that means the operation
  2363. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2364. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2365. ** authorizer will fail with an error message explaining that
  2366. ** access is denied.
  2367. **
  2368. ** ^The first parameter to the authorizer callback is a copy of the third
  2369. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2370. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2371. ** the particular action to be authorized. ^The third through sixth parameters
  2372. ** to the callback are zero-terminated strings that contain additional
  2373. ** details about the action to be authorized.
  2374. **
  2375. ** ^If the action code is [SQLITE_READ]
  2376. ** and the callback returns [SQLITE_IGNORE] then the
  2377. ** [prepared statement] statement is constructed to substitute
  2378. ** a NULL value in place of the table column that would have
  2379. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2380. ** return can be used to deny an untrusted user access to individual
  2381. ** columns of a table.
  2382. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2383. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2384. ** [truncate optimization] is disabled and all rows are deleted individually.
  2385. **
  2386. ** An authorizer is used when [sqlite3_prepare | preparing]
  2387. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2388. ** do not try to access data they are not allowed to see, or that they do not
  2389. ** try to execute malicious statements that damage the database. For
  2390. ** example, an application may allow a user to enter arbitrary
  2391. ** SQL queries for evaluation by a database. But the application does
  2392. ** not want the user to be able to make arbitrary changes to the
  2393. ** database. An authorizer could then be put in place while the
  2394. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2395. ** disallows everything except [SELECT] statements.
  2396. **
  2397. ** Applications that need to process SQL from untrusted sources
  2398. ** might also consider lowering resource limits using [sqlite3_limit()]
  2399. ** and limiting database size using the [max_page_count] [PRAGMA]
  2400. ** in addition to using an authorizer.
  2401. **
  2402. ** ^(Only a single authorizer can be in place on a database connection
  2403. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2404. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2405. ** The authorizer is disabled by default.
  2406. **
  2407. ** The authorizer callback must not do anything that will modify
  2408. ** the database connection that invoked the authorizer callback.
  2409. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2410. ** database connections for the meaning of "modify" in this paragraph.
  2411. **
  2412. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2413. ** statement might be re-prepared during [sqlite3_step()] due to a
  2414. ** schema change. Hence, the application should ensure that the
  2415. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2416. **
  2417. ** ^Note that the authorizer callback is invoked only during
  2418. ** [sqlite3_prepare()] or its variants. Authorization is not
  2419. ** performed during statement evaluation in [sqlite3_step()], unless
  2420. ** as stated in the previous paragraph, sqlite3_step() invokes
  2421. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2422. */
  2423. SQLITE_API int sqlite3_set_authorizer(
  2424. sqlite3*,
  2425. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2426. void *pUserData
  2427. );
  2428. /*
  2429. ** CAPI3REF: Authorizer Return Codes
  2430. **
  2431. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2432. ** return either [SQLITE_OK] or one of these two constants in order
  2433. ** to signal SQLite whether or not the action is permitted. See the
  2434. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2435. ** information.
  2436. **
  2437. ** Note that SQLITE_IGNORE is also used as a [SQLITE_ROLLBACK | return code]
  2438. ** from the [sqlite3_vtab_on_conflict()] interface.
  2439. */
  2440. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2441. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2442. /*
  2443. ** CAPI3REF: Authorizer Action Codes
  2444. **
  2445. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2446. ** that is invoked to authorize certain SQL statement actions. The
  2447. ** second parameter to the callback is an integer code that specifies
  2448. ** what action is being authorized. These are the integer action codes that
  2449. ** the authorizer callback may be passed.
  2450. **
  2451. ** These action code values signify what kind of operation is to be
  2452. ** authorized. The 3rd and 4th parameters to the authorization
  2453. ** callback function will be parameters or NULL depending on which of these
  2454. ** codes is used as the second parameter. ^(The 5th parameter to the
  2455. ** authorizer callback is the name of the database ("main", "temp",
  2456. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2457. ** is the name of the inner-most trigger or view that is responsible for
  2458. ** the access attempt or NULL if this access attempt is directly from
  2459. ** top-level SQL code.
  2460. */
  2461. /******************************************* 3rd ************ 4th ***********/
  2462. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2463. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2464. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2465. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2466. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2467. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2468. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2469. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2470. #define SQLITE_DELETE 9 /* Table Name NULL */
  2471. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2472. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2473. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2474. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2475. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2476. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2477. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2478. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2479. #define SQLITE_INSERT 18 /* Table Name NULL */
  2480. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2481. #define SQLITE_READ 20 /* Table Name Column Name */
  2482. #define SQLITE_SELECT 21 /* NULL NULL */
  2483. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2484. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2485. #define SQLITE_ATTACH 24 /* Filename NULL */
  2486. #define SQLITE_DETACH 25 /* Database Name NULL */
  2487. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2488. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2489. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2490. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2491. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2492. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2493. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2494. #define SQLITE_COPY 0 /* No longer used */
  2495. /*
  2496. ** CAPI3REF: Tracing And Profiling Functions
  2497. **
  2498. ** These routines register callback functions that can be used for
  2499. ** tracing and profiling the execution of SQL statements.
  2500. **
  2501. ** ^The callback function registered by sqlite3_trace() is invoked at
  2502. ** various times when an SQL statement is being run by [sqlite3_step()].
  2503. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2504. ** SQL statement text as the statement first begins executing.
  2505. ** ^(Additional sqlite3_trace() callbacks might occur
  2506. ** as each triggered subprogram is entered. The callbacks for triggers
  2507. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2508. **
  2509. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2510. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2511. **
  2512. ** ^The callback function registered by sqlite3_profile() is invoked
  2513. ** as each SQL statement finishes. ^The profile callback contains
  2514. ** the original statement text and an estimate of wall-clock time
  2515. ** of how long that statement took to run. ^The profile callback
  2516. ** time is in units of nanoseconds, however the current implementation
  2517. ** is only capable of millisecond resolution so the six least significant
  2518. ** digits in the time are meaningless. Future versions of SQLite
  2519. ** might provide greater resolution on the profiler callback. The
  2520. ** sqlite3_profile() function is considered experimental and is
  2521. ** subject to change in future versions of SQLite.
  2522. */
  2523. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2524. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2525. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2526. /*
  2527. ** CAPI3REF: Query Progress Callbacks
  2528. **
  2529. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2530. ** function X to be invoked periodically during long running calls to
  2531. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2532. ** database connection D. An example use for this
  2533. ** interface is to keep a GUI updated during a large query.
  2534. **
  2535. ** ^The parameter P is passed through as the only parameter to the
  2536. ** callback function X. ^The parameter N is the approximate number of
  2537. ** [virtual machine instructions] that are evaluated between successive
  2538. ** invocations of the callback X. ^If N is less than one then the progress
  2539. ** handler is disabled.
  2540. **
  2541. ** ^Only a single progress handler may be defined at one time per
  2542. ** [database connection]; setting a new progress handler cancels the
  2543. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2544. ** ^The progress handler is also disabled by setting N to a value less
  2545. ** than 1.
  2546. **
  2547. ** ^If the progress callback returns non-zero, the operation is
  2548. ** interrupted. This feature can be used to implement a
  2549. ** "Cancel" button on a GUI progress dialog box.
  2550. **
  2551. ** The progress handler callback must not do anything that will modify
  2552. ** the database connection that invoked the progress handler.
  2553. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2554. ** database connections for the meaning of "modify" in this paragraph.
  2555. **
  2556. */
  2557. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2558. /*
  2559. ** CAPI3REF: Opening A New Database Connection
  2560. **
  2561. ** ^These routines open an SQLite database file as specified by the
  2562. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2563. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2564. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2565. ** returned in *ppDb, even if an error occurs. The only exception is that
  2566. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2567. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2568. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2569. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2570. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2571. ** an English language description of the error following a failure of any
  2572. ** of the sqlite3_open() routines.
  2573. **
  2574. ** ^The default encoding for the database will be UTF-8 if
  2575. ** sqlite3_open() or sqlite3_open_v2() is called and
  2576. ** UTF-16 in the native byte order if sqlite3_open16() is used.
  2577. **
  2578. ** Whether or not an error occurs when it is opened, resources
  2579. ** associated with the [database connection] handle should be released by
  2580. ** passing it to [sqlite3_close()] when it is no longer required.
  2581. **
  2582. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2583. ** except that it accepts two additional parameters for additional control
  2584. ** over the new database connection. ^(The flags parameter to
  2585. ** sqlite3_open_v2() can take one of
  2586. ** the following three values, optionally combined with the
  2587. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2588. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2589. **
  2590. ** <dl>
  2591. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2592. ** <dd>The database is opened in read-only mode. If the database does not
  2593. ** already exist, an error is returned.</dd>)^
  2594. **
  2595. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2596. ** <dd>The database is opened for reading and writing if possible, or reading
  2597. ** only if the file is write protected by the operating system. In either
  2598. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2599. **
  2600. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2601. ** <dd>The database is opened for reading and writing, and is created if
  2602. ** it does not already exist. This is the behavior that is always used for
  2603. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2604. ** </dl>
  2605. **
  2606. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2607. ** combinations shown above optionally combined with other
  2608. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2609. ** then the behavior is undefined.
  2610. **
  2611. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2612. ** opens in the multi-thread [threading mode] as long as the single-thread
  2613. ** mode has not been set at compile-time or start-time. ^If the
  2614. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2615. ** in the serialized [threading mode] unless single-thread was
  2616. ** previously selected at compile-time or start-time.
  2617. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2618. ** eligible to use [shared cache mode], regardless of whether or not shared
  2619. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2620. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2621. ** participate in [shared cache mode] even if it is enabled.
  2622. **
  2623. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2624. ** [sqlite3_vfs] object that defines the operating system interface that
  2625. ** the new database connection should use. ^If the fourth parameter is
  2626. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2627. **
  2628. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2629. ** is created for the connection. ^This in-memory database will vanish when
  2630. ** the database connection is closed. Future versions of SQLite might
  2631. ** make use of additional special filenames that begin with the ":" character.
  2632. ** It is recommended that when a database filename actually does begin with
  2633. ** a ":" character you should prefix the filename with a pathname such as
  2634. ** "./" to avoid ambiguity.
  2635. **
  2636. ** ^If the filename is an empty string, then a private, temporary
  2637. ** on-disk database will be created. ^This private database will be
  2638. ** automatically deleted as soon as the database connection is closed.
  2639. **
  2640. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2641. **
  2642. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2643. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2644. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2645. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2646. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2647. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2648. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2649. ** by default, but future releases of SQLite might enable URI filename
  2650. ** interpretation by default. See "[URI filenames]" for additional
  2651. ** information.
  2652. **
  2653. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2654. ** authority, then it must be either an empty string or the string
  2655. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2656. ** error is returned to the caller. ^The fragment component of a URI, if
  2657. ** present, is ignored.
  2658. **
  2659. ** ^SQLite uses the path component of the URI as the name of the disk file
  2660. ** which contains the database. ^If the path begins with a '/' character,
  2661. ** then it is interpreted as an absolute path. ^If the path does not begin
  2662. ** with a '/' (meaning that the authority section is omitted from the URI)
  2663. ** then the path is interpreted as a relative path.
  2664. ** ^On windows, the first component of an absolute path
  2665. ** is a drive specification (e.g. "C:").
  2666. **
  2667. ** [[core URI query parameters]]
  2668. ** The query component of a URI may contain parameters that are interpreted
  2669. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2670. ** SQLite interprets the following three query parameters:
  2671. **
  2672. ** <ul>
  2673. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2674. ** a VFS object that provides the operating system interface that should
  2675. ** be used to access the database file on disk. ^If this option is set to
  2676. ** an empty string the default VFS object is used. ^Specifying an unknown
  2677. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2678. ** present, then the VFS specified by the option takes precedence over
  2679. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2680. **
  2681. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2682. ** "rwc", or "memory". Attempting to set it to any other value is
  2683. ** an error)^.
  2684. ** ^If "ro" is specified, then the database is opened for read-only
  2685. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2686. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2687. ** "rw", then the database is opened for read-write (but not create)
  2688. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2689. ** been set. ^Value "rwc" is equivalent to setting both
  2690. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2691. ** set to "memory" then a pure [in-memory database] that never reads
  2692. ** or writes from disk is used. ^It is an error to specify a value for
  2693. ** the mode parameter that is less restrictive than that specified by
  2694. ** the flags passed in the third parameter to sqlite3_open_v2().
  2695. **
  2696. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2697. ** "private". ^Setting it to "shared" is equivalent to setting the
  2698. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2699. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2700. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2701. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2702. ** a URI filename, its value overrides any behavior requested by setting
  2703. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2704. ** </ul>
  2705. **
  2706. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2707. ** error. Future versions of SQLite might understand additional query
  2708. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2709. ** additional information.
  2710. **
  2711. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2712. **
  2713. ** <table border="1" align=center cellpadding=5>
  2714. ** <tr><th> URI filenames <th> Results
  2715. ** <tr><td> file:data.db <td>
  2716. ** Open the file "data.db" in the current directory.
  2717. ** <tr><td> file:/home/fred/data.db<br>
  2718. ** file:///home/fred/data.db <br>
  2719. ** file://localhost/home/fred/data.db <br> <td>
  2720. ** Open the database file "/home/fred/data.db".
  2721. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2722. ** An error. "darkstar" is not a recognized authority.
  2723. ** <tr><td style="white-space:nowrap">
  2724. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2725. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2726. ** C:. Note that the %20 escaping in this example is not strictly
  2727. ** necessary - space characters can be used literally
  2728. ** in URI filenames.
  2729. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2730. ** Open file "data.db" in the current directory for read-only access.
  2731. ** Regardless of whether or not shared-cache mode is enabled by
  2732. ** default, use a private cache.
  2733. ** <tr><td> file:/home/fred/data.db?vfs=unix-nolock <td>
  2734. ** Open file "/home/fred/data.db". Use the special VFS "unix-nolock".
  2735. ** <tr><td> file:data.db?mode=readonly <td>
  2736. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2737. ** </table>
  2738. **
  2739. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2740. ** query components of a URI. A hexadecimal escape sequence consists of a
  2741. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2742. ** specifying an octet value. ^Before the path or query components of a
  2743. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2744. ** hexadecimal escape sequences replaced by a single byte containing the
  2745. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2746. ** the results are undefined.
  2747. **
  2748. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2749. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2750. ** codepage is currently defined. Filenames containing international
  2751. ** characters must be converted to UTF-8 prior to passing them into
  2752. ** sqlite3_open() or sqlite3_open_v2().
  2753. **
  2754. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2755. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2756. ** features that require the use of temporary files may fail.
  2757. **
  2758. ** See also: [sqlite3_temp_directory]
  2759. */
  2760. SQLITE_API int sqlite3_open(
  2761. const char *filename, /* Database filename (UTF-8) */
  2762. sqlite3 **ppDb /* OUT: SQLite db handle */
  2763. );
  2764. SQLITE_API int sqlite3_open16(
  2765. const void *filename, /* Database filename (UTF-16) */
  2766. sqlite3 **ppDb /* OUT: SQLite db handle */
  2767. );
  2768. SQLITE_API int sqlite3_open_v2(
  2769. const char *filename, /* Database filename (UTF-8) */
  2770. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2771. int flags, /* Flags */
  2772. const char *zVfs /* Name of VFS module to use */
  2773. );
  2774. /*
  2775. ** CAPI3REF: Obtain Values For URI Parameters
  2776. **
  2777. ** These are utility routines, useful to VFS implementations, that check
  2778. ** to see if a database file was a URI that contained a specific query
  2779. ** parameter, and if so obtains the value of that query parameter.
  2780. **
  2781. ** If F is the database filename pointer passed into the xOpen() method of
  2782. ** a VFS implementation when the flags parameter to xOpen() has one or
  2783. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2784. ** P is the name of the query parameter, then
  2785. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2786. ** parameter if it exists or a NULL pointer if P does not appear as a
  2787. ** query parameter on F. If P is a query parameter of F
  2788. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2789. ** a pointer to an empty string.
  2790. **
  2791. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2792. ** parameter and returns true (1) or false (0) according to the value
  2793. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2794. ** value of query parameter P is one of "yes", "true", or "on" in any
  2795. ** case or if the value begins with a non-zero number. The
  2796. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2797. ** query parameter P is one of "no", "false", or "off" in any case or
  2798. ** if the value begins with a numeric zero. If P is not a query
  2799. ** parameter on F or if the value of P is does not match any of the
  2800. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2801. **
  2802. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2803. ** 64-bit signed integer and returns that integer, or D if P does not
  2804. ** exist. If the value of P is something other than an integer, then
  2805. ** zero is returned.
  2806. **
  2807. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2808. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2809. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2810. ** VFS method, then the behavior of this routine is undefined and probably
  2811. ** undesirable.
  2812. */
  2813. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2814. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  2815. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2816. /*
  2817. ** CAPI3REF: Error Codes And Messages
  2818. **
  2819. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  2820. ** [extended result code] for the most recent failed sqlite3_* API call
  2821. ** associated with a [database connection]. If a prior API call failed
  2822. ** but the most recent API call succeeded, the return value from
  2823. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  2824. ** interface is the same except that it always returns the
  2825. ** [extended result code] even when extended result codes are
  2826. ** disabled.
  2827. **
  2828. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  2829. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  2830. ** ^(Memory to hold the error message string is managed internally.
  2831. ** The application does not need to worry about freeing the result.
  2832. ** However, the error string might be overwritten or deallocated by
  2833. ** subsequent calls to other SQLite interface functions.)^
  2834. **
  2835. ** ^The sqlite3_errstr() interface returns the English-language text
  2836. ** that describes the [result code], as UTF-8.
  2837. ** ^(Memory to hold the error message string is managed internally
  2838. ** and must not be freed by the application)^.
  2839. **
  2840. ** When the serialized [threading mode] is in use, it might be the
  2841. ** case that a second error occurs on a separate thread in between
  2842. ** the time of the first error and the call to these interfaces.
  2843. ** When that happens, the second error will be reported since these
  2844. ** interfaces always report the most recent result. To avoid
  2845. ** this, each thread can obtain exclusive use of the [database connection] D
  2846. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  2847. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  2848. ** all calls to the interfaces listed here are completed.
  2849. **
  2850. ** If an interface fails with SQLITE_MISUSE, that means the interface
  2851. ** was invoked incorrectly by the application. In that case, the
  2852. ** error code and message may or may not be set.
  2853. */
  2854. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  2855. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  2856. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  2857. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  2858. SQLITE_API const char *sqlite3_errstr(int);
  2859. /*
  2860. ** CAPI3REF: SQL Statement Object
  2861. ** KEYWORDS: {prepared statement} {prepared statements}
  2862. **
  2863. ** An instance of this object represents a single SQL statement.
  2864. ** This object is variously known as a "prepared statement" or a
  2865. ** "compiled SQL statement" or simply as a "statement".
  2866. **
  2867. ** The life of a statement object goes something like this:
  2868. **
  2869. ** <ol>
  2870. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  2871. ** function.
  2872. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  2873. ** interfaces.
  2874. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  2875. ** <li> Reset the statement using [sqlite3_reset()] then go back
  2876. ** to step 2. Do this zero or more times.
  2877. ** <li> Destroy the object using [sqlite3_finalize()].
  2878. ** </ol>
  2879. **
  2880. ** Refer to documentation on individual methods above for additional
  2881. ** information.
  2882. */
  2883. typedef struct sqlite3_stmt sqlite3_stmt;
  2884. /*
  2885. ** CAPI3REF: Run-time Limits
  2886. **
  2887. ** ^(This interface allows the size of various constructs to be limited
  2888. ** on a connection by connection basis. The first parameter is the
  2889. ** [database connection] whose limit is to be set or queried. The
  2890. ** second parameter is one of the [limit categories] that define a
  2891. ** class of constructs to be size limited. The third parameter is the
  2892. ** new limit for that construct.)^
  2893. **
  2894. ** ^If the new limit is a negative number, the limit is unchanged.
  2895. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  2896. ** [limits | hard upper bound]
  2897. ** set at compile-time by a C preprocessor macro called
  2898. ** [limits | SQLITE_MAX_<i>NAME</i>].
  2899. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  2900. ** ^Attempts to increase a limit above its hard upper bound are
  2901. ** silently truncated to the hard upper bound.
  2902. **
  2903. ** ^Regardless of whether or not the limit was changed, the
  2904. ** [sqlite3_limit()] interface returns the prior value of the limit.
  2905. ** ^Hence, to find the current value of a limit without changing it,
  2906. ** simply invoke this interface with the third parameter set to -1.
  2907. **
  2908. ** Run-time limits are intended for use in applications that manage
  2909. ** both their own internal database and also databases that are controlled
  2910. ** by untrusted external sources. An example application might be a
  2911. ** web browser that has its own databases for storing history and
  2912. ** separate databases controlled by JavaScript applications downloaded
  2913. ** off the Internet. The internal databases can be given the
  2914. ** large, default limits. Databases managed by external sources can
  2915. ** be given much smaller limits designed to prevent a denial of service
  2916. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  2917. ** interface to further control untrusted SQL. The size of the database
  2918. ** created by an untrusted script can be contained using the
  2919. ** [max_page_count] [PRAGMA].
  2920. **
  2921. ** New run-time limit categories may be added in future releases.
  2922. */
  2923. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  2924. /*
  2925. ** CAPI3REF: Run-Time Limit Categories
  2926. ** KEYWORDS: {limit category} {*limit categories}
  2927. **
  2928. ** These constants define various performance limits
  2929. ** that can be lowered at run-time using [sqlite3_limit()].
  2930. ** The synopsis of the meanings of the various limits is shown below.
  2931. ** Additional information is available at [limits | Limits in SQLite].
  2932. **
  2933. ** <dl>
  2934. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  2935. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  2936. **
  2937. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  2938. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  2939. **
  2940. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  2941. ** <dd>The maximum number of columns in a table definition or in the
  2942. ** result set of a [SELECT] or the maximum number of columns in an index
  2943. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  2944. **
  2945. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  2946. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  2947. **
  2948. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  2949. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  2950. **
  2951. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  2952. ** <dd>The maximum number of instructions in a virtual machine program
  2953. ** used to implement an SQL statement. This limit is not currently
  2954. ** enforced, though that might be added in some future release of
  2955. ** SQLite.</dd>)^
  2956. **
  2957. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  2958. ** <dd>The maximum number of arguments on a function.</dd>)^
  2959. **
  2960. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  2961. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  2962. **
  2963. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  2964. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  2965. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  2966. ** [GLOB] operators.</dd>)^
  2967. **
  2968. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  2969. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  2970. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  2971. **
  2972. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  2973. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  2974. ** </dl>
  2975. */
  2976. #define SQLITE_LIMIT_LENGTH 0
  2977. #define SQLITE_LIMIT_SQL_LENGTH 1
  2978. #define SQLITE_LIMIT_COLUMN 2
  2979. #define SQLITE_LIMIT_EXPR_DEPTH 3
  2980. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  2981. #define SQLITE_LIMIT_VDBE_OP 5
  2982. #define SQLITE_LIMIT_FUNCTION_ARG 6
  2983. #define SQLITE_LIMIT_ATTACHED 7
  2984. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  2985. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  2986. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  2987. /*
  2988. ** CAPI3REF: Compiling An SQL Statement
  2989. ** KEYWORDS: {SQL statement compiler}
  2990. **
  2991. ** To execute an SQL query, it must first be compiled into a byte-code
  2992. ** program using one of these routines.
  2993. **
  2994. ** The first argument, "db", is a [database connection] obtained from a
  2995. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  2996. ** [sqlite3_open16()]. The database connection must not have been closed.
  2997. **
  2998. ** The second argument, "zSql", is the statement to be compiled, encoded
  2999. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3000. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3001. ** use UTF-16.
  3002. **
  3003. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3004. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3005. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3006. ** zSql string ends at either the first '\000' or '\u0000' character or
  3007. ** the nByte-th byte, whichever comes first. If the caller knows
  3008. ** that the supplied string is nul-terminated, then there is a small
  3009. ** performance advantage to be gained by passing an nByte parameter that
  3010. ** is equal to the number of bytes in the input string <i>including</i>
  3011. ** the nul-terminator bytes as this saves SQLite from having to
  3012. ** make a copy of the input string.
  3013. **
  3014. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3015. ** past the end of the first SQL statement in zSql. These routines only
  3016. ** compile the first statement in zSql, so *pzTail is left pointing to
  3017. ** what remains uncompiled.
  3018. **
  3019. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3020. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3021. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3022. ** string or a comment) then *ppStmt is set to NULL.
  3023. ** The calling procedure is responsible for deleting the compiled
  3024. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3025. ** ppStmt may not be NULL.
  3026. **
  3027. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3028. ** otherwise an [error code] is returned.
  3029. **
  3030. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3031. ** recommended for all new programs. The two older interfaces are retained
  3032. ** for backwards compatibility, but their use is discouraged.
  3033. ** ^In the "v2" interfaces, the prepared statement
  3034. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3035. ** original SQL text. This causes the [sqlite3_step()] interface to
  3036. ** behave differently in three ways:
  3037. **
  3038. ** <ol>
  3039. ** <li>
  3040. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3041. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3042. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3043. ** retries will occur before sqlite3_step() gives up and returns an error.
  3044. ** </li>
  3045. **
  3046. ** <li>
  3047. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3048. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3049. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3050. ** and the application would have to make a second call to [sqlite3_reset()]
  3051. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3052. ** interfaces, the underlying reason for the error is returned immediately.
  3053. ** </li>
  3054. **
  3055. ** <li>
  3056. ** ^If the specific value bound to [parameter | host parameter] in the
  3057. ** WHERE clause might influence the choice of query plan for a statement,
  3058. ** then the statement will be automatically recompiled, as if there had been
  3059. ** a schema change, on the first [sqlite3_step()] call following any change
  3060. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3061. ** ^The specific value of WHERE-clause [parameter] might influence the
  3062. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3063. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3064. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3065. ** the
  3066. ** </li>
  3067. ** </ol>
  3068. */
  3069. SQLITE_API int sqlite3_prepare(
  3070. sqlite3 *db, /* Database handle */
  3071. const char *zSql, /* SQL statement, UTF-8 encoded */
  3072. int nByte, /* Maximum length of zSql in bytes. */
  3073. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3074. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3075. );
  3076. SQLITE_API int sqlite3_prepare_v2(
  3077. sqlite3 *db, /* Database handle */
  3078. const char *zSql, /* SQL statement, UTF-8 encoded */
  3079. int nByte, /* Maximum length of zSql in bytes. */
  3080. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3081. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3082. );
  3083. SQLITE_API int sqlite3_prepare16(
  3084. sqlite3 *db, /* Database handle */
  3085. const void *zSql, /* SQL statement, UTF-16 encoded */
  3086. int nByte, /* Maximum length of zSql in bytes. */
  3087. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3088. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3089. );
  3090. SQLITE_API int sqlite3_prepare16_v2(
  3091. sqlite3 *db, /* Database handle */
  3092. const void *zSql, /* SQL statement, UTF-16 encoded */
  3093. int nByte, /* Maximum length of zSql in bytes. */
  3094. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3095. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3096. );
  3097. /*
  3098. ** CAPI3REF: Retrieving Statement SQL
  3099. **
  3100. ** ^This interface can be used to retrieve a saved copy of the original
  3101. ** SQL text used to create a [prepared statement] if that statement was
  3102. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3103. */
  3104. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3105. /*
  3106. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3107. **
  3108. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3109. ** and only if the [prepared statement] X makes no direct changes to
  3110. ** the content of the database file.
  3111. **
  3112. ** Note that [application-defined SQL functions] or
  3113. ** [virtual tables] might change the database indirectly as a side effect.
  3114. ** ^(For example, if an application defines a function "eval()" that
  3115. ** calls [sqlite3_exec()], then the following SQL statement would
  3116. ** change the database file through side-effects:
  3117. **
  3118. ** <blockquote><pre>
  3119. ** SELECT eval('DELETE FROM t1') FROM t2;
  3120. ** </pre></blockquote>
  3121. **
  3122. ** But because the [SELECT] statement does not change the database file
  3123. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3124. **
  3125. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3126. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3127. ** since the statements themselves do not actually modify the database but
  3128. ** rather they control the timing of when other statements modify the
  3129. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3130. ** sqlite3_stmt_readonly() to return true since, while those statements
  3131. ** change the configuration of a database connection, they do not make
  3132. ** changes to the content of the database files on disk.
  3133. */
  3134. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3135. /*
  3136. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3137. **
  3138. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3139. ** [prepared statement] S has been stepped at least once using
  3140. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3141. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3142. ** interface returns false if S is a NULL pointer. If S is not a
  3143. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3144. ** object, then the behavior is undefined and probably undesirable.
  3145. **
  3146. ** This interface can be used in combination [sqlite3_next_stmt()]
  3147. ** to locate all prepared statements associated with a database
  3148. ** connection that are in need of being reset. This can be used,
  3149. ** for example, in diagnostic routines to search for prepared
  3150. ** statements that are holding a transaction open.
  3151. */
  3152. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3153. /*
  3154. ** CAPI3REF: Dynamically Typed Value Object
  3155. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3156. **
  3157. ** SQLite uses the sqlite3_value object to represent all values
  3158. ** that can be stored in a database table. SQLite uses dynamic typing
  3159. ** for the values it stores. ^Values stored in sqlite3_value objects
  3160. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3161. **
  3162. ** An sqlite3_value object may be either "protected" or "unprotected".
  3163. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3164. ** will accept either a protected or an unprotected sqlite3_value.
  3165. ** Every interface that accepts sqlite3_value arguments specifies
  3166. ** whether or not it requires a protected sqlite3_value.
  3167. **
  3168. ** The terms "protected" and "unprotected" refer to whether or not
  3169. ** a mutex is held. An internal mutex is held for a protected
  3170. ** sqlite3_value object but no mutex is held for an unprotected
  3171. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3172. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3173. ** or if SQLite is run in one of reduced mutex modes
  3174. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3175. ** then there is no distinction between protected and unprotected
  3176. ** sqlite3_value objects and they can be used interchangeably. However,
  3177. ** for maximum code portability it is recommended that applications
  3178. ** still make the distinction between protected and unprotected
  3179. ** sqlite3_value objects even when not strictly required.
  3180. **
  3181. ** ^The sqlite3_value objects that are passed as parameters into the
  3182. ** implementation of [application-defined SQL functions] are protected.
  3183. ** ^The sqlite3_value object returned by
  3184. ** [sqlite3_column_value()] is unprotected.
  3185. ** Unprotected sqlite3_value objects may only be used with
  3186. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3187. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3188. ** interfaces require protected sqlite3_value objects.
  3189. */
  3190. typedef struct Mem sqlite3_value;
  3191. /*
  3192. ** CAPI3REF: SQL Function Context Object
  3193. **
  3194. ** The context in which an SQL function executes is stored in an
  3195. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3196. ** is always first parameter to [application-defined SQL functions].
  3197. ** The application-defined SQL function implementation will pass this
  3198. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3199. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3200. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3201. ** and/or [sqlite3_set_auxdata()].
  3202. */
  3203. typedef struct sqlite3_context sqlite3_context;
  3204. /*
  3205. ** CAPI3REF: Binding Values To Prepared Statements
  3206. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3207. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3208. **
  3209. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3210. ** literals may be replaced by a [parameter] that matches one of following
  3211. ** templates:
  3212. **
  3213. ** <ul>
  3214. ** <li> ?
  3215. ** <li> ?NNN
  3216. ** <li> :VVV
  3217. ** <li> @VVV
  3218. ** <li> $VVV
  3219. ** </ul>
  3220. **
  3221. ** In the templates above, NNN represents an integer literal,
  3222. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3223. ** parameters (also called "host parameter names" or "SQL parameters")
  3224. ** can be set using the sqlite3_bind_*() routines defined here.
  3225. **
  3226. ** ^The first argument to the sqlite3_bind_*() routines is always
  3227. ** a pointer to the [sqlite3_stmt] object returned from
  3228. ** [sqlite3_prepare_v2()] or its variants.
  3229. **
  3230. ** ^The second argument is the index of the SQL parameter to be set.
  3231. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3232. ** SQL parameter is used more than once, second and subsequent
  3233. ** occurrences have the same index as the first occurrence.
  3234. ** ^The index for named parameters can be looked up using the
  3235. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3236. ** for "?NNN" parameters is the value of NNN.
  3237. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3238. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3239. **
  3240. ** ^The third argument is the value to bind to the parameter.
  3241. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3242. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3243. ** is ignored and the end result is the same as sqlite3_bind_null().
  3244. **
  3245. ** ^(In those routines that have a fourth argument, its value is the
  3246. ** number of bytes in the parameter. To be clear: the value is the
  3247. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3248. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3249. ** is negative, then the length of the string is
  3250. ** the number of bytes up to the first zero terminator.
  3251. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3252. ** the behavior is undefined.
  3253. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3254. ** or sqlite3_bind_text16() then that parameter must be the byte offset
  3255. ** where the NUL terminator would occur assuming the string were NUL
  3256. ** terminated. If any NUL characters occur at byte offsets less than
  3257. ** the value of the fourth parameter then the resulting string value will
  3258. ** contain embedded NULs. The result of expressions involving strings
  3259. ** with embedded NULs is undefined.
  3260. **
  3261. ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
  3262. ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
  3263. ** string after SQLite has finished with it. ^The destructor is called
  3264. ** to dispose of the BLOB or string even if the call to sqlite3_bind_blob(),
  3265. ** sqlite3_bind_text(), or sqlite3_bind_text16() fails.
  3266. ** ^If the fifth argument is
  3267. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3268. ** information is in static, unmanaged space and does not need to be freed.
  3269. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3270. ** SQLite makes its own private copy of the data immediately, before
  3271. ** the sqlite3_bind_*() routine returns.
  3272. **
  3273. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3274. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3275. ** (just an integer to hold its size) while it is being processed.
  3276. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3277. ** content is later written using
  3278. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3279. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3280. **
  3281. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3282. ** for the [prepared statement] or with a prepared statement for which
  3283. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3284. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3285. ** routine is passed a [prepared statement] that has been finalized, the
  3286. ** result is undefined and probably harmful.
  3287. **
  3288. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3289. ** ^Unbound parameters are interpreted as NULL.
  3290. **
  3291. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3292. ** [error code] if anything goes wrong.
  3293. ** ^[SQLITE_RANGE] is returned if the parameter
  3294. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3295. **
  3296. ** See also: [sqlite3_bind_parameter_count()],
  3297. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3298. */
  3299. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3300. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3301. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3302. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3303. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3304. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
  3305. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3306. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3307. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3308. /*
  3309. ** CAPI3REF: Number Of SQL Parameters
  3310. **
  3311. ** ^This routine can be used to find the number of [SQL parameters]
  3312. ** in a [prepared statement]. SQL parameters are tokens of the
  3313. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3314. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3315. ** to the parameters at a later time.
  3316. **
  3317. ** ^(This routine actually returns the index of the largest (rightmost)
  3318. ** parameter. For all forms except ?NNN, this will correspond to the
  3319. ** number of unique parameters. If parameters of the ?NNN form are used,
  3320. ** there may be gaps in the list.)^
  3321. **
  3322. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3323. ** [sqlite3_bind_parameter_name()], and
  3324. ** [sqlite3_bind_parameter_index()].
  3325. */
  3326. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3327. /*
  3328. ** CAPI3REF: Name Of A Host Parameter
  3329. **
  3330. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3331. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3332. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3333. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3334. ** respectively.
  3335. ** In other words, the initial ":" or "$" or "@" or "?"
  3336. ** is included as part of the name.)^
  3337. ** ^Parameters of the form "?" without a following integer have no name
  3338. ** and are referred to as "nameless" or "anonymous parameters".
  3339. **
  3340. ** ^The first host parameter has an index of 1, not 0.
  3341. **
  3342. ** ^If the value N is out of range or if the N-th parameter is
  3343. ** nameless, then NULL is returned. ^The returned string is
  3344. ** always in UTF-8 encoding even if the named parameter was
  3345. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3346. ** [sqlite3_prepare16_v2()].
  3347. **
  3348. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3349. ** [sqlite3_bind_parameter_count()], and
  3350. ** [sqlite3_bind_parameter_index()].
  3351. */
  3352. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3353. /*
  3354. ** CAPI3REF: Index Of A Parameter With A Given Name
  3355. **
  3356. ** ^Return the index of an SQL parameter given its name. ^The
  3357. ** index value returned is suitable for use as the second
  3358. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3359. ** is returned if no matching parameter is found. ^The parameter
  3360. ** name must be given in UTF-8 even if the original statement
  3361. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3362. **
  3363. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3364. ** [sqlite3_bind_parameter_count()], and
  3365. ** [sqlite3_bind_parameter_index()].
  3366. */
  3367. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3368. /*
  3369. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3370. **
  3371. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3372. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3373. ** ^Use this routine to reset all host parameters to NULL.
  3374. */
  3375. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3376. /*
  3377. ** CAPI3REF: Number Of Columns In A Result Set
  3378. **
  3379. ** ^Return the number of columns in the result set returned by the
  3380. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3381. ** statement that does not return data (for example an [UPDATE]).
  3382. **
  3383. ** See also: [sqlite3_data_count()]
  3384. */
  3385. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3386. /*
  3387. ** CAPI3REF: Column Names In A Result Set
  3388. **
  3389. ** ^These routines return the name assigned to a particular column
  3390. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3391. ** interface returns a pointer to a zero-terminated UTF-8 string
  3392. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3393. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3394. ** that implements the [SELECT] statement. ^The second parameter is the
  3395. ** column number. ^The leftmost column is number 0.
  3396. **
  3397. ** ^The returned string pointer is valid until either the [prepared statement]
  3398. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3399. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3400. ** or until the next call to
  3401. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3402. **
  3403. ** ^If sqlite3_malloc() fails during the processing of either routine
  3404. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3405. ** NULL pointer is returned.
  3406. **
  3407. ** ^The name of a result column is the value of the "AS" clause for
  3408. ** that column, if there is an AS clause. If there is no AS clause
  3409. ** then the name of the column is unspecified and may change from
  3410. ** one release of SQLite to the next.
  3411. */
  3412. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3413. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3414. /*
  3415. ** CAPI3REF: Source Of Data In A Query Result
  3416. **
  3417. ** ^These routines provide a means to determine the database, table, and
  3418. ** table column that is the origin of a particular result column in
  3419. ** [SELECT] statement.
  3420. ** ^The name of the database or table or column can be returned as
  3421. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3422. ** the database name, the _table_ routines return the table name, and
  3423. ** the origin_ routines return the column name.
  3424. ** ^The returned string is valid until the [prepared statement] is destroyed
  3425. ** using [sqlite3_finalize()] or until the statement is automatically
  3426. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3427. ** or until the same information is requested
  3428. ** again in a different encoding.
  3429. **
  3430. ** ^The names returned are the original un-aliased names of the
  3431. ** database, table, and column.
  3432. **
  3433. ** ^The first argument to these interfaces is a [prepared statement].
  3434. ** ^These functions return information about the Nth result column returned by
  3435. ** the statement, where N is the second function argument.
  3436. ** ^The left-most column is column 0 for these routines.
  3437. **
  3438. ** ^If the Nth column returned by the statement is an expression or
  3439. ** subquery and is not a column value, then all of these functions return
  3440. ** NULL. ^These routine might also return NULL if a memory allocation error
  3441. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3442. ** or column that query result column was extracted from.
  3443. **
  3444. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3445. ** UTF-16 encoded strings and the other functions return UTF-8.
  3446. **
  3447. ** ^These APIs are only available if the library was compiled with the
  3448. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3449. **
  3450. ** If two or more threads call one or more of these routines against the same
  3451. ** prepared statement and column at the same time then the results are
  3452. ** undefined.
  3453. **
  3454. ** If two or more threads call one or more
  3455. ** [sqlite3_column_database_name | column metadata interfaces]
  3456. ** for the same [prepared statement] and result column
  3457. ** at the same time then the results are undefined.
  3458. */
  3459. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3460. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3461. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3462. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3463. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3464. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3465. /*
  3466. ** CAPI3REF: Declared Datatype Of A Query Result
  3467. **
  3468. ** ^(The first parameter is a [prepared statement].
  3469. ** If this statement is a [SELECT] statement and the Nth column of the
  3470. ** returned result set of that [SELECT] is a table column (not an
  3471. ** expression or subquery) then the declared type of the table
  3472. ** column is returned.)^ ^If the Nth column of the result set is an
  3473. ** expression or subquery, then a NULL pointer is returned.
  3474. ** ^The returned string is always UTF-8 encoded.
  3475. **
  3476. ** ^(For example, given the database schema:
  3477. **
  3478. ** CREATE TABLE t1(c1 VARIANT);
  3479. **
  3480. ** and the following statement to be compiled:
  3481. **
  3482. ** SELECT c1 + 1, c1 FROM t1;
  3483. **
  3484. ** this routine would return the string "VARIANT" for the second result
  3485. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3486. **
  3487. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3488. ** is declared to contain a particular type does not mean that the
  3489. ** data stored in that column is of the declared type. SQLite is
  3490. ** strongly typed, but the typing is dynamic not static. ^Type
  3491. ** is associated with individual values, not with the containers
  3492. ** used to hold those values.
  3493. */
  3494. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3495. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3496. /*
  3497. ** CAPI3REF: Evaluate An SQL Statement
  3498. **
  3499. ** After a [prepared statement] has been prepared using either
  3500. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3501. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3502. ** must be called one or more times to evaluate the statement.
  3503. **
  3504. ** The details of the behavior of the sqlite3_step() interface depend
  3505. ** on whether the statement was prepared using the newer "v2" interface
  3506. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3507. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3508. ** new "v2" interface is recommended for new applications but the legacy
  3509. ** interface will continue to be supported.
  3510. **
  3511. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3512. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3513. ** ^With the "v2" interface, any of the other [result codes] or
  3514. ** [extended result codes] might be returned as well.
  3515. **
  3516. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3517. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3518. ** or occurs outside of an explicit transaction, then you can retry the
  3519. ** statement. If the statement is not a [COMMIT] and occurs within an
  3520. ** explicit transaction then you should rollback the transaction before
  3521. ** continuing.
  3522. **
  3523. ** ^[SQLITE_DONE] means that the statement has finished executing
  3524. ** successfully. sqlite3_step() should not be called again on this virtual
  3525. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3526. ** machine back to its initial state.
  3527. **
  3528. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3529. ** is returned each time a new row of data is ready for processing by the
  3530. ** caller. The values may be accessed using the [column access functions].
  3531. ** sqlite3_step() is called again to retrieve the next row of data.
  3532. **
  3533. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3534. ** violation) has occurred. sqlite3_step() should not be called again on
  3535. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3536. ** ^With the legacy interface, a more specific error code (for example,
  3537. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3538. ** can be obtained by calling [sqlite3_reset()] on the
  3539. ** [prepared statement]. ^In the "v2" interface,
  3540. ** the more specific error code is returned directly by sqlite3_step().
  3541. **
  3542. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3543. ** Perhaps it was called on a [prepared statement] that has
  3544. ** already been [sqlite3_finalize | finalized] or on one that had
  3545. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3546. ** be the case that the same database connection is being used by two or
  3547. ** more threads at the same moment in time.
  3548. **
  3549. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3550. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3551. ** other than [SQLITE_ROW] before any subsequent invocation of
  3552. ** sqlite3_step(). Failure to reset the prepared statement using
  3553. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3554. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3555. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3556. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3557. ** break because any application that ever receives an SQLITE_MISUSE error
  3558. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3559. ** can be used to restore the legacy behavior.
  3560. **
  3561. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3562. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3563. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3564. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3565. ** specific [error codes] that better describes the error.
  3566. ** We admit that this is a goofy design. The problem has been fixed
  3567. ** with the "v2" interface. If you prepare all of your SQL statements
  3568. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3569. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3570. ** then the more specific [error codes] are returned directly
  3571. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3572. */
  3573. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3574. /*
  3575. ** CAPI3REF: Number of columns in a result set
  3576. **
  3577. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3578. ** current row of the result set of [prepared statement] P.
  3579. ** ^If prepared statement P does not have results ready to return
  3580. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3581. ** interfaces) then sqlite3_data_count(P) returns 0.
  3582. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3583. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3584. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3585. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3586. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3587. ** where it always returns zero since each step of that multi-step
  3588. ** pragma returns 0 columns of data.
  3589. **
  3590. ** See also: [sqlite3_column_count()]
  3591. */
  3592. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3593. /*
  3594. ** CAPI3REF: Fundamental Datatypes
  3595. ** KEYWORDS: SQLITE_TEXT
  3596. **
  3597. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3598. **
  3599. ** <ul>
  3600. ** <li> 64-bit signed integer
  3601. ** <li> 64-bit IEEE floating point number
  3602. ** <li> string
  3603. ** <li> BLOB
  3604. ** <li> NULL
  3605. ** </ul>)^
  3606. **
  3607. ** These constants are codes for each of those types.
  3608. **
  3609. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3610. ** for a completely different meaning. Software that links against both
  3611. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3612. ** SQLITE_TEXT.
  3613. */
  3614. #define SQLITE_INTEGER 1
  3615. #define SQLITE_FLOAT 2
  3616. #define SQLITE_BLOB 4
  3617. #define SQLITE_NULL 5
  3618. #ifdef SQLITE_TEXT
  3619. # undef SQLITE_TEXT
  3620. #else
  3621. # define SQLITE_TEXT 3
  3622. #endif
  3623. #define SQLITE3_TEXT 3
  3624. /*
  3625. ** CAPI3REF: Result Values From A Query
  3626. ** KEYWORDS: {column access functions}
  3627. **
  3628. ** These routines form the "result set" interface.
  3629. **
  3630. ** ^These routines return information about a single column of the current
  3631. ** result row of a query. ^In every case the first argument is a pointer
  3632. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3633. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3634. ** and the second argument is the index of the column for which information
  3635. ** should be returned. ^The leftmost column of the result set has the index 0.
  3636. ** ^The number of columns in the result can be determined using
  3637. ** [sqlite3_column_count()].
  3638. **
  3639. ** If the SQL statement does not currently point to a valid row, or if the
  3640. ** column index is out of range, the result is undefined.
  3641. ** These routines may only be called when the most recent call to
  3642. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3643. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3644. ** If any of these routines are called after [sqlite3_reset()] or
  3645. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3646. ** something other than [SQLITE_ROW], the results are undefined.
  3647. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3648. ** are called from a different thread while any of these routines
  3649. ** are pending, then the results are undefined.
  3650. **
  3651. ** ^The sqlite3_column_type() routine returns the
  3652. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3653. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3654. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3655. ** returned by sqlite3_column_type() is only meaningful if no type
  3656. ** conversions have occurred as described below. After a type conversion,
  3657. ** the value returned by sqlite3_column_type() is undefined. Future
  3658. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3659. ** following a type conversion.
  3660. **
  3661. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3662. ** routine returns the number of bytes in that BLOB or string.
  3663. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3664. ** the string to UTF-8 and then returns the number of bytes.
  3665. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3666. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3667. ** the number of bytes in that string.
  3668. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3669. **
  3670. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3671. ** routine returns the number of bytes in that BLOB or string.
  3672. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3673. ** the string to UTF-16 and then returns the number of bytes.
  3674. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3675. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3676. ** the number of bytes in that string.
  3677. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3678. **
  3679. ** ^The values returned by [sqlite3_column_bytes()] and
  3680. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3681. ** of the string. ^For clarity: the values returned by
  3682. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3683. ** bytes in the string, not the number of characters.
  3684. **
  3685. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3686. ** even empty strings, are always zero-terminated. ^The return
  3687. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3688. **
  3689. ** ^The object returned by [sqlite3_column_value()] is an
  3690. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3691. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3692. ** If the [unprotected sqlite3_value] object returned by
  3693. ** [sqlite3_column_value()] is used in any other way, including calls
  3694. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3695. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3696. **
  3697. ** These routines attempt to convert the value where appropriate. ^For
  3698. ** example, if the internal representation is FLOAT and a text result
  3699. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3700. ** conversion automatically. ^(The following table details the conversions
  3701. ** that are applied:
  3702. **
  3703. ** <blockquote>
  3704. ** <table border="1">
  3705. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3706. **
  3707. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3708. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3709. ** <tr><td> NULL <td> TEXT <td> Result is NULL pointer
  3710. ** <tr><td> NULL <td> BLOB <td> Result is NULL pointer
  3711. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3712. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3713. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3714. ** <tr><td> FLOAT <td> INTEGER <td> Convert from float to integer
  3715. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3716. ** <tr><td> FLOAT <td> BLOB <td> Same as FLOAT->TEXT
  3717. ** <tr><td> TEXT <td> INTEGER <td> Use atoi()
  3718. ** <tr><td> TEXT <td> FLOAT <td> Use atof()
  3719. ** <tr><td> TEXT <td> BLOB <td> No change
  3720. ** <tr><td> BLOB <td> INTEGER <td> Convert to TEXT then use atoi()
  3721. ** <tr><td> BLOB <td> FLOAT <td> Convert to TEXT then use atof()
  3722. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3723. ** </table>
  3724. ** </blockquote>)^
  3725. **
  3726. ** The table above makes reference to standard C library functions atoi()
  3727. ** and atof(). SQLite does not really use these functions. It has its
  3728. ** own equivalent internal routines. The atoi() and atof() names are
  3729. ** used in the table for brevity and because they are familiar to most
  3730. ** C programmers.
  3731. **
  3732. ** Note that when type conversions occur, pointers returned by prior
  3733. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3734. ** sqlite3_column_text16() may be invalidated.
  3735. ** Type conversions and pointer invalidations might occur
  3736. ** in the following cases:
  3737. **
  3738. ** <ul>
  3739. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3740. ** sqlite3_column_text16() is called. A zero-terminator might
  3741. ** need to be added to the string.</li>
  3742. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3743. ** sqlite3_column_text16() is called. The content must be converted
  3744. ** to UTF-16.</li>
  3745. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3746. ** sqlite3_column_text() is called. The content must be converted
  3747. ** to UTF-8.</li>
  3748. ** </ul>
  3749. **
  3750. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3751. ** not invalidate a prior pointer, though of course the content of the buffer
  3752. ** that the prior pointer references will have been modified. Other kinds
  3753. ** of conversion are done in place when it is possible, but sometimes they
  3754. ** are not possible and in those cases prior pointers are invalidated.
  3755. **
  3756. ** The safest and easiest to remember policy is to invoke these routines
  3757. ** in one of the following ways:
  3758. **
  3759. ** <ul>
  3760. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3761. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3762. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3763. ** </ul>
  3764. **
  3765. ** In other words, you should call sqlite3_column_text(),
  3766. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3767. ** into the desired format, then invoke sqlite3_column_bytes() or
  3768. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3769. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3770. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3771. ** with calls to sqlite3_column_bytes().
  3772. **
  3773. ** ^The pointers returned are valid until a type conversion occurs as
  3774. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3775. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3776. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3777. ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3778. ** [sqlite3_free()].
  3779. **
  3780. ** ^(If a memory allocation error occurs during the evaluation of any
  3781. ** of these routines, a default value is returned. The default value
  3782. ** is either the integer 0, the floating point number 0.0, or a NULL
  3783. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3784. ** [SQLITE_NOMEM].)^
  3785. */
  3786. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3787. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3788. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3789. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3790. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3791. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3792. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3793. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3794. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3795. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3796. /*
  3797. ** CAPI3REF: Destroy A Prepared Statement Object
  3798. **
  3799. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  3800. ** ^If the most recent evaluation of the statement encountered no errors
  3801. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  3802. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  3803. ** sqlite3_finalize(S) returns the appropriate [error code] or
  3804. ** [extended error code].
  3805. **
  3806. ** ^The sqlite3_finalize(S) routine can be called at any point during
  3807. ** the life cycle of [prepared statement] S:
  3808. ** before statement S is ever evaluated, after
  3809. ** one or more calls to [sqlite3_reset()], or after any call
  3810. ** to [sqlite3_step()] regardless of whether or not the statement has
  3811. ** completed execution.
  3812. **
  3813. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  3814. **
  3815. ** The application must finalize every [prepared statement] in order to avoid
  3816. ** resource leaks. It is a grievous error for the application to try to use
  3817. ** a prepared statement after it has been finalized. Any use of a prepared
  3818. ** statement after it has been finalized can result in undefined and
  3819. ** undesirable behavior such as segfaults and heap corruption.
  3820. */
  3821. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  3822. /*
  3823. ** CAPI3REF: Reset A Prepared Statement Object
  3824. **
  3825. ** The sqlite3_reset() function is called to reset a [prepared statement]
  3826. ** object back to its initial state, ready to be re-executed.
  3827. ** ^Any SQL statement variables that had values bound to them using
  3828. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  3829. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  3830. **
  3831. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  3832. ** back to the beginning of its program.
  3833. **
  3834. ** ^If the most recent call to [sqlite3_step(S)] for the
  3835. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  3836. ** or if [sqlite3_step(S)] has never before been called on S,
  3837. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  3838. **
  3839. ** ^If the most recent call to [sqlite3_step(S)] for the
  3840. ** [prepared statement] S indicated an error, then
  3841. ** [sqlite3_reset(S)] returns an appropriate [error code].
  3842. **
  3843. ** ^The [sqlite3_reset(S)] interface does not change the values
  3844. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  3845. */
  3846. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  3847. /*
  3848. ** CAPI3REF: Create Or Redefine SQL Functions
  3849. ** KEYWORDS: {function creation routines}
  3850. ** KEYWORDS: {application-defined SQL function}
  3851. ** KEYWORDS: {application-defined SQL functions}
  3852. **
  3853. ** ^These functions (collectively known as "function creation routines")
  3854. ** are used to add SQL functions or aggregates or to redefine the behavior
  3855. ** of existing SQL functions or aggregates. The only differences between
  3856. ** these routines are the text encoding expected for
  3857. ** the second parameter (the name of the function being created)
  3858. ** and the presence or absence of a destructor callback for
  3859. ** the application data pointer.
  3860. **
  3861. ** ^The first parameter is the [database connection] to which the SQL
  3862. ** function is to be added. ^If an application uses more than one database
  3863. ** connection then application-defined SQL functions must be added
  3864. ** to each database connection separately.
  3865. **
  3866. ** ^The second parameter is the name of the SQL function to be created or
  3867. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  3868. ** representation, exclusive of the zero-terminator. ^Note that the name
  3869. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  3870. ** ^Any attempt to create a function with a longer name
  3871. ** will result in [SQLITE_MISUSE] being returned.
  3872. **
  3873. ** ^The third parameter (nArg)
  3874. ** is the number of arguments that the SQL function or
  3875. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  3876. ** aggregate may take any number of arguments between 0 and the limit
  3877. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  3878. ** parameter is less than -1 or greater than 127 then the behavior is
  3879. ** undefined.
  3880. **
  3881. ** ^The fourth parameter, eTextRep, specifies what
  3882. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  3883. ** its parameters. Every SQL function implementation must be able to work
  3884. ** with UTF-8, UTF-16le, or UTF-16be. But some implementations may be
  3885. ** more efficient with one encoding than another. ^An application may
  3886. ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
  3887. ** times with the same function but with different values of eTextRep.
  3888. ** ^When multiple implementations of the same function are available, SQLite
  3889. ** will pick the one that involves the least amount of data conversion.
  3890. ** If there is only a single implementation which does not care what text
  3891. ** encoding is used, then the fourth argument should be [SQLITE_ANY].
  3892. **
  3893. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  3894. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  3895. **
  3896. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  3897. ** pointers to C-language functions that implement the SQL function or
  3898. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  3899. ** callback only; NULL pointers must be passed as the xStep and xFinal
  3900. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  3901. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  3902. ** SQL function or aggregate, pass NULL pointers for all three function
  3903. ** callbacks.
  3904. **
  3905. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  3906. ** then it is destructor for the application data pointer.
  3907. ** The destructor is invoked when the function is deleted, either by being
  3908. ** overloaded or when the database connection closes.)^
  3909. ** ^The destructor is also invoked if the call to
  3910. ** sqlite3_create_function_v2() fails.
  3911. ** ^When the destructor callback of the tenth parameter is invoked, it
  3912. ** is passed a single argument which is a copy of the application data
  3913. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  3914. **
  3915. ** ^It is permitted to register multiple implementations of the same
  3916. ** functions with the same name but with either differing numbers of
  3917. ** arguments or differing preferred text encodings. ^SQLite will use
  3918. ** the implementation that most closely matches the way in which the
  3919. ** SQL function is used. ^A function implementation with a non-negative
  3920. ** nArg parameter is a better match than a function implementation with
  3921. ** a negative nArg. ^A function where the preferred text encoding
  3922. ** matches the database encoding is a better
  3923. ** match than a function where the encoding is different.
  3924. ** ^A function where the encoding difference is between UTF16le and UTF16be
  3925. ** is a closer match than a function where the encoding difference is
  3926. ** between UTF8 and UTF16.
  3927. **
  3928. ** ^Built-in functions may be overloaded by new application-defined functions.
  3929. **
  3930. ** ^An application-defined function is permitted to call other
  3931. ** SQLite interfaces. However, such calls must not
  3932. ** close the database connection nor finalize or reset the prepared
  3933. ** statement in which the function is running.
  3934. */
  3935. SQLITE_API int sqlite3_create_function(
  3936. sqlite3 *db,
  3937. const char *zFunctionName,
  3938. int nArg,
  3939. int eTextRep,
  3940. void *pApp,
  3941. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3942. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3943. void (*xFinal)(sqlite3_context*)
  3944. );
  3945. SQLITE_API int sqlite3_create_function16(
  3946. sqlite3 *db,
  3947. const void *zFunctionName,
  3948. int nArg,
  3949. int eTextRep,
  3950. void *pApp,
  3951. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3952. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3953. void (*xFinal)(sqlite3_context*)
  3954. );
  3955. SQLITE_API int sqlite3_create_function_v2(
  3956. sqlite3 *db,
  3957. const char *zFunctionName,
  3958. int nArg,
  3959. int eTextRep,
  3960. void *pApp,
  3961. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  3962. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  3963. void (*xFinal)(sqlite3_context*),
  3964. void(*xDestroy)(void*)
  3965. );
  3966. /*
  3967. ** CAPI3REF: Text Encodings
  3968. **
  3969. ** These constant define integer codes that represent the various
  3970. ** text encodings supported by SQLite.
  3971. */
  3972. #define SQLITE_UTF8 1
  3973. #define SQLITE_UTF16LE 2
  3974. #define SQLITE_UTF16BE 3
  3975. #define SQLITE_UTF16 4 /* Use native byte order */
  3976. #define SQLITE_ANY 5 /* sqlite3_create_function only */
  3977. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  3978. /*
  3979. ** CAPI3REF: Deprecated Functions
  3980. ** DEPRECATED
  3981. **
  3982. ** These functions are [deprecated]. In order to maintain
  3983. ** backwards compatibility with older code, these functions continue
  3984. ** to be supported. However, new applications should avoid
  3985. ** the use of these functions. To help encourage people to avoid
  3986. ** using these functions, we are not going to tell you what they do.
  3987. */
  3988. #ifndef SQLITE_OMIT_DEPRECATED
  3989. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  3990. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  3991. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  3992. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  3993. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  3994. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  3995. void*,sqlite3_int64);
  3996. #endif
  3997. /*
  3998. ** CAPI3REF: Obtaining SQL Function Parameter Values
  3999. **
  4000. ** The C-language implementation of SQL functions and aggregates uses
  4001. ** this set of interface routines to access the parameter values on
  4002. ** the function or aggregate.
  4003. **
  4004. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4005. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4006. ** define callbacks that implement the SQL functions and aggregates.
  4007. ** The 3rd parameter to these callbacks is an array of pointers to
  4008. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4009. ** each parameter to the SQL function. These routines are used to
  4010. ** extract values from the [sqlite3_value] objects.
  4011. **
  4012. ** These routines work only with [protected sqlite3_value] objects.
  4013. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4014. ** object results in undefined behavior.
  4015. **
  4016. ** ^These routines work just like the corresponding [column access functions]
  4017. ** except that these routines take a single [protected sqlite3_value] object
  4018. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4019. **
  4020. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4021. ** in the native byte-order of the host machine. ^The
  4022. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4023. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4024. **
  4025. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4026. ** numeric affinity to the value. This means that an attempt is
  4027. ** made to convert the value to an integer or floating point. If
  4028. ** such a conversion is possible without loss of information (in other
  4029. ** words, if the value is a string that looks like a number)
  4030. ** then the conversion is performed. Otherwise no conversion occurs.
  4031. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4032. **
  4033. ** Please pay particular attention to the fact that the pointer returned
  4034. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4035. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4036. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4037. ** or [sqlite3_value_text16()].
  4038. **
  4039. ** These routines must be called from the same thread as
  4040. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4041. */
  4042. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4043. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4044. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4045. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4046. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4047. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4048. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4049. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4050. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4051. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4052. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4053. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4054. /*
  4055. ** CAPI3REF: Obtain Aggregate Function Context
  4056. **
  4057. ** Implementations of aggregate SQL functions use this
  4058. ** routine to allocate memory for storing their state.
  4059. **
  4060. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4061. ** for a particular aggregate function, SQLite
  4062. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4063. ** to the new memory. ^On second and subsequent calls to
  4064. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4065. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4066. ** called once for each invocation of the xStep callback and then one
  4067. ** last time when the xFinal callback is invoked. ^(When no rows match
  4068. ** an aggregate query, the xStep() callback of the aggregate function
  4069. ** implementation is never called and xFinal() is called exactly once.
  4070. ** In those cases, sqlite3_aggregate_context() might be called for the
  4071. ** first time from within xFinal().)^
  4072. **
  4073. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4074. ** when first called if N is less than or equal to zero or if a memory
  4075. ** allocate error occurs.
  4076. **
  4077. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4078. ** determined by the N parameter on first successful call. Changing the
  4079. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4080. ** the same aggregate function instance will not resize the memory
  4081. ** allocation.)^ Within the xFinal callback, it is customary to set
  4082. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4083. ** pointless memory allocations occur.
  4084. **
  4085. ** ^SQLite automatically frees the memory allocated by
  4086. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4087. **
  4088. ** The first parameter must be a copy of the
  4089. ** [sqlite3_context | SQL function context] that is the first parameter
  4090. ** to the xStep or xFinal callback routine that implements the aggregate
  4091. ** function.
  4092. **
  4093. ** This routine must be called from the same thread in which
  4094. ** the aggregate SQL function is running.
  4095. */
  4096. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4097. /*
  4098. ** CAPI3REF: User Data For Functions
  4099. **
  4100. ** ^The sqlite3_user_data() interface returns a copy of
  4101. ** the pointer that was the pUserData parameter (the 5th parameter)
  4102. ** of the [sqlite3_create_function()]
  4103. ** and [sqlite3_create_function16()] routines that originally
  4104. ** registered the application defined function.
  4105. **
  4106. ** This routine must be called from the same thread in which
  4107. ** the application-defined function is running.
  4108. */
  4109. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4110. /*
  4111. ** CAPI3REF: Database Connection For Functions
  4112. **
  4113. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4114. ** the pointer to the [database connection] (the 1st parameter)
  4115. ** of the [sqlite3_create_function()]
  4116. ** and [sqlite3_create_function16()] routines that originally
  4117. ** registered the application defined function.
  4118. */
  4119. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4120. /*
  4121. ** CAPI3REF: Function Auxiliary Data
  4122. **
  4123. ** These functions may be used by (non-aggregate) SQL functions to
  4124. ** associate metadata with argument values. If the same value is passed to
  4125. ** multiple invocations of the same SQL function during query execution, under
  4126. ** some circumstances the associated metadata may be preserved. An example
  4127. ** of where this might be useful is in a regular-expression matching
  4128. ** function. The compiled version of the regular expression can be stored as
  4129. ** metadata associated with the pattern string.
  4130. ** Then as long as the pattern string remains the same,
  4131. ** the compiled regular expression can be reused on multiple
  4132. ** invocations of the same function.
  4133. **
  4134. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4135. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4136. ** value to the application-defined function. ^If there is no metadata
  4137. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4138. ** returns a NULL pointer.
  4139. **
  4140. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4141. ** argument of the application-defined function. ^Subsequent
  4142. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4143. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4144. ** NULL if the metadata has been discarded.
  4145. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4146. ** SQLite will invoke the destructor function X with parameter P exactly
  4147. ** once, when the metadata is discarded.
  4148. ** SQLite is free to discard the metadata at any time, including: <ul>
  4149. ** <li> when the corresponding function parameter changes, or
  4150. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4151. ** SQL statement, or
  4152. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4153. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4154. ** allocation error occurs. </ul>)^
  4155. **
  4156. ** Note the last bullet in particular. The destructor X in
  4157. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4158. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4159. ** should be called near the end of the function implementation and the
  4160. ** function implementation should not make any use of P after
  4161. ** sqlite3_set_auxdata() has been called.
  4162. **
  4163. ** ^(In practice, metadata is preserved between function calls for
  4164. ** function parameters that are compile-time constants, including literal
  4165. ** values and [parameters] and expressions composed from the same.)^
  4166. **
  4167. ** These routines must be called from the same thread in which
  4168. ** the SQL function is running.
  4169. */
  4170. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4171. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4172. /*
  4173. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4174. **
  4175. ** These are special values for the destructor that is passed in as the
  4176. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4177. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4178. ** and will never change. It does not need to be destroyed. ^The
  4179. ** SQLITE_TRANSIENT value means that the content will likely change in
  4180. ** the near future and that SQLite should make its own private copy of
  4181. ** the content before returning.
  4182. **
  4183. ** The typedef is necessary to work around problems in certain
  4184. ** C++ compilers.
  4185. */
  4186. typedef void (*sqlite3_destructor_type)(void*);
  4187. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4188. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4189. /*
  4190. ** CAPI3REF: Setting The Result Of An SQL Function
  4191. **
  4192. ** These routines are used by the xFunc or xFinal callbacks that
  4193. ** implement SQL functions and aggregates. See
  4194. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4195. ** for additional information.
  4196. **
  4197. ** These functions work very much like the [parameter binding] family of
  4198. ** functions used to bind values to host parameters in prepared statements.
  4199. ** Refer to the [SQL parameter] documentation for additional information.
  4200. **
  4201. ** ^The sqlite3_result_blob() interface sets the result from
  4202. ** an application-defined function to be the BLOB whose content is pointed
  4203. ** to by the second parameter and which is N bytes long where N is the
  4204. ** third parameter.
  4205. **
  4206. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4207. ** the application-defined function to be a BLOB containing all zero
  4208. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4209. **
  4210. ** ^The sqlite3_result_double() interface sets the result from
  4211. ** an application-defined function to be a floating point value specified
  4212. ** by its 2nd argument.
  4213. **
  4214. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4215. ** cause the implemented SQL function to throw an exception.
  4216. ** ^SQLite uses the string pointed to by the
  4217. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4218. ** as the text of an error message. ^SQLite interprets the error
  4219. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4220. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4221. ** byte order. ^If the third parameter to sqlite3_result_error()
  4222. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4223. ** message all text up through the first zero character.
  4224. ** ^If the third parameter to sqlite3_result_error() or
  4225. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4226. ** bytes (not characters) from the 2nd parameter as the error message.
  4227. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4228. ** routines make a private copy of the error message text before
  4229. ** they return. Hence, the calling function can deallocate or
  4230. ** modify the text after they return without harm.
  4231. ** ^The sqlite3_result_error_code() function changes the error code
  4232. ** returned by SQLite as a result of an error in a function. ^By default,
  4233. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4234. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4235. **
  4236. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4237. ** error indicating that a string or BLOB is too long to represent.
  4238. **
  4239. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4240. ** error indicating that a memory allocation failed.
  4241. **
  4242. ** ^The sqlite3_result_int() interface sets the return value
  4243. ** of the application-defined function to be the 32-bit signed integer
  4244. ** value given in the 2nd argument.
  4245. ** ^The sqlite3_result_int64() interface sets the return value
  4246. ** of the application-defined function to be the 64-bit signed integer
  4247. ** value given in the 2nd argument.
  4248. **
  4249. ** ^The sqlite3_result_null() interface sets the return value
  4250. ** of the application-defined function to be NULL.
  4251. **
  4252. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4253. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4254. ** set the return value of the application-defined function to be
  4255. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4256. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4257. ** ^SQLite takes the text result from the application from
  4258. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4259. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4260. ** is negative, then SQLite takes result text from the 2nd parameter
  4261. ** through the first zero character.
  4262. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4263. ** is non-negative, then as many bytes (not characters) of the text
  4264. ** pointed to by the 2nd parameter are taken as the application-defined
  4265. ** function result. If the 3rd parameter is non-negative, then it
  4266. ** must be the byte offset into the string where the NUL terminator would
  4267. ** appear if the string where NUL terminated. If any NUL characters occur
  4268. ** in the string at a byte offset that is less than the value of the 3rd
  4269. ** parameter, then the resulting string will contain embedded NULs and the
  4270. ** result of expressions operating on strings with embedded NULs is undefined.
  4271. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4272. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4273. ** function as the destructor on the text or BLOB result when it has
  4274. ** finished using that result.
  4275. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4276. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4277. ** assumes that the text or BLOB result is in constant space and does not
  4278. ** copy the content of the parameter nor call a destructor on the content
  4279. ** when it has finished using that result.
  4280. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4281. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4282. ** then SQLite makes a copy of the result into space obtained from
  4283. ** from [sqlite3_malloc()] before it returns.
  4284. **
  4285. ** ^The sqlite3_result_value() interface sets the result of
  4286. ** the application-defined function to be a copy the
  4287. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4288. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4289. ** so that the [sqlite3_value] specified in the parameter may change or
  4290. ** be deallocated after sqlite3_result_value() returns without harm.
  4291. ** ^A [protected sqlite3_value] object may always be used where an
  4292. ** [unprotected sqlite3_value] object is required, so either
  4293. ** kind of [sqlite3_value] object can be used with this interface.
  4294. **
  4295. ** If these routines are called from within the different thread
  4296. ** than the one containing the application-defined function that received
  4297. ** the [sqlite3_context] pointer, the results are undefined.
  4298. */
  4299. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4300. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4301. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4302. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4303. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4304. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4305. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4306. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4307. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4308. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4309. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4310. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4311. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4312. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4313. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4314. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4315. /*
  4316. ** CAPI3REF: Define New Collating Sequences
  4317. **
  4318. ** ^These functions add, remove, or modify a [collation] associated
  4319. ** with the [database connection] specified as the first argument.
  4320. **
  4321. ** ^The name of the collation is a UTF-8 string
  4322. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4323. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4324. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4325. ** considered to be the same name.
  4326. **
  4327. ** ^(The third argument (eTextRep) must be one of the constants:
  4328. ** <ul>
  4329. ** <li> [SQLITE_UTF8],
  4330. ** <li> [SQLITE_UTF16LE],
  4331. ** <li> [SQLITE_UTF16BE],
  4332. ** <li> [SQLITE_UTF16], or
  4333. ** <li> [SQLITE_UTF16_ALIGNED].
  4334. ** </ul>)^
  4335. ** ^The eTextRep argument determines the encoding of strings passed
  4336. ** to the collating function callback, xCallback.
  4337. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4338. ** force strings to be UTF16 with native byte order.
  4339. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4340. ** on an even byte address.
  4341. **
  4342. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4343. ** through as the first argument to the collating function callback.
  4344. **
  4345. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4346. ** ^Multiple collating functions can be registered using the same name but
  4347. ** with different eTextRep parameters and SQLite will use whichever
  4348. ** function requires the least amount of data transformation.
  4349. ** ^If the xCallback argument is NULL then the collating function is
  4350. ** deleted. ^When all collating functions having the same name are deleted,
  4351. ** that collation is no longer usable.
  4352. **
  4353. ** ^The collating function callback is invoked with a copy of the pArg
  4354. ** application data pointer and with two strings in the encoding specified
  4355. ** by the eTextRep argument. The collating function must return an
  4356. ** integer that is negative, zero, or positive
  4357. ** if the first string is less than, equal to, or greater than the second,
  4358. ** respectively. A collating function must always return the same answer
  4359. ** given the same inputs. If two or more collating functions are registered
  4360. ** to the same collation name (using different eTextRep values) then all
  4361. ** must give an equivalent answer when invoked with equivalent strings.
  4362. ** The collating function must obey the following properties for all
  4363. ** strings A, B, and C:
  4364. **
  4365. ** <ol>
  4366. ** <li> If A==B then B==A.
  4367. ** <li> If A==B and B==C then A==C.
  4368. ** <li> If A&lt;B THEN B&gt;A.
  4369. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4370. ** </ol>
  4371. **
  4372. ** If a collating function fails any of the above constraints and that
  4373. ** collating function is registered and used, then the behavior of SQLite
  4374. ** is undefined.
  4375. **
  4376. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4377. ** with the addition that the xDestroy callback is invoked on pArg when
  4378. ** the collating function is deleted.
  4379. ** ^Collating functions are deleted when they are overridden by later
  4380. ** calls to the collation creation functions or when the
  4381. ** [database connection] is closed using [sqlite3_close()].
  4382. **
  4383. ** ^The xDestroy callback is <u>not</u> called if the
  4384. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4385. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4386. ** check the return code and dispose of the application data pointer
  4387. ** themselves rather than expecting SQLite to deal with it for them.
  4388. ** This is different from every other SQLite interface. The inconsistency
  4389. ** is unfortunate but cannot be changed without breaking backwards
  4390. ** compatibility.
  4391. **
  4392. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4393. */
  4394. SQLITE_API int sqlite3_create_collation(
  4395. sqlite3*,
  4396. const char *zName,
  4397. int eTextRep,
  4398. void *pArg,
  4399. int(*xCompare)(void*,int,const void*,int,const void*)
  4400. );
  4401. SQLITE_API int sqlite3_create_collation_v2(
  4402. sqlite3*,
  4403. const char *zName,
  4404. int eTextRep,
  4405. void *pArg,
  4406. int(*xCompare)(void*,int,const void*,int,const void*),
  4407. void(*xDestroy)(void*)
  4408. );
  4409. SQLITE_API int sqlite3_create_collation16(
  4410. sqlite3*,
  4411. const void *zName,
  4412. int eTextRep,
  4413. void *pArg,
  4414. int(*xCompare)(void*,int,const void*,int,const void*)
  4415. );
  4416. /*
  4417. ** CAPI3REF: Collation Needed Callbacks
  4418. **
  4419. ** ^To avoid having to register all collation sequences before a database
  4420. ** can be used, a single callback function may be registered with the
  4421. ** [database connection] to be invoked whenever an undefined collation
  4422. ** sequence is required.
  4423. **
  4424. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4425. ** then it is passed the names of undefined collation sequences as strings
  4426. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4427. ** the names are passed as UTF-16 in machine native byte order.
  4428. ** ^A call to either function replaces the existing collation-needed callback.
  4429. **
  4430. ** ^(When the callback is invoked, the first argument passed is a copy
  4431. ** of the second argument to sqlite3_collation_needed() or
  4432. ** sqlite3_collation_needed16(). The second argument is the database
  4433. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4434. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4435. ** sequence function required. The fourth parameter is the name of the
  4436. ** required collation sequence.)^
  4437. **
  4438. ** The callback function should register the desired collation using
  4439. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4440. ** [sqlite3_create_collation_v2()].
  4441. */
  4442. SQLITE_API int sqlite3_collation_needed(
  4443. sqlite3*,
  4444. void*,
  4445. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4446. );
  4447. SQLITE_API int sqlite3_collation_needed16(
  4448. sqlite3*,
  4449. void*,
  4450. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4451. );
  4452. #ifdef SQLITE_HAS_CODEC
  4453. /*
  4454. ** Specify the key for an encrypted database. This routine should be
  4455. ** called right after sqlite3_open().
  4456. **
  4457. ** The code to implement this API is not available in the public release
  4458. ** of SQLite.
  4459. */
  4460. SQLITE_API int sqlite3_key(
  4461. sqlite3 *db, /* Database to be rekeyed */
  4462. const void *pKey, int nKey /* The key */
  4463. );
  4464. SQLITE_API int sqlite3_key_v2(
  4465. sqlite3 *db, /* Database to be rekeyed */
  4466. const char *zDbName, /* Name of the database */
  4467. const void *pKey, int nKey /* The key */
  4468. );
  4469. /*
  4470. ** Change the key on an open database. If the current database is not
  4471. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4472. ** database is decrypted.
  4473. **
  4474. ** The code to implement this API is not available in the public release
  4475. ** of SQLite.
  4476. */
  4477. SQLITE_API int sqlite3_rekey(
  4478. sqlite3 *db, /* Database to be rekeyed */
  4479. const void *pKey, int nKey /* The new key */
  4480. );
  4481. SQLITE_API int sqlite3_rekey_v2(
  4482. sqlite3 *db, /* Database to be rekeyed */
  4483. const char *zDbName, /* Name of the database */
  4484. const void *pKey, int nKey /* The new key */
  4485. );
  4486. /*
  4487. ** Specify the activation key for a SEE database. Unless
  4488. ** activated, none of the SEE routines will work.
  4489. */
  4490. SQLITE_API void sqlite3_activate_see(
  4491. const char *zPassPhrase /* Activation phrase */
  4492. );
  4493. #endif
  4494. #ifdef SQLITE_ENABLE_CEROD
  4495. /*
  4496. ** Specify the activation key for a CEROD database. Unless
  4497. ** activated, none of the CEROD routines will work.
  4498. */
  4499. SQLITE_API void sqlite3_activate_cerod(
  4500. const char *zPassPhrase /* Activation phrase */
  4501. );
  4502. #endif
  4503. /*
  4504. ** CAPI3REF: Suspend Execution For A Short Time
  4505. **
  4506. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4507. ** for at least a number of milliseconds specified in its parameter.
  4508. **
  4509. ** If the operating system does not support sleep requests with
  4510. ** millisecond time resolution, then the time will be rounded up to
  4511. ** the nearest second. The number of milliseconds of sleep actually
  4512. ** requested from the operating system is returned.
  4513. **
  4514. ** ^SQLite implements this interface by calling the xSleep()
  4515. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4516. ** of the default VFS is not implemented correctly, or not implemented at
  4517. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4518. ** in the previous paragraphs.
  4519. */
  4520. SQLITE_API int sqlite3_sleep(int);
  4521. /*
  4522. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4523. **
  4524. ** ^(If this global variable is made to point to a string which is
  4525. ** the name of a folder (a.k.a. directory), then all temporary files
  4526. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4527. ** will be placed in that directory.)^ ^If this variable
  4528. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4529. ** temporary file directory.
  4530. **
  4531. ** It is not safe to read or modify this variable in more than one
  4532. ** thread at a time. It is not safe to read or modify this variable
  4533. ** if a [database connection] is being used at the same time in a separate
  4534. ** thread.
  4535. ** It is intended that this variable be set once
  4536. ** as part of process initialization and before any SQLite interface
  4537. ** routines have been called and that this variable remain unchanged
  4538. ** thereafter.
  4539. **
  4540. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4541. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4542. ** the [temp_store_directory pragma] always assumes that any string
  4543. ** that this variable points to is held in memory obtained from
  4544. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4545. ** using [sqlite3_free].
  4546. ** Hence, if this variable is modified directly, either it should be
  4547. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4548. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4549. **
  4550. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4551. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4552. ** features that require the use of temporary files may fail. Here is an
  4553. ** example of how to do this using C++ with the Windows Runtime:
  4554. **
  4555. ** <blockquote><pre>
  4556. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4557. ** &nbsp; TemporaryFolder->Path->Data();
  4558. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4559. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4560. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4561. ** &nbsp; NULL, NULL);
  4562. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4563. ** </pre></blockquote>
  4564. */
  4565. SQLITE_API char *sqlite3_temp_directory;
  4566. /*
  4567. ** CAPI3REF: Name Of The Folder Holding Database Files
  4568. **
  4569. ** ^(If this global variable is made to point to a string which is
  4570. ** the name of a folder (a.k.a. directory), then all database files
  4571. ** specified with a relative pathname and created or accessed by
  4572. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4573. ** to be relative to that directory.)^ ^If this variable is a NULL
  4574. ** pointer, then SQLite assumes that all database files specified
  4575. ** with a relative pathname are relative to the current directory
  4576. ** for the process. Only the windows VFS makes use of this global
  4577. ** variable; it is ignored by the unix VFS.
  4578. **
  4579. ** Changing the value of this variable while a database connection is
  4580. ** open can result in a corrupt database.
  4581. **
  4582. ** It is not safe to read or modify this variable in more than one
  4583. ** thread at a time. It is not safe to read or modify this variable
  4584. ** if a [database connection] is being used at the same time in a separate
  4585. ** thread.
  4586. ** It is intended that this variable be set once
  4587. ** as part of process initialization and before any SQLite interface
  4588. ** routines have been called and that this variable remain unchanged
  4589. ** thereafter.
  4590. **
  4591. ** ^The [data_store_directory pragma] may modify this variable and cause
  4592. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4593. ** the [data_store_directory pragma] always assumes that any string
  4594. ** that this variable points to is held in memory obtained from
  4595. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4596. ** using [sqlite3_free].
  4597. ** Hence, if this variable is modified directly, either it should be
  4598. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4599. ** or else the use of the [data_store_directory pragma] should be avoided.
  4600. */
  4601. SQLITE_API char *sqlite3_data_directory;
  4602. /*
  4603. ** CAPI3REF: Test For Auto-Commit Mode
  4604. ** KEYWORDS: {autocommit mode}
  4605. **
  4606. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4607. ** zero if the given database connection is or is not in autocommit mode,
  4608. ** respectively. ^Autocommit mode is on by default.
  4609. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4610. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4611. **
  4612. ** If certain kinds of errors occur on a statement within a multi-statement
  4613. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4614. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4615. ** transaction might be rolled back automatically. The only way to
  4616. ** find out whether SQLite automatically rolled back the transaction after
  4617. ** an error is to use this function.
  4618. **
  4619. ** If another thread changes the autocommit status of the database
  4620. ** connection while this routine is running, then the return value
  4621. ** is undefined.
  4622. */
  4623. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4624. /*
  4625. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4626. **
  4627. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4628. ** to which a [prepared statement] belongs. ^The [database connection]
  4629. ** returned by sqlite3_db_handle is the same [database connection]
  4630. ** that was the first argument
  4631. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4632. ** create the statement in the first place.
  4633. */
  4634. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4635. /*
  4636. ** CAPI3REF: Return The Filename For A Database Connection
  4637. **
  4638. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4639. ** associated with database N of connection D. ^The main database file
  4640. ** has the name "main". If there is no attached database N on the database
  4641. ** connection D, or if database N is a temporary or in-memory database, then
  4642. ** a NULL pointer is returned.
  4643. **
  4644. ** ^The filename returned by this function is the output of the
  4645. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4646. ** will be an absolute pathname, even if the filename used
  4647. ** to open the database originally was a URI or relative pathname.
  4648. */
  4649. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4650. /*
  4651. ** CAPI3REF: Determine if a database is read-only
  4652. **
  4653. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4654. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4655. ** the name of a database on connection D.
  4656. */
  4657. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4658. /*
  4659. ** CAPI3REF: Find the next prepared statement
  4660. **
  4661. ** ^This interface returns a pointer to the next [prepared statement] after
  4662. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4663. ** then this interface returns a pointer to the first prepared statement
  4664. ** associated with the database connection pDb. ^If no prepared statement
  4665. ** satisfies the conditions of this routine, it returns NULL.
  4666. **
  4667. ** The [database connection] pointer D in a call to
  4668. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4669. ** connection and in particular must not be a NULL pointer.
  4670. */
  4671. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4672. /*
  4673. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4674. **
  4675. ** ^The sqlite3_commit_hook() interface registers a callback
  4676. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4677. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4678. ** for the same database connection is overridden.
  4679. ** ^The sqlite3_rollback_hook() interface registers a callback
  4680. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4681. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4682. ** for the same database connection is overridden.
  4683. ** ^The pArg argument is passed through to the callback.
  4684. ** ^If the callback on a commit hook function returns non-zero,
  4685. ** then the commit is converted into a rollback.
  4686. **
  4687. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4688. ** return the P argument from the previous call of the same function
  4689. ** on the same [database connection] D, or NULL for
  4690. ** the first call for each function on D.
  4691. **
  4692. ** The commit and rollback hook callbacks are not reentrant.
  4693. ** The callback implementation must not do anything that will modify
  4694. ** the database connection that invoked the callback. Any actions
  4695. ** to modify the database connection must be deferred until after the
  4696. ** completion of the [sqlite3_step()] call that triggered the commit
  4697. ** or rollback hook in the first place.
  4698. ** Note that running any other SQL statements, including SELECT statements,
  4699. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4700. ** the database connections for the meaning of "modify" in this paragraph.
  4701. **
  4702. ** ^Registering a NULL function disables the callback.
  4703. **
  4704. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4705. ** operation is allowed to continue normally. ^If the commit hook
  4706. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4707. ** ^The rollback hook is invoked on a rollback that results from a commit
  4708. ** hook returning non-zero, just as it would be with any other rollback.
  4709. **
  4710. ** ^For the purposes of this API, a transaction is said to have been
  4711. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4712. ** an error or constraint causes an implicit rollback to occur.
  4713. ** ^The rollback callback is not invoked if a transaction is
  4714. ** automatically rolled back because the database connection is closed.
  4715. **
  4716. ** See also the [sqlite3_update_hook()] interface.
  4717. */
  4718. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4719. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4720. /*
  4721. ** CAPI3REF: Data Change Notification Callbacks
  4722. **
  4723. ** ^The sqlite3_update_hook() interface registers a callback function
  4724. ** with the [database connection] identified by the first argument
  4725. ** to be invoked whenever a row is updated, inserted or deleted.
  4726. ** ^Any callback set by a previous call to this function
  4727. ** for the same database connection is overridden.
  4728. **
  4729. ** ^The second argument is a pointer to the function to invoke when a
  4730. ** row is updated, inserted or deleted.
  4731. ** ^The first argument to the callback is a copy of the third argument
  4732. ** to sqlite3_update_hook().
  4733. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4734. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4735. ** to be invoked.
  4736. ** ^The third and fourth arguments to the callback contain pointers to the
  4737. ** database and table name containing the affected row.
  4738. ** ^The final callback parameter is the [rowid] of the row.
  4739. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4740. **
  4741. ** ^(The update hook is not invoked when internal system tables are
  4742. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4743. **
  4744. ** ^In the current implementation, the update hook
  4745. ** is not invoked when duplication rows are deleted because of an
  4746. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4747. ** invoked when rows are deleted using the [truncate optimization].
  4748. ** The exceptions defined in this paragraph might change in a future
  4749. ** release of SQLite.
  4750. **
  4751. ** The update hook implementation must not do anything that will modify
  4752. ** the database connection that invoked the update hook. Any actions
  4753. ** to modify the database connection must be deferred until after the
  4754. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4755. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4756. ** database connections for the meaning of "modify" in this paragraph.
  4757. **
  4758. ** ^The sqlite3_update_hook(D,C,P) function
  4759. ** returns the P argument from the previous call
  4760. ** on the same [database connection] D, or NULL for
  4761. ** the first call on D.
  4762. **
  4763. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  4764. ** interfaces.
  4765. */
  4766. SQLITE_API void *sqlite3_update_hook(
  4767. sqlite3*,
  4768. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  4769. void*
  4770. );
  4771. /*
  4772. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  4773. **
  4774. ** ^(This routine enables or disables the sharing of the database cache
  4775. ** and schema data structures between [database connection | connections]
  4776. ** to the same database. Sharing is enabled if the argument is true
  4777. ** and disabled if the argument is false.)^
  4778. **
  4779. ** ^Cache sharing is enabled and disabled for an entire process.
  4780. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  4781. ** sharing was enabled or disabled for each thread separately.
  4782. **
  4783. ** ^(The cache sharing mode set by this interface effects all subsequent
  4784. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  4785. ** Existing database connections continue use the sharing mode
  4786. ** that was in effect at the time they were opened.)^
  4787. **
  4788. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  4789. ** successfully. An [error code] is returned otherwise.)^
  4790. **
  4791. ** ^Shared cache is disabled by default. But this might change in
  4792. ** future releases of SQLite. Applications that care about shared
  4793. ** cache setting should set it explicitly.
  4794. **
  4795. ** This interface is threadsafe on processors where writing a
  4796. ** 32-bit integer is atomic.
  4797. **
  4798. ** See Also: [SQLite Shared-Cache Mode]
  4799. */
  4800. SQLITE_API int sqlite3_enable_shared_cache(int);
  4801. /*
  4802. ** CAPI3REF: Attempt To Free Heap Memory
  4803. **
  4804. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  4805. ** of heap memory by deallocating non-essential memory allocations
  4806. ** held by the database library. Memory used to cache database
  4807. ** pages to improve performance is an example of non-essential memory.
  4808. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  4809. ** which might be more or less than the amount requested.
  4810. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  4811. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4812. **
  4813. ** See also: [sqlite3_db_release_memory()]
  4814. */
  4815. SQLITE_API int sqlite3_release_memory(int);
  4816. /*
  4817. ** CAPI3REF: Free Memory Used By A Database Connection
  4818. **
  4819. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  4820. ** memory as possible from database connection D. Unlike the
  4821. ** [sqlite3_release_memory()] interface, this interface is effect even
  4822. ** when then [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  4823. ** omitted.
  4824. **
  4825. ** See also: [sqlite3_release_memory()]
  4826. */
  4827. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  4828. /*
  4829. ** CAPI3REF: Impose A Limit On Heap Size
  4830. **
  4831. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  4832. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  4833. ** ^SQLite strives to keep heap memory utilization below the soft heap
  4834. ** limit by reducing the number of pages held in the page cache
  4835. ** as heap memory usages approaches the limit.
  4836. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  4837. ** below the limit, it will exceed the limit rather than generate
  4838. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  4839. ** is advisory only.
  4840. **
  4841. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  4842. ** the soft heap limit prior to the call, or negative in the case of an
  4843. ** error. ^If the argument N is negative
  4844. ** then no change is made to the soft heap limit. Hence, the current
  4845. ** size of the soft heap limit can be determined by invoking
  4846. ** sqlite3_soft_heap_limit64() with a negative argument.
  4847. **
  4848. ** ^If the argument N is zero then the soft heap limit is disabled.
  4849. **
  4850. ** ^(The soft heap limit is not enforced in the current implementation
  4851. ** if one or more of following conditions are true:
  4852. **
  4853. ** <ul>
  4854. ** <li> The soft heap limit is set to zero.
  4855. ** <li> Memory accounting is disabled using a combination of the
  4856. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  4857. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  4858. ** <li> An alternative page cache implementation is specified using
  4859. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  4860. ** <li> The page cache allocates from its own memory pool supplied
  4861. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  4862. ** from the heap.
  4863. ** </ul>)^
  4864. **
  4865. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  4866. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  4867. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  4868. ** the soft heap limit is enforced on every memory allocation. Without
  4869. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  4870. ** when memory is allocated by the page cache. Testing suggests that because
  4871. ** the page cache is the predominate memory user in SQLite, most
  4872. ** applications will achieve adequate soft heap limit enforcement without
  4873. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  4874. **
  4875. ** The circumstances under which SQLite will enforce the soft heap limit may
  4876. ** changes in future releases of SQLite.
  4877. */
  4878. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  4879. /*
  4880. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  4881. ** DEPRECATED
  4882. **
  4883. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  4884. ** interface. This routine is provided for historical compatibility
  4885. ** only. All new applications should use the
  4886. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  4887. */
  4888. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  4889. /*
  4890. ** CAPI3REF: Extract Metadata About A Column Of A Table
  4891. **
  4892. ** ^This routine returns metadata about a specific column of a specific
  4893. ** database table accessible using the [database connection] handle
  4894. ** passed as the first function argument.
  4895. **
  4896. ** ^The column is identified by the second, third and fourth parameters to
  4897. ** this function. ^The second parameter is either the name of the database
  4898. ** (i.e. "main", "temp", or an attached database) containing the specified
  4899. ** table or NULL. ^If it is NULL, then all attached databases are searched
  4900. ** for the table using the same algorithm used by the database engine to
  4901. ** resolve unqualified table references.
  4902. **
  4903. ** ^The third and fourth parameters to this function are the table and column
  4904. ** name of the desired column, respectively. Neither of these parameters
  4905. ** may be NULL.
  4906. **
  4907. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  4908. ** and subsequent parameters to this function. ^Any of these arguments may be
  4909. ** NULL, in which case the corresponding element of metadata is omitted.
  4910. **
  4911. ** ^(<blockquote>
  4912. ** <table border="1">
  4913. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  4914. **
  4915. ** <tr><td> 5th <td> const char* <td> Data type
  4916. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  4917. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  4918. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  4919. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  4920. ** </table>
  4921. ** </blockquote>)^
  4922. **
  4923. ** ^The memory pointed to by the character pointers returned for the
  4924. ** declaration type and collation sequence is valid only until the next
  4925. ** call to any SQLite API function.
  4926. **
  4927. ** ^If the specified table is actually a view, an [error code] is returned.
  4928. **
  4929. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  4930. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  4931. ** parameters are set for the explicitly declared column. ^(If there is no
  4932. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  4933. ** parameters are set as follows:
  4934. **
  4935. ** <pre>
  4936. ** data type: "INTEGER"
  4937. ** collation sequence: "BINARY"
  4938. ** not null: 0
  4939. ** primary key: 1
  4940. ** auto increment: 0
  4941. ** </pre>)^
  4942. **
  4943. ** ^(This function may load one or more schemas from database files. If an
  4944. ** error occurs during this process, or if the requested table or column
  4945. ** cannot be found, an [error code] is returned and an error message left
  4946. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  4947. **
  4948. ** ^This API is only available if the library was compiled with the
  4949. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  4950. */
  4951. SQLITE_API int sqlite3_table_column_metadata(
  4952. sqlite3 *db, /* Connection handle */
  4953. const char *zDbName, /* Database name or NULL */
  4954. const char *zTableName, /* Table name */
  4955. const char *zColumnName, /* Column name */
  4956. char const **pzDataType, /* OUTPUT: Declared data type */
  4957. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  4958. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  4959. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  4960. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  4961. );
  4962. /*
  4963. ** CAPI3REF: Load An Extension
  4964. **
  4965. ** ^This interface loads an SQLite extension library from the named file.
  4966. **
  4967. ** ^The sqlite3_load_extension() interface attempts to load an
  4968. ** [SQLite extension] library contained in the file zFile. If
  4969. ** the file cannot be loaded directly, attempts are made to load
  4970. ** with various operating-system specific extensions added.
  4971. ** So for example, if "samplelib" cannot be loaded, then names like
  4972. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  4973. ** be tried also.
  4974. **
  4975. ** ^The entry point is zProc.
  4976. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  4977. ** entry point name on its own. It first tries "sqlite3_extension_init".
  4978. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  4979. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  4980. ** characters in the filename from the last "/" to the first following
  4981. ** "." and omitting any initial "lib".)^
  4982. ** ^The sqlite3_load_extension() interface returns
  4983. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  4984. ** ^If an error occurs and pzErrMsg is not 0, then the
  4985. ** [sqlite3_load_extension()] interface shall attempt to
  4986. ** fill *pzErrMsg with error message text stored in memory
  4987. ** obtained from [sqlite3_malloc()]. The calling function
  4988. ** should free this memory by calling [sqlite3_free()].
  4989. **
  4990. ** ^Extension loading must be enabled using
  4991. ** [sqlite3_enable_load_extension()] prior to calling this API,
  4992. ** otherwise an error will be returned.
  4993. **
  4994. ** See also the [load_extension() SQL function].
  4995. */
  4996. SQLITE_API int sqlite3_load_extension(
  4997. sqlite3 *db, /* Load the extension into this database connection */
  4998. const char *zFile, /* Name of the shared library containing extension */
  4999. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5000. char **pzErrMsg /* Put error message here if not 0 */
  5001. );
  5002. /*
  5003. ** CAPI3REF: Enable Or Disable Extension Loading
  5004. **
  5005. ** ^So as not to open security holes in older applications that are
  5006. ** unprepared to deal with [extension loading], and as a means of disabling
  5007. ** [extension loading] while evaluating user-entered SQL, the following API
  5008. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5009. **
  5010. ** ^Extension loading is off by default.
  5011. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5012. ** to turn extension loading on and call it with onoff==0 to turn
  5013. ** it back off again.
  5014. */
  5015. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5016. /*
  5017. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5018. **
  5019. ** ^This interface causes the xEntryPoint() function to be invoked for
  5020. ** each new [database connection] that is created. The idea here is that
  5021. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5022. ** that is to be automatically loaded into all new database connections.
  5023. **
  5024. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5025. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5026. ** arguments and expects and integer result as if the signature of the
  5027. ** entry point where as follows:
  5028. **
  5029. ** <blockquote><pre>
  5030. ** &nbsp; int xEntryPoint(
  5031. ** &nbsp; sqlite3 *db,
  5032. ** &nbsp; const char **pzErrMsg,
  5033. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5034. ** &nbsp; );
  5035. ** </pre></blockquote>)^
  5036. **
  5037. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5038. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5039. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5040. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5041. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5042. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5043. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5044. **
  5045. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5046. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5047. ** will be called more than once for each database connection that is opened.
  5048. **
  5049. ** See also: [sqlite3_reset_auto_extension()]
  5050. ** and [sqlite3_cancel_auto_extension()]
  5051. */
  5052. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5053. /*
  5054. ** CAPI3REF: Cancel Automatic Extension Loading
  5055. **
  5056. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5057. ** initialization routine X that was registered using a prior call to
  5058. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5059. ** routine returns 1 if initialization routine X was successfully
  5060. ** unregistered and it returns 0 if X was not on the list of initialization
  5061. ** routines.
  5062. */
  5063. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5064. /*
  5065. ** CAPI3REF: Reset Automatic Extension Loading
  5066. **
  5067. ** ^This interface disables all automatic extensions previously
  5068. ** registered using [sqlite3_auto_extension()].
  5069. */
  5070. SQLITE_API void sqlite3_reset_auto_extension(void);
  5071. /*
  5072. ** The interface to the virtual-table mechanism is currently considered
  5073. ** to be experimental. The interface might change in incompatible ways.
  5074. ** If this is a problem for you, do not use the interface at this time.
  5075. **
  5076. ** When the virtual-table mechanism stabilizes, we will declare the
  5077. ** interface fixed, support it indefinitely, and remove this comment.
  5078. */
  5079. /*
  5080. ** Structures used by the virtual table interface
  5081. */
  5082. typedef struct sqlite3_vtab sqlite3_vtab;
  5083. typedef struct sqlite3_index_info sqlite3_index_info;
  5084. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5085. typedef struct sqlite3_module sqlite3_module;
  5086. /*
  5087. ** CAPI3REF: Virtual Table Object
  5088. ** KEYWORDS: sqlite3_module {virtual table module}
  5089. **
  5090. ** This structure, sometimes called a "virtual table module",
  5091. ** defines the implementation of a [virtual tables].
  5092. ** This structure consists mostly of methods for the module.
  5093. **
  5094. ** ^A virtual table module is created by filling in a persistent
  5095. ** instance of this structure and passing a pointer to that instance
  5096. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5097. ** ^The registration remains valid until it is replaced by a different
  5098. ** module or until the [database connection] closes. The content
  5099. ** of this structure must not change while it is registered with
  5100. ** any database connection.
  5101. */
  5102. struct sqlite3_module {
  5103. int iVersion;
  5104. int (*xCreate)(sqlite3*, void *pAux,
  5105. int argc, const char *const*argv,
  5106. sqlite3_vtab **ppVTab, char**);
  5107. int (*xConnect)(sqlite3*, void *pAux,
  5108. int argc, const char *const*argv,
  5109. sqlite3_vtab **ppVTab, char**);
  5110. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5111. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5112. int (*xDestroy)(sqlite3_vtab *pVTab);
  5113. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5114. int (*xClose)(sqlite3_vtab_cursor*);
  5115. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5116. int argc, sqlite3_value **argv);
  5117. int (*xNext)(sqlite3_vtab_cursor*);
  5118. int (*xEof)(sqlite3_vtab_cursor*);
  5119. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5120. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5121. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5122. int (*xBegin)(sqlite3_vtab *pVTab);
  5123. int (*xSync)(sqlite3_vtab *pVTab);
  5124. int (*xCommit)(sqlite3_vtab *pVTab);
  5125. int (*xRollback)(sqlite3_vtab *pVTab);
  5126. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5127. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5128. void **ppArg);
  5129. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5130. /* The methods above are in version 1 of the sqlite_module object. Those
  5131. ** below are for version 2 and greater. */
  5132. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5133. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5134. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5135. };
  5136. /*
  5137. ** CAPI3REF: Virtual Table Indexing Information
  5138. ** KEYWORDS: sqlite3_index_info
  5139. **
  5140. ** The sqlite3_index_info structure and its substructures is used as part
  5141. ** of the [virtual table] interface to
  5142. ** pass information into and receive the reply from the [xBestIndex]
  5143. ** method of a [virtual table module]. The fields under **Inputs** are the
  5144. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5145. ** results into the **Outputs** fields.
  5146. **
  5147. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5148. **
  5149. ** <blockquote>column OP expr</blockquote>
  5150. **
  5151. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5152. ** stored in aConstraint[].op using one of the
  5153. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5154. ** ^(The index of the column is stored in
  5155. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5156. ** expr on the right-hand side can be evaluated (and thus the constraint
  5157. ** is usable) and false if it cannot.)^
  5158. **
  5159. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5160. ** and makes other simplifications to the WHERE clause in an attempt to
  5161. ** get as many WHERE clause terms into the form shown above as possible.
  5162. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5163. ** relevant to the particular virtual table being queried.
  5164. **
  5165. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5166. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5167. **
  5168. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5169. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5170. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5171. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5172. ** is true, then the constraint is assumed to be fully handled by the
  5173. ** virtual table and is not checked again by SQLite.)^
  5174. **
  5175. ** ^The idxNum and idxPtr values are recorded and passed into the
  5176. ** [xFilter] method.
  5177. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5178. ** needToFreeIdxPtr is true.
  5179. **
  5180. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5181. ** the correct order to satisfy the ORDER BY clause so that no separate
  5182. ** sorting step is required.
  5183. **
  5184. ** ^The estimatedCost value is an estimate of the cost of doing the
  5185. ** particular lookup. A full scan of a table with N entries should have
  5186. ** a cost of N. A binary search of a table of N entries should have a
  5187. ** cost of approximately log(N).
  5188. */
  5189. struct sqlite3_index_info {
  5190. /* Inputs */
  5191. int nConstraint; /* Number of entries in aConstraint */
  5192. struct sqlite3_index_constraint {
  5193. int iColumn; /* Column on left-hand side of constraint */
  5194. unsigned char op; /* Constraint operator */
  5195. unsigned char usable; /* True if this constraint is usable */
  5196. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5197. } *aConstraint; /* Table of WHERE clause constraints */
  5198. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5199. struct sqlite3_index_orderby {
  5200. int iColumn; /* Column number */
  5201. unsigned char desc; /* True for DESC. False for ASC. */
  5202. } *aOrderBy; /* The ORDER BY clause */
  5203. /* Outputs */
  5204. struct sqlite3_index_constraint_usage {
  5205. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5206. unsigned char omit; /* Do not code a test for this constraint */
  5207. } *aConstraintUsage;
  5208. int idxNum; /* Number used to identify the index */
  5209. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5210. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5211. int orderByConsumed; /* True if output is already ordered */
  5212. double estimatedCost; /* Estimated cost of using this index */
  5213. };
  5214. /*
  5215. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5216. **
  5217. ** These macros defined the allowed values for the
  5218. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5219. ** an operator that is part of a constraint term in the wHERE clause of
  5220. ** a query that uses a [virtual table].
  5221. */
  5222. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5223. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5224. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5225. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5226. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5227. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5228. /*
  5229. ** CAPI3REF: Register A Virtual Table Implementation
  5230. **
  5231. ** ^These routines are used to register a new [virtual table module] name.
  5232. ** ^Module names must be registered before
  5233. ** creating a new [virtual table] using the module and before using a
  5234. ** preexisting [virtual table] for the module.
  5235. **
  5236. ** ^The module name is registered on the [database connection] specified
  5237. ** by the first parameter. ^The name of the module is given by the
  5238. ** second parameter. ^The third parameter is a pointer to
  5239. ** the implementation of the [virtual table module]. ^The fourth
  5240. ** parameter is an arbitrary client data pointer that is passed through
  5241. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5242. ** when a new virtual table is be being created or reinitialized.
  5243. **
  5244. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5245. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5246. ** invoke the destructor function (if it is not NULL) when SQLite
  5247. ** no longer needs the pClientData pointer. ^The destructor will also
  5248. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5249. ** ^The sqlite3_create_module()
  5250. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5251. ** destructor.
  5252. */
  5253. SQLITE_API int sqlite3_create_module(
  5254. sqlite3 *db, /* SQLite connection to register module with */
  5255. const char *zName, /* Name of the module */
  5256. const sqlite3_module *p, /* Methods for the module */
  5257. void *pClientData /* Client data for xCreate/xConnect */
  5258. );
  5259. SQLITE_API int sqlite3_create_module_v2(
  5260. sqlite3 *db, /* SQLite connection to register module with */
  5261. const char *zName, /* Name of the module */
  5262. const sqlite3_module *p, /* Methods for the module */
  5263. void *pClientData, /* Client data for xCreate/xConnect */
  5264. void(*xDestroy)(void*) /* Module destructor function */
  5265. );
  5266. /*
  5267. ** CAPI3REF: Virtual Table Instance Object
  5268. ** KEYWORDS: sqlite3_vtab
  5269. **
  5270. ** Every [virtual table module] implementation uses a subclass
  5271. ** of this object to describe a particular instance
  5272. ** of the [virtual table]. Each subclass will
  5273. ** be tailored to the specific needs of the module implementation.
  5274. ** The purpose of this superclass is to define certain fields that are
  5275. ** common to all module implementations.
  5276. **
  5277. ** ^Virtual tables methods can set an error message by assigning a
  5278. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5279. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5280. ** prior to assigning a new string to zErrMsg. ^After the error message
  5281. ** is delivered up to the client application, the string will be automatically
  5282. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5283. */
  5284. struct sqlite3_vtab {
  5285. const sqlite3_module *pModule; /* The module for this virtual table */
  5286. int nRef; /* NO LONGER USED */
  5287. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5288. /* Virtual table implementations will typically add additional fields */
  5289. };
  5290. /*
  5291. ** CAPI3REF: Virtual Table Cursor Object
  5292. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5293. **
  5294. ** Every [virtual table module] implementation uses a subclass of the
  5295. ** following structure to describe cursors that point into the
  5296. ** [virtual table] and are used
  5297. ** to loop through the virtual table. Cursors are created using the
  5298. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5299. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5300. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5301. ** of the module. Each module implementation will define
  5302. ** the content of a cursor structure to suit its own needs.
  5303. **
  5304. ** This superclass exists in order to define fields of the cursor that
  5305. ** are common to all implementations.
  5306. */
  5307. struct sqlite3_vtab_cursor {
  5308. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5309. /* Virtual table implementations will typically add additional fields */
  5310. };
  5311. /*
  5312. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5313. **
  5314. ** ^The [xCreate] and [xConnect] methods of a
  5315. ** [virtual table module] call this interface
  5316. ** to declare the format (the names and datatypes of the columns) of
  5317. ** the virtual tables they implement.
  5318. */
  5319. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5320. /*
  5321. ** CAPI3REF: Overload A Function For A Virtual Table
  5322. **
  5323. ** ^(Virtual tables can provide alternative implementations of functions
  5324. ** using the [xFindFunction] method of the [virtual table module].
  5325. ** But global versions of those functions
  5326. ** must exist in order to be overloaded.)^
  5327. **
  5328. ** ^(This API makes sure a global version of a function with a particular
  5329. ** name and number of parameters exists. If no such function exists
  5330. ** before this API is called, a new function is created.)^ ^The implementation
  5331. ** of the new function always causes an exception to be thrown. So
  5332. ** the new function is not good for anything by itself. Its only
  5333. ** purpose is to be a placeholder function that can be overloaded
  5334. ** by a [virtual table].
  5335. */
  5336. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5337. /*
  5338. ** The interface to the virtual-table mechanism defined above (back up
  5339. ** to a comment remarkably similar to this one) is currently considered
  5340. ** to be experimental. The interface might change in incompatible ways.
  5341. ** If this is a problem for you, do not use the interface at this time.
  5342. **
  5343. ** When the virtual-table mechanism stabilizes, we will declare the
  5344. ** interface fixed, support it indefinitely, and remove this comment.
  5345. */
  5346. /*
  5347. ** CAPI3REF: A Handle To An Open BLOB
  5348. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5349. **
  5350. ** An instance of this object represents an open BLOB on which
  5351. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5352. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5353. ** and destroyed by [sqlite3_blob_close()].
  5354. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5355. ** can be used to read or write small subsections of the BLOB.
  5356. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5357. */
  5358. typedef struct sqlite3_blob sqlite3_blob;
  5359. /*
  5360. ** CAPI3REF: Open A BLOB For Incremental I/O
  5361. **
  5362. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5363. ** in row iRow, column zColumn, table zTable in database zDb;
  5364. ** in other words, the same BLOB that would be selected by:
  5365. **
  5366. ** <pre>
  5367. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5368. ** </pre>)^
  5369. **
  5370. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5371. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5372. ** ^It is not possible to open a column that is part of an index or primary
  5373. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5374. ** not possible to open a column that is part of a [child key] for writing.
  5375. **
  5376. ** ^Note that the database name is not the filename that contains
  5377. ** the database but rather the symbolic name of the database that
  5378. ** appears after the AS keyword when the database is connected using [ATTACH].
  5379. ** ^For the main database file, the database name is "main".
  5380. ** ^For TEMP tables, the database name is "temp".
  5381. **
  5382. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5383. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5384. ** to be a null pointer.)^
  5385. ** ^This function sets the [database connection] error code and message
  5386. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5387. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5388. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5389. ** regardless of the success or failure of this routine.
  5390. **
  5391. ** ^(If the row that a BLOB handle points to is modified by an
  5392. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5393. ** then the BLOB handle is marked as "expired".
  5394. ** This is true if any column of the row is changed, even a column
  5395. ** other than the one the BLOB handle is open on.)^
  5396. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5397. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5398. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5399. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5400. ** commit if the transaction continues to completion.)^
  5401. **
  5402. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5403. ** the opened blob. ^The size of a blob may not be changed by this
  5404. ** interface. Use the [UPDATE] SQL command to change the size of a
  5405. ** blob.
  5406. **
  5407. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5408. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5409. ** to create an empty, zero-filled blob in which to read or write using
  5410. ** this interface.
  5411. **
  5412. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5413. ** be released by a call to [sqlite3_blob_close()].
  5414. */
  5415. SQLITE_API int sqlite3_blob_open(
  5416. sqlite3*,
  5417. const char *zDb,
  5418. const char *zTable,
  5419. const char *zColumn,
  5420. sqlite3_int64 iRow,
  5421. int flags,
  5422. sqlite3_blob **ppBlob
  5423. );
  5424. /*
  5425. ** CAPI3REF: Move a BLOB Handle to a New Row
  5426. **
  5427. ** ^This function is used to move an existing blob handle so that it points
  5428. ** to a different row of the same database table. ^The new row is identified
  5429. ** by the rowid value passed as the second argument. Only the row can be
  5430. ** changed. ^The database, table and column on which the blob handle is open
  5431. ** remain the same. Moving an existing blob handle to a new row can be
  5432. ** faster than closing the existing handle and opening a new one.
  5433. **
  5434. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5435. ** it must exist and there must be either a blob or text value stored in
  5436. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5437. ** it does not contain a blob or text value, or if another error occurs, an
  5438. ** SQLite error code is returned and the blob handle is considered aborted.
  5439. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5440. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5441. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5442. ** always returns zero.
  5443. **
  5444. ** ^This function sets the database handle error code and message.
  5445. */
  5446. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5447. /*
  5448. ** CAPI3REF: Close A BLOB Handle
  5449. **
  5450. ** ^Closes an open [BLOB handle].
  5451. **
  5452. ** ^Closing a BLOB shall cause the current transaction to commit
  5453. ** if there are no other BLOBs, no pending prepared statements, and the
  5454. ** database connection is in [autocommit mode].
  5455. ** ^If any writes were made to the BLOB, they might be held in cache
  5456. ** until the close operation if they will fit.
  5457. **
  5458. ** ^(Closing the BLOB often forces the changes
  5459. ** out to disk and so if any I/O errors occur, they will likely occur
  5460. ** at the time when the BLOB is closed. Any errors that occur during
  5461. ** closing are reported as a non-zero return value.)^
  5462. **
  5463. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5464. ** an error code, the BLOB is still closed.)^
  5465. **
  5466. ** ^Calling this routine with a null pointer (such as would be returned
  5467. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5468. */
  5469. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5470. /*
  5471. ** CAPI3REF: Return The Size Of An Open BLOB
  5472. **
  5473. ** ^Returns the size in bytes of the BLOB accessible via the
  5474. ** successfully opened [BLOB handle] in its only argument. ^The
  5475. ** incremental blob I/O routines can only read or overwriting existing
  5476. ** blob content; they cannot change the size of a blob.
  5477. **
  5478. ** This routine only works on a [BLOB handle] which has been created
  5479. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5480. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5481. ** to this routine results in undefined and probably undesirable behavior.
  5482. */
  5483. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5484. /*
  5485. ** CAPI3REF: Read Data From A BLOB Incrementally
  5486. **
  5487. ** ^(This function is used to read data from an open [BLOB handle] into a
  5488. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5489. ** from the open BLOB, starting at offset iOffset.)^
  5490. **
  5491. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5492. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5493. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5494. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5495. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5496. **
  5497. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5498. ** error code of [SQLITE_ABORT].
  5499. **
  5500. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5501. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5502. **
  5503. ** This routine only works on a [BLOB handle] which has been created
  5504. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5505. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5506. ** to this routine results in undefined and probably undesirable behavior.
  5507. **
  5508. ** See also: [sqlite3_blob_write()].
  5509. */
  5510. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5511. /*
  5512. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5513. **
  5514. ** ^This function is used to write data into an open [BLOB handle] from a
  5515. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5516. ** into the open BLOB, starting at offset iOffset.
  5517. **
  5518. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5519. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5520. ** this function returns [SQLITE_READONLY].
  5521. **
  5522. ** ^This function may only modify the contents of the BLOB; it is
  5523. ** not possible to increase the size of a BLOB using this API.
  5524. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5525. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5526. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5527. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5528. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5529. **
  5530. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5531. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5532. ** before the [BLOB handle] expired are not rolled back by the
  5533. ** expiration of the handle, though of course those changes might
  5534. ** have been overwritten by the statement that expired the BLOB handle
  5535. ** or by other independent statements.
  5536. **
  5537. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5538. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5539. **
  5540. ** This routine only works on a [BLOB handle] which has been created
  5541. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5542. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5543. ** to this routine results in undefined and probably undesirable behavior.
  5544. **
  5545. ** See also: [sqlite3_blob_read()].
  5546. */
  5547. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5548. /*
  5549. ** CAPI3REF: Virtual File System Objects
  5550. **
  5551. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5552. ** that SQLite uses to interact
  5553. ** with the underlying operating system. Most SQLite builds come with a
  5554. ** single default VFS that is appropriate for the host computer.
  5555. ** New VFSes can be registered and existing VFSes can be unregistered.
  5556. ** The following interfaces are provided.
  5557. **
  5558. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5559. ** ^Names are case sensitive.
  5560. ** ^Names are zero-terminated UTF-8 strings.
  5561. ** ^If there is no match, a NULL pointer is returned.
  5562. ** ^If zVfsName is NULL then the default VFS is returned.
  5563. **
  5564. ** ^New VFSes are registered with sqlite3_vfs_register().
  5565. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5566. ** ^The same VFS can be registered multiple times without injury.
  5567. ** ^To make an existing VFS into the default VFS, register it again
  5568. ** with the makeDflt flag set. If two different VFSes with the
  5569. ** same name are registered, the behavior is undefined. If a
  5570. ** VFS is registered with a name that is NULL or an empty string,
  5571. ** then the behavior is undefined.
  5572. **
  5573. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5574. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5575. ** the default. The choice for the new VFS is arbitrary.)^
  5576. */
  5577. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5578. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5579. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5580. /*
  5581. ** CAPI3REF: Mutexes
  5582. **
  5583. ** The SQLite core uses these routines for thread
  5584. ** synchronization. Though they are intended for internal
  5585. ** use by SQLite, code that links against SQLite is
  5586. ** permitted to use any of these routines.
  5587. **
  5588. ** The SQLite source code contains multiple implementations
  5589. ** of these mutex routines. An appropriate implementation
  5590. ** is selected automatically at compile-time. ^(The following
  5591. ** implementations are available in the SQLite core:
  5592. **
  5593. ** <ul>
  5594. ** <li> SQLITE_MUTEX_PTHREADS
  5595. ** <li> SQLITE_MUTEX_W32
  5596. ** <li> SQLITE_MUTEX_NOOP
  5597. ** </ul>)^
  5598. **
  5599. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5600. ** that does no real locking and is appropriate for use in
  5601. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5602. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5603. ** and Windows.
  5604. **
  5605. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5606. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5607. ** implementation is included with the library. In this case the
  5608. ** application must supply a custom mutex implementation using the
  5609. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5610. ** before calling sqlite3_initialize() or any other public sqlite3_
  5611. ** function that calls sqlite3_initialize().)^
  5612. **
  5613. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5614. ** mutex and returns a pointer to it. ^If it returns NULL
  5615. ** that means that a mutex could not be allocated. ^SQLite
  5616. ** will unwind its stack and return an error. ^(The argument
  5617. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5618. **
  5619. ** <ul>
  5620. ** <li> SQLITE_MUTEX_FAST
  5621. ** <li> SQLITE_MUTEX_RECURSIVE
  5622. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5623. ** <li> SQLITE_MUTEX_STATIC_MEM
  5624. ** <li> SQLITE_MUTEX_STATIC_MEM2
  5625. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5626. ** <li> SQLITE_MUTEX_STATIC_LRU
  5627. ** <li> SQLITE_MUTEX_STATIC_LRU2
  5628. ** </ul>)^
  5629. **
  5630. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5631. ** cause sqlite3_mutex_alloc() to create
  5632. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5633. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5634. ** The mutex implementation does not need to make a distinction
  5635. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5636. ** not want to. ^SQLite will only request a recursive mutex in
  5637. ** cases where it really needs one. ^If a faster non-recursive mutex
  5638. ** implementation is available on the host platform, the mutex subsystem
  5639. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5640. **
  5641. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5642. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5643. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5644. ** used by the current version of SQLite. Future versions of SQLite
  5645. ** may add additional static mutexes. Static mutexes are for internal
  5646. ** use by SQLite only. Applications that use SQLite mutexes should
  5647. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5648. ** SQLITE_MUTEX_RECURSIVE.
  5649. **
  5650. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5651. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5652. ** returns a different mutex on every call. ^But for the static
  5653. ** mutex types, the same mutex is returned on every call that has
  5654. ** the same type number.
  5655. **
  5656. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5657. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5658. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5659. ** use when they are deallocated. Attempting to deallocate a static
  5660. ** mutex results in undefined behavior. ^SQLite never deallocates
  5661. ** a static mutex.
  5662. **
  5663. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5664. ** to enter a mutex. ^If another thread is already within the mutex,
  5665. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5666. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5667. ** upon successful entry. ^(Mutexes created using
  5668. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5669. ** In such cases the,
  5670. ** mutex must be exited an equal number of times before another thread
  5671. ** can enter.)^ ^(If the same thread tries to enter any other
  5672. ** kind of mutex more than once, the behavior is undefined.
  5673. ** SQLite will never exhibit
  5674. ** such behavior in its own use of mutexes.)^
  5675. **
  5676. ** ^(Some systems (for example, Windows 95) do not support the operation
  5677. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5678. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5679. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5680. **
  5681. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5682. ** previously entered by the same thread. ^(The behavior
  5683. ** is undefined if the mutex is not currently entered by the
  5684. ** calling thread or is not currently allocated. SQLite will
  5685. ** never do either.)^
  5686. **
  5687. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5688. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5689. ** behave as no-ops.
  5690. **
  5691. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5692. */
  5693. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5694. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5695. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5696. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5697. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5698. /*
  5699. ** CAPI3REF: Mutex Methods Object
  5700. **
  5701. ** An instance of this structure defines the low-level routines
  5702. ** used to allocate and use mutexes.
  5703. **
  5704. ** Usually, the default mutex implementations provided by SQLite are
  5705. ** sufficient, however the user has the option of substituting a custom
  5706. ** implementation for specialized deployments or systems for which SQLite
  5707. ** does not provide a suitable implementation. In this case, the user
  5708. ** creates and populates an instance of this structure to pass
  5709. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5710. ** Additionally, an instance of this structure can be used as an
  5711. ** output variable when querying the system for the current mutex
  5712. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5713. **
  5714. ** ^The xMutexInit method defined by this structure is invoked as
  5715. ** part of system initialization by the sqlite3_initialize() function.
  5716. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5717. ** effective call to [sqlite3_initialize()].
  5718. **
  5719. ** ^The xMutexEnd method defined by this structure is invoked as
  5720. ** part of system shutdown by the sqlite3_shutdown() function. The
  5721. ** implementation of this method is expected to release all outstanding
  5722. ** resources obtained by the mutex methods implementation, especially
  5723. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5724. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5725. **
  5726. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5727. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5728. ** xMutexNotheld) implement the following interfaces (respectively):
  5729. **
  5730. ** <ul>
  5731. ** <li> [sqlite3_mutex_alloc()] </li>
  5732. ** <li> [sqlite3_mutex_free()] </li>
  5733. ** <li> [sqlite3_mutex_enter()] </li>
  5734. ** <li> [sqlite3_mutex_try()] </li>
  5735. ** <li> [sqlite3_mutex_leave()] </li>
  5736. ** <li> [sqlite3_mutex_held()] </li>
  5737. ** <li> [sqlite3_mutex_notheld()] </li>
  5738. ** </ul>)^
  5739. **
  5740. ** The only difference is that the public sqlite3_XXX functions enumerated
  5741. ** above silently ignore any invocations that pass a NULL pointer instead
  5742. ** of a valid mutex handle. The implementations of the methods defined
  5743. ** by this structure are not required to handle this case, the results
  5744. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  5745. ** (i.e. it is acceptable to provide an implementation that segfaults if
  5746. ** it is passed a NULL pointer).
  5747. **
  5748. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  5749. ** invoke xMutexInit() multiple times within the same process and without
  5750. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  5751. ** xMutexInit() must be no-ops.
  5752. **
  5753. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  5754. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  5755. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  5756. ** memory allocation for a fast or recursive mutex.
  5757. **
  5758. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  5759. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  5760. ** If xMutexInit fails in any way, it is expected to clean up after itself
  5761. ** prior to returning.
  5762. */
  5763. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  5764. struct sqlite3_mutex_methods {
  5765. int (*xMutexInit)(void);
  5766. int (*xMutexEnd)(void);
  5767. sqlite3_mutex *(*xMutexAlloc)(int);
  5768. void (*xMutexFree)(sqlite3_mutex *);
  5769. void (*xMutexEnter)(sqlite3_mutex *);
  5770. int (*xMutexTry)(sqlite3_mutex *);
  5771. void (*xMutexLeave)(sqlite3_mutex *);
  5772. int (*xMutexHeld)(sqlite3_mutex *);
  5773. int (*xMutexNotheld)(sqlite3_mutex *);
  5774. };
  5775. /*
  5776. ** CAPI3REF: Mutex Verification Routines
  5777. **
  5778. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  5779. ** are intended for use inside assert() statements. ^The SQLite core
  5780. ** never uses these routines except inside an assert() and applications
  5781. ** are advised to follow the lead of the core. ^The SQLite core only
  5782. ** provides implementations for these routines when it is compiled
  5783. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  5784. ** are only required to provide these routines if SQLITE_DEBUG is
  5785. ** defined and if NDEBUG is not defined.
  5786. **
  5787. ** ^These routines should return true if the mutex in their argument
  5788. ** is held or not held, respectively, by the calling thread.
  5789. **
  5790. ** ^The implementation is not required to provide versions of these
  5791. ** routines that actually work. If the implementation does not provide working
  5792. ** versions of these routines, it should at least provide stubs that always
  5793. ** return true so that one does not get spurious assertion failures.
  5794. **
  5795. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  5796. ** the routine should return 1. This seems counter-intuitive since
  5797. ** clearly the mutex cannot be held if it does not exist. But
  5798. ** the reason the mutex does not exist is because the build is not
  5799. ** using mutexes. And we do not want the assert() containing the
  5800. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  5801. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  5802. ** interface should also return 1 when given a NULL pointer.
  5803. */
  5804. #ifndef NDEBUG
  5805. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  5806. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  5807. #endif
  5808. /*
  5809. ** CAPI3REF: Mutex Types
  5810. **
  5811. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  5812. ** which is one of these integer constants.
  5813. **
  5814. ** The set of static mutexes may change from one SQLite release to the
  5815. ** next. Applications that override the built-in mutex logic must be
  5816. ** prepared to accommodate additional static mutexes.
  5817. */
  5818. #define SQLITE_MUTEX_FAST 0
  5819. #define SQLITE_MUTEX_RECURSIVE 1
  5820. #define SQLITE_MUTEX_STATIC_MASTER 2
  5821. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  5822. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  5823. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  5824. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  5825. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  5826. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  5827. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  5828. /*
  5829. ** CAPI3REF: Retrieve the mutex for a database connection
  5830. **
  5831. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  5832. ** serializes access to the [database connection] given in the argument
  5833. ** when the [threading mode] is Serialized.
  5834. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  5835. ** routine returns a NULL pointer.
  5836. */
  5837. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  5838. /*
  5839. ** CAPI3REF: Low-Level Control Of Database Files
  5840. **
  5841. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  5842. ** xFileControl method for the [sqlite3_io_methods] object associated
  5843. ** with a particular database identified by the second argument. ^The
  5844. ** name of the database is "main" for the main database or "temp" for the
  5845. ** TEMP database, or the name that appears after the AS keyword for
  5846. ** databases that are added using the [ATTACH] SQL command.
  5847. ** ^A NULL pointer can be used in place of "main" to refer to the
  5848. ** main database file.
  5849. ** ^The third and fourth parameters to this routine
  5850. ** are passed directly through to the second and third parameters of
  5851. ** the xFileControl method. ^The return value of the xFileControl
  5852. ** method becomes the return value of this routine.
  5853. **
  5854. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  5855. ** a pointer to the underlying [sqlite3_file] object to be written into
  5856. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  5857. ** case is a short-circuit path which does not actually invoke the
  5858. ** underlying sqlite3_io_methods.xFileControl method.
  5859. **
  5860. ** ^If the second parameter (zDbName) does not match the name of any
  5861. ** open database file, then SQLITE_ERROR is returned. ^This error
  5862. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  5863. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  5864. ** also return SQLITE_ERROR. There is no way to distinguish between
  5865. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  5866. ** xFileControl method.
  5867. **
  5868. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  5869. */
  5870. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  5871. /*
  5872. ** CAPI3REF: Testing Interface
  5873. **
  5874. ** ^The sqlite3_test_control() interface is used to read out internal
  5875. ** state of SQLite and to inject faults into SQLite for testing
  5876. ** purposes. ^The first parameter is an operation code that determines
  5877. ** the number, meaning, and operation of all subsequent parameters.
  5878. **
  5879. ** This interface is not for use by applications. It exists solely
  5880. ** for verifying the correct operation of the SQLite library. Depending
  5881. ** on how the SQLite library is compiled, this interface might not exist.
  5882. **
  5883. ** The details of the operation codes, their meanings, the parameters
  5884. ** they take, and what they do are all subject to change without notice.
  5885. ** Unlike most of the SQLite API, this function is not guaranteed to
  5886. ** operate consistently from one release to the next.
  5887. */
  5888. SQLITE_API int sqlite3_test_control(int op, ...);
  5889. /*
  5890. ** CAPI3REF: Testing Interface Operation Codes
  5891. **
  5892. ** These constants are the valid operation code parameters used
  5893. ** as the first argument to [sqlite3_test_control()].
  5894. **
  5895. ** These parameters and their meanings are subject to change
  5896. ** without notice. These values are for testing purposes only.
  5897. ** Applications should not use any of these parameters or the
  5898. ** [sqlite3_test_control()] interface.
  5899. */
  5900. #define SQLITE_TESTCTRL_FIRST 5
  5901. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  5902. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  5903. #define SQLITE_TESTCTRL_PRNG_RESET 7
  5904. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  5905. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  5906. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  5907. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  5908. #define SQLITE_TESTCTRL_ASSERT 12
  5909. #define SQLITE_TESTCTRL_ALWAYS 13
  5910. #define SQLITE_TESTCTRL_RESERVE 14
  5911. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  5912. #define SQLITE_TESTCTRL_ISKEYWORD 16
  5913. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  5914. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  5915. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19
  5916. #define SQLITE_TESTCTRL_LAST 19
  5917. /*
  5918. ** CAPI3REF: SQLite Runtime Status
  5919. **
  5920. ** ^This interface is used to retrieve runtime status information
  5921. ** about the performance of SQLite, and optionally to reset various
  5922. ** highwater marks. ^The first argument is an integer code for
  5923. ** the specific parameter to measure. ^(Recognized integer codes
  5924. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  5925. ** ^The current value of the parameter is returned into *pCurrent.
  5926. ** ^The highest recorded value is returned in *pHighwater. ^If the
  5927. ** resetFlag is true, then the highest record value is reset after
  5928. ** *pHighwater is written. ^(Some parameters do not record the highest
  5929. ** value. For those parameters
  5930. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  5931. ** ^(Other parameters record only the highwater mark and not the current
  5932. ** value. For these latter parameters nothing is written into *pCurrent.)^
  5933. **
  5934. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  5935. ** non-zero [error code] on failure.
  5936. **
  5937. ** This routine is threadsafe but is not atomic. This routine can be
  5938. ** called while other threads are running the same or different SQLite
  5939. ** interfaces. However the values returned in *pCurrent and
  5940. ** *pHighwater reflect the status of SQLite at different points in time
  5941. ** and it is possible that another thread might change the parameter
  5942. ** in between the times when *pCurrent and *pHighwater are written.
  5943. **
  5944. ** See also: [sqlite3_db_status()]
  5945. */
  5946. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  5947. /*
  5948. ** CAPI3REF: Status Parameters
  5949. ** KEYWORDS: {status parameters}
  5950. **
  5951. ** These integer constants designate various run-time status parameters
  5952. ** that can be returned by [sqlite3_status()].
  5953. **
  5954. ** <dl>
  5955. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  5956. ** <dd>This parameter is the current amount of memory checked out
  5957. ** using [sqlite3_malloc()], either directly or indirectly. The
  5958. ** figure includes calls made to [sqlite3_malloc()] by the application
  5959. ** and internal memory usage by the SQLite library. Scratch memory
  5960. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  5961. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  5962. ** this parameter. The amount returned is the sum of the allocation
  5963. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  5964. **
  5965. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  5966. ** <dd>This parameter records the largest memory allocation request
  5967. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  5968. ** internal equivalents). Only the value returned in the
  5969. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5970. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5971. **
  5972. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  5973. ** <dd>This parameter records the number of separate memory allocations
  5974. ** currently checked out.</dd>)^
  5975. **
  5976. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  5977. ** <dd>This parameter returns the number of pages used out of the
  5978. ** [pagecache memory allocator] that was configured using
  5979. ** [SQLITE_CONFIG_PAGECACHE]. The
  5980. ** value returned is in pages, not in bytes.</dd>)^
  5981. **
  5982. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  5983. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  5984. ** <dd>This parameter returns the number of bytes of page cache
  5985. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  5986. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  5987. ** returned value includes allocations that overflowed because they
  5988. ** where too large (they were larger than the "sz" parameter to
  5989. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  5990. ** no space was left in the page cache.</dd>)^
  5991. **
  5992. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  5993. ** <dd>This parameter records the largest memory allocation request
  5994. ** handed to [pagecache memory allocator]. Only the value returned in the
  5995. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  5996. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  5997. **
  5998. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  5999. ** <dd>This parameter returns the number of allocations used out of the
  6000. ** [scratch memory allocator] configured using
  6001. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6002. ** in bytes. Since a single thread may only have one scratch allocation
  6003. ** outstanding at time, this parameter also reports the number of threads
  6004. ** using scratch memory at the same time.</dd>)^
  6005. **
  6006. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6007. ** <dd>This parameter returns the number of bytes of scratch memory
  6008. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6009. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6010. ** returned include overflows because the requested allocation was too
  6011. ** larger (that is, because the requested allocation was larger than the
  6012. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6013. ** slots were available.
  6014. ** </dd>)^
  6015. **
  6016. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6017. ** <dd>This parameter records the largest memory allocation request
  6018. ** handed to [scratch memory allocator]. Only the value returned in the
  6019. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6020. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6021. **
  6022. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6023. ** <dd>This parameter records the deepest parser stack. It is only
  6024. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6025. ** </dl>
  6026. **
  6027. ** New status parameters may be added from time to time.
  6028. */
  6029. #define SQLITE_STATUS_MEMORY_USED 0
  6030. #define SQLITE_STATUS_PAGECACHE_USED 1
  6031. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6032. #define SQLITE_STATUS_SCRATCH_USED 3
  6033. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6034. #define SQLITE_STATUS_MALLOC_SIZE 5
  6035. #define SQLITE_STATUS_PARSER_STACK 6
  6036. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6037. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6038. #define SQLITE_STATUS_MALLOC_COUNT 9
  6039. /*
  6040. ** CAPI3REF: Database Connection Status
  6041. **
  6042. ** ^This interface is used to retrieve runtime status information
  6043. ** about a single [database connection]. ^The first argument is the
  6044. ** database connection object to be interrogated. ^The second argument
  6045. ** is an integer constant, taken from the set of
  6046. ** [SQLITE_DBSTATUS options], that
  6047. ** determines the parameter to interrogate. The set of
  6048. ** [SQLITE_DBSTATUS options] is likely
  6049. ** to grow in future releases of SQLite.
  6050. **
  6051. ** ^The current value of the requested parameter is written into *pCur
  6052. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6053. ** the resetFlg is true, then the highest instantaneous value is
  6054. ** reset back down to the current value.
  6055. **
  6056. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6057. ** non-zero [error code] on failure.
  6058. **
  6059. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6060. */
  6061. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6062. /*
  6063. ** CAPI3REF: Status Parameters for database connections
  6064. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6065. **
  6066. ** These constants are the available integer "verbs" that can be passed as
  6067. ** the second argument to the [sqlite3_db_status()] interface.
  6068. **
  6069. ** New verbs may be added in future releases of SQLite. Existing verbs
  6070. ** might be discontinued. Applications should check the return code from
  6071. ** [sqlite3_db_status()] to make sure that the call worked.
  6072. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6073. ** if a discontinued or unsupported verb is invoked.
  6074. **
  6075. ** <dl>
  6076. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6077. ** <dd>This parameter returns the number of lookaside memory slots currently
  6078. ** checked out.</dd>)^
  6079. **
  6080. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6081. ** <dd>This parameter returns the number malloc attempts that were
  6082. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6083. ** the current value is always zero.)^
  6084. **
  6085. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6086. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6087. ** <dd>This parameter returns the number malloc attempts that might have
  6088. ** been satisfied using lookaside memory but failed due to the amount of
  6089. ** memory requested being larger than the lookaside slot size.
  6090. ** Only the high-water value is meaningful;
  6091. ** the current value is always zero.)^
  6092. **
  6093. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6094. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6095. ** <dd>This parameter returns the number malloc attempts that might have
  6096. ** been satisfied using lookaside memory but failed due to all lookaside
  6097. ** memory already being in use.
  6098. ** Only the high-water value is meaningful;
  6099. ** the current value is always zero.)^
  6100. **
  6101. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6102. ** <dd>This parameter returns the approximate number of of bytes of heap
  6103. ** memory used by all pager caches associated with the database connection.)^
  6104. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6105. **
  6106. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6107. ** <dd>This parameter returns the approximate number of of bytes of heap
  6108. ** memory used to store the schema for all databases associated
  6109. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6110. ** ^The full amount of memory used by the schemas is reported, even if the
  6111. ** schema memory is shared with other database connections due to
  6112. ** [shared cache mode] being enabled.
  6113. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6114. **
  6115. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6116. ** <dd>This parameter returns the approximate number of of bytes of heap
  6117. ** and lookaside memory used by all prepared statements associated with
  6118. ** the database connection.)^
  6119. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6120. ** </dd>
  6121. **
  6122. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6123. ** <dd>This parameter returns the number of pager cache hits that have
  6124. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6125. ** is always 0.
  6126. ** </dd>
  6127. **
  6128. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6129. ** <dd>This parameter returns the number of pager cache misses that have
  6130. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6131. ** is always 0.
  6132. ** </dd>
  6133. **
  6134. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6135. ** <dd>This parameter returns the number of dirty cache entries that have
  6136. ** been written to disk. Specifically, the number of pages written to the
  6137. ** wal file in wal mode databases, or the number of pages written to the
  6138. ** database file in rollback mode databases. Any pages written as part of
  6139. ** transaction rollback or database recovery operations are not included.
  6140. ** If an IO or other error occurs while writing a page to disk, the effect
  6141. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6142. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6143. ** </dd>
  6144. **
  6145. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6146. ** <dd>This parameter returns zero for the current value if and only if
  6147. ** all foreign key constraints (deferred or immediate) have been
  6148. ** resolved.)^ ^The highwater mark is always 0.
  6149. ** </dd>
  6150. ** </dl>
  6151. */
  6152. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6153. #define SQLITE_DBSTATUS_CACHE_USED 1
  6154. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6155. #define SQLITE_DBSTATUS_STMT_USED 3
  6156. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6157. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6158. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6159. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6160. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6161. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6162. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6163. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6164. /*
  6165. ** CAPI3REF: Prepared Statement Status
  6166. **
  6167. ** ^(Each prepared statement maintains various
  6168. ** [SQLITE_STMTSTATUS counters] that measure the number
  6169. ** of times it has performed specific operations.)^ These counters can
  6170. ** be used to monitor the performance characteristics of the prepared
  6171. ** statements. For example, if the number of table steps greatly exceeds
  6172. ** the number of table searches or result rows, that would tend to indicate
  6173. ** that the prepared statement is using a full table scan rather than
  6174. ** an index.
  6175. **
  6176. ** ^(This interface is used to retrieve and reset counter values from
  6177. ** a [prepared statement]. The first argument is the prepared statement
  6178. ** object to be interrogated. The second argument
  6179. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6180. ** to be interrogated.)^
  6181. ** ^The current value of the requested counter is returned.
  6182. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6183. ** interface call returns.
  6184. **
  6185. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6186. */
  6187. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6188. /*
  6189. ** CAPI3REF: Status Parameters for prepared statements
  6190. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6191. **
  6192. ** These preprocessor macros define integer codes that name counter
  6193. ** values associated with the [sqlite3_stmt_status()] interface.
  6194. ** The meanings of the various counters are as follows:
  6195. **
  6196. ** <dl>
  6197. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6198. ** <dd>^This is the number of times that SQLite has stepped forward in
  6199. ** a table as part of a full table scan. Large numbers for this counter
  6200. ** may indicate opportunities for performance improvement through
  6201. ** careful use of indices.</dd>
  6202. **
  6203. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6204. ** <dd>^This is the number of sort operations that have occurred.
  6205. ** A non-zero value in this counter may indicate an opportunity to
  6206. ** improvement performance through careful use of indices.</dd>
  6207. **
  6208. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6209. ** <dd>^This is the number of rows inserted into transient indices that
  6210. ** were created automatically in order to help joins run faster.
  6211. ** A non-zero value in this counter may indicate an opportunity to
  6212. ** improvement performance by adding permanent indices that do not
  6213. ** need to be reinitialized each time the statement is run.</dd>
  6214. **
  6215. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6216. ** <dd>^This is the number of virtual machine operations executed
  6217. ** by the prepared statement if that number is less than or equal
  6218. ** to 2147483647. The number of virtual machine operations can be
  6219. ** used as a proxy for the total work done by the prepared statement.
  6220. ** If the number of virtual machine operations exceeds 2147483647
  6221. ** then the value returned by this statement status code is undefined.
  6222. ** </dd>
  6223. ** </dl>
  6224. */
  6225. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6226. #define SQLITE_STMTSTATUS_SORT 2
  6227. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6228. #define SQLITE_STMTSTATUS_VM_STEP 4
  6229. /*
  6230. ** CAPI3REF: Custom Page Cache Object
  6231. **
  6232. ** The sqlite3_pcache type is opaque. It is implemented by
  6233. ** the pluggable module. The SQLite core has no knowledge of
  6234. ** its size or internal structure and never deals with the
  6235. ** sqlite3_pcache object except by holding and passing pointers
  6236. ** to the object.
  6237. **
  6238. ** See [sqlite3_pcache_methods2] for additional information.
  6239. */
  6240. typedef struct sqlite3_pcache sqlite3_pcache;
  6241. /*
  6242. ** CAPI3REF: Custom Page Cache Object
  6243. **
  6244. ** The sqlite3_pcache_page object represents a single page in the
  6245. ** page cache. The page cache will allocate instances of this
  6246. ** object. Various methods of the page cache use pointers to instances
  6247. ** of this object as parameters or as their return value.
  6248. **
  6249. ** See [sqlite3_pcache_methods2] for additional information.
  6250. */
  6251. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6252. struct sqlite3_pcache_page {
  6253. void *pBuf; /* The content of the page */
  6254. void *pExtra; /* Extra information associated with the page */
  6255. };
  6256. /*
  6257. ** CAPI3REF: Application Defined Page Cache.
  6258. ** KEYWORDS: {page cache}
  6259. **
  6260. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6261. ** register an alternative page cache implementation by passing in an
  6262. ** instance of the sqlite3_pcache_methods2 structure.)^
  6263. ** In many applications, most of the heap memory allocated by
  6264. ** SQLite is used for the page cache.
  6265. ** By implementing a
  6266. ** custom page cache using this API, an application can better control
  6267. ** the amount of memory consumed by SQLite, the way in which
  6268. ** that memory is allocated and released, and the policies used to
  6269. ** determine exactly which parts of a database file are cached and for
  6270. ** how long.
  6271. **
  6272. ** The alternative page cache mechanism is an
  6273. ** extreme measure that is only needed by the most demanding applications.
  6274. ** The built-in page cache is recommended for most uses.
  6275. **
  6276. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6277. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6278. ** the application may discard the parameter after the call to
  6279. ** [sqlite3_config()] returns.)^
  6280. **
  6281. ** [[the xInit() page cache method]]
  6282. ** ^(The xInit() method is called once for each effective
  6283. ** call to [sqlite3_initialize()])^
  6284. ** (usually only once during the lifetime of the process). ^(The xInit()
  6285. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6286. ** The intent of the xInit() method is to set up global data structures
  6287. ** required by the custom page cache implementation.
  6288. ** ^(If the xInit() method is NULL, then the
  6289. ** built-in default page cache is used instead of the application defined
  6290. ** page cache.)^
  6291. **
  6292. ** [[the xShutdown() page cache method]]
  6293. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6294. ** It can be used to clean up
  6295. ** any outstanding resources before process shutdown, if required.
  6296. ** ^The xShutdown() method may be NULL.
  6297. **
  6298. ** ^SQLite automatically serializes calls to the xInit method,
  6299. ** so the xInit method need not be threadsafe. ^The
  6300. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6301. ** not need to be threadsafe either. All other methods must be threadsafe
  6302. ** in multithreaded applications.
  6303. **
  6304. ** ^SQLite will never invoke xInit() more than once without an intervening
  6305. ** call to xShutdown().
  6306. **
  6307. ** [[the xCreate() page cache methods]]
  6308. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6309. ** SQLite will typically create one cache instance for each open database file,
  6310. ** though this is not guaranteed. ^The
  6311. ** first parameter, szPage, is the size in bytes of the pages that must
  6312. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6313. ** second parameter szExtra is a number of bytes of extra storage
  6314. ** associated with each page cache entry. ^The szExtra parameter will
  6315. ** a number less than 250. SQLite will use the
  6316. ** extra szExtra bytes on each page to store metadata about the underlying
  6317. ** database page on disk. The value passed into szExtra depends
  6318. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6319. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6320. ** created will be used to cache database pages of a file stored on disk, or
  6321. ** false if it is used for an in-memory database. The cache implementation
  6322. ** does not have to do anything special based with the value of bPurgeable;
  6323. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6324. ** never invoke xUnpin() except to deliberately delete a page.
  6325. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6326. ** false will always have the "discard" flag set to true.
  6327. ** ^Hence, a cache created with bPurgeable false will
  6328. ** never contain any unpinned pages.
  6329. **
  6330. ** [[the xCachesize() page cache method]]
  6331. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6332. ** suggested maximum cache-size (number of pages stored by) the cache
  6333. ** instance passed as the first argument. This is the value configured using
  6334. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6335. ** parameter, the implementation is not required to do anything with this
  6336. ** value; it is advisory only.
  6337. **
  6338. ** [[the xPagecount() page cache methods]]
  6339. ** The xPagecount() method must return the number of pages currently
  6340. ** stored in the cache, both pinned and unpinned.
  6341. **
  6342. ** [[the xFetch() page cache methods]]
  6343. ** The xFetch() method locates a page in the cache and returns a pointer to
  6344. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6345. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6346. ** pointer to a buffer of szPage bytes used to store the content of a
  6347. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6348. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6349. ** for each entry in the page cache.
  6350. **
  6351. ** The page to be fetched is determined by the key. ^The minimum key value
  6352. ** is 1. After it has been retrieved using xFetch, the page is considered
  6353. ** to be "pinned".
  6354. **
  6355. ** If the requested page is already in the page cache, then the page cache
  6356. ** implementation must return a pointer to the page buffer with its content
  6357. ** intact. If the requested page is not already in the cache, then the
  6358. ** cache implementation should use the value of the createFlag
  6359. ** parameter to help it determined what action to take:
  6360. **
  6361. ** <table border=1 width=85% align=center>
  6362. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6363. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6364. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6365. ** Otherwise return NULL.
  6366. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6367. ** NULL if allocating a new page is effectively impossible.
  6368. ** </table>
  6369. **
  6370. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6371. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6372. ** failed.)^ In between the to xFetch() calls, SQLite may
  6373. ** attempt to unpin one or more cache pages by spilling the content of
  6374. ** pinned pages to disk and synching the operating system disk cache.
  6375. **
  6376. ** [[the xUnpin() page cache method]]
  6377. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6378. ** as its second argument. If the third parameter, discard, is non-zero,
  6379. ** then the page must be evicted from the cache.
  6380. ** ^If the discard parameter is
  6381. ** zero, then the page may be discarded or retained at the discretion of
  6382. ** page cache implementation. ^The page cache implementation
  6383. ** may choose to evict unpinned pages at any time.
  6384. **
  6385. ** The cache must not perform any reference counting. A single
  6386. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6387. ** to xFetch().
  6388. **
  6389. ** [[the xRekey() page cache methods]]
  6390. ** The xRekey() method is used to change the key value associated with the
  6391. ** page passed as the second argument. If the cache
  6392. ** previously contains an entry associated with newKey, it must be
  6393. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6394. ** to be pinned.
  6395. **
  6396. ** When SQLite calls the xTruncate() method, the cache must discard all
  6397. ** existing cache entries with page numbers (keys) greater than or equal
  6398. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6399. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6400. ** they can be safely discarded.
  6401. **
  6402. ** [[the xDestroy() page cache method]]
  6403. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6404. ** All resources associated with the specified cache should be freed. ^After
  6405. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6406. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6407. ** functions.
  6408. **
  6409. ** [[the xShrink() page cache method]]
  6410. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6411. ** free up as much of heap memory as possible. The page cache implementation
  6412. ** is not obligated to free any memory, but well-behaved implementations should
  6413. ** do their best.
  6414. */
  6415. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6416. struct sqlite3_pcache_methods2 {
  6417. int iVersion;
  6418. void *pArg;
  6419. int (*xInit)(void*);
  6420. void (*xShutdown)(void*);
  6421. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6422. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6423. int (*xPagecount)(sqlite3_pcache*);
  6424. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6425. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6426. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6427. unsigned oldKey, unsigned newKey);
  6428. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6429. void (*xDestroy)(sqlite3_pcache*);
  6430. void (*xShrink)(sqlite3_pcache*);
  6431. };
  6432. /*
  6433. ** This is the obsolete pcache_methods object that has now been replaced
  6434. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6435. ** retained in the header file for backwards compatibility only.
  6436. */
  6437. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6438. struct sqlite3_pcache_methods {
  6439. void *pArg;
  6440. int (*xInit)(void*);
  6441. void (*xShutdown)(void*);
  6442. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6443. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6444. int (*xPagecount)(sqlite3_pcache*);
  6445. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6446. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6447. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6448. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6449. void (*xDestroy)(sqlite3_pcache*);
  6450. };
  6451. /*
  6452. ** CAPI3REF: Online Backup Object
  6453. **
  6454. ** The sqlite3_backup object records state information about an ongoing
  6455. ** online backup operation. ^The sqlite3_backup object is created by
  6456. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6457. ** [sqlite3_backup_finish()].
  6458. **
  6459. ** See Also: [Using the SQLite Online Backup API]
  6460. */
  6461. typedef struct sqlite3_backup sqlite3_backup;
  6462. /*
  6463. ** CAPI3REF: Online Backup API.
  6464. **
  6465. ** The backup API copies the content of one database into another.
  6466. ** It is useful either for creating backups of databases or
  6467. ** for copying in-memory databases to or from persistent files.
  6468. **
  6469. ** See Also: [Using the SQLite Online Backup API]
  6470. **
  6471. ** ^SQLite holds a write transaction open on the destination database file
  6472. ** for the duration of the backup operation.
  6473. ** ^The source database is read-locked only while it is being read;
  6474. ** it is not locked continuously for the entire backup operation.
  6475. ** ^Thus, the backup may be performed on a live source database without
  6476. ** preventing other database connections from
  6477. ** reading or writing to the source database while the backup is underway.
  6478. **
  6479. ** ^(To perform a backup operation:
  6480. ** <ol>
  6481. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6482. ** backup,
  6483. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6484. ** the data between the two databases, and finally
  6485. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6486. ** associated with the backup operation.
  6487. ** </ol>)^
  6488. ** There should be exactly one call to sqlite3_backup_finish() for each
  6489. ** successful call to sqlite3_backup_init().
  6490. **
  6491. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6492. **
  6493. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6494. ** [database connection] associated with the destination database
  6495. ** and the database name, respectively.
  6496. ** ^The database name is "main" for the main database, "temp" for the
  6497. ** temporary database, or the name specified after the AS keyword in
  6498. ** an [ATTACH] statement for an attached database.
  6499. ** ^The S and M arguments passed to
  6500. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6501. ** and database name of the source database, respectively.
  6502. ** ^The source and destination [database connections] (parameters S and D)
  6503. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6504. ** an error.
  6505. **
  6506. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6507. ** returned and an error code and error message are stored in the
  6508. ** destination [database connection] D.
  6509. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6510. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6511. ** [sqlite3_errmsg16()] functions.
  6512. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6513. ** [sqlite3_backup] object.
  6514. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6515. ** sqlite3_backup_finish() functions to perform the specified backup
  6516. ** operation.
  6517. **
  6518. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6519. **
  6520. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6521. ** the source and destination databases specified by [sqlite3_backup] object B.
  6522. ** ^If N is negative, all remaining source pages are copied.
  6523. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6524. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6525. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6526. ** from source to destination, then it returns [SQLITE_DONE].
  6527. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6528. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6529. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6530. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6531. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6532. **
  6533. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6534. ** <ol>
  6535. ** <li> the destination database was opened read-only, or
  6536. ** <li> the destination database is using write-ahead-log journaling
  6537. ** and the destination and source page sizes differ, or
  6538. ** <li> the destination database is an in-memory database and the
  6539. ** destination and source page sizes differ.
  6540. ** </ol>)^
  6541. **
  6542. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6543. ** the [sqlite3_busy_handler | busy-handler function]
  6544. ** is invoked (if one is specified). ^If the
  6545. ** busy-handler returns non-zero before the lock is available, then
  6546. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6547. ** sqlite3_backup_step() can be retried later. ^If the source
  6548. ** [database connection]
  6549. ** is being used to write to the source database when sqlite3_backup_step()
  6550. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6551. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6552. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6553. ** [SQLITE_READONLY] is returned, then
  6554. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6555. ** errors are considered fatal.)^ The application must accept
  6556. ** that the backup operation has failed and pass the backup operation handle
  6557. ** to the sqlite3_backup_finish() to release associated resources.
  6558. **
  6559. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6560. ** on the destination file. ^The exclusive lock is not released until either
  6561. ** sqlite3_backup_finish() is called or the backup operation is complete
  6562. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6563. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6564. ** lasts for the duration of the sqlite3_backup_step() call.
  6565. ** ^Because the source database is not locked between calls to
  6566. ** sqlite3_backup_step(), the source database may be modified mid-way
  6567. ** through the backup process. ^If the source database is modified by an
  6568. ** external process or via a database connection other than the one being
  6569. ** used by the backup operation, then the backup will be automatically
  6570. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6571. ** database is modified by the using the same database connection as is used
  6572. ** by the backup operation, then the backup database is automatically
  6573. ** updated at the same time.
  6574. **
  6575. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6576. **
  6577. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6578. ** application wishes to abandon the backup operation, the application
  6579. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6580. ** ^The sqlite3_backup_finish() interfaces releases all
  6581. ** resources associated with the [sqlite3_backup] object.
  6582. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6583. ** active write-transaction on the destination database is rolled back.
  6584. ** The [sqlite3_backup] object is invalid
  6585. ** and may not be used following a call to sqlite3_backup_finish().
  6586. **
  6587. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6588. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6589. ** sqlite3_backup_step() completed.
  6590. ** ^If an out-of-memory condition or IO error occurred during any prior
  6591. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6592. ** sqlite3_backup_finish() returns the corresponding [error code].
  6593. **
  6594. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6595. ** is not a permanent error and does not affect the return value of
  6596. ** sqlite3_backup_finish().
  6597. **
  6598. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6599. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6600. **
  6601. ** ^Each call to sqlite3_backup_step() sets two values inside
  6602. ** the [sqlite3_backup] object: the number of pages still to be backed
  6603. ** up and the total number of pages in the source database file.
  6604. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6605. ** retrieve these two values, respectively.
  6606. **
  6607. ** ^The values returned by these functions are only updated by
  6608. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6609. ** operation, then the values are not updated to account for any extra
  6610. ** pages that need to be updated or the size of the source database file
  6611. ** changing.
  6612. **
  6613. ** <b>Concurrent Usage of Database Handles</b>
  6614. **
  6615. ** ^The source [database connection] may be used by the application for other
  6616. ** purposes while a backup operation is underway or being initialized.
  6617. ** ^If SQLite is compiled and configured to support threadsafe database
  6618. ** connections, then the source database connection may be used concurrently
  6619. ** from within other threads.
  6620. **
  6621. ** However, the application must guarantee that the destination
  6622. ** [database connection] is not passed to any other API (by any thread) after
  6623. ** sqlite3_backup_init() is called and before the corresponding call to
  6624. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6625. ** if the application incorrectly accesses the destination [database connection]
  6626. ** and so no error code is reported, but the operations may malfunction
  6627. ** nevertheless. Use of the destination database connection while a
  6628. ** backup is in progress might also also cause a mutex deadlock.
  6629. **
  6630. ** If running in [shared cache mode], the application must
  6631. ** guarantee that the shared cache used by the destination database
  6632. ** is not accessed while the backup is running. In practice this means
  6633. ** that the application must guarantee that the disk file being
  6634. ** backed up to is not accessed by any connection within the process,
  6635. ** not just the specific connection that was passed to sqlite3_backup_init().
  6636. **
  6637. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6638. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6639. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6640. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6641. ** same time as another thread is invoking sqlite3_backup_step() it is
  6642. ** possible that they return invalid values.
  6643. */
  6644. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6645. sqlite3 *pDest, /* Destination database handle */
  6646. const char *zDestName, /* Destination database name */
  6647. sqlite3 *pSource, /* Source database handle */
  6648. const char *zSourceName /* Source database name */
  6649. );
  6650. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6651. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6652. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6653. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6654. /*
  6655. ** CAPI3REF: Unlock Notification
  6656. **
  6657. ** ^When running in shared-cache mode, a database operation may fail with
  6658. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6659. ** individual tables within the shared-cache cannot be obtained. See
  6660. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6661. ** ^This API may be used to register a callback that SQLite will invoke
  6662. ** when the connection currently holding the required lock relinquishes it.
  6663. ** ^This API is only available if the library was compiled with the
  6664. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6665. **
  6666. ** See Also: [Using the SQLite Unlock Notification Feature].
  6667. **
  6668. ** ^Shared-cache locks are released when a database connection concludes
  6669. ** its current transaction, either by committing it or rolling it back.
  6670. **
  6671. ** ^When a connection (known as the blocked connection) fails to obtain a
  6672. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6673. ** identity of the database connection (the blocking connection) that
  6674. ** has locked the required resource is stored internally. ^After an
  6675. ** application receives an SQLITE_LOCKED error, it may call the
  6676. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6677. ** the first argument to register for a callback that will be invoked
  6678. ** when the blocking connections current transaction is concluded. ^The
  6679. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6680. ** call that concludes the blocking connections transaction.
  6681. **
  6682. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6683. ** there is a chance that the blocking connection will have already
  6684. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6685. ** If this happens, then the specified callback is invoked immediately,
  6686. ** from within the call to sqlite3_unlock_notify().)^
  6687. **
  6688. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6689. ** shared-cache table, and more than one other connection currently holds
  6690. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6691. ** the other connections to use as the blocking connection.
  6692. **
  6693. ** ^(There may be at most one unlock-notify callback registered by a
  6694. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6695. ** blocked connection already has a registered unlock-notify callback,
  6696. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6697. ** called with a NULL pointer as its second argument, then any existing
  6698. ** unlock-notify callback is canceled. ^The blocked connections
  6699. ** unlock-notify callback may also be canceled by closing the blocked
  6700. ** connection using [sqlite3_close()].
  6701. **
  6702. ** The unlock-notify callback is not reentrant. If an application invokes
  6703. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6704. ** crash or deadlock may be the result.
  6705. **
  6706. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6707. ** returns SQLITE_OK.
  6708. **
  6709. ** <b>Callback Invocation Details</b>
  6710. **
  6711. ** When an unlock-notify callback is registered, the application provides a
  6712. ** single void* pointer that is passed to the callback when it is invoked.
  6713. ** However, the signature of the callback function allows SQLite to pass
  6714. ** it an array of void* context pointers. The first argument passed to
  6715. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6716. ** and the second is the number of entries in the array.
  6717. **
  6718. ** When a blocking connections transaction is concluded, there may be
  6719. ** more than one blocked connection that has registered for an unlock-notify
  6720. ** callback. ^If two or more such blocked connections have specified the
  6721. ** same callback function, then instead of invoking the callback function
  6722. ** multiple times, it is invoked once with the set of void* context pointers
  6723. ** specified by the blocked connections bundled together into an array.
  6724. ** This gives the application an opportunity to prioritize any actions
  6725. ** related to the set of unblocked database connections.
  6726. **
  6727. ** <b>Deadlock Detection</b>
  6728. **
  6729. ** Assuming that after registering for an unlock-notify callback a
  6730. ** database waits for the callback to be issued before taking any further
  6731. ** action (a reasonable assumption), then using this API may cause the
  6732. ** application to deadlock. For example, if connection X is waiting for
  6733. ** connection Y's transaction to be concluded, and similarly connection
  6734. ** Y is waiting on connection X's transaction, then neither connection
  6735. ** will proceed and the system may remain deadlocked indefinitely.
  6736. **
  6737. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  6738. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  6739. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  6740. ** unlock-notify callback is registered. The system is said to be in
  6741. ** a deadlocked state if connection A has registered for an unlock-notify
  6742. ** callback on the conclusion of connection B's transaction, and connection
  6743. ** B has itself registered for an unlock-notify callback when connection
  6744. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  6745. ** the system is also considered to be deadlocked if connection B has
  6746. ** registered for an unlock-notify callback on the conclusion of connection
  6747. ** C's transaction, where connection C is waiting on connection A. ^Any
  6748. ** number of levels of indirection are allowed.
  6749. **
  6750. ** <b>The "DROP TABLE" Exception</b>
  6751. **
  6752. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  6753. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  6754. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  6755. ** SQLite checks if there are any currently executing SELECT statements
  6756. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  6757. ** returned. In this case there is no "blocking connection", so invoking
  6758. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  6759. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  6760. ** or "DROP INDEX" query, an infinite loop might be the result.
  6761. **
  6762. ** One way around this problem is to check the extended error code returned
  6763. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  6764. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  6765. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  6766. ** SQLITE_LOCKED.)^
  6767. */
  6768. SQLITE_API int sqlite3_unlock_notify(
  6769. sqlite3 *pBlocked, /* Waiting connection */
  6770. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  6771. void *pNotifyArg /* Argument to pass to xNotify */
  6772. );
  6773. /*
  6774. ** CAPI3REF: String Comparison
  6775. **
  6776. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  6777. ** and extensions to compare the contents of two buffers containing UTF-8
  6778. ** strings in a case-independent fashion, using the same definition of "case
  6779. ** independence" that SQLite uses internally when comparing identifiers.
  6780. */
  6781. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  6782. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  6783. /*
  6784. ** CAPI3REF: String Globbing
  6785. *
  6786. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  6787. ** the glob pattern P, and it returns non-zero if string X does not match
  6788. ** the glob pattern P. ^The definition of glob pattern matching used in
  6789. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  6790. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  6791. ** sensitive.
  6792. **
  6793. ** Note that this routine returns zero on a match and non-zero if the strings
  6794. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  6795. */
  6796. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  6797. /*
  6798. ** CAPI3REF: Error Logging Interface
  6799. **
  6800. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  6801. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  6802. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  6803. ** used with [sqlite3_snprintf()] to generate the final output string.
  6804. **
  6805. ** The sqlite3_log() interface is intended for use by extensions such as
  6806. ** virtual tables, collating functions, and SQL functions. While there is
  6807. ** nothing to prevent an application from calling sqlite3_log(), doing so
  6808. ** is considered bad form.
  6809. **
  6810. ** The zFormat string must not be NULL.
  6811. **
  6812. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  6813. ** will not use dynamically allocated memory. The log message is stored in
  6814. ** a fixed-length buffer on the stack. If the log message is longer than
  6815. ** a few hundred characters, it will be truncated to the length of the
  6816. ** buffer.
  6817. */
  6818. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  6819. /*
  6820. ** CAPI3REF: Write-Ahead Log Commit Hook
  6821. **
  6822. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  6823. ** will be invoked each time a database connection commits data to a
  6824. ** [write-ahead log] (i.e. whenever a transaction is committed in
  6825. ** [journal_mode | journal_mode=WAL mode]).
  6826. **
  6827. ** ^The callback is invoked by SQLite after the commit has taken place and
  6828. ** the associated write-lock on the database released, so the implementation
  6829. ** may read, write or [checkpoint] the database as required.
  6830. **
  6831. ** ^The first parameter passed to the callback function when it is invoked
  6832. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  6833. ** registering the callback. ^The second is a copy of the database handle.
  6834. ** ^The third parameter is the name of the database that was written to -
  6835. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  6836. ** is the number of pages currently in the write-ahead log file,
  6837. ** including those that were just committed.
  6838. **
  6839. ** The callback function should normally return [SQLITE_OK]. ^If an error
  6840. ** code is returned, that error will propagate back up through the
  6841. ** SQLite code base to cause the statement that provoked the callback
  6842. ** to report an error, though the commit will have still occurred. If the
  6843. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  6844. ** that does not correspond to any valid SQLite error code, the results
  6845. ** are undefined.
  6846. **
  6847. ** A single database handle may have at most a single write-ahead log callback
  6848. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  6849. ** previously registered write-ahead log callback. ^Note that the
  6850. ** [sqlite3_wal_autocheckpoint()] interface and the
  6851. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  6852. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  6853. */
  6854. SQLITE_API void *sqlite3_wal_hook(
  6855. sqlite3*,
  6856. int(*)(void *,sqlite3*,const char*,int),
  6857. void*
  6858. );
  6859. /*
  6860. ** CAPI3REF: Configure an auto-checkpoint
  6861. **
  6862. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  6863. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  6864. ** to automatically [checkpoint]
  6865. ** after committing a transaction if there are N or
  6866. ** more frames in the [write-ahead log] file. ^Passing zero or
  6867. ** a negative value as the nFrame parameter disables automatic
  6868. ** checkpoints entirely.
  6869. **
  6870. ** ^The callback registered by this function replaces any existing callback
  6871. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  6872. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  6873. ** configured by this function.
  6874. **
  6875. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  6876. ** from SQL.
  6877. **
  6878. ** ^Every new [database connection] defaults to having the auto-checkpoint
  6879. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  6880. ** pages. The use of this interface
  6881. ** is only necessary if the default setting is found to be suboptimal
  6882. ** for a particular application.
  6883. */
  6884. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  6885. /*
  6886. ** CAPI3REF: Checkpoint a database
  6887. **
  6888. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  6889. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  6890. ** empty string, then a checkpoint is run on all databases of
  6891. ** connection D. ^If the database connection D is not in
  6892. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  6893. **
  6894. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  6895. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  6896. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  6897. ** run whenever the WAL reaches a certain size threshold.
  6898. **
  6899. ** See also: [sqlite3_wal_checkpoint_v2()]
  6900. */
  6901. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  6902. /*
  6903. ** CAPI3REF: Checkpoint a database
  6904. **
  6905. ** Run a checkpoint operation on WAL database zDb attached to database
  6906. ** handle db. The specific operation is determined by the value of the
  6907. ** eMode parameter:
  6908. **
  6909. ** <dl>
  6910. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  6911. ** Checkpoint as many frames as possible without waiting for any database
  6912. ** readers or writers to finish. Sync the db file if all frames in the log
  6913. ** are checkpointed. This mode is the same as calling
  6914. ** sqlite3_wal_checkpoint(). The busy-handler callback is never invoked.
  6915. **
  6916. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  6917. ** This mode blocks (calls the busy-handler callback) until there is no
  6918. ** database writer and all readers are reading from the most recent database
  6919. ** snapshot. It then checkpoints all frames in the log file and syncs the
  6920. ** database file. This call blocks database writers while it is running,
  6921. ** but not database readers.
  6922. **
  6923. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  6924. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  6925. ** checkpointing the log file it blocks (calls the busy-handler callback)
  6926. ** until all readers are reading from the database file only. This ensures
  6927. ** that the next client to write to the database file restarts the log file
  6928. ** from the beginning. This call blocks database writers while it is running,
  6929. ** but not database readers.
  6930. ** </dl>
  6931. **
  6932. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  6933. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  6934. ** the total number of checkpointed frames (including any that were already
  6935. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  6936. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  6937. ** If no values are available because of an error, they are both set to -1
  6938. ** before returning to communicate this to the caller.
  6939. **
  6940. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  6941. ** any other process is running a checkpoint operation at the same time, the
  6942. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  6943. ** busy-handler configured, it will not be invoked in this case.
  6944. **
  6945. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  6946. ** "writer" lock on the database file. If the writer lock cannot be obtained
  6947. ** immediately, and a busy-handler is configured, it is invoked and the writer
  6948. ** lock retried until either the busy-handler returns 0 or the lock is
  6949. ** successfully obtained. The busy-handler is also invoked while waiting for
  6950. ** database readers as described above. If the busy-handler returns 0 before
  6951. ** the writer lock is obtained or while waiting for database readers, the
  6952. ** checkpoint operation proceeds from that point in the same way as
  6953. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  6954. ** without blocking any further. SQLITE_BUSY is returned in this case.
  6955. **
  6956. ** If parameter zDb is NULL or points to a zero length string, then the
  6957. ** specified operation is attempted on all WAL databases. In this case the
  6958. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  6959. ** an SQLITE_BUSY error is encountered when processing one or more of the
  6960. ** attached WAL databases, the operation is still attempted on any remaining
  6961. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  6962. ** error occurs while processing an attached database, processing is abandoned
  6963. ** and the error code returned to the caller immediately. If no error
  6964. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  6965. ** databases, SQLITE_OK is returned.
  6966. **
  6967. ** If database zDb is the name of an attached database that is not in WAL
  6968. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  6969. ** zDb is not NULL (or a zero length string) and is not the name of any
  6970. ** attached database, SQLITE_ERROR is returned to the caller.
  6971. */
  6972. SQLITE_API int sqlite3_wal_checkpoint_v2(
  6973. sqlite3 *db, /* Database handle */
  6974. const char *zDb, /* Name of attached database (or NULL) */
  6975. int eMode, /* SQLITE_CHECKPOINT_* value */
  6976. int *pnLog, /* OUT: Size of WAL log in frames */
  6977. int *pnCkpt /* OUT: Total number of frames checkpointed */
  6978. );
  6979. /*
  6980. ** CAPI3REF: Checkpoint operation parameters
  6981. **
  6982. ** These constants can be used as the 3rd parameter to
  6983. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  6984. ** documentation for additional information about the meaning and use of
  6985. ** each of these values.
  6986. */
  6987. #define SQLITE_CHECKPOINT_PASSIVE 0
  6988. #define SQLITE_CHECKPOINT_FULL 1
  6989. #define SQLITE_CHECKPOINT_RESTART 2
  6990. /*
  6991. ** CAPI3REF: Virtual Table Interface Configuration
  6992. **
  6993. ** This function may be called by either the [xConnect] or [xCreate] method
  6994. ** of a [virtual table] implementation to configure
  6995. ** various facets of the virtual table interface.
  6996. **
  6997. ** If this interface is invoked outside the context of an xConnect or
  6998. ** xCreate virtual table method then the behavior is undefined.
  6999. **
  7000. ** At present, there is only one option that may be configured using
  7001. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7002. ** may be added in the future.
  7003. */
  7004. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7005. /*
  7006. ** CAPI3REF: Virtual Table Configuration Options
  7007. **
  7008. ** These macros define the various options to the
  7009. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7010. ** can use to customize and optimize their behavior.
  7011. **
  7012. ** <dl>
  7013. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7014. ** <dd>Calls of the form
  7015. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7016. ** where X is an integer. If X is zero, then the [virtual table] whose
  7017. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7018. ** support constraints. In this configuration (which is the default) if
  7019. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7020. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7021. ** specified as part of the users SQL statement, regardless of the actual
  7022. ** ON CONFLICT mode specified.
  7023. **
  7024. ** If X is non-zero, then the virtual table implementation guarantees
  7025. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7026. ** any modifications to internal or persistent data structures have been made.
  7027. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7028. ** is able to roll back a statement or database transaction, and abandon
  7029. ** or continue processing the current SQL statement as appropriate.
  7030. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7031. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7032. ** had been ABORT.
  7033. **
  7034. ** Virtual table implementations that are required to handle OR REPLACE
  7035. ** must do so within the [xUpdate] method. If a call to the
  7036. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7037. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7038. ** silently replace the appropriate rows within the xUpdate callback and
  7039. ** return SQLITE_OK. Or, if this is not possible, it may return
  7040. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7041. ** constraint handling.
  7042. ** </dl>
  7043. */
  7044. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7045. /*
  7046. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7047. **
  7048. ** This function may only be called from within a call to the [xUpdate] method
  7049. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7050. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7051. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7052. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7053. ** [virtual table].
  7054. */
  7055. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7056. /*
  7057. ** CAPI3REF: Conflict resolution modes
  7058. **
  7059. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7060. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7061. ** is for the SQL statement being evaluated.
  7062. **
  7063. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7064. ** return value from the [sqlite3_set_authorizer()] callback and that
  7065. ** [SQLITE_ABORT] is also a [result code].
  7066. */
  7067. #define SQLITE_ROLLBACK 1
  7068. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7069. #define SQLITE_FAIL 3
  7070. /* #define SQLITE_ABORT 4 // Also an error code */
  7071. #define SQLITE_REPLACE 5
  7072. /*
  7073. ** Undo the hack that converts floating point types to integer for
  7074. ** builds on processors without floating point support.
  7075. */
  7076. #ifdef SQLITE_OMIT_FLOATING_POINT
  7077. # undef double
  7078. #endif
  7079. #if 0
  7080. } /* End of the 'extern "C"' block */
  7081. #endif
  7082. #endif /* _SQLITE3_H_ */
  7083. /*
  7084. ** 2010 August 30
  7085. **
  7086. ** The author disclaims copyright to this source code. In place of
  7087. ** a legal notice, here is a blessing:
  7088. **
  7089. ** May you do good and not evil.
  7090. ** May you find forgiveness for yourself and forgive others.
  7091. ** May you share freely, never taking more than you give.
  7092. **
  7093. *************************************************************************
  7094. */
  7095. #ifndef _SQLITE3RTREE_H_
  7096. #define _SQLITE3RTREE_H_
  7097. #if 0
  7098. extern "C" {
  7099. #endif
  7100. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7101. /*
  7102. ** Register a geometry callback named zGeom that can be used as part of an
  7103. ** R-Tree geometry query as follows:
  7104. **
  7105. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7106. */
  7107. SQLITE_API int sqlite3_rtree_geometry_callback(
  7108. sqlite3 *db,
  7109. const char *zGeom,
  7110. #ifdef SQLITE_RTREE_INT_ONLY
  7111. int (*xGeom)(sqlite3_rtree_geometry*, int n, sqlite3_int64 *a, int *pRes),
  7112. #else
  7113. int (*xGeom)(sqlite3_rtree_geometry*, int n, double *a, int *pRes),
  7114. #endif
  7115. void *pContext
  7116. );
  7117. /*
  7118. ** A pointer to a structure of the following type is passed as the first
  7119. ** argument to callbacks registered using rtree_geometry_callback().
  7120. */
  7121. struct sqlite3_rtree_geometry {
  7122. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7123. int nParam; /* Size of array aParam[] */
  7124. double *aParam; /* Parameters passed to SQL geom function */
  7125. void *pUser; /* Callback implementation user data */
  7126. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7127. };
  7128. #if 0
  7129. } /* end of the 'extern "C"' block */
  7130. #endif
  7131. #endif /* ifndef _SQLITE3RTREE_H_ */
  7132. /************** End of sqlite3.h *********************************************/
  7133. /************** Begin file sqliteInt.h ***************************************/
  7134. /*
  7135. ** 2001 September 15
  7136. **
  7137. ** The author disclaims copyright to this source code. In place of
  7138. ** a legal notice, here is a blessing:
  7139. **
  7140. ** May you do good and not evil.
  7141. ** May you find forgiveness for yourself and forgive others.
  7142. ** May you share freely, never taking more than you give.
  7143. **
  7144. *************************************************************************
  7145. ** Internal interface definitions for SQLite.
  7146. **
  7147. */
  7148. #ifndef _SQLITEINT_H_
  7149. #define _SQLITEINT_H_
  7150. /*
  7151. ** These #defines should enable >2GB file support on POSIX if the
  7152. ** underlying operating system supports it. If the OS lacks
  7153. ** large file support, or if the OS is windows, these should be no-ops.
  7154. **
  7155. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  7156. ** system #includes. Hence, this block of code must be the very first
  7157. ** code in all source files.
  7158. **
  7159. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  7160. ** on the compiler command line. This is necessary if you are compiling
  7161. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  7162. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  7163. ** without this option, LFS is enable. But LFS does not exist in the kernel
  7164. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  7165. ** portability you should omit LFS.
  7166. **
  7167. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  7168. */
  7169. #ifndef SQLITE_DISABLE_LFS
  7170. # define _LARGE_FILE 1
  7171. # ifndef _FILE_OFFSET_BITS
  7172. # define _FILE_OFFSET_BITS 64
  7173. # endif
  7174. # define _LARGEFILE_SOURCE 1
  7175. #endif
  7176. /*
  7177. ** Include the configuration header output by 'configure' if we're using the
  7178. ** autoconf-based build
  7179. */
  7180. #ifdef _HAVE_SQLITE_CONFIG_H
  7181. #include "config.h"
  7182. #endif
  7183. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7184. /************** Begin file sqliteLimit.h *************************************/
  7185. /*
  7186. ** 2007 May 7
  7187. **
  7188. ** The author disclaims copyright to this source code. In place of
  7189. ** a legal notice, here is a blessing:
  7190. **
  7191. ** May you do good and not evil.
  7192. ** May you find forgiveness for yourself and forgive others.
  7193. ** May you share freely, never taking more than you give.
  7194. **
  7195. *************************************************************************
  7196. **
  7197. ** This file defines various limits of what SQLite can process.
  7198. */
  7199. /*
  7200. ** The maximum length of a TEXT or BLOB in bytes. This also
  7201. ** limits the size of a row in a table or index.
  7202. **
  7203. ** The hard limit is the ability of a 32-bit signed integer
  7204. ** to count the size: 2^31-1 or 2147483647.
  7205. */
  7206. #ifndef SQLITE_MAX_LENGTH
  7207. # define SQLITE_MAX_LENGTH 1000000000
  7208. #endif
  7209. /*
  7210. ** This is the maximum number of
  7211. **
  7212. ** * Columns in a table
  7213. ** * Columns in an index
  7214. ** * Columns in a view
  7215. ** * Terms in the SET clause of an UPDATE statement
  7216. ** * Terms in the result set of a SELECT statement
  7217. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7218. ** * Terms in the VALUES clause of an INSERT statement
  7219. **
  7220. ** The hard upper limit here is 32676. Most database people will
  7221. ** tell you that in a well-normalized database, you usually should
  7222. ** not have more than a dozen or so columns in any table. And if
  7223. ** that is the case, there is no point in having more than a few
  7224. ** dozen values in any of the other situations described above.
  7225. */
  7226. #ifndef SQLITE_MAX_COLUMN
  7227. # define SQLITE_MAX_COLUMN 2000
  7228. #endif
  7229. /*
  7230. ** The maximum length of a single SQL statement in bytes.
  7231. **
  7232. ** It used to be the case that setting this value to zero would
  7233. ** turn the limit off. That is no longer true. It is not possible
  7234. ** to turn this limit off.
  7235. */
  7236. #ifndef SQLITE_MAX_SQL_LENGTH
  7237. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7238. #endif
  7239. /*
  7240. ** The maximum depth of an expression tree. This is limited to
  7241. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7242. ** want to place more severe limits on the complexity of an
  7243. ** expression.
  7244. **
  7245. ** A value of 0 used to mean that the limit was not enforced.
  7246. ** But that is no longer true. The limit is now strictly enforced
  7247. ** at all times.
  7248. */
  7249. #ifndef SQLITE_MAX_EXPR_DEPTH
  7250. # define SQLITE_MAX_EXPR_DEPTH 1000
  7251. #endif
  7252. /*
  7253. ** The maximum number of terms in a compound SELECT statement.
  7254. ** The code generator for compound SELECT statements does one
  7255. ** level of recursion for each term. A stack overflow can result
  7256. ** if the number of terms is too large. In practice, most SQL
  7257. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7258. ** any limit on the number of terms in a compount SELECT.
  7259. */
  7260. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7261. # define SQLITE_MAX_COMPOUND_SELECT 500
  7262. #endif
  7263. /*
  7264. ** The maximum number of opcodes in a VDBE program.
  7265. ** Not currently enforced.
  7266. */
  7267. #ifndef SQLITE_MAX_VDBE_OP
  7268. # define SQLITE_MAX_VDBE_OP 25000
  7269. #endif
  7270. /*
  7271. ** The maximum number of arguments to an SQL function.
  7272. */
  7273. #ifndef SQLITE_MAX_FUNCTION_ARG
  7274. # define SQLITE_MAX_FUNCTION_ARG 127
  7275. #endif
  7276. /*
  7277. ** The maximum number of in-memory pages to use for the main database
  7278. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7279. */
  7280. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7281. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7282. #endif
  7283. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7284. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7285. #endif
  7286. /*
  7287. ** The default number of frames to accumulate in the log file before
  7288. ** checkpointing the database in WAL mode.
  7289. */
  7290. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7291. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7292. #endif
  7293. /*
  7294. ** The maximum number of attached databases. This must be between 0
  7295. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7296. ** is used internally to track attached databases.
  7297. */
  7298. #ifndef SQLITE_MAX_ATTACHED
  7299. # define SQLITE_MAX_ATTACHED 10
  7300. #endif
  7301. /*
  7302. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7303. */
  7304. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7305. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7306. #endif
  7307. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7308. ** imposed by the use of 16-bit offsets within each page.
  7309. **
  7310. ** Earlier versions of SQLite allowed the user to change this value at
  7311. ** compile time. This is no longer permitted, on the grounds that it creates
  7312. ** a library that is technically incompatible with an SQLite library
  7313. ** compiled with a different limit. If a process operating on a database
  7314. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7315. ** compiled with the default page-size limit will not be able to rollback
  7316. ** the aborted transaction. This could lead to database corruption.
  7317. */
  7318. #ifdef SQLITE_MAX_PAGE_SIZE
  7319. # undef SQLITE_MAX_PAGE_SIZE
  7320. #endif
  7321. #define SQLITE_MAX_PAGE_SIZE 65536
  7322. /*
  7323. ** The default size of a database page.
  7324. */
  7325. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7326. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7327. #endif
  7328. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7329. # undef SQLITE_DEFAULT_PAGE_SIZE
  7330. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7331. #endif
  7332. /*
  7333. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7334. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7335. ** device characteristics (sector-size and atomic write() support),
  7336. ** SQLite may choose a larger value. This constant is the maximum value
  7337. ** SQLite will choose on its own.
  7338. */
  7339. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7340. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7341. #endif
  7342. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7343. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7344. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7345. #endif
  7346. /*
  7347. ** Maximum number of pages in one database file.
  7348. **
  7349. ** This is really just the default value for the max_page_count pragma.
  7350. ** This value can be lowered (or raised) at run-time using that the
  7351. ** max_page_count macro.
  7352. */
  7353. #ifndef SQLITE_MAX_PAGE_COUNT
  7354. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7355. #endif
  7356. /*
  7357. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7358. ** operator.
  7359. */
  7360. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7361. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7362. #endif
  7363. /*
  7364. ** Maximum depth of recursion for triggers.
  7365. **
  7366. ** A value of 1 means that a trigger program will not be able to itself
  7367. ** fire any triggers. A value of 0 means that no trigger programs at all
  7368. ** may be executed.
  7369. */
  7370. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7371. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7372. #endif
  7373. /************** End of sqliteLimit.h *****************************************/
  7374. /************** Continuing where we left off in sqliteInt.h ******************/
  7375. /* Disable nuisance warnings on Borland compilers */
  7376. #if defined(__BORLANDC__)
  7377. #pragma warn -rch /* unreachable code */
  7378. #pragma warn -ccc /* Condition is always true or false */
  7379. #pragma warn -aus /* Assigned value is never used */
  7380. #pragma warn -csu /* Comparing signed and unsigned */
  7381. #pragma warn -spa /* Suspicious pointer arithmetic */
  7382. #endif
  7383. /* Needed for various definitions... */
  7384. #ifndef _GNU_SOURCE
  7385. # define _GNU_SOURCE
  7386. #endif
  7387. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  7388. # define _BSD_SOURCE
  7389. #endif
  7390. /*
  7391. ** Include standard header files as necessary
  7392. */
  7393. #ifdef HAVE_STDINT_H
  7394. #include <stdint.h>
  7395. #endif
  7396. #ifdef HAVE_INTTYPES_H
  7397. #include <inttypes.h>
  7398. #endif
  7399. /*
  7400. ** The following macros are used to cast pointers to integers and
  7401. ** integers to pointers. The way you do this varies from one compiler
  7402. ** to the next, so we have developed the following set of #if statements
  7403. ** to generate appropriate macros for a wide range of compilers.
  7404. **
  7405. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7406. ** Unfortunately, that typedef is not available on all compilers, or
  7407. ** if it is available, it requires an #include of specific headers
  7408. ** that vary from one machine to the next.
  7409. **
  7410. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7411. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7412. ** So we have to define the macros in different ways depending on the
  7413. ** compiler.
  7414. */
  7415. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7416. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7417. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7418. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7419. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7420. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7421. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7422. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7423. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7424. #else /* Generates a warning - but it always works */
  7425. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7426. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7427. #endif
  7428. /*
  7429. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7430. ** 0 means mutexes are permanently disable and the library is never
  7431. ** threadsafe. 1 means the library is serialized which is the highest
  7432. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7433. ** threads can use SQLite as long as no two threads try to use the same
  7434. ** database connection at the same time.
  7435. **
  7436. ** Older versions of SQLite used an optional THREADSAFE macro.
  7437. ** We support that for legacy.
  7438. */
  7439. #if !defined(SQLITE_THREADSAFE)
  7440. # if defined(THREADSAFE)
  7441. # define SQLITE_THREADSAFE THREADSAFE
  7442. # else
  7443. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7444. # endif
  7445. #endif
  7446. /*
  7447. ** Powersafe overwrite is on by default. But can be turned off using
  7448. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7449. */
  7450. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7451. # define SQLITE_POWERSAFE_OVERWRITE 1
  7452. #endif
  7453. /*
  7454. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7455. ** It determines whether or not the features related to
  7456. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7457. ** be overridden at runtime using the sqlite3_config() API.
  7458. */
  7459. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7460. # define SQLITE_DEFAULT_MEMSTATUS 1
  7461. #endif
  7462. /*
  7463. ** Exactly one of the following macros must be defined in order to
  7464. ** specify which memory allocation subsystem to use.
  7465. **
  7466. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7467. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7468. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7469. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7470. **
  7471. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7472. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7473. ** will cause HeapValidate to be called. If heap validation should fail, an
  7474. ** assertion will be triggered.
  7475. **
  7476. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7477. ** the default.
  7478. */
  7479. #if defined(SQLITE_SYSTEM_MALLOC) \
  7480. + defined(SQLITE_WIN32_MALLOC) \
  7481. + defined(SQLITE_ZERO_MALLOC) \
  7482. + defined(SQLITE_MEMDEBUG)>1
  7483. # error "Two or more of the following compile-time configuration options\
  7484. are defined but at most one is allowed:\
  7485. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7486. SQLITE_ZERO_MALLOC"
  7487. #endif
  7488. #if defined(SQLITE_SYSTEM_MALLOC) \
  7489. + defined(SQLITE_WIN32_MALLOC) \
  7490. + defined(SQLITE_ZERO_MALLOC) \
  7491. + defined(SQLITE_MEMDEBUG)==0
  7492. # define SQLITE_SYSTEM_MALLOC 1
  7493. #endif
  7494. /*
  7495. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7496. ** sizes of memory allocations below this value where possible.
  7497. */
  7498. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7499. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7500. #endif
  7501. /*
  7502. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7503. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7504. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7505. ** it.
  7506. */
  7507. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7508. # define _XOPEN_SOURCE 600
  7509. #endif
  7510. /*
  7511. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7512. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7513. ** make it true by defining or undefining NDEBUG.
  7514. **
  7515. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7516. ** assert() statements in the code. So we want the default action
  7517. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7518. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7519. ** feature.
  7520. */
  7521. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7522. # define NDEBUG 1
  7523. #endif
  7524. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7525. # undef NDEBUG
  7526. #endif
  7527. /*
  7528. ** The testcase() macro is used to aid in coverage testing. When
  7529. ** doing coverage testing, the condition inside the argument to
  7530. ** testcase() must be evaluated both true and false in order to
  7531. ** get full branch coverage. The testcase() macro is inserted
  7532. ** to help ensure adequate test coverage in places where simple
  7533. ** condition/decision coverage is inadequate. For example, testcase()
  7534. ** can be used to make sure boundary values are tested. For
  7535. ** bitmask tests, testcase() can be used to make sure each bit
  7536. ** is significant and used at least once. On switch statements
  7537. ** where multiple cases go to the same block of code, testcase()
  7538. ** can insure that all cases are evaluated.
  7539. **
  7540. */
  7541. #ifdef SQLITE_COVERAGE_TEST
  7542. SQLITE_PRIVATE void sqlite3Coverage(int);
  7543. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7544. #else
  7545. # define testcase(X)
  7546. #endif
  7547. /*
  7548. ** The TESTONLY macro is used to enclose variable declarations or
  7549. ** other bits of code that are needed to support the arguments
  7550. ** within testcase() and assert() macros.
  7551. */
  7552. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7553. # define TESTONLY(X) X
  7554. #else
  7555. # define TESTONLY(X)
  7556. #endif
  7557. /*
  7558. ** Sometimes we need a small amount of code such as a variable initialization
  7559. ** to setup for a later assert() statement. We do not want this code to
  7560. ** appear when assert() is disabled. The following macro is therefore
  7561. ** used to contain that setup code. The "VVA" acronym stands for
  7562. ** "Verification, Validation, and Accreditation". In other words, the
  7563. ** code within VVA_ONLY() will only run during verification processes.
  7564. */
  7565. #ifndef NDEBUG
  7566. # define VVA_ONLY(X) X
  7567. #else
  7568. # define VVA_ONLY(X)
  7569. #endif
  7570. /*
  7571. ** The ALWAYS and NEVER macros surround boolean expressions which
  7572. ** are intended to always be true or false, respectively. Such
  7573. ** expressions could be omitted from the code completely. But they
  7574. ** are included in a few cases in order to enhance the resilience
  7575. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7576. ** or "ductile" rather than being "brittle" and crashing at the first
  7577. ** hint of unplanned behavior.
  7578. **
  7579. ** In other words, ALWAYS and NEVER are added for defensive code.
  7580. **
  7581. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7582. ** be true and false so that the unreachable code they specify will
  7583. ** not be counted as untested code.
  7584. */
  7585. #if defined(SQLITE_COVERAGE_TEST)
  7586. # define ALWAYS(X) (1)
  7587. # define NEVER(X) (0)
  7588. #elif !defined(NDEBUG)
  7589. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7590. # define NEVER(X) ((X)?(assert(0),1):0)
  7591. #else
  7592. # define ALWAYS(X) (X)
  7593. # define NEVER(X) (X)
  7594. #endif
  7595. /*
  7596. ** Return true (non-zero) if the input is a integer that is too large
  7597. ** to fit in 32-bits. This macro is used inside of various testcase()
  7598. ** macros to verify that we have tested SQLite for large-file support.
  7599. */
  7600. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7601. /*
  7602. ** The macro unlikely() is a hint that surrounds a boolean
  7603. ** expression that is usually false. Macro likely() surrounds
  7604. ** a boolean expression that is usually true. These hints could,
  7605. ** in theory, be used by the compiler to generate better code, but
  7606. ** currently they are just comments for human readers.
  7607. */
  7608. #define likely(X) (X)
  7609. #define unlikely(X) (X)
  7610. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7611. /************** Begin file hash.h ********************************************/
  7612. /*
  7613. ** 2001 September 22
  7614. **
  7615. ** The author disclaims copyright to this source code. In place of
  7616. ** a legal notice, here is a blessing:
  7617. **
  7618. ** May you do good and not evil.
  7619. ** May you find forgiveness for yourself and forgive others.
  7620. ** May you share freely, never taking more than you give.
  7621. **
  7622. *************************************************************************
  7623. ** This is the header file for the generic hash-table implementation
  7624. ** used in SQLite.
  7625. */
  7626. #ifndef _SQLITE_HASH_H_
  7627. #define _SQLITE_HASH_H_
  7628. /* Forward declarations of structures. */
  7629. typedef struct Hash Hash;
  7630. typedef struct HashElem HashElem;
  7631. /* A complete hash table is an instance of the following structure.
  7632. ** The internals of this structure are intended to be opaque -- client
  7633. ** code should not attempt to access or modify the fields of this structure
  7634. ** directly. Change this structure only by using the routines below.
  7635. ** However, some of the "procedures" and "functions" for modifying and
  7636. ** accessing this structure are really macros, so we can't really make
  7637. ** this structure opaque.
  7638. **
  7639. ** All elements of the hash table are on a single doubly-linked list.
  7640. ** Hash.first points to the head of this list.
  7641. **
  7642. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7643. ** the global doubly-linked list. The contents of the bucket are the
  7644. ** element pointed to plus the next _ht.count-1 elements in the list.
  7645. **
  7646. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7647. ** by a linear search of the global list. For small tables, the
  7648. ** Hash.ht table is never allocated because if there are few elements
  7649. ** in the table, it is faster to do a linear search than to manage
  7650. ** the hash table.
  7651. */
  7652. struct Hash {
  7653. unsigned int htsize; /* Number of buckets in the hash table */
  7654. unsigned int count; /* Number of entries in this table */
  7655. HashElem *first; /* The first element of the array */
  7656. struct _ht { /* the hash table */
  7657. int count; /* Number of entries with this hash */
  7658. HashElem *chain; /* Pointer to first entry with this hash */
  7659. } *ht;
  7660. };
  7661. /* Each element in the hash table is an instance of the following
  7662. ** structure. All elements are stored on a single doubly-linked list.
  7663. **
  7664. ** Again, this structure is intended to be opaque, but it can't really
  7665. ** be opaque because it is used by macros.
  7666. */
  7667. struct HashElem {
  7668. HashElem *next, *prev; /* Next and previous elements in the table */
  7669. void *data; /* Data associated with this element */
  7670. const char *pKey; int nKey; /* Key associated with this element */
  7671. };
  7672. /*
  7673. ** Access routines. To delete, insert a NULL pointer.
  7674. */
  7675. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7676. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
  7677. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
  7678. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7679. /*
  7680. ** Macros for looping over all elements of a hash table. The idiom is
  7681. ** like this:
  7682. **
  7683. ** Hash h;
  7684. ** HashElem *p;
  7685. ** ...
  7686. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7687. ** SomeStructure *pData = sqliteHashData(p);
  7688. ** // do something with pData
  7689. ** }
  7690. */
  7691. #define sqliteHashFirst(H) ((H)->first)
  7692. #define sqliteHashNext(E) ((E)->next)
  7693. #define sqliteHashData(E) ((E)->data)
  7694. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7695. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7696. /*
  7697. ** Number of entries in a hash table
  7698. */
  7699. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7700. #endif /* _SQLITE_HASH_H_ */
  7701. /************** End of hash.h ************************************************/
  7702. /************** Continuing where we left off in sqliteInt.h ******************/
  7703. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7704. /************** Begin file parse.h *******************************************/
  7705. #define TK_SEMI 1
  7706. #define TK_EXPLAIN 2
  7707. #define TK_QUERY 3
  7708. #define TK_PLAN 4
  7709. #define TK_BEGIN 5
  7710. #define TK_TRANSACTION 6
  7711. #define TK_DEFERRED 7
  7712. #define TK_IMMEDIATE 8
  7713. #define TK_EXCLUSIVE 9
  7714. #define TK_COMMIT 10
  7715. #define TK_END 11
  7716. #define TK_ROLLBACK 12
  7717. #define TK_SAVEPOINT 13
  7718. #define TK_RELEASE 14
  7719. #define TK_TO 15
  7720. #define TK_TABLE 16
  7721. #define TK_CREATE 17
  7722. #define TK_IF 18
  7723. #define TK_NOT 19
  7724. #define TK_EXISTS 20
  7725. #define TK_TEMP 21
  7726. #define TK_LP 22
  7727. #define TK_RP 23
  7728. #define TK_AS 24
  7729. #define TK_COMMA 25
  7730. #define TK_ID 26
  7731. #define TK_INDEXED 27
  7732. #define TK_ABORT 28
  7733. #define TK_ACTION 29
  7734. #define TK_AFTER 30
  7735. #define TK_ANALYZE 31
  7736. #define TK_ASC 32
  7737. #define TK_ATTACH 33
  7738. #define TK_BEFORE 34
  7739. #define TK_BY 35
  7740. #define TK_CASCADE 36
  7741. #define TK_CAST 37
  7742. #define TK_COLUMNKW 38
  7743. #define TK_CONFLICT 39
  7744. #define TK_DATABASE 40
  7745. #define TK_DESC 41
  7746. #define TK_DETACH 42
  7747. #define TK_EACH 43
  7748. #define TK_FAIL 44
  7749. #define TK_FOR 45
  7750. #define TK_IGNORE 46
  7751. #define TK_INITIALLY 47
  7752. #define TK_INSTEAD 48
  7753. #define TK_LIKE_KW 49
  7754. #define TK_MATCH 50
  7755. #define TK_NO 51
  7756. #define TK_KEY 52
  7757. #define TK_OF 53
  7758. #define TK_OFFSET 54
  7759. #define TK_PRAGMA 55
  7760. #define TK_RAISE 56
  7761. #define TK_REPLACE 57
  7762. #define TK_RESTRICT 58
  7763. #define TK_ROW 59
  7764. #define TK_TRIGGER 60
  7765. #define TK_VACUUM 61
  7766. #define TK_VIEW 62
  7767. #define TK_VIRTUAL 63
  7768. #define TK_REINDEX 64
  7769. #define TK_RENAME 65
  7770. #define TK_CTIME_KW 66
  7771. #define TK_ANY 67
  7772. #define TK_OR 68
  7773. #define TK_AND 69
  7774. #define TK_IS 70
  7775. #define TK_BETWEEN 71
  7776. #define TK_IN 72
  7777. #define TK_ISNULL 73
  7778. #define TK_NOTNULL 74
  7779. #define TK_NE 75
  7780. #define TK_EQ 76
  7781. #define TK_GT 77
  7782. #define TK_LE 78
  7783. #define TK_LT 79
  7784. #define TK_GE 80
  7785. #define TK_ESCAPE 81
  7786. #define TK_BITAND 82
  7787. #define TK_BITOR 83
  7788. #define TK_LSHIFT 84
  7789. #define TK_RSHIFT 85
  7790. #define TK_PLUS 86
  7791. #define TK_MINUS 87
  7792. #define TK_STAR 88
  7793. #define TK_SLASH 89
  7794. #define TK_REM 90
  7795. #define TK_CONCAT 91
  7796. #define TK_COLLATE 92
  7797. #define TK_BITNOT 93
  7798. #define TK_STRING 94
  7799. #define TK_JOIN_KW 95
  7800. #define TK_CONSTRAINT 96
  7801. #define TK_DEFAULT 97
  7802. #define TK_NULL 98
  7803. #define TK_PRIMARY 99
  7804. #define TK_UNIQUE 100
  7805. #define TK_CHECK 101
  7806. #define TK_REFERENCES 102
  7807. #define TK_AUTOINCR 103
  7808. #define TK_ON 104
  7809. #define TK_INSERT 105
  7810. #define TK_DELETE 106
  7811. #define TK_UPDATE 107
  7812. #define TK_SET 108
  7813. #define TK_DEFERRABLE 109
  7814. #define TK_FOREIGN 110
  7815. #define TK_DROP 111
  7816. #define TK_UNION 112
  7817. #define TK_ALL 113
  7818. #define TK_EXCEPT 114
  7819. #define TK_INTERSECT 115
  7820. #define TK_SELECT 116
  7821. #define TK_DISTINCT 117
  7822. #define TK_DOT 118
  7823. #define TK_FROM 119
  7824. #define TK_JOIN 120
  7825. #define TK_USING 121
  7826. #define TK_ORDER 122
  7827. #define TK_GROUP 123
  7828. #define TK_HAVING 124
  7829. #define TK_LIMIT 125
  7830. #define TK_WHERE 126
  7831. #define TK_INTO 127
  7832. #define TK_VALUES 128
  7833. #define TK_INTEGER 129
  7834. #define TK_FLOAT 130
  7835. #define TK_BLOB 131
  7836. #define TK_REGISTER 132
  7837. #define TK_VARIABLE 133
  7838. #define TK_CASE 134
  7839. #define TK_WHEN 135
  7840. #define TK_THEN 136
  7841. #define TK_ELSE 137
  7842. #define TK_INDEX 138
  7843. #define TK_ALTER 139
  7844. #define TK_ADD 140
  7845. #define TK_TO_TEXT 141
  7846. #define TK_TO_BLOB 142
  7847. #define TK_TO_NUMERIC 143
  7848. #define TK_TO_INT 144
  7849. #define TK_TO_REAL 145
  7850. #define TK_ISNOT 146
  7851. #define TK_END_OF_FILE 147
  7852. #define TK_ILLEGAL 148
  7853. #define TK_SPACE 149
  7854. #define TK_UNCLOSED_STRING 150
  7855. #define TK_FUNCTION 151
  7856. #define TK_COLUMN 152
  7857. #define TK_AGG_FUNCTION 153
  7858. #define TK_AGG_COLUMN 154
  7859. #define TK_CONST_FUNC 155
  7860. #define TK_UMINUS 156
  7861. #define TK_UPLUS 157
  7862. /************** End of parse.h ***********************************************/
  7863. /************** Continuing where we left off in sqliteInt.h ******************/
  7864. #include <stdio.h>
  7865. #include <stdlib.h>
  7866. #include <string.h>
  7867. #include <assert.h>
  7868. #include <stddef.h>
  7869. /*
  7870. ** If compiling for a processor that lacks floating point support,
  7871. ** substitute integer for floating-point
  7872. */
  7873. #ifdef SQLITE_OMIT_FLOATING_POINT
  7874. # define double sqlite_int64
  7875. # define float sqlite_int64
  7876. # define LONGDOUBLE_TYPE sqlite_int64
  7877. # ifndef SQLITE_BIG_DBL
  7878. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  7879. # endif
  7880. # define SQLITE_OMIT_DATETIME_FUNCS 1
  7881. # define SQLITE_OMIT_TRACE 1
  7882. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  7883. # undef SQLITE_HAVE_ISNAN
  7884. #endif
  7885. #ifndef SQLITE_BIG_DBL
  7886. # define SQLITE_BIG_DBL (1e99)
  7887. #endif
  7888. /*
  7889. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  7890. ** afterward. Having this macro allows us to cause the C compiler
  7891. ** to omit code used by TEMP tables without messy #ifndef statements.
  7892. */
  7893. #ifdef SQLITE_OMIT_TEMPDB
  7894. #define OMIT_TEMPDB 1
  7895. #else
  7896. #define OMIT_TEMPDB 0
  7897. #endif
  7898. /*
  7899. ** The "file format" number is an integer that is incremented whenever
  7900. ** the VDBE-level file format changes. The following macros define the
  7901. ** the default file format for new databases and the maximum file format
  7902. ** that the library can read.
  7903. */
  7904. #define SQLITE_MAX_FILE_FORMAT 4
  7905. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  7906. # define SQLITE_DEFAULT_FILE_FORMAT 4
  7907. #endif
  7908. /*
  7909. ** Determine whether triggers are recursive by default. This can be
  7910. ** changed at run-time using a pragma.
  7911. */
  7912. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  7913. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  7914. #endif
  7915. /*
  7916. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  7917. ** on the command-line
  7918. */
  7919. #ifndef SQLITE_TEMP_STORE
  7920. # define SQLITE_TEMP_STORE 1
  7921. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  7922. #endif
  7923. /*
  7924. ** GCC does not define the offsetof() macro so we'll have to do it
  7925. ** ourselves.
  7926. */
  7927. #ifndef offsetof
  7928. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  7929. #endif
  7930. /*
  7931. ** Macros to compute minimum and maximum of two numbers.
  7932. */
  7933. #define MIN(A,B) ((A)<(B)?(A):(B))
  7934. #define MAX(A,B) ((A)>(B)?(A):(B))
  7935. /*
  7936. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  7937. ** not, there are still machines out there that use EBCDIC.)
  7938. */
  7939. #if 'A' == '\301'
  7940. # define SQLITE_EBCDIC 1
  7941. #else
  7942. # define SQLITE_ASCII 1
  7943. #endif
  7944. /*
  7945. ** Integers of known sizes. These typedefs might change for architectures
  7946. ** where the sizes very. Preprocessor macros are available so that the
  7947. ** types can be conveniently redefined at compile-type. Like this:
  7948. **
  7949. ** cc '-DUINTPTR_TYPE=long long int' ...
  7950. */
  7951. #ifndef UINT32_TYPE
  7952. # ifdef HAVE_UINT32_T
  7953. # define UINT32_TYPE uint32_t
  7954. # else
  7955. # define UINT32_TYPE unsigned int
  7956. # endif
  7957. #endif
  7958. #ifndef UINT16_TYPE
  7959. # ifdef HAVE_UINT16_T
  7960. # define UINT16_TYPE uint16_t
  7961. # else
  7962. # define UINT16_TYPE unsigned short int
  7963. # endif
  7964. #endif
  7965. #ifndef INT16_TYPE
  7966. # ifdef HAVE_INT16_T
  7967. # define INT16_TYPE int16_t
  7968. # else
  7969. # define INT16_TYPE short int
  7970. # endif
  7971. #endif
  7972. #ifndef UINT8_TYPE
  7973. # ifdef HAVE_UINT8_T
  7974. # define UINT8_TYPE uint8_t
  7975. # else
  7976. # define UINT8_TYPE unsigned char
  7977. # endif
  7978. #endif
  7979. #ifndef INT8_TYPE
  7980. # ifdef HAVE_INT8_T
  7981. # define INT8_TYPE int8_t
  7982. # else
  7983. # define INT8_TYPE signed char
  7984. # endif
  7985. #endif
  7986. #ifndef LONGDOUBLE_TYPE
  7987. # define LONGDOUBLE_TYPE long double
  7988. #endif
  7989. typedef sqlite_int64 i64; /* 8-byte signed integer */
  7990. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  7991. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  7992. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  7993. typedef INT16_TYPE i16; /* 2-byte signed integer */
  7994. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  7995. typedef INT8_TYPE i8; /* 1-byte signed integer */
  7996. /*
  7997. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  7998. ** that can be stored in a u32 without loss of data. The value
  7999. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8000. ** have to specify the value in the less intuitive manner shown:
  8001. */
  8002. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8003. /*
  8004. ** The datatype used to store estimates of the number of rows in a
  8005. ** table or index. This is an unsigned integer type. For 99.9% of
  8006. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8007. ** can be used at compile-time if desired.
  8008. */
  8009. #ifdef SQLITE_64BIT_STATS
  8010. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8011. #else
  8012. typedef u32 tRowcnt; /* 32-bit is the default */
  8013. #endif
  8014. /*
  8015. ** Estimated quantities used for query planning are stored as 16-bit
  8016. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8017. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8018. ** But the allowed values are "grainy". Not every value is representable.
  8019. ** For example, quantities 16 and 17 are both represented by a LogEst
  8020. ** of 40. However, since LogEst quantatites are suppose to be estimates,
  8021. ** not exact values, this imprecision is not a problem.
  8022. **
  8023. ** "LogEst" is short for "Logarithimic Estimate".
  8024. **
  8025. ** Examples:
  8026. ** 1 -> 0 20 -> 43 10000 -> 132
  8027. ** 2 -> 10 25 -> 46 25000 -> 146
  8028. ** 3 -> 16 100 -> 66 1000000 -> 199
  8029. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8030. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8031. **
  8032. ** The LogEst can be negative to indicate fractional values.
  8033. ** Examples:
  8034. **
  8035. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8036. */
  8037. typedef INT16_TYPE LogEst;
  8038. /*
  8039. ** Macros to determine whether the machine is big or little endian,
  8040. ** evaluated at runtime.
  8041. */
  8042. #ifdef SQLITE_AMALGAMATION
  8043. SQLITE_PRIVATE const int sqlite3one = 1;
  8044. #else
  8045. SQLITE_PRIVATE const int sqlite3one;
  8046. #endif
  8047. #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
  8048. || defined(__x86_64) || defined(__x86_64__)
  8049. # define SQLITE_BIGENDIAN 0
  8050. # define SQLITE_LITTLEENDIAN 1
  8051. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8052. #else
  8053. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8054. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8055. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8056. #endif
  8057. /*
  8058. ** Constants for the largest and smallest possible 64-bit signed integers.
  8059. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8060. ** compilers.
  8061. */
  8062. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8063. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8064. /*
  8065. ** Round up a number to the next larger multiple of 8. This is used
  8066. ** to force 8-byte alignment on 64-bit architectures.
  8067. */
  8068. #define ROUND8(x) (((x)+7)&~7)
  8069. /*
  8070. ** Round down to the nearest multiple of 8
  8071. */
  8072. #define ROUNDDOWN8(x) ((x)&~7)
  8073. /*
  8074. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8075. ** macro is used only within assert() to verify that the code gets
  8076. ** all alignment restrictions correct.
  8077. **
  8078. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8079. ** underlying malloc() implemention might return us 4-byte aligned
  8080. ** pointers. In that case, only verify 4-byte alignment.
  8081. */
  8082. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8083. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8084. #else
  8085. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8086. #endif
  8087. /*
  8088. ** Disable MMAP on platforms where it is known to not work
  8089. */
  8090. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8091. # undef SQLITE_MAX_MMAP_SIZE
  8092. # define SQLITE_MAX_MMAP_SIZE 0
  8093. #endif
  8094. /*
  8095. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8096. */
  8097. #ifdef __APPLE__
  8098. # include <TargetConditionals.h>
  8099. # if TARGET_OS_IPHONE
  8100. # undef SQLITE_MAX_MMAP_SIZE
  8101. # define SQLITE_MAX_MMAP_SIZE 0
  8102. # endif
  8103. #endif
  8104. #ifndef SQLITE_MAX_MMAP_SIZE
  8105. # if defined(SQLITE_OS_RTT)
  8106. # define SQLITE_MAX_MMAP_SIZE 0
  8107. # elif defined(__linux__) \
  8108. || defined(_WIN32) \
  8109. || (defined(__APPLE__) && defined(__MACH__)) \
  8110. || defined(__sun)
  8111. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8112. # else
  8113. # define SQLITE_MAX_MMAP_SIZE 0
  8114. # endif
  8115. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8116. #endif
  8117. /*
  8118. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8119. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8120. ** not exceed the maximum mmap size.
  8121. */
  8122. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8123. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8124. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8125. #endif
  8126. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8127. # undef SQLITE_DEFAULT_MMAP_SIZE
  8128. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8129. #endif
  8130. /*
  8131. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8132. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8133. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8134. */
  8135. #ifdef SQLITE_ENABLE_STAT4
  8136. # undef SQLITE_ENABLE_STAT3
  8137. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8138. #elif SQLITE_ENABLE_STAT3
  8139. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8140. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8141. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8142. #endif
  8143. /*
  8144. ** An instance of the following structure is used to store the busy-handler
  8145. ** callback for a given sqlite handle.
  8146. **
  8147. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8148. ** callback for the database handle. Each pager opened via the sqlite
  8149. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8150. ** callback is currently invoked only from within pager.c.
  8151. */
  8152. typedef struct BusyHandler BusyHandler;
  8153. struct BusyHandler {
  8154. int (*xFunc)(void *,int); /* The busy callback */
  8155. void *pArg; /* First arg to busy callback */
  8156. int nBusy; /* Incremented with each busy call */
  8157. };
  8158. /*
  8159. ** Name of the master database table. The master database table
  8160. ** is a special table that holds the names and attributes of all
  8161. ** user tables and indices.
  8162. */
  8163. #define MASTER_NAME "sqlite_master"
  8164. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8165. /*
  8166. ** The root-page of the master database table.
  8167. */
  8168. #define MASTER_ROOT 1
  8169. /*
  8170. ** The name of the schema table.
  8171. */
  8172. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8173. /*
  8174. ** A convenience macro that returns the number of elements in
  8175. ** an array.
  8176. */
  8177. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8178. /*
  8179. ** Determine if the argument is a power of two
  8180. */
  8181. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8182. /*
  8183. ** The following value as a destructor means to use sqlite3DbFree().
  8184. ** The sqlite3DbFree() routine requires two parameters instead of the
  8185. ** one parameter that destructors normally want. So we have to introduce
  8186. ** this magic value that the code knows to handle differently. Any
  8187. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8188. ** and SQLITE_TRANSIENT.
  8189. */
  8190. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8191. /*
  8192. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8193. ** not support Writable Static Data (WSD) such as global and static variables.
  8194. ** All variables must either be on the stack or dynamically allocated from
  8195. ** the heap. When WSD is unsupported, the variable declarations scattered
  8196. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8197. ** macro is used for this purpose. And instead of referencing the variable
  8198. ** directly, we use its constant as a key to lookup the run-time allocated
  8199. ** buffer that holds real variable. The constant is also the initializer
  8200. ** for the run-time allocated buffer.
  8201. **
  8202. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8203. ** macros become no-ops and have zero performance impact.
  8204. */
  8205. #ifdef SQLITE_OMIT_WSD
  8206. #define SQLITE_WSD const
  8207. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8208. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8209. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8210. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8211. #else
  8212. #define SQLITE_WSD
  8213. #define GLOBAL(t,v) v
  8214. #define sqlite3GlobalConfig sqlite3Config
  8215. #endif
  8216. /*
  8217. ** The following macros are used to suppress compiler warnings and to
  8218. ** make it clear to human readers when a function parameter is deliberately
  8219. ** left unused within the body of a function. This usually happens when
  8220. ** a function is called via a function pointer. For example the
  8221. ** implementation of an SQL aggregate step callback may not use the
  8222. ** parameter indicating the number of arguments passed to the aggregate,
  8223. ** if it knows that this is enforced elsewhere.
  8224. **
  8225. ** When a function parameter is not used at all within the body of a function,
  8226. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8227. ** However, these macros may also be used to suppress warnings related to
  8228. ** parameters that may or may not be used depending on compilation options.
  8229. ** For example those parameters only used in assert() statements. In these
  8230. ** cases the parameters are named as per the usual conventions.
  8231. */
  8232. #define UNUSED_PARAMETER(x) (void)(x)
  8233. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8234. /*
  8235. ** Forward references to structures
  8236. */
  8237. typedef struct AggInfo AggInfo;
  8238. typedef struct AuthContext AuthContext;
  8239. typedef struct AutoincInfo AutoincInfo;
  8240. typedef struct Bitvec Bitvec;
  8241. typedef struct CollSeq CollSeq;
  8242. typedef struct Column Column;
  8243. typedef struct Db Db;
  8244. typedef struct Schema Schema;
  8245. typedef struct Expr Expr;
  8246. typedef struct ExprList ExprList;
  8247. typedef struct ExprSpan ExprSpan;
  8248. typedef struct FKey FKey;
  8249. typedef struct FuncDestructor FuncDestructor;
  8250. typedef struct FuncDef FuncDef;
  8251. typedef struct FuncDefHash FuncDefHash;
  8252. typedef struct IdList IdList;
  8253. typedef struct Index Index;
  8254. typedef struct IndexSample IndexSample;
  8255. typedef struct KeyClass KeyClass;
  8256. typedef struct KeyInfo KeyInfo;
  8257. typedef struct Lookaside Lookaside;
  8258. typedef struct LookasideSlot LookasideSlot;
  8259. typedef struct Module Module;
  8260. typedef struct NameContext NameContext;
  8261. typedef struct Parse Parse;
  8262. typedef struct RowSet RowSet;
  8263. typedef struct Savepoint Savepoint;
  8264. typedef struct Select Select;
  8265. typedef struct SelectDest SelectDest;
  8266. typedef struct SrcList SrcList;
  8267. typedef struct StrAccum StrAccum;
  8268. typedef struct Table Table;
  8269. typedef struct TableLock TableLock;
  8270. typedef struct Token Token;
  8271. typedef struct Trigger Trigger;
  8272. typedef struct TriggerPrg TriggerPrg;
  8273. typedef struct TriggerStep TriggerStep;
  8274. typedef struct UnpackedRecord UnpackedRecord;
  8275. typedef struct VTable VTable;
  8276. typedef struct VtabCtx VtabCtx;
  8277. typedef struct Walker Walker;
  8278. typedef struct WhereInfo WhereInfo;
  8279. /*
  8280. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8281. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8282. ** pointer types (i.e. FuncDef) defined above.
  8283. */
  8284. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8285. /************** Begin file btree.h *******************************************/
  8286. /*
  8287. ** 2001 September 15
  8288. **
  8289. ** The author disclaims copyright to this source code. In place of
  8290. ** a legal notice, here is a blessing:
  8291. **
  8292. ** May you do good and not evil.
  8293. ** May you find forgiveness for yourself and forgive others.
  8294. ** May you share freely, never taking more than you give.
  8295. **
  8296. *************************************************************************
  8297. ** This header file defines the interface that the sqlite B-Tree file
  8298. ** subsystem. See comments in the source code for a detailed description
  8299. ** of what each interface routine does.
  8300. */
  8301. #ifndef _BTREE_H_
  8302. #define _BTREE_H_
  8303. /* TODO: This definition is just included so other modules compile. It
  8304. ** needs to be revisited.
  8305. */
  8306. #define SQLITE_N_BTREE_META 10
  8307. /*
  8308. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8309. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8310. */
  8311. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8312. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8313. #endif
  8314. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8315. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8316. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8317. /*
  8318. ** Forward declarations of structure
  8319. */
  8320. typedef struct Btree Btree;
  8321. typedef struct BtCursor BtCursor;
  8322. typedef struct BtShared BtShared;
  8323. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8324. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8325. const char *zFilename, /* Name of database file to open */
  8326. sqlite3 *db, /* Associated database connection */
  8327. Btree **ppBtree, /* Return open Btree* here */
  8328. int flags, /* Flags */
  8329. int vfsFlags /* Flags passed through to VFS open */
  8330. );
  8331. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8332. ** following values.
  8333. **
  8334. ** NOTE: These values must match the corresponding PAGER_ values in
  8335. ** pager.h.
  8336. */
  8337. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8338. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8339. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8340. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8341. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8342. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8343. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8344. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8345. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8346. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8347. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8348. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8349. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8350. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8351. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8352. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8353. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8354. #endif
  8355. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8356. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8357. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8358. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8359. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8360. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8361. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int);
  8362. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8363. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8364. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8365. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8366. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8367. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8368. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8369. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8370. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8371. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8372. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8373. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8374. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8375. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8376. ** of the flags shown below.
  8377. **
  8378. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8379. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8380. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8381. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8382. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8383. ** indices.)
  8384. */
  8385. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8386. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8387. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8388. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8389. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
  8390. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8391. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8392. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8393. /*
  8394. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8395. ** should be one of the following values. The integer values are assigned
  8396. ** to constants so that the offset of the corresponding field in an
  8397. ** SQLite database header may be found using the following formula:
  8398. **
  8399. ** offset = 36 + (idx * 4)
  8400. **
  8401. ** For example, the free-page-count field is located at byte offset 36 of
  8402. ** the database file header. The incr-vacuum-flag field is located at
  8403. ** byte offset 64 (== 36+4*7).
  8404. */
  8405. #define BTREE_FREE_PAGE_COUNT 0
  8406. #define BTREE_SCHEMA_VERSION 1
  8407. #define BTREE_FILE_FORMAT 2
  8408. #define BTREE_DEFAULT_CACHE_SIZE 3
  8409. #define BTREE_LARGEST_ROOT_PAGE 4
  8410. #define BTREE_TEXT_ENCODING 5
  8411. #define BTREE_USER_VERSION 6
  8412. #define BTREE_INCR_VACUUM 7
  8413. #define BTREE_APPLICATION_ID 8
  8414. /*
  8415. ** Values that may be OR'd together to form the second argument of an
  8416. ** sqlite3BtreeCursorHints() call.
  8417. */
  8418. #define BTREE_BULKLOAD 0x00000001
  8419. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8420. Btree*, /* BTree containing table to open */
  8421. int iTable, /* Index of root page */
  8422. int wrFlag, /* 1 for writing. 0 for read-only */
  8423. struct KeyInfo*, /* First argument to compare function */
  8424. BtCursor *pCursor /* Space to write cursor structure */
  8425. );
  8426. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8427. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8428. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8429. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8430. BtCursor*,
  8431. UnpackedRecord *pUnKey,
  8432. i64 intKey,
  8433. int bias,
  8434. int *pRes
  8435. );
  8436. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
  8437. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8438. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8439. const void *pData, int nData,
  8440. int nZero, int bias, int seekResult);
  8441. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8442. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8443. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8444. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8445. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8446. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8447. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8448. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
  8449. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
  8450. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8451. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8452. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
  8453. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
  8454. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8455. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8456. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8457. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
  8458. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8459. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8460. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8461. #ifndef NDEBUG
  8462. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8463. #endif
  8464. #ifndef SQLITE_OMIT_BTREECOUNT
  8465. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8466. #endif
  8467. #ifdef SQLITE_TEST
  8468. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8469. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8470. #endif
  8471. #ifndef SQLITE_OMIT_WAL
  8472. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8473. #endif
  8474. /*
  8475. ** If we are not using shared cache, then there is no need to
  8476. ** use mutexes to access the BtShared structures. So make the
  8477. ** Enter and Leave procedures no-ops.
  8478. */
  8479. #ifndef SQLITE_OMIT_SHARED_CACHE
  8480. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8481. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8482. #else
  8483. # define sqlite3BtreeEnter(X)
  8484. # define sqlite3BtreeEnterAll(X)
  8485. #endif
  8486. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8487. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8488. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8489. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8490. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8491. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8492. #ifndef NDEBUG
  8493. /* These routines are used inside assert() statements only. */
  8494. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8495. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8496. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8497. #endif
  8498. #else
  8499. # define sqlite3BtreeSharable(X) 0
  8500. # define sqlite3BtreeLeave(X)
  8501. # define sqlite3BtreeEnterCursor(X)
  8502. # define sqlite3BtreeLeaveCursor(X)
  8503. # define sqlite3BtreeLeaveAll(X)
  8504. # define sqlite3BtreeHoldsMutex(X) 1
  8505. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8506. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8507. #endif
  8508. #endif /* _BTREE_H_ */
  8509. /************** End of btree.h ***********************************************/
  8510. /************** Continuing where we left off in sqliteInt.h ******************/
  8511. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8512. /************** Begin file vdbe.h ********************************************/
  8513. /*
  8514. ** 2001 September 15
  8515. **
  8516. ** The author disclaims copyright to this source code. In place of
  8517. ** a legal notice, here is a blessing:
  8518. **
  8519. ** May you do good and not evil.
  8520. ** May you find forgiveness for yourself and forgive others.
  8521. ** May you share freely, never taking more than you give.
  8522. **
  8523. *************************************************************************
  8524. ** Header file for the Virtual DataBase Engine (VDBE)
  8525. **
  8526. ** This header defines the interface to the virtual database engine
  8527. ** or VDBE. The VDBE implements an abstract machine that runs a
  8528. ** simple program to access and modify the underlying database.
  8529. */
  8530. #ifndef _SQLITE_VDBE_H_
  8531. #define _SQLITE_VDBE_H_
  8532. /* #include <stdio.h> */
  8533. /*
  8534. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8535. ** in the source file sqliteVdbe.c are allowed to see the insides
  8536. ** of this structure.
  8537. */
  8538. typedef struct Vdbe Vdbe;
  8539. /*
  8540. ** The names of the following types declared in vdbeInt.h are required
  8541. ** for the VdbeOp definition.
  8542. */
  8543. typedef struct Mem Mem;
  8544. typedef struct SubProgram SubProgram;
  8545. /*
  8546. ** A single instruction of the virtual machine has an opcode
  8547. ** and as many as three operands. The instruction is recorded
  8548. ** as an instance of the following structure:
  8549. */
  8550. struct VdbeOp {
  8551. u8 opcode; /* What operation to perform */
  8552. signed char p4type; /* One of the P4_xxx constants for p4 */
  8553. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8554. u8 p5; /* Fifth parameter is an unsigned character */
  8555. int p1; /* First operand */
  8556. int p2; /* Second parameter (often the jump destination) */
  8557. int p3; /* The third parameter */
  8558. union { /* fourth parameter */
  8559. int i; /* Integer value if p4type==P4_INT32 */
  8560. void *p; /* Generic pointer */
  8561. char *z; /* Pointer to data for string (char array) types */
  8562. i64 *pI64; /* Used when p4type is P4_INT64 */
  8563. double *pReal; /* Used when p4type is P4_REAL */
  8564. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8565. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8566. Mem *pMem; /* Used when p4type is P4_MEM */
  8567. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8568. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8569. int *ai; /* Used when p4type is P4_INTARRAY */
  8570. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8571. int (*xAdvance)(BtCursor *, int *);
  8572. } p4;
  8573. #ifdef SQLITE_DEBUG
  8574. char *zComment; /* Comment to improve readability */
  8575. #endif
  8576. #ifdef VDBE_PROFILE
  8577. int cnt; /* Number of times this instruction was executed */
  8578. u64 cycles; /* Total time spent executing this instruction */
  8579. #endif
  8580. };
  8581. typedef struct VdbeOp VdbeOp;
  8582. /*
  8583. ** A sub-routine used to implement a trigger program.
  8584. */
  8585. struct SubProgram {
  8586. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8587. int nOp; /* Elements in aOp[] */
  8588. int nMem; /* Number of memory cells required */
  8589. int nCsr; /* Number of cursors required */
  8590. int nOnce; /* Number of OP_Once instructions */
  8591. void *token; /* id that may be used to recursive triggers */
  8592. SubProgram *pNext; /* Next sub-program already visited */
  8593. };
  8594. /*
  8595. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8596. ** it takes up less space.
  8597. */
  8598. struct VdbeOpList {
  8599. u8 opcode; /* What operation to perform */
  8600. signed char p1; /* First operand */
  8601. signed char p2; /* Second parameter (often the jump destination) */
  8602. signed char p3; /* Third parameter */
  8603. };
  8604. typedef struct VdbeOpList VdbeOpList;
  8605. /*
  8606. ** Allowed values of VdbeOp.p4type
  8607. */
  8608. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8609. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8610. #define P4_STATIC (-2) /* Pointer to a static string */
  8611. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8612. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8613. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8614. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8615. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8616. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8617. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8618. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8619. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8620. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8621. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8622. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8623. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8624. /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
  8625. ** is made. That copy is freed when the Vdbe is finalized. But if the
  8626. ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
  8627. ** gets freed when the Vdbe is finalized so it still should be obtained
  8628. ** from a single sqliteMalloc(). But no copy is made and the calling
  8629. ** function should *not* try to free the KeyInfo.
  8630. */
  8631. #define P4_KEYINFO_HANDOFF (-16)
  8632. #define P4_KEYINFO_STATIC (-17)
  8633. /*
  8634. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8635. ** number of columns of data returned by the statement.
  8636. */
  8637. #define COLNAME_NAME 0
  8638. #define COLNAME_DECLTYPE 1
  8639. #define COLNAME_DATABASE 2
  8640. #define COLNAME_TABLE 3
  8641. #define COLNAME_COLUMN 4
  8642. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8643. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8644. #else
  8645. # ifdef SQLITE_OMIT_DECLTYPE
  8646. # define COLNAME_N 1 /* Store only the name */
  8647. # else
  8648. # define COLNAME_N 2 /* Store the name and decltype */
  8649. # endif
  8650. #endif
  8651. /*
  8652. ** The following macro converts a relative address in the p2 field
  8653. ** of a VdbeOp structure into a negative number so that
  8654. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  8655. ** the macro again restores the address.
  8656. */
  8657. #define ADDR(X) (-1-(X))
  8658. /*
  8659. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  8660. ** header file that defines a number for each opcode used by the VDBE.
  8661. */
  8662. /************** Include opcodes.h in the middle of vdbe.h ********************/
  8663. /************** Begin file opcodes.h *****************************************/
  8664. /* Automatically generated. Do not edit */
  8665. /* See the mkopcodeh.awk script for details */
  8666. #define OP_Function 1
  8667. #define OP_Savepoint 2
  8668. #define OP_AutoCommit 3
  8669. #define OP_Transaction 4
  8670. #define OP_SorterNext 5
  8671. #define OP_Prev 6
  8672. #define OP_Next 7
  8673. #define OP_AggStep 8
  8674. #define OP_Checkpoint 9
  8675. #define OP_JournalMode 10
  8676. #define OP_Vacuum 11
  8677. #define OP_VFilter 12
  8678. #define OP_VUpdate 13
  8679. #define OP_Goto 14
  8680. #define OP_Gosub 15
  8681. #define OP_Return 16
  8682. #define OP_Yield 17
  8683. #define OP_HaltIfNull 18
  8684. #define OP_Not 19 /* same as TK_NOT */
  8685. #define OP_Halt 20
  8686. #define OP_Integer 21
  8687. #define OP_Int64 22
  8688. #define OP_String 23
  8689. #define OP_Null 24
  8690. #define OP_Blob 25
  8691. #define OP_Variable 26
  8692. #define OP_Move 27
  8693. #define OP_Copy 28
  8694. #define OP_SCopy 29
  8695. #define OP_ResultRow 30
  8696. #define OP_CollSeq 31
  8697. #define OP_AddImm 32
  8698. #define OP_MustBeInt 33
  8699. #define OP_RealAffinity 34
  8700. #define OP_Permutation 35
  8701. #define OP_Compare 36
  8702. #define OP_Jump 37
  8703. #define OP_Once 38
  8704. #define OP_If 39
  8705. #define OP_IfNot 40
  8706. #define OP_Column 41
  8707. #define OP_Affinity 42
  8708. #define OP_MakeRecord 43
  8709. #define OP_Count 44
  8710. #define OP_ReadCookie 45
  8711. #define OP_SetCookie 46
  8712. #define OP_VerifyCookie 47
  8713. #define OP_OpenRead 48
  8714. #define OP_OpenWrite 49
  8715. #define OP_OpenAutoindex 50
  8716. #define OP_OpenEphemeral 51
  8717. #define OP_SorterOpen 52
  8718. #define OP_OpenPseudo 53
  8719. #define OP_Close 54
  8720. #define OP_SeekLt 55
  8721. #define OP_SeekLe 56
  8722. #define OP_SeekGe 57
  8723. #define OP_SeekGt 58
  8724. #define OP_Seek 59
  8725. #define OP_NotFound 60
  8726. #define OP_Found 61
  8727. #define OP_IsUnique 62
  8728. #define OP_NotExists 63
  8729. #define OP_Sequence 64
  8730. #define OP_NewRowid 65
  8731. #define OP_Insert 66
  8732. #define OP_InsertInt 67
  8733. #define OP_Or 68 /* same as TK_OR */
  8734. #define OP_And 69 /* same as TK_AND */
  8735. #define OP_Delete 70
  8736. #define OP_ResetCount 71
  8737. #define OP_SorterCompare 72
  8738. #define OP_IsNull 73 /* same as TK_ISNULL */
  8739. #define OP_NotNull 74 /* same as TK_NOTNULL */
  8740. #define OP_Ne 75 /* same as TK_NE */
  8741. #define OP_Eq 76 /* same as TK_EQ */
  8742. #define OP_Gt 77 /* same as TK_GT */
  8743. #define OP_Le 78 /* same as TK_LE */
  8744. #define OP_Lt 79 /* same as TK_LT */
  8745. #define OP_Ge 80 /* same as TK_GE */
  8746. #define OP_SorterData 81
  8747. #define OP_BitAnd 82 /* same as TK_BITAND */
  8748. #define OP_BitOr 83 /* same as TK_BITOR */
  8749. #define OP_ShiftLeft 84 /* same as TK_LSHIFT */
  8750. #define OP_ShiftRight 85 /* same as TK_RSHIFT */
  8751. #define OP_Add 86 /* same as TK_PLUS */
  8752. #define OP_Subtract 87 /* same as TK_MINUS */
  8753. #define OP_Multiply 88 /* same as TK_STAR */
  8754. #define OP_Divide 89 /* same as TK_SLASH */
  8755. #define OP_Remainder 90 /* same as TK_REM */
  8756. #define OP_Concat 91 /* same as TK_CONCAT */
  8757. #define OP_RowKey 92
  8758. #define OP_BitNot 93 /* same as TK_BITNOT */
  8759. #define OP_String8 94 /* same as TK_STRING */
  8760. #define OP_RowData 95
  8761. #define OP_Rowid 96
  8762. #define OP_NullRow 97
  8763. #define OP_Last 98
  8764. #define OP_SorterSort 99
  8765. #define OP_Sort 100
  8766. #define OP_Rewind 101
  8767. #define OP_SorterInsert 102
  8768. #define OP_IdxInsert 103
  8769. #define OP_IdxDelete 104
  8770. #define OP_IdxRowid 105
  8771. #define OP_IdxLT 106
  8772. #define OP_IdxGE 107
  8773. #define OP_Destroy 108
  8774. #define OP_Clear 109
  8775. #define OP_CreateIndex 110
  8776. #define OP_CreateTable 111
  8777. #define OP_ParseSchema 112
  8778. #define OP_LoadAnalysis 113
  8779. #define OP_DropTable 114
  8780. #define OP_DropIndex 115
  8781. #define OP_DropTrigger 116
  8782. #define OP_IntegrityCk 117
  8783. #define OP_RowSetAdd 118
  8784. #define OP_RowSetRead 119
  8785. #define OP_RowSetTest 120
  8786. #define OP_Program 121
  8787. #define OP_Param 122
  8788. #define OP_FkCounter 123
  8789. #define OP_FkIfZero 124
  8790. #define OP_MemMax 125
  8791. #define OP_IfPos 126
  8792. #define OP_IfNeg 127
  8793. #define OP_IfZero 128
  8794. #define OP_AggFinal 129
  8795. #define OP_Real 130 /* same as TK_FLOAT */
  8796. #define OP_IncrVacuum 131
  8797. #define OP_Expire 132
  8798. #define OP_TableLock 133
  8799. #define OP_VBegin 134
  8800. #define OP_VCreate 135
  8801. #define OP_VDestroy 136
  8802. #define OP_VOpen 137
  8803. #define OP_VColumn 138
  8804. #define OP_VNext 139
  8805. #define OP_VRename 140
  8806. #define OP_ToText 141 /* same as TK_TO_TEXT */
  8807. #define OP_ToBlob 142 /* same as TK_TO_BLOB */
  8808. #define OP_ToNumeric 143 /* same as TK_TO_NUMERIC*/
  8809. #define OP_ToInt 144 /* same as TK_TO_INT */
  8810. #define OP_ToReal 145 /* same as TK_TO_REAL */
  8811. #define OP_Pagecount 146
  8812. #define OP_MaxPgcnt 147
  8813. #define OP_Trace 148
  8814. #define OP_Noop 149
  8815. #define OP_Explain 150
  8816. /* Properties such as "out2" or "jump" that are specified in
  8817. ** comments following the "case" for each opcode in the vdbe.c
  8818. ** are encoded into bitvectors as follows:
  8819. */
  8820. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  8821. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  8822. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  8823. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  8824. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  8825. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  8826. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  8827. #define OPFLG_INITIALIZER {\
  8828. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  8829. /* 8 */ 0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x01, 0x01,\
  8830. /* 16 */ 0x04, 0x04, 0x10, 0x24, 0x00, 0x02, 0x02, 0x02,\
  8831. /* 24 */ 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x00, 0x00,\
  8832. /* 32 */ 0x04, 0x05, 0x04, 0x00, 0x00, 0x01, 0x01, 0x05,\
  8833. /* 40 */ 0x05, 0x00, 0x00, 0x00, 0x02, 0x02, 0x10, 0x00,\
  8834. /* 48 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11,\
  8835. /* 56 */ 0x11, 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11,\
  8836. /* 64 */ 0x02, 0x02, 0x00, 0x00, 0x4c, 0x4c, 0x00, 0x00,\
  8837. /* 72 */ 0x00, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
  8838. /* 80 */ 0x15, 0x00, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
  8839. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x00, 0x24, 0x02, 0x00,\
  8840. /* 96 */ 0x02, 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08,\
  8841. /* 104 */ 0x00, 0x02, 0x01, 0x01, 0x02, 0x00, 0x02, 0x02,\
  8842. /* 112 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x45,\
  8843. /* 120 */ 0x15, 0x01, 0x02, 0x00, 0x01, 0x08, 0x05, 0x05,\
  8844. /* 128 */ 0x05, 0x00, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00,\
  8845. /* 136 */ 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x04, 0x04,\
  8846. /* 144 */ 0x04, 0x04, 0x02, 0x02, 0x00, 0x00, 0x00,}
  8847. /************** End of opcodes.h *********************************************/
  8848. /************** Continuing where we left off in vdbe.h ***********************/
  8849. /*
  8850. ** Prototypes for the VDBE interface. See comments on the implementation
  8851. ** for a description of what each of these routines does.
  8852. */
  8853. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
  8854. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  8855. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  8856. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  8857. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  8858. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  8859. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  8860. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  8861. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  8862. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  8863. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  8864. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  8865. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  8866. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  8867. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  8868. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  8869. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  8870. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  8871. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  8872. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  8873. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  8874. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  8875. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  8876. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  8877. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  8878. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  8879. #ifdef SQLITE_DEBUG
  8880. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  8881. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe*,FILE*);
  8882. #endif
  8883. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  8884. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  8885. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  8886. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  8887. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  8888. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  8889. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  8890. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  8891. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  8892. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  8893. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  8894. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  8895. #ifndef SQLITE_OMIT_TRACE
  8896. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  8897. #endif
  8898. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  8899. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  8900. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  8901. #ifndef SQLITE_OMIT_TRIGGER
  8902. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  8903. #endif
  8904. #ifndef NDEBUG
  8905. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  8906. # define VdbeComment(X) sqlite3VdbeComment X
  8907. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  8908. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  8909. #else
  8910. # define VdbeComment(X)
  8911. # define VdbeNoopComment(X)
  8912. #endif
  8913. #endif
  8914. /************** End of vdbe.h ************************************************/
  8915. /************** Continuing where we left off in sqliteInt.h ******************/
  8916. /************** Include pager.h in the middle of sqliteInt.h *****************/
  8917. /************** Begin file pager.h *******************************************/
  8918. /*
  8919. ** 2001 September 15
  8920. **
  8921. ** The author disclaims copyright to this source code. In place of
  8922. ** a legal notice, here is a blessing:
  8923. **
  8924. ** May you do good and not evil.
  8925. ** May you find forgiveness for yourself and forgive others.
  8926. ** May you share freely, never taking more than you give.
  8927. **
  8928. *************************************************************************
  8929. ** This header file defines the interface that the sqlite page cache
  8930. ** subsystem. The page cache subsystem reads and writes a file a page
  8931. ** at a time and provides a journal for rollback.
  8932. */
  8933. #ifndef _PAGER_H_
  8934. #define _PAGER_H_
  8935. /*
  8936. ** Default maximum size for persistent journal files. A negative
  8937. ** value means no limit. This value may be overridden using the
  8938. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  8939. */
  8940. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  8941. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  8942. #endif
  8943. /*
  8944. ** The type used to represent a page number. The first page in a file
  8945. ** is called page 1. 0 is used to represent "not a page".
  8946. */
  8947. typedef u32 Pgno;
  8948. /*
  8949. ** Each open file is managed by a separate instance of the "Pager" structure.
  8950. */
  8951. typedef struct Pager Pager;
  8952. /*
  8953. ** Handle type for pages.
  8954. */
  8955. typedef struct PgHdr DbPage;
  8956. /*
  8957. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  8958. ** reserved for working around a windows/posix incompatibility). It is
  8959. ** used in the journal to signify that the remainder of the journal file
  8960. ** is devoted to storing a master journal name - there are no more pages to
  8961. ** roll back. See comments for function writeMasterJournal() in pager.c
  8962. ** for details.
  8963. */
  8964. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  8965. /*
  8966. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  8967. **
  8968. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  8969. */
  8970. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  8971. #define PAGER_MEMORY 0x0002 /* In-memory database */
  8972. /*
  8973. ** Valid values for the second argument to sqlite3PagerLockingMode().
  8974. */
  8975. #define PAGER_LOCKINGMODE_QUERY -1
  8976. #define PAGER_LOCKINGMODE_NORMAL 0
  8977. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  8978. /*
  8979. ** Numeric constants that encode the journalmode.
  8980. */
  8981. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  8982. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  8983. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  8984. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  8985. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  8986. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  8987. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  8988. /*
  8989. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  8990. */
  8991. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  8992. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  8993. /*
  8994. ** Flags for sqlite3PagerSetFlags()
  8995. */
  8996. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  8997. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  8998. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  8999. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9000. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9001. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9002. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9003. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9004. /*
  9005. ** The remainder of this file contains the declarations of the functions
  9006. ** that make up the Pager sub-system API. See source code comments for
  9007. ** a detailed description of each routine.
  9008. */
  9009. /* Open and close a Pager connection. */
  9010. SQLITE_PRIVATE int sqlite3PagerOpen(
  9011. sqlite3_vfs*,
  9012. Pager **ppPager,
  9013. const char*,
  9014. int,
  9015. int,
  9016. int,
  9017. void(*)(DbPage*)
  9018. );
  9019. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9020. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9021. /* Functions used to configure a Pager object. */
  9022. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9023. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9024. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9025. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9026. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9027. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9028. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9029. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9030. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9031. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9032. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9033. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9034. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9035. /* Functions used to obtain and release page references. */
  9036. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9037. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9038. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9039. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9040. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9041. /* Operations on page references. */
  9042. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9043. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9044. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9045. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9046. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9047. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9048. /* Functions used to manage pager transactions and savepoints. */
  9049. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9050. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9051. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9052. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9053. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
  9054. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9055. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9056. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9057. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9058. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9059. #ifndef SQLITE_OMIT_WAL
  9060. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9061. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9062. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9063. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9064. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9065. #endif
  9066. #ifdef SQLITE_ENABLE_ZIPVFS
  9067. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9068. #endif
  9069. /* Functions used to query pager state and configuration. */
  9070. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9071. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9072. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9073. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9074. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9075. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9076. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9077. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9078. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9079. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9080. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9081. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9082. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9083. /* Functions used to truncate the database file. */
  9084. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9085. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9086. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9087. #endif
  9088. /* Functions to support testing and debugging. */
  9089. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9090. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9091. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9092. #endif
  9093. #ifdef SQLITE_TEST
  9094. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9095. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9096. void disable_simulated_io_errors(void);
  9097. void enable_simulated_io_errors(void);
  9098. #else
  9099. # define disable_simulated_io_errors()
  9100. # define enable_simulated_io_errors()
  9101. #endif
  9102. #endif /* _PAGER_H_ */
  9103. /************** End of pager.h ***********************************************/
  9104. /************** Continuing where we left off in sqliteInt.h ******************/
  9105. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9106. /************** Begin file pcache.h ******************************************/
  9107. /*
  9108. ** 2008 August 05
  9109. **
  9110. ** The author disclaims copyright to this source code. In place of
  9111. ** a legal notice, here is a blessing:
  9112. **
  9113. ** May you do good and not evil.
  9114. ** May you find forgiveness for yourself and forgive others.
  9115. ** May you share freely, never taking more than you give.
  9116. **
  9117. *************************************************************************
  9118. ** This header file defines the interface that the sqlite page cache
  9119. ** subsystem.
  9120. */
  9121. #ifndef _PCACHE_H_
  9122. typedef struct PgHdr PgHdr;
  9123. typedef struct PCache PCache;
  9124. /*
  9125. ** Every page in the cache is controlled by an instance of the following
  9126. ** structure.
  9127. */
  9128. struct PgHdr {
  9129. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9130. void *pData; /* Page data */
  9131. void *pExtra; /* Extra content */
  9132. PgHdr *pDirty; /* Transient list of dirty pages */
  9133. Pager *pPager; /* The pager this page is part of */
  9134. Pgno pgno; /* Page number for this page */
  9135. #ifdef SQLITE_CHECK_PAGES
  9136. u32 pageHash; /* Hash of page content */
  9137. #endif
  9138. u16 flags; /* PGHDR flags defined below */
  9139. /**********************************************************************
  9140. ** Elements above are public. All that follows is private to pcache.c
  9141. ** and should not be accessed by other modules.
  9142. */
  9143. i16 nRef; /* Number of users of this page */
  9144. PCache *pCache; /* Cache that owns this page */
  9145. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9146. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9147. };
  9148. /* Bit values for PgHdr.flags */
  9149. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9150. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9151. ** writing this page to the database */
  9152. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9153. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9154. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9155. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9156. /* Initialize and shutdown the page cache subsystem */
  9157. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9158. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9159. /* Page cache buffer management:
  9160. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9161. */
  9162. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9163. /* Create a new pager cache.
  9164. ** Under memory stress, invoke xStress to try to make pages clean.
  9165. ** Only clean and unpinned pages can be reclaimed.
  9166. */
  9167. SQLITE_PRIVATE void sqlite3PcacheOpen(
  9168. int szPage, /* Size of every page */
  9169. int szExtra, /* Extra space associated with each page */
  9170. int bPurgeable, /* True if pages are on backing store */
  9171. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9172. void *pStress, /* Argument to xStress */
  9173. PCache *pToInit /* Preallocated space for the PCache */
  9174. );
  9175. /* Modify the page-size after the cache has been created. */
  9176. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
  9177. /* Return the size in bytes of a PCache object. Used to preallocate
  9178. ** storage space.
  9179. */
  9180. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9181. /* One release per successful fetch. Page is pinned until released.
  9182. ** Reference counted.
  9183. */
  9184. SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
  9185. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9186. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9187. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9188. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9189. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9190. /* Change a page number. Used by incr-vacuum. */
  9191. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9192. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9193. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9194. /* Get a list of all dirty pages in the cache, sorted by page number */
  9195. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9196. /* Reset and close the cache object */
  9197. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9198. /* Clear flags from pages of the page cache */
  9199. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9200. /* Discard the contents of the cache */
  9201. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9202. /* Return the total number of outstanding page references */
  9203. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9204. /* Increment the reference count of an existing page */
  9205. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9206. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9207. /* Return the total number of pages stored in the cache */
  9208. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9209. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9210. /* Iterate through all dirty pages currently stored in the cache. This
  9211. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9212. ** library is built.
  9213. */
  9214. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9215. #endif
  9216. /* Set and get the suggested cache-size for the specified pager-cache.
  9217. **
  9218. ** If no global maximum is configured, then the system attempts to limit
  9219. ** the total number of pages cached by purgeable pager-caches to the sum
  9220. ** of the suggested cache-sizes.
  9221. */
  9222. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9223. #ifdef SQLITE_TEST
  9224. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9225. #endif
  9226. /* Free up as much memory as possible from the page cache */
  9227. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9228. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9229. /* Try to return memory used by the pcache module to the main memory heap */
  9230. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9231. #endif
  9232. #ifdef SQLITE_TEST
  9233. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9234. #endif
  9235. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9236. #endif /* _PCACHE_H_ */
  9237. /************** End of pcache.h **********************************************/
  9238. /************** Continuing where we left off in sqliteInt.h ******************/
  9239. /************** Include os.h in the middle of sqliteInt.h ********************/
  9240. /************** Begin file os.h **********************************************/
  9241. /*
  9242. ** 2001 September 16
  9243. **
  9244. ** The author disclaims copyright to this source code. In place of
  9245. ** a legal notice, here is a blessing:
  9246. **
  9247. ** May you do good and not evil.
  9248. ** May you find forgiveness for yourself and forgive others.
  9249. ** May you share freely, never taking more than you give.
  9250. **
  9251. ******************************************************************************
  9252. **
  9253. ** This header file (together with is companion C source-code file
  9254. ** "os.c") attempt to abstract the underlying operating system so that
  9255. ** the SQLite library will work on both POSIX and windows systems.
  9256. **
  9257. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9258. ** being included by every source file.
  9259. */
  9260. #ifndef _SQLITE_OS_H_
  9261. #define _SQLITE_OS_H_
  9262. /*
  9263. ** Figure out if we are dealing with Unix, Windows, or some other
  9264. ** operating system. After the following block of preprocess macros,
  9265. ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, and SQLITE_OS_OTHER
  9266. ** will defined to either 1 or 0. One of the four will be 1. The other
  9267. ** three will be 0.
  9268. */
  9269. #if defined(SQLITE_OS_OTHER)
  9270. # if SQLITE_OS_OTHER==1
  9271. # undef SQLITE_OS_UNIX
  9272. # define SQLITE_OS_UNIX 0
  9273. # undef SQLITE_OS_WIN
  9274. # define SQLITE_OS_WIN 0
  9275. # undef SQLITE_OS_RTT
  9276. # define SQLITE_OS_RTT 1
  9277. # else
  9278. # undef SQLITE_OS_OTHER
  9279. # endif
  9280. #endif
  9281. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9282. # define SQLITE_OS_OTHER 0
  9283. # ifndef SQLITE_OS_WIN
  9284. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  9285. # define SQLITE_OS_WIN 1
  9286. # define SQLITE_OS_UNIX 0
  9287. # else
  9288. # define SQLITE_OS_WIN 0
  9289. # define SQLITE_OS_UNIX 1
  9290. # endif
  9291. # else
  9292. # define SQLITE_OS_UNIX 0
  9293. # endif
  9294. #else
  9295. # ifndef SQLITE_OS_WIN
  9296. # define SQLITE_OS_WIN 0
  9297. # endif
  9298. #endif
  9299. #if SQLITE_OS_WIN
  9300. # include <windows.h>
  9301. #endif
  9302. /*
  9303. ** Determine if we are dealing with Windows NT.
  9304. **
  9305. ** We ought to be able to determine if we are compiling for win98 or winNT
  9306. ** using the _WIN32_WINNT macro as follows:
  9307. **
  9308. ** #if defined(_WIN32_WINNT)
  9309. ** # define SQLITE_OS_WINNT 1
  9310. ** #else
  9311. ** # define SQLITE_OS_WINNT 0
  9312. ** #endif
  9313. **
  9314. ** However, vs2005 does not set _WIN32_WINNT by default, as it ought to,
  9315. ** so the above test does not work. We'll just assume that everything is
  9316. ** winNT unless the programmer explicitly says otherwise by setting
  9317. ** SQLITE_OS_WINNT to 0.
  9318. */
  9319. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  9320. # define SQLITE_OS_WINNT 1
  9321. #endif
  9322. /*
  9323. ** Determine if we are dealing with WindowsCE - which has a much
  9324. ** reduced API.
  9325. */
  9326. #if defined(_WIN32_WCE)
  9327. # define SQLITE_OS_WINCE 1
  9328. #else
  9329. # define SQLITE_OS_WINCE 0
  9330. #endif
  9331. /*
  9332. ** Determine if we are dealing with WinRT, which provides only a subset of
  9333. ** the full Win32 API.
  9334. */
  9335. #if !defined(SQLITE_OS_WINRT)
  9336. # define SQLITE_OS_WINRT 0
  9337. #endif
  9338. /* If the SET_FULLSYNC macro is not defined above, then make it
  9339. ** a no-op
  9340. */
  9341. #ifndef SET_FULLSYNC
  9342. # define SET_FULLSYNC(x,y)
  9343. #endif
  9344. /*
  9345. ** The default size of a disk sector
  9346. */
  9347. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9348. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9349. #endif
  9350. /*
  9351. ** Temporary files are named starting with this prefix followed by 16 random
  9352. ** alphanumeric characters, and no file extension. They are stored in the
  9353. ** OS's standard temporary file directory, and are deleted prior to exit.
  9354. ** If sqlite is being embedded in another program, you may wish to change the
  9355. ** prefix to reflect your program's name, so that if your program exits
  9356. ** prematurely, old temporary files can be easily identified. This can be done
  9357. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9358. **
  9359. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9360. ** Mcafee started using SQLite in their anti-virus product and it
  9361. ** started putting files with the "sqlite" name in the c:/temp folder.
  9362. ** This annoyed many windows users. Those users would then do a
  9363. ** Google search for "sqlite", find the telephone numbers of the
  9364. ** developers and call to wake them up at night and complain.
  9365. ** For this reason, the default name prefix is changed to be "sqlite"
  9366. ** spelled backwards. So the temp files are still identified, but
  9367. ** anybody smart enough to figure out the code is also likely smart
  9368. ** enough to know that calling the developer will not help get rid
  9369. ** of the file.
  9370. */
  9371. #ifndef SQLITE_TEMP_FILE_PREFIX
  9372. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9373. #endif
  9374. /*
  9375. ** The following values may be passed as the second argument to
  9376. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9377. **
  9378. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9379. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9380. ** any time. Other processes may hold and obtain new SHARED locks.
  9381. ** PENDING: A single process may hold a PENDING lock on a file at
  9382. ** any one time. Existing SHARED locks may persist, but no new
  9383. ** SHARED locks may be obtained by other processes.
  9384. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9385. **
  9386. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9387. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9388. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9389. ** sqlite3OsLock().
  9390. */
  9391. #define NO_LOCK 0
  9392. #define SHARED_LOCK 1
  9393. #define RESERVED_LOCK 2
  9394. #define PENDING_LOCK 3
  9395. #define EXCLUSIVE_LOCK 4
  9396. /*
  9397. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9398. **
  9399. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9400. ** those functions are not available. So we use only LockFile() and
  9401. ** UnlockFile().
  9402. **
  9403. ** LockFile() prevents not just writing but also reading by other processes.
  9404. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9405. ** byte out of a specific range of bytes. The lock byte is obtained at
  9406. ** random so two separate readers can probably access the file at the
  9407. ** same time, unless they are unlucky and choose the same lock byte.
  9408. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9409. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9410. ** a single byte of the file that is designated as the reserved lock byte.
  9411. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9412. ** the RESERVED_LOCK byte.
  9413. **
  9414. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9415. ** which means we can use reader/writer locks. When reader/writer locks
  9416. ** are used, the lock is placed on the same range of bytes that is used
  9417. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9418. ** will support two or more Win95 readers or two or more WinNT readers.
  9419. ** But a single Win95 reader will lock out all WinNT readers and a single
  9420. ** WinNT reader will lock out all other Win95 readers.
  9421. **
  9422. ** The following #defines specify the range of bytes used for locking.
  9423. ** SHARED_SIZE is the number of bytes available in the pool from which
  9424. ** a random byte is selected for a shared lock. The pool of bytes for
  9425. ** shared locks begins at SHARED_FIRST.
  9426. **
  9427. ** The same locking strategy and
  9428. ** byte ranges are used for Unix. This leaves open the possiblity of having
  9429. ** clients on win95, winNT, and unix all talking to the same shared file
  9430. ** and all locking correctly. To do so would require that samba (or whatever
  9431. ** tool is being used for file sharing) implements locks correctly between
  9432. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9433. ** using the same locking range we are at least open to the possibility.
  9434. **
  9435. ** Locking in windows is manditory. For this reason, we cannot store
  9436. ** actual data in the bytes used for locking. The pager never allocates
  9437. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9438. ** that all locks will fit on a single page even at the minimum page size.
  9439. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9440. ** is set high so that we don't have to allocate an unused page except
  9441. ** for very large databases. But one should test the page skipping logic
  9442. ** by setting PENDING_BYTE low and running the entire regression suite.
  9443. **
  9444. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9445. ** file format. Depending on how it is changed, you might not notice
  9446. ** the incompatibility right away, even running a full regression test.
  9447. ** The default location of PENDING_BYTE is the first byte past the
  9448. ** 1GB boundary.
  9449. **
  9450. */
  9451. #ifdef SQLITE_OMIT_WSD
  9452. # define PENDING_BYTE (0x40000000)
  9453. #else
  9454. # define PENDING_BYTE sqlite3PendingByte
  9455. #endif
  9456. #define RESERVED_BYTE (PENDING_BYTE+1)
  9457. #define SHARED_FIRST (PENDING_BYTE+2)
  9458. #define SHARED_SIZE 510
  9459. /*
  9460. ** Wrapper around OS specific sqlite3_os_init() function.
  9461. */
  9462. SQLITE_PRIVATE int sqlite3OsInit(void);
  9463. /*
  9464. ** Functions for accessing sqlite3_file methods
  9465. */
  9466. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9467. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9468. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9469. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9470. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9471. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9472. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9473. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9474. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9475. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9476. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9477. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9478. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9479. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9480. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9481. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9482. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9483. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9484. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9485. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9486. /*
  9487. ** Functions for accessing sqlite3_vfs methods
  9488. */
  9489. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9490. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9491. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9492. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9493. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9494. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9495. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9496. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9497. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9498. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9499. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9500. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9501. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9502. /*
  9503. ** Convenience functions for opening and closing files using
  9504. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9505. */
  9506. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9507. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9508. #endif /* _SQLITE_OS_H_ */
  9509. /************** End of os.h **************************************************/
  9510. /************** Continuing where we left off in sqliteInt.h ******************/
  9511. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9512. /************** Begin file mutex.h *******************************************/
  9513. /*
  9514. ** 2007 August 28
  9515. **
  9516. ** The author disclaims copyright to this source code. In place of
  9517. ** a legal notice, here is a blessing:
  9518. **
  9519. ** May you do good and not evil.
  9520. ** May you find forgiveness for yourself and forgive others.
  9521. ** May you share freely, never taking more than you give.
  9522. **
  9523. *************************************************************************
  9524. **
  9525. ** This file contains the common header for all mutex implementations.
  9526. ** The sqliteInt.h header #includes this file so that it is available
  9527. ** to all source files. We break it out in an effort to keep the code
  9528. ** better organized.
  9529. **
  9530. ** NOTE: source files should *not* #include this header file directly.
  9531. ** Source files should #include the sqliteInt.h file and let that file
  9532. ** include this one indirectly.
  9533. */
  9534. /*
  9535. ** Figure out what version of the code to use. The choices are
  9536. **
  9537. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9538. ** mutexes implemention cannot be overridden
  9539. ** at start-time.
  9540. **
  9541. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9542. ** mutual exclusion is provided. But this
  9543. ** implementation can be overridden at
  9544. ** start-time.
  9545. **
  9546. ** SQLITE_MUTEX_RTT For multi_threaded applications on rt-thread.
  9547. **
  9548. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9549. **
  9550. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9551. */
  9552. #if !SQLITE_THREADSAFE
  9553. # define SQLITE_MUTEX_OMIT
  9554. #endif
  9555. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9556. # if SQLITE_OS_UNIX
  9557. # define SQLITE_MUTEX_PTHREADS
  9558. # elif SQLITE_OS_WIN
  9559. # define SQLITE_MUTEX_W32
  9560. # elif SQLITE_OS_RTT
  9561. # define SQLITE_MUTEX_RTT
  9562. # else
  9563. # define SQLITE_MUTEX_NOOP
  9564. # endif
  9565. #endif
  9566. #ifdef SQLITE_MUTEX_OMIT
  9567. /*
  9568. ** If this is a no-op implementation, implement everything as macros.
  9569. */
  9570. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9571. #define sqlite3_mutex_free(X)
  9572. #define sqlite3_mutex_enter(X)
  9573. #define sqlite3_mutex_try(X) SQLITE_OK
  9574. #define sqlite3_mutex_leave(X)
  9575. #define sqlite3_mutex_held(X) ((void)(X),1)
  9576. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9577. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9578. #define sqlite3MutexInit() SQLITE_OK
  9579. #define sqlite3MutexEnd()
  9580. #define MUTEX_LOGIC(X)
  9581. #else
  9582. #define MUTEX_LOGIC(X) X
  9583. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9584. /************** End of mutex.h ***********************************************/
  9585. /************** Continuing where we left off in sqliteInt.h ******************/
  9586. /*
  9587. ** Each database file to be accessed by the system is an instance
  9588. ** of the following structure. There are normally two of these structures
  9589. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9590. ** aDb[1] is the database file used to hold temporary tables. Additional
  9591. ** databases may be attached.
  9592. */
  9593. struct Db {
  9594. char *zName; /* Name of this database */
  9595. Btree *pBt; /* The B*Tree structure for this database file */
  9596. u8 safety_level; /* How aggressive at syncing data to disk */
  9597. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9598. };
  9599. /*
  9600. ** An instance of the following structure stores a database schema.
  9601. **
  9602. ** Most Schema objects are associated with a Btree. The exception is
  9603. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9604. ** In shared cache mode, a single Schema object can be shared by multiple
  9605. ** Btrees that refer to the same underlying BtShared object.
  9606. **
  9607. ** Schema objects are automatically deallocated when the last Btree that
  9608. ** references them is destroyed. The TEMP Schema is manually freed by
  9609. ** sqlite3_close().
  9610. *
  9611. ** A thread must be holding a mutex on the corresponding Btree in order
  9612. ** to access Schema content. This implies that the thread must also be
  9613. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  9614. ** For a TEMP Schema, only the connection mutex is required.
  9615. */
  9616. struct Schema {
  9617. int schema_cookie; /* Database schema version number for this file */
  9618. int iGeneration; /* Generation counter. Incremented with each change */
  9619. Hash tblHash; /* All tables indexed by name */
  9620. Hash idxHash; /* All (named) indices indexed by name */
  9621. Hash trigHash; /* All triggers indexed by name */
  9622. Hash fkeyHash; /* All foreign keys by referenced table name */
  9623. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  9624. u8 file_format; /* Schema format version for this file */
  9625. u8 enc; /* Text encoding used by this database */
  9626. u16 flags; /* Flags associated with this schema */
  9627. int cache_size; /* Number of pages to use in the cache */
  9628. };
  9629. /*
  9630. ** These macros can be used to test, set, or clear bits in the
  9631. ** Db.pSchema->flags field.
  9632. */
  9633. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))==(P))
  9634. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->flags&(P))!=0)
  9635. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->flags|=(P)
  9636. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->flags&=~(P)
  9637. /*
  9638. ** Allowed values for the DB.pSchema->flags field.
  9639. **
  9640. ** The DB_SchemaLoaded flag is set after the database schema has been
  9641. ** read into internal hash tables.
  9642. **
  9643. ** DB_UnresetViews means that one or more views have column names that
  9644. ** have been filled out. If the schema changes, these column names might
  9645. ** changes and so the view will need to be reset.
  9646. */
  9647. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  9648. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  9649. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  9650. /*
  9651. ** The number of different kinds of things that can be limited
  9652. ** using the sqlite3_limit() interface.
  9653. */
  9654. #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
  9655. /*
  9656. ** Lookaside malloc is a set of fixed-size buffers that can be used
  9657. ** to satisfy small transient memory allocation requests for objects
  9658. ** associated with a particular database connection. The use of
  9659. ** lookaside malloc provides a significant performance enhancement
  9660. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  9661. ** SQL statements.
  9662. **
  9663. ** The Lookaside structure holds configuration information about the
  9664. ** lookaside malloc subsystem. Each available memory allocation in
  9665. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  9666. ** objects.
  9667. **
  9668. ** Lookaside allocations are only allowed for objects that are associated
  9669. ** with a particular database connection. Hence, schema information cannot
  9670. ** be stored in lookaside because in shared cache mode the schema information
  9671. ** is shared by multiple database connections. Therefore, while parsing
  9672. ** schema information, the Lookaside.bEnabled flag is cleared so that
  9673. ** lookaside allocations are not used to construct the schema objects.
  9674. */
  9675. struct Lookaside {
  9676. u16 sz; /* Size of each buffer in bytes */
  9677. u8 bEnabled; /* False to disable new lookaside allocations */
  9678. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  9679. int nOut; /* Number of buffers currently checked out */
  9680. int mxOut; /* Highwater mark for nOut */
  9681. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  9682. LookasideSlot *pFree; /* List of available buffers */
  9683. void *pStart; /* First byte of available memory space */
  9684. void *pEnd; /* First byte past end of available space */
  9685. };
  9686. struct LookasideSlot {
  9687. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  9688. };
  9689. /*
  9690. ** A hash table for function definitions.
  9691. **
  9692. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  9693. ** Collisions are on the FuncDef.pHash chain.
  9694. */
  9695. struct FuncDefHash {
  9696. FuncDef *a[23]; /* Hash table for functions */
  9697. };
  9698. /*
  9699. ** Each database connection is an instance of the following structure.
  9700. */
  9701. struct sqlite3 {
  9702. sqlite3_vfs *pVfs; /* OS Interface */
  9703. struct Vdbe *pVdbe; /* List of active virtual machines */
  9704. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  9705. sqlite3_mutex *mutex; /* Connection mutex */
  9706. Db *aDb; /* All backends */
  9707. int nDb; /* Number of backends currently in use */
  9708. int flags; /* Miscellaneous flags. See below */
  9709. i64 lastRowid; /* ROWID of most recent insert (see above) */
  9710. i64 szMmap; /* Default mmap_size setting */
  9711. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  9712. int errCode; /* Most recent error code (SQLITE_*) */
  9713. int errMask; /* & result codes with this before returning */
  9714. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  9715. u8 autoCommit; /* The auto-commit flag. */
  9716. u8 temp_store; /* 1: file 2: memory 0: default */
  9717. u8 mallocFailed; /* True if we have seen a malloc failure */
  9718. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  9719. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  9720. u8 suppressErr; /* Do not issue error messages if true */
  9721. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  9722. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  9723. int nextPagesize; /* Pagesize after VACUUM if >0 */
  9724. u32 magic; /* Magic number for detect library misuse */
  9725. int nChange; /* Value returned by sqlite3_changes() */
  9726. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  9727. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  9728. struct sqlite3InitInfo { /* Information used during initialization */
  9729. int newTnum; /* Rootpage of table being initialized */
  9730. u8 iDb; /* Which db file is being initialized */
  9731. u8 busy; /* TRUE if currently initializing */
  9732. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  9733. } init;
  9734. int nVdbeActive; /* Number of VDBEs currently running */
  9735. int nVdbeRead; /* Number of active VDBEs that read or write */
  9736. int nVdbeWrite; /* Number of active VDBEs that read and write */
  9737. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  9738. int nExtension; /* Number of loaded extensions */
  9739. void **aExtension; /* Array of shared library handles */
  9740. void (*xTrace)(void*,const char*); /* Trace function */
  9741. void *pTraceArg; /* Argument to the trace function */
  9742. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  9743. void *pProfileArg; /* Argument to profile function */
  9744. void *pCommitArg; /* Argument to xCommitCallback() */
  9745. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  9746. void *pRollbackArg; /* Argument to xRollbackCallback() */
  9747. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  9748. void *pUpdateArg;
  9749. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  9750. #ifndef SQLITE_OMIT_WAL
  9751. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  9752. void *pWalArg;
  9753. #endif
  9754. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  9755. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  9756. void *pCollNeededArg;
  9757. sqlite3_value *pErr; /* Most recent error message */
  9758. union {
  9759. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  9760. double notUsed1; /* Spacer */
  9761. } u1;
  9762. Lookaside lookaside; /* Lookaside malloc configuration */
  9763. #ifndef SQLITE_OMIT_AUTHORIZATION
  9764. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  9765. /* Access authorization function */
  9766. void *pAuthArg; /* 1st argument to the access auth function */
  9767. #endif
  9768. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  9769. int (*xProgress)(void *); /* The progress callback */
  9770. void *pProgressArg; /* Argument to the progress callback */
  9771. unsigned nProgressOps; /* Number of opcodes for progress callback */
  9772. #endif
  9773. #ifndef SQLITE_OMIT_VIRTUALTABLE
  9774. int nVTrans; /* Allocated size of aVTrans */
  9775. Hash aModule; /* populated by sqlite3_create_module() */
  9776. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  9777. VTable **aVTrans; /* Virtual tables with open transactions */
  9778. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  9779. #endif
  9780. FuncDefHash aFunc; /* Hash table of connection functions */
  9781. Hash aCollSeq; /* All collating sequences */
  9782. BusyHandler busyHandler; /* Busy callback */
  9783. Db aDbStatic[2]; /* Static space for the 2 default backends */
  9784. Savepoint *pSavepoint; /* List of active savepoints */
  9785. int busyTimeout; /* Busy handler timeout, in msec */
  9786. int nSavepoint; /* Number of non-transaction savepoints */
  9787. int nStatement; /* Number of nested statement-transactions */
  9788. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  9789. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  9790. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  9791. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  9792. /* The following variables are all protected by the STATIC_MASTER
  9793. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  9794. **
  9795. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  9796. ** unlock so that it can proceed.
  9797. **
  9798. ** When X.pBlockingConnection==Y, that means that something that X tried
  9799. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  9800. ** held by Y.
  9801. */
  9802. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  9803. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  9804. void *pUnlockArg; /* Argument to xUnlockNotify */
  9805. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  9806. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  9807. #endif
  9808. };
  9809. /*
  9810. ** A macro to discover the encoding of a database.
  9811. */
  9812. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  9813. /*
  9814. ** Possible values for the sqlite3.flags.
  9815. */
  9816. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  9817. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  9818. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  9819. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  9820. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  9821. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  9822. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  9823. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  9824. /* DELETE, or UPDATE and return */
  9825. /* the count using a callback. */
  9826. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  9827. /* result set is empty */
  9828. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  9829. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  9830. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  9831. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  9832. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  9833. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  9834. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  9835. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  9836. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  9837. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  9838. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  9839. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  9840. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  9841. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  9842. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  9843. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  9844. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  9845. /*
  9846. ** Bits of the sqlite3.dbOptFlags field that are used by the
  9847. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  9848. ** selectively disable various optimizations.
  9849. */
  9850. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  9851. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  9852. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  9853. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  9854. #define SQLITE_IdxRealAsInt 0x0010 /* Store REAL as INT in indices */
  9855. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  9856. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  9857. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  9858. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  9859. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  9860. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  9861. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  9862. #define SQLITE_AdjustOutEst 0x1000 /* Adjust output estimates using WHERE */
  9863. #define SQLITE_AllOpts 0xffff /* All optimizations */
  9864. /*
  9865. ** Macros for testing whether or not optimizations are enabled or disabled.
  9866. */
  9867. #ifndef SQLITE_OMIT_BUILTIN_TEST
  9868. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  9869. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  9870. #else
  9871. #define OptimizationDisabled(db, mask) 0
  9872. #define OptimizationEnabled(db, mask) 1
  9873. #endif
  9874. /*
  9875. ** Possible values for the sqlite.magic field.
  9876. ** The numbers are obtained at random and have no special meaning, other
  9877. ** than being distinct from one another.
  9878. */
  9879. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  9880. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  9881. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  9882. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  9883. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  9884. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  9885. /*
  9886. ** Each SQL function is defined by an instance of the following
  9887. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  9888. ** hash table. When multiple functions have the same name, the hash table
  9889. ** points to a linked list of these structures.
  9890. */
  9891. struct FuncDef {
  9892. i16 nArg; /* Number of arguments. -1 means unlimited */
  9893. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  9894. void *pUserData; /* User data parameter */
  9895. FuncDef *pNext; /* Next function with same name */
  9896. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  9897. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  9898. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  9899. char *zName; /* SQL name of the function. */
  9900. FuncDef *pHash; /* Next with a different name but the same hash */
  9901. FuncDestructor *pDestructor; /* Reference counted destructor function */
  9902. };
  9903. /*
  9904. ** This structure encapsulates a user-function destructor callback (as
  9905. ** configured using create_function_v2()) and a reference counter. When
  9906. ** create_function_v2() is called to create a function with a destructor,
  9907. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  9908. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  9909. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  9910. ** member of each of the new FuncDef objects is set to point to the allocated
  9911. ** FuncDestructor.
  9912. **
  9913. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  9914. ** count on this object is decremented. When it reaches 0, the destructor
  9915. ** is invoked and the FuncDestructor structure freed.
  9916. */
  9917. struct FuncDestructor {
  9918. int nRef;
  9919. void (*xDestroy)(void *);
  9920. void *pUserData;
  9921. };
  9922. /*
  9923. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  9924. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  9925. ** are assert() statements in the code to verify this.
  9926. */
  9927. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  9928. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  9929. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  9930. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  9931. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  9932. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  9933. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  9934. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  9935. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  9936. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  9937. /*
  9938. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  9939. ** used to create the initializers for the FuncDef structures.
  9940. **
  9941. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  9942. ** Used to create a scalar function definition of a function zName
  9943. ** implemented by C function xFunc that accepts nArg arguments. The
  9944. ** value passed as iArg is cast to a (void*) and made available
  9945. ** as the user-data (sqlite3_user_data()) for the function. If
  9946. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  9947. **
  9948. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  9949. ** Used to create an aggregate function definition implemented by
  9950. ** the C functions xStep and xFinal. The first four parameters
  9951. ** are interpreted in the same way as the first 4 parameters to
  9952. ** FUNCTION().
  9953. **
  9954. ** LIKEFUNC(zName, nArg, pArg, flags)
  9955. ** Used to create a scalar function definition of a function zName
  9956. ** that accepts nArg arguments and is implemented by a call to C
  9957. ** function likeFunc. Argument pArg is cast to a (void *) and made
  9958. ** available as the function user-data (sqlite3_user_data()). The
  9959. ** FuncDef.flags variable is set to the value passed as the flags
  9960. ** parameter.
  9961. */
  9962. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  9963. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9964. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9965. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  9966. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  9967. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  9968. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  9969. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  9970. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  9971. #define LIKEFUNC(zName, nArg, arg, flags) \
  9972. {nArg, SQLITE_UTF8|flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  9973. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  9974. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  9975. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  9976. /*
  9977. ** All current savepoints are stored in a linked list starting at
  9978. ** sqlite3.pSavepoint. The first element in the list is the most recently
  9979. ** opened savepoint. Savepoints are added to the list by the vdbe
  9980. ** OP_Savepoint instruction.
  9981. */
  9982. struct Savepoint {
  9983. char *zName; /* Savepoint name (nul-terminated) */
  9984. i64 nDeferredCons; /* Number of deferred fk violations */
  9985. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  9986. Savepoint *pNext; /* Parent savepoint (if any) */
  9987. };
  9988. /*
  9989. ** The following are used as the second parameter to sqlite3Savepoint(),
  9990. ** and as the P1 argument to the OP_Savepoint instruction.
  9991. */
  9992. #define SAVEPOINT_BEGIN 0
  9993. #define SAVEPOINT_RELEASE 1
  9994. #define SAVEPOINT_ROLLBACK 2
  9995. /*
  9996. ** Each SQLite module (virtual table definition) is defined by an
  9997. ** instance of the following structure, stored in the sqlite3.aModule
  9998. ** hash table.
  9999. */
  10000. struct Module {
  10001. const sqlite3_module *pModule; /* Callback pointers */
  10002. const char *zName; /* Name passed to create_module() */
  10003. void *pAux; /* pAux passed to create_module() */
  10004. void (*xDestroy)(void *); /* Module destructor function */
  10005. };
  10006. /*
  10007. ** information about each column of an SQL table is held in an instance
  10008. ** of this structure.
  10009. */
  10010. struct Column {
  10011. char *zName; /* Name of this column */
  10012. Expr *pDflt; /* Default value of this column */
  10013. char *zDflt; /* Original text of the default value */
  10014. char *zType; /* Data type for this column */
  10015. char *zColl; /* Collating sequence. If NULL, use the default */
  10016. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10017. char affinity; /* One of the SQLITE_AFF_... values */
  10018. u8 szEst; /* Estimated size of this column. INT==1 */
  10019. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10020. };
  10021. /* Allowed values for Column.colFlags:
  10022. */
  10023. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10024. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10025. /*
  10026. ** A "Collating Sequence" is defined by an instance of the following
  10027. ** structure. Conceptually, a collating sequence consists of a name and
  10028. ** a comparison routine that defines the order of that sequence.
  10029. **
  10030. ** If CollSeq.xCmp is NULL, it means that the
  10031. ** collating sequence is undefined. Indices built on an undefined
  10032. ** collating sequence may not be read or written.
  10033. */
  10034. struct CollSeq {
  10035. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10036. u8 enc; /* Text encoding handled by xCmp() */
  10037. void *pUser; /* First argument to xCmp() */
  10038. int (*xCmp)(void*,int, const void*, int, const void*);
  10039. void (*xDel)(void*); /* Destructor for pUser */
  10040. };
  10041. /*
  10042. ** A sort order can be either ASC or DESC.
  10043. */
  10044. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10045. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10046. /*
  10047. ** Column affinity types.
  10048. **
  10049. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10050. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10051. ** the speed a little by numbering the values consecutively.
  10052. **
  10053. ** But rather than start with 0 or 1, we begin with 'a'. That way,
  10054. ** when multiple affinity types are concatenated into a string and
  10055. ** used as the P4 operand, they will be more readable.
  10056. **
  10057. ** Note also that the numeric types are grouped together so that testing
  10058. ** for a numeric type is a single comparison.
  10059. */
  10060. #define SQLITE_AFF_TEXT 'a'
  10061. #define SQLITE_AFF_NONE 'b'
  10062. #define SQLITE_AFF_NUMERIC 'c'
  10063. #define SQLITE_AFF_INTEGER 'd'
  10064. #define SQLITE_AFF_REAL 'e'
  10065. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10066. /*
  10067. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10068. ** affinity value.
  10069. */
  10070. #define SQLITE_AFF_MASK 0x67
  10071. /*
  10072. ** Additional bit values that can be ORed with an affinity without
  10073. ** changing the affinity.
  10074. */
  10075. #define SQLITE_JUMPIFNULL 0x08 /* jumps if either operand is NULL */
  10076. #define SQLITE_STOREP2 0x10 /* Store result in reg[P2] rather than jump */
  10077. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10078. /*
  10079. ** An object of this type is created for each virtual table present in
  10080. ** the database schema.
  10081. **
  10082. ** If the database schema is shared, then there is one instance of this
  10083. ** structure for each database connection (sqlite3*) that uses the shared
  10084. ** schema. This is because each database connection requires its own unique
  10085. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10086. ** implementation. sqlite3_vtab* handles can not be shared between
  10087. ** database connections, even when the rest of the in-memory database
  10088. ** schema is shared, as the implementation often stores the database
  10089. ** connection handle passed to it via the xConnect() or xCreate() method
  10090. ** during initialization internally. This database connection handle may
  10091. ** then be used by the virtual table implementation to access real tables
  10092. ** within the database. So that they appear as part of the callers
  10093. ** transaction, these accesses need to be made via the same database
  10094. ** connection as that used to execute SQL operations on the virtual table.
  10095. **
  10096. ** All VTable objects that correspond to a single table in a shared
  10097. ** database schema are initially stored in a linked-list pointed to by
  10098. ** the Table.pVTable member variable of the corresponding Table object.
  10099. ** When an sqlite3_prepare() operation is required to access the virtual
  10100. ** table, it searches the list for the VTable that corresponds to the
  10101. ** database connection doing the preparing so as to use the correct
  10102. ** sqlite3_vtab* handle in the compiled query.
  10103. **
  10104. ** When an in-memory Table object is deleted (for example when the
  10105. ** schema is being reloaded for some reason), the VTable objects are not
  10106. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10107. ** immediately. Instead, they are moved from the Table.pVTable list to
  10108. ** another linked list headed by the sqlite3.pDisconnect member of the
  10109. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10110. ** next time a statement is prepared using said sqlite3*. This is done
  10111. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10112. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10113. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10114. ** list without holding the corresponding sqlite3.mutex mutex.
  10115. **
  10116. ** The memory for objects of this type is always allocated by
  10117. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10118. ** the first argument.
  10119. */
  10120. struct VTable {
  10121. sqlite3 *db; /* Database connection associated with this table */
  10122. Module *pMod; /* Pointer to module implementation */
  10123. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10124. int nRef; /* Number of pointers to this structure */
  10125. u8 bConstraint; /* True if constraints are supported */
  10126. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10127. VTable *pNext; /* Next in linked list (see above) */
  10128. };
  10129. /*
  10130. ** Each SQL table is represented in memory by an instance of the
  10131. ** following structure.
  10132. **
  10133. ** Table.zName is the name of the table. The case of the original
  10134. ** CREATE TABLE statement is stored, but case is not significant for
  10135. ** comparisons.
  10136. **
  10137. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10138. ** pointer to an array of Column structures, one for each column.
  10139. **
  10140. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10141. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10142. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10143. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10144. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10145. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10146. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10147. **
  10148. ** Table.tnum is the page number for the root BTree page of the table in the
  10149. ** database file. If Table.iDb is the index of the database table backend
  10150. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10151. ** holds temporary tables and indices. If TF_Ephemeral is set
  10152. ** then the table is stored in a file that is automatically deleted
  10153. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10154. ** refers VDBE cursor number that holds the table open, not to the root
  10155. ** page number. Transient tables are used to hold the results of a
  10156. ** sub-query that appears instead of a real table name in the FROM clause
  10157. ** of a SELECT statement.
  10158. */
  10159. struct Table {
  10160. char *zName; /* Name of the table or view */
  10161. Column *aCol; /* Information about each column */
  10162. Index *pIndex; /* List of SQL indexes on this table. */
  10163. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10164. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10165. char *zColAff; /* String defining the affinity of each column */
  10166. #ifndef SQLITE_OMIT_CHECK
  10167. ExprList *pCheck; /* All CHECK constraints */
  10168. #endif
  10169. tRowcnt nRowEst; /* Estimated rows in table - from sqlite_stat1 table */
  10170. int tnum; /* Root BTree node for this table (see note above) */
  10171. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10172. i16 nCol; /* Number of columns in this table */
  10173. u16 nRef; /* Number of pointers to this Table */
  10174. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10175. u8 tabFlags; /* Mask of TF_* values */
  10176. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10177. #ifndef SQLITE_OMIT_ALTERTABLE
  10178. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10179. #endif
  10180. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10181. int nModuleArg; /* Number of arguments to the module */
  10182. char **azModuleArg; /* Text of all module args. [0] is module name */
  10183. VTable *pVTable; /* List of VTable objects. */
  10184. #endif
  10185. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10186. Schema *pSchema; /* Schema that contains this table */
  10187. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10188. };
  10189. /*
  10190. ** Allowed values for Tabe.tabFlags.
  10191. */
  10192. #define TF_Readonly 0x01 /* Read-only system table */
  10193. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10194. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10195. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10196. #define TF_Virtual 0x10 /* Is a virtual table */
  10197. /*
  10198. ** Test to see whether or not a table is a virtual table. This is
  10199. ** done as a macro so that it will be optimized out when virtual
  10200. ** table support is omitted from the build.
  10201. */
  10202. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10203. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10204. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10205. #else
  10206. # define IsVirtual(X) 0
  10207. # define IsHiddenColumn(X) 0
  10208. #endif
  10209. /*
  10210. ** Each foreign key constraint is an instance of the following structure.
  10211. **
  10212. ** A foreign key is associated with two tables. The "from" table is
  10213. ** the table that contains the REFERENCES clause that creates the foreign
  10214. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10215. ** Consider this example:
  10216. **
  10217. ** CREATE TABLE ex1(
  10218. ** a INTEGER PRIMARY KEY,
  10219. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10220. ** );
  10221. **
  10222. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10223. **
  10224. ** Each REFERENCES clause generates an instance of the following structure
  10225. ** which is attached to the from-table. The to-table need not exist when
  10226. ** the from-table is created. The existence of the to-table is not checked.
  10227. */
  10228. struct FKey {
  10229. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10230. FKey *pNextFrom; /* Next foreign key in pFrom */
  10231. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10232. FKey *pNextTo; /* Next foreign key on table named zTo */
  10233. FKey *pPrevTo; /* Previous foreign key on table named zTo */
  10234. int nCol; /* Number of columns in this key */
  10235. /* EV: R-30323-21917 */
  10236. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10237. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10238. Trigger *apTrigger[2]; /* Triggers for aAction[] actions */
  10239. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10240. int iFrom; /* Index of column in pFrom */
  10241. char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  10242. } aCol[1]; /* One entry for each of nCol column s */
  10243. };
  10244. /*
  10245. ** SQLite supports many different ways to resolve a constraint
  10246. ** error. ROLLBACK processing means that a constraint violation
  10247. ** causes the operation in process to fail and for the current transaction
  10248. ** to be rolled back. ABORT processing means the operation in process
  10249. ** fails and any prior changes from that one operation are backed out,
  10250. ** but the transaction is not rolled back. FAIL processing means that
  10251. ** the operation in progress stops and returns an error code. But prior
  10252. ** changes due to the same operation are not backed out and no rollback
  10253. ** occurs. IGNORE means that the particular row that caused the constraint
  10254. ** error is not inserted or updated. Processing continues and no error
  10255. ** is returned. REPLACE means that preexisting database rows that caused
  10256. ** a UNIQUE constraint violation are removed so that the new insert or
  10257. ** update can proceed. Processing continues and no error is reported.
  10258. **
  10259. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10260. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10261. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10262. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10263. ** referenced table row is propagated into the row that holds the
  10264. ** foreign key.
  10265. **
  10266. ** The following symbolic values are used to record which type
  10267. ** of action to take.
  10268. */
  10269. #define OE_None 0 /* There is no constraint to check */
  10270. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10271. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10272. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10273. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10274. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10275. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10276. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10277. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10278. #define OE_Cascade 9 /* Cascade the changes */
  10279. #define OE_Default 10 /* Do whatever the default action is */
  10280. /*
  10281. ** An instance of the following structure is passed as the first
  10282. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10283. ** comparison of the two index keys.
  10284. **
  10285. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10286. ** are nField slots for the columns of an index then one extra slot
  10287. ** for the rowid at the end.
  10288. */
  10289. struct KeyInfo {
  10290. sqlite3 *db; /* The database connection */
  10291. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10292. u16 nField; /* Maximum index for aColl[] and aSortOrder[] */
  10293. u8 *aSortOrder; /* Sort order for each column. */
  10294. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10295. };
  10296. /*
  10297. ** An instance of the following structure holds information about a
  10298. ** single index record that has already been parsed out into individual
  10299. ** values.
  10300. **
  10301. ** A record is an object that contains one or more fields of data.
  10302. ** Records are used to store the content of a table row and to store
  10303. ** the key of an index. A blob encoding of a record is created by
  10304. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10305. ** OP_Column opcode.
  10306. **
  10307. ** This structure holds a record that has already been disassembled
  10308. ** into its constituent fields.
  10309. */
  10310. struct UnpackedRecord {
  10311. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10312. u16 nField; /* Number of entries in apMem[] */
  10313. u8 flags; /* Boolean settings. UNPACKED_... below */
  10314. i64 rowid; /* Used by UNPACKED_PREFIX_SEARCH */
  10315. Mem *aMem; /* Values */
  10316. };
  10317. /*
  10318. ** Allowed values of UnpackedRecord.flags
  10319. */
  10320. #define UNPACKED_INCRKEY 0x01 /* Make this key an epsilon larger */
  10321. #define UNPACKED_PREFIX_MATCH 0x02 /* A prefix match is considered OK */
  10322. #define UNPACKED_PREFIX_SEARCH 0x04 /* Ignore final (rowid) field */
  10323. /*
  10324. ** Each SQL index is represented in memory by an
  10325. ** instance of the following structure.
  10326. **
  10327. ** The columns of the table that are to be indexed are described
  10328. ** by the aiColumn[] field of this structure. For example, suppose
  10329. ** we have the following table and index:
  10330. **
  10331. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10332. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10333. **
  10334. ** In the Table structure describing Ex1, nCol==3 because there are
  10335. ** three columns in the table. In the Index structure describing
  10336. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10337. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10338. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10339. ** The second column to be indexed (c1) has an index of 0 in
  10340. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10341. **
  10342. ** The Index.onError field determines whether or not the indexed columns
  10343. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10344. ** it means this is not a unique index. Otherwise it is a unique index
  10345. ** and the value of Index.onError indicate the which conflict resolution
  10346. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10347. ** element.
  10348. */
  10349. struct Index {
  10350. char *zName; /* Name of this index */
  10351. int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10352. tRowcnt *aiRowEst; /* From ANALYZE: Est. rows selected by each column */
  10353. Table *pTable; /* The SQL table being indexed */
  10354. char *zColAff; /* String defining the affinity of each column */
  10355. Index *pNext; /* The next index associated with the same table */
  10356. Schema *pSchema; /* Schema containing this index */
  10357. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10358. char **azColl; /* Array of collation sequence names for index */
  10359. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10360. int tnum; /* DB Page containing root of this index */
  10361. LogEst szIdxRow; /* Estimated average row size in bytes */
  10362. u16 nColumn; /* Number of columns in table used by this index */
  10363. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10364. unsigned autoIndex:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10365. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10366. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10367. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10368. int nSample; /* Number of elements in aSample[] */
  10369. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10370. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10371. IndexSample *aSample; /* Samples of the left-most key */
  10372. #endif
  10373. };
  10374. /*
  10375. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10376. ** using a structure of this type. See documentation at the top of the
  10377. ** analyze.c source file for additional information.
  10378. */
  10379. struct IndexSample {
  10380. void *p; /* Pointer to sampled record */
  10381. int n; /* Size of record in bytes */
  10382. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10383. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10384. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10385. };
  10386. /*
  10387. ** Each token coming out of the lexer is an instance of
  10388. ** this structure. Tokens are also used as part of an expression.
  10389. **
  10390. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10391. ** may contain random values. Do not make any assumptions about Token.dyn
  10392. ** and Token.n when Token.z==0.
  10393. */
  10394. struct Token {
  10395. const char *z; /* Text of the token. Not NULL-terminated! */
  10396. unsigned int n; /* Number of characters in this token */
  10397. };
  10398. /*
  10399. ** An instance of this structure contains information needed to generate
  10400. ** code for a SELECT that contains aggregate functions.
  10401. **
  10402. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10403. ** pointer to this structure. The Expr.iColumn field is the index in
  10404. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10405. ** code for that node.
  10406. **
  10407. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10408. ** original Select structure that describes the SELECT statement. These
  10409. ** fields do not need to be freed when deallocating the AggInfo structure.
  10410. */
  10411. struct AggInfo {
  10412. u8 directMode; /* Direct rendering mode means take data directly
  10413. ** from source tables rather than from accumulators */
  10414. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10415. ** than the source table */
  10416. int sortingIdx; /* Cursor number of the sorting index */
  10417. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10418. int nSortingColumn; /* Number of columns in the sorting index */
  10419. ExprList *pGroupBy; /* The group by clause */
  10420. struct AggInfo_col { /* For each column used in source tables */
  10421. Table *pTab; /* Source table */
  10422. int iTable; /* Cursor number of the source table */
  10423. int iColumn; /* Column number within the source table */
  10424. int iSorterColumn; /* Column number in the sorting index */
  10425. int iMem; /* Memory location that acts as accumulator */
  10426. Expr *pExpr; /* The original expression */
  10427. } *aCol;
  10428. int nColumn; /* Number of used entries in aCol[] */
  10429. int nAccumulator; /* Number of columns that show through to the output.
  10430. ** Additional columns are used only as parameters to
  10431. ** aggregate functions */
  10432. struct AggInfo_func { /* For each aggregate function */
  10433. Expr *pExpr; /* Expression encoding the function */
  10434. FuncDef *pFunc; /* The aggregate function implementation */
  10435. int iMem; /* Memory location that acts as accumulator */
  10436. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10437. } *aFunc;
  10438. int nFunc; /* Number of entries in aFunc[] */
  10439. };
  10440. /*
  10441. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10442. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10443. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10444. ** it uses less memory in the Expr object, which is a big memory user
  10445. ** in systems with lots of prepared statements. And few applications
  10446. ** need more than about 10 or 20 variables. But some extreme users want
  10447. ** to have prepared statements with over 32767 variables, and for them
  10448. ** the option is available (at compile-time).
  10449. */
  10450. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10451. typedef i16 ynVar;
  10452. #else
  10453. typedef int ynVar;
  10454. #endif
  10455. /*
  10456. ** Each node of an expression in the parse tree is an instance
  10457. ** of this structure.
  10458. **
  10459. ** Expr.op is the opcode. The integer parser token codes are reused
  10460. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10461. ** code representing the ">=" operator. This same integer code is reused
  10462. ** to represent the greater-than-or-equal-to operator in the expression
  10463. ** tree.
  10464. **
  10465. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10466. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10467. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10468. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10469. ** then Expr.token contains the name of the function.
  10470. **
  10471. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10472. ** binary operator. Either or both may be NULL.
  10473. **
  10474. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10475. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10476. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10477. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10478. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10479. ** valid.
  10480. **
  10481. ** An expression of the form ID or ID.ID refers to a column in a table.
  10482. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10483. ** the integer cursor number of a VDBE cursor pointing to that table and
  10484. ** Expr.iColumn is the column number for the specific column. If the
  10485. ** expression is used as a result in an aggregate SELECT, then the
  10486. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10487. ** it can be accessed after all aggregates are computed.
  10488. **
  10489. ** If the expression is an unbound variable marker (a question mark
  10490. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10491. ** number for that variable.
  10492. **
  10493. ** If the expression is a subquery then Expr.iColumn holds an integer
  10494. ** register number containing the result of the subquery. If the
  10495. ** subquery gives a constant result, then iTable is -1. If the subquery
  10496. ** gives a different answer at different times during statement processing
  10497. ** then iTable is the address of a subroutine that computes the subquery.
  10498. **
  10499. ** If the Expr is of type OP_Column, and the table it is selecting from
  10500. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10501. ** corresponding table definition.
  10502. **
  10503. ** ALLOCATION NOTES:
  10504. **
  10505. ** Expr objects can use a lot of memory space in database schema. To
  10506. ** help reduce memory requirements, sometimes an Expr object will be
  10507. ** truncated. And to reduce the number of memory allocations, sometimes
  10508. ** two or more Expr objects will be stored in a single memory allocation,
  10509. ** together with Expr.zToken strings.
  10510. **
  10511. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10512. ** an Expr object is truncated. When EP_Reduced is set, then all
  10513. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  10514. ** are contained within the same memory allocation. Note, however, that
  10515. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  10516. ** allocated, regardless of whether or not EP_Reduced is set.
  10517. */
  10518. struct Expr {
  10519. u8 op; /* Operation performed by this node */
  10520. char affinity; /* The affinity of the column or 0 if not a column */
  10521. u32 flags; /* Various flags. EP_* See below */
  10522. union {
  10523. char *zToken; /* Token value. Zero terminated and dequoted */
  10524. int iValue; /* Non-negative integer value if EP_IntValue */
  10525. } u;
  10526. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  10527. ** space is allocated for the fields below this point. An attempt to
  10528. ** access them will result in a segfault or malfunction.
  10529. *********************************************************************/
  10530. Expr *pLeft; /* Left subnode */
  10531. Expr *pRight; /* Right subnode */
  10532. union {
  10533. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  10534. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  10535. } x;
  10536. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  10537. ** space is allocated for the fields below this point. An attempt to
  10538. ** access them will result in a segfault or malfunction.
  10539. *********************************************************************/
  10540. #if SQLITE_MAX_EXPR_DEPTH>0
  10541. int nHeight; /* Height of the tree headed by this node */
  10542. #endif
  10543. int iTable; /* TK_COLUMN: cursor number of table holding column
  10544. ** TK_REGISTER: register number
  10545. ** TK_TRIGGER: 1 -> new, 0 -> old
  10546. ** EP_Unlikely: 1000 times likelihood */
  10547. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  10548. ** TK_VARIABLE: variable number (always >= 1). */
  10549. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  10550. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  10551. u8 op2; /* TK_REGISTER: original value of Expr.op
  10552. ** TK_COLUMN: the value of p5 for OP_Column
  10553. ** TK_AGG_FUNCTION: nesting depth */
  10554. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  10555. Table *pTab; /* Table for TK_COLUMN expressions. */
  10556. };
  10557. /*
  10558. ** The following are the meanings of bits in the Expr.flags field.
  10559. */
  10560. #define EP_FromJoin 0x000001 /* Originated in ON or USING clause of a join */
  10561. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  10562. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  10563. #define EP_Error 0x000008 /* Expression contains one or more errors */
  10564. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  10565. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  10566. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  10567. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  10568. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE opeartor */
  10569. #define EP_FixedDest 0x000200 /* Result needed in a specific register */
  10570. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  10571. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  10572. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  10573. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  10574. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  10575. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  10576. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  10577. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  10578. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  10579. /*
  10580. ** These macros can be used to test, set, or clear bits in the
  10581. ** Expr.flags field.
  10582. */
  10583. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  10584. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  10585. #define ExprSetProperty(E,P) (E)->flags|=(P)
  10586. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  10587. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  10588. ** and Accreditation only. It works like ExprSetProperty() during VVA
  10589. ** processes but is a no-op for delivery.
  10590. */
  10591. #ifdef SQLITE_DEBUG
  10592. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  10593. #else
  10594. # define ExprSetVVAProperty(E,P)
  10595. #endif
  10596. /*
  10597. ** Macros to determine the number of bytes required by a normal Expr
  10598. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  10599. ** and an Expr struct with the EP_TokenOnly flag set.
  10600. */
  10601. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  10602. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  10603. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  10604. /*
  10605. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  10606. ** above sqlite3ExprDup() for details.
  10607. */
  10608. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  10609. /*
  10610. ** A list of expressions. Each expression may optionally have a
  10611. ** name. An expr/name combination can be used in several ways, such
  10612. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  10613. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  10614. ** also be used as the argument to a function, in which case the a.zName
  10615. ** field is not used.
  10616. **
  10617. ** By default the Expr.zSpan field holds a human-readable description of
  10618. ** the expression that is used in the generation of error messages and
  10619. ** column labels. In this case, Expr.zSpan is typically the text of a
  10620. ** column expression as it exists in a SELECT statement. However, if
  10621. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  10622. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  10623. ** form is used for name resolution with nested FROM clauses.
  10624. */
  10625. struct ExprList {
  10626. int nExpr; /* Number of expressions on the list */
  10627. int iECursor; /* VDBE Cursor associated with this ExprList */
  10628. struct ExprList_item { /* For each expression in the list */
  10629. Expr *pExpr; /* The list of expressions */
  10630. char *zName; /* Token associated with this expression */
  10631. char *zSpan; /* Original text of the expression */
  10632. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  10633. unsigned done :1; /* A flag to indicate when processing is finished */
  10634. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  10635. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  10636. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  10637. } *a; /* Alloc a power of two greater or equal to nExpr */
  10638. };
  10639. /*
  10640. ** An instance of this structure is used by the parser to record both
  10641. ** the parse tree for an expression and the span of input text for an
  10642. ** expression.
  10643. */
  10644. struct ExprSpan {
  10645. Expr *pExpr; /* The expression parse tree */
  10646. const char *zStart; /* First character of input text */
  10647. const char *zEnd; /* One character past the end of input text */
  10648. };
  10649. /*
  10650. ** An instance of this structure can hold a simple list of identifiers,
  10651. ** such as the list "a,b,c" in the following statements:
  10652. **
  10653. ** INSERT INTO t(a,b,c) VALUES ...;
  10654. ** CREATE INDEX idx ON t(a,b,c);
  10655. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  10656. **
  10657. ** The IdList.a.idx field is used when the IdList represents the list of
  10658. ** column names after a table name in an INSERT statement. In the statement
  10659. **
  10660. ** INSERT INTO t(a,b,c) ...
  10661. **
  10662. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  10663. */
  10664. struct IdList {
  10665. struct IdList_item {
  10666. char *zName; /* Name of the identifier */
  10667. int idx; /* Index in some Table.aCol[] of a column named zName */
  10668. } *a;
  10669. int nId; /* Number of identifiers on the list */
  10670. };
  10671. /*
  10672. ** The bitmask datatype defined below is used for various optimizations.
  10673. **
  10674. ** Changing this from a 64-bit to a 32-bit type limits the number of
  10675. ** tables in a join to 32 instead of 64. But it also reduces the size
  10676. ** of the library by 738 bytes on ix86.
  10677. */
  10678. typedef u64 Bitmask;
  10679. /*
  10680. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  10681. */
  10682. #define BMS ((int)(sizeof(Bitmask)*8))
  10683. /*
  10684. ** A bit in a Bitmask
  10685. */
  10686. #define MASKBIT(n) (((Bitmask)1)<<(n))
  10687. /*
  10688. ** The following structure describes the FROM clause of a SELECT statement.
  10689. ** Each table or subquery in the FROM clause is a separate element of
  10690. ** the SrcList.a[] array.
  10691. **
  10692. ** With the addition of multiple database support, the following structure
  10693. ** can also be used to describe a particular table such as the table that
  10694. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  10695. ** such a table must be a simple name: ID. But in SQLite, the table can
  10696. ** now be identified by a database name, a dot, then the table name: ID.ID.
  10697. **
  10698. ** The jointype starts out showing the join type between the current table
  10699. ** and the next table on the list. The parser builds the list this way.
  10700. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  10701. ** jointype expresses the join between the table and the previous table.
  10702. **
  10703. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  10704. ** contains more than 63 columns and the 64-th or later column is used.
  10705. */
  10706. struct SrcList {
  10707. u8 nSrc; /* Number of tables or subqueries in the FROM clause */
  10708. u8 nAlloc; /* Number of entries allocated in a[] below */
  10709. struct SrcList_item {
  10710. Schema *pSchema; /* Schema to which this item is fixed */
  10711. char *zDatabase; /* Name of database holding this table */
  10712. char *zName; /* Name of the table */
  10713. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  10714. Table *pTab; /* An SQL table corresponding to zName */
  10715. Select *pSelect; /* A SELECT statement used in place of a table name */
  10716. int addrFillSub; /* Address of subroutine to manifest a subquery */
  10717. int regReturn; /* Register holding return address of addrFillSub */
  10718. u8 jointype; /* Type of join between this able and the previous */
  10719. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  10720. unsigned isCorrelated :1; /* True if sub-query is correlated */
  10721. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  10722. #ifndef SQLITE_OMIT_EXPLAIN
  10723. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  10724. #endif
  10725. int iCursor; /* The VDBE cursor number used to access this table */
  10726. Expr *pOn; /* The ON clause of a join */
  10727. IdList *pUsing; /* The USING clause of a join */
  10728. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  10729. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  10730. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  10731. } a[1]; /* One entry for each identifier on the list */
  10732. };
  10733. /*
  10734. ** Permitted values of the SrcList.a.jointype field
  10735. */
  10736. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  10737. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  10738. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  10739. #define JT_LEFT 0x0008 /* Left outer join */
  10740. #define JT_RIGHT 0x0010 /* Right outer join */
  10741. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  10742. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  10743. /*
  10744. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  10745. ** and the WhereInfo.wctrlFlags member.
  10746. */
  10747. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  10748. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  10749. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  10750. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  10751. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  10752. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  10753. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  10754. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  10755. #define WHERE_AND_ONLY 0x0080 /* Don't use indices for OR terms */
  10756. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  10757. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  10758. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  10759. /* Allowed return values from sqlite3WhereIsDistinct()
  10760. */
  10761. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  10762. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  10763. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  10764. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  10765. /*
  10766. ** A NameContext defines a context in which to resolve table and column
  10767. ** names. The context consists of a list of tables (the pSrcList) field and
  10768. ** a list of named expression (pEList). The named expression list may
  10769. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  10770. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  10771. ** pEList corresponds to the result set of a SELECT and is NULL for
  10772. ** other statements.
  10773. **
  10774. ** NameContexts can be nested. When resolving names, the inner-most
  10775. ** context is searched first. If no match is found, the next outer
  10776. ** context is checked. If there is still no match, the next context
  10777. ** is checked. This process continues until either a match is found
  10778. ** or all contexts are check. When a match is found, the nRef member of
  10779. ** the context containing the match is incremented.
  10780. **
  10781. ** Each subquery gets a new NameContext. The pNext field points to the
  10782. ** NameContext in the parent query. Thus the process of scanning the
  10783. ** NameContext list corresponds to searching through successively outer
  10784. ** subqueries looking for a match.
  10785. */
  10786. struct NameContext {
  10787. Parse *pParse; /* The parser */
  10788. SrcList *pSrcList; /* One or more tables used to resolve names */
  10789. ExprList *pEList; /* Optional list of result-set columns */
  10790. AggInfo *pAggInfo; /* Information about aggregates at this level */
  10791. NameContext *pNext; /* Next outer name context. NULL for outermost */
  10792. int nRef; /* Number of names resolved by this context */
  10793. int nErr; /* Number of errors encountered while resolving names */
  10794. u8 ncFlags; /* Zero or more NC_* flags defined below */
  10795. };
  10796. /*
  10797. ** Allowed values for the NameContext, ncFlags field.
  10798. */
  10799. #define NC_AllowAgg 0x01 /* Aggregate functions are allowed here */
  10800. #define NC_HasAgg 0x02 /* One or more aggregate functions seen */
  10801. #define NC_IsCheck 0x04 /* True if resolving names in a CHECK constraint */
  10802. #define NC_InAggFunc 0x08 /* True if analyzing arguments to an agg func */
  10803. #define NC_PartIdx 0x10 /* True if resolving a partial index WHERE */
  10804. /*
  10805. ** An instance of the following structure contains all information
  10806. ** needed to generate code for a single SELECT statement.
  10807. **
  10808. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  10809. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  10810. ** limit and nOffset to the value of the offset (or 0 if there is not
  10811. ** offset). But later on, nLimit and nOffset become the memory locations
  10812. ** in the VDBE that record the limit and offset counters.
  10813. **
  10814. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  10815. ** These addresses must be stored so that we can go back and fill in
  10816. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  10817. ** the number of columns in P2 can be computed at the same time
  10818. ** as the OP_OpenEphm instruction is coded because not
  10819. ** enough information about the compound query is known at that point.
  10820. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  10821. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  10822. ** sequences for the ORDER BY clause.
  10823. */
  10824. struct Select {
  10825. ExprList *pEList; /* The fields of the result */
  10826. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  10827. u16 selFlags; /* Various SF_* values */
  10828. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  10829. int addrOpenEphm[3]; /* OP_OpenEphem opcodes related to this select */
  10830. u64 nSelectRow; /* Estimated number of result rows */
  10831. SrcList *pSrc; /* The FROM clause */
  10832. Expr *pWhere; /* The WHERE clause */
  10833. ExprList *pGroupBy; /* The GROUP BY clause */
  10834. Expr *pHaving; /* The HAVING clause */
  10835. ExprList *pOrderBy; /* The ORDER BY clause */
  10836. Select *pPrior; /* Prior select in a compound select statement */
  10837. Select *pNext; /* Next select to the left in a compound */
  10838. Select *pRightmost; /* Right-most select in a compound select statement */
  10839. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  10840. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  10841. };
  10842. /*
  10843. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  10844. ** "Select Flag".
  10845. */
  10846. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  10847. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  10848. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  10849. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  10850. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  10851. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  10852. #define SF_UseSorter 0x0040 /* Sort using a sorter */
  10853. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  10854. #define SF_Materialize 0x0100 /* Force materialization of views */
  10855. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  10856. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  10857. /*
  10858. ** The results of a select can be distributed in several ways. The
  10859. ** "SRT" prefix means "SELECT Result Type".
  10860. */
  10861. #define SRT_Union 1 /* Store result as keys in an index */
  10862. #define SRT_Except 2 /* Remove result from a UNION index */
  10863. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  10864. #define SRT_Discard 4 /* Do not save the results anywhere */
  10865. /* The ORDER BY clause is ignored for all of the above */
  10866. #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
  10867. #define SRT_Output 5 /* Output each row of result */
  10868. #define SRT_Mem 6 /* Store result in a memory cell */
  10869. #define SRT_Set 7 /* Store results as keys in an index */
  10870. #define SRT_Table 8 /* Store result as data with an automatic rowid */
  10871. #define SRT_EphemTab 9 /* Create transient tab and store like SRT_Table */
  10872. #define SRT_Coroutine 10 /* Generate a single row of result */
  10873. /*
  10874. ** An instance of this object describes where to put of the results of
  10875. ** a SELECT statement.
  10876. */
  10877. struct SelectDest {
  10878. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  10879. char affSdst; /* Affinity used when eDest==SRT_Set */
  10880. int iSDParm; /* A parameter used by the eDest disposal method */
  10881. int iSdst; /* Base register where results are written */
  10882. int nSdst; /* Number of registers allocated */
  10883. };
  10884. /*
  10885. ** During code generation of statements that do inserts into AUTOINCREMENT
  10886. ** tables, the following information is attached to the Table.u.autoInc.p
  10887. ** pointer of each autoincrement table to record some side information that
  10888. ** the code generator needs. We have to keep per-table autoincrement
  10889. ** information in case inserts are down within triggers. Triggers do not
  10890. ** normally coordinate their activities, but we do need to coordinate the
  10891. ** loading and saving of autoincrement information.
  10892. */
  10893. struct AutoincInfo {
  10894. AutoincInfo *pNext; /* Next info block in a list of them all */
  10895. Table *pTab; /* Table this info block refers to */
  10896. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  10897. int regCtr; /* Memory register holding the rowid counter */
  10898. };
  10899. /*
  10900. ** Size of the column cache
  10901. */
  10902. #ifndef SQLITE_N_COLCACHE
  10903. # define SQLITE_N_COLCACHE 10
  10904. #endif
  10905. /*
  10906. ** At least one instance of the following structure is created for each
  10907. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  10908. ** statement. All such objects are stored in the linked list headed at
  10909. ** Parse.pTriggerPrg and deleted once statement compilation has been
  10910. ** completed.
  10911. **
  10912. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  10913. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  10914. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  10915. ** The Parse.pTriggerPrg list never contains two entries with the same
  10916. ** values for both pTrigger and orconf.
  10917. **
  10918. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  10919. ** accessed (or set to 0 for triggers fired as a result of INSERT
  10920. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  10921. ** a mask of new.* columns used by the program.
  10922. */
  10923. struct TriggerPrg {
  10924. Trigger *pTrigger; /* Trigger this program was coded from */
  10925. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  10926. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  10927. int orconf; /* Default ON CONFLICT policy */
  10928. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  10929. };
  10930. /*
  10931. ** The yDbMask datatype for the bitmask of all attached databases.
  10932. */
  10933. #if SQLITE_MAX_ATTACHED>30
  10934. typedef sqlite3_uint64 yDbMask;
  10935. #else
  10936. typedef unsigned int yDbMask;
  10937. #endif
  10938. /*
  10939. ** An SQL parser context. A copy of this structure is passed through
  10940. ** the parser and down into all the parser action routine in order to
  10941. ** carry around information that is global to the entire parse.
  10942. **
  10943. ** The structure is divided into two parts. When the parser and code
  10944. ** generate call themselves recursively, the first part of the structure
  10945. ** is constant but the second part is reset at the beginning and end of
  10946. ** each recursion.
  10947. **
  10948. ** The nTableLock and aTableLock variables are only used if the shared-cache
  10949. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  10950. ** used to store the set of table-locks required by the statement being
  10951. ** compiled. Function sqlite3TableLock() is used to add entries to the
  10952. ** list.
  10953. */
  10954. struct Parse {
  10955. sqlite3 *db; /* The main database structure */
  10956. char *zErrMsg; /* An error message */
  10957. Vdbe *pVdbe; /* An engine for executing database bytecode */
  10958. int rc; /* Return code from execution */
  10959. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  10960. u8 checkSchema; /* Causes schema cookie check after an error */
  10961. u8 nested; /* Number of nested calls to the parser/code generator */
  10962. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  10963. u8 nTempInUse; /* Number of aTempReg[] currently checked out */
  10964. u8 nColCache; /* Number of entries in aColCache[] */
  10965. u8 iColCache; /* Next entry in aColCache[] to replace */
  10966. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  10967. u8 mayAbort; /* True if statement may throw an ABORT exception */
  10968. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  10969. int aTempReg[8]; /* Holding area for temporary registers */
  10970. int nRangeReg; /* Size of the temporary register block */
  10971. int iRangeReg; /* First register in temporary register block */
  10972. int nErr; /* Number of errors seen */
  10973. int nTab; /* Number of previously allocated VDBE cursors */
  10974. int nMem; /* Number of memory cells used so far */
  10975. int nSet; /* Number of sets used so far */
  10976. int nOnce; /* Number of OP_Once instructions so far */
  10977. int ckBase; /* Base register of data during check constraints */
  10978. int iPartIdxTab; /* Table corresponding to a partial index */
  10979. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  10980. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  10981. struct yColCache {
  10982. int iTable; /* Table cursor number */
  10983. int iColumn; /* Table column number */
  10984. u8 tempReg; /* iReg is a temp register that needs to be freed */
  10985. int iLevel; /* Nesting level */
  10986. int iReg; /* Reg with value of this column. 0 means none. */
  10987. int lru; /* Least recently used entry has the smallest value */
  10988. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  10989. yDbMask writeMask; /* Start a write transaction on these databases */
  10990. yDbMask cookieMask; /* Bitmask of schema verified databases */
  10991. int cookieGoto; /* Address of OP_Goto to cookie verifier subroutine */
  10992. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  10993. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  10994. int regRoot; /* Register holding root page number for new objects */
  10995. int nMaxArg; /* Max args passed to user function by sub-program */
  10996. Token constraintName;/* Name of the constraint currently being parsed */
  10997. #ifndef SQLITE_OMIT_SHARED_CACHE
  10998. int nTableLock; /* Number of locks in aTableLock */
  10999. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  11000. #endif
  11001. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  11002. /* Information used while coding trigger programs. */
  11003. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  11004. Table *pTriggerTab; /* Table triggers are being coded for */
  11005. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  11006. u32 oldmask; /* Mask of old.* columns referenced */
  11007. u32 newmask; /* Mask of new.* columns referenced */
  11008. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11009. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11010. u8 disableTriggers; /* True to disable triggers */
  11011. /* Above is constant between recursions. Below is reset before and after
  11012. ** each recursion */
  11013. int nVar; /* Number of '?' variables seen in the SQL so far */
  11014. int nzVar; /* Number of available slots in azVar[] */
  11015. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11016. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11017. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11018. int nVtabLock; /* Number of virtual tables to lock */
  11019. #endif
  11020. int nAlias; /* Number of aliased result set columns */
  11021. int nHeight; /* Expression tree height of current sub-select */
  11022. #ifndef SQLITE_OMIT_EXPLAIN
  11023. int iSelectId; /* ID of current select for EXPLAIN output */
  11024. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11025. #endif
  11026. char **azVar; /* Pointers to names of parameters */
  11027. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11028. int *aAlias; /* Register used to hold aliased result */
  11029. const char *zTail; /* All SQL text past the last semicolon parsed */
  11030. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11031. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11032. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11033. Token sNameToken; /* Token with unqualified schema object name */
  11034. Token sLastToken; /* The last token parsed */
  11035. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11036. Token sArg; /* Complete text of a module argument */
  11037. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11038. #endif
  11039. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11040. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11041. };
  11042. /*
  11043. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11044. */
  11045. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11046. #define IN_DECLARE_VTAB 0
  11047. #else
  11048. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11049. #endif
  11050. /*
  11051. ** An instance of the following structure can be declared on a stack and used
  11052. ** to save the Parse.zAuthContext value so that it can be restored later.
  11053. */
  11054. struct AuthContext {
  11055. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11056. Parse *pParse; /* The Parse structure */
  11057. };
  11058. /*
  11059. ** Bitfield flags for P5 value in various opcodes.
  11060. */
  11061. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11062. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11063. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11064. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11065. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11066. #define OPFLAG_CLEARCACHE 0x20 /* Clear pseudo-table cache in OP_Column */
  11067. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11068. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11069. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11070. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11071. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11072. /*
  11073. * Each trigger present in the database schema is stored as an instance of
  11074. * struct Trigger.
  11075. *
  11076. * Pointers to instances of struct Trigger are stored in two ways.
  11077. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11078. * database). This allows Trigger structures to be retrieved by name.
  11079. * 2. All triggers associated with a single table form a linked list, using the
  11080. * pNext member of struct Trigger. A pointer to the first element of the
  11081. * linked list is stored as the "pTrigger" member of the associated
  11082. * struct Table.
  11083. *
  11084. * The "step_list" member points to the first element of a linked list
  11085. * containing the SQL statements specified as the trigger program.
  11086. */
  11087. struct Trigger {
  11088. char *zName; /* The name of the trigger */
  11089. char *table; /* The table or view to which the trigger applies */
  11090. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11091. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11092. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11093. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11094. the <column-list> is stored here */
  11095. Schema *pSchema; /* Schema containing the trigger */
  11096. Schema *pTabSchema; /* Schema containing the table */
  11097. TriggerStep *step_list; /* Link list of trigger program steps */
  11098. Trigger *pNext; /* Next trigger associated with the table */
  11099. };
  11100. /*
  11101. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11102. ** determine which.
  11103. **
  11104. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11105. ** In that cases, the constants below can be ORed together.
  11106. */
  11107. #define TRIGGER_BEFORE 1
  11108. #define TRIGGER_AFTER 2
  11109. /*
  11110. * An instance of struct TriggerStep is used to store a single SQL statement
  11111. * that is a part of a trigger-program.
  11112. *
  11113. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11114. * using the "pNext" member) referenced by the "step_list" member of the
  11115. * associated struct Trigger instance. The first element of the linked list is
  11116. * the first step of the trigger-program.
  11117. *
  11118. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11119. * "SELECT" statement. The meanings of the other members is determined by the
  11120. * value of "op" as follows:
  11121. *
  11122. * (op == TK_INSERT)
  11123. * orconf -> stores the ON CONFLICT algorithm
  11124. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11125. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11126. * target -> A token holding the quoted name of the table to insert into.
  11127. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11128. * this stores values to be inserted. Otherwise NULL.
  11129. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11130. * statement, then this stores the column-names to be
  11131. * inserted into.
  11132. *
  11133. * (op == TK_DELETE)
  11134. * target -> A token holding the quoted name of the table to delete from.
  11135. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11136. * Otherwise NULL.
  11137. *
  11138. * (op == TK_UPDATE)
  11139. * target -> A token holding the quoted name of the table to update rows of.
  11140. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11141. * Otherwise NULL.
  11142. * pExprList -> A list of the columns to update and the expressions to update
  11143. * them to. See sqlite3Update() documentation of "pChanges"
  11144. * argument.
  11145. *
  11146. */
  11147. struct TriggerStep {
  11148. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11149. u8 orconf; /* OE_Rollback etc. */
  11150. Trigger *pTrig; /* The trigger that this step is a part of */
  11151. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11152. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11153. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11154. ExprList *pExprList; /* SET clause for UPDATE. VALUES clause for INSERT */
  11155. IdList *pIdList; /* Column names for INSERT */
  11156. TriggerStep *pNext; /* Next in the link-list */
  11157. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11158. };
  11159. /*
  11160. ** The following structure contains information used by the sqliteFix...
  11161. ** routines as they walk the parse tree to make database references
  11162. ** explicit.
  11163. */
  11164. typedef struct DbFixer DbFixer;
  11165. struct DbFixer {
  11166. Parse *pParse; /* The parsing context. Error messages written here */
  11167. Schema *pSchema; /* Fix items to this schema */
  11168. int bVarOnly; /* Check for variable references only */
  11169. const char *zDb; /* Make sure all objects are contained in this database */
  11170. const char *zType; /* Type of the container - used for error messages */
  11171. const Token *pName; /* Name of the container - used for error messages */
  11172. };
  11173. /*
  11174. ** An objected used to accumulate the text of a string where we
  11175. ** do not necessarily know how big the string will be in the end.
  11176. */
  11177. struct StrAccum {
  11178. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11179. char *zBase; /* A base allocation. Not from malloc. */
  11180. char *zText; /* The string collected so far */
  11181. int nChar; /* Length of the string so far */
  11182. int nAlloc; /* Amount of space allocated in zText */
  11183. int mxAlloc; /* Maximum allowed string length */
  11184. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11185. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11186. };
  11187. #define STRACCUM_NOMEM 1
  11188. #define STRACCUM_TOOBIG 2
  11189. /*
  11190. ** A pointer to this structure is used to communicate information
  11191. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11192. */
  11193. typedef struct {
  11194. sqlite3 *db; /* The database being initialized */
  11195. char **pzErrMsg; /* Error message stored here */
  11196. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11197. int rc; /* Result code stored here */
  11198. } InitData;
  11199. /*
  11200. ** Structure containing global configuration data for the SQLite library.
  11201. **
  11202. ** This structure also contains some state information.
  11203. */
  11204. struct Sqlite3Config {
  11205. int bMemstat; /* True to enable memory status */
  11206. int bCoreMutex; /* True to enable core mutexing */
  11207. int bFullMutex; /* True to enable full mutexing */
  11208. int bOpenUri; /* True to interpret filenames as URIs */
  11209. int bUseCis; /* Use covering indices for full-scans */
  11210. int mxStrlen; /* Maximum string length */
  11211. int szLookaside; /* Default lookaside buffer size */
  11212. int nLookaside; /* Default lookaside buffer count */
  11213. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11214. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11215. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11216. void *pHeap; /* Heap storage space */
  11217. int nHeap; /* Size of pHeap[] */
  11218. int mnReq, mxReq; /* Min and max heap requests sizes */
  11219. sqlite3_int64 szMmap; /* mmap() space per open file */
  11220. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11221. void *pScratch; /* Scratch memory */
  11222. int szScratch; /* Size of each scratch buffer */
  11223. int nScratch; /* Number of scratch buffers */
  11224. void *pPage; /* Page cache memory */
  11225. int szPage; /* Size of each page in pPage[] */
  11226. int nPage; /* Number of pages in pPage[] */
  11227. int mxParserStack; /* maximum depth of the parser stack */
  11228. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11229. /* The above might be initialized to non-zero. The following need to always
  11230. ** initially be zero, however. */
  11231. int isInit; /* True after initialization has finished */
  11232. int inProgress; /* True while initialization in progress */
  11233. int isMutexInit; /* True after mutexes are initialized */
  11234. int isMallocInit; /* True after malloc is initialized */
  11235. int isPCacheInit; /* True after malloc is initialized */
  11236. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11237. int nRefInitMutex; /* Number of users of pInitMutex */
  11238. void (*xLog)(void*,int,const char*); /* Function for logging */
  11239. void *pLogArg; /* First argument to xLog() */
  11240. int bLocaltimeFault; /* True to fail localtime() calls */
  11241. #ifdef SQLITE_ENABLE_SQLLOG
  11242. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11243. void *pSqllogArg;
  11244. #endif
  11245. };
  11246. /*
  11247. ** Context pointer passed down through the tree-walk.
  11248. */
  11249. struct Walker {
  11250. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11251. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11252. Parse *pParse; /* Parser context. */
  11253. int walkerDepth; /* Number of subqueries */
  11254. u8 bSelectDepthFirst; /* Do subqueries first */
  11255. union { /* Extra data for callback */
  11256. NameContext *pNC; /* Naming context */
  11257. int i; /* Integer value */
  11258. SrcList *pSrcList; /* FROM clause */
  11259. struct SrcCount *pSrcCount; /* Counting column references */
  11260. } u;
  11261. };
  11262. /* Forward declarations */
  11263. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11264. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11265. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11266. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11267. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11268. /*
  11269. ** Return code from the parse-tree walking primitives and their
  11270. ** callbacks.
  11271. */
  11272. #define WRC_Continue 0 /* Continue down into children */
  11273. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11274. #define WRC_Abort 2 /* Abandon the tree walk */
  11275. /*
  11276. ** Assuming zIn points to the first byte of a UTF-8 character,
  11277. ** advance zIn to point to the first byte of the next UTF-8 character.
  11278. */
  11279. #define SQLITE_SKIP_UTF8(zIn) { \
  11280. if( (*(zIn++))>=0xc0 ){ \
  11281. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11282. } \
  11283. }
  11284. /*
  11285. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11286. ** the same name but without the _BKPT suffix. These macros invoke
  11287. ** routines that report the line-number on which the error originated
  11288. ** using sqlite3_log(). The routines also provide a convenient place
  11289. ** to set a debugger breakpoint.
  11290. */
  11291. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11292. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11293. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11294. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11295. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11296. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11297. /*
  11298. ** FTS4 is really an extension for FTS3. It is enabled using the
  11299. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  11300. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  11301. */
  11302. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11303. # define SQLITE_ENABLE_FTS3
  11304. #endif
  11305. /*
  11306. ** The ctype.h header is needed for non-ASCII systems. It is also
  11307. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11308. */
  11309. #if !defined(SQLITE_ASCII) || \
  11310. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11311. # include <ctype.h>
  11312. #endif
  11313. /*
  11314. ** The following macros mimic the standard library functions toupper(),
  11315. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11316. ** sqlite versions only work for ASCII characters, regardless of locale.
  11317. */
  11318. #ifdef SQLITE_ASCII
  11319. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11320. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11321. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11322. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11323. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11324. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11325. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11326. #else
  11327. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11328. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11329. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11330. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11331. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11332. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11333. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11334. #endif
  11335. /*
  11336. ** Internal function prototypes
  11337. */
  11338. #define sqlite3StrICmp sqlite3_stricmp
  11339. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11340. #define sqlite3StrNICmp sqlite3_strnicmp
  11341. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11342. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11343. SQLITE_PRIVATE void *sqlite3Malloc(int);
  11344. SQLITE_PRIVATE void *sqlite3MallocZero(int);
  11345. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
  11346. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
  11347. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11348. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
  11349. SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
  11350. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
  11351. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
  11352. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  11353. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  11354. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  11355. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  11356. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  11357. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  11358. SQLITE_PRIVATE void sqlite3PageFree(void*);
  11359. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  11360. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  11361. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  11362. /*
  11363. ** On systems with ample stack space and that support alloca(), make
  11364. ** use of alloca() to obtain space for large automatic objects. By default,
  11365. ** obtain space from malloc().
  11366. **
  11367. ** The alloca() routine never returns NULL. This will cause code paths
  11368. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  11369. */
  11370. #ifdef SQLITE_USE_ALLOCA
  11371. # define sqlite3StackAllocRaw(D,N) alloca(N)
  11372. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  11373. # define sqlite3StackFree(D,P)
  11374. #else
  11375. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  11376. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  11377. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  11378. #endif
  11379. #ifdef SQLITE_ENABLE_MEMSYS3
  11380. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  11381. #endif
  11382. #ifdef SQLITE_ENABLE_MEMSYS5
  11383. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  11384. #endif
  11385. #ifndef SQLITE_MUTEX_OMIT
  11386. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  11387. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  11388. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  11389. SQLITE_PRIVATE int sqlite3MutexInit(void);
  11390. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  11391. #endif
  11392. SQLITE_PRIVATE int sqlite3StatusValue(int);
  11393. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  11394. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  11395. #ifndef SQLITE_OMIT_FLOATING_POINT
  11396. SQLITE_PRIVATE int sqlite3IsNaN(double);
  11397. #else
  11398. # define sqlite3IsNaN(X) 0
  11399. #endif
  11400. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
  11401. #ifndef SQLITE_OMIT_TRACE
  11402. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
  11403. #endif
  11404. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  11405. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  11406. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  11407. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  11408. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  11409. #endif
  11410. #if defined(SQLITE_TEST)
  11411. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  11412. #endif
  11413. /* Output formatting for SQLITE_TESTCTRL_EXPLAIN */
  11414. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  11415. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe*);
  11416. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe*, const char*, ...);
  11417. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe*);
  11418. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe*);
  11419. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe*);
  11420. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe*);
  11421. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe*, Select*);
  11422. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe*, Expr*);
  11423. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe*, ExprList*);
  11424. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe*);
  11425. #else
  11426. # define sqlite3ExplainBegin(X)
  11427. # define sqlite3ExplainSelect(A,B)
  11428. # define sqlite3ExplainExpr(A,B)
  11429. # define sqlite3ExplainExprList(A,B)
  11430. # define sqlite3ExplainFinish(X)
  11431. # define sqlite3VdbeExplanation(X) 0
  11432. #endif
  11433. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  11434. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  11435. SQLITE_PRIVATE int sqlite3Dequote(char*);
  11436. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  11437. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  11438. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  11439. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  11440. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  11441. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  11442. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  11443. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  11444. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  11445. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  11446. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  11447. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  11448. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  11449. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  11450. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  11451. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  11452. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  11453. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  11454. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  11455. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  11456. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  11457. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  11458. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  11459. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  11460. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  11461. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  11462. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  11463. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  11464. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  11465. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  11466. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  11467. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  11468. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  11469. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  11470. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  11471. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  11472. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  11473. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  11474. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
  11475. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  11476. sqlite3_vfs**,char**,char **);
  11477. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  11478. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  11479. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  11480. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  11481. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  11482. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  11483. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  11484. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  11485. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  11486. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  11487. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  11488. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  11489. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
  11490. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  11491. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  11492. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  11493. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  11494. #else
  11495. # define sqlite3ViewGetColumnNames(A,B) 0
  11496. #endif
  11497. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  11498. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  11499. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  11500. #ifndef SQLITE_OMIT_AUTOINCREMENT
  11501. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  11502. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  11503. #else
  11504. # define sqlite3AutoincrementBegin(X)
  11505. # define sqlite3AutoincrementEnd(X)
  11506. #endif
  11507. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse*, Select*, SelectDest*);
  11508. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  11509. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  11510. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  11511. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  11512. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  11513. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  11514. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  11515. Token*, Select*, Expr*, IdList*);
  11516. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  11517. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  11518. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  11519. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  11520. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  11521. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  11522. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  11523. Expr*, int, int);
  11524. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  11525. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  11526. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  11527. Expr*,ExprList*,u16,Expr*,Expr*);
  11528. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  11529. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  11530. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  11531. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  11532. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  11533. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  11534. #endif
  11535. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  11536. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  11537. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  11538. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  11539. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  11540. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  11541. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  11542. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  11543. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  11544. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*);
  11545. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  11546. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  11547. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  11548. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  11549. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  11550. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
  11551. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  11552. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  11553. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  11554. SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
  11555. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  11556. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  11557. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  11558. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
  11559. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
  11560. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  11561. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  11562. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  11563. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  11564. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  11565. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  11566. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  11567. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  11568. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  11569. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  11570. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  11571. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  11572. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  11573. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  11574. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  11575. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  11576. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  11577. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  11578. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  11579. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  11580. SQLITE_PRIVATE void sqlite3PrngResetState(void);
  11581. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  11582. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  11583. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  11584. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  11585. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  11586. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  11587. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  11588. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  11589. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  11590. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  11591. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  11592. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
  11593. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  11594. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  11595. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
  11596. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  11597. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  11598. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
  11599. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
  11600. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*);
  11601. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
  11602. int*,int,int,int,int,int*);
  11603. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
  11604. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
  11605. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  11606. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  11607. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  11608. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, int);
  11609. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  11610. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  11611. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  11612. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  11613. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  11614. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  11615. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  11616. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  11617. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  11618. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  11619. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  11620. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  11621. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  11622. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  11623. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  11624. #endif
  11625. #ifndef SQLITE_OMIT_TRIGGER
  11626. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  11627. Expr*,int, int);
  11628. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  11629. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  11630. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  11631. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  11632. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  11633. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  11634. int, int, int);
  11635. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  11636. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  11637. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  11638. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  11639. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  11640. ExprList*,Select*,u8);
  11641. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  11642. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  11643. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  11644. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  11645. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  11646. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  11647. #else
  11648. # define sqlite3TriggersExist(B,C,D,E,F) 0
  11649. # define sqlite3DeleteTrigger(A,B)
  11650. # define sqlite3DropTriggerPtr(A,B)
  11651. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  11652. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  11653. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  11654. # define sqlite3TriggerList(X, Y) 0
  11655. # define sqlite3ParseToplevel(p) p
  11656. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  11657. #endif
  11658. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  11659. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  11660. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  11661. #ifndef SQLITE_OMIT_AUTHORIZATION
  11662. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  11663. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  11664. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  11665. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  11666. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  11667. #else
  11668. # define sqlite3AuthRead(a,b,c,d)
  11669. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  11670. # define sqlite3AuthContextPush(a,b,c)
  11671. # define sqlite3AuthContextPop(a) ((void)(a))
  11672. #endif
  11673. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  11674. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  11675. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  11676. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  11677. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  11678. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  11679. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  11680. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  11681. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  11682. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  11683. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  11684. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  11685. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  11686. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  11687. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  11688. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  11689. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11690. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  11691. #endif
  11692. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  11693. /*
  11694. ** Routines to read and write variable-length integers. These used to
  11695. ** be defined locally, but now we use the varint routines in the util.c
  11696. ** file. Code should use the MACRO forms below, as the Varint32 versions
  11697. ** are coded to assume the single byte case is already handled (which
  11698. ** the MACRO form does).
  11699. */
  11700. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  11701. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
  11702. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  11703. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  11704. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  11705. /*
  11706. ** The header of a record consists of a sequence variable-length integers.
  11707. ** These integers are almost always small and are encoded as a single byte.
  11708. ** The following macros take advantage this fact to provide a fast encode
  11709. ** and decode of the integers in a record header. It is faster for the common
  11710. ** case where the integer is a single byte. It is a little slower when the
  11711. ** integer is two or more bytes. But overall it is faster.
  11712. **
  11713. ** The following expressions are equivalent:
  11714. **
  11715. ** x = sqlite3GetVarint32( A, &B );
  11716. ** x = sqlite3PutVarint32( A, B );
  11717. **
  11718. ** x = getVarint32( A, B );
  11719. ** x = putVarint32( A, B );
  11720. **
  11721. */
  11722. #define getVarint32(A,B) \
  11723. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  11724. #define putVarint32(A,B) \
  11725. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  11726. sqlite3PutVarint32((A),(B)))
  11727. #define getVarint sqlite3GetVarint
  11728. #define putVarint sqlite3PutVarint
  11729. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  11730. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
  11731. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  11732. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  11733. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  11734. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  11735. SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
  11736. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  11737. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  11738. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  11739. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  11740. defined(SQLITE_DEBUG_OS_TRACE)
  11741. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  11742. #endif
  11743. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  11744. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  11745. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  11746. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  11747. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  11748. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, Token*);
  11749. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  11750. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  11751. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  11752. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  11753. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  11754. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  11755. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  11756. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  11757. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  11758. #ifdef SQLITE_ENABLE_8_3_NAMES
  11759. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  11760. #else
  11761. # define sqlite3FileSuffix3(X,Y)
  11762. #endif
  11763. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,int);
  11764. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  11765. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  11766. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  11767. void(*)(void*));
  11768. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  11769. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  11770. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  11771. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  11772. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  11773. #ifndef SQLITE_AMALGAMATION
  11774. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  11775. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  11776. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  11777. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  11778. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  11779. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  11780. #ifndef SQLITE_OMIT_WSD
  11781. SQLITE_PRIVATE int sqlite3PendingByte;
  11782. #endif
  11783. #endif
  11784. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  11785. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  11786. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  11787. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  11788. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  11789. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  11790. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  11791. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  11792. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  11793. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  11794. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  11795. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  11796. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  11797. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  11798. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  11799. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  11800. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  11801. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  11802. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  11803. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  11804. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  11805. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  11806. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  11807. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  11808. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  11809. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  11810. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  11811. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  11812. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  11813. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  11814. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  11815. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  11816. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int);
  11817. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
  11818. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  11819. void (*)(sqlite3_context*,int,sqlite3_value **),
  11820. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  11821. FuncDestructor *pDestructor
  11822. );
  11823. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  11824. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  11825. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  11826. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  11827. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum*,int);
  11828. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  11829. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  11830. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  11831. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  11832. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  11833. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  11834. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  11835. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  11836. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  11837. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  11838. #endif
  11839. /*
  11840. ** The interface to the LEMON-generated parser
  11841. */
  11842. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
  11843. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  11844. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  11845. #ifdef YYTRACKMAXSTACKDEPTH
  11846. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  11847. #endif
  11848. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  11849. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  11850. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  11851. #else
  11852. # define sqlite3CloseExtensions(X)
  11853. #endif
  11854. #ifndef SQLITE_OMIT_SHARED_CACHE
  11855. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  11856. #else
  11857. #define sqlite3TableLock(v,w,x,y,z)
  11858. #endif
  11859. #ifdef SQLITE_TEST
  11860. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  11861. #endif
  11862. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11863. # define sqlite3VtabClear(Y)
  11864. # define sqlite3VtabSync(X,Y) SQLITE_OK
  11865. # define sqlite3VtabRollback(X)
  11866. # define sqlite3VtabCommit(X)
  11867. # define sqlite3VtabInSync(db) 0
  11868. # define sqlite3VtabLock(X)
  11869. # define sqlite3VtabUnlock(X)
  11870. # define sqlite3VtabUnlockList(X)
  11871. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  11872. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  11873. #else
  11874. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  11875. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  11876. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  11877. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  11878. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  11879. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  11880. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  11881. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  11882. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  11883. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  11884. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  11885. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  11886. #endif
  11887. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  11888. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  11889. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  11890. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  11891. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  11892. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  11893. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  11894. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  11895. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  11896. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  11897. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  11898. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  11899. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  11900. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  11901. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  11902. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  11903. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  11904. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  11905. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  11906. #ifndef SQLITE_OMIT_WAL
  11907. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  11908. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  11909. #endif
  11910. /* Declarations for functions in fkey.c. All of these are replaced by
  11911. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  11912. ** key functionality is available. If OMIT_TRIGGER is defined but
  11913. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  11914. ** this case foreign keys are parsed, but no other functionality is
  11915. ** provided (enforcement of FK constraints requires the triggers sub-system).
  11916. */
  11917. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  11918. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  11919. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  11920. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  11921. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  11922. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  11923. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  11924. #else
  11925. #define sqlite3FkActions(a,b,c,d,e,f)
  11926. #define sqlite3FkCheck(a,b,c,d,e,f)
  11927. #define sqlite3FkDropTable(a,b,c)
  11928. #define sqlite3FkOldmask(a,b) 0
  11929. #define sqlite3FkRequired(a,b,c,d) 0
  11930. #endif
  11931. #ifndef SQLITE_OMIT_FOREIGN_KEY
  11932. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  11933. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  11934. #else
  11935. #define sqlite3FkDelete(a,b)
  11936. #define sqlite3FkLocateIndex(a,b,c,d,e)
  11937. #endif
  11938. /*
  11939. ** Available fault injectors. Should be numbered beginning with 0.
  11940. */
  11941. #define SQLITE_FAULTINJECTOR_MALLOC 0
  11942. #define SQLITE_FAULTINJECTOR_COUNT 1
  11943. /*
  11944. ** The interface to the code in fault.c used for identifying "benign"
  11945. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  11946. ** is not defined.
  11947. */
  11948. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11949. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  11950. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  11951. #else
  11952. #define sqlite3BeginBenignMalloc()
  11953. #define sqlite3EndBenignMalloc()
  11954. #endif
  11955. #define IN_INDEX_ROWID 1
  11956. #define IN_INDEX_EPH 2
  11957. #define IN_INDEX_INDEX_ASC 3
  11958. #define IN_INDEX_INDEX_DESC 4
  11959. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
  11960. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  11961. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  11962. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  11963. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  11964. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  11965. #else
  11966. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  11967. #define sqlite3JournalExists(p) 1
  11968. #endif
  11969. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  11970. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  11971. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  11972. #if SQLITE_MAX_EXPR_DEPTH>0
  11973. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  11974. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  11975. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  11976. #else
  11977. #define sqlite3ExprSetHeight(x,y)
  11978. #define sqlite3SelectExprHeight(x) 0
  11979. #define sqlite3ExprCheckHeight(x,y)
  11980. #endif
  11981. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  11982. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  11983. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  11984. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  11985. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  11986. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  11987. #else
  11988. #define sqlite3ConnectionBlocked(x,y)
  11989. #define sqlite3ConnectionUnlocked(x)
  11990. #define sqlite3ConnectionClosed(x)
  11991. #endif
  11992. #ifdef SQLITE_DEBUG
  11993. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  11994. #endif
  11995. /*
  11996. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  11997. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  11998. ** print I/O tracing messages.
  11999. */
  12000. #ifdef SQLITE_ENABLE_IOTRACE
  12001. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  12002. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  12003. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  12004. #else
  12005. # define IOTRACE(A)
  12006. # define sqlite3VdbeIOTraceSql(X)
  12007. #endif
  12008. /*
  12009. ** These routines are available for the mem2.c debugging memory allocator
  12010. ** only. They are used to verify that different "types" of memory
  12011. ** allocations are properly tracked by the system.
  12012. **
  12013. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12014. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12015. ** a single bit set.
  12016. **
  12017. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12018. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12019. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12020. **
  12021. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12022. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12023. **
  12024. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12025. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12026. ** it might have been allocated by lookaside, except the allocation was
  12027. ** too large or lookaside was already full. It is important to verify
  12028. ** that allocations that might have been satisfied by lookaside are not
  12029. ** passed back to non-lookaside free() routines. Asserts such as the
  12030. ** example above are placed on the non-lookaside free() routines to verify
  12031. ** this constraint.
  12032. **
  12033. ** All of this is no-op for a production build. It only comes into
  12034. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12035. */
  12036. #ifdef SQLITE_MEMDEBUG
  12037. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12038. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12039. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12040. #else
  12041. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12042. # define sqlite3MemdebugHasType(X,Y) 1
  12043. # define sqlite3MemdebugNoType(X,Y) 1
  12044. #endif
  12045. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12046. #define MEMTYPE_LOOKASIDE 0x02 /* Might have been lookaside memory */
  12047. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12048. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12049. #define MEMTYPE_DB 0x10 /* Uses sqlite3DbMalloc, not sqlite_malloc */
  12050. #endif /* _SQLITEINT_H_ */
  12051. /************** End of sqliteInt.h *******************************************/
  12052. /************** Begin file global.c ******************************************/
  12053. /*
  12054. ** 2008 June 13
  12055. **
  12056. ** The author disclaims copyright to this source code. In place of
  12057. ** a legal notice, here is a blessing:
  12058. **
  12059. ** May you do good and not evil.
  12060. ** May you find forgiveness for yourself and forgive others.
  12061. ** May you share freely, never taking more than you give.
  12062. **
  12063. *************************************************************************
  12064. **
  12065. ** This file contains definitions of global variables and contants.
  12066. */
  12067. /* An array to map all upper-case characters into their corresponding
  12068. ** lower-case character.
  12069. **
  12070. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12071. ** handle case conversions for the UTF character set since the tables
  12072. ** involved are nearly as big or bigger than SQLite itself.
  12073. */
  12074. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12075. #ifdef SQLITE_ASCII
  12076. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12077. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12078. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12079. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12080. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12081. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12082. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12083. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12084. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12085. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12086. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12087. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12088. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12089. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12090. 252,253,254,255
  12091. #endif
  12092. #ifdef SQLITE_EBCDIC
  12093. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12094. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12095. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12096. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12097. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12098. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12099. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12100. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12101. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12102. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12103. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12104. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12105. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12106. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12107. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12108. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12109. #endif
  12110. };
  12111. /*
  12112. ** The following 256 byte lookup table is used to support SQLites built-in
  12113. ** equivalents to the following standard library functions:
  12114. **
  12115. ** isspace() 0x01
  12116. ** isalpha() 0x02
  12117. ** isdigit() 0x04
  12118. ** isalnum() 0x06
  12119. ** isxdigit() 0x08
  12120. ** toupper() 0x20
  12121. ** SQLite identifier character 0x40
  12122. **
  12123. ** Bit 0x20 is set if the mapped character requires translation to upper
  12124. ** case. i.e. if the character is a lower-case ASCII character.
  12125. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12126. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12127. **
  12128. ** (x & ~(map[x]&0x20))
  12129. **
  12130. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12131. ** array. tolower() is used more often than toupper() by SQLite.
  12132. **
  12133. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12134. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12135. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12136. ** part of an identifier is 0x46.
  12137. **
  12138. ** SQLite's versions are identical to the standard versions assuming a
  12139. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12140. */
  12141. #ifdef SQLITE_ASCII
  12142. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12143. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12144. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12145. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12146. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12147. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12148. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12149. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12150. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12151. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12152. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12153. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12154. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12155. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12156. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12157. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12158. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12159. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12160. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12161. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12162. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12163. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12164. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12165. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12166. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12167. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12168. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12169. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12170. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12171. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12172. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12173. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12174. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12175. };
  12176. #endif
  12177. #ifndef SQLITE_USE_URI
  12178. # define SQLITE_USE_URI 0
  12179. #endif
  12180. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12181. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12182. #endif
  12183. /*
  12184. ** The following singleton contains the global configuration for
  12185. ** the SQLite library.
  12186. */
  12187. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12188. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12189. 1, /* bCoreMutex */
  12190. SQLITE_THREADSAFE==1, /* bFullMutex */
  12191. SQLITE_USE_URI, /* bOpenUri */
  12192. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12193. 0x7ffffffe, /* mxStrlen */
  12194. 128, /* szLookaside */
  12195. 500, /* nLookaside */
  12196. {0,0,0,0,0,0,0,0}, /* m */
  12197. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12198. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12199. (void*)0, /* pHeap */
  12200. 0, /* nHeap */
  12201. 0, 0, /* mnHeap, mxHeap */
  12202. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12203. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12204. (void*)0, /* pScratch */
  12205. 0, /* szScratch */
  12206. 0, /* nScratch */
  12207. (void*)0, /* pPage */
  12208. 0, /* szPage */
  12209. 0, /* nPage */
  12210. 0, /* mxParserStack */
  12211. 0, /* sharedCacheEnabled */
  12212. /* All the rest should always be initialized to zero */
  12213. 0, /* isInit */
  12214. 0, /* inProgress */
  12215. 0, /* isMutexInit */
  12216. 0, /* isMallocInit */
  12217. 0, /* isPCacheInit */
  12218. 0, /* pInitMutex */
  12219. 0, /* nRefInitMutex */
  12220. 0, /* xLog */
  12221. 0, /* pLogArg */
  12222. 0, /* bLocaltimeFault */
  12223. #ifdef SQLITE_ENABLE_SQLLOG
  12224. 0, /* xSqllog */
  12225. 0 /* pSqllogArg */
  12226. #endif
  12227. };
  12228. /*
  12229. ** Hash table for global functions - functions common to all
  12230. ** database connections. After initialization, this table is
  12231. ** read-only.
  12232. */
  12233. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12234. /*
  12235. ** Constant tokens for values 0 and 1.
  12236. */
  12237. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12238. { "0", 1 },
  12239. { "1", 1 }
  12240. };
  12241. /*
  12242. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12243. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12244. ** the database page that contains the pending byte. It never attempts
  12245. ** to read or write that page. The pending byte page is set assign
  12246. ** for use by the VFS layers as space for managing file locks.
  12247. **
  12248. ** During testing, it is often desirable to move the pending byte to
  12249. ** a different position in the file. This allows code that has to
  12250. ** deal with the pending byte to run on files that are much smaller
  12251. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12252. ** move the pending byte.
  12253. **
  12254. ** IMPORTANT: Changing the pending byte to any value other than
  12255. ** 0x40000000 results in an incompatible database file format!
  12256. ** Changing the pending byte during operating results in undefined
  12257. ** and dileterious behavior.
  12258. */
  12259. #ifndef SQLITE_OMIT_WSD
  12260. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12261. #endif
  12262. /*
  12263. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12264. ** created by mkopcodeh.awk during compilation. Data is obtained
  12265. ** from the comments following the "case OP_xxxx:" statements in
  12266. ** the vdbe.c file.
  12267. */
  12268. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12269. /************** End of global.c **********************************************/
  12270. /************** Begin file ctime.c *******************************************/
  12271. /*
  12272. ** 2010 February 23
  12273. **
  12274. ** The author disclaims copyright to this source code. In place of
  12275. ** a legal notice, here is a blessing:
  12276. **
  12277. ** May you do good and not evil.
  12278. ** May you find forgiveness for yourself and forgive others.
  12279. ** May you share freely, never taking more than you give.
  12280. **
  12281. *************************************************************************
  12282. **
  12283. ** This file implements routines used to report what compile-time options
  12284. ** SQLite was built with.
  12285. */
  12286. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12287. /*
  12288. ** An array of names of all compile-time options. This array should
  12289. ** be sorted A-Z.
  12290. **
  12291. ** This array looks large, but in a typical installation actually uses
  12292. ** only a handful of compile-time options, so most times this array is usually
  12293. ** rather short and uses little memory space.
  12294. */
  12295. static const char * const azCompileOpt[] = {
  12296. /* These macros are provided to "stringify" the value of the define
  12297. ** for those options in which the value is meaningful. */
  12298. #define CTIMEOPT_VAL_(opt) #opt
  12299. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  12300. #ifdef SQLITE_32BIT_ROWID
  12301. "32BIT_ROWID",
  12302. #endif
  12303. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  12304. "4_BYTE_ALIGNED_MALLOC",
  12305. #endif
  12306. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  12307. "CASE_SENSITIVE_LIKE",
  12308. #endif
  12309. #ifdef SQLITE_CHECK_PAGES
  12310. "CHECK_PAGES",
  12311. #endif
  12312. #ifdef SQLITE_COVERAGE_TEST
  12313. "COVERAGE_TEST",
  12314. #endif
  12315. #ifdef SQLITE_DEBUG
  12316. "DEBUG",
  12317. #endif
  12318. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  12319. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  12320. #endif
  12321. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  12322. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  12323. #endif
  12324. #ifdef SQLITE_DISABLE_DIRSYNC
  12325. "DISABLE_DIRSYNC",
  12326. #endif
  12327. #ifdef SQLITE_DISABLE_LFS
  12328. "DISABLE_LFS",
  12329. #endif
  12330. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12331. "ENABLE_ATOMIC_WRITE",
  12332. #endif
  12333. #ifdef SQLITE_ENABLE_CEROD
  12334. "ENABLE_CEROD",
  12335. #endif
  12336. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  12337. "ENABLE_COLUMN_METADATA",
  12338. #endif
  12339. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  12340. "ENABLE_EXPENSIVE_ASSERT",
  12341. #endif
  12342. #ifdef SQLITE_ENABLE_FTS1
  12343. "ENABLE_FTS1",
  12344. #endif
  12345. #ifdef SQLITE_ENABLE_FTS2
  12346. "ENABLE_FTS2",
  12347. #endif
  12348. #ifdef SQLITE_ENABLE_FTS3
  12349. "ENABLE_FTS3",
  12350. #endif
  12351. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  12352. "ENABLE_FTS3_PARENTHESIS",
  12353. #endif
  12354. #ifdef SQLITE_ENABLE_FTS4
  12355. "ENABLE_FTS4",
  12356. #endif
  12357. #ifdef SQLITE_ENABLE_ICU
  12358. "ENABLE_ICU",
  12359. #endif
  12360. #ifdef SQLITE_ENABLE_IOTRACE
  12361. "ENABLE_IOTRACE",
  12362. #endif
  12363. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  12364. "ENABLE_LOAD_EXTENSION",
  12365. #endif
  12366. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  12367. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  12368. #endif
  12369. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  12370. "ENABLE_MEMORY_MANAGEMENT",
  12371. #endif
  12372. #ifdef SQLITE_ENABLE_MEMSYS3
  12373. "ENABLE_MEMSYS3",
  12374. #endif
  12375. #ifdef SQLITE_ENABLE_MEMSYS5
  12376. "ENABLE_MEMSYS5",
  12377. #endif
  12378. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  12379. "ENABLE_OVERSIZE_CELL_CHECK",
  12380. #endif
  12381. #ifdef SQLITE_ENABLE_RTREE
  12382. "ENABLE_RTREE",
  12383. #endif
  12384. #if defined(SQLITE_ENABLE_STAT4)
  12385. "ENABLE_STAT4",
  12386. #elif defined(SQLITE_ENABLE_STAT3)
  12387. "ENABLE_STAT3",
  12388. #endif
  12389. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12390. "ENABLE_UNLOCK_NOTIFY",
  12391. #endif
  12392. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  12393. "ENABLE_UPDATE_DELETE_LIMIT",
  12394. #endif
  12395. #ifdef SQLITE_HAS_CODEC
  12396. "HAS_CODEC",
  12397. #endif
  12398. #ifdef SQLITE_HAVE_ISNAN
  12399. "HAVE_ISNAN",
  12400. #endif
  12401. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  12402. "HOMEGROWN_RECURSIVE_MUTEX",
  12403. #endif
  12404. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  12405. "IGNORE_AFP_LOCK_ERRORS",
  12406. #endif
  12407. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  12408. "IGNORE_FLOCK_LOCK_ERRORS",
  12409. #endif
  12410. #ifdef SQLITE_INT64_TYPE
  12411. "INT64_TYPE",
  12412. #endif
  12413. #ifdef SQLITE_LOCK_TRACE
  12414. "LOCK_TRACE",
  12415. #endif
  12416. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  12417. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  12418. #endif
  12419. #ifdef SQLITE_MAX_SCHEMA_RETRY
  12420. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  12421. #endif
  12422. #ifdef SQLITE_MEMDEBUG
  12423. "MEMDEBUG",
  12424. #endif
  12425. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  12426. "MIXED_ENDIAN_64BIT_FLOAT",
  12427. #endif
  12428. #ifdef SQLITE_NO_SYNC
  12429. "NO_SYNC",
  12430. #endif
  12431. #ifdef SQLITE_OMIT_ALTERTABLE
  12432. "OMIT_ALTERTABLE",
  12433. #endif
  12434. #ifdef SQLITE_OMIT_ANALYZE
  12435. "OMIT_ANALYZE",
  12436. #endif
  12437. #ifdef SQLITE_OMIT_ATTACH
  12438. "OMIT_ATTACH",
  12439. #endif
  12440. #ifdef SQLITE_OMIT_AUTHORIZATION
  12441. "OMIT_AUTHORIZATION",
  12442. #endif
  12443. #ifdef SQLITE_OMIT_AUTOINCREMENT
  12444. "OMIT_AUTOINCREMENT",
  12445. #endif
  12446. #ifdef SQLITE_OMIT_AUTOINIT
  12447. "OMIT_AUTOINIT",
  12448. #endif
  12449. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  12450. "OMIT_AUTOMATIC_INDEX",
  12451. #endif
  12452. #ifdef SQLITE_OMIT_AUTORESET
  12453. "OMIT_AUTORESET",
  12454. #endif
  12455. #ifdef SQLITE_OMIT_AUTOVACUUM
  12456. "OMIT_AUTOVACUUM",
  12457. #endif
  12458. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  12459. "OMIT_BETWEEN_OPTIMIZATION",
  12460. #endif
  12461. #ifdef SQLITE_OMIT_BLOB_LITERAL
  12462. "OMIT_BLOB_LITERAL",
  12463. #endif
  12464. #ifdef SQLITE_OMIT_BTREECOUNT
  12465. "OMIT_BTREECOUNT",
  12466. #endif
  12467. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12468. "OMIT_BUILTIN_TEST",
  12469. #endif
  12470. #ifdef SQLITE_OMIT_CAST
  12471. "OMIT_CAST",
  12472. #endif
  12473. #ifdef SQLITE_OMIT_CHECK
  12474. "OMIT_CHECK",
  12475. #endif
  12476. #ifdef SQLITE_OMIT_COMPLETE
  12477. "OMIT_COMPLETE",
  12478. #endif
  12479. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  12480. "OMIT_COMPOUND_SELECT",
  12481. #endif
  12482. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  12483. "OMIT_DATETIME_FUNCS",
  12484. #endif
  12485. #ifdef SQLITE_OMIT_DECLTYPE
  12486. "OMIT_DECLTYPE",
  12487. #endif
  12488. #ifdef SQLITE_OMIT_DEPRECATED
  12489. "OMIT_DEPRECATED",
  12490. #endif
  12491. #ifdef SQLITE_OMIT_DISKIO
  12492. "OMIT_DISKIO",
  12493. #endif
  12494. #ifdef SQLITE_OMIT_EXPLAIN
  12495. "OMIT_EXPLAIN",
  12496. #endif
  12497. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  12498. "OMIT_FLAG_PRAGMAS",
  12499. #endif
  12500. #ifdef SQLITE_OMIT_FLOATING_POINT
  12501. "OMIT_FLOATING_POINT",
  12502. #endif
  12503. #ifdef SQLITE_OMIT_FOREIGN_KEY
  12504. "OMIT_FOREIGN_KEY",
  12505. #endif
  12506. #ifdef SQLITE_OMIT_GET_TABLE
  12507. "OMIT_GET_TABLE",
  12508. #endif
  12509. #ifdef SQLITE_OMIT_INCRBLOB
  12510. "OMIT_INCRBLOB",
  12511. #endif
  12512. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  12513. "OMIT_INTEGRITY_CHECK",
  12514. #endif
  12515. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  12516. "OMIT_LIKE_OPTIMIZATION",
  12517. #endif
  12518. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  12519. "OMIT_LOAD_EXTENSION",
  12520. #endif
  12521. #ifdef SQLITE_OMIT_LOCALTIME
  12522. "OMIT_LOCALTIME",
  12523. #endif
  12524. #ifdef SQLITE_OMIT_LOOKASIDE
  12525. "OMIT_LOOKASIDE",
  12526. #endif
  12527. #ifdef SQLITE_OMIT_MEMORYDB
  12528. "OMIT_MEMORYDB",
  12529. #endif
  12530. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  12531. "OMIT_OR_OPTIMIZATION",
  12532. #endif
  12533. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  12534. "OMIT_PAGER_PRAGMAS",
  12535. #endif
  12536. #ifdef SQLITE_OMIT_PRAGMA
  12537. "OMIT_PRAGMA",
  12538. #endif
  12539. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  12540. "OMIT_PROGRESS_CALLBACK",
  12541. #endif
  12542. #ifdef SQLITE_OMIT_QUICKBALANCE
  12543. "OMIT_QUICKBALANCE",
  12544. #endif
  12545. #ifdef SQLITE_OMIT_REINDEX
  12546. "OMIT_REINDEX",
  12547. #endif
  12548. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  12549. "OMIT_SCHEMA_PRAGMAS",
  12550. #endif
  12551. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  12552. "OMIT_SCHEMA_VERSION_PRAGMAS",
  12553. #endif
  12554. #ifdef SQLITE_OMIT_SHARED_CACHE
  12555. "OMIT_SHARED_CACHE",
  12556. #endif
  12557. #ifdef SQLITE_OMIT_SUBQUERY
  12558. "OMIT_SUBQUERY",
  12559. #endif
  12560. #ifdef SQLITE_OMIT_TCL_VARIABLE
  12561. "OMIT_TCL_VARIABLE",
  12562. #endif
  12563. #ifdef SQLITE_OMIT_TEMPDB
  12564. "OMIT_TEMPDB",
  12565. #endif
  12566. #ifdef SQLITE_OMIT_TRACE
  12567. "OMIT_TRACE",
  12568. #endif
  12569. #ifdef SQLITE_OMIT_TRIGGER
  12570. "OMIT_TRIGGER",
  12571. #endif
  12572. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  12573. "OMIT_TRUNCATE_OPTIMIZATION",
  12574. #endif
  12575. #ifdef SQLITE_OMIT_UTF16
  12576. "OMIT_UTF16",
  12577. #endif
  12578. #ifdef SQLITE_OMIT_VACUUM
  12579. "OMIT_VACUUM",
  12580. #endif
  12581. #ifdef SQLITE_OMIT_VIEW
  12582. "OMIT_VIEW",
  12583. #endif
  12584. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12585. "OMIT_VIRTUALTABLE",
  12586. #endif
  12587. #ifdef SQLITE_OMIT_WAL
  12588. "OMIT_WAL",
  12589. #endif
  12590. #ifdef SQLITE_OMIT_WSD
  12591. "OMIT_WSD",
  12592. #endif
  12593. #ifdef SQLITE_OMIT_XFER_OPT
  12594. "OMIT_XFER_OPT",
  12595. #endif
  12596. #ifdef SQLITE_PERFORMANCE_TRACE
  12597. "PERFORMANCE_TRACE",
  12598. #endif
  12599. #ifdef SQLITE_PROXY_DEBUG
  12600. "PROXY_DEBUG",
  12601. #endif
  12602. #ifdef SQLITE_RTREE_INT_ONLY
  12603. "RTREE_INT_ONLY",
  12604. #endif
  12605. #ifdef SQLITE_SECURE_DELETE
  12606. "SECURE_DELETE",
  12607. #endif
  12608. #ifdef SQLITE_SMALL_STACK
  12609. "SMALL_STACK",
  12610. #endif
  12611. #ifdef SQLITE_SOUNDEX
  12612. "SOUNDEX",
  12613. #endif
  12614. #ifdef SQLITE_TCL
  12615. "TCL",
  12616. #endif
  12617. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  12618. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  12619. #endif
  12620. #ifdef SQLITE_TEST
  12621. "TEST",
  12622. #endif
  12623. #if defined(SQLITE_THREADSAFE)
  12624. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  12625. #endif
  12626. #ifdef SQLITE_USE_ALLOCA
  12627. "USE_ALLOCA",
  12628. #endif
  12629. #ifdef SQLITE_ZERO_MALLOC
  12630. "ZERO_MALLOC"
  12631. #endif
  12632. };
  12633. /*
  12634. ** Given the name of a compile-time option, return true if that option
  12635. ** was used and false if not.
  12636. **
  12637. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  12638. ** is not required for a match.
  12639. */
  12640. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  12641. int i, n;
  12642. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  12643. n = sqlite3Strlen30(zOptName);
  12644. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  12645. ** linear search is adequate. No need for a binary search. */
  12646. for(i=0; i<ArraySize(azCompileOpt); i++){
  12647. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  12648. && sqlite3CtypeMap[(unsigned char)azCompileOpt[i][n]]==0
  12649. ){
  12650. return 1;
  12651. }
  12652. }
  12653. return 0;
  12654. }
  12655. /*
  12656. ** Return the N-th compile-time option string. If N is out of range,
  12657. ** return a NULL pointer.
  12658. */
  12659. SQLITE_API const char *sqlite3_compileoption_get(int N){
  12660. if( N>=0 && N<ArraySize(azCompileOpt) ){
  12661. return azCompileOpt[N];
  12662. }
  12663. return 0;
  12664. }
  12665. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  12666. /************** End of ctime.c ***********************************************/
  12667. /************** Begin file status.c ******************************************/
  12668. /*
  12669. ** 2008 June 18
  12670. **
  12671. ** The author disclaims copyright to this source code. In place of
  12672. ** a legal notice, here is a blessing:
  12673. **
  12674. ** May you do good and not evil.
  12675. ** May you find forgiveness for yourself and forgive others.
  12676. ** May you share freely, never taking more than you give.
  12677. **
  12678. *************************************************************************
  12679. **
  12680. ** This module implements the sqlite3_status() interface and related
  12681. ** functionality.
  12682. */
  12683. /************** Include vdbeInt.h in the middle of status.c ******************/
  12684. /************** Begin file vdbeInt.h *****************************************/
  12685. /*
  12686. ** 2003 September 6
  12687. **
  12688. ** The author disclaims copyright to this source code. In place of
  12689. ** a legal notice, here is a blessing:
  12690. **
  12691. ** May you do good and not evil.
  12692. ** May you find forgiveness for yourself and forgive others.
  12693. ** May you share freely, never taking more than you give.
  12694. **
  12695. *************************************************************************
  12696. ** This is the header file for information that is private to the
  12697. ** VDBE. This information used to all be at the top of the single
  12698. ** source code file "vdbe.c". When that file became too big (over
  12699. ** 6000 lines long) it was split up into several smaller files and
  12700. ** this header information was factored out.
  12701. */
  12702. #ifndef _VDBEINT_H_
  12703. #define _VDBEINT_H_
  12704. /*
  12705. ** The maximum number of times that a statement will try to reparse
  12706. ** itself before giving up and returning SQLITE_SCHEMA.
  12707. */
  12708. #ifndef SQLITE_MAX_SCHEMA_RETRY
  12709. # define SQLITE_MAX_SCHEMA_RETRY 50
  12710. #endif
  12711. /*
  12712. ** SQL is translated into a sequence of instructions to be
  12713. ** executed by a virtual machine. Each instruction is an instance
  12714. ** of the following structure.
  12715. */
  12716. typedef struct VdbeOp Op;
  12717. /*
  12718. ** Boolean values
  12719. */
  12720. typedef unsigned char Bool;
  12721. /* Opaque type used by code in vdbesort.c */
  12722. typedef struct VdbeSorter VdbeSorter;
  12723. /* Opaque type used by the explainer */
  12724. typedef struct Explain Explain;
  12725. /* Elements of the linked list at Vdbe.pAuxData */
  12726. typedef struct AuxData AuxData;
  12727. /*
  12728. ** A cursor is a pointer into a single BTree within a database file.
  12729. ** The cursor can seek to a BTree entry with a particular key, or
  12730. ** loop over all entries of the Btree. You can also insert new BTree
  12731. ** entries or retrieve the key or data from the entry that the cursor
  12732. ** is currently pointing to.
  12733. **
  12734. ** Every cursor that the virtual machine has open is represented by an
  12735. ** instance of the following structure.
  12736. */
  12737. struct VdbeCursor {
  12738. BtCursor *pCursor; /* The cursor structure of the backend */
  12739. Btree *pBt; /* Separate file holding temporary table */
  12740. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  12741. int iDb; /* Index of cursor database in db->aDb[] (or -1) */
  12742. int pseudoTableReg; /* Register holding pseudotable content. */
  12743. int nField; /* Number of fields in the header */
  12744. Bool zeroed; /* True if zeroed out and ready for reuse */
  12745. Bool rowidIsValid; /* True if lastRowid is valid */
  12746. Bool atFirst; /* True if pointing to first entry */
  12747. Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  12748. Bool nullRow; /* True if pointing to a row with no data */
  12749. Bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  12750. Bool isTable; /* True if a table requiring integer keys */
  12751. Bool isIndex; /* True if an index containing keys only - no data */
  12752. Bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
  12753. Bool isSorter; /* True if a new-style sorter */
  12754. Bool multiPseudo; /* Multi-register pseudo-cursor */
  12755. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  12756. const sqlite3_module *pModule; /* Module for cursor pVtabCursor */
  12757. i64 seqCount; /* Sequence counter */
  12758. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  12759. i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
  12760. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  12761. /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
  12762. ** OP_IsUnique opcode on this cursor. */
  12763. int seekResult;
  12764. /* Cached information about the header for the data record that the
  12765. ** cursor is currently pointing to. Only valid if cacheStatus matches
  12766. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  12767. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  12768. ** the cache is out of date.
  12769. **
  12770. ** aRow might point to (ephemeral) data for the current row, or it might
  12771. ** be NULL.
  12772. */
  12773. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  12774. int payloadSize; /* Total number of bytes in the record */
  12775. u32 *aType; /* Type values for all entries in the record */
  12776. u32 *aOffset; /* Cached offsets to the start of each columns data */
  12777. u8 *aRow; /* Data for the current row, if all on one page */
  12778. };
  12779. typedef struct VdbeCursor VdbeCursor;
  12780. /*
  12781. ** When a sub-program is executed (OP_Program), a structure of this type
  12782. ** is allocated to store the current value of the program counter, as
  12783. ** well as the current memory cell array and various other frame specific
  12784. ** values stored in the Vdbe struct. When the sub-program is finished,
  12785. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  12786. ** restoring the state of the VM to as it was before the sub-program
  12787. ** began executing.
  12788. **
  12789. ** The memory for a VdbeFrame object is allocated and managed by a memory
  12790. ** cell in the parent (calling) frame. When the memory cell is deleted or
  12791. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  12792. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  12793. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  12794. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  12795. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  12796. ** child frame are released.
  12797. **
  12798. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  12799. ** set to NULL if the currently executing frame is the main program.
  12800. */
  12801. typedef struct VdbeFrame VdbeFrame;
  12802. struct VdbeFrame {
  12803. Vdbe *v; /* VM this frame belongs to */
  12804. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  12805. Op *aOp; /* Program instructions for parent frame */
  12806. Mem *aMem; /* Array of memory cells for parent frame */
  12807. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  12808. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  12809. void *token; /* Copy of SubProgram.token */
  12810. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  12811. int nCursor; /* Number of entries in apCsr */
  12812. int pc; /* Program Counter in parent (calling) frame */
  12813. int nOp; /* Size of aOp array */
  12814. int nMem; /* Number of entries in aMem */
  12815. int nOnceFlag; /* Number of entries in aOnceFlag */
  12816. int nChildMem; /* Number of memory cells for child frame */
  12817. int nChildCsr; /* Number of cursors for child frame */
  12818. int nChange; /* Statement changes (Vdbe.nChanges) */
  12819. };
  12820. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  12821. /*
  12822. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  12823. */
  12824. #define CACHE_STALE 0
  12825. /*
  12826. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  12827. ** structures. Each Mem struct may cache multiple representations (string,
  12828. ** integer etc.) of the same value.
  12829. */
  12830. struct Mem {
  12831. sqlite3 *db; /* The associated database connection */
  12832. char *z; /* String or BLOB value */
  12833. double r; /* Real value */
  12834. union {
  12835. i64 i; /* Integer value used when MEM_Int is set in flags */
  12836. int nZero; /* Used when bit MEM_Zero is set in flags */
  12837. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  12838. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  12839. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  12840. } u;
  12841. int n; /* Number of characters in string value, excluding '\0' */
  12842. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  12843. u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
  12844. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  12845. #ifdef SQLITE_DEBUG
  12846. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  12847. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  12848. #endif
  12849. void (*xDel)(void *); /* If not null, call this function to delete Mem.z */
  12850. char *zMalloc; /* Dynamic buffer allocated by sqlite3_malloc() */
  12851. };
  12852. /* One or more of the following flags are set to indicate the validOK
  12853. ** representations of the value stored in the Mem struct.
  12854. **
  12855. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  12856. ** No other flags may be set in this case.
  12857. **
  12858. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  12859. ** Usually this is encoded in the same unicode encoding as the main
  12860. ** database (see below for exceptions). If the MEM_Term flag is also
  12861. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  12862. ** flags may coexist with the MEM_Str flag.
  12863. */
  12864. #define MEM_Null 0x0001 /* Value is NULL */
  12865. #define MEM_Str 0x0002 /* Value is a string */
  12866. #define MEM_Int 0x0004 /* Value is an integer */
  12867. #define MEM_Real 0x0008 /* Value is a real number */
  12868. #define MEM_Blob 0x0010 /* Value is a BLOB */
  12869. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  12870. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  12871. #define MEM_Invalid 0x0080 /* Value is undefined */
  12872. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  12873. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  12874. /* Whenever Mem contains a valid string or blob representation, one of
  12875. ** the following flags must be set to determine the memory management
  12876. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  12877. ** string is \000 or \u0000 terminated
  12878. */
  12879. #define MEM_Term 0x0200 /* String rep is nul terminated */
  12880. #define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
  12881. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  12882. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  12883. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  12884. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  12885. #ifdef SQLITE_OMIT_INCRBLOB
  12886. #undef MEM_Zero
  12887. #define MEM_Zero 0x0000
  12888. #endif
  12889. /*
  12890. ** Clear any existing type flags from a Mem and replace them with f
  12891. */
  12892. #define MemSetTypeFlag(p, f) \
  12893. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  12894. /*
  12895. ** Return true if a memory cell is not marked as invalid. This macro
  12896. ** is for use inside assert() statements only.
  12897. */
  12898. #ifdef SQLITE_DEBUG
  12899. #define memIsValid(M) ((M)->flags & MEM_Invalid)==0
  12900. #endif
  12901. /*
  12902. ** Each auxilliary data pointer stored by a user defined function
  12903. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  12904. ** of this structure. All such structures associated with a single VM
  12905. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  12906. ** when the VM is halted (if not before).
  12907. */
  12908. struct AuxData {
  12909. int iOp; /* Instruction number of OP_Function opcode */
  12910. int iArg; /* Index of function argument. */
  12911. void *pAux; /* Aux data pointer */
  12912. void (*xDelete)(void *); /* Destructor for the aux data */
  12913. AuxData *pNext; /* Next element in list */
  12914. };
  12915. /*
  12916. ** The "context" argument for a installable function. A pointer to an
  12917. ** instance of this structure is the first argument to the routines used
  12918. ** implement the SQL functions.
  12919. **
  12920. ** There is a typedef for this structure in sqlite.h. So all routines,
  12921. ** even the public interface to SQLite, can use a pointer to this structure.
  12922. ** But this file is the only place where the internal details of this
  12923. ** structure are known.
  12924. **
  12925. ** This structure is defined inside of vdbeInt.h because it uses substructures
  12926. ** (Mem) which are only defined there.
  12927. */
  12928. struct sqlite3_context {
  12929. FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  12930. Mem s; /* The return value is stored here */
  12931. Mem *pMem; /* Memory cell used to store aggregate context */
  12932. CollSeq *pColl; /* Collating sequence */
  12933. Vdbe *pVdbe; /* The VM that owns this context */
  12934. int iOp; /* Instruction number of OP_Function */
  12935. int isError; /* Error code returned by the function. */
  12936. u8 skipFlag; /* Skip skip accumulator loading if true */
  12937. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  12938. };
  12939. /*
  12940. ** An Explain object accumulates indented output which is helpful
  12941. ** in describing recursive data structures.
  12942. */
  12943. struct Explain {
  12944. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  12945. StrAccum str; /* The string being accumulated */
  12946. int nIndent; /* Number of elements in aIndent */
  12947. u16 aIndent[100]; /* Levels of indentation */
  12948. char zBase[100]; /* Initial space */
  12949. };
  12950. /* A bitfield type for use inside of structures. Always follow with :N where
  12951. ** N is the number of bits.
  12952. */
  12953. typedef unsigned bft; /* Bit Field Type */
  12954. /*
  12955. ** An instance of the virtual machine. This structure contains the complete
  12956. ** state of the virtual machine.
  12957. **
  12958. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  12959. ** is really a pointer to an instance of this structure.
  12960. **
  12961. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  12962. ** any virtual table method invocations made by the vdbe program. It is
  12963. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  12964. ** variable is used for two purposes: to allow xDestroy methods to execute
  12965. ** "DROP TABLE" statements and to prevent some nasty side effects of
  12966. ** malloc failure when SQLite is invoked recursively by a virtual table
  12967. ** method function.
  12968. */
  12969. struct Vdbe {
  12970. sqlite3 *db; /* The database connection that owns this statement */
  12971. Op *aOp; /* Space to hold the virtual machine's program */
  12972. Mem *aMem; /* The memory locations */
  12973. Mem **apArg; /* Arguments to currently executing user function */
  12974. Mem *aColName; /* Column names to return */
  12975. Mem *pResultSet; /* Pointer to an array of results */
  12976. int nMem; /* Number of memory locations currently allocated */
  12977. int nOp; /* Number of instructions in the program */
  12978. int nOpAlloc; /* Number of slots allocated for aOp[] */
  12979. int nLabel; /* Number of labels used */
  12980. int *aLabel; /* Space to hold the labels */
  12981. u16 nResColumn; /* Number of columns in one row of the result set */
  12982. int nCursor; /* Number of slots in apCsr[] */
  12983. u32 magic; /* Magic number for sanity checking */
  12984. char *zErrMsg; /* Error message written here */
  12985. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  12986. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  12987. Mem *aVar; /* Values for the OP_Variable opcode. */
  12988. char **azVar; /* Name of variables */
  12989. ynVar nVar; /* Number of entries in aVar[] */
  12990. ynVar nzVar; /* Number of entries in azVar[] */
  12991. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  12992. int pc; /* The program counter */
  12993. int rc; /* Value to return */
  12994. u8 errorAction; /* Recovery action to do in case of an error */
  12995. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  12996. bft explain:2; /* True if EXPLAIN present on SQL command */
  12997. bft inVtabMethod:2; /* See comments above */
  12998. bft changeCntOn:1; /* True to update the change-counter */
  12999. bft expired:1; /* True if the VM needs to be recompiled */
  13000. bft runOnlyOnce:1; /* Automatically expire on reset */
  13001. bft usesStmtJournal:1; /* True if uses a statement journal */
  13002. bft readOnly:1; /* True for statements that do not write */
  13003. bft bIsReader:1; /* True for statements that read */
  13004. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  13005. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  13006. int nChange; /* Number of db changes made since last reset */
  13007. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  13008. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13009. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13010. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13011. #ifndef SQLITE_OMIT_TRACE
  13012. i64 startTime; /* Time when query started - used for profiling */
  13013. #endif
  13014. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13015. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13016. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13017. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13018. char *zSql; /* Text of the SQL statement that generated this */
  13019. void *pFree; /* Free this when deleting the vdbe */
  13020. #ifdef SQLITE_DEBUG
  13021. FILE *trace; /* Write an execution trace here, if not NULL */
  13022. #endif
  13023. #ifdef SQLITE_ENABLE_TREE_EXPLAIN
  13024. Explain *pExplain; /* The explainer */
  13025. char *zExplain; /* Explanation of data structures */
  13026. #endif
  13027. VdbeFrame *pFrame; /* Parent frame */
  13028. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13029. int nFrame; /* Number of frames in pFrame list */
  13030. u32 expmask; /* Binding to these vars invalidates VM */
  13031. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13032. int nOnceFlag; /* Size of array aOnceFlag[] */
  13033. u8 *aOnceFlag; /* Flags for OP_Once */
  13034. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13035. };
  13036. /*
  13037. ** The following are allowed values for Vdbe.magic
  13038. */
  13039. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13040. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13041. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13042. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13043. /*
  13044. ** Function prototypes
  13045. */
  13046. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13047. void sqliteVdbePopStack(Vdbe*,int);
  13048. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13049. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13050. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13051. #endif
  13052. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13053. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13054. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
  13055. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13056. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13057. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13058. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
  13059. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
  13060. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  13061. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13062. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13063. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13064. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13065. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13066. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13067. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13068. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13069. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13070. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13071. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13072. #ifdef SQLITE_OMIT_FLOATING_POINT
  13073. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13074. #else
  13075. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13076. #endif
  13077. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13078. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13079. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13080. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13081. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
  13082. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13083. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13084. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13085. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13086. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13087. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13088. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
  13089. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13090. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
  13091. #define VdbeMemRelease(X) \
  13092. if((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame)) \
  13093. sqlite3VdbeMemReleaseExternal(X);
  13094. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13095. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13096. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13097. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13098. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13099. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13100. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
  13101. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13102. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, VdbeCursor *);
  13103. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13104. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13105. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13106. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *, const VdbeCursor *, int *);
  13107. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(sqlite3 *, const VdbeCursor *, Mem *);
  13108. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int *);
  13109. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13110. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13111. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13112. #else
  13113. # define sqlite3VdbeEnter(X)
  13114. # define sqlite3VdbeLeave(X)
  13115. #endif
  13116. #ifdef SQLITE_DEBUG
  13117. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13118. #endif
  13119. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13120. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13121. #else
  13122. # define sqlite3VdbeCheckFk(p,i) 0
  13123. #endif
  13124. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13125. #ifdef SQLITE_DEBUG
  13126. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13127. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13128. #endif
  13129. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13130. #ifndef SQLITE_OMIT_INCRBLOB
  13131. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13132. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13133. #else
  13134. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13135. #define ExpandBlob(P) SQLITE_OK
  13136. #endif
  13137. #endif /* !defined(_VDBEINT_H_) */
  13138. /************** End of vdbeInt.h *********************************************/
  13139. /************** Continuing where we left off in status.c *********************/
  13140. /*
  13141. ** Variables in which to record status information.
  13142. */
  13143. typedef struct sqlite3StatType sqlite3StatType;
  13144. static SQLITE_WSD struct sqlite3StatType {
  13145. int nowValue[10]; /* Current value */
  13146. int mxValue[10]; /* Maximum value */
  13147. } sqlite3Stat = { {0,}, {0,} };
  13148. /* The "wsdStat" macro will resolve to the status information
  13149. ** state vector. If writable static data is unsupported on the target,
  13150. ** we have to locate the state vector at run-time. In the more common
  13151. ** case where writable static data is supported, wsdStat can refer directly
  13152. ** to the "sqlite3Stat" state vector declared above.
  13153. */
  13154. #ifdef SQLITE_OMIT_WSD
  13155. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13156. # define wsdStat x[0]
  13157. #else
  13158. # define wsdStatInit
  13159. # define wsdStat sqlite3Stat
  13160. #endif
  13161. /*
  13162. ** Return the current value of a status parameter.
  13163. */
  13164. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13165. wsdStatInit;
  13166. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13167. return wsdStat.nowValue[op];
  13168. }
  13169. /*
  13170. ** Add N to the value of a status record. It is assumed that the
  13171. ** caller holds appropriate locks.
  13172. */
  13173. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13174. wsdStatInit;
  13175. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13176. wsdStat.nowValue[op] += N;
  13177. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13178. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13179. }
  13180. }
  13181. /*
  13182. ** Set the value of a status to X.
  13183. */
  13184. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13185. wsdStatInit;
  13186. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13187. wsdStat.nowValue[op] = X;
  13188. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13189. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13190. }
  13191. }
  13192. /*
  13193. ** Query status information.
  13194. **
  13195. ** This implementation assumes that reading or writing an aligned
  13196. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13197. ** then this routine is not threadsafe.
  13198. */
  13199. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13200. wsdStatInit;
  13201. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13202. return SQLITE_MISUSE_BKPT;
  13203. }
  13204. *pCurrent = wsdStat.nowValue[op];
  13205. *pHighwater = wsdStat.mxValue[op];
  13206. if( resetFlag ){
  13207. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13208. }
  13209. return SQLITE_OK;
  13210. }
  13211. /*
  13212. ** Query status information for a single database connection
  13213. */
  13214. SQLITE_API int sqlite3_db_status(
  13215. sqlite3 *db, /* The database connection whose status is desired */
  13216. int op, /* Status verb */
  13217. int *pCurrent, /* Write current value here */
  13218. int *pHighwater, /* Write high-water mark here */
  13219. int resetFlag /* Reset high-water mark if true */
  13220. ){
  13221. int rc = SQLITE_OK; /* Return code */
  13222. sqlite3_mutex_enter(db->mutex);
  13223. switch( op ){
  13224. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13225. *pCurrent = db->lookaside.nOut;
  13226. *pHighwater = db->lookaside.mxOut;
  13227. if( resetFlag ){
  13228. db->lookaside.mxOut = db->lookaside.nOut;
  13229. }
  13230. break;
  13231. }
  13232. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13233. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13234. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13235. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13236. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13237. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13238. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13239. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13240. *pCurrent = 0;
  13241. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13242. if( resetFlag ){
  13243. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13244. }
  13245. break;
  13246. }
  13247. /*
  13248. ** Return an approximation for the amount of memory currently used
  13249. ** by all pagers associated with the given database connection. The
  13250. ** highwater mark is meaningless and is returned as zero.
  13251. */
  13252. case SQLITE_DBSTATUS_CACHE_USED: {
  13253. int totalUsed = 0;
  13254. int i;
  13255. sqlite3BtreeEnterAll(db);
  13256. for(i=0; i<db->nDb; i++){
  13257. Btree *pBt = db->aDb[i].pBt;
  13258. if( pBt ){
  13259. Pager *pPager = sqlite3BtreePager(pBt);
  13260. totalUsed += sqlite3PagerMemUsed(pPager);
  13261. }
  13262. }
  13263. sqlite3BtreeLeaveAll(db);
  13264. *pCurrent = totalUsed;
  13265. *pHighwater = 0;
  13266. break;
  13267. }
  13268. /*
  13269. ** *pCurrent gets an accurate estimate of the amount of memory used
  13270. ** to store the schema for all databases (main, temp, and any ATTACHed
  13271. ** databases. *pHighwater is set to zero.
  13272. */
  13273. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13274. int i; /* Used to iterate through schemas */
  13275. int nByte = 0; /* Used to accumulate return value */
  13276. sqlite3BtreeEnterAll(db);
  13277. db->pnBytesFreed = &nByte;
  13278. for(i=0; i<db->nDb; i++){
  13279. Schema *pSchema = db->aDb[i].pSchema;
  13280. if( ALWAYS(pSchema!=0) ){
  13281. HashElem *p;
  13282. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13283. pSchema->tblHash.count
  13284. + pSchema->trigHash.count
  13285. + pSchema->idxHash.count
  13286. + pSchema->fkeyHash.count
  13287. );
  13288. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  13289. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  13290. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  13291. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  13292. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  13293. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  13294. }
  13295. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  13296. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  13297. }
  13298. }
  13299. }
  13300. db->pnBytesFreed = 0;
  13301. sqlite3BtreeLeaveAll(db);
  13302. *pHighwater = 0;
  13303. *pCurrent = nByte;
  13304. break;
  13305. }
  13306. /*
  13307. ** *pCurrent gets an accurate estimate of the amount of memory used
  13308. ** to store all prepared statements.
  13309. ** *pHighwater is set to zero.
  13310. */
  13311. case SQLITE_DBSTATUS_STMT_USED: {
  13312. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  13313. int nByte = 0; /* Used to accumulate return value */
  13314. db->pnBytesFreed = &nByte;
  13315. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  13316. sqlite3VdbeClearObject(db, pVdbe);
  13317. sqlite3DbFree(db, pVdbe);
  13318. }
  13319. db->pnBytesFreed = 0;
  13320. *pHighwater = 0;
  13321. *pCurrent = nByte;
  13322. break;
  13323. }
  13324. /*
  13325. ** Set *pCurrent to the total cache hits or misses encountered by all
  13326. ** pagers the database handle is connected to. *pHighwater is always set
  13327. ** to zero.
  13328. */
  13329. case SQLITE_DBSTATUS_CACHE_HIT:
  13330. case SQLITE_DBSTATUS_CACHE_MISS:
  13331. case SQLITE_DBSTATUS_CACHE_WRITE:{
  13332. int i;
  13333. int nRet = 0;
  13334. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  13335. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  13336. for(i=0; i<db->nDb; i++){
  13337. if( db->aDb[i].pBt ){
  13338. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  13339. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  13340. }
  13341. }
  13342. *pHighwater = 0;
  13343. *pCurrent = nRet;
  13344. break;
  13345. }
  13346. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  13347. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  13348. ** have been satisfied. The *pHighwater is always set to zero.
  13349. */
  13350. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  13351. *pHighwater = 0;
  13352. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  13353. break;
  13354. }
  13355. default: {
  13356. rc = SQLITE_ERROR;
  13357. }
  13358. }
  13359. sqlite3_mutex_leave(db->mutex);
  13360. return rc;
  13361. }
  13362. /************** End of status.c **********************************************/
  13363. /************** Begin file date.c ********************************************/
  13364. /*
  13365. ** 2003 October 31
  13366. **
  13367. ** The author disclaims copyright to this source code. In place of
  13368. ** a legal notice, here is a blessing:
  13369. **
  13370. ** May you do good and not evil.
  13371. ** May you find forgiveness for yourself and forgive others.
  13372. ** May you share freely, never taking more than you give.
  13373. **
  13374. *************************************************************************
  13375. ** This file contains the C functions that implement date and time
  13376. ** functions for SQLite.
  13377. **
  13378. ** There is only one exported symbol in this file - the function
  13379. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  13380. ** All other code has file scope.
  13381. **
  13382. ** SQLite processes all times and dates as Julian Day numbers. The
  13383. ** dates and times are stored as the number of days since noon
  13384. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  13385. ** calendar system.
  13386. **
  13387. ** 1970-01-01 00:00:00 is JD 2440587.5
  13388. ** 2000-01-01 00:00:00 is JD 2451544.5
  13389. **
  13390. ** This implemention requires years to be expressed as a 4-digit number
  13391. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  13392. ** be represented, even though julian day numbers allow a much wider
  13393. ** range of dates.
  13394. **
  13395. ** The Gregorian calendar system is used for all dates and times,
  13396. ** even those that predate the Gregorian calendar. Historians usually
  13397. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  13398. ** dates afterwards, depending on locale. Beware of this difference.
  13399. **
  13400. ** The conversion algorithms are implemented based on descriptions
  13401. ** in the following text:
  13402. **
  13403. ** Jean Meeus
  13404. ** Astronomical Algorithms, 2nd Edition, 1998
  13405. ** ISBM 0-943396-61-1
  13406. ** Willmann-Bell, Inc
  13407. ** Richmond, Virginia (USA)
  13408. */
  13409. /* #include <stdlib.h> */
  13410. /* #include <assert.h> */
  13411. #include <time.h>
  13412. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  13413. /*
  13414. ** A structure for holding a single date and time.
  13415. */
  13416. typedef struct DateTime DateTime;
  13417. struct DateTime {
  13418. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  13419. int Y, M, D; /* Year, month, and day */
  13420. int h, m; /* Hour and minutes */
  13421. int tz; /* Timezone offset in minutes */
  13422. double s; /* Seconds */
  13423. char validYMD; /* True (1) if Y,M,D are valid */
  13424. char validHMS; /* True (1) if h,m,s are valid */
  13425. char validJD; /* True (1) if iJD is valid */
  13426. char validTZ; /* True (1) if tz is valid */
  13427. };
  13428. /*
  13429. ** Convert zDate into one or more integers. Additional arguments
  13430. ** come in groups of 5 as follows:
  13431. **
  13432. ** N number of digits in the integer
  13433. ** min minimum allowed value of the integer
  13434. ** max maximum allowed value of the integer
  13435. ** nextC first character after the integer
  13436. ** pVal where to write the integers value.
  13437. **
  13438. ** Conversions continue until one with nextC==0 is encountered.
  13439. ** The function returns the number of successful conversions.
  13440. */
  13441. static int getDigits(const char *zDate, ...){
  13442. va_list ap;
  13443. int val;
  13444. int N;
  13445. int min;
  13446. int max;
  13447. int nextC;
  13448. int *pVal;
  13449. int cnt = 0;
  13450. va_start(ap, zDate);
  13451. do{
  13452. N = va_arg(ap, int);
  13453. min = va_arg(ap, int);
  13454. max = va_arg(ap, int);
  13455. nextC = va_arg(ap, int);
  13456. pVal = va_arg(ap, int*);
  13457. val = 0;
  13458. while( N-- ){
  13459. if( !sqlite3Isdigit(*zDate) ){
  13460. goto end_getDigits;
  13461. }
  13462. val = val*10 + *zDate - '0';
  13463. zDate++;
  13464. }
  13465. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  13466. goto end_getDigits;
  13467. }
  13468. *pVal = val;
  13469. zDate++;
  13470. cnt++;
  13471. }while( nextC );
  13472. end_getDigits:
  13473. va_end(ap);
  13474. return cnt;
  13475. }
  13476. /*
  13477. ** Parse a timezone extension on the end of a date-time.
  13478. ** The extension is of the form:
  13479. **
  13480. ** (+/-)HH:MM
  13481. **
  13482. ** Or the "zulu" notation:
  13483. **
  13484. ** Z
  13485. **
  13486. ** If the parse is successful, write the number of minutes
  13487. ** of change in p->tz and return 0. If a parser error occurs,
  13488. ** return non-zero.
  13489. **
  13490. ** A missing specifier is not considered an error.
  13491. */
  13492. static int parseTimezone(const char *zDate, DateTime *p){
  13493. int sgn = 0;
  13494. int nHr, nMn;
  13495. int c;
  13496. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13497. p->tz = 0;
  13498. c = *zDate;
  13499. if( c=='-' ){
  13500. sgn = -1;
  13501. }else if( c=='+' ){
  13502. sgn = +1;
  13503. }else if( c=='Z' || c=='z' ){
  13504. zDate++;
  13505. goto zulu_time;
  13506. }else{
  13507. return c!=0;
  13508. }
  13509. zDate++;
  13510. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  13511. return 1;
  13512. }
  13513. zDate += 5;
  13514. p->tz = sgn*(nMn + nHr*60);
  13515. zulu_time:
  13516. while( sqlite3Isspace(*zDate) ){ zDate++; }
  13517. return *zDate!=0;
  13518. }
  13519. /*
  13520. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  13521. ** The HH, MM, and SS must each be exactly 2 digits. The
  13522. ** fractional seconds FFFF can be one or more digits.
  13523. **
  13524. ** Return 1 if there is a parsing error and 0 on success.
  13525. */
  13526. static int parseHhMmSs(const char *zDate, DateTime *p){
  13527. int h, m, s;
  13528. double ms = 0.0;
  13529. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  13530. return 1;
  13531. }
  13532. zDate += 5;
  13533. if( *zDate==':' ){
  13534. zDate++;
  13535. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  13536. return 1;
  13537. }
  13538. zDate += 2;
  13539. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  13540. double rScale = 1.0;
  13541. zDate++;
  13542. while( sqlite3Isdigit(*zDate) ){
  13543. ms = ms*10.0 + *zDate - '0';
  13544. rScale *= 10.0;
  13545. zDate++;
  13546. }
  13547. ms /= rScale;
  13548. }
  13549. }else{
  13550. s = 0;
  13551. }
  13552. p->validJD = 0;
  13553. p->validHMS = 1;
  13554. p->h = h;
  13555. p->m = m;
  13556. p->s = s + ms;
  13557. if( parseTimezone(zDate, p) ) return 1;
  13558. p->validTZ = (p->tz!=0)?1:0;
  13559. return 0;
  13560. }
  13561. /*
  13562. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  13563. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  13564. **
  13565. ** Reference: Meeus page 61
  13566. */
  13567. static void computeJD(DateTime *p){
  13568. int Y, M, D, A, B, X1, X2;
  13569. if( p->validJD ) return;
  13570. if( p->validYMD ){
  13571. Y = p->Y;
  13572. M = p->M;
  13573. D = p->D;
  13574. }else{
  13575. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  13576. M = 1;
  13577. D = 1;
  13578. }
  13579. if( M<=2 ){
  13580. Y--;
  13581. M += 12;
  13582. }
  13583. A = Y/100;
  13584. B = 2 - A + (A/4);
  13585. X1 = 36525*(Y+4716)/100;
  13586. X2 = 306001*(M+1)/10000;
  13587. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  13588. p->validJD = 1;
  13589. if( p->validHMS ){
  13590. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  13591. if( p->validTZ ){
  13592. p->iJD -= p->tz*60000;
  13593. p->validYMD = 0;
  13594. p->validHMS = 0;
  13595. p->validTZ = 0;
  13596. }
  13597. }
  13598. }
  13599. /*
  13600. ** Parse dates of the form
  13601. **
  13602. ** YYYY-MM-DD HH:MM:SS.FFF
  13603. ** YYYY-MM-DD HH:MM:SS
  13604. ** YYYY-MM-DD HH:MM
  13605. ** YYYY-MM-DD
  13606. **
  13607. ** Write the result into the DateTime structure and return 0
  13608. ** on success and 1 if the input string is not a well-formed
  13609. ** date.
  13610. */
  13611. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  13612. int Y, M, D, neg;
  13613. if( zDate[0]=='-' ){
  13614. zDate++;
  13615. neg = 1;
  13616. }else{
  13617. neg = 0;
  13618. }
  13619. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  13620. return 1;
  13621. }
  13622. zDate += 10;
  13623. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  13624. if( parseHhMmSs(zDate, p)==0 ){
  13625. /* We got the time */
  13626. }else if( *zDate==0 ){
  13627. p->validHMS = 0;
  13628. }else{
  13629. return 1;
  13630. }
  13631. p->validJD = 0;
  13632. p->validYMD = 1;
  13633. p->Y = neg ? -Y : Y;
  13634. p->M = M;
  13635. p->D = D;
  13636. if( p->validTZ ){
  13637. computeJD(p);
  13638. }
  13639. return 0;
  13640. }
  13641. /*
  13642. ** Set the time to the current time reported by the VFS.
  13643. **
  13644. ** Return the number of errors.
  13645. */
  13646. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  13647. p->iJD = sqlite3StmtCurrentTime(context);
  13648. if( p->iJD>0 ){
  13649. p->validJD = 1;
  13650. return 0;
  13651. }else{
  13652. return 1;
  13653. }
  13654. }
  13655. /*
  13656. ** Attempt to parse the given string into a Julian Day Number. Return
  13657. ** the number of errors.
  13658. **
  13659. ** The following are acceptable forms for the input string:
  13660. **
  13661. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  13662. ** DDDD.DD
  13663. ** now
  13664. **
  13665. ** In the first form, the +/-HH:MM is always optional. The fractional
  13666. ** seconds extension (the ".FFF") is optional. The seconds portion
  13667. ** (":SS.FFF") is option. The year and date can be omitted as long
  13668. ** as there is a time string. The time string can be omitted as long
  13669. ** as there is a year and date.
  13670. */
  13671. static int parseDateOrTime(
  13672. sqlite3_context *context,
  13673. const char *zDate,
  13674. DateTime *p
  13675. ){
  13676. double r;
  13677. if( parseYyyyMmDd(zDate,p)==0 ){
  13678. return 0;
  13679. }else if( parseHhMmSs(zDate, p)==0 ){
  13680. return 0;
  13681. }else if( sqlite3StrICmp(zDate,"now")==0){
  13682. return setDateTimeToCurrent(context, p);
  13683. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  13684. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  13685. p->validJD = 1;
  13686. return 0;
  13687. }
  13688. return 1;
  13689. }
  13690. /*
  13691. ** Compute the Year, Month, and Day from the julian day number.
  13692. */
  13693. static void computeYMD(DateTime *p){
  13694. int Z, A, B, C, D, E, X1;
  13695. if( p->validYMD ) return;
  13696. if( !p->validJD ){
  13697. p->Y = 2000;
  13698. p->M = 1;
  13699. p->D = 1;
  13700. }else{
  13701. Z = (int)((p->iJD + 43200000)/86400000);
  13702. A = (int)((Z - 1867216.25)/36524.25);
  13703. A = Z + 1 + A - (A/4);
  13704. B = A + 1524;
  13705. C = (int)((B - 122.1)/365.25);
  13706. D = (36525*C)/100;
  13707. E = (int)((B-D)/30.6001);
  13708. X1 = (int)(30.6001*E);
  13709. p->D = B - D - X1;
  13710. p->M = E<14 ? E-1 : E-13;
  13711. p->Y = p->M>2 ? C - 4716 : C - 4715;
  13712. }
  13713. p->validYMD = 1;
  13714. }
  13715. /*
  13716. ** Compute the Hour, Minute, and Seconds from the julian day number.
  13717. */
  13718. static void computeHMS(DateTime *p){
  13719. int s;
  13720. if( p->validHMS ) return;
  13721. computeJD(p);
  13722. s = (int)((p->iJD + 43200000) % 86400000);
  13723. p->s = s/1000.0;
  13724. s = (int)p->s;
  13725. p->s -= s;
  13726. p->h = s/3600;
  13727. s -= p->h*3600;
  13728. p->m = s/60;
  13729. p->s += s - p->m*60;
  13730. p->validHMS = 1;
  13731. }
  13732. /*
  13733. ** Compute both YMD and HMS
  13734. */
  13735. static void computeYMD_HMS(DateTime *p){
  13736. computeYMD(p);
  13737. computeHMS(p);
  13738. }
  13739. /*
  13740. ** Clear the YMD and HMS and the TZ
  13741. */
  13742. static void clearYMD_HMS_TZ(DateTime *p){
  13743. p->validYMD = 0;
  13744. p->validHMS = 0;
  13745. p->validTZ = 0;
  13746. }
  13747. /*
  13748. ** On recent Windows platforms, the localtime_s() function is available
  13749. ** as part of the "Secure CRT". It is essentially equivalent to
  13750. ** localtime_r() available under most POSIX platforms, except that the
  13751. ** order of the parameters is reversed.
  13752. **
  13753. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  13754. **
  13755. ** If the user has not indicated to use localtime_r() or localtime_s()
  13756. ** already, check for an MSVC build environment that provides
  13757. ** localtime_s().
  13758. */
  13759. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  13760. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  13761. #define HAVE_LOCALTIME_S 1
  13762. #endif
  13763. #ifndef SQLITE_OMIT_LOCALTIME
  13764. /*
  13765. ** The following routine implements the rough equivalent of localtime_r()
  13766. ** using whatever operating-system specific localtime facility that
  13767. ** is available. This routine returns 0 on success and
  13768. ** non-zero on any kind of error.
  13769. **
  13770. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  13771. ** routine will always fail.
  13772. **
  13773. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  13774. ** library function localtime_r() is used to assist in the calculation of
  13775. ** local time.
  13776. */
  13777. static int osLocaltime(time_t *t, struct tm *pTm){
  13778. int rc;
  13779. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  13780. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  13781. struct tm *pX;
  13782. #if SQLITE_THREADSAFE>0
  13783. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  13784. #endif
  13785. sqlite3_mutex_enter(mutex);
  13786. pX = localtime(t);
  13787. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13788. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  13789. #endif
  13790. if( pX ) *pTm = *pX;
  13791. sqlite3_mutex_leave(mutex);
  13792. rc = pX==0;
  13793. #else
  13794. #ifndef SQLITE_OMIT_BUILTIN_TEST
  13795. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  13796. #endif
  13797. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  13798. rc = localtime_r(t, pTm)==0;
  13799. #else
  13800. rc = localtime_s(pTm, t);
  13801. #endif /* HAVE_LOCALTIME_R */
  13802. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  13803. return rc;
  13804. }
  13805. #endif /* SQLITE_OMIT_LOCALTIME */
  13806. #ifndef SQLITE_OMIT_LOCALTIME
  13807. /*
  13808. ** Compute the difference (in milliseconds) between localtime and UTC
  13809. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  13810. ** return this value and set *pRc to SQLITE_OK.
  13811. **
  13812. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  13813. ** is undefined in this case.
  13814. */
  13815. static sqlite3_int64 localtimeOffset(
  13816. DateTime *p, /* Date at which to calculate offset */
  13817. sqlite3_context *pCtx, /* Write error here if one occurs */
  13818. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  13819. ){
  13820. DateTime x, y;
  13821. time_t t;
  13822. struct tm sLocal;
  13823. /* Initialize the contents of sLocal to avoid a compiler warning. */
  13824. memset(&sLocal, 0, sizeof(sLocal));
  13825. x = *p;
  13826. computeYMD_HMS(&x);
  13827. if( x.Y<1971 || x.Y>=2038 ){
  13828. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  13829. ** works for years between 1970 and 2037. For dates outside this range,
  13830. ** SQLite attempts to map the year into an equivalent year within this
  13831. ** range, do the calculation, then map the year back.
  13832. */
  13833. x.Y = 2000;
  13834. x.M = 1;
  13835. x.D = 1;
  13836. x.h = 0;
  13837. x.m = 0;
  13838. x.s = 0.0;
  13839. } else {
  13840. int s = (int)(x.s + 0.5);
  13841. x.s = s;
  13842. }
  13843. x.tz = 0;
  13844. x.validJD = 0;
  13845. computeJD(&x);
  13846. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  13847. if( osLocaltime(&t, &sLocal) ){
  13848. sqlite3_result_error(pCtx, "local time unavailable", -1);
  13849. *pRc = SQLITE_ERROR;
  13850. return 0;
  13851. }
  13852. y.Y = sLocal.tm_year + 1900;
  13853. y.M = sLocal.tm_mon + 1;
  13854. y.D = sLocal.tm_mday;
  13855. y.h = sLocal.tm_hour;
  13856. y.m = sLocal.tm_min;
  13857. y.s = sLocal.tm_sec;
  13858. y.validYMD = 1;
  13859. y.validHMS = 1;
  13860. y.validJD = 0;
  13861. y.validTZ = 0;
  13862. computeJD(&y);
  13863. *pRc = SQLITE_OK;
  13864. return y.iJD - x.iJD;
  13865. }
  13866. #endif /* SQLITE_OMIT_LOCALTIME */
  13867. /*
  13868. ** Process a modifier to a date-time stamp. The modifiers are
  13869. ** as follows:
  13870. **
  13871. ** NNN days
  13872. ** NNN hours
  13873. ** NNN minutes
  13874. ** NNN.NNNN seconds
  13875. ** NNN months
  13876. ** NNN years
  13877. ** start of month
  13878. ** start of year
  13879. ** start of week
  13880. ** start of day
  13881. ** weekday N
  13882. ** unixepoch
  13883. ** localtime
  13884. ** utc
  13885. **
  13886. ** Return 0 on success and 1 if there is any kind of error. If the error
  13887. ** is in a system call (i.e. localtime()), then an error message is written
  13888. ** to context pCtx. If the error is an unrecognized modifier, no error is
  13889. ** written to pCtx.
  13890. */
  13891. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  13892. int rc = 1;
  13893. int n;
  13894. double r;
  13895. char *z, zBuf[30];
  13896. z = zBuf;
  13897. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  13898. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  13899. }
  13900. z[n] = 0;
  13901. switch( z[0] ){
  13902. #ifndef SQLITE_OMIT_LOCALTIME
  13903. case 'l': {
  13904. /* localtime
  13905. **
  13906. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  13907. ** show local time.
  13908. */
  13909. if( strcmp(z, "localtime")==0 ){
  13910. computeJD(p);
  13911. p->iJD += localtimeOffset(p, pCtx, &rc);
  13912. clearYMD_HMS_TZ(p);
  13913. }
  13914. break;
  13915. }
  13916. #endif
  13917. case 'u': {
  13918. /*
  13919. ** unixepoch
  13920. **
  13921. ** Treat the current value of p->iJD as the number of
  13922. ** seconds since 1970. Convert to a real julian day number.
  13923. */
  13924. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  13925. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  13926. clearYMD_HMS_TZ(p);
  13927. rc = 0;
  13928. }
  13929. #ifndef SQLITE_OMIT_LOCALTIME
  13930. else if( strcmp(z, "utc")==0 ){
  13931. sqlite3_int64 c1;
  13932. computeJD(p);
  13933. c1 = localtimeOffset(p, pCtx, &rc);
  13934. if( rc==SQLITE_OK ){
  13935. p->iJD -= c1;
  13936. clearYMD_HMS_TZ(p);
  13937. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  13938. }
  13939. }
  13940. #endif
  13941. break;
  13942. }
  13943. case 'w': {
  13944. /*
  13945. ** weekday N
  13946. **
  13947. ** Move the date to the same time on the next occurrence of
  13948. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  13949. ** date is already on the appropriate weekday, this is a no-op.
  13950. */
  13951. if( strncmp(z, "weekday ", 8)==0
  13952. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  13953. && (n=(int)r)==r && n>=0 && r<7 ){
  13954. sqlite3_int64 Z;
  13955. computeYMD_HMS(p);
  13956. p->validTZ = 0;
  13957. p->validJD = 0;
  13958. computeJD(p);
  13959. Z = ((p->iJD + 129600000)/86400000) % 7;
  13960. if( Z>n ) Z -= 7;
  13961. p->iJD += (n - Z)*86400000;
  13962. clearYMD_HMS_TZ(p);
  13963. rc = 0;
  13964. }
  13965. break;
  13966. }
  13967. case 's': {
  13968. /*
  13969. ** start of TTTTT
  13970. **
  13971. ** Move the date backwards to the beginning of the current day,
  13972. ** or month or year.
  13973. */
  13974. if( strncmp(z, "start of ", 9)!=0 ) break;
  13975. z += 9;
  13976. computeYMD(p);
  13977. p->validHMS = 1;
  13978. p->h = p->m = 0;
  13979. p->s = 0.0;
  13980. p->validTZ = 0;
  13981. p->validJD = 0;
  13982. if( strcmp(z,"month")==0 ){
  13983. p->D = 1;
  13984. rc = 0;
  13985. }else if( strcmp(z,"year")==0 ){
  13986. computeYMD(p);
  13987. p->M = 1;
  13988. p->D = 1;
  13989. rc = 0;
  13990. }else if( strcmp(z,"day")==0 ){
  13991. rc = 0;
  13992. }
  13993. break;
  13994. }
  13995. case '+':
  13996. case '-':
  13997. case '0':
  13998. case '1':
  13999. case '2':
  14000. case '3':
  14001. case '4':
  14002. case '5':
  14003. case '6':
  14004. case '7':
  14005. case '8':
  14006. case '9': {
  14007. double rRounder;
  14008. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14009. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14010. rc = 1;
  14011. break;
  14012. }
  14013. if( z[n]==':' ){
  14014. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14015. ** specified number of hours, minutes, seconds, and fractional seconds
  14016. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14017. ** omitted.
  14018. */
  14019. const char *z2 = z;
  14020. DateTime tx;
  14021. sqlite3_int64 day;
  14022. if( !sqlite3Isdigit(*z2) ) z2++;
  14023. memset(&tx, 0, sizeof(tx));
  14024. if( parseHhMmSs(z2, &tx) ) break;
  14025. computeJD(&tx);
  14026. tx.iJD -= 43200000;
  14027. day = tx.iJD/86400000;
  14028. tx.iJD -= day*86400000;
  14029. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14030. computeJD(p);
  14031. clearYMD_HMS_TZ(p);
  14032. p->iJD += tx.iJD;
  14033. rc = 0;
  14034. break;
  14035. }
  14036. z += n;
  14037. while( sqlite3Isspace(*z) ) z++;
  14038. n = sqlite3Strlen30(z);
  14039. if( n>10 || n<3 ) break;
  14040. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14041. computeJD(p);
  14042. rc = 0;
  14043. rRounder = r<0 ? -0.5 : +0.5;
  14044. if( n==3 && strcmp(z,"day")==0 ){
  14045. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14046. }else if( n==4 && strcmp(z,"hour")==0 ){
  14047. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14048. }else if( n==6 && strcmp(z,"minute")==0 ){
  14049. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14050. }else if( n==6 && strcmp(z,"second")==0 ){
  14051. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14052. }else if( n==5 && strcmp(z,"month")==0 ){
  14053. int x, y;
  14054. computeYMD_HMS(p);
  14055. p->M += (int)r;
  14056. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14057. p->Y += x;
  14058. p->M -= x*12;
  14059. p->validJD = 0;
  14060. computeJD(p);
  14061. y = (int)r;
  14062. if( y!=r ){
  14063. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14064. }
  14065. }else if( n==4 && strcmp(z,"year")==0 ){
  14066. int y = (int)r;
  14067. computeYMD_HMS(p);
  14068. p->Y += y;
  14069. p->validJD = 0;
  14070. computeJD(p);
  14071. if( y!=r ){
  14072. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14073. }
  14074. }else{
  14075. rc = 1;
  14076. }
  14077. clearYMD_HMS_TZ(p);
  14078. break;
  14079. }
  14080. default: {
  14081. break;
  14082. }
  14083. }
  14084. return rc;
  14085. }
  14086. /*
  14087. ** Process time function arguments. argv[0] is a date-time stamp.
  14088. ** argv[1] and following are modifiers. Parse them all and write
  14089. ** the resulting time into the DateTime structure p. Return 0
  14090. ** on success and 1 if there are any errors.
  14091. **
  14092. ** If there are zero parameters (if even argv[0] is undefined)
  14093. ** then assume a default value of "now" for argv[0].
  14094. */
  14095. static int isDate(
  14096. sqlite3_context *context,
  14097. int argc,
  14098. sqlite3_value **argv,
  14099. DateTime *p
  14100. ){
  14101. int i;
  14102. const unsigned char *z;
  14103. int eType;
  14104. memset(p, 0, sizeof(*p));
  14105. if( argc==0 ){
  14106. return setDateTimeToCurrent(context, p);
  14107. }
  14108. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14109. || eType==SQLITE_INTEGER ){
  14110. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14111. p->validJD = 1;
  14112. }else{
  14113. z = sqlite3_value_text(argv[0]);
  14114. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14115. return 1;
  14116. }
  14117. }
  14118. for(i=1; i<argc; i++){
  14119. z = sqlite3_value_text(argv[i]);
  14120. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14121. }
  14122. return 0;
  14123. }
  14124. /*
  14125. ** The following routines implement the various date and time functions
  14126. ** of SQLite.
  14127. */
  14128. /*
  14129. ** julianday( TIMESTRING, MOD, MOD, ...)
  14130. **
  14131. ** Return the julian day number of the date specified in the arguments
  14132. */
  14133. static void juliandayFunc(
  14134. sqlite3_context *context,
  14135. int argc,
  14136. sqlite3_value **argv
  14137. ){
  14138. DateTime x;
  14139. if( isDate(context, argc, argv, &x)==0 ){
  14140. computeJD(&x);
  14141. sqlite3_result_double(context, x.iJD/86400000.0);
  14142. }
  14143. }
  14144. /*
  14145. ** datetime( TIMESTRING, MOD, MOD, ...)
  14146. **
  14147. ** Return YYYY-MM-DD HH:MM:SS
  14148. */
  14149. static void datetimeFunc(
  14150. sqlite3_context *context,
  14151. int argc,
  14152. sqlite3_value **argv
  14153. ){
  14154. DateTime x;
  14155. if( isDate(context, argc, argv, &x)==0 ){
  14156. char zBuf[100];
  14157. computeYMD_HMS(&x);
  14158. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14159. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14160. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14161. }
  14162. }
  14163. /*
  14164. ** time( TIMESTRING, MOD, MOD, ...)
  14165. **
  14166. ** Return HH:MM:SS
  14167. */
  14168. static void timeFunc(
  14169. sqlite3_context *context,
  14170. int argc,
  14171. sqlite3_value **argv
  14172. ){
  14173. DateTime x;
  14174. if( isDate(context, argc, argv, &x)==0 ){
  14175. char zBuf[100];
  14176. computeHMS(&x);
  14177. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14178. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14179. }
  14180. }
  14181. /*
  14182. ** date( TIMESTRING, MOD, MOD, ...)
  14183. **
  14184. ** Return YYYY-MM-DD
  14185. */
  14186. static void dateFunc(
  14187. sqlite3_context *context,
  14188. int argc,
  14189. sqlite3_value **argv
  14190. ){
  14191. DateTime x;
  14192. if( isDate(context, argc, argv, &x)==0 ){
  14193. char zBuf[100];
  14194. computeYMD(&x);
  14195. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14196. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14197. }
  14198. }
  14199. /*
  14200. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14201. **
  14202. ** Return a string described by FORMAT. Conversions as follows:
  14203. **
  14204. ** %d day of month
  14205. ** %f ** fractional seconds SS.SSS
  14206. ** %H hour 00-24
  14207. ** %j day of year 000-366
  14208. ** %J ** Julian day number
  14209. ** %m month 01-12
  14210. ** %M minute 00-59
  14211. ** %s seconds since 1970-01-01
  14212. ** %S seconds 00-59
  14213. ** %w day of week 0-6 sunday==0
  14214. ** %W week of year 00-53
  14215. ** %Y year 0000-9999
  14216. ** %% %
  14217. */
  14218. static void strftimeFunc(
  14219. sqlite3_context *context,
  14220. int argc,
  14221. sqlite3_value **argv
  14222. ){
  14223. DateTime x;
  14224. u64 n;
  14225. size_t i,j;
  14226. char *z;
  14227. sqlite3 *db;
  14228. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14229. char zBuf[100];
  14230. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14231. db = sqlite3_context_db_handle(context);
  14232. for(i=0, n=1; zFmt[i]; i++, n++){
  14233. if( zFmt[i]=='%' ){
  14234. switch( zFmt[i+1] ){
  14235. case 'd':
  14236. case 'H':
  14237. case 'm':
  14238. case 'M':
  14239. case 'S':
  14240. case 'W':
  14241. n++;
  14242. /* fall thru */
  14243. case 'w':
  14244. case '%':
  14245. break;
  14246. case 'f':
  14247. n += 8;
  14248. break;
  14249. case 'j':
  14250. n += 3;
  14251. break;
  14252. case 'Y':
  14253. n += 8;
  14254. break;
  14255. case 's':
  14256. case 'J':
  14257. n += 50;
  14258. break;
  14259. default:
  14260. return; /* ERROR. return a NULL */
  14261. }
  14262. i++;
  14263. }
  14264. }
  14265. testcase( n==sizeof(zBuf)-1 );
  14266. testcase( n==sizeof(zBuf) );
  14267. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14268. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14269. if( n<sizeof(zBuf) ){
  14270. z = zBuf;
  14271. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14272. sqlite3_result_error_toobig(context);
  14273. return;
  14274. }else{
  14275. z = sqlite3DbMallocRaw(db, (int)n);
  14276. if( z==0 ){
  14277. sqlite3_result_error_nomem(context);
  14278. return;
  14279. }
  14280. }
  14281. computeJD(&x);
  14282. computeYMD_HMS(&x);
  14283. for(i=j=0; zFmt[i]; i++){
  14284. if( zFmt[i]!='%' ){
  14285. z[j++] = zFmt[i];
  14286. }else{
  14287. i++;
  14288. switch( zFmt[i] ){
  14289. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  14290. case 'f': {
  14291. double s = x.s;
  14292. if( s>59.999 ) s = 59.999;
  14293. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  14294. j += sqlite3Strlen30(&z[j]);
  14295. break;
  14296. }
  14297. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  14298. case 'W': /* Fall thru */
  14299. case 'j': {
  14300. int nDay; /* Number of days since 1st day of year */
  14301. DateTime y = x;
  14302. y.validJD = 0;
  14303. y.M = 1;
  14304. y.D = 1;
  14305. computeJD(&y);
  14306. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  14307. if( zFmt[i]=='W' ){
  14308. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  14309. wd = (int)(((x.iJD+43200000)/86400000)%7);
  14310. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  14311. j += 2;
  14312. }else{
  14313. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  14314. j += 3;
  14315. }
  14316. break;
  14317. }
  14318. case 'J': {
  14319. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  14320. j+=sqlite3Strlen30(&z[j]);
  14321. break;
  14322. }
  14323. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  14324. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  14325. case 's': {
  14326. sqlite3_snprintf(30,&z[j],"%lld",
  14327. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  14328. j += sqlite3Strlen30(&z[j]);
  14329. break;
  14330. }
  14331. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  14332. case 'w': {
  14333. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  14334. break;
  14335. }
  14336. case 'Y': {
  14337. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  14338. break;
  14339. }
  14340. default: z[j++] = '%'; break;
  14341. }
  14342. }
  14343. }
  14344. z[j] = 0;
  14345. sqlite3_result_text(context, z, -1,
  14346. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  14347. }
  14348. /*
  14349. ** current_time()
  14350. **
  14351. ** This function returns the same value as time('now').
  14352. */
  14353. static void ctimeFunc(
  14354. sqlite3_context *context,
  14355. int NotUsed,
  14356. sqlite3_value **NotUsed2
  14357. ){
  14358. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14359. timeFunc(context, 0, 0);
  14360. }
  14361. /*
  14362. ** current_date()
  14363. **
  14364. ** This function returns the same value as date('now').
  14365. */
  14366. static void cdateFunc(
  14367. sqlite3_context *context,
  14368. int NotUsed,
  14369. sqlite3_value **NotUsed2
  14370. ){
  14371. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14372. dateFunc(context, 0, 0);
  14373. }
  14374. /*
  14375. ** current_timestamp()
  14376. **
  14377. ** This function returns the same value as datetime('now').
  14378. */
  14379. static void ctimestampFunc(
  14380. sqlite3_context *context,
  14381. int NotUsed,
  14382. sqlite3_value **NotUsed2
  14383. ){
  14384. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  14385. datetimeFunc(context, 0, 0);
  14386. }
  14387. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  14388. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  14389. /*
  14390. ** If the library is compiled to omit the full-scale date and time
  14391. ** handling (to get a smaller binary), the following minimal version
  14392. ** of the functions current_time(), current_date() and current_timestamp()
  14393. ** are included instead. This is to support column declarations that
  14394. ** include "DEFAULT CURRENT_TIME" etc.
  14395. **
  14396. ** This function uses the C-library functions time(), gmtime()
  14397. ** and strftime(). The format string to pass to strftime() is supplied
  14398. ** as the user-data for the function.
  14399. */
  14400. static void currentTimeFunc(
  14401. sqlite3_context *context,
  14402. int argc,
  14403. sqlite3_value **argv
  14404. ){
  14405. time_t t;
  14406. char *zFormat = (char *)sqlite3_user_data(context);
  14407. sqlite3 *db;
  14408. sqlite3_int64 iT;
  14409. struct tm *pTm;
  14410. struct tm sNow;
  14411. char zBuf[20];
  14412. UNUSED_PARAMETER(argc);
  14413. UNUSED_PARAMETER(argv);
  14414. iT = sqlite3StmtCurrentTime(context);
  14415. if( iT<=0 ) return;
  14416. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  14417. #ifdef HAVE_GMTIME_R
  14418. pTm = gmtime_r(&t, &sNow);
  14419. #else
  14420. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14421. pTm = gmtime(&t);
  14422. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  14423. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  14424. #endif
  14425. if( pTm ){
  14426. strftime(zBuf, 20, zFormat, &sNow);
  14427. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14428. }
  14429. }
  14430. #endif
  14431. /*
  14432. ** This function registered all of the above C functions as SQL
  14433. ** functions. This should be the only routine in this file with
  14434. ** external linkage.
  14435. */
  14436. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  14437. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  14438. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14439. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  14440. FUNCTION(date, -1, 0, 0, dateFunc ),
  14441. FUNCTION(time, -1, 0, 0, timeFunc ),
  14442. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  14443. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  14444. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  14445. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  14446. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  14447. #else
  14448. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  14449. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  14450. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  14451. #endif
  14452. };
  14453. int i;
  14454. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  14455. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  14456. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  14457. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  14458. }
  14459. }
  14460. /************** End of date.c ************************************************/
  14461. /************** Begin file os.c **********************************************/
  14462. /*
  14463. ** 2005 November 29
  14464. **
  14465. ** The author disclaims copyright to this source code. In place of
  14466. ** a legal notice, here is a blessing:
  14467. **
  14468. ** May you do good and not evil.
  14469. ** May you find forgiveness for yourself and forgive others.
  14470. ** May you share freely, never taking more than you give.
  14471. **
  14472. ******************************************************************************
  14473. **
  14474. ** This file contains OS interface code that is common to all
  14475. ** architectures.
  14476. */
  14477. #define _SQLITE_OS_C_ 1
  14478. #undef _SQLITE_OS_C_
  14479. /*
  14480. ** The default SQLite sqlite3_vfs implementations do not allocate
  14481. ** memory (actually, os_unix.c allocates a small amount of memory
  14482. ** from within OsOpen()), but some third-party implementations may.
  14483. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  14484. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  14485. **
  14486. ** The following functions are instrumented for malloc() failure
  14487. ** testing:
  14488. **
  14489. ** sqlite3OsRead()
  14490. ** sqlite3OsWrite()
  14491. ** sqlite3OsSync()
  14492. ** sqlite3OsFileSize()
  14493. ** sqlite3OsLock()
  14494. ** sqlite3OsCheckReservedLock()
  14495. ** sqlite3OsFileControl()
  14496. ** sqlite3OsShmMap()
  14497. ** sqlite3OsOpen()
  14498. ** sqlite3OsDelete()
  14499. ** sqlite3OsAccess()
  14500. ** sqlite3OsFullPathname()
  14501. **
  14502. */
  14503. #if defined(SQLITE_TEST)
  14504. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  14505. #define DO_OS_MALLOC_TEST(x) \
  14506. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  14507. void *pTstAlloc = sqlite3Malloc(10); \
  14508. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  14509. sqlite3_free(pTstAlloc); \
  14510. }
  14511. #else
  14512. #define DO_OS_MALLOC_TEST(x)
  14513. #endif
  14514. /*
  14515. ** The following routines are convenience wrappers around methods
  14516. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  14517. ** of this would be completely automatic if SQLite were coded using
  14518. ** C++ instead of plain old C.
  14519. */
  14520. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  14521. int rc = SQLITE_OK;
  14522. if( pId->pMethods ){
  14523. rc = pId->pMethods->xClose(pId);
  14524. pId->pMethods = 0;
  14525. }
  14526. return rc;
  14527. }
  14528. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  14529. DO_OS_MALLOC_TEST(id);
  14530. return id->pMethods->xRead(id, pBuf, amt, offset);
  14531. }
  14532. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  14533. DO_OS_MALLOC_TEST(id);
  14534. return id->pMethods->xWrite(id, pBuf, amt, offset);
  14535. }
  14536. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  14537. return id->pMethods->xTruncate(id, size);
  14538. }
  14539. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  14540. DO_OS_MALLOC_TEST(id);
  14541. return id->pMethods->xSync(id, flags);
  14542. }
  14543. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  14544. DO_OS_MALLOC_TEST(id);
  14545. return id->pMethods->xFileSize(id, pSize);
  14546. }
  14547. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  14548. DO_OS_MALLOC_TEST(id);
  14549. return id->pMethods->xLock(id, lockType);
  14550. }
  14551. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  14552. return id->pMethods->xUnlock(id, lockType);
  14553. }
  14554. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  14555. DO_OS_MALLOC_TEST(id);
  14556. return id->pMethods->xCheckReservedLock(id, pResOut);
  14557. }
  14558. /*
  14559. ** Use sqlite3OsFileControl() when we are doing something that might fail
  14560. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  14561. ** when simply tossing information over the wall to the VFS and we do not
  14562. ** really care if the VFS receives and understands the information since it
  14563. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  14564. ** routine has no return value since the return value would be meaningless.
  14565. */
  14566. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  14567. DO_OS_MALLOC_TEST(id);
  14568. return id->pMethods->xFileControl(id, op, pArg);
  14569. }
  14570. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  14571. (void)id->pMethods->xFileControl(id, op, pArg);
  14572. }
  14573. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  14574. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  14575. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  14576. }
  14577. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  14578. return id->pMethods->xDeviceCharacteristics(id);
  14579. }
  14580. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  14581. return id->pMethods->xShmLock(id, offset, n, flags);
  14582. }
  14583. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  14584. id->pMethods->xShmBarrier(id);
  14585. }
  14586. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  14587. return id->pMethods->xShmUnmap(id, deleteFlag);
  14588. }
  14589. SQLITE_PRIVATE int sqlite3OsShmMap(
  14590. sqlite3_file *id, /* Database file handle */
  14591. int iPage,
  14592. int pgsz,
  14593. int bExtend, /* True to extend file if necessary */
  14594. void volatile **pp /* OUT: Pointer to mapping */
  14595. ){
  14596. DO_OS_MALLOC_TEST(id);
  14597. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  14598. }
  14599. #if SQLITE_MAX_MMAP_SIZE>0
  14600. /* The real implementation of xFetch and xUnfetch */
  14601. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14602. DO_OS_MALLOC_TEST(id);
  14603. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  14604. }
  14605. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14606. return id->pMethods->xUnfetch(id, iOff, p);
  14607. }
  14608. #else
  14609. /* No-op stubs to use when memory-mapped I/O is disabled */
  14610. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  14611. *pp = 0;
  14612. return SQLITE_OK;
  14613. }
  14614. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  14615. return SQLITE_OK;
  14616. }
  14617. #endif
  14618. /*
  14619. ** The next group of routines are convenience wrappers around the
  14620. ** VFS methods.
  14621. */
  14622. SQLITE_PRIVATE int sqlite3OsOpen(
  14623. sqlite3_vfs *pVfs,
  14624. const char *zPath,
  14625. sqlite3_file *pFile,
  14626. int flags,
  14627. int *pFlagsOut
  14628. ){
  14629. int rc;
  14630. DO_OS_MALLOC_TEST(0);
  14631. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  14632. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  14633. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  14634. ** reaching the VFS. */
  14635. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  14636. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  14637. return rc;
  14638. }
  14639. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  14640. DO_OS_MALLOC_TEST(0);
  14641. assert( dirSync==0 || dirSync==1 );
  14642. return pVfs->xDelete(pVfs, zPath, dirSync);
  14643. }
  14644. SQLITE_PRIVATE int sqlite3OsAccess(
  14645. sqlite3_vfs *pVfs,
  14646. const char *zPath,
  14647. int flags,
  14648. int *pResOut
  14649. ){
  14650. DO_OS_MALLOC_TEST(0);
  14651. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  14652. }
  14653. SQLITE_PRIVATE int sqlite3OsFullPathname(
  14654. sqlite3_vfs *pVfs,
  14655. const char *zPath,
  14656. int nPathOut,
  14657. char *zPathOut
  14658. ){
  14659. DO_OS_MALLOC_TEST(0);
  14660. zPathOut[0] = 0;
  14661. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  14662. }
  14663. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  14664. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  14665. return pVfs->xDlOpen(pVfs, zPath);
  14666. }
  14667. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14668. pVfs->xDlError(pVfs, nByte, zBufOut);
  14669. }
  14670. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  14671. return pVfs->xDlSym(pVfs, pHdle, zSym);
  14672. }
  14673. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  14674. pVfs->xDlClose(pVfs, pHandle);
  14675. }
  14676. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  14677. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  14678. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  14679. }
  14680. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  14681. return pVfs->xSleep(pVfs, nMicro);
  14682. }
  14683. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  14684. int rc;
  14685. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  14686. ** method to get the current date and time if that method is available
  14687. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  14688. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  14689. ** unavailable.
  14690. */
  14691. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  14692. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  14693. }else{
  14694. double r;
  14695. rc = pVfs->xCurrentTime(pVfs, &r);
  14696. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  14697. }
  14698. return rc;
  14699. }
  14700. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  14701. sqlite3_vfs *pVfs,
  14702. const char *zFile,
  14703. sqlite3_file **ppFile,
  14704. int flags,
  14705. int *pOutFlags
  14706. ){
  14707. int rc = SQLITE_NOMEM;
  14708. sqlite3_file *pFile;
  14709. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  14710. if( pFile ){
  14711. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  14712. if( rc!=SQLITE_OK ){
  14713. sqlite3_free(pFile);
  14714. }else{
  14715. *ppFile = pFile;
  14716. }
  14717. }
  14718. return rc;
  14719. }
  14720. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  14721. int rc = SQLITE_OK;
  14722. assert( pFile );
  14723. rc = sqlite3OsClose(pFile);
  14724. sqlite3_free(pFile);
  14725. return rc;
  14726. }
  14727. /*
  14728. ** This function is a wrapper around the OS specific implementation of
  14729. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  14730. ** ability to simulate a malloc failure, so that the handling of an
  14731. ** error in sqlite3_os_init() by the upper layers can be tested.
  14732. */
  14733. SQLITE_PRIVATE int sqlite3OsInit(void){
  14734. void *p = sqlite3_malloc(10);
  14735. if( p==0 ) return SQLITE_NOMEM;
  14736. sqlite3_free(p);
  14737. return sqlite3_os_init();
  14738. }
  14739. /*
  14740. ** The list of all registered VFS implementations.
  14741. */
  14742. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  14743. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  14744. /*
  14745. ** Locate a VFS by name. If no name is given, simply return the
  14746. ** first VFS on the list.
  14747. */
  14748. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  14749. sqlite3_vfs *pVfs = 0;
  14750. #if SQLITE_THREADSAFE
  14751. sqlite3_mutex *mutex;
  14752. #endif
  14753. #ifndef SQLITE_OMIT_AUTOINIT
  14754. int rc = sqlite3_initialize();
  14755. if( rc ) return 0;
  14756. #endif
  14757. #if SQLITE_THREADSAFE
  14758. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14759. #endif
  14760. sqlite3_mutex_enter(mutex);
  14761. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  14762. if( zVfs==0 ) break;
  14763. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  14764. }
  14765. sqlite3_mutex_leave(mutex);
  14766. return pVfs;
  14767. }
  14768. /*
  14769. ** Unlink a VFS from the linked list
  14770. */
  14771. static void vfsUnlink(sqlite3_vfs *pVfs){
  14772. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  14773. if( pVfs==0 ){
  14774. /* No-op */
  14775. }else if( vfsList==pVfs ){
  14776. vfsList = pVfs->pNext;
  14777. }else if( vfsList ){
  14778. sqlite3_vfs *p = vfsList;
  14779. while( p->pNext && p->pNext!=pVfs ){
  14780. p = p->pNext;
  14781. }
  14782. if( p->pNext==pVfs ){
  14783. p->pNext = pVfs->pNext;
  14784. }
  14785. }
  14786. }
  14787. /*
  14788. ** Register a VFS with the system. It is harmless to register the same
  14789. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  14790. ** true.
  14791. */
  14792. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  14793. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  14794. #ifndef SQLITE_OMIT_AUTOINIT
  14795. int rc = sqlite3_initialize();
  14796. if( rc ) return rc;
  14797. #endif
  14798. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  14799. sqlite3_mutex_enter(mutex);
  14800. vfsUnlink(pVfs);
  14801. if( makeDflt || vfsList==0 ){
  14802. pVfs->pNext = vfsList;
  14803. vfsList = pVfs;
  14804. }else{
  14805. pVfs->pNext = vfsList->pNext;
  14806. vfsList->pNext = pVfs;
  14807. }
  14808. assert(vfsList);
  14809. sqlite3_mutex_leave(mutex);
  14810. return SQLITE_OK;
  14811. }
  14812. /*
  14813. ** Unregister a VFS so that it is no longer accessible.
  14814. */
  14815. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  14816. #if SQLITE_THREADSAFE
  14817. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14818. #endif
  14819. sqlite3_mutex_enter(mutex);
  14820. vfsUnlink(pVfs);
  14821. sqlite3_mutex_leave(mutex);
  14822. return SQLITE_OK;
  14823. }
  14824. /************** End of os.c **************************************************/
  14825. /************** Begin file fault.c *******************************************/
  14826. /*
  14827. ** 2008 Jan 22
  14828. **
  14829. ** The author disclaims copyright to this source code. In place of
  14830. ** a legal notice, here is a blessing:
  14831. **
  14832. ** May you do good and not evil.
  14833. ** May you find forgiveness for yourself and forgive others.
  14834. ** May you share freely, never taking more than you give.
  14835. **
  14836. *************************************************************************
  14837. **
  14838. ** This file contains code to support the concept of "benign"
  14839. ** malloc failures (when the xMalloc() or xRealloc() method of the
  14840. ** sqlite3_mem_methods structure fails to allocate a block of memory
  14841. ** and returns 0).
  14842. **
  14843. ** Most malloc failures are non-benign. After they occur, SQLite
  14844. ** abandons the current operation and returns an error code (usually
  14845. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  14846. ** fatal. For example, if a malloc fails while resizing a hash table, this
  14847. ** is completely recoverable simply by not carrying out the resize. The
  14848. ** hash table will continue to function normally. So a malloc failure
  14849. ** during a hash table resize is a benign fault.
  14850. */
  14851. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14852. /*
  14853. ** Global variables.
  14854. */
  14855. typedef struct BenignMallocHooks BenignMallocHooks;
  14856. static SQLITE_WSD struct BenignMallocHooks {
  14857. void (*xBenignBegin)(void);
  14858. void (*xBenignEnd)(void);
  14859. } sqlite3Hooks = { 0, 0 };
  14860. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  14861. ** structure. If writable static data is unsupported on the target,
  14862. ** we have to locate the state vector at run-time. In the more common
  14863. ** case where writable static data is supported, wsdHooks can refer directly
  14864. ** to the "sqlite3Hooks" state vector declared above.
  14865. */
  14866. #ifdef SQLITE_OMIT_WSD
  14867. # define wsdHooksInit \
  14868. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  14869. # define wsdHooks x[0]
  14870. #else
  14871. # define wsdHooksInit
  14872. # define wsdHooks sqlite3Hooks
  14873. #endif
  14874. /*
  14875. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  14876. ** sqlite3EndBenignMalloc() are called, respectively.
  14877. */
  14878. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  14879. void (*xBenignBegin)(void),
  14880. void (*xBenignEnd)(void)
  14881. ){
  14882. wsdHooksInit;
  14883. wsdHooks.xBenignBegin = xBenignBegin;
  14884. wsdHooks.xBenignEnd = xBenignEnd;
  14885. }
  14886. /*
  14887. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  14888. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  14889. ** indicates that subsequent malloc failures are non-benign.
  14890. */
  14891. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  14892. wsdHooksInit;
  14893. if( wsdHooks.xBenignBegin ){
  14894. wsdHooks.xBenignBegin();
  14895. }
  14896. }
  14897. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  14898. wsdHooksInit;
  14899. if( wsdHooks.xBenignEnd ){
  14900. wsdHooks.xBenignEnd();
  14901. }
  14902. }
  14903. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  14904. /************** End of fault.c ***********************************************/
  14905. /************** Begin file mem0.c ********************************************/
  14906. /*
  14907. ** 2008 October 28
  14908. **
  14909. ** The author disclaims copyright to this source code. In place of
  14910. ** a legal notice, here is a blessing:
  14911. **
  14912. ** May you do good and not evil.
  14913. ** May you find forgiveness for yourself and forgive others.
  14914. ** May you share freely, never taking more than you give.
  14915. **
  14916. *************************************************************************
  14917. **
  14918. ** This file contains a no-op memory allocation drivers for use when
  14919. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  14920. ** here always fail. SQLite will not operate with these drivers. These
  14921. ** are merely placeholders. Real drivers must be substituted using
  14922. ** sqlite3_config() before SQLite will operate.
  14923. */
  14924. /*
  14925. ** This version of the memory allocator is the default. It is
  14926. ** used when no other memory allocator is specified using compile-time
  14927. ** macros.
  14928. */
  14929. #ifdef SQLITE_ZERO_MALLOC
  14930. /*
  14931. ** No-op versions of all memory allocation routines
  14932. */
  14933. static void *sqlite3MemMalloc(int nByte){ return 0; }
  14934. static void sqlite3MemFree(void *pPrior){ return; }
  14935. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  14936. static int sqlite3MemSize(void *pPrior){ return 0; }
  14937. static int sqlite3MemRoundup(int n){ return n; }
  14938. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  14939. static void sqlite3MemShutdown(void *NotUsed){ return; }
  14940. /*
  14941. ** This routine is the only routine in this file with external linkage.
  14942. **
  14943. ** Populate the low-level memory allocation function pointers in
  14944. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  14945. */
  14946. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  14947. static const sqlite3_mem_methods defaultMethods = {
  14948. sqlite3MemMalloc,
  14949. sqlite3MemFree,
  14950. sqlite3MemRealloc,
  14951. sqlite3MemSize,
  14952. sqlite3MemRoundup,
  14953. sqlite3MemInit,
  14954. sqlite3MemShutdown,
  14955. 0
  14956. };
  14957. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  14958. }
  14959. #endif /* SQLITE_ZERO_MALLOC */
  14960. /************** End of mem0.c ************************************************/
  14961. /************** Begin file mem1.c ********************************************/
  14962. /*
  14963. ** 2007 August 14
  14964. **
  14965. ** The author disclaims copyright to this source code. In place of
  14966. ** a legal notice, here is a blessing:
  14967. **
  14968. ** May you do good and not evil.
  14969. ** May you find forgiveness for yourself and forgive others.
  14970. ** May you share freely, never taking more than you give.
  14971. **
  14972. *************************************************************************
  14973. **
  14974. ** This file contains low-level memory allocation drivers for when
  14975. ** SQLite will use the standard C-library malloc/realloc/free interface
  14976. ** to obtain the memory it needs.
  14977. **
  14978. ** This file contains implementations of the low-level memory allocation
  14979. ** routines specified in the sqlite3_mem_methods object. The content of
  14980. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  14981. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  14982. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  14983. ** default configuration is to use memory allocation routines in this
  14984. ** file.
  14985. **
  14986. ** C-preprocessor macro summary:
  14987. **
  14988. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  14989. ** the malloc_usable_size() interface exists
  14990. ** on the target platform. Or, this symbol
  14991. ** can be set manually, if desired.
  14992. ** If an equivalent interface exists by
  14993. ** a different name, using a separate -D
  14994. ** option to rename it.
  14995. **
  14996. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  14997. ** memory allocator. Set this symbol to enable
  14998. ** building on older macs.
  14999. **
  15000. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  15001. ** _msize() on windows systems. This might
  15002. ** be necessary when compiling for Delphi,
  15003. ** for example.
  15004. */
  15005. /*
  15006. ** This version of the memory allocator is the default. It is
  15007. ** used when no other memory allocator is specified using compile-time
  15008. ** macros.
  15009. */
  15010. #ifdef SQLITE_SYSTEM_MALLOC
  15011. /*
  15012. ** The MSVCRT has malloc_usable_size() but it is called _msize().
  15013. ** The use of _msize() is automatic, but can be disabled by compiling
  15014. ** with -DSQLITE_WITHOUT_MSIZE
  15015. */
  15016. #if defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15017. # define SQLITE_MALLOCSIZE _msize
  15018. #endif
  15019. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15020. /*
  15021. ** Use the zone allocator available on apple products unless the
  15022. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15023. */
  15024. #include <sys/sysctl.h>
  15025. #include <malloc/malloc.h>
  15026. #include <libkern/OSAtomic.h>
  15027. static malloc_zone_t* _sqliteZone_;
  15028. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15029. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15030. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15031. #define SQLITE_MALLOCSIZE(x) \
  15032. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15033. #elif defined(SQLITE_OS_RTT)
  15034. #include <rtthread.h>
  15035. /*
  15036. ** Use standard C library malloc and free on non-Apple systems.
  15037. ** Also used by rt-thread systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15038. */
  15039. #define SQLITE_MALLOC(x) rt_malloc((rt_size_t)x)
  15040. #define SQLITE_FREE(x) rt_free(x)
  15041. #define SQLITE_REALLOC(x,y) rt_realloc((x),(rt_size_t)(y))
  15042. #if (!defined(SQLITE_WITHOUT_MSIZE)) \
  15043. && (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15044. # error "not have malloc_usable_size()"
  15045. #endif
  15046. #ifdef HAVE_MALLOC_USABLE_SIZE
  15047. # undef SQLITE_MALLOCSIZE
  15048. #endif
  15049. #else /* if not __APPLE__ */
  15050. /*
  15051. ** Use standard C library malloc and free on non-Apple systems.
  15052. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15053. */
  15054. #define SQLITE_MALLOC(x) malloc(x)
  15055. #define SQLITE_FREE(x) free(x)
  15056. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15057. #if (defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)) \
  15058. || (defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE))
  15059. # include <malloc.h> /* Needed for malloc_usable_size on linux */
  15060. #endif
  15061. #ifdef HAVE_MALLOC_USABLE_SIZE
  15062. # ifndef SQLITE_MALLOCSIZE
  15063. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15064. # endif
  15065. #else
  15066. # undef SQLITE_MALLOCSIZE
  15067. #endif
  15068. #endif /* __APPLE__ or not __APPLE__ */
  15069. /*
  15070. ** Like malloc(), but remember the size of the allocation
  15071. ** so that we can find it later using sqlite3MemSize().
  15072. **
  15073. ** For this low-level routine, we are guaranteed that nByte>0 because
  15074. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15075. ** routines.
  15076. */
  15077. static void *sqlite3MemMalloc(int nByte){
  15078. #ifdef SQLITE_MALLOCSIZE
  15079. void *p = SQLITE_MALLOC( nByte );
  15080. if( p==0 ){
  15081. testcase( sqlite3GlobalConfig.xLog!=0 );
  15082. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15083. }
  15084. return p;
  15085. #else
  15086. sqlite3_int64 *p;
  15087. assert( nByte>0 );
  15088. nByte = ROUND8(nByte);
  15089. p = SQLITE_MALLOC( nByte+8 );
  15090. if( p ){
  15091. p[0] = nByte;
  15092. p++;
  15093. }else{
  15094. testcase( sqlite3GlobalConfig.xLog!=0 );
  15095. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15096. }
  15097. return (void *)p;
  15098. #endif
  15099. }
  15100. /*
  15101. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15102. ** or sqlite3MemRealloc().
  15103. **
  15104. ** For this low-level routine, we already know that pPrior!=0 since
  15105. ** cases where pPrior==0 will have been intecepted and dealt with
  15106. ** by higher-level routines.
  15107. */
  15108. static void sqlite3MemFree(void *pPrior){
  15109. #ifdef SQLITE_MALLOCSIZE
  15110. SQLITE_FREE(pPrior);
  15111. #else
  15112. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15113. assert( pPrior!=0 );
  15114. p--;
  15115. SQLITE_FREE(p);
  15116. #endif
  15117. }
  15118. /*
  15119. ** Report the allocated size of a prior return from xMalloc()
  15120. ** or xRealloc().
  15121. */
  15122. static int sqlite3MemSize(void *pPrior){
  15123. #ifdef SQLITE_MALLOCSIZE
  15124. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15125. #else
  15126. sqlite3_int64 *p;
  15127. if( pPrior==0 ) return 0;
  15128. p = (sqlite3_int64*)pPrior;
  15129. p--;
  15130. return (int)p[0];
  15131. #endif
  15132. }
  15133. /*
  15134. ** Like realloc(). Resize an allocation previously obtained from
  15135. ** sqlite3MemMalloc().
  15136. **
  15137. ** For this low-level interface, we know that pPrior!=0. Cases where
  15138. ** pPrior==0 while have been intercepted by higher-level routine and
  15139. ** redirected to xMalloc. Similarly, we know that nByte>0 becauses
  15140. ** cases where nByte<=0 will have been intercepted by higher-level
  15141. ** routines and redirected to xFree.
  15142. */
  15143. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15144. #ifdef SQLITE_MALLOCSIZE
  15145. void *p = SQLITE_REALLOC(pPrior, nByte);
  15146. if( p==0 ){
  15147. testcase( sqlite3GlobalConfig.xLog!=0 );
  15148. sqlite3_log(SQLITE_NOMEM,
  15149. "failed memory resize %u to %u bytes",
  15150. SQLITE_MALLOCSIZE(pPrior), nByte);
  15151. }
  15152. return p;
  15153. #else
  15154. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15155. assert( pPrior!=0 && nByte>0 );
  15156. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15157. p--;
  15158. p = SQLITE_REALLOC(p, nByte+8 );
  15159. if( p ){
  15160. p[0] = nByte;
  15161. p++;
  15162. }else{
  15163. testcase( sqlite3GlobalConfig.xLog!=0 );
  15164. sqlite3_log(SQLITE_NOMEM,
  15165. "failed memory resize %u to %u bytes",
  15166. sqlite3MemSize(pPrior), nByte);
  15167. }
  15168. return (void*)p;
  15169. #endif
  15170. }
  15171. /*
  15172. ** Round up a request size to the next valid allocation size.
  15173. */
  15174. static int sqlite3MemRoundup(int n){
  15175. return ROUND8(n);
  15176. }
  15177. /*
  15178. ** Initialize this module.
  15179. */
  15180. static int sqlite3MemInit(void *NotUsed){
  15181. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15182. int cpuCount;
  15183. size_t len;
  15184. if( _sqliteZone_ ){
  15185. return SQLITE_OK;
  15186. }
  15187. len = sizeof(cpuCount);
  15188. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15189. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15190. if( cpuCount>1 ){
  15191. /* defer MT decisions to system malloc */
  15192. _sqliteZone_ = malloc_default_zone();
  15193. }else{
  15194. /* only 1 core, use our own zone to contention over global locks,
  15195. ** e.g. we have our own dedicated locks */
  15196. bool success;
  15197. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15198. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15199. do{
  15200. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15201. (void * volatile *)&_sqliteZone_);
  15202. }while(!_sqliteZone_);
  15203. if( !success ){
  15204. /* somebody registered a zone first */
  15205. malloc_destroy_zone(newzone);
  15206. }
  15207. }
  15208. #endif
  15209. UNUSED_PARAMETER(NotUsed);
  15210. return SQLITE_OK;
  15211. }
  15212. /*
  15213. ** Deinitialize this module.
  15214. */
  15215. static void sqlite3MemShutdown(void *NotUsed){
  15216. UNUSED_PARAMETER(NotUsed);
  15217. return;
  15218. }
  15219. /*
  15220. ** This routine is the only routine in this file with external linkage.
  15221. **
  15222. ** Populate the low-level memory allocation function pointers in
  15223. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15224. */
  15225. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15226. static const sqlite3_mem_methods defaultMethods = {
  15227. sqlite3MemMalloc,
  15228. sqlite3MemFree,
  15229. sqlite3MemRealloc,
  15230. sqlite3MemSize,
  15231. sqlite3MemRoundup,
  15232. sqlite3MemInit,
  15233. sqlite3MemShutdown,
  15234. 0
  15235. };
  15236. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15237. }
  15238. #endif /* SQLITE_SYSTEM_MALLOC */
  15239. /************** End of mem1.c ************************************************/
  15240. /************** Begin file mem2.c ********************************************/
  15241. /*
  15242. ** 2007 August 15
  15243. **
  15244. ** The author disclaims copyright to this source code. In place of
  15245. ** a legal notice, here is a blessing:
  15246. **
  15247. ** May you do good and not evil.
  15248. ** May you find forgiveness for yourself and forgive others.
  15249. ** May you share freely, never taking more than you give.
  15250. **
  15251. *************************************************************************
  15252. **
  15253. ** This file contains low-level memory allocation drivers for when
  15254. ** SQLite will use the standard C-library malloc/realloc/free interface
  15255. ** to obtain the memory it needs while adding lots of additional debugging
  15256. ** information to each allocation in order to help detect and fix memory
  15257. ** leaks and memory usage errors.
  15258. **
  15259. ** This file contains implementations of the low-level memory allocation
  15260. ** routines specified in the sqlite3_mem_methods object.
  15261. */
  15262. /*
  15263. ** This version of the memory allocator is used only if the
  15264. ** SQLITE_MEMDEBUG macro is defined
  15265. */
  15266. #ifdef SQLITE_MEMDEBUG
  15267. /*
  15268. ** The backtrace functionality is only available with GLIBC
  15269. */
  15270. #ifdef __GLIBC__
  15271. extern int backtrace(void**,int);
  15272. extern void backtrace_symbols_fd(void*const*,int,int);
  15273. #else
  15274. # define backtrace(A,B) 1
  15275. # define backtrace_symbols_fd(A,B,C)
  15276. #endif
  15277. /* #include <stdio.h> */
  15278. /*
  15279. ** Each memory allocation looks like this:
  15280. **
  15281. ** ------------------------------------------------------------------------
  15282. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  15283. ** ------------------------------------------------------------------------
  15284. **
  15285. ** The application code sees only a pointer to the allocation. We have
  15286. ** to back up from the allocation pointer to find the MemBlockHdr. The
  15287. ** MemBlockHdr tells us the size of the allocation and the number of
  15288. ** backtrace pointers. There is also a guard word at the end of the
  15289. ** MemBlockHdr.
  15290. */
  15291. struct MemBlockHdr {
  15292. i64 iSize; /* Size of this allocation */
  15293. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  15294. char nBacktrace; /* Number of backtraces on this alloc */
  15295. char nBacktraceSlots; /* Available backtrace slots */
  15296. u8 nTitle; /* Bytes of title; includes '\0' */
  15297. u8 eType; /* Allocation type code */
  15298. int iForeGuard; /* Guard word for sanity */
  15299. };
  15300. /*
  15301. ** Guard words
  15302. */
  15303. #define FOREGUARD 0x80F5E153
  15304. #define REARGUARD 0xE4676B53
  15305. /*
  15306. ** Number of malloc size increments to track.
  15307. */
  15308. #define NCSIZE 1000
  15309. /*
  15310. ** All of the static variables used by this module are collected
  15311. ** into a single structure named "mem". This is to keep the
  15312. ** static variables organized and to reduce namespace pollution
  15313. ** when this module is combined with other in the amalgamation.
  15314. */
  15315. static struct {
  15316. /*
  15317. ** Mutex to control access to the memory allocation subsystem.
  15318. */
  15319. sqlite3_mutex *mutex;
  15320. /*
  15321. ** Head and tail of a linked list of all outstanding allocations
  15322. */
  15323. struct MemBlockHdr *pFirst;
  15324. struct MemBlockHdr *pLast;
  15325. /*
  15326. ** The number of levels of backtrace to save in new allocations.
  15327. */
  15328. int nBacktrace;
  15329. void (*xBacktrace)(int, int, void **);
  15330. /*
  15331. ** Title text to insert in front of each block
  15332. */
  15333. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  15334. char zTitle[100]; /* The title text */
  15335. /*
  15336. ** sqlite3MallocDisallow() increments the following counter.
  15337. ** sqlite3MallocAllow() decrements it.
  15338. */
  15339. int disallow; /* Do not allow memory allocation */
  15340. /*
  15341. ** Gather statistics on the sizes of memory allocations.
  15342. ** nAlloc[i] is the number of allocation attempts of i*8
  15343. ** bytes. i==NCSIZE is the number of allocation attempts for
  15344. ** sizes more than NCSIZE*8 bytes.
  15345. */
  15346. int nAlloc[NCSIZE]; /* Total number of allocations */
  15347. int nCurrent[NCSIZE]; /* Current number of allocations */
  15348. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  15349. } mem;
  15350. /*
  15351. ** Adjust memory usage statistics
  15352. */
  15353. static void adjustStats(int iSize, int increment){
  15354. int i = ROUND8(iSize)/8;
  15355. if( i>NCSIZE-1 ){
  15356. i = NCSIZE - 1;
  15357. }
  15358. if( increment>0 ){
  15359. mem.nAlloc[i]++;
  15360. mem.nCurrent[i]++;
  15361. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  15362. mem.mxCurrent[i] = mem.nCurrent[i];
  15363. }
  15364. }else{
  15365. mem.nCurrent[i]--;
  15366. assert( mem.nCurrent[i]>=0 );
  15367. }
  15368. }
  15369. /*
  15370. ** Given an allocation, find the MemBlockHdr for that allocation.
  15371. **
  15372. ** This routine checks the guards at either end of the allocation and
  15373. ** if they are incorrect it asserts.
  15374. */
  15375. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  15376. struct MemBlockHdr *p;
  15377. int *pInt;
  15378. u8 *pU8;
  15379. int nReserve;
  15380. p = (struct MemBlockHdr*)pAllocation;
  15381. p--;
  15382. assert( p->iForeGuard==(int)FOREGUARD );
  15383. nReserve = ROUND8(p->iSize);
  15384. pInt = (int*)pAllocation;
  15385. pU8 = (u8*)pAllocation;
  15386. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  15387. /* This checks any of the "extra" bytes allocated due
  15388. ** to rounding up to an 8 byte boundary to ensure
  15389. ** they haven't been overwritten.
  15390. */
  15391. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  15392. return p;
  15393. }
  15394. /*
  15395. ** Return the number of bytes currently allocated at address p.
  15396. */
  15397. static int sqlite3MemSize(void *p){
  15398. struct MemBlockHdr *pHdr;
  15399. if( !p ){
  15400. return 0;
  15401. }
  15402. pHdr = sqlite3MemsysGetHeader(p);
  15403. return (int)pHdr->iSize;
  15404. }
  15405. /*
  15406. ** Initialize the memory allocation subsystem.
  15407. */
  15408. static int sqlite3MemInit(void *NotUsed){
  15409. UNUSED_PARAMETER(NotUsed);
  15410. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  15411. if( !sqlite3GlobalConfig.bMemstat ){
  15412. /* If memory status is enabled, then the malloc.c wrapper will already
  15413. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  15414. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15415. }
  15416. return SQLITE_OK;
  15417. }
  15418. /*
  15419. ** Deinitialize the memory allocation subsystem.
  15420. */
  15421. static void sqlite3MemShutdown(void *NotUsed){
  15422. UNUSED_PARAMETER(NotUsed);
  15423. mem.mutex = 0;
  15424. }
  15425. /*
  15426. ** Round up a request size to the next valid allocation size.
  15427. */
  15428. static int sqlite3MemRoundup(int n){
  15429. return ROUND8(n);
  15430. }
  15431. /*
  15432. ** Fill a buffer with pseudo-random bytes. This is used to preset
  15433. ** the content of a new memory allocation to unpredictable values and
  15434. ** to clear the content of a freed allocation to unpredictable values.
  15435. */
  15436. static void randomFill(char *pBuf, int nByte){
  15437. unsigned int x, y, r;
  15438. x = SQLITE_PTR_TO_INT(pBuf);
  15439. y = nByte | 1;
  15440. while( nByte >= 4 ){
  15441. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15442. y = y*1103515245 + 12345;
  15443. r = x ^ y;
  15444. *(int*)pBuf = r;
  15445. pBuf += 4;
  15446. nByte -= 4;
  15447. }
  15448. while( nByte-- > 0 ){
  15449. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  15450. y = y*1103515245 + 12345;
  15451. r = x ^ y;
  15452. *(pBuf++) = r & 0xff;
  15453. }
  15454. }
  15455. /*
  15456. ** Allocate nByte bytes of memory.
  15457. */
  15458. static void *sqlite3MemMalloc(int nByte){
  15459. struct MemBlockHdr *pHdr;
  15460. void **pBt;
  15461. char *z;
  15462. int *pInt;
  15463. void *p = 0;
  15464. int totalSize;
  15465. int nReserve;
  15466. sqlite3_mutex_enter(mem.mutex);
  15467. assert( mem.disallow==0 );
  15468. nReserve = ROUND8(nByte);
  15469. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  15470. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  15471. p = malloc(totalSize);
  15472. if( p ){
  15473. z = p;
  15474. pBt = (void**)&z[mem.nTitle];
  15475. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  15476. pHdr->pNext = 0;
  15477. pHdr->pPrev = mem.pLast;
  15478. if( mem.pLast ){
  15479. mem.pLast->pNext = pHdr;
  15480. }else{
  15481. mem.pFirst = pHdr;
  15482. }
  15483. mem.pLast = pHdr;
  15484. pHdr->iForeGuard = FOREGUARD;
  15485. pHdr->eType = MEMTYPE_HEAP;
  15486. pHdr->nBacktraceSlots = mem.nBacktrace;
  15487. pHdr->nTitle = mem.nTitle;
  15488. if( mem.nBacktrace ){
  15489. void *aAddr[40];
  15490. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  15491. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  15492. assert(pBt[0]);
  15493. if( mem.xBacktrace ){
  15494. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  15495. }
  15496. }else{
  15497. pHdr->nBacktrace = 0;
  15498. }
  15499. if( mem.nTitle ){
  15500. memcpy(z, mem.zTitle, mem.nTitle);
  15501. }
  15502. pHdr->iSize = nByte;
  15503. adjustStats(nByte, +1);
  15504. pInt = (int*)&pHdr[1];
  15505. pInt[nReserve/sizeof(int)] = REARGUARD;
  15506. randomFill((char*)pInt, nByte);
  15507. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  15508. p = (void*)pInt;
  15509. }
  15510. sqlite3_mutex_leave(mem.mutex);
  15511. return p;
  15512. }
  15513. /*
  15514. ** Free memory.
  15515. */
  15516. static void sqlite3MemFree(void *pPrior){
  15517. struct MemBlockHdr *pHdr;
  15518. void **pBt;
  15519. char *z;
  15520. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  15521. || mem.mutex!=0 );
  15522. pHdr = sqlite3MemsysGetHeader(pPrior);
  15523. pBt = (void**)pHdr;
  15524. pBt -= pHdr->nBacktraceSlots;
  15525. sqlite3_mutex_enter(mem.mutex);
  15526. if( pHdr->pPrev ){
  15527. assert( pHdr->pPrev->pNext==pHdr );
  15528. pHdr->pPrev->pNext = pHdr->pNext;
  15529. }else{
  15530. assert( mem.pFirst==pHdr );
  15531. mem.pFirst = pHdr->pNext;
  15532. }
  15533. if( pHdr->pNext ){
  15534. assert( pHdr->pNext->pPrev==pHdr );
  15535. pHdr->pNext->pPrev = pHdr->pPrev;
  15536. }else{
  15537. assert( mem.pLast==pHdr );
  15538. mem.pLast = pHdr->pPrev;
  15539. }
  15540. z = (char*)pBt;
  15541. z -= pHdr->nTitle;
  15542. adjustStats((int)pHdr->iSize, -1);
  15543. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  15544. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  15545. free(z);
  15546. sqlite3_mutex_leave(mem.mutex);
  15547. }
  15548. /*
  15549. ** Change the size of an existing memory allocation.
  15550. **
  15551. ** For this debugging implementation, we *always* make a copy of the
  15552. ** allocation into a new place in memory. In this way, if the
  15553. ** higher level code is using pointer to the old allocation, it is
  15554. ** much more likely to break and we are much more liking to find
  15555. ** the error.
  15556. */
  15557. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15558. struct MemBlockHdr *pOldHdr;
  15559. void *pNew;
  15560. assert( mem.disallow==0 );
  15561. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  15562. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  15563. pNew = sqlite3MemMalloc(nByte);
  15564. if( pNew ){
  15565. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  15566. if( nByte>pOldHdr->iSize ){
  15567. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  15568. }
  15569. sqlite3MemFree(pPrior);
  15570. }
  15571. return pNew;
  15572. }
  15573. /*
  15574. ** Populate the low-level memory allocation function pointers in
  15575. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15576. */
  15577. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15578. static const sqlite3_mem_methods defaultMethods = {
  15579. sqlite3MemMalloc,
  15580. sqlite3MemFree,
  15581. sqlite3MemRealloc,
  15582. sqlite3MemSize,
  15583. sqlite3MemRoundup,
  15584. sqlite3MemInit,
  15585. sqlite3MemShutdown,
  15586. 0
  15587. };
  15588. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15589. }
  15590. /*
  15591. ** Set the "type" of an allocation.
  15592. */
  15593. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  15594. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15595. struct MemBlockHdr *pHdr;
  15596. pHdr = sqlite3MemsysGetHeader(p);
  15597. assert( pHdr->iForeGuard==FOREGUARD );
  15598. pHdr->eType = eType;
  15599. }
  15600. }
  15601. /*
  15602. ** Return TRUE if the mask of type in eType matches the type of the
  15603. ** allocation p. Also return true if p==NULL.
  15604. **
  15605. ** This routine is designed for use within an assert() statement, to
  15606. ** verify the type of an allocation. For example:
  15607. **
  15608. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  15609. */
  15610. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  15611. int rc = 1;
  15612. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15613. struct MemBlockHdr *pHdr;
  15614. pHdr = sqlite3MemsysGetHeader(p);
  15615. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15616. if( (pHdr->eType&eType)==0 ){
  15617. rc = 0;
  15618. }
  15619. }
  15620. return rc;
  15621. }
  15622. /*
  15623. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  15624. ** allocation p. Also return true if p==NULL.
  15625. **
  15626. ** This routine is designed for use within an assert() statement, to
  15627. ** verify the type of an allocation. For example:
  15628. **
  15629. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  15630. */
  15631. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  15632. int rc = 1;
  15633. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  15634. struct MemBlockHdr *pHdr;
  15635. pHdr = sqlite3MemsysGetHeader(p);
  15636. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  15637. if( (pHdr->eType&eType)!=0 ){
  15638. rc = 0;
  15639. }
  15640. }
  15641. return rc;
  15642. }
  15643. /*
  15644. ** Set the number of backtrace levels kept for each allocation.
  15645. ** A value of zero turns off backtracing. The number is always rounded
  15646. ** up to a multiple of 2.
  15647. */
  15648. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  15649. if( depth<0 ){ depth = 0; }
  15650. if( depth>20 ){ depth = 20; }
  15651. depth = (depth+1)&0xfe;
  15652. mem.nBacktrace = depth;
  15653. }
  15654. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  15655. mem.xBacktrace = xBacktrace;
  15656. }
  15657. /*
  15658. ** Set the title string for subsequent allocations.
  15659. */
  15660. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  15661. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  15662. sqlite3_mutex_enter(mem.mutex);
  15663. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  15664. memcpy(mem.zTitle, zTitle, n);
  15665. mem.zTitle[n] = 0;
  15666. mem.nTitle = ROUND8(n);
  15667. sqlite3_mutex_leave(mem.mutex);
  15668. }
  15669. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  15670. struct MemBlockHdr *pHdr;
  15671. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15672. void **pBt = (void**)pHdr;
  15673. pBt -= pHdr->nBacktraceSlots;
  15674. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  15675. }
  15676. }
  15677. /*
  15678. ** Open the file indicated and write a log of all unfreed memory
  15679. ** allocations into that log.
  15680. */
  15681. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  15682. FILE *out;
  15683. struct MemBlockHdr *pHdr;
  15684. void **pBt;
  15685. int i;
  15686. out = fopen(zFilename, "w");
  15687. if( out==0 ){
  15688. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  15689. zFilename);
  15690. return;
  15691. }
  15692. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  15693. char *z = (char*)pHdr;
  15694. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  15695. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  15696. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  15697. if( pHdr->nBacktrace ){
  15698. fflush(out);
  15699. pBt = (void**)pHdr;
  15700. pBt -= pHdr->nBacktraceSlots;
  15701. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  15702. fprintf(out, "\n");
  15703. }
  15704. }
  15705. fprintf(out, "COUNTS:\n");
  15706. for(i=0; i<NCSIZE-1; i++){
  15707. if( mem.nAlloc[i] ){
  15708. fprintf(out, " %5d: %10d %10d %10d\n",
  15709. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  15710. }
  15711. }
  15712. if( mem.nAlloc[NCSIZE-1] ){
  15713. fprintf(out, " %5d: %10d %10d %10d\n",
  15714. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  15715. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  15716. }
  15717. fclose(out);
  15718. }
  15719. /*
  15720. ** Return the number of times sqlite3MemMalloc() has been called.
  15721. */
  15722. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  15723. int i;
  15724. int nTotal = 0;
  15725. for(i=0; i<NCSIZE; i++){
  15726. nTotal += mem.nAlloc[i];
  15727. }
  15728. return nTotal;
  15729. }
  15730. #endif /* SQLITE_MEMDEBUG */
  15731. /************** End of mem2.c ************************************************/
  15732. /************** Begin file mem3.c ********************************************/
  15733. /*
  15734. ** 2007 October 14
  15735. **
  15736. ** The author disclaims copyright to this source code. In place of
  15737. ** a legal notice, here is a blessing:
  15738. **
  15739. ** May you do good and not evil.
  15740. ** May you find forgiveness for yourself and forgive others.
  15741. ** May you share freely, never taking more than you give.
  15742. **
  15743. *************************************************************************
  15744. ** This file contains the C functions that implement a memory
  15745. ** allocation subsystem for use by SQLite.
  15746. **
  15747. ** This version of the memory allocation subsystem omits all
  15748. ** use of malloc(). The SQLite user supplies a block of memory
  15749. ** before calling sqlite3_initialize() from which allocations
  15750. ** are made and returned by the xMalloc() and xRealloc()
  15751. ** implementations. Once sqlite3_initialize() has been called,
  15752. ** the amount of memory available to SQLite is fixed and cannot
  15753. ** be changed.
  15754. **
  15755. ** This version of the memory allocation subsystem is included
  15756. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  15757. */
  15758. /*
  15759. ** This version of the memory allocator is only built into the library
  15760. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  15761. ** mean that the library will use a memory-pool by default, just that
  15762. ** it is available. The mempool allocator is activated by calling
  15763. ** sqlite3_config().
  15764. */
  15765. #ifdef SQLITE_ENABLE_MEMSYS3
  15766. /*
  15767. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  15768. */
  15769. #define MX_SMALL 10
  15770. /*
  15771. ** Number of freelist hash slots
  15772. */
  15773. #define N_HASH 61
  15774. /*
  15775. ** A memory allocation (also called a "chunk") consists of two or
  15776. ** more blocks where each block is 8 bytes. The first 8 bytes are
  15777. ** a header that is not returned to the user.
  15778. **
  15779. ** A chunk is two or more blocks that is either checked out or
  15780. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  15781. ** size of the allocation in blocks if the allocation is free.
  15782. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  15783. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  15784. ** is true if the previous chunk is checked out and false if the
  15785. ** previous chunk is free. The u.hdr.prevSize field is the size of
  15786. ** the previous chunk in blocks if the previous chunk is on the
  15787. ** freelist. If the previous chunk is checked out, then
  15788. ** u.hdr.prevSize can be part of the data for that chunk and should
  15789. ** not be read or written.
  15790. **
  15791. ** We often identify a chunk by its index in mem3.aPool[]. When
  15792. ** this is done, the chunk index refers to the second block of
  15793. ** the chunk. In this way, the first chunk has an index of 1.
  15794. ** A chunk index of 0 means "no such chunk" and is the equivalent
  15795. ** of a NULL pointer.
  15796. **
  15797. ** The second block of free chunks is of the form u.list. The
  15798. ** two fields form a double-linked list of chunks of related sizes.
  15799. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  15800. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  15801. **
  15802. ** The second block of a chunk is user data if the chunk is checked
  15803. ** out. If a chunk is checked out, the user data may extend into
  15804. ** the u.hdr.prevSize value of the following chunk.
  15805. */
  15806. typedef struct Mem3Block Mem3Block;
  15807. struct Mem3Block {
  15808. union {
  15809. struct {
  15810. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  15811. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  15812. } hdr;
  15813. struct {
  15814. u32 next; /* Index in mem3.aPool[] of next free chunk */
  15815. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  15816. } list;
  15817. } u;
  15818. };
  15819. /*
  15820. ** All of the static variables used by this module are collected
  15821. ** into a single structure named "mem3". This is to keep the
  15822. ** static variables organized and to reduce namespace pollution
  15823. ** when this module is combined with other in the amalgamation.
  15824. */
  15825. static SQLITE_WSD struct Mem3Global {
  15826. /*
  15827. ** Memory available for allocation. nPool is the size of the array
  15828. ** (in Mem3Blocks) pointed to by aPool less 2.
  15829. */
  15830. u32 nPool;
  15831. Mem3Block *aPool;
  15832. /*
  15833. ** True if we are evaluating an out-of-memory callback.
  15834. */
  15835. int alarmBusy;
  15836. /*
  15837. ** Mutex to control access to the memory allocation subsystem.
  15838. */
  15839. sqlite3_mutex *mutex;
  15840. /*
  15841. ** The minimum amount of free space that we have seen.
  15842. */
  15843. u32 mnMaster;
  15844. /*
  15845. ** iMaster is the index of the master chunk. Most new allocations
  15846. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  15847. ** of the current master. iMaster is 0 if there is not master chunk.
  15848. ** The master chunk is not in either the aiHash[] or aiSmall[].
  15849. */
  15850. u32 iMaster;
  15851. u32 szMaster;
  15852. /*
  15853. ** Array of lists of free blocks according to the block size
  15854. ** for smaller chunks, or a hash on the block size for larger
  15855. ** chunks.
  15856. */
  15857. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  15858. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  15859. } mem3 = { 97535575 };
  15860. #define mem3 GLOBAL(struct Mem3Global, mem3)
  15861. /*
  15862. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  15863. ** on. *pRoot is the list that i is a member of.
  15864. */
  15865. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  15866. u32 next = mem3.aPool[i].u.list.next;
  15867. u32 prev = mem3.aPool[i].u.list.prev;
  15868. assert( sqlite3_mutex_held(mem3.mutex) );
  15869. if( prev==0 ){
  15870. *pRoot = next;
  15871. }else{
  15872. mem3.aPool[prev].u.list.next = next;
  15873. }
  15874. if( next ){
  15875. mem3.aPool[next].u.list.prev = prev;
  15876. }
  15877. mem3.aPool[i].u.list.next = 0;
  15878. mem3.aPool[i].u.list.prev = 0;
  15879. }
  15880. /*
  15881. ** Unlink the chunk at index i from
  15882. ** whatever list is currently a member of.
  15883. */
  15884. static void memsys3Unlink(u32 i){
  15885. u32 size, hash;
  15886. assert( sqlite3_mutex_held(mem3.mutex) );
  15887. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15888. assert( i>=1 );
  15889. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15890. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15891. assert( size>=2 );
  15892. if( size <= MX_SMALL ){
  15893. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  15894. }else{
  15895. hash = size % N_HASH;
  15896. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  15897. }
  15898. }
  15899. /*
  15900. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  15901. ** at *pRoot.
  15902. */
  15903. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  15904. assert( sqlite3_mutex_held(mem3.mutex) );
  15905. mem3.aPool[i].u.list.next = *pRoot;
  15906. mem3.aPool[i].u.list.prev = 0;
  15907. if( *pRoot ){
  15908. mem3.aPool[*pRoot].u.list.prev = i;
  15909. }
  15910. *pRoot = i;
  15911. }
  15912. /*
  15913. ** Link the chunk at index i into either the appropriate
  15914. ** small chunk list, or into the large chunk hash table.
  15915. */
  15916. static void memsys3Link(u32 i){
  15917. u32 size, hash;
  15918. assert( sqlite3_mutex_held(mem3.mutex) );
  15919. assert( i>=1 );
  15920. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  15921. size = mem3.aPool[i-1].u.hdr.size4x/4;
  15922. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  15923. assert( size>=2 );
  15924. if( size <= MX_SMALL ){
  15925. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  15926. }else{
  15927. hash = size % N_HASH;
  15928. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  15929. }
  15930. }
  15931. /*
  15932. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  15933. ** will already be held (obtained by code in malloc.c) if
  15934. ** sqlite3GlobalConfig.bMemStat is true.
  15935. */
  15936. static void memsys3Enter(void){
  15937. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  15938. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  15939. }
  15940. sqlite3_mutex_enter(mem3.mutex);
  15941. }
  15942. static void memsys3Leave(void){
  15943. sqlite3_mutex_leave(mem3.mutex);
  15944. }
  15945. /*
  15946. ** Called when we are unable to satisfy an allocation of nBytes.
  15947. */
  15948. static void memsys3OutOfMemory(int nByte){
  15949. if( !mem3.alarmBusy ){
  15950. mem3.alarmBusy = 1;
  15951. assert( sqlite3_mutex_held(mem3.mutex) );
  15952. sqlite3_mutex_leave(mem3.mutex);
  15953. sqlite3_release_memory(nByte);
  15954. sqlite3_mutex_enter(mem3.mutex);
  15955. mem3.alarmBusy = 0;
  15956. }
  15957. }
  15958. /*
  15959. ** Chunk i is a free chunk that has been unlinked. Adjust its
  15960. ** size parameters for check-out and return a pointer to the
  15961. ** user portion of the chunk.
  15962. */
  15963. static void *memsys3Checkout(u32 i, u32 nBlock){
  15964. u32 x;
  15965. assert( sqlite3_mutex_held(mem3.mutex) );
  15966. assert( i>=1 );
  15967. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  15968. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  15969. x = mem3.aPool[i-1].u.hdr.size4x;
  15970. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  15971. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  15972. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  15973. return &mem3.aPool[i];
  15974. }
  15975. /*
  15976. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  15977. ** Return a pointer to the new allocation. Or, if the master chunk
  15978. ** is not large enough, return 0.
  15979. */
  15980. static void *memsys3FromMaster(u32 nBlock){
  15981. assert( sqlite3_mutex_held(mem3.mutex) );
  15982. assert( mem3.szMaster>=nBlock );
  15983. if( nBlock>=mem3.szMaster-1 ){
  15984. /* Use the entire master */
  15985. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  15986. mem3.iMaster = 0;
  15987. mem3.szMaster = 0;
  15988. mem3.mnMaster = 0;
  15989. return p;
  15990. }else{
  15991. /* Split the master block. Return the tail. */
  15992. u32 newi, x;
  15993. newi = mem3.iMaster + mem3.szMaster - nBlock;
  15994. assert( newi > mem3.iMaster+1 );
  15995. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  15996. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  15997. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  15998. mem3.szMaster -= nBlock;
  15999. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  16000. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16001. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16002. if( mem3.szMaster < mem3.mnMaster ){
  16003. mem3.mnMaster = mem3.szMaster;
  16004. }
  16005. return (void*)&mem3.aPool[newi];
  16006. }
  16007. }
  16008. /*
  16009. ** *pRoot is the head of a list of free chunks of the same size
  16010. ** or same size hash. In other words, *pRoot is an entry in either
  16011. ** mem3.aiSmall[] or mem3.aiHash[].
  16012. **
  16013. ** This routine examines all entries on the given list and tries
  16014. ** to coalesce each entries with adjacent free chunks.
  16015. **
  16016. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  16017. ** the current mem3.iMaster with the new larger chunk. In order for
  16018. ** this mem3.iMaster replacement to work, the master chunk must be
  16019. ** linked into the hash tables. That is not the normal state of
  16020. ** affairs, of course. The calling routine must link the master
  16021. ** chunk before invoking this routine, then must unlink the (possibly
  16022. ** changed) master chunk once this routine has finished.
  16023. */
  16024. static void memsys3Merge(u32 *pRoot){
  16025. u32 iNext, prev, size, i, x;
  16026. assert( sqlite3_mutex_held(mem3.mutex) );
  16027. for(i=*pRoot; i>0; i=iNext){
  16028. iNext = mem3.aPool[i].u.list.next;
  16029. size = mem3.aPool[i-1].u.hdr.size4x;
  16030. assert( (size&1)==0 );
  16031. if( (size&2)==0 ){
  16032. memsys3UnlinkFromList(i, pRoot);
  16033. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16034. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16035. if( prev==iNext ){
  16036. iNext = mem3.aPool[prev].u.list.next;
  16037. }
  16038. memsys3Unlink(prev);
  16039. size = i + size/4 - prev;
  16040. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16041. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16042. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16043. memsys3Link(prev);
  16044. i = prev;
  16045. }else{
  16046. size /= 4;
  16047. }
  16048. if( size>mem3.szMaster ){
  16049. mem3.iMaster = i;
  16050. mem3.szMaster = size;
  16051. }
  16052. }
  16053. }
  16054. /*
  16055. ** Return a block of memory of at least nBytes in size.
  16056. ** Return NULL if unable.
  16057. **
  16058. ** This function assumes that the necessary mutexes, if any, are
  16059. ** already held by the caller. Hence "Unsafe".
  16060. */
  16061. static void *memsys3MallocUnsafe(int nByte){
  16062. u32 i;
  16063. u32 nBlock;
  16064. u32 toFree;
  16065. assert( sqlite3_mutex_held(mem3.mutex) );
  16066. assert( sizeof(Mem3Block)==8 );
  16067. if( nByte<=12 ){
  16068. nBlock = 2;
  16069. }else{
  16070. nBlock = (nByte + 11)/8;
  16071. }
  16072. assert( nBlock>=2 );
  16073. /* STEP 1:
  16074. ** Look for an entry of the correct size in either the small
  16075. ** chunk table or in the large chunk hash table. This is
  16076. ** successful most of the time (about 9 times out of 10).
  16077. */
  16078. if( nBlock <= MX_SMALL ){
  16079. i = mem3.aiSmall[nBlock-2];
  16080. if( i>0 ){
  16081. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16082. return memsys3Checkout(i, nBlock);
  16083. }
  16084. }else{
  16085. int hash = nBlock % N_HASH;
  16086. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16087. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16088. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16089. return memsys3Checkout(i, nBlock);
  16090. }
  16091. }
  16092. }
  16093. /* STEP 2:
  16094. ** Try to satisfy the allocation by carving a piece off of the end
  16095. ** of the master chunk. This step usually works if step 1 fails.
  16096. */
  16097. if( mem3.szMaster>=nBlock ){
  16098. return memsys3FromMaster(nBlock);
  16099. }
  16100. /* STEP 3:
  16101. ** Loop through the entire memory pool. Coalesce adjacent free
  16102. ** chunks. Recompute the master chunk as the largest free chunk.
  16103. ** Then try again to satisfy the allocation by carving a piece off
  16104. ** of the end of the master chunk. This step happens very
  16105. ** rarely (we hope!)
  16106. */
  16107. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16108. memsys3OutOfMemory(toFree);
  16109. if( mem3.iMaster ){
  16110. memsys3Link(mem3.iMaster);
  16111. mem3.iMaster = 0;
  16112. mem3.szMaster = 0;
  16113. }
  16114. for(i=0; i<N_HASH; i++){
  16115. memsys3Merge(&mem3.aiHash[i]);
  16116. }
  16117. for(i=0; i<MX_SMALL-1; i++){
  16118. memsys3Merge(&mem3.aiSmall[i]);
  16119. }
  16120. if( mem3.szMaster ){
  16121. memsys3Unlink(mem3.iMaster);
  16122. if( mem3.szMaster>=nBlock ){
  16123. return memsys3FromMaster(nBlock);
  16124. }
  16125. }
  16126. }
  16127. /* If none of the above worked, then we fail. */
  16128. return 0;
  16129. }
  16130. /*
  16131. ** Free an outstanding memory allocation.
  16132. **
  16133. ** This function assumes that the necessary mutexes, if any, are
  16134. ** already held by the caller. Hence "Unsafe".
  16135. */
  16136. static void memsys3FreeUnsafe(void *pOld){
  16137. Mem3Block *p = (Mem3Block*)pOld;
  16138. int i;
  16139. u32 size, x;
  16140. assert( sqlite3_mutex_held(mem3.mutex) );
  16141. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16142. i = p - mem3.aPool;
  16143. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16144. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16145. assert( i+size<=mem3.nPool+1 );
  16146. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16147. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16148. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16149. memsys3Link(i);
  16150. /* Try to expand the master using the newly freed chunk */
  16151. if( mem3.iMaster ){
  16152. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16153. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16154. mem3.iMaster -= size;
  16155. mem3.szMaster += size;
  16156. memsys3Unlink(mem3.iMaster);
  16157. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16158. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16159. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16160. }
  16161. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16162. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16163. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16164. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16165. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16166. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16167. }
  16168. }
  16169. }
  16170. /*
  16171. ** Return the size of an outstanding allocation, in bytes. The
  16172. ** size returned omits the 8-byte header overhead. This only
  16173. ** works for chunks that are currently checked out.
  16174. */
  16175. static int memsys3Size(void *p){
  16176. Mem3Block *pBlock;
  16177. if( p==0 ) return 0;
  16178. pBlock = (Mem3Block*)p;
  16179. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16180. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16181. }
  16182. /*
  16183. ** Round up a request size to the next valid allocation size.
  16184. */
  16185. static int memsys3Roundup(int n){
  16186. if( n<=12 ){
  16187. return 12;
  16188. }else{
  16189. return ((n+11)&~7) - 4;
  16190. }
  16191. }
  16192. /*
  16193. ** Allocate nBytes of memory.
  16194. */
  16195. static void *memsys3Malloc(int nBytes){
  16196. sqlite3_int64 *p;
  16197. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16198. memsys3Enter();
  16199. p = memsys3MallocUnsafe(nBytes);
  16200. memsys3Leave();
  16201. return (void*)p;
  16202. }
  16203. /*
  16204. ** Free memory.
  16205. */
  16206. static void memsys3Free(void *pPrior){
  16207. assert( pPrior );
  16208. memsys3Enter();
  16209. memsys3FreeUnsafe(pPrior);
  16210. memsys3Leave();
  16211. }
  16212. /*
  16213. ** Change the size of an existing memory allocation
  16214. */
  16215. static void *memsys3Realloc(void *pPrior, int nBytes){
  16216. int nOld;
  16217. void *p;
  16218. if( pPrior==0 ){
  16219. return sqlite3_malloc(nBytes);
  16220. }
  16221. if( nBytes<=0 ){
  16222. sqlite3_free(pPrior);
  16223. return 0;
  16224. }
  16225. nOld = memsys3Size(pPrior);
  16226. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16227. return pPrior;
  16228. }
  16229. memsys3Enter();
  16230. p = memsys3MallocUnsafe(nBytes);
  16231. if( p ){
  16232. if( nOld<nBytes ){
  16233. memcpy(p, pPrior, nOld);
  16234. }else{
  16235. memcpy(p, pPrior, nBytes);
  16236. }
  16237. memsys3FreeUnsafe(pPrior);
  16238. }
  16239. memsys3Leave();
  16240. return p;
  16241. }
  16242. /*
  16243. ** Initialize this module.
  16244. */
  16245. static int memsys3Init(void *NotUsed){
  16246. UNUSED_PARAMETER(NotUsed);
  16247. if( !sqlite3GlobalConfig.pHeap ){
  16248. return SQLITE_ERROR;
  16249. }
  16250. /* Store a pointer to the memory block in global structure mem3. */
  16251. assert( sizeof(Mem3Block)==8 );
  16252. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16253. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16254. /* Initialize the master block. */
  16255. mem3.szMaster = mem3.nPool;
  16256. mem3.mnMaster = mem3.szMaster;
  16257. mem3.iMaster = 1;
  16258. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16259. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16260. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16261. return SQLITE_OK;
  16262. }
  16263. /*
  16264. ** Deinitialize this module.
  16265. */
  16266. static void memsys3Shutdown(void *NotUsed){
  16267. UNUSED_PARAMETER(NotUsed);
  16268. mem3.mutex = 0;
  16269. return;
  16270. }
  16271. /*
  16272. ** Open the file indicated and write a log of all unfreed memory
  16273. ** allocations into that log.
  16274. */
  16275. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  16276. #ifdef SQLITE_DEBUG
  16277. FILE *out;
  16278. u32 i, j;
  16279. u32 size;
  16280. if( zFilename==0 || zFilename[0]==0 ){
  16281. out = stdout;
  16282. }else{
  16283. out = fopen(zFilename, "w");
  16284. if( out==0 ){
  16285. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16286. zFilename);
  16287. return;
  16288. }
  16289. }
  16290. memsys3Enter();
  16291. fprintf(out, "CHUNKS:\n");
  16292. for(i=1; i<=mem3.nPool; i+=size/4){
  16293. size = mem3.aPool[i-1].u.hdr.size4x;
  16294. if( size/4<=1 ){
  16295. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  16296. assert( 0 );
  16297. break;
  16298. }
  16299. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  16300. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  16301. assert( 0 );
  16302. break;
  16303. }
  16304. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  16305. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  16306. assert( 0 );
  16307. break;
  16308. }
  16309. if( size&1 ){
  16310. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  16311. }else{
  16312. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  16313. i==mem3.iMaster ? " **master**" : "");
  16314. }
  16315. }
  16316. for(i=0; i<MX_SMALL-1; i++){
  16317. if( mem3.aiSmall[i]==0 ) continue;
  16318. fprintf(out, "small(%2d):", i);
  16319. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  16320. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16321. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16322. }
  16323. fprintf(out, "\n");
  16324. }
  16325. for(i=0; i<N_HASH; i++){
  16326. if( mem3.aiHash[i]==0 ) continue;
  16327. fprintf(out, "hash(%2d):", i);
  16328. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  16329. fprintf(out, " %p(%d)", &mem3.aPool[j],
  16330. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  16331. }
  16332. fprintf(out, "\n");
  16333. }
  16334. fprintf(out, "master=%d\n", mem3.iMaster);
  16335. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  16336. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  16337. sqlite3_mutex_leave(mem3.mutex);
  16338. if( out==stdout ){
  16339. fflush(stdout);
  16340. }else{
  16341. fclose(out);
  16342. }
  16343. #else
  16344. UNUSED_PARAMETER(zFilename);
  16345. #endif
  16346. }
  16347. /*
  16348. ** This routine is the only routine in this file with external
  16349. ** linkage.
  16350. **
  16351. ** Populate the low-level memory allocation function pointers in
  16352. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  16353. ** arguments specify the block of memory to manage.
  16354. **
  16355. ** This routine is only called by sqlite3_config(), and therefore
  16356. ** is not required to be threadsafe (it is not).
  16357. */
  16358. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  16359. static const sqlite3_mem_methods mempoolMethods = {
  16360. memsys3Malloc,
  16361. memsys3Free,
  16362. memsys3Realloc,
  16363. memsys3Size,
  16364. memsys3Roundup,
  16365. memsys3Init,
  16366. memsys3Shutdown,
  16367. 0
  16368. };
  16369. return &mempoolMethods;
  16370. }
  16371. #endif /* SQLITE_ENABLE_MEMSYS3 */
  16372. /************** End of mem3.c ************************************************/
  16373. /************** Begin file mem5.c ********************************************/
  16374. /*
  16375. ** 2007 October 14
  16376. **
  16377. ** The author disclaims copyright to this source code. In place of
  16378. ** a legal notice, here is a blessing:
  16379. **
  16380. ** May you do good and not evil.
  16381. ** May you find forgiveness for yourself and forgive others.
  16382. ** May you share freely, never taking more than you give.
  16383. **
  16384. *************************************************************************
  16385. ** This file contains the C functions that implement a memory
  16386. ** allocation subsystem for use by SQLite.
  16387. **
  16388. ** This version of the memory allocation subsystem omits all
  16389. ** use of malloc(). The application gives SQLite a block of memory
  16390. ** before calling sqlite3_initialize() from which allocations
  16391. ** are made and returned by the xMalloc() and xRealloc()
  16392. ** implementations. Once sqlite3_initialize() has been called,
  16393. ** the amount of memory available to SQLite is fixed and cannot
  16394. ** be changed.
  16395. **
  16396. ** This version of the memory allocation subsystem is included
  16397. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  16398. **
  16399. ** This memory allocator uses the following algorithm:
  16400. **
  16401. ** 1. All memory allocations sizes are rounded up to a power of 2.
  16402. **
  16403. ** 2. If two adjacent free blocks are the halves of a larger block,
  16404. ** then the two blocks are coalesed into the single larger block.
  16405. **
  16406. ** 3. New memory is allocated from the first available free block.
  16407. **
  16408. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  16409. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  16410. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  16411. **
  16412. ** Let n be the size of the largest allocation divided by the minimum
  16413. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  16414. ** be the maximum amount of memory ever outstanding at one time. Let
  16415. ** N be the total amount of memory available for allocation. Robson
  16416. ** proved that this memory allocator will never breakdown due to
  16417. ** fragmentation as long as the following constraint holds:
  16418. **
  16419. ** N >= M*(1 + log2(n)/2) - n + 1
  16420. **
  16421. ** The sqlite3_status() logic tracks the maximum values of n and M so
  16422. ** that an application can, at any time, verify this constraint.
  16423. */
  16424. /*
  16425. ** This version of the memory allocator is used only when
  16426. ** SQLITE_ENABLE_MEMSYS5 is defined.
  16427. */
  16428. #ifdef SQLITE_ENABLE_MEMSYS5
  16429. /*
  16430. ** A minimum allocation is an instance of the following structure.
  16431. ** Larger allocations are an array of these structures where the
  16432. ** size of the array is a power of 2.
  16433. **
  16434. ** The size of this object must be a power of two. That fact is
  16435. ** verified in memsys5Init().
  16436. */
  16437. typedef struct Mem5Link Mem5Link;
  16438. struct Mem5Link {
  16439. int next; /* Index of next free chunk */
  16440. int prev; /* Index of previous free chunk */
  16441. };
  16442. /*
  16443. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  16444. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  16445. ** it is not actually possible to reach this limit.
  16446. */
  16447. #define LOGMAX 30
  16448. /*
  16449. ** Masks used for mem5.aCtrl[] elements.
  16450. */
  16451. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  16452. #define CTRL_FREE 0x20 /* True if not checked out */
  16453. /*
  16454. ** All of the static variables used by this module are collected
  16455. ** into a single structure named "mem5". This is to keep the
  16456. ** static variables organized and to reduce namespace pollution
  16457. ** when this module is combined with other in the amalgamation.
  16458. */
  16459. static SQLITE_WSD struct Mem5Global {
  16460. /*
  16461. ** Memory available for allocation
  16462. */
  16463. int szAtom; /* Smallest possible allocation in bytes */
  16464. int nBlock; /* Number of szAtom sized blocks in zPool */
  16465. u8 *zPool; /* Memory available to be allocated */
  16466. /*
  16467. ** Mutex to control access to the memory allocation subsystem.
  16468. */
  16469. sqlite3_mutex *mutex;
  16470. /*
  16471. ** Performance statistics
  16472. */
  16473. u64 nAlloc; /* Total number of calls to malloc */
  16474. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  16475. u64 totalExcess; /* Total internal fragmentation */
  16476. u32 currentOut; /* Current checkout, including internal fragmentation */
  16477. u32 currentCount; /* Current number of distinct checkouts */
  16478. u32 maxOut; /* Maximum instantaneous currentOut */
  16479. u32 maxCount; /* Maximum instantaneous currentCount */
  16480. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  16481. /*
  16482. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  16483. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  16484. ** and so forth.
  16485. */
  16486. int aiFreelist[LOGMAX+1];
  16487. /*
  16488. ** Space for tracking which blocks are checked out and the size
  16489. ** of each block. One byte per block.
  16490. */
  16491. u8 *aCtrl;
  16492. } mem5;
  16493. /*
  16494. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  16495. */
  16496. #define mem5 GLOBAL(struct Mem5Global, mem5)
  16497. /*
  16498. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  16499. ** structures, return a pointer to the idx-th such link.
  16500. */
  16501. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  16502. /*
  16503. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  16504. ** on. It should be found on mem5.aiFreelist[iLogsize].
  16505. */
  16506. static void memsys5Unlink(int i, int iLogsize){
  16507. int next, prev;
  16508. assert( i>=0 && i<mem5.nBlock );
  16509. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16510. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16511. next = MEM5LINK(i)->next;
  16512. prev = MEM5LINK(i)->prev;
  16513. if( prev<0 ){
  16514. mem5.aiFreelist[iLogsize] = next;
  16515. }else{
  16516. MEM5LINK(prev)->next = next;
  16517. }
  16518. if( next>=0 ){
  16519. MEM5LINK(next)->prev = prev;
  16520. }
  16521. }
  16522. /*
  16523. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  16524. ** free list.
  16525. */
  16526. static void memsys5Link(int i, int iLogsize){
  16527. int x;
  16528. assert( sqlite3_mutex_held(mem5.mutex) );
  16529. assert( i>=0 && i<mem5.nBlock );
  16530. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16531. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  16532. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  16533. MEM5LINK(i)->prev = -1;
  16534. if( x>=0 ){
  16535. assert( x<mem5.nBlock );
  16536. MEM5LINK(x)->prev = i;
  16537. }
  16538. mem5.aiFreelist[iLogsize] = i;
  16539. }
  16540. /*
  16541. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16542. ** will already be held (obtained by code in malloc.c) if
  16543. ** sqlite3GlobalConfig.bMemStat is true.
  16544. */
  16545. static void memsys5Enter(void){
  16546. sqlite3_mutex_enter(mem5.mutex);
  16547. }
  16548. static void memsys5Leave(void){
  16549. sqlite3_mutex_leave(mem5.mutex);
  16550. }
  16551. /*
  16552. ** Return the size of an outstanding allocation, in bytes. The
  16553. ** size returned omits the 8-byte header overhead. This only
  16554. ** works for chunks that are currently checked out.
  16555. */
  16556. static int memsys5Size(void *p){
  16557. int iSize = 0;
  16558. if( p ){
  16559. int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
  16560. assert( i>=0 && i<mem5.nBlock );
  16561. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  16562. }
  16563. return iSize;
  16564. }
  16565. /*
  16566. ** Find the first entry on the freelist iLogsize. Unlink that
  16567. ** entry and return its index.
  16568. */
  16569. static int memsys5UnlinkFirst(int iLogsize){
  16570. int i;
  16571. int iFirst;
  16572. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  16573. i = iFirst = mem5.aiFreelist[iLogsize];
  16574. assert( iFirst>=0 );
  16575. while( i>0 ){
  16576. if( i<iFirst ) iFirst = i;
  16577. i = MEM5LINK(i)->next;
  16578. }
  16579. memsys5Unlink(iFirst, iLogsize);
  16580. return iFirst;
  16581. }
  16582. /*
  16583. ** Return a block of memory of at least nBytes in size.
  16584. ** Return NULL if unable. Return NULL if nBytes==0.
  16585. **
  16586. ** The caller guarantees that nByte is positive.
  16587. **
  16588. ** The caller has obtained a mutex prior to invoking this
  16589. ** routine so there is never any chance that two or more
  16590. ** threads can be in this routine at the same time.
  16591. */
  16592. static void *memsys5MallocUnsafe(int nByte){
  16593. int i; /* Index of a mem5.aPool[] slot */
  16594. int iBin; /* Index into mem5.aiFreelist[] */
  16595. int iFullSz; /* Size of allocation rounded up to power of 2 */
  16596. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  16597. /* nByte must be a positive */
  16598. assert( nByte>0 );
  16599. /* Keep track of the maximum allocation request. Even unfulfilled
  16600. ** requests are counted */
  16601. if( (u32)nByte>mem5.maxRequest ){
  16602. mem5.maxRequest = nByte;
  16603. }
  16604. /* Abort if the requested allocation size is larger than the largest
  16605. ** power of two that we can represent using 32-bit signed integers.
  16606. */
  16607. if( nByte > 0x40000000 ){
  16608. return 0;
  16609. }
  16610. /* Round nByte up to the next valid power of two */
  16611. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  16612. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  16613. ** block. If not, then split a block of the next larger power of
  16614. ** two in order to create a new free block of size iLogsize.
  16615. */
  16616. for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
  16617. if( iBin>LOGMAX ){
  16618. testcase( sqlite3GlobalConfig.xLog!=0 );
  16619. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  16620. return 0;
  16621. }
  16622. i = memsys5UnlinkFirst(iBin);
  16623. while( iBin>iLogsize ){
  16624. int newSize;
  16625. iBin--;
  16626. newSize = 1 << iBin;
  16627. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  16628. memsys5Link(i+newSize, iBin);
  16629. }
  16630. mem5.aCtrl[i] = iLogsize;
  16631. /* Update allocator performance statistics. */
  16632. mem5.nAlloc++;
  16633. mem5.totalAlloc += iFullSz;
  16634. mem5.totalExcess += iFullSz - nByte;
  16635. mem5.currentCount++;
  16636. mem5.currentOut += iFullSz;
  16637. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  16638. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  16639. /* Return a pointer to the allocated memory. */
  16640. return (void*)&mem5.zPool[i*mem5.szAtom];
  16641. }
  16642. /*
  16643. ** Free an outstanding memory allocation.
  16644. */
  16645. static void memsys5FreeUnsafe(void *pOld){
  16646. u32 size, iLogsize;
  16647. int iBlock;
  16648. /* Set iBlock to the index of the block pointed to by pOld in
  16649. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  16650. */
  16651. iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
  16652. /* Check that the pointer pOld points to a valid, non-free block. */
  16653. assert( iBlock>=0 && iBlock<mem5.nBlock );
  16654. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  16655. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  16656. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  16657. size = 1<<iLogsize;
  16658. assert( iBlock+size-1<(u32)mem5.nBlock );
  16659. mem5.aCtrl[iBlock] |= CTRL_FREE;
  16660. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  16661. assert( mem5.currentCount>0 );
  16662. assert( mem5.currentOut>=(size*mem5.szAtom) );
  16663. mem5.currentCount--;
  16664. mem5.currentOut -= size*mem5.szAtom;
  16665. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  16666. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  16667. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16668. while( ALWAYS(iLogsize<LOGMAX) ){
  16669. int iBuddy;
  16670. if( (iBlock>>iLogsize) & 1 ){
  16671. iBuddy = iBlock - size;
  16672. }else{
  16673. iBuddy = iBlock + size;
  16674. }
  16675. assert( iBuddy>=0 );
  16676. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  16677. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  16678. memsys5Unlink(iBuddy, iLogsize);
  16679. iLogsize++;
  16680. if( iBuddy<iBlock ){
  16681. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  16682. mem5.aCtrl[iBlock] = 0;
  16683. iBlock = iBuddy;
  16684. }else{
  16685. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  16686. mem5.aCtrl[iBuddy] = 0;
  16687. }
  16688. size *= 2;
  16689. }
  16690. memsys5Link(iBlock, iLogsize);
  16691. }
  16692. /*
  16693. ** Allocate nBytes of memory.
  16694. */
  16695. static void *memsys5Malloc(int nBytes){
  16696. sqlite3_int64 *p = 0;
  16697. if( nBytes>0 ){
  16698. memsys5Enter();
  16699. p = memsys5MallocUnsafe(nBytes);
  16700. memsys5Leave();
  16701. }
  16702. return (void*)p;
  16703. }
  16704. /*
  16705. ** Free memory.
  16706. **
  16707. ** The outer layer memory allocator prevents this routine from
  16708. ** being called with pPrior==0.
  16709. */
  16710. static void memsys5Free(void *pPrior){
  16711. assert( pPrior!=0 );
  16712. memsys5Enter();
  16713. memsys5FreeUnsafe(pPrior);
  16714. memsys5Leave();
  16715. }
  16716. /*
  16717. ** Change the size of an existing memory allocation.
  16718. **
  16719. ** The outer layer memory allocator prevents this routine from
  16720. ** being called with pPrior==0.
  16721. **
  16722. ** nBytes is always a value obtained from a prior call to
  16723. ** memsys5Round(). Hence nBytes is always a non-negative power
  16724. ** of two. If nBytes==0 that means that an oversize allocation
  16725. ** (an allocation larger than 0x40000000) was requested and this
  16726. ** routine should return 0 without freeing pPrior.
  16727. */
  16728. static void *memsys5Realloc(void *pPrior, int nBytes){
  16729. int nOld;
  16730. void *p;
  16731. assert( pPrior!=0 );
  16732. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  16733. assert( nBytes>=0 );
  16734. if( nBytes==0 ){
  16735. return 0;
  16736. }
  16737. nOld = memsys5Size(pPrior);
  16738. if( nBytes<=nOld ){
  16739. return pPrior;
  16740. }
  16741. memsys5Enter();
  16742. p = memsys5MallocUnsafe(nBytes);
  16743. if( p ){
  16744. memcpy(p, pPrior, nOld);
  16745. memsys5FreeUnsafe(pPrior);
  16746. }
  16747. memsys5Leave();
  16748. return p;
  16749. }
  16750. /*
  16751. ** Round up a request size to the next valid allocation size. If
  16752. ** the allocation is too large to be handled by this allocation system,
  16753. ** return 0.
  16754. **
  16755. ** All allocations must be a power of two and must be expressed by a
  16756. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  16757. ** or 1073741824 bytes.
  16758. */
  16759. static int memsys5Roundup(int n){
  16760. int iFullSz;
  16761. if( n > 0x40000000 ) return 0;
  16762. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  16763. return iFullSz;
  16764. }
  16765. /*
  16766. ** Return the ceiling of the logarithm base 2 of iValue.
  16767. **
  16768. ** Examples: memsys5Log(1) -> 0
  16769. ** memsys5Log(2) -> 1
  16770. ** memsys5Log(4) -> 2
  16771. ** memsys5Log(5) -> 3
  16772. ** memsys5Log(8) -> 3
  16773. ** memsys5Log(9) -> 4
  16774. */
  16775. static int memsys5Log(int iValue){
  16776. int iLog;
  16777. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  16778. return iLog;
  16779. }
  16780. /*
  16781. ** Initialize the memory allocator.
  16782. **
  16783. ** This routine is not threadsafe. The caller must be holding a mutex
  16784. ** to prevent multiple threads from entering at the same time.
  16785. */
  16786. static int memsys5Init(void *NotUsed){
  16787. int ii; /* Loop counter */
  16788. int nByte; /* Number of bytes of memory available to this allocator */
  16789. u8 *zByte; /* Memory usable by this allocator */
  16790. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  16791. int iOffset; /* An offset into mem5.aCtrl[] */
  16792. UNUSED_PARAMETER(NotUsed);
  16793. /* For the purposes of this routine, disable the mutex */
  16794. mem5.mutex = 0;
  16795. /* The size of a Mem5Link object must be a power of two. Verify that
  16796. ** this is case.
  16797. */
  16798. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  16799. nByte = sqlite3GlobalConfig.nHeap;
  16800. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  16801. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  16802. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  16803. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  16804. mem5.szAtom = (1<<nMinLog);
  16805. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  16806. mem5.szAtom = mem5.szAtom << 1;
  16807. }
  16808. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  16809. mem5.zPool = zByte;
  16810. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  16811. for(ii=0; ii<=LOGMAX; ii++){
  16812. mem5.aiFreelist[ii] = -1;
  16813. }
  16814. iOffset = 0;
  16815. for(ii=LOGMAX; ii>=0; ii--){
  16816. int nAlloc = (1<<ii);
  16817. if( (iOffset+nAlloc)<=mem5.nBlock ){
  16818. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  16819. memsys5Link(iOffset, ii);
  16820. iOffset += nAlloc;
  16821. }
  16822. assert((iOffset+nAlloc)>mem5.nBlock);
  16823. }
  16824. /* If a mutex is required for normal operation, allocate one */
  16825. if( sqlite3GlobalConfig.bMemstat==0 ){
  16826. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16827. }
  16828. return SQLITE_OK;
  16829. }
  16830. /*
  16831. ** Deinitialize this module.
  16832. */
  16833. static void memsys5Shutdown(void *NotUsed){
  16834. UNUSED_PARAMETER(NotUsed);
  16835. mem5.mutex = 0;
  16836. return;
  16837. }
  16838. #ifdef SQLITE_TEST
  16839. /*
  16840. ** Open the file indicated and write a log of all unfreed memory
  16841. ** allocations into that log.
  16842. */
  16843. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  16844. FILE *out;
  16845. int i, j, n;
  16846. int nMinLog;
  16847. if( zFilename==0 || zFilename[0]==0 ){
  16848. out = stdout;
  16849. }else{
  16850. out = fopen(zFilename, "w");
  16851. if( out==0 ){
  16852. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16853. zFilename);
  16854. return;
  16855. }
  16856. }
  16857. memsys5Enter();
  16858. nMinLog = memsys5Log(mem5.szAtom);
  16859. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  16860. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  16861. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  16862. }
  16863. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  16864. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  16865. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  16866. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  16867. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  16868. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  16869. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  16870. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  16871. memsys5Leave();
  16872. if( out==stdout ){
  16873. fflush(stdout);
  16874. }else{
  16875. fclose(out);
  16876. }
  16877. }
  16878. #endif
  16879. /*
  16880. ** This routine is the only routine in this file with external
  16881. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  16882. ** struct populated with the memsys5 methods.
  16883. */
  16884. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  16885. static const sqlite3_mem_methods memsys5Methods = {
  16886. memsys5Malloc,
  16887. memsys5Free,
  16888. memsys5Realloc,
  16889. memsys5Size,
  16890. memsys5Roundup,
  16891. memsys5Init,
  16892. memsys5Shutdown,
  16893. 0
  16894. };
  16895. return &memsys5Methods;
  16896. }
  16897. #endif /* SQLITE_ENABLE_MEMSYS5 */
  16898. /************** End of mem5.c ************************************************/
  16899. /************** Begin file mutex.c *******************************************/
  16900. /*
  16901. ** 2007 August 14
  16902. **
  16903. ** The author disclaims copyright to this source code. In place of
  16904. ** a legal notice, here is a blessing:
  16905. **
  16906. ** May you do good and not evil.
  16907. ** May you find forgiveness for yourself and forgive others.
  16908. ** May you share freely, never taking more than you give.
  16909. **
  16910. *************************************************************************
  16911. ** This file contains the C functions that implement mutexes.
  16912. **
  16913. ** This file contains code that is common across all mutex implementations.
  16914. */
  16915. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  16916. /*
  16917. ** For debugging purposes, record when the mutex subsystem is initialized
  16918. ** and uninitialized so that we can assert() if there is an attempt to
  16919. ** allocate a mutex while the system is uninitialized.
  16920. */
  16921. static SQLITE_WSD int mutexIsInit = 0;
  16922. #endif /* SQLITE_DEBUG */
  16923. #ifndef SQLITE_MUTEX_OMIT
  16924. /*
  16925. ** Initialize the mutex system.
  16926. */
  16927. SQLITE_PRIVATE int sqlite3MutexInit(void){
  16928. int rc = SQLITE_OK;
  16929. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  16930. /* If the xMutexAlloc method has not been set, then the user did not
  16931. ** install a mutex implementation via sqlite3_config() prior to
  16932. ** sqlite3_initialize() being called. This block copies pointers to
  16933. ** the default implementation into the sqlite3GlobalConfig structure.
  16934. */
  16935. sqlite3_mutex_methods const *pFrom;
  16936. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  16937. if( sqlite3GlobalConfig.bCoreMutex ){
  16938. pFrom = sqlite3DefaultMutex();
  16939. }else{
  16940. pFrom = sqlite3NoopMutex();
  16941. }
  16942. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  16943. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  16944. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  16945. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  16946. }
  16947. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  16948. #ifdef SQLITE_DEBUG
  16949. GLOBAL(int, mutexIsInit) = 1;
  16950. #endif
  16951. return rc;
  16952. }
  16953. /*
  16954. ** Shutdown the mutex system. This call frees resources allocated by
  16955. ** sqlite3MutexInit().
  16956. */
  16957. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  16958. int rc = SQLITE_OK;
  16959. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  16960. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  16961. }
  16962. #ifdef SQLITE_DEBUG
  16963. GLOBAL(int, mutexIsInit) = 0;
  16964. #endif
  16965. return rc;
  16966. }
  16967. /*
  16968. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  16969. */
  16970. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  16971. #ifndef SQLITE_OMIT_AUTOINIT
  16972. if( sqlite3_initialize() ) return 0;
  16973. #endif
  16974. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16975. }
  16976. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  16977. if( !sqlite3GlobalConfig.bCoreMutex ){
  16978. return 0;
  16979. }
  16980. assert( GLOBAL(int, mutexIsInit) );
  16981. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  16982. }
  16983. /*
  16984. ** Free a dynamic mutex.
  16985. */
  16986. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  16987. if( p ){
  16988. sqlite3GlobalConfig.mutex.xMutexFree(p);
  16989. }
  16990. }
  16991. /*
  16992. ** Obtain the mutex p. If some other thread already has the mutex, block
  16993. ** until it can be obtained.
  16994. */
  16995. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  16996. if( p ){
  16997. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  16998. }
  16999. }
  17000. /*
  17001. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  17002. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  17003. */
  17004. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  17005. int rc = SQLITE_OK;
  17006. if( p ){
  17007. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  17008. }
  17009. return rc;
  17010. }
  17011. /*
  17012. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  17013. ** entered by the same thread. The behavior is undefined if the mutex
  17014. ** is not currently entered. If a NULL pointer is passed as an argument
  17015. ** this function is a no-op.
  17016. */
  17017. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  17018. if( p ){
  17019. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  17020. }
  17021. }
  17022. #ifndef NDEBUG
  17023. /*
  17024. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17025. ** intended for use inside assert() statements.
  17026. */
  17027. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17028. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17029. }
  17030. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17031. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17032. }
  17033. #endif
  17034. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17035. /************** End of mutex.c ***********************************************/
  17036. /************** Begin file mutex_noop.c **************************************/
  17037. /*
  17038. ** 2008 October 07
  17039. **
  17040. ** The author disclaims copyright to this source code. In place of
  17041. ** a legal notice, here is a blessing:
  17042. **
  17043. ** May you do good and not evil.
  17044. ** May you find forgiveness for yourself and forgive others.
  17045. ** May you share freely, never taking more than you give.
  17046. **
  17047. *************************************************************************
  17048. ** This file contains the C functions that implement mutexes.
  17049. **
  17050. ** This implementation in this file does not provide any mutual
  17051. ** exclusion and is thus suitable for use only in applications
  17052. ** that use SQLite in a single thread. The routines defined
  17053. ** here are place-holders. Applications can substitute working
  17054. ** mutex routines at start-time using the
  17055. **
  17056. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17057. **
  17058. ** interface.
  17059. **
  17060. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17061. ** that does error checking on mutexes to make sure they are being
  17062. ** called correctly.
  17063. */
  17064. #ifndef SQLITE_MUTEX_OMIT
  17065. #ifndef SQLITE_DEBUG
  17066. /*
  17067. ** Stub routines for all mutex methods.
  17068. **
  17069. ** This routines provide no mutual exclusion or error checking.
  17070. */
  17071. static int noopMutexInit(void){ return SQLITE_OK; }
  17072. static int noopMutexEnd(void){ return SQLITE_OK; }
  17073. static sqlite3_mutex *noopMutexAlloc(int id){
  17074. UNUSED_PARAMETER(id);
  17075. return (sqlite3_mutex*)8;
  17076. }
  17077. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17078. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17079. static int noopMutexTry(sqlite3_mutex *p){
  17080. UNUSED_PARAMETER(p);
  17081. return SQLITE_OK;
  17082. }
  17083. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17084. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17085. static const sqlite3_mutex_methods sMutex = {
  17086. noopMutexInit,
  17087. noopMutexEnd,
  17088. noopMutexAlloc,
  17089. noopMutexFree,
  17090. noopMutexEnter,
  17091. noopMutexTry,
  17092. noopMutexLeave,
  17093. 0,
  17094. 0,
  17095. };
  17096. return &sMutex;
  17097. }
  17098. #endif /* !SQLITE_DEBUG */
  17099. #ifdef SQLITE_DEBUG
  17100. /*
  17101. ** In this implementation, error checking is provided for testing
  17102. ** and debugging purposes. The mutexes still do not provide any
  17103. ** mutual exclusion.
  17104. */
  17105. /*
  17106. ** The mutex object
  17107. */
  17108. typedef struct sqlite3_debug_mutex {
  17109. int id; /* The mutex type */
  17110. int cnt; /* Number of entries without a matching leave */
  17111. } sqlite3_debug_mutex;
  17112. /*
  17113. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17114. ** intended for use inside assert() statements.
  17115. */
  17116. static int debugMutexHeld(sqlite3_mutex *pX){
  17117. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17118. return p==0 || p->cnt>0;
  17119. }
  17120. static int debugMutexNotheld(sqlite3_mutex *pX){
  17121. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17122. return p==0 || p->cnt==0;
  17123. }
  17124. /*
  17125. ** Initialize and deinitialize the mutex subsystem.
  17126. */
  17127. static int debugMutexInit(void){ return SQLITE_OK; }
  17128. static int debugMutexEnd(void){ return SQLITE_OK; }
  17129. /*
  17130. ** The sqlite3_mutex_alloc() routine allocates a new
  17131. ** mutex and returns a pointer to it. If it returns NULL
  17132. ** that means that a mutex could not be allocated.
  17133. */
  17134. static sqlite3_mutex *debugMutexAlloc(int id){
  17135. static sqlite3_debug_mutex aStatic[6];
  17136. sqlite3_debug_mutex *pNew = 0;
  17137. switch( id ){
  17138. case SQLITE_MUTEX_FAST:
  17139. case SQLITE_MUTEX_RECURSIVE: {
  17140. pNew = sqlite3Malloc(sizeof(*pNew));
  17141. if( pNew ){
  17142. pNew->id = id;
  17143. pNew->cnt = 0;
  17144. }
  17145. break;
  17146. }
  17147. default: {
  17148. assert( id-2 >= 0 );
  17149. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17150. pNew = &aStatic[id-2];
  17151. pNew->id = id;
  17152. break;
  17153. }
  17154. }
  17155. return (sqlite3_mutex*)pNew;
  17156. }
  17157. /*
  17158. ** This routine deallocates a previously allocated mutex.
  17159. */
  17160. static void debugMutexFree(sqlite3_mutex *pX){
  17161. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17162. assert( p->cnt==0 );
  17163. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17164. sqlite3_free(p);
  17165. }
  17166. /*
  17167. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17168. ** to enter a mutex. If another thread is already within the mutex,
  17169. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17170. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17171. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17172. ** be entered multiple times by the same thread. In such cases the,
  17173. ** mutex must be exited an equal number of times before another thread
  17174. ** can enter. If the same thread tries to enter any other kind of mutex
  17175. ** more than once, the behavior is undefined.
  17176. */
  17177. static void debugMutexEnter(sqlite3_mutex *pX){
  17178. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17179. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17180. p->cnt++;
  17181. }
  17182. static int debugMutexTry(sqlite3_mutex *pX){
  17183. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17184. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17185. p->cnt++;
  17186. return SQLITE_OK;
  17187. }
  17188. /*
  17189. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17190. ** previously entered by the same thread. The behavior
  17191. ** is undefined if the mutex is not currently entered or
  17192. ** is not currently allocated. SQLite will never do either.
  17193. */
  17194. static void debugMutexLeave(sqlite3_mutex *pX){
  17195. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17196. assert( debugMutexHeld(pX) );
  17197. p->cnt--;
  17198. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17199. }
  17200. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17201. static const sqlite3_mutex_methods sMutex = {
  17202. debugMutexInit,
  17203. debugMutexEnd,
  17204. debugMutexAlloc,
  17205. debugMutexFree,
  17206. debugMutexEnter,
  17207. debugMutexTry,
  17208. debugMutexLeave,
  17209. debugMutexHeld,
  17210. debugMutexNotheld
  17211. };
  17212. return &sMutex;
  17213. }
  17214. #endif /* SQLITE_DEBUG */
  17215. /*
  17216. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17217. ** is used regardless of the run-time threadsafety setting.
  17218. */
  17219. #ifdef SQLITE_MUTEX_NOOP
  17220. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17221. return sqlite3NoopMutex();
  17222. }
  17223. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17224. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17225. /************** End of mutex_noop.c ******************************************/
  17226. /************** Begin file mutex_unix.c **************************************/
  17227. /*
  17228. ** 2007 August 28
  17229. **
  17230. ** The author disclaims copyright to this source code. In place of
  17231. ** a legal notice, here is a blessing:
  17232. **
  17233. ** May you do good and not evil.
  17234. ** May you find forgiveness for yourself and forgive others.
  17235. ** May you share freely, never taking more than you give.
  17236. **
  17237. *************************************************************************
  17238. ** This file contains the C functions that implement mutexes for pthreads
  17239. */
  17240. /*
  17241. ** The code in this file is only used if we are compiling threadsafe
  17242. ** under unix with pthreads.
  17243. **
  17244. ** Note that this implementation requires a version of pthreads that
  17245. ** supports recursive mutexes.
  17246. */
  17247. #ifdef SQLITE_MUTEX_PTHREADS
  17248. #include <pthread.h>
  17249. /*
  17250. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17251. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17252. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17253. */
  17254. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17255. # define SQLITE_MUTEX_NREF 1
  17256. #else
  17257. # define SQLITE_MUTEX_NREF 0
  17258. #endif
  17259. /*
  17260. ** Each recursive mutex is an instance of the following structure.
  17261. */
  17262. struct sqlite3_mutex {
  17263. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17264. #if SQLITE_MUTEX_NREF
  17265. int id; /* Mutex type */
  17266. volatile int nRef; /* Number of entrances */
  17267. volatile pthread_t owner; /* Thread that is within this mutex */
  17268. int trace; /* True to trace changes */
  17269. #endif
  17270. };
  17271. #if SQLITE_MUTEX_NREF
  17272. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17273. #else
  17274. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  17275. #endif
  17276. /*
  17277. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17278. ** intended for use only inside assert() statements. On some platforms,
  17279. ** there might be race conditions that can cause these routines to
  17280. ** deliver incorrect results. In particular, if pthread_equal() is
  17281. ** not an atomic operation, then these routines might delivery
  17282. ** incorrect results. On most platforms, pthread_equal() is a
  17283. ** comparison of two integers and is therefore atomic. But we are
  17284. ** told that HPUX is not such a platform. If so, then these routines
  17285. ** will not always work correctly on HPUX.
  17286. **
  17287. ** On those platforms where pthread_equal() is not atomic, SQLite
  17288. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17289. ** make sure no assert() statements are evaluated and hence these
  17290. ** routines are never called.
  17291. */
  17292. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17293. static int pthreadMutexHeld(sqlite3_mutex *p){
  17294. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  17295. }
  17296. static int pthreadMutexNotheld(sqlite3_mutex *p){
  17297. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  17298. }
  17299. #endif
  17300. /*
  17301. ** Initialize and deinitialize the mutex subsystem.
  17302. */
  17303. static int pthreadMutexInit(void){ return SQLITE_OK; }
  17304. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  17305. /*
  17306. ** The sqlite3_mutex_alloc() routine allocates a new
  17307. ** mutex and returns a pointer to it. If it returns NULL
  17308. ** that means that a mutex could not be allocated. SQLite
  17309. ** will unwind its stack and return an error. The argument
  17310. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17311. **
  17312. ** <ul>
  17313. ** <li> SQLITE_MUTEX_FAST
  17314. ** <li> SQLITE_MUTEX_RECURSIVE
  17315. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17316. ** <li> SQLITE_MUTEX_STATIC_MEM
  17317. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17318. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17319. ** <li> SQLITE_MUTEX_STATIC_LRU
  17320. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17321. ** </ul>
  17322. **
  17323. ** The first two constants cause sqlite3_mutex_alloc() to create
  17324. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17325. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17326. ** The mutex implementation does not need to make a distinction
  17327. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17328. ** not want to. But SQLite will only request a recursive mutex in
  17329. ** cases where it really needs one. If a faster non-recursive mutex
  17330. ** implementation is available on the host platform, the mutex subsystem
  17331. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17332. **
  17333. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17334. ** a pointer to a static preexisting mutex. Six static mutexes are
  17335. ** used by the current version of SQLite. Future versions of SQLite
  17336. ** may add additional static mutexes. Static mutexes are for internal
  17337. ** use by SQLite only. Applications that use SQLite mutexes should
  17338. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17339. ** SQLITE_MUTEX_RECURSIVE.
  17340. **
  17341. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17342. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17343. ** returns a different mutex on every call. But for the static
  17344. ** mutex types, the same mutex is returned on every call that has
  17345. ** the same type number.
  17346. */
  17347. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  17348. static sqlite3_mutex staticMutexes[] = {
  17349. SQLITE3_MUTEX_INITIALIZER,
  17350. SQLITE3_MUTEX_INITIALIZER,
  17351. SQLITE3_MUTEX_INITIALIZER,
  17352. SQLITE3_MUTEX_INITIALIZER,
  17353. SQLITE3_MUTEX_INITIALIZER,
  17354. SQLITE3_MUTEX_INITIALIZER
  17355. };
  17356. sqlite3_mutex *p;
  17357. switch( iType ){
  17358. case SQLITE_MUTEX_RECURSIVE: {
  17359. p = sqlite3MallocZero( sizeof(*p) );
  17360. if( p ){
  17361. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17362. /* If recursive mutexes are not available, we will have to
  17363. ** build our own. See below. */
  17364. pthread_mutex_init(&p->mutex, 0);
  17365. #else
  17366. /* Use a recursive mutex if it is available */
  17367. pthread_mutexattr_t recursiveAttr;
  17368. pthread_mutexattr_init(&recursiveAttr);
  17369. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  17370. pthread_mutex_init(&p->mutex, &recursiveAttr);
  17371. pthread_mutexattr_destroy(&recursiveAttr);
  17372. #endif
  17373. #if SQLITE_MUTEX_NREF
  17374. p->id = iType;
  17375. #endif
  17376. }
  17377. break;
  17378. }
  17379. case SQLITE_MUTEX_FAST: {
  17380. p = sqlite3MallocZero( sizeof(*p) );
  17381. if( p ){
  17382. #if SQLITE_MUTEX_NREF
  17383. p->id = iType;
  17384. #endif
  17385. pthread_mutex_init(&p->mutex, 0);
  17386. }
  17387. break;
  17388. }
  17389. default: {
  17390. assert( iType-2 >= 0 );
  17391. assert( iType-2 < ArraySize(staticMutexes) );
  17392. p = &staticMutexes[iType-2];
  17393. #if SQLITE_MUTEX_NREF
  17394. p->id = iType;
  17395. #endif
  17396. break;
  17397. }
  17398. }
  17399. return p;
  17400. }
  17401. /*
  17402. ** This routine deallocates a previously
  17403. ** allocated mutex. SQLite is careful to deallocate every
  17404. ** mutex that it allocates.
  17405. */
  17406. static void pthreadMutexFree(sqlite3_mutex *p){
  17407. assert( p->nRef==0 );
  17408. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17409. pthread_mutex_destroy(&p->mutex);
  17410. sqlite3_free(p);
  17411. }
  17412. /*
  17413. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17414. ** to enter a mutex. If another thread is already within the mutex,
  17415. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17416. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17417. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17418. ** be entered multiple times by the same thread. In such cases the,
  17419. ** mutex must be exited an equal number of times before another thread
  17420. ** can enter. If the same thread tries to enter any other kind of mutex
  17421. ** more than once, the behavior is undefined.
  17422. */
  17423. static void pthreadMutexEnter(sqlite3_mutex *p){
  17424. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17425. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17426. /* If recursive mutexes are not available, then we have to grow
  17427. ** our own. This implementation assumes that pthread_equal()
  17428. ** is atomic - that it cannot be deceived into thinking self
  17429. ** and p->owner are equal if p->owner changes between two values
  17430. ** that are not equal to self while the comparison is taking place.
  17431. ** This implementation also assumes a coherent cache - that
  17432. ** separate processes cannot read different values from the same
  17433. ** address at the same time. If either of these two conditions
  17434. ** are not met, then the mutexes will fail and problems will result.
  17435. */
  17436. {
  17437. pthread_t self = pthread_self();
  17438. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17439. p->nRef++;
  17440. }else{
  17441. pthread_mutex_lock(&p->mutex);
  17442. assert( p->nRef==0 );
  17443. p->owner = self;
  17444. p->nRef = 1;
  17445. }
  17446. }
  17447. #else
  17448. /* Use the built-in recursive mutexes if they are available.
  17449. */
  17450. pthread_mutex_lock(&p->mutex);
  17451. #if SQLITE_MUTEX_NREF
  17452. assert( p->nRef>0 || p->owner==0 );
  17453. p->owner = pthread_self();
  17454. p->nRef++;
  17455. #endif
  17456. #endif
  17457. #ifdef SQLITE_DEBUG
  17458. if( p->trace ){
  17459. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17460. }
  17461. #endif
  17462. }
  17463. static int pthreadMutexTry(sqlite3_mutex *p){
  17464. int rc;
  17465. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  17466. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17467. /* If recursive mutexes are not available, then we have to grow
  17468. ** our own. This implementation assumes that pthread_equal()
  17469. ** is atomic - that it cannot be deceived into thinking self
  17470. ** and p->owner are equal if p->owner changes between two values
  17471. ** that are not equal to self while the comparison is taking place.
  17472. ** This implementation also assumes a coherent cache - that
  17473. ** separate processes cannot read different values from the same
  17474. ** address at the same time. If either of these two conditions
  17475. ** are not met, then the mutexes will fail and problems will result.
  17476. */
  17477. {
  17478. pthread_t self = pthread_self();
  17479. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  17480. p->nRef++;
  17481. rc = SQLITE_OK;
  17482. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  17483. assert( p->nRef==0 );
  17484. p->owner = self;
  17485. p->nRef = 1;
  17486. rc = SQLITE_OK;
  17487. }else{
  17488. rc = SQLITE_BUSY;
  17489. }
  17490. }
  17491. #else
  17492. /* Use the built-in recursive mutexes if they are available.
  17493. */
  17494. if( pthread_mutex_trylock(&p->mutex)==0 ){
  17495. #if SQLITE_MUTEX_NREF
  17496. p->owner = pthread_self();
  17497. p->nRef++;
  17498. #endif
  17499. rc = SQLITE_OK;
  17500. }else{
  17501. rc = SQLITE_BUSY;
  17502. }
  17503. #endif
  17504. #ifdef SQLITE_DEBUG
  17505. if( rc==SQLITE_OK && p->trace ){
  17506. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17507. }
  17508. #endif
  17509. return rc;
  17510. }
  17511. /*
  17512. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17513. ** previously entered by the same thread. The behavior
  17514. ** is undefined if the mutex is not currently entered or
  17515. ** is not currently allocated. SQLite will never do either.
  17516. */
  17517. static void pthreadMutexLeave(sqlite3_mutex *p){
  17518. assert( pthreadMutexHeld(p) );
  17519. #if SQLITE_MUTEX_NREF
  17520. p->nRef--;
  17521. if( p->nRef==0 ) p->owner = 0;
  17522. #endif
  17523. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17524. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  17525. if( p->nRef==0 ){
  17526. pthread_mutex_unlock(&p->mutex);
  17527. }
  17528. #else
  17529. pthread_mutex_unlock(&p->mutex);
  17530. #endif
  17531. #ifdef SQLITE_DEBUG
  17532. if( p->trace ){
  17533. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17534. }
  17535. #endif
  17536. }
  17537. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17538. static const sqlite3_mutex_methods sMutex = {
  17539. pthreadMutexInit,
  17540. pthreadMutexEnd,
  17541. pthreadMutexAlloc,
  17542. pthreadMutexFree,
  17543. pthreadMutexEnter,
  17544. pthreadMutexTry,
  17545. pthreadMutexLeave,
  17546. #ifdef SQLITE_DEBUG
  17547. pthreadMutexHeld,
  17548. pthreadMutexNotheld
  17549. #else
  17550. 0,
  17551. 0
  17552. #endif
  17553. };
  17554. return &sMutex;
  17555. }
  17556. #endif /* SQLITE_MUTEX_PTHREADS */
  17557. /************** End of mutex_unix.c ******************************************/
  17558. /************** Begin file mutex_w32.c ***************************************/
  17559. /*
  17560. ** 2007 August 14
  17561. **
  17562. ** The author disclaims copyright to this source code. In place of
  17563. ** a legal notice, here is a blessing:
  17564. **
  17565. ** May you do good and not evil.
  17566. ** May you find forgiveness for yourself and forgive others.
  17567. ** May you share freely, never taking more than you give.
  17568. **
  17569. *************************************************************************
  17570. ** This file contains the C functions that implement mutexes for win32
  17571. */
  17572. /*
  17573. ** The code in this file is only used if we are compiling multithreaded
  17574. ** on a win32 system.
  17575. */
  17576. #ifdef SQLITE_MUTEX_W32
  17577. /*
  17578. ** Each recursive mutex is an instance of the following structure.
  17579. */
  17580. struct sqlite3_mutex {
  17581. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  17582. int id; /* Mutex type */
  17583. #ifdef SQLITE_DEBUG
  17584. volatile int nRef; /* Number of enterances */
  17585. volatile DWORD owner; /* Thread holding this mutex */
  17586. int trace; /* True to trace changes */
  17587. #endif
  17588. };
  17589. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  17590. #ifdef SQLITE_DEBUG
  17591. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
  17592. #else
  17593. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  17594. #endif
  17595. /*
  17596. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  17597. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  17598. **
  17599. ** Here is an interesting observation: Win95, Win98, and WinME lack
  17600. ** the LockFileEx() API. But we can still statically link against that
  17601. ** API as long as we don't call it win running Win95/98/ME. A call to
  17602. ** this routine is used to determine if the host is Win95/98/ME or
  17603. ** WinNT/2K/XP so that we will know whether or not we can safely call
  17604. ** the LockFileEx() API.
  17605. **
  17606. ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
  17607. ** which is only available if your application was compiled with
  17608. ** _WIN32_WINNT defined to a value >= 0x0400. Currently, the only
  17609. ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef
  17610. ** this out as well.
  17611. */
  17612. #if 0
  17613. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  17614. # define mutexIsNT() (1)
  17615. #else
  17616. static int mutexIsNT(void){
  17617. static int osType = 0;
  17618. if( osType==0 ){
  17619. OSVERSIONINFO sInfo;
  17620. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  17621. GetVersionEx(&sInfo);
  17622. osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  17623. }
  17624. return osType==2;
  17625. }
  17626. #endif /* SQLITE_OS_WINCE || SQLITE_OS_WINRT */
  17627. #endif
  17628. #ifdef SQLITE_DEBUG
  17629. /*
  17630. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17631. ** intended for use only inside assert() statements.
  17632. */
  17633. static int winMutexHeld(sqlite3_mutex *p){
  17634. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  17635. }
  17636. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  17637. return p->nRef==0 || p->owner!=tid;
  17638. }
  17639. static int winMutexNotheld(sqlite3_mutex *p){
  17640. DWORD tid = GetCurrentThreadId();
  17641. return winMutexNotheld2(p, tid);
  17642. }
  17643. #endif
  17644. /*
  17645. ** Initialize and deinitialize the mutex subsystem.
  17646. */
  17647. static sqlite3_mutex winMutex_staticMutexes[6] = {
  17648. SQLITE3_MUTEX_INITIALIZER,
  17649. SQLITE3_MUTEX_INITIALIZER,
  17650. SQLITE3_MUTEX_INITIALIZER,
  17651. SQLITE3_MUTEX_INITIALIZER,
  17652. SQLITE3_MUTEX_INITIALIZER,
  17653. SQLITE3_MUTEX_INITIALIZER
  17654. };
  17655. static int winMutex_isInit = 0;
  17656. /* As winMutexInit() and winMutexEnd() are called as part
  17657. ** of the sqlite3_initialize and sqlite3_shutdown()
  17658. ** processing, the "interlocked" magic is probably not
  17659. ** strictly necessary.
  17660. */
  17661. static LONG winMutex_lock = 0;
  17662. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  17663. static int winMutexInit(void){
  17664. /* The first to increment to 1 does actual initialization */
  17665. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  17666. int i;
  17667. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17668. #if SQLITE_OS_WINRT
  17669. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  17670. #else
  17671. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  17672. #endif
  17673. }
  17674. winMutex_isInit = 1;
  17675. }else{
  17676. /* Someone else is in the process of initing the static mutexes */
  17677. while( !winMutex_isInit ){
  17678. sqlite3_win32_sleep(1);
  17679. }
  17680. }
  17681. return SQLITE_OK;
  17682. }
  17683. static int winMutexEnd(void){
  17684. /* The first to decrement to 0 does actual shutdown
  17685. ** (which should be the last to shutdown.) */
  17686. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  17687. if( winMutex_isInit==1 ){
  17688. int i;
  17689. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  17690. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  17691. }
  17692. winMutex_isInit = 0;
  17693. }
  17694. }
  17695. return SQLITE_OK;
  17696. }
  17697. /*
  17698. ** The sqlite3_mutex_alloc() routine allocates a new
  17699. ** mutex and returns a pointer to it. If it returns NULL
  17700. ** that means that a mutex could not be allocated. SQLite
  17701. ** will unwind its stack and return an error. The argument
  17702. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17703. **
  17704. ** <ul>
  17705. ** <li> SQLITE_MUTEX_FAST
  17706. ** <li> SQLITE_MUTEX_RECURSIVE
  17707. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17708. ** <li> SQLITE_MUTEX_STATIC_MEM
  17709. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17710. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17711. ** <li> SQLITE_MUTEX_STATIC_LRU
  17712. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17713. ** </ul>
  17714. **
  17715. ** The first two constants cause sqlite3_mutex_alloc() to create
  17716. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17717. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17718. ** The mutex implementation does not need to make a distinction
  17719. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17720. ** not want to. But SQLite will only request a recursive mutex in
  17721. ** cases where it really needs one. If a faster non-recursive mutex
  17722. ** implementation is available on the host platform, the mutex subsystem
  17723. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17724. **
  17725. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17726. ** a pointer to a static preexisting mutex. Six static mutexes are
  17727. ** used by the current version of SQLite. Future versions of SQLite
  17728. ** may add additional static mutexes. Static mutexes are for internal
  17729. ** use by SQLite only. Applications that use SQLite mutexes should
  17730. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17731. ** SQLITE_MUTEX_RECURSIVE.
  17732. **
  17733. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  17734. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  17735. ** returns a different mutex on every call. But for the static
  17736. ** mutex types, the same mutex is returned on every call that has
  17737. ** the same type number.
  17738. */
  17739. static sqlite3_mutex *winMutexAlloc(int iType){
  17740. sqlite3_mutex *p;
  17741. switch( iType ){
  17742. case SQLITE_MUTEX_FAST:
  17743. case SQLITE_MUTEX_RECURSIVE: {
  17744. p = sqlite3MallocZero( sizeof(*p) );
  17745. if( p ){
  17746. #ifdef SQLITE_DEBUG
  17747. p->id = iType;
  17748. #endif
  17749. #if SQLITE_OS_WINRT
  17750. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  17751. #else
  17752. InitializeCriticalSection(&p->mutex);
  17753. #endif
  17754. }
  17755. break;
  17756. }
  17757. default: {
  17758. assert( winMutex_isInit==1 );
  17759. assert( iType-2 >= 0 );
  17760. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  17761. p = &winMutex_staticMutexes[iType-2];
  17762. #ifdef SQLITE_DEBUG
  17763. p->id = iType;
  17764. #endif
  17765. break;
  17766. }
  17767. }
  17768. return p;
  17769. }
  17770. /*
  17771. ** This routine deallocates a previously
  17772. ** allocated mutex. SQLite is careful to deallocate every
  17773. ** mutex that it allocates.
  17774. */
  17775. static void winMutexFree(sqlite3_mutex *p){
  17776. assert( p );
  17777. assert( p->nRef==0 && p->owner==0 );
  17778. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17779. DeleteCriticalSection(&p->mutex);
  17780. sqlite3_free(p);
  17781. }
  17782. /*
  17783. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17784. ** to enter a mutex. If another thread is already within the mutex,
  17785. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17786. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17787. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17788. ** be entered multiple times by the same thread. In such cases the,
  17789. ** mutex must be exited an equal number of times before another thread
  17790. ** can enter. If the same thread tries to enter any other kind of mutex
  17791. ** more than once, the behavior is undefined.
  17792. */
  17793. static void winMutexEnter(sqlite3_mutex *p){
  17794. #ifdef SQLITE_DEBUG
  17795. DWORD tid = GetCurrentThreadId();
  17796. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17797. #endif
  17798. EnterCriticalSection(&p->mutex);
  17799. #ifdef SQLITE_DEBUG
  17800. assert( p->nRef>0 || p->owner==0 );
  17801. p->owner = tid;
  17802. p->nRef++;
  17803. if( p->trace ){
  17804. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17805. }
  17806. #endif
  17807. }
  17808. static int winMutexTry(sqlite3_mutex *p){
  17809. #ifndef NDEBUG
  17810. DWORD tid = GetCurrentThreadId();
  17811. #endif
  17812. int rc = SQLITE_BUSY;
  17813. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  17814. /*
  17815. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  17816. ** is used it is merely an optimization. So it is OK for it to always
  17817. ** fail.
  17818. **
  17819. ** The TryEnterCriticalSection() interface is only available on WinNT.
  17820. ** And some windows compilers complain if you try to use it without
  17821. ** first doing some #defines that prevent SQLite from building on Win98.
  17822. ** For that reason, we will omit this optimization for now. See
  17823. ** ticket #2685.
  17824. */
  17825. #if 0
  17826. if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
  17827. p->owner = tid;
  17828. p->nRef++;
  17829. rc = SQLITE_OK;
  17830. }
  17831. #else
  17832. UNUSED_PARAMETER(p);
  17833. #endif
  17834. #ifdef SQLITE_DEBUG
  17835. if( rc==SQLITE_OK && p->trace ){
  17836. printf("try mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17837. }
  17838. #endif
  17839. return rc;
  17840. }
  17841. /*
  17842. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17843. ** previously entered by the same thread. The behavior
  17844. ** is undefined if the mutex is not currently entered or
  17845. ** is not currently allocated. SQLite will never do either.
  17846. */
  17847. static void winMutexLeave(sqlite3_mutex *p){
  17848. #ifndef NDEBUG
  17849. DWORD tid = GetCurrentThreadId();
  17850. assert( p->nRef>0 );
  17851. assert( p->owner==tid );
  17852. p->nRef--;
  17853. if( p->nRef==0 ) p->owner = 0;
  17854. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  17855. #endif
  17856. LeaveCriticalSection(&p->mutex);
  17857. #ifdef SQLITE_DEBUG
  17858. if( p->trace ){
  17859. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  17860. }
  17861. #endif
  17862. }
  17863. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17864. static const sqlite3_mutex_methods sMutex = {
  17865. winMutexInit,
  17866. winMutexEnd,
  17867. winMutexAlloc,
  17868. winMutexFree,
  17869. winMutexEnter,
  17870. winMutexTry,
  17871. winMutexLeave,
  17872. #ifdef SQLITE_DEBUG
  17873. winMutexHeld,
  17874. winMutexNotheld
  17875. #else
  17876. 0,
  17877. 0
  17878. #endif
  17879. };
  17880. return &sMutex;
  17881. }
  17882. #endif /* SQLITE_MUTEX_W32 */
  17883. /************** End of mutex_w32.c *******************************************/
  17884. /************** Begin file mutex_rtt.c ***************************************/
  17885. /*
  17886. ** 2007 August 28
  17887. **
  17888. ** The author disclaims copyright to this source code. In place of
  17889. ** a legal notice, here is a blessing:
  17890. **
  17891. ** May you do good and not evil.
  17892. ** May you find forgiveness for yourself and forgive others.
  17893. ** May you share freely, never taking more than you give.
  17894. **
  17895. *************************************************************************
  17896. ** This file contains the C functions that implement mutexes for rtthread
  17897. */
  17898. /*
  17899. ** The code in this file is only used if we are compiling threadsafe
  17900. ** under rt-thread with rt_mutex.
  17901. **
  17902. ** Note that this implementation requires a version of rt-thread that
  17903. ** supports recursive mutexes.
  17904. */
  17905. #ifdef SQLITE_MUTEX_RTT
  17906. /* #include <rtthread.h> */
  17907. /*
  17908. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17909. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17910. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17911. */
  17912. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17913. # define SQLITE_MUTEX_NREF 1
  17914. #else
  17915. # define SQLITE_MUTEX_NREF 0
  17916. #endif
  17917. /*
  17918. ** Each recursive mutex is an instance of the following structure.
  17919. */
  17920. struct sqlite3_mutex {
  17921. struct rt_mutex mutex; /* Mutex controlling the lock */
  17922. #if SQLITE_MUTEX_NREF
  17923. int id; /* Mutex type */
  17924. volatile int nRef; /* Number of entrances */
  17925. volatile rt_thread_t owner; /* Thread that is within this mutex */
  17926. int trace; /* True to trace changes */
  17927. #endif
  17928. };
  17929. #define RTT_MUTEX_INITIALIZER { 0 }
  17930. #if SQLITE_MUTEX_NREF
  17931. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER, 0, 0, (rt_thread_t)0, 0 }
  17932. #else
  17933. #define SQLITE3_MUTEX_INITIALIZER { RTT_MUTEX_INITIALIZER }
  17934. #endif
  17935. /*
  17936. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17937. ** intended for use only inside assert() statements. On some platforms,
  17938. ** there might be race conditions that can cause these routines to
  17939. ** deliver incorrect results. In particular, if rtt_equal() is
  17940. ** not an atomic operation, then these routines might delivery
  17941. ** incorrect results. On most platforms, rtt_equal() is a
  17942. ** comparison of two integers and is therefore atomic. But we are
  17943. ** told that HPUX is not such a platform. If so, then these routines
  17944. ** will not always work correctly on HPUX.
  17945. **
  17946. ** On those platforms where rtt_equal() is not atomic, SQLite
  17947. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  17948. ** make sure no assert() statements are evaluated and hence these
  17949. ** routines are never called.
  17950. */
  17951. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  17952. static int rttMutexHeld(sqlite3_mutex *p){
  17953. return (p->nRef != 0 && p->owner == rt_thread_self());
  17954. }
  17955. static int rttMutexNotheld(sqlite3_mutex *p){
  17956. return (p->nRef == 0 || p->owner != rt_thread_self());
  17957. }
  17958. #endif
  17959. /*
  17960. ** Initialize and deinitialize the mutex subsystem.
  17961. */
  17962. static int rttMutexInit(void){ return SQLITE_OK; }
  17963. static int rttMutexEnd(void){ return SQLITE_OK; }
  17964. /*
  17965. ** The sqlite3_mutex_alloc() routine allocates a new
  17966. ** mutex and returns a pointer to it. If it returns NULL
  17967. ** that means that a mutex could not be allocated. SQLite
  17968. ** will unwind its stack and return an error. The argument
  17969. ** to sqlite3_mutex_alloc() is one of these integer constants:
  17970. **
  17971. ** <ul>
  17972. ** <li> SQLITE_MUTEX_FAST
  17973. ** <li> SQLITE_MUTEX_RECURSIVE
  17974. ** <li> SQLITE_MUTEX_STATIC_MASTER
  17975. ** <li> SQLITE_MUTEX_STATIC_MEM
  17976. ** <li> SQLITE_MUTEX_STATIC_MEM2
  17977. ** <li> SQLITE_MUTEX_STATIC_PRNG
  17978. ** <li> SQLITE_MUTEX_STATIC_LRU
  17979. ** <li> SQLITE_MUTEX_STATIC_PMEM
  17980. ** </ul>
  17981. **
  17982. ** The first two constants cause sqlite3_mutex_alloc() to create
  17983. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  17984. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  17985. ** The mutex implementation does not need to make a distinction
  17986. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  17987. ** not want to. But SQLite will only request a recursive mutex in
  17988. ** cases where it really needs one. If a faster non-recursive mutex
  17989. ** implementation is available on the host platform, the mutex subsystem
  17990. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  17991. **
  17992. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  17993. ** a pointer to a static preexisting mutex. Six static mutexes are
  17994. ** used by the current version of SQLite. Future versions of SQLite
  17995. ** may add additional static mutexes. Static mutexes are for internal
  17996. ** use by SQLite only. Applications that use SQLite mutexes should
  17997. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  17998. ** SQLITE_MUTEX_RECURSIVE.
  17999. **
  18000. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18001. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18002. ** returns a different mutex on every call. But for the static
  18003. ** mutex types, the same mutex is returned on every call that has
  18004. ** the same type number.
  18005. */
  18006. static sqlite3_mutex *rttMutexAlloc(int iType){
  18007. static sqlite3_mutex staticMutexes[] = {
  18008. SQLITE3_MUTEX_INITIALIZER,
  18009. SQLITE3_MUTEX_INITIALIZER,
  18010. SQLITE3_MUTEX_INITIALIZER,
  18011. SQLITE3_MUTEX_INITIALIZER,
  18012. SQLITE3_MUTEX_INITIALIZER,
  18013. SQLITE3_MUTEX_INITIALIZER
  18014. };
  18015. sqlite3_mutex *p;
  18016. switch( iType ){
  18017. case SQLITE_MUTEX_RECURSIVE: {
  18018. p = sqlite3MallocZero( sizeof(*p) );
  18019. if( p ){
  18020. /* Use a recursive mutex if it is available */
  18021. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  18022. #if SQLITE_MUTEX_NREF
  18023. p->id = iType;
  18024. #endif
  18025. }
  18026. break;
  18027. }
  18028. case SQLITE_MUTEX_FAST: {
  18029. p = sqlite3MallocZero( sizeof(*p) );
  18030. if( p ){
  18031. #if SQLITE_MUTEX_NREF
  18032. p->id = iType;
  18033. #endif
  18034. rt_mutex_init(&p->mutex, "sqlmtx", RT_IPC_FLAG_PRIO);
  18035. }
  18036. break;
  18037. }
  18038. default: {
  18039. assert( iType-2 >= 0 );
  18040. assert( iType-2 < ArraySize(staticMutexes) );
  18041. p = &staticMutexes[iType-2];
  18042. #if SQLITE_MUTEX_NREF
  18043. p->id = iType;
  18044. #endif
  18045. break;
  18046. }
  18047. }
  18048. return p;
  18049. }
  18050. /*
  18051. ** This routine deallocates a previously
  18052. ** allocated mutex. SQLite is careful to deallocate every
  18053. ** mutex that it allocates.
  18054. */
  18055. static void rttMutexFree(sqlite3_mutex *p){
  18056. assert( p->nRef==0 );
  18057. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18058. rt_mutex_delete(&p->mutex);
  18059. sqlite3_free(p);
  18060. }
  18061. /*
  18062. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18063. ** to enter a mutex. If another thread is already within the mutex,
  18064. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18065. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18066. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18067. ** be entered multiple times by the same thread. In such cases the,
  18068. ** mutex must be exited an equal number of times before another thread
  18069. ** can enter. If the same thread tries to enter any other kind of mutex
  18070. ** more than once, the behavior is undefined.
  18071. */
  18072. static void rttMutexEnter(sqlite3_mutex *p){
  18073. assert( p->id==SQLITE_MUTEX_RECURSIVE || rttMutexNotheld(p) );
  18074. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18075. /* If recursive mutexes are not available, then we have to grow
  18076. ** our own. This implementation assumes that rtt_equal()
  18077. ** is atomic - that it cannot be deceived into thinking self
  18078. ** and p->owner are equal if p->owner changes between two values
  18079. ** that are not equal to self while the comparison is taking place.
  18080. ** This implementation also assumes a coherent cache - that
  18081. ** separate processes cannot read different values from the same
  18082. ** address at the same time. If either of these two conditions
  18083. ** are not met, then the mutexes will fail and problems will result.
  18084. */
  18085. {
  18086. rt_thread_t self = rt_thread_self();
  18087. if( p->nRef>0 && (p->owner == self) ){
  18088. p->nRef++;
  18089. }else{
  18090. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  18091. assert( p->nRef==0 );
  18092. p->owner = self;
  18093. p->nRef = 1;
  18094. }
  18095. }
  18096. #else
  18097. /* Use the built-in recursive mutexes if they are available.
  18098. */
  18099. rt_mutex_take(&p->mutex, RT_WAITING_FOREVER);
  18100. #if SQLITE_MUTEX_NREF
  18101. assert( p->nRef>0 || p->owner==0 );
  18102. p->owner = rt_thread_self();
  18103. p->nRef++;
  18104. #endif
  18105. #endif
  18106. #ifdef SQLITE_DEBUG
  18107. if( p->trace ){
  18108. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18109. }
  18110. #endif
  18111. }
  18112. static int rttMutexTry(sqlite3_mutex *p){
  18113. int rc;
  18114. assert( p->id==SQLITE_MUTEX_RECURSIVE || rttMutexNotheld(p) );
  18115. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18116. /* If recursive mutexes are not available, then we have to grow
  18117. ** our own. This implementation assumes that rtt_equal()
  18118. ** is atomic - that it cannot be deceived into thinking self
  18119. ** and p->owner are equal if p->owner changes between two values
  18120. ** that are not equal to self while the comparison is taking place.
  18121. ** This implementation also assumes a coherent cache - that
  18122. ** separate processes cannot read different values from the same
  18123. ** address at the same time. If either of these two conditions
  18124. ** are not met, then the mutexes will fail and problems will result.
  18125. */
  18126. {
  18127. rt_thread_t self = rt_thread_self();
  18128. if( p->nRef>0 && (p->owner == self) ){
  18129. p->nRef++;
  18130. rc = SQLITE_OK;
  18131. }else if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  18132. assert( p->nRef==0 );
  18133. p->owner = self;
  18134. p->nRef = 1;
  18135. rc = SQLITE_OK;
  18136. }else{
  18137. rc = SQLITE_BUSY;
  18138. }
  18139. }
  18140. #else
  18141. /* Use the built-in recursive mutexes if they are available.
  18142. */
  18143. if( rt_mutex_take(&p->mutex, RT_WAITING_NO)==RT_EOK ){
  18144. #if SQLITE_MUTEX_NREF
  18145. p->owner = rt_thread_self();
  18146. p->nRef++;
  18147. #endif
  18148. rc = SQLITE_OK;
  18149. }else{
  18150. rc = SQLITE_BUSY;
  18151. }
  18152. #endif
  18153. #ifdef SQLITE_DEBUG
  18154. if( rc==SQLITE_OK && p->trace ){
  18155. rt_kprintf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18156. }
  18157. #endif
  18158. return rc;
  18159. }
  18160. /*
  18161. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18162. ** previously entered by the same thread. The behavior
  18163. ** is undefined if the mutex is not currently entered or
  18164. ** is not currently allocated. SQLite will never do either.
  18165. */
  18166. static void rttMutexLeave(sqlite3_mutex *p){
  18167. assert( rttMutexHeld(p) );
  18168. #if SQLITE_MUTEX_NREF
  18169. p->nRef--;
  18170. if( p->nRef==0 ) p->owner = 0;
  18171. #endif
  18172. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18173. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18174. if( p->nRef==0 ){
  18175. rt_mutex_release(&p->mutex);
  18176. }
  18177. #else
  18178. rt_mutex_release(&p->mutex);
  18179. #endif
  18180. #ifdef SQLITE_DEBUG
  18181. if( p->trace ){
  18182. rt_kprintf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18183. }
  18184. #endif
  18185. }
  18186. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18187. static const sqlite3_mutex_methods sMutex = {
  18188. rttMutexInit,
  18189. rttMutexEnd,
  18190. rttMutexAlloc,
  18191. rttMutexFree,
  18192. rttMutexEnter,
  18193. rttMutexTry,
  18194. rttMutexLeave,
  18195. #ifdef SQLITE_DEBUG
  18196. rttMutexHeld,
  18197. rttMutexNotheld
  18198. #else
  18199. 0,
  18200. 0
  18201. #endif
  18202. };
  18203. return &sMutex;
  18204. }
  18205. #endif /* SQLITE_MUTEX_RTT */
  18206. /************** End of mutex_rtt.c *******************************************/
  18207. /************** Begin file malloc.c ******************************************/
  18208. /*
  18209. ** 2001 September 15
  18210. **
  18211. ** The author disclaims copyright to this source code. In place of
  18212. ** a legal notice, here is a blessing:
  18213. **
  18214. ** May you do good and not evil.
  18215. ** May you find forgiveness for yourself and forgive others.
  18216. ** May you share freely, never taking more than you give.
  18217. **
  18218. *************************************************************************
  18219. **
  18220. ** Memory allocation functions used throughout sqlite.
  18221. */
  18222. /* #include <stdarg.h> */
  18223. /*
  18224. ** Attempt to release up to n bytes of non-essential memory currently
  18225. ** held by SQLite. An example of non-essential memory is memory used to
  18226. ** cache database pages that are not currently in use.
  18227. */
  18228. SQLITE_API int sqlite3_release_memory(int n){
  18229. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18230. return sqlite3PcacheReleaseMemory(n);
  18231. #else
  18232. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  18233. ** is a no-op returning zero if SQLite is not compiled with
  18234. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  18235. UNUSED_PARAMETER(n);
  18236. return 0;
  18237. #endif
  18238. }
  18239. /*
  18240. ** An instance of the following object records the location of
  18241. ** each unused scratch buffer.
  18242. */
  18243. typedef struct ScratchFreeslot {
  18244. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  18245. } ScratchFreeslot;
  18246. /*
  18247. ** State information local to the memory allocation subsystem.
  18248. */
  18249. static SQLITE_WSD struct Mem0Global {
  18250. sqlite3_mutex *mutex; /* Mutex to serialize access */
  18251. /*
  18252. ** The alarm callback and its arguments. The mem0.mutex lock will
  18253. ** be held while the callback is running. Recursive calls into
  18254. ** the memory subsystem are allowed, but no new callbacks will be
  18255. ** issued.
  18256. */
  18257. sqlite3_int64 alarmThreshold;
  18258. void (*alarmCallback)(void*, sqlite3_int64,int);
  18259. void *alarmArg;
  18260. /*
  18261. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  18262. ** (so that a range test can be used to determine if an allocation
  18263. ** being freed came from pScratch) and a pointer to the list of
  18264. ** unused scratch allocations.
  18265. */
  18266. void *pScratchEnd;
  18267. ScratchFreeslot *pScratchFree;
  18268. u32 nScratchFree;
  18269. /*
  18270. ** True if heap is nearly "full" where "full" is defined by the
  18271. ** sqlite3_soft_heap_limit() setting.
  18272. */
  18273. int nearlyFull;
  18274. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  18275. #define mem0 GLOBAL(struct Mem0Global, mem0)
  18276. /*
  18277. ** This routine runs when the memory allocator sees that the
  18278. ** total memory allocation is about to exceed the soft heap
  18279. ** limit.
  18280. */
  18281. static void softHeapLimitEnforcer(
  18282. void *NotUsed,
  18283. sqlite3_int64 NotUsed2,
  18284. int allocSize
  18285. ){
  18286. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  18287. sqlite3_release_memory(allocSize);
  18288. }
  18289. /*
  18290. ** Change the alarm callback
  18291. */
  18292. static int sqlite3MemoryAlarm(
  18293. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  18294. void *pArg,
  18295. sqlite3_int64 iThreshold
  18296. ){
  18297. int nUsed;
  18298. sqlite3_mutex_enter(mem0.mutex);
  18299. mem0.alarmCallback = xCallback;
  18300. mem0.alarmArg = pArg;
  18301. mem0.alarmThreshold = iThreshold;
  18302. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18303. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  18304. sqlite3_mutex_leave(mem0.mutex);
  18305. return SQLITE_OK;
  18306. }
  18307. #ifndef SQLITE_OMIT_DEPRECATED
  18308. /*
  18309. ** Deprecated external interface. Internal/core SQLite code
  18310. ** should call sqlite3MemoryAlarm.
  18311. */
  18312. SQLITE_API int sqlite3_memory_alarm(
  18313. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  18314. void *pArg,
  18315. sqlite3_int64 iThreshold
  18316. ){
  18317. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  18318. }
  18319. #endif
  18320. /*
  18321. ** Set the soft heap-size limit for the library. Passing a zero or
  18322. ** negative value indicates no limit.
  18323. */
  18324. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  18325. sqlite3_int64 priorLimit;
  18326. sqlite3_int64 excess;
  18327. #ifndef SQLITE_OMIT_AUTOINIT
  18328. int rc = sqlite3_initialize();
  18329. if( rc ) return -1;
  18330. #endif
  18331. sqlite3_mutex_enter(mem0.mutex);
  18332. priorLimit = mem0.alarmThreshold;
  18333. sqlite3_mutex_leave(mem0.mutex);
  18334. if( n<0 ) return priorLimit;
  18335. if( n>0 ){
  18336. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  18337. }else{
  18338. sqlite3MemoryAlarm(0, 0, 0);
  18339. }
  18340. excess = sqlite3_memory_used() - n;
  18341. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  18342. return priorLimit;
  18343. }
  18344. SQLITE_API void sqlite3_soft_heap_limit(int n){
  18345. if( n<0 ) n = 0;
  18346. sqlite3_soft_heap_limit64(n);
  18347. }
  18348. /*
  18349. ** Initialize the memory allocation subsystem.
  18350. */
  18351. SQLITE_PRIVATE int sqlite3MallocInit(void){
  18352. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  18353. sqlite3MemSetDefault();
  18354. }
  18355. memset(&mem0, 0, sizeof(mem0));
  18356. if( sqlite3GlobalConfig.bCoreMutex ){
  18357. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  18358. }
  18359. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  18360. && sqlite3GlobalConfig.nScratch>0 ){
  18361. int i, n, sz;
  18362. ScratchFreeslot *pSlot;
  18363. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  18364. sqlite3GlobalConfig.szScratch = sz;
  18365. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  18366. n = sqlite3GlobalConfig.nScratch;
  18367. mem0.pScratchFree = pSlot;
  18368. mem0.nScratchFree = n;
  18369. for(i=0; i<n-1; i++){
  18370. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  18371. pSlot = pSlot->pNext;
  18372. }
  18373. pSlot->pNext = 0;
  18374. mem0.pScratchEnd = (void*)&pSlot[1];
  18375. }else{
  18376. mem0.pScratchEnd = 0;
  18377. sqlite3GlobalConfig.pScratch = 0;
  18378. sqlite3GlobalConfig.szScratch = 0;
  18379. sqlite3GlobalConfig.nScratch = 0;
  18380. }
  18381. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  18382. || sqlite3GlobalConfig.nPage<1 ){
  18383. sqlite3GlobalConfig.pPage = 0;
  18384. sqlite3GlobalConfig.szPage = 0;
  18385. sqlite3GlobalConfig.nPage = 0;
  18386. }
  18387. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  18388. }
  18389. /*
  18390. ** Return true if the heap is currently under memory pressure - in other
  18391. ** words if the amount of heap used is close to the limit set by
  18392. ** sqlite3_soft_heap_limit().
  18393. */
  18394. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  18395. return mem0.nearlyFull;
  18396. }
  18397. /*
  18398. ** Deinitialize the memory allocation subsystem.
  18399. */
  18400. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  18401. if( sqlite3GlobalConfig.m.xShutdown ){
  18402. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  18403. }
  18404. memset(&mem0, 0, sizeof(mem0));
  18405. }
  18406. /*
  18407. ** Return the amount of memory currently checked out.
  18408. */
  18409. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  18410. int n, mx;
  18411. sqlite3_int64 res;
  18412. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  18413. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  18414. return res;
  18415. }
  18416. /*
  18417. ** Return the maximum amount of memory that has ever been
  18418. ** checked out since either the beginning of this process
  18419. ** or since the most recent reset.
  18420. */
  18421. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  18422. int n, mx;
  18423. sqlite3_int64 res;
  18424. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  18425. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  18426. return res;
  18427. }
  18428. /*
  18429. ** Trigger the alarm
  18430. */
  18431. static void sqlite3MallocAlarm(int nByte){
  18432. void (*xCallback)(void*,sqlite3_int64,int);
  18433. sqlite3_int64 nowUsed;
  18434. void *pArg;
  18435. if( mem0.alarmCallback==0 ) return;
  18436. xCallback = mem0.alarmCallback;
  18437. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18438. pArg = mem0.alarmArg;
  18439. mem0.alarmCallback = 0;
  18440. sqlite3_mutex_leave(mem0.mutex);
  18441. xCallback(pArg, nowUsed, nByte);
  18442. sqlite3_mutex_enter(mem0.mutex);
  18443. mem0.alarmCallback = xCallback;
  18444. mem0.alarmArg = pArg;
  18445. }
  18446. /*
  18447. ** Do a memory allocation with statistics and alarms. Assume the
  18448. ** lock is already held.
  18449. */
  18450. static int mallocWithAlarm(int n, void **pp){
  18451. int nFull;
  18452. void *p;
  18453. assert( sqlite3_mutex_held(mem0.mutex) );
  18454. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  18455. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  18456. if( mem0.alarmCallback!=0 ){
  18457. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18458. if( nUsed >= mem0.alarmThreshold - nFull ){
  18459. mem0.nearlyFull = 1;
  18460. sqlite3MallocAlarm(nFull);
  18461. }else{
  18462. mem0.nearlyFull = 0;
  18463. }
  18464. }
  18465. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18466. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18467. if( p==0 && mem0.alarmCallback ){
  18468. sqlite3MallocAlarm(nFull);
  18469. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  18470. }
  18471. #endif
  18472. if( p ){
  18473. nFull = sqlite3MallocSize(p);
  18474. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  18475. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  18476. }
  18477. *pp = p;
  18478. return nFull;
  18479. }
  18480. /*
  18481. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  18482. ** assumes the memory subsystem has already been initialized.
  18483. */
  18484. SQLITE_PRIVATE void *sqlite3Malloc(int n){
  18485. void *p;
  18486. if( n<=0 /* IMP: R-65312-04917 */
  18487. || n>=0x7fffff00
  18488. ){
  18489. /* A memory allocation of a number of bytes which is near the maximum
  18490. ** signed integer value might cause an integer overflow inside of the
  18491. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  18492. ** 255 bytes of overhead. SQLite itself will never use anything near
  18493. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  18494. p = 0;
  18495. }else if( sqlite3GlobalConfig.bMemstat ){
  18496. sqlite3_mutex_enter(mem0.mutex);
  18497. mallocWithAlarm(n, &p);
  18498. sqlite3_mutex_leave(mem0.mutex);
  18499. }else{
  18500. p = sqlite3GlobalConfig.m.xMalloc(n);
  18501. }
  18502. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-04675-44850 */
  18503. return p;
  18504. }
  18505. /*
  18506. ** This version of the memory allocation is for use by the application.
  18507. ** First make sure the memory subsystem is initialized, then do the
  18508. ** allocation.
  18509. */
  18510. SQLITE_API void *sqlite3_malloc(int n){
  18511. #ifndef SQLITE_OMIT_AUTOINIT
  18512. if( sqlite3_initialize() ) return 0;
  18513. #endif
  18514. return sqlite3Malloc(n);
  18515. }
  18516. /*
  18517. ** Each thread may only have a single outstanding allocation from
  18518. ** xScratchMalloc(). We verify this constraint in the single-threaded
  18519. ** case by setting scratchAllocOut to 1 when an allocation
  18520. ** is outstanding clearing it when the allocation is freed.
  18521. */
  18522. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18523. static int scratchAllocOut = 0;
  18524. #endif
  18525. /*
  18526. ** Allocate memory that is to be used and released right away.
  18527. ** This routine is similar to alloca() in that it is not intended
  18528. ** for situations where the memory might be held long-term. This
  18529. ** routine is intended to get memory to old large transient data
  18530. ** structures that would not normally fit on the stack of an
  18531. ** embedded processor.
  18532. */
  18533. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  18534. void *p;
  18535. assert( n>0 );
  18536. sqlite3_mutex_enter(mem0.mutex);
  18537. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  18538. p = mem0.pScratchFree;
  18539. mem0.pScratchFree = mem0.pScratchFree->pNext;
  18540. mem0.nScratchFree--;
  18541. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  18542. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18543. sqlite3_mutex_leave(mem0.mutex);
  18544. }else{
  18545. if( sqlite3GlobalConfig.bMemstat ){
  18546. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  18547. n = mallocWithAlarm(n, &p);
  18548. if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
  18549. sqlite3_mutex_leave(mem0.mutex);
  18550. }else{
  18551. sqlite3_mutex_leave(mem0.mutex);
  18552. p = sqlite3GlobalConfig.m.xMalloc(n);
  18553. }
  18554. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  18555. }
  18556. assert( sqlite3_mutex_notheld(mem0.mutex) );
  18557. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18558. /* Verify that no more than two scratch allocations per thread
  18559. ** are outstanding at one time. (This is only checked in the
  18560. ** single-threaded case since checking in the multi-threaded case
  18561. ** would be much more complicated.) */
  18562. assert( scratchAllocOut<=1 );
  18563. if( p ) scratchAllocOut++;
  18564. #endif
  18565. return p;
  18566. }
  18567. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  18568. if( p ){
  18569. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  18570. /* Verify that no more than two scratch allocation per thread
  18571. ** is outstanding at one time. (This is only checked in the
  18572. ** single-threaded case since checking in the multi-threaded case
  18573. ** would be much more complicated.) */
  18574. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  18575. scratchAllocOut--;
  18576. #endif
  18577. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  18578. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  18579. ScratchFreeslot *pSlot;
  18580. pSlot = (ScratchFreeslot*)p;
  18581. sqlite3_mutex_enter(mem0.mutex);
  18582. pSlot->pNext = mem0.pScratchFree;
  18583. mem0.pScratchFree = pSlot;
  18584. mem0.nScratchFree++;
  18585. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  18586. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  18587. sqlite3_mutex_leave(mem0.mutex);
  18588. }else{
  18589. /* Release memory back to the heap */
  18590. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  18591. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  18592. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18593. if( sqlite3GlobalConfig.bMemstat ){
  18594. int iSize = sqlite3MallocSize(p);
  18595. sqlite3_mutex_enter(mem0.mutex);
  18596. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  18597. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  18598. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18599. sqlite3GlobalConfig.m.xFree(p);
  18600. sqlite3_mutex_leave(mem0.mutex);
  18601. }else{
  18602. sqlite3GlobalConfig.m.xFree(p);
  18603. }
  18604. }
  18605. }
  18606. }
  18607. /*
  18608. ** TRUE if p is a lookaside memory allocation from db
  18609. */
  18610. #ifndef SQLITE_OMIT_LOOKASIDE
  18611. static int isLookaside(sqlite3 *db, void *p){
  18612. return p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  18613. }
  18614. #else
  18615. #define isLookaside(A,B) 0
  18616. #endif
  18617. /*
  18618. ** Return the size of a memory allocation previously obtained from
  18619. ** sqlite3Malloc() or sqlite3_malloc().
  18620. */
  18621. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  18622. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18623. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18624. return sqlite3GlobalConfig.m.xSize(p);
  18625. }
  18626. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  18627. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18628. if( db && isLookaside(db, p) ){
  18629. return db->lookaside.sz;
  18630. }else{
  18631. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18632. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18633. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18634. return sqlite3GlobalConfig.m.xSize(p);
  18635. }
  18636. }
  18637. /*
  18638. ** Free memory previously obtained from sqlite3Malloc().
  18639. */
  18640. SQLITE_API void sqlite3_free(void *p){
  18641. if( p==0 ) return; /* IMP: R-49053-54554 */
  18642. assert( sqlite3MemdebugNoType(p, MEMTYPE_DB) );
  18643. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  18644. if( sqlite3GlobalConfig.bMemstat ){
  18645. sqlite3_mutex_enter(mem0.mutex);
  18646. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  18647. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  18648. sqlite3GlobalConfig.m.xFree(p);
  18649. sqlite3_mutex_leave(mem0.mutex);
  18650. }else{
  18651. sqlite3GlobalConfig.m.xFree(p);
  18652. }
  18653. }
  18654. /*
  18655. ** Free memory that might be associated with a particular database
  18656. ** connection.
  18657. */
  18658. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  18659. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18660. if( p==0 ) return;
  18661. if( db ){
  18662. if( db->pnBytesFreed ){
  18663. *db->pnBytesFreed += sqlite3DbMallocSize(db, p);
  18664. return;
  18665. }
  18666. if( isLookaside(db, p) ){
  18667. LookasideSlot *pBuf = (LookasideSlot*)p;
  18668. #if SQLITE_DEBUG
  18669. /* Trash all content in the buffer being freed */
  18670. memset(p, 0xaa, db->lookaside.sz);
  18671. #endif
  18672. pBuf->pNext = db->lookaside.pFree;
  18673. db->lookaside.pFree = pBuf;
  18674. db->lookaside.nOut--;
  18675. return;
  18676. }
  18677. }
  18678. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18679. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18680. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  18681. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18682. sqlite3_free(p);
  18683. }
  18684. /*
  18685. ** Change the size of an existing memory allocation
  18686. */
  18687. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
  18688. int nOld, nNew, nDiff;
  18689. void *pNew;
  18690. if( pOld==0 ){
  18691. return sqlite3Malloc(nBytes); /* IMP: R-28354-25769 */
  18692. }
  18693. if( nBytes<=0 ){
  18694. sqlite3_free(pOld); /* IMP: R-31593-10574 */
  18695. return 0;
  18696. }
  18697. if( nBytes>=0x7fffff00 ){
  18698. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  18699. return 0;
  18700. }
  18701. nOld = sqlite3MallocSize(pOld);
  18702. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  18703. ** argument to xRealloc is always a value returned by a prior call to
  18704. ** xRoundup. */
  18705. nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
  18706. if( nOld==nNew ){
  18707. pNew = pOld;
  18708. }else if( sqlite3GlobalConfig.bMemstat ){
  18709. sqlite3_mutex_enter(mem0.mutex);
  18710. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
  18711. nDiff = nNew - nOld;
  18712. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  18713. mem0.alarmThreshold-nDiff ){
  18714. sqlite3MallocAlarm(nDiff);
  18715. }
  18716. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  18717. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  18718. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18719. if( pNew==0 && mem0.alarmCallback ){
  18720. sqlite3MallocAlarm(nBytes);
  18721. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18722. }
  18723. if( pNew ){
  18724. nNew = sqlite3MallocSize(pNew);
  18725. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  18726. }
  18727. sqlite3_mutex_leave(mem0.mutex);
  18728. }else{
  18729. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  18730. }
  18731. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-04675-44850 */
  18732. return pNew;
  18733. }
  18734. /*
  18735. ** The public interface to sqlite3Realloc. Make sure that the memory
  18736. ** subsystem is initialized prior to invoking sqliteRealloc.
  18737. */
  18738. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  18739. #ifndef SQLITE_OMIT_AUTOINIT
  18740. if( sqlite3_initialize() ) return 0;
  18741. #endif
  18742. return sqlite3Realloc(pOld, n);
  18743. }
  18744. /*
  18745. ** Allocate and zero memory.
  18746. */
  18747. SQLITE_PRIVATE void *sqlite3MallocZero(int n){
  18748. void *p = sqlite3Malloc(n);
  18749. if( p ){
  18750. memset(p, 0, n);
  18751. }
  18752. return p;
  18753. }
  18754. /*
  18755. ** Allocate and zero memory. If the allocation fails, make
  18756. ** the mallocFailed flag in the connection pointer.
  18757. */
  18758. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
  18759. void *p = sqlite3DbMallocRaw(db, n);
  18760. if( p ){
  18761. memset(p, 0, n);
  18762. }
  18763. return p;
  18764. }
  18765. /*
  18766. ** Allocate and zero memory. If the allocation fails, make
  18767. ** the mallocFailed flag in the connection pointer.
  18768. **
  18769. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  18770. ** failure on the same database connection) then always return 0.
  18771. ** Hence for a particular database connection, once malloc starts
  18772. ** failing, it fails consistently until mallocFailed is reset.
  18773. ** This is an important assumption. There are many places in the
  18774. ** code that do things like this:
  18775. **
  18776. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  18777. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  18778. ** if( b ) a[10] = 9;
  18779. **
  18780. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  18781. ** that all prior mallocs (ex: "a") worked too.
  18782. */
  18783. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
  18784. void *p;
  18785. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  18786. assert( db==0 || db->pnBytesFreed==0 );
  18787. #ifndef SQLITE_OMIT_LOOKASIDE
  18788. if( db ){
  18789. LookasideSlot *pBuf;
  18790. if( db->mallocFailed ){
  18791. return 0;
  18792. }
  18793. if( db->lookaside.bEnabled ){
  18794. if( n>db->lookaside.sz ){
  18795. db->lookaside.anStat[1]++;
  18796. }else if( (pBuf = db->lookaside.pFree)==0 ){
  18797. db->lookaside.anStat[2]++;
  18798. }else{
  18799. db->lookaside.pFree = pBuf->pNext;
  18800. db->lookaside.nOut++;
  18801. db->lookaside.anStat[0]++;
  18802. if( db->lookaside.nOut>db->lookaside.mxOut ){
  18803. db->lookaside.mxOut = db->lookaside.nOut;
  18804. }
  18805. return (void*)pBuf;
  18806. }
  18807. }
  18808. }
  18809. #else
  18810. if( db && db->mallocFailed ){
  18811. return 0;
  18812. }
  18813. #endif
  18814. p = sqlite3Malloc(n);
  18815. if( !p && db ){
  18816. db->mallocFailed = 1;
  18817. }
  18818. sqlite3MemdebugSetType(p, MEMTYPE_DB |
  18819. ((db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18820. return p;
  18821. }
  18822. /*
  18823. ** Resize the block of memory pointed to by p to n bytes. If the
  18824. ** resize fails, set the mallocFailed flag in the connection object.
  18825. */
  18826. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
  18827. void *pNew = 0;
  18828. assert( db!=0 );
  18829. assert( sqlite3_mutex_held(db->mutex) );
  18830. if( db->mallocFailed==0 ){
  18831. if( p==0 ){
  18832. return sqlite3DbMallocRaw(db, n);
  18833. }
  18834. if( isLookaside(db, p) ){
  18835. if( n<=db->lookaside.sz ){
  18836. return p;
  18837. }
  18838. pNew = sqlite3DbMallocRaw(db, n);
  18839. if( pNew ){
  18840. memcpy(pNew, p, db->lookaside.sz);
  18841. sqlite3DbFree(db, p);
  18842. }
  18843. }else{
  18844. assert( sqlite3MemdebugHasType(p, MEMTYPE_DB) );
  18845. assert( sqlite3MemdebugHasType(p, MEMTYPE_LOOKASIDE|MEMTYPE_HEAP) );
  18846. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  18847. pNew = sqlite3_realloc(p, n);
  18848. if( !pNew ){
  18849. sqlite3MemdebugSetType(p, MEMTYPE_DB|MEMTYPE_HEAP);
  18850. db->mallocFailed = 1;
  18851. }
  18852. sqlite3MemdebugSetType(pNew, MEMTYPE_DB |
  18853. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  18854. }
  18855. }
  18856. return pNew;
  18857. }
  18858. /*
  18859. ** Attempt to reallocate p. If the reallocation fails, then free p
  18860. ** and set the mallocFailed flag in the database connection.
  18861. */
  18862. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
  18863. void *pNew;
  18864. pNew = sqlite3DbRealloc(db, p, n);
  18865. if( !pNew ){
  18866. sqlite3DbFree(db, p);
  18867. }
  18868. return pNew;
  18869. }
  18870. /*
  18871. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  18872. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  18873. ** is because when memory debugging is turned on, these two functions are
  18874. ** called via macros that record the current file and line number in the
  18875. ** ThreadData structure.
  18876. */
  18877. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  18878. char *zNew;
  18879. size_t n;
  18880. if( z==0 ){
  18881. return 0;
  18882. }
  18883. n = sqlite3Strlen30(z) + 1;
  18884. assert( (n&0x7fffffff)==n );
  18885. zNew = sqlite3DbMallocRaw(db, (int)n);
  18886. if( zNew ){
  18887. memcpy(zNew, z, n);
  18888. }
  18889. return zNew;
  18890. }
  18891. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
  18892. char *zNew;
  18893. if( z==0 ){
  18894. return 0;
  18895. }
  18896. assert( (n&0x7fffffff)==n );
  18897. zNew = sqlite3DbMallocRaw(db, n+1);
  18898. if( zNew ){
  18899. memcpy(zNew, z, n);
  18900. zNew[n] = 0;
  18901. }
  18902. return zNew;
  18903. }
  18904. /*
  18905. ** Create a string from the zFromat argument and the va_list that follows.
  18906. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  18907. ** point to that string.
  18908. */
  18909. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  18910. va_list ap;
  18911. char *z;
  18912. va_start(ap, zFormat);
  18913. z = sqlite3VMPrintf(db, zFormat, ap);
  18914. va_end(ap);
  18915. sqlite3DbFree(db, *pz);
  18916. *pz = z;
  18917. }
  18918. /*
  18919. ** This function must be called before exiting any API function (i.e.
  18920. ** returning control to the user) that has called sqlite3_malloc or
  18921. ** sqlite3_realloc.
  18922. **
  18923. ** The returned value is normally a copy of the second argument to this
  18924. ** function. However, if a malloc() failure has occurred since the previous
  18925. ** invocation SQLITE_NOMEM is returned instead.
  18926. **
  18927. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  18928. ** then the connection error-code (the value returned by sqlite3_errcode())
  18929. ** is set to SQLITE_NOMEM.
  18930. */
  18931. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  18932. /* If the db handle is not NULL, then we must hold the connection handle
  18933. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  18934. ** is unsafe, as is the call to sqlite3Error().
  18935. */
  18936. assert( !db || sqlite3_mutex_held(db->mutex) );
  18937. if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
  18938. sqlite3Error(db, SQLITE_NOMEM, 0);
  18939. db->mallocFailed = 0;
  18940. rc = SQLITE_NOMEM;
  18941. }
  18942. return rc & (db ? db->errMask : 0xff);
  18943. }
  18944. /************** End of malloc.c **********************************************/
  18945. /************** Begin file printf.c ******************************************/
  18946. /*
  18947. ** The "printf" code that follows dates from the 1980's. It is in
  18948. ** the public domain. The original comments are included here for
  18949. ** completeness. They are very out-of-date but might be useful as
  18950. ** an historical reference. Most of the "enhancements" have been backed
  18951. ** out so that the functionality is now the same as standard printf().
  18952. **
  18953. **************************************************************************
  18954. **
  18955. ** This file contains code for a set of "printf"-like routines. These
  18956. ** routines format strings much like the printf() from the standard C
  18957. ** library, though the implementation here has enhancements to support
  18958. ** SQLlite.
  18959. */
  18960. /*
  18961. ** Conversion types fall into various categories as defined by the
  18962. ** following enumeration.
  18963. */
  18964. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  18965. #define etFLOAT 2 /* Floating point. %f */
  18966. #define etEXP 3 /* Exponentional notation. %e and %E */
  18967. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  18968. #define etSIZE 5 /* Return number of characters processed so far. %n */
  18969. #define etSTRING 6 /* Strings. %s */
  18970. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  18971. #define etPERCENT 8 /* Percent symbol. %% */
  18972. #define etCHARX 9 /* Characters. %c */
  18973. /* The rest are extensions, not normally found in printf() */
  18974. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  18975. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  18976. NULL pointers replaced by SQL NULL. %Q */
  18977. #define etTOKEN 12 /* a pointer to a Token structure */
  18978. #define etSRCLIST 13 /* a pointer to a SrcList */
  18979. #define etPOINTER 14 /* The %p conversion */
  18980. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  18981. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  18982. #define etINVALID 0 /* Any unrecognized conversion type */
  18983. /*
  18984. ** An "etByte" is an 8-bit unsigned value.
  18985. */
  18986. typedef unsigned char etByte;
  18987. /*
  18988. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  18989. ** by an instance of the following structure
  18990. */
  18991. typedef struct et_info { /* Information about each format field */
  18992. char fmttype; /* The format field code letter */
  18993. etByte base; /* The base for radix conversion */
  18994. etByte flags; /* One or more of FLAG_ constants below */
  18995. etByte type; /* Conversion paradigm */
  18996. etByte charset; /* Offset into aDigits[] of the digits string */
  18997. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  18998. } et_info;
  18999. /*
  19000. ** Allowed values for et_info.flags
  19001. */
  19002. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  19003. #define FLAG_INTERN 2 /* True if for internal use only */
  19004. #define FLAG_STRING 4 /* Allow infinity precision */
  19005. /*
  19006. ** The following table is searched linearly, so it is good to put the
  19007. ** most frequently used conversion types first.
  19008. */
  19009. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  19010. static const char aPrefix[] = "-x0\000X0";
  19011. static const et_info fmtinfo[] = {
  19012. { 'd', 10, 1, etRADIX, 0, 0 },
  19013. { 's', 0, 4, etSTRING, 0, 0 },
  19014. { 'g', 0, 1, etGENERIC, 30, 0 },
  19015. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  19016. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  19017. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  19018. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  19019. { 'c', 0, 0, etCHARX, 0, 0 },
  19020. { 'o', 8, 0, etRADIX, 0, 2 },
  19021. { 'u', 10, 0, etRADIX, 0, 0 },
  19022. { 'x', 16, 0, etRADIX, 16, 1 },
  19023. { 'X', 16, 0, etRADIX, 0, 4 },
  19024. #ifndef SQLITE_OMIT_FLOATING_POINT
  19025. { 'f', 0, 1, etFLOAT, 0, 0 },
  19026. { 'e', 0, 1, etEXP, 30, 0 },
  19027. { 'E', 0, 1, etEXP, 14, 0 },
  19028. { 'G', 0, 1, etGENERIC, 14, 0 },
  19029. #endif
  19030. { 'i', 10, 1, etRADIX, 0, 0 },
  19031. { 'n', 0, 0, etSIZE, 0, 0 },
  19032. { '%', 0, 0, etPERCENT, 0, 0 },
  19033. { 'p', 16, 0, etPOINTER, 0, 1 },
  19034. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  19035. ** use only */
  19036. { 'T', 0, 2, etTOKEN, 0, 0 },
  19037. { 'S', 0, 2, etSRCLIST, 0, 0 },
  19038. { 'r', 10, 3, etORDINAL, 0, 0 },
  19039. };
  19040. /*
  19041. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  19042. ** conversions will work.
  19043. */
  19044. #ifndef SQLITE_OMIT_FLOATING_POINT
  19045. /*
  19046. ** "*val" is a double such that 0.1 <= *val < 10.0
  19047. ** Return the ascii code for the leading digit of *val, then
  19048. ** multiply "*val" by 10.0 to renormalize.
  19049. **
  19050. ** Example:
  19051. ** input: *val = 3.14159
  19052. ** output: *val = 1.4159 function return = '3'
  19053. **
  19054. ** The counter *cnt is incremented each time. After counter exceeds
  19055. ** 16 (the number of significant digits in a 64-bit float) '0' is
  19056. ** always returned.
  19057. */
  19058. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  19059. int digit;
  19060. LONGDOUBLE_TYPE d;
  19061. if( (*cnt)<=0 ) return '0';
  19062. (*cnt)--;
  19063. digit = (int)*val;
  19064. d = digit;
  19065. digit += '0';
  19066. *val = (*val - d)*10.0;
  19067. return (char)digit;
  19068. }
  19069. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19070. /*
  19071. ** Append N space characters to the given string buffer.
  19072. */
  19073. SQLITE_PRIVATE void sqlite3AppendSpace(StrAccum *pAccum, int N){
  19074. static const char zSpaces[] = " ";
  19075. while( N>=(int)sizeof(zSpaces)-1 ){
  19076. sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
  19077. N -= sizeof(zSpaces)-1;
  19078. }
  19079. if( N>0 ){
  19080. sqlite3StrAccumAppend(pAccum, zSpaces, N);
  19081. }
  19082. }
  19083. /*
  19084. ** On machines with a small stack size, you can redefine the
  19085. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  19086. */
  19087. #ifndef SQLITE_PRINT_BUF_SIZE
  19088. # define SQLITE_PRINT_BUF_SIZE 70
  19089. #endif
  19090. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  19091. /*
  19092. ** Render a string given by "fmt" into the StrAccum object.
  19093. */
  19094. SQLITE_PRIVATE void sqlite3VXPrintf(
  19095. StrAccum *pAccum, /* Accumulate results here */
  19096. int useExtended, /* Allow extended %-conversions */
  19097. const char *fmt, /* Format string */
  19098. va_list ap /* arguments */
  19099. ){
  19100. int c; /* Next character in the format string */
  19101. char *bufpt; /* Pointer to the conversion buffer */
  19102. int precision; /* Precision of the current field */
  19103. int length; /* Length of the field */
  19104. int idx; /* A general purpose loop counter */
  19105. int width; /* Width of the current field */
  19106. etByte flag_leftjustify; /* True if "-" flag is present */
  19107. etByte flag_plussign; /* True if "+" flag is present */
  19108. etByte flag_blanksign; /* True if " " flag is present */
  19109. etByte flag_alternateform; /* True if "#" flag is present */
  19110. etByte flag_altform2; /* True if "!" flag is present */
  19111. etByte flag_zeropad; /* True if field width constant starts with zero */
  19112. etByte flag_long; /* True if "l" flag is present */
  19113. etByte flag_longlong; /* True if the "ll" flag is present */
  19114. etByte done; /* Loop termination flag */
  19115. etByte xtype = 0; /* Conversion paradigm */
  19116. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  19117. sqlite_uint64 longvalue; /* Value for integer types */
  19118. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  19119. const et_info *infop; /* Pointer to the appropriate info structure */
  19120. char *zOut; /* Rendering buffer */
  19121. int nOut; /* Size of the rendering buffer */
  19122. char *zExtra; /* Malloced memory used by some conversion */
  19123. #ifndef SQLITE_OMIT_FLOATING_POINT
  19124. int exp, e2; /* exponent of real numbers */
  19125. int nsd; /* Number of significant digits returned */
  19126. double rounder; /* Used for rounding floating point values */
  19127. etByte flag_dp; /* True if decimal point should be shown */
  19128. etByte flag_rtz; /* True if trailing zeros should be removed */
  19129. #endif
  19130. char buf[etBUFSIZE]; /* Conversion buffer */
  19131. bufpt = 0;
  19132. for(; (c=(*fmt))!=0; ++fmt){
  19133. if( c!='%' ){
  19134. int amt;
  19135. bufpt = (char *)fmt;
  19136. amt = 1;
  19137. while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  19138. sqlite3StrAccumAppend(pAccum, bufpt, amt);
  19139. if( c==0 ) break;
  19140. }
  19141. if( (c=(*++fmt))==0 ){
  19142. sqlite3StrAccumAppend(pAccum, "%", 1);
  19143. break;
  19144. }
  19145. /* Find out what flags are present */
  19146. flag_leftjustify = flag_plussign = flag_blanksign =
  19147. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  19148. done = 0;
  19149. do{
  19150. switch( c ){
  19151. case '-': flag_leftjustify = 1; break;
  19152. case '+': flag_plussign = 1; break;
  19153. case ' ': flag_blanksign = 1; break;
  19154. case '#': flag_alternateform = 1; break;
  19155. case '!': flag_altform2 = 1; break;
  19156. case '0': flag_zeropad = 1; break;
  19157. default: done = 1; break;
  19158. }
  19159. }while( !done && (c=(*++fmt))!=0 );
  19160. /* Get the field width */
  19161. width = 0;
  19162. if( c=='*' ){
  19163. width = va_arg(ap,int);
  19164. if( width<0 ){
  19165. flag_leftjustify = 1;
  19166. width = -width;
  19167. }
  19168. c = *++fmt;
  19169. }else{
  19170. while( c>='0' && c<='9' ){
  19171. width = width*10 + c - '0';
  19172. c = *++fmt;
  19173. }
  19174. }
  19175. /* Get the precision */
  19176. if( c=='.' ){
  19177. precision = 0;
  19178. c = *++fmt;
  19179. if( c=='*' ){
  19180. precision = va_arg(ap,int);
  19181. if( precision<0 ) precision = -precision;
  19182. c = *++fmt;
  19183. }else{
  19184. while( c>='0' && c<='9' ){
  19185. precision = precision*10 + c - '0';
  19186. c = *++fmt;
  19187. }
  19188. }
  19189. }else{
  19190. precision = -1;
  19191. }
  19192. /* Get the conversion type modifier */
  19193. if( c=='l' ){
  19194. flag_long = 1;
  19195. c = *++fmt;
  19196. if( c=='l' ){
  19197. flag_longlong = 1;
  19198. c = *++fmt;
  19199. }else{
  19200. flag_longlong = 0;
  19201. }
  19202. }else{
  19203. flag_long = flag_longlong = 0;
  19204. }
  19205. /* Fetch the info entry for the field */
  19206. infop = &fmtinfo[0];
  19207. xtype = etINVALID;
  19208. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  19209. if( c==fmtinfo[idx].fmttype ){
  19210. infop = &fmtinfo[idx];
  19211. if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  19212. xtype = infop->type;
  19213. }else{
  19214. return;
  19215. }
  19216. break;
  19217. }
  19218. }
  19219. zExtra = 0;
  19220. /*
  19221. ** At this point, variables are initialized as follows:
  19222. **
  19223. ** flag_alternateform TRUE if a '#' is present.
  19224. ** flag_altform2 TRUE if a '!' is present.
  19225. ** flag_plussign TRUE if a '+' is present.
  19226. ** flag_leftjustify TRUE if a '-' is present or if the
  19227. ** field width was negative.
  19228. ** flag_zeropad TRUE if the width began with 0.
  19229. ** flag_long TRUE if the letter 'l' (ell) prefixed
  19230. ** the conversion character.
  19231. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  19232. ** the conversion character.
  19233. ** flag_blanksign TRUE if a ' ' is present.
  19234. ** width The specified field width. This is
  19235. ** always non-negative. Zero is the default.
  19236. ** precision The specified precision. The default
  19237. ** is -1.
  19238. ** xtype The class of the conversion.
  19239. ** infop Pointer to the appropriate info struct.
  19240. */
  19241. switch( xtype ){
  19242. case etPOINTER:
  19243. flag_longlong = sizeof(char*)==sizeof(i64);
  19244. flag_long = sizeof(char*)==sizeof(long int);
  19245. /* Fall through into the next case */
  19246. case etORDINAL:
  19247. case etRADIX:
  19248. if( infop->flags & FLAG_SIGNED ){
  19249. i64 v;
  19250. if( flag_longlong ){
  19251. v = va_arg(ap,i64);
  19252. }else if( flag_long ){
  19253. v = va_arg(ap,long int);
  19254. }else{
  19255. v = va_arg(ap,int);
  19256. }
  19257. if( v<0 ){
  19258. if( v==SMALLEST_INT64 ){
  19259. longvalue = ((u64)1)<<63;
  19260. }else{
  19261. longvalue = -v;
  19262. }
  19263. prefix = '-';
  19264. }else{
  19265. longvalue = v;
  19266. if( flag_plussign ) prefix = '+';
  19267. else if( flag_blanksign ) prefix = ' ';
  19268. else prefix = 0;
  19269. }
  19270. }else{
  19271. if( flag_longlong ){
  19272. longvalue = va_arg(ap,u64);
  19273. }else if( flag_long ){
  19274. longvalue = va_arg(ap,unsigned long int);
  19275. }else{
  19276. longvalue = va_arg(ap,unsigned int);
  19277. }
  19278. prefix = 0;
  19279. }
  19280. if( longvalue==0 ) flag_alternateform = 0;
  19281. if( flag_zeropad && precision<width-(prefix!=0) ){
  19282. precision = width-(prefix!=0);
  19283. }
  19284. if( precision<etBUFSIZE-10 ){
  19285. nOut = etBUFSIZE;
  19286. zOut = buf;
  19287. }else{
  19288. nOut = precision + 10;
  19289. zOut = zExtra = sqlite3Malloc( nOut );
  19290. if( zOut==0 ){
  19291. pAccum->accError = STRACCUM_NOMEM;
  19292. return;
  19293. }
  19294. }
  19295. bufpt = &zOut[nOut-1];
  19296. if( xtype==etORDINAL ){
  19297. static const char zOrd[] = "thstndrd";
  19298. int x = (int)(longvalue % 10);
  19299. if( x>=4 || (longvalue/10)%10==1 ){
  19300. x = 0;
  19301. }
  19302. *(--bufpt) = zOrd[x*2+1];
  19303. *(--bufpt) = zOrd[x*2];
  19304. }
  19305. {
  19306. register const char *cset; /* Use registers for speed */
  19307. register int base;
  19308. cset = &aDigits[infop->charset];
  19309. base = infop->base;
  19310. do{ /* Convert to ascii */
  19311. *(--bufpt) = cset[longvalue%base];
  19312. longvalue = longvalue/base;
  19313. }while( longvalue>0 );
  19314. }
  19315. length = (int)(&zOut[nOut-1]-bufpt);
  19316. for(idx=precision-length; idx>0; idx--){
  19317. *(--bufpt) = '0'; /* Zero pad */
  19318. }
  19319. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  19320. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  19321. const char *pre;
  19322. char x;
  19323. pre = &aPrefix[infop->prefix];
  19324. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  19325. }
  19326. length = (int)(&zOut[nOut-1]-bufpt);
  19327. break;
  19328. case etFLOAT:
  19329. case etEXP:
  19330. case etGENERIC:
  19331. realvalue = va_arg(ap,double);
  19332. #ifdef SQLITE_OMIT_FLOATING_POINT
  19333. length = 0;
  19334. #else
  19335. if( precision<0 ) precision = 6; /* Set default precision */
  19336. if( realvalue<0.0 ){
  19337. realvalue = -realvalue;
  19338. prefix = '-';
  19339. }else{
  19340. if( flag_plussign ) prefix = '+';
  19341. else if( flag_blanksign ) prefix = ' ';
  19342. else prefix = 0;
  19343. }
  19344. if( xtype==etGENERIC && precision>0 ) precision--;
  19345. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  19346. if( xtype==etFLOAT ) realvalue += rounder;
  19347. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  19348. exp = 0;
  19349. if( sqlite3IsNaN((double)realvalue) ){
  19350. bufpt = "NaN";
  19351. length = 3;
  19352. break;
  19353. }
  19354. if( realvalue>0.0 ){
  19355. LONGDOUBLE_TYPE scale = 1.0;
  19356. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  19357. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  19358. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  19359. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  19360. realvalue /= scale;
  19361. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  19362. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  19363. if( exp>350 ){
  19364. if( prefix=='-' ){
  19365. bufpt = "-Inf";
  19366. }else if( prefix=='+' ){
  19367. bufpt = "+Inf";
  19368. }else{
  19369. bufpt = "Inf";
  19370. }
  19371. length = sqlite3Strlen30(bufpt);
  19372. break;
  19373. }
  19374. }
  19375. bufpt = buf;
  19376. /*
  19377. ** If the field type is etGENERIC, then convert to either etEXP
  19378. ** or etFLOAT, as appropriate.
  19379. */
  19380. if( xtype!=etFLOAT ){
  19381. realvalue += rounder;
  19382. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  19383. }
  19384. if( xtype==etGENERIC ){
  19385. flag_rtz = !flag_alternateform;
  19386. if( exp<-4 || exp>precision ){
  19387. xtype = etEXP;
  19388. }else{
  19389. precision = precision - exp;
  19390. xtype = etFLOAT;
  19391. }
  19392. }else{
  19393. flag_rtz = flag_altform2;
  19394. }
  19395. if( xtype==etEXP ){
  19396. e2 = 0;
  19397. }else{
  19398. e2 = exp;
  19399. }
  19400. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  19401. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  19402. if( bufpt==0 ){
  19403. pAccum->accError = STRACCUM_NOMEM;
  19404. return;
  19405. }
  19406. }
  19407. zOut = bufpt;
  19408. nsd = 16 + flag_altform2*10;
  19409. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  19410. /* The sign in front of the number */
  19411. if( prefix ){
  19412. *(bufpt++) = prefix;
  19413. }
  19414. /* Digits prior to the decimal point */
  19415. if( e2<0 ){
  19416. *(bufpt++) = '0';
  19417. }else{
  19418. for(; e2>=0; e2--){
  19419. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19420. }
  19421. }
  19422. /* The decimal point */
  19423. if( flag_dp ){
  19424. *(bufpt++) = '.';
  19425. }
  19426. /* "0" digits after the decimal point but before the first
  19427. ** significant digit of the number */
  19428. for(e2++; e2<0; precision--, e2++){
  19429. assert( precision>0 );
  19430. *(bufpt++) = '0';
  19431. }
  19432. /* Significant digits after the decimal point */
  19433. while( (precision--)>0 ){
  19434. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  19435. }
  19436. /* Remove trailing zeros and the "." if no digits follow the "." */
  19437. if( flag_rtz && flag_dp ){
  19438. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  19439. assert( bufpt>zOut );
  19440. if( bufpt[-1]=='.' ){
  19441. if( flag_altform2 ){
  19442. *(bufpt++) = '0';
  19443. }else{
  19444. *(--bufpt) = 0;
  19445. }
  19446. }
  19447. }
  19448. /* Add the "eNNN" suffix */
  19449. if( xtype==etEXP ){
  19450. *(bufpt++) = aDigits[infop->charset];
  19451. if( exp<0 ){
  19452. *(bufpt++) = '-'; exp = -exp;
  19453. }else{
  19454. *(bufpt++) = '+';
  19455. }
  19456. if( exp>=100 ){
  19457. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  19458. exp %= 100;
  19459. }
  19460. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  19461. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  19462. }
  19463. *bufpt = 0;
  19464. /* The converted number is in buf[] and zero terminated. Output it.
  19465. ** Note that the number is in the usual order, not reversed as with
  19466. ** integer conversions. */
  19467. length = (int)(bufpt-zOut);
  19468. bufpt = zOut;
  19469. /* Special case: Add leading zeros if the flag_zeropad flag is
  19470. ** set and we are not left justified */
  19471. if( flag_zeropad && !flag_leftjustify && length < width){
  19472. int i;
  19473. int nPad = width - length;
  19474. for(i=width; i>=nPad; i--){
  19475. bufpt[i] = bufpt[i-nPad];
  19476. }
  19477. i = prefix!=0;
  19478. while( nPad-- ) bufpt[i++] = '0';
  19479. length = width;
  19480. }
  19481. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  19482. break;
  19483. case etSIZE:
  19484. *(va_arg(ap,int*)) = pAccum->nChar;
  19485. length = width = 0;
  19486. break;
  19487. case etPERCENT:
  19488. buf[0] = '%';
  19489. bufpt = buf;
  19490. length = 1;
  19491. break;
  19492. case etCHARX:
  19493. c = va_arg(ap,int);
  19494. buf[0] = (char)c;
  19495. if( precision>=0 ){
  19496. for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
  19497. length = precision;
  19498. }else{
  19499. length =1;
  19500. }
  19501. bufpt = buf;
  19502. break;
  19503. case etSTRING:
  19504. case etDYNSTRING:
  19505. bufpt = va_arg(ap,char*);
  19506. if( bufpt==0 ){
  19507. bufpt = "";
  19508. }else if( xtype==etDYNSTRING ){
  19509. zExtra = bufpt;
  19510. }
  19511. if( precision>=0 ){
  19512. for(length=0; length<precision && bufpt[length]; length++){}
  19513. }else{
  19514. length = sqlite3Strlen30(bufpt);
  19515. }
  19516. break;
  19517. case etSQLESCAPE:
  19518. case etSQLESCAPE2:
  19519. case etSQLESCAPE3: {
  19520. int i, j, k, n, isnull;
  19521. int needQuote;
  19522. char ch;
  19523. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  19524. char *escarg = va_arg(ap,char*);
  19525. isnull = escarg==0;
  19526. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  19527. k = precision;
  19528. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  19529. if( ch==q ) n++;
  19530. }
  19531. needQuote = !isnull && xtype==etSQLESCAPE2;
  19532. n += i + 1 + needQuote*2;
  19533. if( n>etBUFSIZE ){
  19534. bufpt = zExtra = sqlite3Malloc( n );
  19535. if( bufpt==0 ){
  19536. pAccum->accError = STRACCUM_NOMEM;
  19537. return;
  19538. }
  19539. }else{
  19540. bufpt = buf;
  19541. }
  19542. j = 0;
  19543. if( needQuote ) bufpt[j++] = q;
  19544. k = i;
  19545. for(i=0; i<k; i++){
  19546. bufpt[j++] = ch = escarg[i];
  19547. if( ch==q ) bufpt[j++] = ch;
  19548. }
  19549. if( needQuote ) bufpt[j++] = q;
  19550. bufpt[j] = 0;
  19551. length = j;
  19552. /* The precision in %q and %Q means how many input characters to
  19553. ** consume, not the length of the output...
  19554. ** if( precision>=0 && precision<length ) length = precision; */
  19555. break;
  19556. }
  19557. case etTOKEN: {
  19558. Token *pToken = va_arg(ap, Token*);
  19559. if( pToken ){
  19560. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  19561. }
  19562. length = width = 0;
  19563. break;
  19564. }
  19565. case etSRCLIST: {
  19566. SrcList *pSrc = va_arg(ap, SrcList*);
  19567. int k = va_arg(ap, int);
  19568. struct SrcList_item *pItem = &pSrc->a[k];
  19569. assert( k>=0 && k<pSrc->nSrc );
  19570. if( pItem->zDatabase ){
  19571. sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
  19572. sqlite3StrAccumAppend(pAccum, ".", 1);
  19573. }
  19574. sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
  19575. length = width = 0;
  19576. break;
  19577. }
  19578. default: {
  19579. assert( xtype==etINVALID );
  19580. return;
  19581. }
  19582. }/* End switch over the format type */
  19583. /*
  19584. ** The text of the conversion is pointed to by "bufpt" and is
  19585. ** "length" characters long. The field width is "width". Do
  19586. ** the output.
  19587. */
  19588. if( !flag_leftjustify ){
  19589. register int nspace;
  19590. nspace = width-length;
  19591. if( nspace>0 ){
  19592. sqlite3AppendSpace(pAccum, nspace);
  19593. }
  19594. }
  19595. if( length>0 ){
  19596. sqlite3StrAccumAppend(pAccum, bufpt, length);
  19597. }
  19598. if( flag_leftjustify ){
  19599. register int nspace;
  19600. nspace = width-length;
  19601. if( nspace>0 ){
  19602. sqlite3AppendSpace(pAccum, nspace);
  19603. }
  19604. }
  19605. sqlite3_free(zExtra);
  19606. }/* End for loop over the format string */
  19607. } /* End of function */
  19608. /*
  19609. ** Append N bytes of text from z to the StrAccum object.
  19610. */
  19611. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  19612. assert( z!=0 || N==0 );
  19613. if( p->accError ){
  19614. testcase(p->accError==STRACCUM_TOOBIG);
  19615. testcase(p->accError==STRACCUM_NOMEM);
  19616. return;
  19617. }
  19618. assert( p->zText!=0 || p->nChar==0 );
  19619. if( N<=0 ){
  19620. if( N==0 || z[0]==0 ) return;
  19621. N = sqlite3Strlen30(z);
  19622. }
  19623. if( p->nChar+N >= p->nAlloc ){
  19624. char *zNew;
  19625. if( !p->useMalloc ){
  19626. p->accError = STRACCUM_TOOBIG;
  19627. N = p->nAlloc - p->nChar - 1;
  19628. if( N<=0 ){
  19629. return;
  19630. }
  19631. }else{
  19632. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  19633. i64 szNew = p->nChar;
  19634. szNew += N + 1;
  19635. if( szNew > p->mxAlloc ){
  19636. sqlite3StrAccumReset(p);
  19637. p->accError = STRACCUM_TOOBIG;
  19638. return;
  19639. }else{
  19640. p->nAlloc = (int)szNew;
  19641. }
  19642. if( p->useMalloc==1 ){
  19643. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  19644. }else{
  19645. zNew = sqlite3_realloc(zOld, p->nAlloc);
  19646. }
  19647. if( zNew ){
  19648. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  19649. p->zText = zNew;
  19650. }else{
  19651. p->accError = STRACCUM_NOMEM;
  19652. sqlite3StrAccumReset(p);
  19653. return;
  19654. }
  19655. }
  19656. }
  19657. assert( p->zText );
  19658. memcpy(&p->zText[p->nChar], z, N);
  19659. p->nChar += N;
  19660. }
  19661. /*
  19662. ** Finish off a string by making sure it is zero-terminated.
  19663. ** Return a pointer to the resulting string. Return a NULL
  19664. ** pointer if any kind of error was encountered.
  19665. */
  19666. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  19667. if( p->zText ){
  19668. p->zText[p->nChar] = 0;
  19669. if( p->useMalloc && p->zText==p->zBase ){
  19670. if( p->useMalloc==1 ){
  19671. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  19672. }else{
  19673. p->zText = sqlite3_malloc(p->nChar+1);
  19674. }
  19675. if( p->zText ){
  19676. memcpy(p->zText, p->zBase, p->nChar+1);
  19677. }else{
  19678. p->accError = STRACCUM_NOMEM;
  19679. }
  19680. }
  19681. }
  19682. return p->zText;
  19683. }
  19684. /*
  19685. ** Reset an StrAccum string. Reclaim all malloced memory.
  19686. */
  19687. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  19688. if( p->zText!=p->zBase ){
  19689. if( p->useMalloc==1 ){
  19690. sqlite3DbFree(p->db, p->zText);
  19691. }else{
  19692. sqlite3_free(p->zText);
  19693. }
  19694. }
  19695. p->zText = 0;
  19696. }
  19697. /*
  19698. ** Initialize a string accumulator
  19699. */
  19700. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  19701. p->zText = p->zBase = zBase;
  19702. p->db = 0;
  19703. p->nChar = 0;
  19704. p->nAlloc = n;
  19705. p->mxAlloc = mx;
  19706. p->useMalloc = 1;
  19707. p->accError = 0;
  19708. }
  19709. /*
  19710. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19711. ** %-conversion extensions.
  19712. */
  19713. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  19714. char *z;
  19715. char zBase[SQLITE_PRINT_BUF_SIZE];
  19716. StrAccum acc;
  19717. assert( db!=0 );
  19718. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  19719. db->aLimit[SQLITE_LIMIT_LENGTH]);
  19720. acc.db = db;
  19721. sqlite3VXPrintf(&acc, 1, zFormat, ap);
  19722. z = sqlite3StrAccumFinish(&acc);
  19723. if( acc.accError==STRACCUM_NOMEM ){
  19724. db->mallocFailed = 1;
  19725. }
  19726. return z;
  19727. }
  19728. /*
  19729. ** Print into memory obtained from sqliteMalloc(). Use the internal
  19730. ** %-conversion extensions.
  19731. */
  19732. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  19733. va_list ap;
  19734. char *z;
  19735. va_start(ap, zFormat);
  19736. z = sqlite3VMPrintf(db, zFormat, ap);
  19737. va_end(ap);
  19738. return z;
  19739. }
  19740. /*
  19741. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  19742. ** the string and before returnning. This routine is intended to be used
  19743. ** to modify an existing string. For example:
  19744. **
  19745. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  19746. **
  19747. */
  19748. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  19749. va_list ap;
  19750. char *z;
  19751. va_start(ap, zFormat);
  19752. z = sqlite3VMPrintf(db, zFormat, ap);
  19753. va_end(ap);
  19754. sqlite3DbFree(db, zStr);
  19755. return z;
  19756. }
  19757. /*
  19758. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  19759. ** %-conversion extensions.
  19760. */
  19761. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  19762. char *z;
  19763. char zBase[SQLITE_PRINT_BUF_SIZE];
  19764. StrAccum acc;
  19765. #ifndef SQLITE_OMIT_AUTOINIT
  19766. if( sqlite3_initialize() ) return 0;
  19767. #endif
  19768. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  19769. acc.useMalloc = 2;
  19770. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19771. z = sqlite3StrAccumFinish(&acc);
  19772. return z;
  19773. }
  19774. /*
  19775. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  19776. ** %-conversion extensions.
  19777. */
  19778. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  19779. va_list ap;
  19780. char *z;
  19781. #ifndef SQLITE_OMIT_AUTOINIT
  19782. if( sqlite3_initialize() ) return 0;
  19783. #endif
  19784. va_start(ap, zFormat);
  19785. z = sqlite3_vmprintf(zFormat, ap);
  19786. va_end(ap);
  19787. return z;
  19788. }
  19789. /*
  19790. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  19791. ** current locale settings. This is important for SQLite because we
  19792. ** are not able to use a "," as the decimal point in place of "." as
  19793. ** specified by some locales.
  19794. **
  19795. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  19796. ** from the snprintf() standard. Unfortunately, it is too late to change
  19797. ** this without breaking compatibility, so we just have to live with the
  19798. ** mistake.
  19799. **
  19800. ** sqlite3_vsnprintf() is the varargs version.
  19801. */
  19802. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  19803. StrAccum acc;
  19804. if( n<=0 ) return zBuf;
  19805. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  19806. acc.useMalloc = 0;
  19807. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19808. return sqlite3StrAccumFinish(&acc);
  19809. }
  19810. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  19811. char *z;
  19812. va_list ap;
  19813. va_start(ap,zFormat);
  19814. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  19815. va_end(ap);
  19816. return z;
  19817. }
  19818. /*
  19819. ** This is the routine that actually formats the sqlite3_log() message.
  19820. ** We house it in a separate routine from sqlite3_log() to avoid using
  19821. ** stack space on small-stack systems when logging is disabled.
  19822. **
  19823. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  19824. ** allocate memory because it might be called while the memory allocator
  19825. ** mutex is held.
  19826. */
  19827. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  19828. StrAccum acc; /* String accumulator */
  19829. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  19830. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  19831. acc.useMalloc = 0;
  19832. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19833. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  19834. sqlite3StrAccumFinish(&acc));
  19835. }
  19836. /*
  19837. ** Format and write a message to the log if logging is enabled.
  19838. */
  19839. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  19840. va_list ap; /* Vararg list */
  19841. if( sqlite3GlobalConfig.xLog ){
  19842. va_start(ap, zFormat);
  19843. renderLogMsg(iErrCode, zFormat, ap);
  19844. va_end(ap);
  19845. }
  19846. }
  19847. #if defined(SQLITE_DEBUG)
  19848. /*
  19849. ** A version of printf() that understands %lld. Used for debugging.
  19850. ** The printf() built into some versions of windows does not understand %lld
  19851. ** and segfaults if you give it a long long int.
  19852. */
  19853. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  19854. va_list ap;
  19855. StrAccum acc;
  19856. char zBuf[500];
  19857. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  19858. acc.useMalloc = 0;
  19859. va_start(ap,zFormat);
  19860. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  19861. va_end(ap);
  19862. sqlite3StrAccumFinish(&acc);
  19863. fprintf(stdout,"%s", zBuf);
  19864. fflush(stdout);
  19865. }
  19866. #endif
  19867. #ifndef SQLITE_OMIT_TRACE
  19868. /*
  19869. ** variable-argument wrapper around sqlite3VXPrintf().
  19870. */
  19871. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
  19872. va_list ap;
  19873. va_start(ap,zFormat);
  19874. sqlite3VXPrintf(p, 1, zFormat, ap);
  19875. va_end(ap);
  19876. }
  19877. #endif
  19878. /************** End of printf.c **********************************************/
  19879. /************** Begin file random.c ******************************************/
  19880. /*
  19881. ** 2001 September 15
  19882. **
  19883. ** The author disclaims copyright to this source code. In place of
  19884. ** a legal notice, here is a blessing:
  19885. **
  19886. ** May you do good and not evil.
  19887. ** May you find forgiveness for yourself and forgive others.
  19888. ** May you share freely, never taking more than you give.
  19889. **
  19890. *************************************************************************
  19891. ** This file contains code to implement a pseudo-random number
  19892. ** generator (PRNG) for SQLite.
  19893. **
  19894. ** Random numbers are used by some of the database backends in order
  19895. ** to generate random integer keys for tables or random filenames.
  19896. */
  19897. /* All threads share a single random number generator.
  19898. ** This structure is the current state of the generator.
  19899. */
  19900. static SQLITE_WSD struct sqlite3PrngType {
  19901. unsigned char isInit; /* True if initialized */
  19902. unsigned char i, j; /* State variables */
  19903. unsigned char s[256]; /* State variables */
  19904. } sqlite3Prng;
  19905. /*
  19906. ** Return N random bytes.
  19907. */
  19908. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  19909. unsigned char t;
  19910. unsigned char *zBuf = pBuf;
  19911. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  19912. ** state vector. If writable static data is unsupported on the target,
  19913. ** we have to locate the state vector at run-time. In the more common
  19914. ** case where writable static data is supported, wsdPrng can refer directly
  19915. ** to the "sqlite3Prng" state vector declared above.
  19916. */
  19917. #ifdef SQLITE_OMIT_WSD
  19918. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  19919. # define wsdPrng p[0]
  19920. #else
  19921. # define wsdPrng sqlite3Prng
  19922. #endif
  19923. #if SQLITE_THREADSAFE
  19924. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  19925. sqlite3_mutex_enter(mutex);
  19926. #endif
  19927. /* Initialize the state of the random number generator once,
  19928. ** the first time this routine is called. The seed value does
  19929. ** not need to contain a lot of randomness since we are not
  19930. ** trying to do secure encryption or anything like that...
  19931. **
  19932. ** Nothing in this file or anywhere else in SQLite does any kind of
  19933. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  19934. ** number generator) not as an encryption device.
  19935. */
  19936. if( !wsdPrng.isInit ){
  19937. int i;
  19938. char k[256];
  19939. wsdPrng.j = 0;
  19940. wsdPrng.i = 0;
  19941. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  19942. for(i=0; i<256; i++){
  19943. wsdPrng.s[i] = (u8)i;
  19944. }
  19945. for(i=0; i<256; i++){
  19946. wsdPrng.j += wsdPrng.s[i] + k[i];
  19947. t = wsdPrng.s[wsdPrng.j];
  19948. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  19949. wsdPrng.s[i] = t;
  19950. }
  19951. wsdPrng.isInit = 1;
  19952. }
  19953. while( N-- ){
  19954. wsdPrng.i++;
  19955. t = wsdPrng.s[wsdPrng.i];
  19956. wsdPrng.j += t;
  19957. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  19958. wsdPrng.s[wsdPrng.j] = t;
  19959. t += wsdPrng.s[wsdPrng.i];
  19960. *(zBuf++) = wsdPrng.s[t];
  19961. }
  19962. sqlite3_mutex_leave(mutex);
  19963. }
  19964. #ifndef SQLITE_OMIT_BUILTIN_TEST
  19965. /*
  19966. ** For testing purposes, we sometimes want to preserve the state of
  19967. ** PRNG and restore the PRNG to its saved state at a later time, or
  19968. ** to reset the PRNG to its initial state. These routines accomplish
  19969. ** those tasks.
  19970. **
  19971. ** The sqlite3_test_control() interface calls these routines to
  19972. ** control the PRNG.
  19973. */
  19974. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  19975. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  19976. memcpy(
  19977. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19978. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19979. sizeof(sqlite3Prng)
  19980. );
  19981. }
  19982. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  19983. memcpy(
  19984. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  19985. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  19986. sizeof(sqlite3Prng)
  19987. );
  19988. }
  19989. SQLITE_PRIVATE void sqlite3PrngResetState(void){
  19990. GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
  19991. }
  19992. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  19993. /************** End of random.c **********************************************/
  19994. /************** Begin file utf.c *********************************************/
  19995. /*
  19996. ** 2004 April 13
  19997. **
  19998. ** The author disclaims copyright to this source code. In place of
  19999. ** a legal notice, here is a blessing:
  20000. **
  20001. ** May you do good and not evil.
  20002. ** May you find forgiveness for yourself and forgive others.
  20003. ** May you share freely, never taking more than you give.
  20004. **
  20005. *************************************************************************
  20006. ** This file contains routines used to translate between UTF-8,
  20007. ** UTF-16, UTF-16BE, and UTF-16LE.
  20008. **
  20009. ** Notes on UTF-8:
  20010. **
  20011. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  20012. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  20013. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  20014. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  20015. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  20016. **
  20017. **
  20018. ** Notes on UTF-16: (with wwww+1==uuuuu)
  20019. **
  20020. ** Word-0 Word-1 Value
  20021. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  20022. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  20023. **
  20024. **
  20025. ** BOM or Byte Order Mark:
  20026. ** 0xff 0xfe little-endian utf-16 follows
  20027. ** 0xfe 0xff big-endian utf-16 follows
  20028. **
  20029. */
  20030. /* #include <assert.h> */
  20031. #ifndef SQLITE_AMALGAMATION
  20032. /*
  20033. ** The following constant value is used by the SQLITE_BIGENDIAN and
  20034. ** SQLITE_LITTLEENDIAN macros.
  20035. */
  20036. SQLITE_PRIVATE const int sqlite3one = 1;
  20037. #endif /* SQLITE_AMALGAMATION */
  20038. /*
  20039. ** This lookup table is used to help decode the first byte of
  20040. ** a multi-byte UTF8 character.
  20041. */
  20042. static const unsigned char sqlite3Utf8Trans1[] = {
  20043. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20044. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  20045. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  20046. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  20047. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20048. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  20049. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  20050. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  20051. };
  20052. #define WRITE_UTF8(zOut, c) { \
  20053. if( c<0x00080 ){ \
  20054. *zOut++ = (u8)(c&0xFF); \
  20055. } \
  20056. else if( c<0x00800 ){ \
  20057. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  20058. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20059. } \
  20060. else if( c<0x10000 ){ \
  20061. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  20062. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  20063. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20064. }else{ \
  20065. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  20066. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  20067. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  20068. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  20069. } \
  20070. }
  20071. #define WRITE_UTF16LE(zOut, c) { \
  20072. if( c<=0xFFFF ){ \
  20073. *zOut++ = (u8)(c&0x00FF); \
  20074. *zOut++ = (u8)((c>>8)&0x00FF); \
  20075. }else{ \
  20076. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  20077. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  20078. *zOut++ = (u8)(c&0x00FF); \
  20079. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  20080. } \
  20081. }
  20082. #define WRITE_UTF16BE(zOut, c) { \
  20083. if( c<=0xFFFF ){ \
  20084. *zOut++ = (u8)((c>>8)&0x00FF); \
  20085. *zOut++ = (u8)(c&0x00FF); \
  20086. }else{ \
  20087. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  20088. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  20089. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  20090. *zOut++ = (u8)(c&0x00FF); \
  20091. } \
  20092. }
  20093. #define READ_UTF16LE(zIn, TERM, c){ \
  20094. c = (*zIn++); \
  20095. c += ((*zIn++)<<8); \
  20096. if( c>=0xD800 && c<0xE000 && TERM ){ \
  20097. int c2 = (*zIn++); \
  20098. c2 += ((*zIn++)<<8); \
  20099. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  20100. } \
  20101. }
  20102. #define READ_UTF16BE(zIn, TERM, c){ \
  20103. c = ((*zIn++)<<8); \
  20104. c += (*zIn++); \
  20105. if( c>=0xD800 && c<0xE000 && TERM ){ \
  20106. int c2 = ((*zIn++)<<8); \
  20107. c2 += (*zIn++); \
  20108. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  20109. } \
  20110. }
  20111. /*
  20112. ** Translate a single UTF-8 character. Return the unicode value.
  20113. **
  20114. ** During translation, assume that the byte that zTerm points
  20115. ** is a 0x00.
  20116. **
  20117. ** Write a pointer to the next unread byte back into *pzNext.
  20118. **
  20119. ** Notes On Invalid UTF-8:
  20120. **
  20121. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  20122. ** be encoded as a multi-byte character. Any multi-byte character that
  20123. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  20124. **
  20125. ** * This routine never allows a UTF16 surrogate value to be encoded.
  20126. ** If a multi-byte character attempts to encode a value between
  20127. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  20128. **
  20129. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  20130. ** byte of a character are interpreted as single-byte characters
  20131. ** and rendered as themselves even though they are technically
  20132. ** invalid characters.
  20133. **
  20134. ** * This routine accepts an infinite number of different UTF8 encodings
  20135. ** for unicode values 0x80 and greater. It do not change over-length
  20136. ** encodings to 0xfffd as some systems recommend.
  20137. */
  20138. #define READ_UTF8(zIn, zTerm, c) \
  20139. c = *(zIn++); \
  20140. if( c>=0xc0 ){ \
  20141. c = sqlite3Utf8Trans1[c-0xc0]; \
  20142. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  20143. c = (c<<6) + (0x3f & *(zIn++)); \
  20144. } \
  20145. if( c<0x80 \
  20146. || (c&0xFFFFF800)==0xD800 \
  20147. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  20148. }
  20149. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  20150. const unsigned char **pz /* Pointer to string from which to read char */
  20151. ){
  20152. unsigned int c;
  20153. /* Same as READ_UTF8() above but without the zTerm parameter.
  20154. ** For this routine, we assume the UTF8 string is always zero-terminated.
  20155. */
  20156. c = *((*pz)++);
  20157. if( c>=0xc0 ){
  20158. c = sqlite3Utf8Trans1[c-0xc0];
  20159. while( (*(*pz) & 0xc0)==0x80 ){
  20160. c = (c<<6) + (0x3f & *((*pz)++));
  20161. }
  20162. if( c<0x80
  20163. || (c&0xFFFFF800)==0xD800
  20164. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  20165. }
  20166. return c;
  20167. }
  20168. /*
  20169. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  20170. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  20171. */
  20172. /* #define TRANSLATE_TRACE 1 */
  20173. #ifndef SQLITE_OMIT_UTF16
  20174. /*
  20175. ** This routine transforms the internal text encoding used by pMem to
  20176. ** desiredEnc. It is an error if the string is already of the desired
  20177. ** encoding, or if *pMem does not contain a string value.
  20178. */
  20179. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  20180. int len; /* Maximum length of output string in bytes */
  20181. unsigned char *zOut; /* Output buffer */
  20182. unsigned char *zIn; /* Input iterator */
  20183. unsigned char *zTerm; /* End of input */
  20184. unsigned char *z; /* Output iterator */
  20185. unsigned int c;
  20186. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  20187. assert( pMem->flags&MEM_Str );
  20188. assert( pMem->enc!=desiredEnc );
  20189. assert( pMem->enc!=0 );
  20190. assert( pMem->n>=0 );
  20191. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  20192. {
  20193. char zBuf[100];
  20194. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  20195. fprintf(stderr, "INPUT: %s\n", zBuf);
  20196. }
  20197. #endif
  20198. /* If the translation is between UTF-16 little and big endian, then
  20199. ** all that is required is to swap the byte order. This case is handled
  20200. ** differently from the others.
  20201. */
  20202. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  20203. u8 temp;
  20204. int rc;
  20205. rc = sqlite3VdbeMemMakeWriteable(pMem);
  20206. if( rc!=SQLITE_OK ){
  20207. assert( rc==SQLITE_NOMEM );
  20208. return SQLITE_NOMEM;
  20209. }
  20210. zIn = (u8*)pMem->z;
  20211. zTerm = &zIn[pMem->n&~1];
  20212. while( zIn<zTerm ){
  20213. temp = *zIn;
  20214. *zIn = *(zIn+1);
  20215. zIn++;
  20216. *zIn++ = temp;
  20217. }
  20218. pMem->enc = desiredEnc;
  20219. goto translate_out;
  20220. }
  20221. /* Set len to the maximum number of bytes required in the output buffer. */
  20222. if( desiredEnc==SQLITE_UTF8 ){
  20223. /* When converting from UTF-16, the maximum growth results from
  20224. ** translating a 2-byte character to a 4-byte UTF-8 character.
  20225. ** A single byte is required for the output string
  20226. ** nul-terminator.
  20227. */
  20228. pMem->n &= ~1;
  20229. len = pMem->n * 2 + 1;
  20230. }else{
  20231. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  20232. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  20233. ** character. Two bytes are required in the output buffer for the
  20234. ** nul-terminator.
  20235. */
  20236. len = pMem->n * 2 + 2;
  20237. }
  20238. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  20239. ** byte past the end.
  20240. **
  20241. ** Variable zOut is set to point at the output buffer, space obtained
  20242. ** from sqlite3_malloc().
  20243. */
  20244. zIn = (u8*)pMem->z;
  20245. zTerm = &zIn[pMem->n];
  20246. zOut = sqlite3DbMallocRaw(pMem->db, len);
  20247. if( !zOut ){
  20248. return SQLITE_NOMEM;
  20249. }
  20250. z = zOut;
  20251. if( pMem->enc==SQLITE_UTF8 ){
  20252. if( desiredEnc==SQLITE_UTF16LE ){
  20253. /* UTF-8 -> UTF-16 Little-endian */
  20254. while( zIn<zTerm ){
  20255. READ_UTF8(zIn, zTerm, c);
  20256. WRITE_UTF16LE(z, c);
  20257. }
  20258. }else{
  20259. assert( desiredEnc==SQLITE_UTF16BE );
  20260. /* UTF-8 -> UTF-16 Big-endian */
  20261. while( zIn<zTerm ){
  20262. READ_UTF8(zIn, zTerm, c);
  20263. WRITE_UTF16BE(z, c);
  20264. }
  20265. }
  20266. pMem->n = (int)(z - zOut);
  20267. *z++ = 0;
  20268. }else{
  20269. assert( desiredEnc==SQLITE_UTF8 );
  20270. if( pMem->enc==SQLITE_UTF16LE ){
  20271. /* UTF-16 Little-endian -> UTF-8 */
  20272. while( zIn<zTerm ){
  20273. READ_UTF16LE(zIn, zIn<zTerm, c);
  20274. WRITE_UTF8(z, c);
  20275. }
  20276. }else{
  20277. /* UTF-16 Big-endian -> UTF-8 */
  20278. while( zIn<zTerm ){
  20279. READ_UTF16BE(zIn, zIn<zTerm, c);
  20280. WRITE_UTF8(z, c);
  20281. }
  20282. }
  20283. pMem->n = (int)(z - zOut);
  20284. }
  20285. *z = 0;
  20286. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  20287. sqlite3VdbeMemRelease(pMem);
  20288. pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
  20289. pMem->enc = desiredEnc;
  20290. pMem->flags |= (MEM_Term|MEM_Dyn);
  20291. pMem->z = (char*)zOut;
  20292. pMem->zMalloc = pMem->z;
  20293. translate_out:
  20294. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  20295. {
  20296. char zBuf[100];
  20297. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  20298. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  20299. }
  20300. #endif
  20301. return SQLITE_OK;
  20302. }
  20303. /*
  20304. ** This routine checks for a byte-order mark at the beginning of the
  20305. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  20306. ** the encoding of the Mem adjusted. This routine does not do any
  20307. ** byte-swapping, it just sets Mem.enc appropriately.
  20308. **
  20309. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  20310. ** changed by this function.
  20311. */
  20312. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  20313. int rc = SQLITE_OK;
  20314. u8 bom = 0;
  20315. assert( pMem->n>=0 );
  20316. if( pMem->n>1 ){
  20317. u8 b1 = *(u8 *)pMem->z;
  20318. u8 b2 = *(((u8 *)pMem->z) + 1);
  20319. if( b1==0xFE && b2==0xFF ){
  20320. bom = SQLITE_UTF16BE;
  20321. }
  20322. if( b1==0xFF && b2==0xFE ){
  20323. bom = SQLITE_UTF16LE;
  20324. }
  20325. }
  20326. if( bom ){
  20327. rc = sqlite3VdbeMemMakeWriteable(pMem);
  20328. if( rc==SQLITE_OK ){
  20329. pMem->n -= 2;
  20330. memmove(pMem->z, &pMem->z[2], pMem->n);
  20331. pMem->z[pMem->n] = '\0';
  20332. pMem->z[pMem->n+1] = '\0';
  20333. pMem->flags |= MEM_Term;
  20334. pMem->enc = bom;
  20335. }
  20336. }
  20337. return rc;
  20338. }
  20339. #endif /* SQLITE_OMIT_UTF16 */
  20340. /*
  20341. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  20342. ** return the number of unicode characters in pZ up to (but not including)
  20343. ** the first 0x00 byte. If nByte is not less than zero, return the
  20344. ** number of unicode characters in the first nByte of pZ (or up to
  20345. ** the first 0x00, whichever comes first).
  20346. */
  20347. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  20348. int r = 0;
  20349. const u8 *z = (const u8*)zIn;
  20350. const u8 *zTerm;
  20351. if( nByte>=0 ){
  20352. zTerm = &z[nByte];
  20353. }else{
  20354. zTerm = (const u8*)(-1);
  20355. }
  20356. assert( z<=zTerm );
  20357. while( *z!=0 && z<zTerm ){
  20358. SQLITE_SKIP_UTF8(z);
  20359. r++;
  20360. }
  20361. return r;
  20362. }
  20363. /* This test function is not currently used by the automated test-suite.
  20364. ** Hence it is only available in debug builds.
  20365. */
  20366. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  20367. /*
  20368. ** Translate UTF-8 to UTF-8.
  20369. **
  20370. ** This has the effect of making sure that the string is well-formed
  20371. ** UTF-8. Miscoded characters are removed.
  20372. **
  20373. ** The translation is done in-place and aborted if the output
  20374. ** overruns the input.
  20375. */
  20376. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  20377. unsigned char *zOut = zIn;
  20378. unsigned char *zStart = zIn;
  20379. u32 c;
  20380. while( zIn[0] && zOut<=zIn ){
  20381. c = sqlite3Utf8Read((const u8**)&zIn);
  20382. if( c!=0xfffd ){
  20383. WRITE_UTF8(zOut, c);
  20384. }
  20385. }
  20386. *zOut = 0;
  20387. return (int)(zOut - zStart);
  20388. }
  20389. #endif
  20390. #ifndef SQLITE_OMIT_UTF16
  20391. /*
  20392. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  20393. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  20394. ** be freed by the calling function.
  20395. **
  20396. ** NULL is returned if there is an allocation error.
  20397. */
  20398. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  20399. Mem m;
  20400. memset(&m, 0, sizeof(m));
  20401. m.db = db;
  20402. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  20403. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  20404. if( db->mallocFailed ){
  20405. sqlite3VdbeMemRelease(&m);
  20406. m.z = 0;
  20407. }
  20408. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  20409. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  20410. assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
  20411. assert( m.z || db->mallocFailed );
  20412. return m.z;
  20413. }
  20414. /*
  20415. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  20416. ** Return the number of bytes in the first nChar unicode characters
  20417. ** in pZ. nChar must be non-negative.
  20418. */
  20419. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  20420. int c;
  20421. unsigned char const *z = zIn;
  20422. int n = 0;
  20423. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  20424. while( n<nChar ){
  20425. READ_UTF16BE(z, 1, c);
  20426. n++;
  20427. }
  20428. }else{
  20429. while( n<nChar ){
  20430. READ_UTF16LE(z, 1, c);
  20431. n++;
  20432. }
  20433. }
  20434. return (int)(z-(unsigned char const *)zIn);
  20435. }
  20436. #if defined(SQLITE_TEST)
  20437. /*
  20438. ** This routine is called from the TCL test function "translate_selftest".
  20439. ** It checks that the primitives for serializing and deserializing
  20440. ** characters in each encoding are inverses of each other.
  20441. */
  20442. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  20443. unsigned int i, t;
  20444. unsigned char zBuf[20];
  20445. unsigned char *z;
  20446. int n;
  20447. unsigned int c;
  20448. for(i=0; i<0x00110000; i++){
  20449. z = zBuf;
  20450. WRITE_UTF8(z, i);
  20451. n = (int)(z-zBuf);
  20452. assert( n>0 && n<=4 );
  20453. z[0] = 0;
  20454. z = zBuf;
  20455. c = sqlite3Utf8Read((const u8**)&z);
  20456. t = i;
  20457. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  20458. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  20459. assert( c==t );
  20460. assert( (z-zBuf)==n );
  20461. }
  20462. for(i=0; i<0x00110000; i++){
  20463. if( i>=0xD800 && i<0xE000 ) continue;
  20464. z = zBuf;
  20465. WRITE_UTF16LE(z, i);
  20466. n = (int)(z-zBuf);
  20467. assert( n>0 && n<=4 );
  20468. z[0] = 0;
  20469. z = zBuf;
  20470. READ_UTF16LE(z, 1, c);
  20471. assert( c==i );
  20472. assert( (z-zBuf)==n );
  20473. }
  20474. for(i=0; i<0x00110000; i++){
  20475. if( i>=0xD800 && i<0xE000 ) continue;
  20476. z = zBuf;
  20477. WRITE_UTF16BE(z, i);
  20478. n = (int)(z-zBuf);
  20479. assert( n>0 && n<=4 );
  20480. z[0] = 0;
  20481. z = zBuf;
  20482. READ_UTF16BE(z, 1, c);
  20483. assert( c==i );
  20484. assert( (z-zBuf)==n );
  20485. }
  20486. }
  20487. #endif /* SQLITE_TEST */
  20488. #endif /* SQLITE_OMIT_UTF16 */
  20489. /************** End of utf.c *************************************************/
  20490. /************** Begin file util.c ********************************************/
  20491. /*
  20492. ** 2001 September 15
  20493. **
  20494. ** The author disclaims copyright to this source code. In place of
  20495. ** a legal notice, here is a blessing:
  20496. **
  20497. ** May you do good and not evil.
  20498. ** May you find forgiveness for yourself and forgive others.
  20499. ** May you share freely, never taking more than you give.
  20500. **
  20501. *************************************************************************
  20502. ** Utility functions used throughout sqlite.
  20503. **
  20504. ** This file contains functions for allocating memory, comparing
  20505. ** strings, and stuff like that.
  20506. **
  20507. */
  20508. /* #include <stdarg.h> */
  20509. #ifdef SQLITE_HAVE_ISNAN
  20510. # include <math.h>
  20511. #endif
  20512. /*
  20513. ** Routine needed to support the testcase() macro.
  20514. */
  20515. #ifdef SQLITE_COVERAGE_TEST
  20516. SQLITE_PRIVATE void sqlite3Coverage(int x){
  20517. static unsigned dummy = 0;
  20518. dummy += (unsigned)x;
  20519. }
  20520. #endif
  20521. #ifndef SQLITE_OMIT_FLOATING_POINT
  20522. /*
  20523. ** Return true if the floating point value is Not a Number (NaN).
  20524. **
  20525. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  20526. ** Otherwise, we have our own implementation that works on most systems.
  20527. */
  20528. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  20529. int rc; /* The value return */
  20530. #if !defined(SQLITE_HAVE_ISNAN)
  20531. /*
  20532. ** Systems that support the isnan() library function should probably
  20533. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  20534. ** found that many systems do not have a working isnan() function so
  20535. ** this implementation is provided as an alternative.
  20536. **
  20537. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  20538. ** On the other hand, the use of -ffast-math comes with the following
  20539. ** warning:
  20540. **
  20541. ** This option [-ffast-math] should never be turned on by any
  20542. ** -O option since it can result in incorrect output for programs
  20543. ** which depend on an exact implementation of IEEE or ISO
  20544. ** rules/specifications for math functions.
  20545. **
  20546. ** Under MSVC, this NaN test may fail if compiled with a floating-
  20547. ** point precision mode other than /fp:precise. From the MSDN
  20548. ** documentation:
  20549. **
  20550. ** The compiler [with /fp:precise] will properly handle comparisons
  20551. ** involving NaN. For example, x != x evaluates to true if x is NaN
  20552. ** ...
  20553. */
  20554. #ifdef __FAST_MATH__
  20555. # error SQLite will not work correctly with the -ffast-math option of GCC.
  20556. #endif
  20557. volatile double y = x;
  20558. volatile double z = y;
  20559. rc = (y!=z);
  20560. #else /* if defined(SQLITE_HAVE_ISNAN) */
  20561. rc = isnan(x);
  20562. #endif /* SQLITE_HAVE_ISNAN */
  20563. testcase( rc );
  20564. return rc;
  20565. }
  20566. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20567. /*
  20568. ** Compute a string length that is limited to what can be stored in
  20569. ** lower 30 bits of a 32-bit signed integer.
  20570. **
  20571. ** The value returned will never be negative. Nor will it ever be greater
  20572. ** than the actual length of the string. For very long strings (greater
  20573. ** than 1GiB) the value returned might be less than the true string length.
  20574. */
  20575. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  20576. const char *z2 = z;
  20577. if( z==0 ) return 0;
  20578. while( *z2 ){ z2++; }
  20579. return 0x3fffffff & (int)(z2 - z);
  20580. }
  20581. /*
  20582. ** Set the most recent error code and error string for the sqlite
  20583. ** handle "db". The error code is set to "err_code".
  20584. **
  20585. ** If it is not NULL, string zFormat specifies the format of the
  20586. ** error string in the style of the printf functions: The following
  20587. ** format characters are allowed:
  20588. **
  20589. ** %s Insert a string
  20590. ** %z A string that should be freed after use
  20591. ** %d Insert an integer
  20592. ** %T Insert a token
  20593. ** %S Insert the first element of a SrcList
  20594. **
  20595. ** zFormat and any string tokens that follow it are assumed to be
  20596. ** encoded in UTF-8.
  20597. **
  20598. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  20599. ** should be called with err_code set to SQLITE_OK and zFormat set
  20600. ** to NULL.
  20601. */
  20602. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
  20603. if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
  20604. db->errCode = err_code;
  20605. if( zFormat ){
  20606. char *z;
  20607. va_list ap;
  20608. va_start(ap, zFormat);
  20609. z = sqlite3VMPrintf(db, zFormat, ap);
  20610. va_end(ap);
  20611. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  20612. }else{
  20613. sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
  20614. }
  20615. }
  20616. }
  20617. /*
  20618. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  20619. ** The following formatting characters are allowed:
  20620. **
  20621. ** %s Insert a string
  20622. ** %z A string that should be freed after use
  20623. ** %d Insert an integer
  20624. ** %T Insert a token
  20625. ** %S Insert the first element of a SrcList
  20626. **
  20627. ** This function should be used to report any error that occurs whilst
  20628. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  20629. ** last thing the sqlite3_prepare() function does is copy the error
  20630. ** stored by this function into the database handle using sqlite3Error().
  20631. ** Function sqlite3Error() should be used during statement execution
  20632. ** (sqlite3_step() etc.).
  20633. */
  20634. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  20635. char *zMsg;
  20636. va_list ap;
  20637. sqlite3 *db = pParse->db;
  20638. va_start(ap, zFormat);
  20639. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  20640. va_end(ap);
  20641. if( db->suppressErr ){
  20642. sqlite3DbFree(db, zMsg);
  20643. }else{
  20644. pParse->nErr++;
  20645. sqlite3DbFree(db, pParse->zErrMsg);
  20646. pParse->zErrMsg = zMsg;
  20647. pParse->rc = SQLITE_ERROR;
  20648. }
  20649. }
  20650. /*
  20651. ** Convert an SQL-style quoted string into a normal string by removing
  20652. ** the quote characters. The conversion is done in-place. If the
  20653. ** input does not begin with a quote character, then this routine
  20654. ** is a no-op.
  20655. **
  20656. ** The input string must be zero-terminated. A new zero-terminator
  20657. ** is added to the dequoted string.
  20658. **
  20659. ** The return value is -1 if no dequoting occurs or the length of the
  20660. ** dequoted string, exclusive of the zero terminator, if dequoting does
  20661. ** occur.
  20662. **
  20663. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  20664. ** brackets from around identifers. For example: "[a-b-c]" becomes
  20665. ** "a-b-c".
  20666. */
  20667. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  20668. char quote;
  20669. int i, j;
  20670. if( z==0 ) return -1;
  20671. quote = z[0];
  20672. switch( quote ){
  20673. case '\'': break;
  20674. case '"': break;
  20675. case '`': break; /* For MySQL compatibility */
  20676. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  20677. default: return -1;
  20678. }
  20679. for(i=1, j=0;; i++){
  20680. assert( z[i] );
  20681. if( z[i]==quote ){
  20682. if( z[i+1]==quote ){
  20683. z[j++] = quote;
  20684. i++;
  20685. }else{
  20686. break;
  20687. }
  20688. }else{
  20689. z[j++] = z[i];
  20690. }
  20691. }
  20692. z[j] = 0;
  20693. return j;
  20694. }
  20695. /* Convenient short-hand */
  20696. #define UpperToLower sqlite3UpperToLower
  20697. /*
  20698. ** Some systems have stricmp(). Others have strcasecmp(). Because
  20699. ** there is no consistency, we will define our own.
  20700. **
  20701. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  20702. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  20703. ** the contents of two buffers containing UTF-8 strings in a
  20704. ** case-independent fashion, using the same definition of "case
  20705. ** independence" that SQLite uses internally when comparing identifiers.
  20706. */
  20707. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  20708. register unsigned char *a, *b;
  20709. a = (unsigned char *)zLeft;
  20710. b = (unsigned char *)zRight;
  20711. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20712. return UpperToLower[*a] - UpperToLower[*b];
  20713. }
  20714. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  20715. register unsigned char *a, *b;
  20716. a = (unsigned char *)zLeft;
  20717. b = (unsigned char *)zRight;
  20718. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  20719. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  20720. }
  20721. /*
  20722. ** The string z[] is an text representation of a real number.
  20723. ** Convert this string to a double and write it into *pResult.
  20724. **
  20725. ** The string z[] is length bytes in length (bytes, not characters) and
  20726. ** uses the encoding enc. The string is not necessarily zero-terminated.
  20727. **
  20728. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  20729. ** if the string is empty or contains extraneous text. Valid numbers
  20730. ** are in one of these formats:
  20731. **
  20732. ** [+-]digits[E[+-]digits]
  20733. ** [+-]digits.[digits][E[+-]digits]
  20734. ** [+-].digits[E[+-]digits]
  20735. **
  20736. ** Leading and trailing whitespace is ignored for the purpose of determining
  20737. ** validity.
  20738. **
  20739. ** If some prefix of the input string is a valid number, this routine
  20740. ** returns FALSE but it still converts the prefix and writes the result
  20741. ** into *pResult.
  20742. */
  20743. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  20744. #ifndef SQLITE_OMIT_FLOATING_POINT
  20745. int incr;
  20746. const char *zEnd = z + length;
  20747. /* sign * significand * (10 ^ (esign * exponent)) */
  20748. int sign = 1; /* sign of significand */
  20749. i64 s = 0; /* significand */
  20750. int d = 0; /* adjust exponent for shifting decimal point */
  20751. int esign = 1; /* sign of exponent */
  20752. int e = 0; /* exponent */
  20753. int eValid = 1; /* True exponent is either not used or is well-formed */
  20754. double result;
  20755. int nDigits = 0;
  20756. int nonNum = 0;
  20757. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20758. *pResult = 0.0; /* Default return value, in case of an error */
  20759. if( enc==SQLITE_UTF8 ){
  20760. incr = 1;
  20761. }else{
  20762. int i;
  20763. incr = 2;
  20764. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20765. for(i=3-enc; i<length && z[i]==0; i+=2){}
  20766. nonNum = i<length;
  20767. zEnd = z+i+enc-3;
  20768. z += (enc&1);
  20769. }
  20770. /* skip leading spaces */
  20771. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20772. if( z>=zEnd ) return 0;
  20773. /* get sign of significand */
  20774. if( *z=='-' ){
  20775. sign = -1;
  20776. z+=incr;
  20777. }else if( *z=='+' ){
  20778. z+=incr;
  20779. }
  20780. /* skip leading zeroes */
  20781. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  20782. /* copy max significant digits to significand */
  20783. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20784. s = s*10 + (*z - '0');
  20785. z+=incr, nDigits++;
  20786. }
  20787. /* skip non-significant significand digits
  20788. ** (increase exponent by d to shift decimal left) */
  20789. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  20790. if( z>=zEnd ) goto do_atof_calc;
  20791. /* if decimal point is present */
  20792. if( *z=='.' ){
  20793. z+=incr;
  20794. /* copy digits from after decimal to significand
  20795. ** (decrease exponent by d to shift decimal right) */
  20796. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  20797. s = s*10 + (*z - '0');
  20798. z+=incr, nDigits++, d--;
  20799. }
  20800. /* skip non-significant digits */
  20801. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  20802. }
  20803. if( z>=zEnd ) goto do_atof_calc;
  20804. /* if exponent is present */
  20805. if( *z=='e' || *z=='E' ){
  20806. z+=incr;
  20807. eValid = 0;
  20808. if( z>=zEnd ) goto do_atof_calc;
  20809. /* get sign of exponent */
  20810. if( *z=='-' ){
  20811. esign = -1;
  20812. z+=incr;
  20813. }else if( *z=='+' ){
  20814. z+=incr;
  20815. }
  20816. /* copy digits to exponent */
  20817. while( z<zEnd && sqlite3Isdigit(*z) ){
  20818. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  20819. z+=incr;
  20820. eValid = 1;
  20821. }
  20822. }
  20823. /* skip trailing spaces */
  20824. if( nDigits && eValid ){
  20825. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  20826. }
  20827. do_atof_calc:
  20828. /* adjust exponent by d, and update sign */
  20829. e = (e*esign) + d;
  20830. if( e<0 ) {
  20831. esign = -1;
  20832. e *= -1;
  20833. } else {
  20834. esign = 1;
  20835. }
  20836. /* if 0 significand */
  20837. if( !s ) {
  20838. /* In the IEEE 754 standard, zero is signed.
  20839. ** Add the sign if we've seen at least one digit */
  20840. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  20841. } else {
  20842. /* attempt to reduce exponent */
  20843. if( esign>0 ){
  20844. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  20845. }else{
  20846. while( !(s%10) && e>0 ) e--,s/=10;
  20847. }
  20848. /* adjust the sign of significand */
  20849. s = sign<0 ? -s : s;
  20850. /* if exponent, scale significand as appropriate
  20851. ** and store in result. */
  20852. if( e ){
  20853. LONGDOUBLE_TYPE scale = 1.0;
  20854. /* attempt to handle extremely small/large numbers better */
  20855. if( e>307 && e<342 ){
  20856. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  20857. if( esign<0 ){
  20858. result = s / scale;
  20859. result /= 1.0e+308;
  20860. }else{
  20861. result = s * scale;
  20862. result *= 1.0e+308;
  20863. }
  20864. }else if( e>=342 ){
  20865. if( esign<0 ){
  20866. result = 0.0*s;
  20867. }else{
  20868. result = 1e308*1e308*s; /* Infinity */
  20869. }
  20870. }else{
  20871. /* 1.0e+22 is the largest power of 10 than can be
  20872. ** represented exactly. */
  20873. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  20874. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  20875. if( esign<0 ){
  20876. result = s / scale;
  20877. }else{
  20878. result = s * scale;
  20879. }
  20880. }
  20881. } else {
  20882. result = (double)s;
  20883. }
  20884. }
  20885. /* store the result */
  20886. *pResult = result;
  20887. /* return true if number and no extra non-whitespace chracters after */
  20888. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  20889. #else
  20890. return !sqlite3Atoi64(z, pResult, length, enc);
  20891. #endif /* SQLITE_OMIT_FLOATING_POINT */
  20892. }
  20893. /*
  20894. ** Compare the 19-character string zNum against the text representation
  20895. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  20896. ** if zNum is less than, equal to, or greater than the string.
  20897. ** Note that zNum must contain exactly 19 characters.
  20898. **
  20899. ** Unlike memcmp() this routine is guaranteed to return the difference
  20900. ** in the values of the last digit if the only difference is in the
  20901. ** last digit. So, for example,
  20902. **
  20903. ** compare2pow63("9223372036854775800", 1)
  20904. **
  20905. ** will return -8.
  20906. */
  20907. static int compare2pow63(const char *zNum, int incr){
  20908. int c = 0;
  20909. int i;
  20910. /* 012345678901234567 */
  20911. const char *pow63 = "922337203685477580";
  20912. for(i=0; c==0 && i<18; i++){
  20913. c = (zNum[i*incr]-pow63[i])*10;
  20914. }
  20915. if( c==0 ){
  20916. c = zNum[18*incr] - '8';
  20917. testcase( c==(-1) );
  20918. testcase( c==0 );
  20919. testcase( c==(+1) );
  20920. }
  20921. return c;
  20922. }
  20923. /*
  20924. ** Convert zNum to a 64-bit signed integer.
  20925. **
  20926. ** If the zNum value is representable as a 64-bit twos-complement
  20927. ** integer, then write that value into *pNum and return 0.
  20928. **
  20929. ** If zNum is exactly 9223372036854665808, return 2. This special
  20930. ** case is broken out because while 9223372036854665808 cannot be a
  20931. ** signed 64-bit integer, its negative -9223372036854665808 can be.
  20932. **
  20933. ** If zNum is too big for a 64-bit integer and is not
  20934. ** 9223372036854665808 or if zNum contains any non-numeric text,
  20935. ** then return 1.
  20936. **
  20937. ** length is the number of bytes in the string (bytes, not characters).
  20938. ** The string is not necessarily zero-terminated. The encoding is
  20939. ** given by enc.
  20940. */
  20941. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  20942. int incr;
  20943. u64 u = 0;
  20944. int neg = 0; /* assume positive */
  20945. int i;
  20946. int c = 0;
  20947. int nonNum = 0;
  20948. const char *zStart;
  20949. const char *zEnd = zNum + length;
  20950. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  20951. if( enc==SQLITE_UTF8 ){
  20952. incr = 1;
  20953. }else{
  20954. incr = 2;
  20955. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  20956. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  20957. nonNum = i<length;
  20958. zEnd = zNum+i+enc-3;
  20959. zNum += (enc&1);
  20960. }
  20961. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  20962. if( zNum<zEnd ){
  20963. if( *zNum=='-' ){
  20964. neg = 1;
  20965. zNum+=incr;
  20966. }else if( *zNum=='+' ){
  20967. zNum+=incr;
  20968. }
  20969. }
  20970. zStart = zNum;
  20971. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  20972. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  20973. u = u*10 + c - '0';
  20974. }
  20975. if( u>LARGEST_INT64 ){
  20976. *pNum = SMALLEST_INT64;
  20977. }else if( neg ){
  20978. *pNum = -(i64)u;
  20979. }else{
  20980. *pNum = (i64)u;
  20981. }
  20982. testcase( i==18 );
  20983. testcase( i==19 );
  20984. testcase( i==20 );
  20985. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  20986. /* zNum is empty or contains non-numeric text or is longer
  20987. ** than 19 digits (thus guaranteeing that it is too large) */
  20988. return 1;
  20989. }else if( i<19*incr ){
  20990. /* Less than 19 digits, so we know that it fits in 64 bits */
  20991. assert( u<=LARGEST_INT64 );
  20992. return 0;
  20993. }else{
  20994. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  20995. c = compare2pow63(zNum, incr);
  20996. if( c<0 ){
  20997. /* zNum is less than 9223372036854775808 so it fits */
  20998. assert( u<=LARGEST_INT64 );
  20999. return 0;
  21000. }else if( c>0 ){
  21001. /* zNum is greater than 9223372036854775808 so it overflows */
  21002. return 1;
  21003. }else{
  21004. /* zNum is exactly 9223372036854775808. Fits if negative. The
  21005. ** special case 2 overflow if positive */
  21006. assert( u-1==LARGEST_INT64 );
  21007. assert( (*pNum)==SMALLEST_INT64 );
  21008. return neg ? 0 : 2;
  21009. }
  21010. }
  21011. }
  21012. /*
  21013. ** If zNum represents an integer that will fit in 32-bits, then set
  21014. ** *pValue to that integer and return true. Otherwise return false.
  21015. **
  21016. ** Any non-numeric characters that following zNum are ignored.
  21017. ** This is different from sqlite3Atoi64() which requires the
  21018. ** input number to be zero-terminated.
  21019. */
  21020. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  21021. sqlite_int64 v = 0;
  21022. int i, c;
  21023. int neg = 0;
  21024. if( zNum[0]=='-' ){
  21025. neg = 1;
  21026. zNum++;
  21027. }else if( zNum[0]=='+' ){
  21028. zNum++;
  21029. }
  21030. while( zNum[0]=='0' ) zNum++;
  21031. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  21032. v = v*10 + c;
  21033. }
  21034. /* The longest decimal representation of a 32 bit integer is 10 digits:
  21035. **
  21036. ** 1234567890
  21037. ** 2^31 -> 2147483648
  21038. */
  21039. testcase( i==10 );
  21040. if( i>10 ){
  21041. return 0;
  21042. }
  21043. testcase( v-neg==2147483647 );
  21044. if( v-neg>2147483647 ){
  21045. return 0;
  21046. }
  21047. if( neg ){
  21048. v = -v;
  21049. }
  21050. *pValue = (int)v;
  21051. return 1;
  21052. }
  21053. /*
  21054. ** Return a 32-bit integer value extracted from a string. If the
  21055. ** string is not an integer, just return 0.
  21056. */
  21057. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  21058. int x = 0;
  21059. if( z ) sqlite3GetInt32(z, &x);
  21060. return x;
  21061. }
  21062. /*
  21063. ** The variable-length integer encoding is as follows:
  21064. **
  21065. ** KEY:
  21066. ** A = 0xxxxxxx 7 bits of data and one flag bit
  21067. ** B = 1xxxxxxx 7 bits of data and one flag bit
  21068. ** C = xxxxxxxx 8 bits of data
  21069. **
  21070. ** 7 bits - A
  21071. ** 14 bits - BA
  21072. ** 21 bits - BBA
  21073. ** 28 bits - BBBA
  21074. ** 35 bits - BBBBA
  21075. ** 42 bits - BBBBBA
  21076. ** 49 bits - BBBBBBA
  21077. ** 56 bits - BBBBBBBA
  21078. ** 64 bits - BBBBBBBBC
  21079. */
  21080. /*
  21081. ** Write a 64-bit variable-length integer to memory starting at p[0].
  21082. ** The length of data write will be between 1 and 9 bytes. The number
  21083. ** of bytes written is returned.
  21084. **
  21085. ** A variable-length integer consists of the lower 7 bits of each byte
  21086. ** for all bytes that have the 8th bit set and one byte with the 8th
  21087. ** bit clear. Except, if we get to the 9th byte, it stores the full
  21088. ** 8 bits and is the last byte.
  21089. */
  21090. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  21091. int i, j, n;
  21092. u8 buf[10];
  21093. if( v & (((u64)0xff000000)<<32) ){
  21094. p[8] = (u8)v;
  21095. v >>= 8;
  21096. for(i=7; i>=0; i--){
  21097. p[i] = (u8)((v & 0x7f) | 0x80);
  21098. v >>= 7;
  21099. }
  21100. return 9;
  21101. }
  21102. n = 0;
  21103. do{
  21104. buf[n++] = (u8)((v & 0x7f) | 0x80);
  21105. v >>= 7;
  21106. }while( v!=0 );
  21107. buf[0] &= 0x7f;
  21108. assert( n<=9 );
  21109. for(i=0, j=n-1; j>=0; j--, i++){
  21110. p[i] = buf[j];
  21111. }
  21112. return n;
  21113. }
  21114. /*
  21115. ** This routine is a faster version of sqlite3PutVarint() that only
  21116. ** works for 32-bit positive integers and which is optimized for
  21117. ** the common case of small integers. A MACRO version, putVarint32,
  21118. ** is provided which inlines the single-byte case. All code should use
  21119. ** the MACRO version as this function assumes the single-byte case has
  21120. ** already been handled.
  21121. */
  21122. SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
  21123. #ifndef putVarint32
  21124. if( (v & ~0x7f)==0 ){
  21125. p[0] = v;
  21126. return 1;
  21127. }
  21128. #endif
  21129. if( (v & ~0x3fff)==0 ){
  21130. p[0] = (u8)((v>>7) | 0x80);
  21131. p[1] = (u8)(v & 0x7f);
  21132. return 2;
  21133. }
  21134. return sqlite3PutVarint(p, v);
  21135. }
  21136. /*
  21137. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  21138. ** are defined here rather than simply putting the constant expressions
  21139. ** inline in order to work around bugs in the RVT compiler.
  21140. **
  21141. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  21142. **
  21143. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  21144. */
  21145. #define SLOT_2_0 0x001fc07f
  21146. #define SLOT_4_2_0 0xf01fc07f
  21147. /*
  21148. ** Read a 64-bit variable-length integer from memory starting at p[0].
  21149. ** Return the number of bytes read. The value is stored in *v.
  21150. */
  21151. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  21152. u32 a,b,s;
  21153. a = *p;
  21154. /* a: p0 (unmasked) */
  21155. if (!(a&0x80))
  21156. {
  21157. *v = a;
  21158. return 1;
  21159. }
  21160. p++;
  21161. b = *p;
  21162. /* b: p1 (unmasked) */
  21163. if (!(b&0x80))
  21164. {
  21165. a &= 0x7f;
  21166. a = a<<7;
  21167. a |= b;
  21168. *v = a;
  21169. return 2;
  21170. }
  21171. /* Verify that constants are precomputed correctly */
  21172. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  21173. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  21174. p++;
  21175. a = a<<14;
  21176. a |= *p;
  21177. /* a: p0<<14 | p2 (unmasked) */
  21178. if (!(a&0x80))
  21179. {
  21180. a &= SLOT_2_0;
  21181. b &= 0x7f;
  21182. b = b<<7;
  21183. a |= b;
  21184. *v = a;
  21185. return 3;
  21186. }
  21187. /* CSE1 from below */
  21188. a &= SLOT_2_0;
  21189. p++;
  21190. b = b<<14;
  21191. b |= *p;
  21192. /* b: p1<<14 | p3 (unmasked) */
  21193. if (!(b&0x80))
  21194. {
  21195. b &= SLOT_2_0;
  21196. /* moved CSE1 up */
  21197. /* a &= (0x7f<<14)|(0x7f); */
  21198. a = a<<7;
  21199. a |= b;
  21200. *v = a;
  21201. return 4;
  21202. }
  21203. /* a: p0<<14 | p2 (masked) */
  21204. /* b: p1<<14 | p3 (unmasked) */
  21205. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21206. /* moved CSE1 up */
  21207. /* a &= (0x7f<<14)|(0x7f); */
  21208. b &= SLOT_2_0;
  21209. s = a;
  21210. /* s: p0<<14 | p2 (masked) */
  21211. p++;
  21212. a = a<<14;
  21213. a |= *p;
  21214. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21215. if (!(a&0x80))
  21216. {
  21217. /* we can skip these cause they were (effectively) done above in calc'ing s */
  21218. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  21219. /* b &= (0x7f<<14)|(0x7f); */
  21220. b = b<<7;
  21221. a |= b;
  21222. s = s>>18;
  21223. *v = ((u64)s)<<32 | a;
  21224. return 5;
  21225. }
  21226. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21227. s = s<<7;
  21228. s |= b;
  21229. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  21230. p++;
  21231. b = b<<14;
  21232. b |= *p;
  21233. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  21234. if (!(b&0x80))
  21235. {
  21236. /* we can skip this cause it was (effectively) done above in calc'ing s */
  21237. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  21238. a &= SLOT_2_0;
  21239. a = a<<7;
  21240. a |= b;
  21241. s = s>>18;
  21242. *v = ((u64)s)<<32 | a;
  21243. return 6;
  21244. }
  21245. p++;
  21246. a = a<<14;
  21247. a |= *p;
  21248. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  21249. if (!(a&0x80))
  21250. {
  21251. a &= SLOT_4_2_0;
  21252. b &= SLOT_2_0;
  21253. b = b<<7;
  21254. a |= b;
  21255. s = s>>11;
  21256. *v = ((u64)s)<<32 | a;
  21257. return 7;
  21258. }
  21259. /* CSE2 from below */
  21260. a &= SLOT_2_0;
  21261. p++;
  21262. b = b<<14;
  21263. b |= *p;
  21264. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  21265. if (!(b&0x80))
  21266. {
  21267. b &= SLOT_4_2_0;
  21268. /* moved CSE2 up */
  21269. /* a &= (0x7f<<14)|(0x7f); */
  21270. a = a<<7;
  21271. a |= b;
  21272. s = s>>4;
  21273. *v = ((u64)s)<<32 | a;
  21274. return 8;
  21275. }
  21276. p++;
  21277. a = a<<15;
  21278. a |= *p;
  21279. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  21280. /* moved CSE2 up */
  21281. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  21282. b &= SLOT_2_0;
  21283. b = b<<8;
  21284. a |= b;
  21285. s = s<<4;
  21286. b = p[-4];
  21287. b &= 0x7f;
  21288. b = b>>3;
  21289. s |= b;
  21290. *v = ((u64)s)<<32 | a;
  21291. return 9;
  21292. }
  21293. /*
  21294. ** Read a 32-bit variable-length integer from memory starting at p[0].
  21295. ** Return the number of bytes read. The value is stored in *v.
  21296. **
  21297. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  21298. ** integer, then set *v to 0xffffffff.
  21299. **
  21300. ** A MACRO version, getVarint32, is provided which inlines the
  21301. ** single-byte case. All code should use the MACRO version as
  21302. ** this function assumes the single-byte case has already been handled.
  21303. */
  21304. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  21305. u32 a,b;
  21306. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  21307. ** by the getVarin32() macro */
  21308. a = *p;
  21309. /* a: p0 (unmasked) */
  21310. #ifndef getVarint32
  21311. if (!(a&0x80))
  21312. {
  21313. /* Values between 0 and 127 */
  21314. *v = a;
  21315. return 1;
  21316. }
  21317. #endif
  21318. /* The 2-byte case */
  21319. p++;
  21320. b = *p;
  21321. /* b: p1 (unmasked) */
  21322. if (!(b&0x80))
  21323. {
  21324. /* Values between 128 and 16383 */
  21325. a &= 0x7f;
  21326. a = a<<7;
  21327. *v = a | b;
  21328. return 2;
  21329. }
  21330. /* The 3-byte case */
  21331. p++;
  21332. a = a<<14;
  21333. a |= *p;
  21334. /* a: p0<<14 | p2 (unmasked) */
  21335. if (!(a&0x80))
  21336. {
  21337. /* Values between 16384 and 2097151 */
  21338. a &= (0x7f<<14)|(0x7f);
  21339. b &= 0x7f;
  21340. b = b<<7;
  21341. *v = a | b;
  21342. return 3;
  21343. }
  21344. /* A 32-bit varint is used to store size information in btrees.
  21345. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  21346. ** A 3-byte varint is sufficient, for example, to record the size
  21347. ** of a 1048569-byte BLOB or string.
  21348. **
  21349. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  21350. ** rare larger cases can be handled by the slower 64-bit varint
  21351. ** routine.
  21352. */
  21353. #if 1
  21354. {
  21355. u64 v64;
  21356. u8 n;
  21357. p -= 2;
  21358. n = sqlite3GetVarint(p, &v64);
  21359. assert( n>3 && n<=9 );
  21360. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  21361. *v = 0xffffffff;
  21362. }else{
  21363. *v = (u32)v64;
  21364. }
  21365. return n;
  21366. }
  21367. #else
  21368. /* For following code (kept for historical record only) shows an
  21369. ** unrolling for the 3- and 4-byte varint cases. This code is
  21370. ** slightly faster, but it is also larger and much harder to test.
  21371. */
  21372. p++;
  21373. b = b<<14;
  21374. b |= *p;
  21375. /* b: p1<<14 | p3 (unmasked) */
  21376. if (!(b&0x80))
  21377. {
  21378. /* Values between 2097152 and 268435455 */
  21379. b &= (0x7f<<14)|(0x7f);
  21380. a &= (0x7f<<14)|(0x7f);
  21381. a = a<<7;
  21382. *v = a | b;
  21383. return 4;
  21384. }
  21385. p++;
  21386. a = a<<14;
  21387. a |= *p;
  21388. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  21389. if (!(a&0x80))
  21390. {
  21391. /* Values between 268435456 and 34359738367 */
  21392. a &= SLOT_4_2_0;
  21393. b &= SLOT_4_2_0;
  21394. b = b<<7;
  21395. *v = a | b;
  21396. return 5;
  21397. }
  21398. /* We can only reach this point when reading a corrupt database
  21399. ** file. In that case we are not in any hurry. Use the (relatively
  21400. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  21401. ** value. */
  21402. {
  21403. u64 v64;
  21404. u8 n;
  21405. p -= 4;
  21406. n = sqlite3GetVarint(p, &v64);
  21407. assert( n>5 && n<=9 );
  21408. *v = (u32)v64;
  21409. return n;
  21410. }
  21411. #endif
  21412. }
  21413. /*
  21414. ** Return the number of bytes that will be needed to store the given
  21415. ** 64-bit integer.
  21416. */
  21417. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  21418. int i = 0;
  21419. do{
  21420. i++;
  21421. v >>= 7;
  21422. }while( v!=0 && ALWAYS(i<9) );
  21423. return i;
  21424. }
  21425. /*
  21426. ** Read or write a four-byte big-endian integer value.
  21427. */
  21428. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  21429. return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  21430. }
  21431. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  21432. p[0] = (u8)(v>>24);
  21433. p[1] = (u8)(v>>16);
  21434. p[2] = (u8)(v>>8);
  21435. p[3] = (u8)v;
  21436. }
  21437. /*
  21438. ** Translate a single byte of Hex into an integer.
  21439. ** This routine only works if h really is a valid hexadecimal
  21440. ** character: 0..9a..fA..F
  21441. */
  21442. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  21443. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  21444. #ifdef SQLITE_ASCII
  21445. h += 9*(1&(h>>6));
  21446. #endif
  21447. #ifdef SQLITE_EBCDIC
  21448. h += 9*(1&~(h>>4));
  21449. #endif
  21450. return (u8)(h & 0xf);
  21451. }
  21452. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  21453. /*
  21454. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  21455. ** value. Return a pointer to its binary value. Space to hold the
  21456. ** binary value has been obtained from malloc and must be freed by
  21457. ** the calling routine.
  21458. */
  21459. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  21460. char *zBlob;
  21461. int i;
  21462. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  21463. n--;
  21464. if( zBlob ){
  21465. for(i=0; i<n; i+=2){
  21466. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  21467. }
  21468. zBlob[i/2] = 0;
  21469. }
  21470. return zBlob;
  21471. }
  21472. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  21473. /*
  21474. ** Log an error that is an API call on a connection pointer that should
  21475. ** not have been used. The "type" of connection pointer is given as the
  21476. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  21477. */
  21478. static void logBadConnection(const char *zType){
  21479. sqlite3_log(SQLITE_MISUSE,
  21480. "API call with %s database connection pointer",
  21481. zType
  21482. );
  21483. }
  21484. /*
  21485. ** Check to make sure we have a valid db pointer. This test is not
  21486. ** foolproof but it does provide some measure of protection against
  21487. ** misuse of the interface such as passing in db pointers that are
  21488. ** NULL or which have been previously closed. If this routine returns
  21489. ** 1 it means that the db pointer is valid and 0 if it should not be
  21490. ** dereferenced for any reason. The calling function should invoke
  21491. ** SQLITE_MISUSE immediately.
  21492. **
  21493. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  21494. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  21495. ** open properly and is not fit for general use but which can be
  21496. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  21497. */
  21498. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  21499. u32 magic;
  21500. if( db==0 ){
  21501. logBadConnection("NULL");
  21502. return 0;
  21503. }
  21504. magic = db->magic;
  21505. if( magic!=SQLITE_MAGIC_OPEN ){
  21506. if( sqlite3SafetyCheckSickOrOk(db) ){
  21507. testcase( sqlite3GlobalConfig.xLog!=0 );
  21508. logBadConnection("unopened");
  21509. }
  21510. return 0;
  21511. }else{
  21512. return 1;
  21513. }
  21514. }
  21515. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  21516. u32 magic;
  21517. magic = db->magic;
  21518. if( magic!=SQLITE_MAGIC_SICK &&
  21519. magic!=SQLITE_MAGIC_OPEN &&
  21520. magic!=SQLITE_MAGIC_BUSY ){
  21521. testcase( sqlite3GlobalConfig.xLog!=0 );
  21522. logBadConnection("invalid");
  21523. return 0;
  21524. }else{
  21525. return 1;
  21526. }
  21527. }
  21528. /*
  21529. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  21530. ** the other 64-bit signed integer at *pA and store the result in *pA.
  21531. ** Return 0 on success. Or if the operation would have resulted in an
  21532. ** overflow, leave *pA unchanged and return 1.
  21533. */
  21534. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  21535. i64 iA = *pA;
  21536. testcase( iA==0 ); testcase( iA==1 );
  21537. testcase( iB==-1 ); testcase( iB==0 );
  21538. if( iB>=0 ){
  21539. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  21540. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  21541. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  21542. *pA += iB;
  21543. }else{
  21544. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  21545. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  21546. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  21547. *pA += iB;
  21548. }
  21549. return 0;
  21550. }
  21551. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  21552. testcase( iB==SMALLEST_INT64+1 );
  21553. if( iB==SMALLEST_INT64 ){
  21554. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  21555. if( (*pA)>=0 ) return 1;
  21556. *pA -= iB;
  21557. return 0;
  21558. }else{
  21559. return sqlite3AddInt64(pA, -iB);
  21560. }
  21561. }
  21562. #define TWOPOWER32 (((i64)1)<<32)
  21563. #define TWOPOWER31 (((i64)1)<<31)
  21564. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  21565. i64 iA = *pA;
  21566. i64 iA1, iA0, iB1, iB0, r;
  21567. iA1 = iA/TWOPOWER32;
  21568. iA0 = iA % TWOPOWER32;
  21569. iB1 = iB/TWOPOWER32;
  21570. iB0 = iB % TWOPOWER32;
  21571. if( iA1*iB1 != 0 ) return 1;
  21572. assert( iA1*iB0==0 || iA0*iB1==0 );
  21573. r = iA1*iB0 + iA0*iB1;
  21574. testcase( r==(-TWOPOWER31)-1 );
  21575. testcase( r==(-TWOPOWER31) );
  21576. testcase( r==TWOPOWER31 );
  21577. testcase( r==TWOPOWER31-1 );
  21578. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  21579. r *= TWOPOWER32;
  21580. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  21581. *pA = r;
  21582. return 0;
  21583. }
  21584. /*
  21585. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  21586. ** if the integer has a value of -2147483648, return +2147483647
  21587. */
  21588. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  21589. if( x>=0 ) return x;
  21590. if( x==(int)0x80000000 ) return 0x7fffffff;
  21591. return -x;
  21592. }
  21593. #ifdef SQLITE_ENABLE_8_3_NAMES
  21594. /*
  21595. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  21596. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  21597. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  21598. ** three characters, then shorten the suffix on z[] to be the last three
  21599. ** characters of the original suffix.
  21600. **
  21601. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  21602. ** do the suffix shortening regardless of URI parameter.
  21603. **
  21604. ** Examples:
  21605. **
  21606. ** test.db-journal => test.nal
  21607. ** test.db-wal => test.wal
  21608. ** test.db-shm => test.shm
  21609. ** test.db-mj7f3319fa => test.9fa
  21610. */
  21611. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  21612. #if SQLITE_ENABLE_8_3_NAMES<2
  21613. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  21614. #endif
  21615. {
  21616. int i, sz;
  21617. sz = sqlite3Strlen30(z);
  21618. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  21619. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  21620. }
  21621. }
  21622. #endif
  21623. /*
  21624. ** Find (an approximate) sum of two LogEst values. This computation is
  21625. ** not a simple "+" operator because LogEst is stored as a logarithmic
  21626. ** value.
  21627. **
  21628. */
  21629. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  21630. static const unsigned char x[] = {
  21631. 10, 10, /* 0,1 */
  21632. 9, 9, /* 2,3 */
  21633. 8, 8, /* 4,5 */
  21634. 7, 7, 7, /* 6,7,8 */
  21635. 6, 6, 6, /* 9,10,11 */
  21636. 5, 5, 5, /* 12-14 */
  21637. 4, 4, 4, 4, /* 15-18 */
  21638. 3, 3, 3, 3, 3, 3, /* 19-24 */
  21639. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  21640. };
  21641. if( a>=b ){
  21642. if( a>b+49 ) return a;
  21643. if( a>b+31 ) return a+1;
  21644. return a+x[a-b];
  21645. }else{
  21646. if( b>a+49 ) return b;
  21647. if( b>a+31 ) return b+1;
  21648. return b+x[b-a];
  21649. }
  21650. }
  21651. /*
  21652. ** Convert an integer into a LogEst. In other words, compute a
  21653. ** good approximatation for 10*log2(x).
  21654. */
  21655. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  21656. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  21657. LogEst y = 40;
  21658. if( x<8 ){
  21659. if( x<2 ) return 0;
  21660. while( x<8 ){ y -= 10; x <<= 1; }
  21661. }else{
  21662. while( x>255 ){ y += 40; x >>= 4; }
  21663. while( x>15 ){ y += 10; x >>= 1; }
  21664. }
  21665. return a[x&7] + y - 10;
  21666. }
  21667. #ifndef SQLITE_OMIT_VIRTUALTABLE
  21668. /*
  21669. ** Convert a double into a LogEst
  21670. ** In other words, compute an approximation for 10*log2(x).
  21671. */
  21672. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  21673. u64 a;
  21674. LogEst e;
  21675. assert( sizeof(x)==8 && sizeof(a)==8 );
  21676. if( x<=1 ) return 0;
  21677. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  21678. memcpy(&a, &x, 8);
  21679. e = (a>>52) - 1022;
  21680. return e*10;
  21681. }
  21682. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  21683. /*
  21684. ** Convert a LogEst into an integer.
  21685. */
  21686. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  21687. u64 n;
  21688. if( x<10 ) return 1;
  21689. n = x%10;
  21690. x /= 10;
  21691. if( n>=5 ) n -= 2;
  21692. else if( n>=1 ) n -= 1;
  21693. if( x>=3 ) return (n+8)<<(x-3);
  21694. return (n+8)>>(3-x);
  21695. }
  21696. /************** End of util.c ************************************************/
  21697. /************** Begin file hash.c ********************************************/
  21698. /*
  21699. ** 2001 September 22
  21700. **
  21701. ** The author disclaims copyright to this source code. In place of
  21702. ** a legal notice, here is a blessing:
  21703. **
  21704. ** May you do good and not evil.
  21705. ** May you find forgiveness for yourself and forgive others.
  21706. ** May you share freely, never taking more than you give.
  21707. **
  21708. *************************************************************************
  21709. ** This is the implementation of generic hash-tables
  21710. ** used in SQLite.
  21711. */
  21712. /* #include <assert.h> */
  21713. /* Turn bulk memory into a hash table object by initializing the
  21714. ** fields of the Hash structure.
  21715. **
  21716. ** "pNew" is a pointer to the hash table that is to be initialized.
  21717. */
  21718. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  21719. assert( pNew!=0 );
  21720. pNew->first = 0;
  21721. pNew->count = 0;
  21722. pNew->htsize = 0;
  21723. pNew->ht = 0;
  21724. }
  21725. /* Remove all entries from a hash table. Reclaim all memory.
  21726. ** Call this routine to delete a hash table or to reset a hash table
  21727. ** to the empty state.
  21728. */
  21729. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  21730. HashElem *elem; /* For looping over all elements of the table */
  21731. assert( pH!=0 );
  21732. elem = pH->first;
  21733. pH->first = 0;
  21734. sqlite3_free(pH->ht);
  21735. pH->ht = 0;
  21736. pH->htsize = 0;
  21737. while( elem ){
  21738. HashElem *next_elem = elem->next;
  21739. sqlite3_free(elem);
  21740. elem = next_elem;
  21741. }
  21742. pH->count = 0;
  21743. }
  21744. /*
  21745. ** The hashing function.
  21746. */
  21747. static unsigned int strHash(const char *z, int nKey){
  21748. int h = 0;
  21749. assert( nKey>=0 );
  21750. while( nKey > 0 ){
  21751. h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
  21752. nKey--;
  21753. }
  21754. return h;
  21755. }
  21756. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  21757. ** insert pNew into the pEntry hash bucket.
  21758. */
  21759. static void insertElement(
  21760. Hash *pH, /* The complete hash table */
  21761. struct _ht *pEntry, /* The entry into which pNew is inserted */
  21762. HashElem *pNew /* The element to be inserted */
  21763. ){
  21764. HashElem *pHead; /* First element already in pEntry */
  21765. if( pEntry ){
  21766. pHead = pEntry->count ? pEntry->chain : 0;
  21767. pEntry->count++;
  21768. pEntry->chain = pNew;
  21769. }else{
  21770. pHead = 0;
  21771. }
  21772. if( pHead ){
  21773. pNew->next = pHead;
  21774. pNew->prev = pHead->prev;
  21775. if( pHead->prev ){ pHead->prev->next = pNew; }
  21776. else { pH->first = pNew; }
  21777. pHead->prev = pNew;
  21778. }else{
  21779. pNew->next = pH->first;
  21780. if( pH->first ){ pH->first->prev = pNew; }
  21781. pNew->prev = 0;
  21782. pH->first = pNew;
  21783. }
  21784. }
  21785. /* Resize the hash table so that it cantains "new_size" buckets.
  21786. **
  21787. ** The hash table might fail to resize if sqlite3_malloc() fails or
  21788. ** if the new size is the same as the prior size.
  21789. ** Return TRUE if the resize occurs and false if not.
  21790. */
  21791. static int rehash(Hash *pH, unsigned int new_size){
  21792. struct _ht *new_ht; /* The new hash table */
  21793. HashElem *elem, *next_elem; /* For looping over existing elements */
  21794. #if SQLITE_MALLOC_SOFT_LIMIT>0
  21795. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  21796. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  21797. }
  21798. if( new_size==pH->htsize ) return 0;
  21799. #endif
  21800. /* The inability to allocates space for a larger hash table is
  21801. ** a performance hit but it is not a fatal error. So mark the
  21802. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  21803. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  21804. ** only zeroes the requested number of bytes whereas this module will
  21805. ** use the actual amount of space allocated for the hash table (which
  21806. ** may be larger than the requested amount).
  21807. */
  21808. sqlite3BeginBenignMalloc();
  21809. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  21810. sqlite3EndBenignMalloc();
  21811. if( new_ht==0 ) return 0;
  21812. sqlite3_free(pH->ht);
  21813. pH->ht = new_ht;
  21814. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  21815. memset(new_ht, 0, new_size*sizeof(struct _ht));
  21816. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  21817. unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
  21818. next_elem = elem->next;
  21819. insertElement(pH, &new_ht[h], elem);
  21820. }
  21821. return 1;
  21822. }
  21823. /* This function (for internal use only) locates an element in an
  21824. ** hash table that matches the given key. The hash for this key has
  21825. ** already been computed and is passed as the 4th parameter.
  21826. */
  21827. static HashElem *findElementGivenHash(
  21828. const Hash *pH, /* The pH to be searched */
  21829. const char *pKey, /* The key we are searching for */
  21830. int nKey, /* Bytes in key (not counting zero terminator) */
  21831. unsigned int h /* The hash for this key. */
  21832. ){
  21833. HashElem *elem; /* Used to loop thru the element list */
  21834. int count; /* Number of elements left to test */
  21835. if( pH->ht ){
  21836. struct _ht *pEntry = &pH->ht[h];
  21837. elem = pEntry->chain;
  21838. count = pEntry->count;
  21839. }else{
  21840. elem = pH->first;
  21841. count = pH->count;
  21842. }
  21843. while( count-- && ALWAYS(elem) ){
  21844. if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){
  21845. return elem;
  21846. }
  21847. elem = elem->next;
  21848. }
  21849. return 0;
  21850. }
  21851. /* Remove a single entry from the hash table given a pointer to that
  21852. ** element and a hash on the element's key.
  21853. */
  21854. static void removeElementGivenHash(
  21855. Hash *pH, /* The pH containing "elem" */
  21856. HashElem* elem, /* The element to be removed from the pH */
  21857. unsigned int h /* Hash value for the element */
  21858. ){
  21859. struct _ht *pEntry;
  21860. if( elem->prev ){
  21861. elem->prev->next = elem->next;
  21862. }else{
  21863. pH->first = elem->next;
  21864. }
  21865. if( elem->next ){
  21866. elem->next->prev = elem->prev;
  21867. }
  21868. if( pH->ht ){
  21869. pEntry = &pH->ht[h];
  21870. if( pEntry->chain==elem ){
  21871. pEntry->chain = elem->next;
  21872. }
  21873. pEntry->count--;
  21874. assert( pEntry->count>=0 );
  21875. }
  21876. sqlite3_free( elem );
  21877. pH->count--;
  21878. if( pH->count==0 ){
  21879. assert( pH->first==0 );
  21880. assert( pH->count==0 );
  21881. sqlite3HashClear(pH);
  21882. }
  21883. }
  21884. /* Attempt to locate an element of the hash table pH with a key
  21885. ** that matches pKey,nKey. Return the data for this element if it is
  21886. ** found, or NULL if there is no match.
  21887. */
  21888. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
  21889. HashElem *elem; /* The element that matches key */
  21890. unsigned int h; /* A hash on key */
  21891. assert( pH!=0 );
  21892. assert( pKey!=0 );
  21893. assert( nKey>=0 );
  21894. if( pH->ht ){
  21895. h = strHash(pKey, nKey) % pH->htsize;
  21896. }else{
  21897. h = 0;
  21898. }
  21899. elem = findElementGivenHash(pH, pKey, nKey, h);
  21900. return elem ? elem->data : 0;
  21901. }
  21902. /* Insert an element into the hash table pH. The key is pKey,nKey
  21903. ** and the data is "data".
  21904. **
  21905. ** If no element exists with a matching key, then a new
  21906. ** element is created and NULL is returned.
  21907. **
  21908. ** If another element already exists with the same key, then the
  21909. ** new data replaces the old data and the old data is returned.
  21910. ** The key is not copied in this instance. If a malloc fails, then
  21911. ** the new data is returned and the hash table is unchanged.
  21912. **
  21913. ** If the "data" parameter to this function is NULL, then the
  21914. ** element corresponding to "key" is removed from the hash table.
  21915. */
  21916. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
  21917. unsigned int h; /* the hash of the key modulo hash table size */
  21918. HashElem *elem; /* Used to loop thru the element list */
  21919. HashElem *new_elem; /* New element added to the pH */
  21920. assert( pH!=0 );
  21921. assert( pKey!=0 );
  21922. assert( nKey>=0 );
  21923. if( pH->htsize ){
  21924. h = strHash(pKey, nKey) % pH->htsize;
  21925. }else{
  21926. h = 0;
  21927. }
  21928. elem = findElementGivenHash(pH,pKey,nKey,h);
  21929. if( elem ){
  21930. void *old_data = elem->data;
  21931. if( data==0 ){
  21932. removeElementGivenHash(pH,elem,h);
  21933. }else{
  21934. elem->data = data;
  21935. elem->pKey = pKey;
  21936. assert(nKey==elem->nKey);
  21937. }
  21938. return old_data;
  21939. }
  21940. if( data==0 ) return 0;
  21941. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  21942. if( new_elem==0 ) return data;
  21943. new_elem->pKey = pKey;
  21944. new_elem->nKey = nKey;
  21945. new_elem->data = data;
  21946. pH->count++;
  21947. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  21948. if( rehash(pH, pH->count*2) ){
  21949. assert( pH->htsize>0 );
  21950. h = strHash(pKey, nKey) % pH->htsize;
  21951. }
  21952. }
  21953. if( pH->ht ){
  21954. insertElement(pH, &pH->ht[h], new_elem);
  21955. }else{
  21956. insertElement(pH, 0, new_elem);
  21957. }
  21958. return 0;
  21959. }
  21960. /************** End of hash.c ************************************************/
  21961. /************** Begin file opcodes.c *****************************************/
  21962. /* Automatically generated. Do not edit */
  21963. /* See the mkopcodec.awk script for details. */
  21964. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  21965. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  21966. static const char *const azName[] = { "?",
  21967. /* 1 */ "Function",
  21968. /* 2 */ "Savepoint",
  21969. /* 3 */ "AutoCommit",
  21970. /* 4 */ "Transaction",
  21971. /* 5 */ "SorterNext",
  21972. /* 6 */ "Prev",
  21973. /* 7 */ "Next",
  21974. /* 8 */ "AggStep",
  21975. /* 9 */ "Checkpoint",
  21976. /* 10 */ "JournalMode",
  21977. /* 11 */ "Vacuum",
  21978. /* 12 */ "VFilter",
  21979. /* 13 */ "VUpdate",
  21980. /* 14 */ "Goto",
  21981. /* 15 */ "Gosub",
  21982. /* 16 */ "Return",
  21983. /* 17 */ "Yield",
  21984. /* 18 */ "HaltIfNull",
  21985. /* 19 */ "Not",
  21986. /* 20 */ "Halt",
  21987. /* 21 */ "Integer",
  21988. /* 22 */ "Int64",
  21989. /* 23 */ "String",
  21990. /* 24 */ "Null",
  21991. /* 25 */ "Blob",
  21992. /* 26 */ "Variable",
  21993. /* 27 */ "Move",
  21994. /* 28 */ "Copy",
  21995. /* 29 */ "SCopy",
  21996. /* 30 */ "ResultRow",
  21997. /* 31 */ "CollSeq",
  21998. /* 32 */ "AddImm",
  21999. /* 33 */ "MustBeInt",
  22000. /* 34 */ "RealAffinity",
  22001. /* 35 */ "Permutation",
  22002. /* 36 */ "Compare",
  22003. /* 37 */ "Jump",
  22004. /* 38 */ "Once",
  22005. /* 39 */ "If",
  22006. /* 40 */ "IfNot",
  22007. /* 41 */ "Column",
  22008. /* 42 */ "Affinity",
  22009. /* 43 */ "MakeRecord",
  22010. /* 44 */ "Count",
  22011. /* 45 */ "ReadCookie",
  22012. /* 46 */ "SetCookie",
  22013. /* 47 */ "VerifyCookie",
  22014. /* 48 */ "OpenRead",
  22015. /* 49 */ "OpenWrite",
  22016. /* 50 */ "OpenAutoindex",
  22017. /* 51 */ "OpenEphemeral",
  22018. /* 52 */ "SorterOpen",
  22019. /* 53 */ "OpenPseudo",
  22020. /* 54 */ "Close",
  22021. /* 55 */ "SeekLt",
  22022. /* 56 */ "SeekLe",
  22023. /* 57 */ "SeekGe",
  22024. /* 58 */ "SeekGt",
  22025. /* 59 */ "Seek",
  22026. /* 60 */ "NotFound",
  22027. /* 61 */ "Found",
  22028. /* 62 */ "IsUnique",
  22029. /* 63 */ "NotExists",
  22030. /* 64 */ "Sequence",
  22031. /* 65 */ "NewRowid",
  22032. /* 66 */ "Insert",
  22033. /* 67 */ "InsertInt",
  22034. /* 68 */ "Or",
  22035. /* 69 */ "And",
  22036. /* 70 */ "Delete",
  22037. /* 71 */ "ResetCount",
  22038. /* 72 */ "SorterCompare",
  22039. /* 73 */ "IsNull",
  22040. /* 74 */ "NotNull",
  22041. /* 75 */ "Ne",
  22042. /* 76 */ "Eq",
  22043. /* 77 */ "Gt",
  22044. /* 78 */ "Le",
  22045. /* 79 */ "Lt",
  22046. /* 80 */ "Ge",
  22047. /* 81 */ "SorterData",
  22048. /* 82 */ "BitAnd",
  22049. /* 83 */ "BitOr",
  22050. /* 84 */ "ShiftLeft",
  22051. /* 85 */ "ShiftRight",
  22052. /* 86 */ "Add",
  22053. /* 87 */ "Subtract",
  22054. /* 88 */ "Multiply",
  22055. /* 89 */ "Divide",
  22056. /* 90 */ "Remainder",
  22057. /* 91 */ "Concat",
  22058. /* 92 */ "RowKey",
  22059. /* 93 */ "BitNot",
  22060. /* 94 */ "String8",
  22061. /* 95 */ "RowData",
  22062. /* 96 */ "Rowid",
  22063. /* 97 */ "NullRow",
  22064. /* 98 */ "Last",
  22065. /* 99 */ "SorterSort",
  22066. /* 100 */ "Sort",
  22067. /* 101 */ "Rewind",
  22068. /* 102 */ "SorterInsert",
  22069. /* 103 */ "IdxInsert",
  22070. /* 104 */ "IdxDelete",
  22071. /* 105 */ "IdxRowid",
  22072. /* 106 */ "IdxLT",
  22073. /* 107 */ "IdxGE",
  22074. /* 108 */ "Destroy",
  22075. /* 109 */ "Clear",
  22076. /* 110 */ "CreateIndex",
  22077. /* 111 */ "CreateTable",
  22078. /* 112 */ "ParseSchema",
  22079. /* 113 */ "LoadAnalysis",
  22080. /* 114 */ "DropTable",
  22081. /* 115 */ "DropIndex",
  22082. /* 116 */ "DropTrigger",
  22083. /* 117 */ "IntegrityCk",
  22084. /* 118 */ "RowSetAdd",
  22085. /* 119 */ "RowSetRead",
  22086. /* 120 */ "RowSetTest",
  22087. /* 121 */ "Program",
  22088. /* 122 */ "Param",
  22089. /* 123 */ "FkCounter",
  22090. /* 124 */ "FkIfZero",
  22091. /* 125 */ "MemMax",
  22092. /* 126 */ "IfPos",
  22093. /* 127 */ "IfNeg",
  22094. /* 128 */ "IfZero",
  22095. /* 129 */ "AggFinal",
  22096. /* 130 */ "Real",
  22097. /* 131 */ "IncrVacuum",
  22098. /* 132 */ "Expire",
  22099. /* 133 */ "TableLock",
  22100. /* 134 */ "VBegin",
  22101. /* 135 */ "VCreate",
  22102. /* 136 */ "VDestroy",
  22103. /* 137 */ "VOpen",
  22104. /* 138 */ "VColumn",
  22105. /* 139 */ "VNext",
  22106. /* 140 */ "VRename",
  22107. /* 141 */ "ToText",
  22108. /* 142 */ "ToBlob",
  22109. /* 143 */ "ToNumeric",
  22110. /* 144 */ "ToInt",
  22111. /* 145 */ "ToReal",
  22112. /* 146 */ "Pagecount",
  22113. /* 147 */ "MaxPgcnt",
  22114. /* 148 */ "Trace",
  22115. /* 149 */ "Noop",
  22116. /* 150 */ "Explain",
  22117. };
  22118. return azName[i];
  22119. }
  22120. #endif
  22121. /************** End of opcodes.c *********************************************/
  22122. /************** Begin file os_unix.c *****************************************/
  22123. /*
  22124. ** 2004 May 22
  22125. **
  22126. ** The author disclaims copyright to this source code. In place of
  22127. ** a legal notice, here is a blessing:
  22128. **
  22129. ** May you do good and not evil.
  22130. ** May you find forgiveness for yourself and forgive others.
  22131. ** May you share freely, never taking more than you give.
  22132. **
  22133. ******************************************************************************
  22134. **
  22135. ** This file contains the VFS implementation for unix-like operating systems
  22136. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  22137. **
  22138. ** There are actually several different VFS implementations in this file.
  22139. ** The differences are in the way that file locking is done. The default
  22140. ** implementation uses Posix Advisory Locks. Alternative implementations
  22141. ** use flock(), dot-files, various proprietary locking schemas, or simply
  22142. ** skip locking all together.
  22143. **
  22144. ** This source file is organized into divisions where the logic for various
  22145. ** subfunctions is contained within the appropriate division. PLEASE
  22146. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  22147. ** in the correct division and should be clearly labeled.
  22148. **
  22149. ** The layout of divisions is as follows:
  22150. **
  22151. ** * General-purpose declarations and utility functions.
  22152. ** * Unique file ID logic used by VxWorks.
  22153. ** * Various locking primitive implementations (all except proxy locking):
  22154. ** + for Posix Advisory Locks
  22155. ** + for no-op locks
  22156. ** + for dot-file locks
  22157. ** + for flock() locking
  22158. ** + for named semaphore locks (VxWorks only)
  22159. ** + for AFP filesystem locks (MacOSX only)
  22160. ** * sqlite3_file methods not associated with locking.
  22161. ** * Definitions of sqlite3_io_methods objects for all locking
  22162. ** methods plus "finder" functions for each locking method.
  22163. ** * sqlite3_vfs method implementations.
  22164. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  22165. ** * Definitions of sqlite3_vfs objects for all locking methods
  22166. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  22167. */
  22168. #if SQLITE_OS_UNIX /* This file is used on unix only */
  22169. /*
  22170. ** There are various methods for file locking used for concurrency
  22171. ** control:
  22172. **
  22173. ** 1. POSIX locking (the default),
  22174. ** 2. No locking,
  22175. ** 3. Dot-file locking,
  22176. ** 4. flock() locking,
  22177. ** 5. AFP locking (OSX only),
  22178. ** 6. Named POSIX semaphores (VXWorks only),
  22179. ** 7. proxy locking. (OSX only)
  22180. **
  22181. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  22182. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  22183. ** selection of the appropriate locking style based on the filesystem
  22184. ** where the database is located.
  22185. */
  22186. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  22187. # if defined(__APPLE__)
  22188. # define SQLITE_ENABLE_LOCKING_STYLE 1
  22189. # else
  22190. # define SQLITE_ENABLE_LOCKING_STYLE 0
  22191. # endif
  22192. #endif
  22193. /*
  22194. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  22195. ** vxworks, or 0 otherwise.
  22196. */
  22197. #ifndef OS_VXWORKS
  22198. # if defined(__RTP__) || defined(_WRS_KERNEL)
  22199. # define OS_VXWORKS 1
  22200. # else
  22201. # define OS_VXWORKS 0
  22202. # endif
  22203. #endif
  22204. /*
  22205. ** These #defines should enable >2GB file support on Posix if the
  22206. ** underlying operating system supports it. If the OS lacks
  22207. ** large file support, these should be no-ops.
  22208. **
  22209. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  22210. ** on the compiler command line. This is necessary if you are compiling
  22211. ** on a recent machine (ex: RedHat 7.2) but you want your code to work
  22212. ** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  22213. ** without this option, LFS is enable. But LFS does not exist in the kernel
  22214. ** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  22215. ** portability you should omit LFS.
  22216. **
  22217. ** The previous paragraph was written in 2005. (This paragraph is written
  22218. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  22219. ** you should probably leave LFS enabled. But some embedded platforms might
  22220. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  22221. */
  22222. #ifndef SQLITE_DISABLE_LFS
  22223. # define _LARGE_FILE 1
  22224. # ifndef _FILE_OFFSET_BITS
  22225. # define _FILE_OFFSET_BITS 64
  22226. # endif
  22227. # define _LARGEFILE_SOURCE 1
  22228. #endif
  22229. /*
  22230. ** standard include files.
  22231. */
  22232. #include <sys/types.h>
  22233. #include <sys/stat.h>
  22234. #include <fcntl.h>
  22235. #include <unistd.h>
  22236. /* #include <time.h> */
  22237. #include <sys/time.h>
  22238. #include <errno.h>
  22239. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  22240. #include <sys/mman.h>
  22241. #endif
  22242. #if SQLITE_ENABLE_LOCKING_STYLE
  22243. # include <sys/ioctl.h>
  22244. # if OS_VXWORKS
  22245. # include <semaphore.h>
  22246. # include <limits.h>
  22247. # else
  22248. # include <sys/file.h>
  22249. # include <sys/param.h>
  22250. # endif
  22251. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  22252. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  22253. # include <sys/mount.h>
  22254. #endif
  22255. #ifdef HAVE_UTIME
  22256. # include <utime.h>
  22257. #endif
  22258. /*
  22259. ** Allowed values of unixFile.fsFlags
  22260. */
  22261. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  22262. /*
  22263. ** If we are to be thread-safe, include the pthreads header and define
  22264. ** the SQLITE_UNIX_THREADS macro.
  22265. */
  22266. #if SQLITE_THREADSAFE
  22267. /* # include <pthread.h> */
  22268. # define SQLITE_UNIX_THREADS 1
  22269. #endif
  22270. /*
  22271. ** Default permissions when creating a new file
  22272. */
  22273. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  22274. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  22275. #endif
  22276. /*
  22277. ** Default permissions when creating auto proxy dir
  22278. */
  22279. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  22280. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  22281. #endif
  22282. /*
  22283. ** Maximum supported path-length.
  22284. */
  22285. #define MAX_PATHNAME 512
  22286. /*
  22287. ** Only set the lastErrno if the error code is a real error and not
  22288. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  22289. */
  22290. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  22291. /* Forward references */
  22292. typedef struct unixShm unixShm; /* Connection shared memory */
  22293. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  22294. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  22295. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  22296. /*
  22297. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  22298. ** cannot be closed immediately. In these cases, instances of the following
  22299. ** structure are used to store the file descriptor while waiting for an
  22300. ** opportunity to either close or reuse it.
  22301. */
  22302. struct UnixUnusedFd {
  22303. int fd; /* File descriptor to close */
  22304. int flags; /* Flags this file descriptor was opened with */
  22305. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  22306. };
  22307. /*
  22308. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  22309. ** VFS implementations.
  22310. */
  22311. typedef struct unixFile unixFile;
  22312. struct unixFile {
  22313. sqlite3_io_methods const *pMethod; /* Always the first entry */
  22314. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  22315. unixInodeInfo *pInode; /* Info about locks on this inode */
  22316. int h; /* The file descriptor */
  22317. unsigned char eFileLock; /* The type of lock held on this fd */
  22318. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  22319. int lastErrno; /* The unix errno from last I/O error */
  22320. void *lockingContext; /* Locking style specific state */
  22321. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  22322. const char *zPath; /* Name of the file */
  22323. unixShm *pShm; /* Shared memory segment information */
  22324. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  22325. #if SQLITE_MAX_MMAP_SIZE>0
  22326. int nFetchOut; /* Number of outstanding xFetch refs */
  22327. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  22328. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  22329. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  22330. void *pMapRegion; /* Memory mapped region */
  22331. #endif
  22332. #ifdef __QNXNTO__
  22333. int sectorSize; /* Device sector size */
  22334. int deviceCharacteristics; /* Precomputed device characteristics */
  22335. #endif
  22336. #if SQLITE_ENABLE_LOCKING_STYLE
  22337. int openFlags; /* The flags specified at open() */
  22338. #endif
  22339. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  22340. unsigned fsFlags; /* cached details from statfs() */
  22341. #endif
  22342. #if OS_VXWORKS
  22343. struct vxworksFileId *pId; /* Unique file ID */
  22344. #endif
  22345. #ifdef SQLITE_DEBUG
  22346. /* The next group of variables are used to track whether or not the
  22347. ** transaction counter in bytes 24-27 of database files are updated
  22348. ** whenever any part of the database changes. An assertion fault will
  22349. ** occur if a file is updated without also updating the transaction
  22350. ** counter. This test is made to avoid new problems similar to the
  22351. ** one described by ticket #3584.
  22352. */
  22353. unsigned char transCntrChng; /* True if the transaction counter changed */
  22354. unsigned char dbUpdate; /* True if any part of database file changed */
  22355. unsigned char inNormalWrite; /* True if in a normal write operation */
  22356. #endif
  22357. #ifdef SQLITE_TEST
  22358. /* In test mode, increase the size of this structure a bit so that
  22359. ** it is larger than the struct CrashFile defined in test6.c.
  22360. */
  22361. char aPadding[32];
  22362. #endif
  22363. };
  22364. /*
  22365. ** Allowed values for the unixFile.ctrlFlags bitmask:
  22366. */
  22367. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  22368. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  22369. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  22370. #ifndef SQLITE_DISABLE_DIRSYNC
  22371. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  22372. #else
  22373. # define UNIXFILE_DIRSYNC 0x00
  22374. #endif
  22375. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  22376. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  22377. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  22378. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  22379. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  22380. /*
  22381. ** Include code that is common to all os_*.c files
  22382. */
  22383. /************** Include os_common.h in the middle of os_unix.c ***************/
  22384. /************** Begin file os_common.h ***************************************/
  22385. /*
  22386. ** 2004 May 22
  22387. **
  22388. ** The author disclaims copyright to this source code. In place of
  22389. ** a legal notice, here is a blessing:
  22390. **
  22391. ** May you do good and not evil.
  22392. ** May you find forgiveness for yourself and forgive others.
  22393. ** May you share freely, never taking more than you give.
  22394. **
  22395. ******************************************************************************
  22396. **
  22397. ** This file contains macros and a little bit of code that is common to
  22398. ** all of the platform-specific files (os_*.c) and is #included into those
  22399. ** files.
  22400. **
  22401. ** This file should be #included by the os_*.c files only. It is not a
  22402. ** general purpose header file.
  22403. */
  22404. #ifndef _OS_COMMON_H_
  22405. #define _OS_COMMON_H_
  22406. /*
  22407. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  22408. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  22409. ** switch. The following code should catch this problem at compile-time.
  22410. */
  22411. #ifdef MEMORY_DEBUG
  22412. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  22413. #endif
  22414. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22415. # ifndef SQLITE_DEBUG_OS_TRACE
  22416. # define SQLITE_DEBUG_OS_TRACE 0
  22417. # endif
  22418. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  22419. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  22420. #else
  22421. # define OSTRACE(X)
  22422. #endif
  22423. /*
  22424. ** Macros for performance tracing. Normally turned off. Only works
  22425. ** on i486 hardware.
  22426. */
  22427. #ifdef SQLITE_PERFORMANCE_TRACE
  22428. /*
  22429. ** hwtime.h contains inline assembler code for implementing
  22430. ** high-performance timing routines.
  22431. */
  22432. /************** Include hwtime.h in the middle of os_common.h ****************/
  22433. /************** Begin file hwtime.h ******************************************/
  22434. /*
  22435. ** 2008 May 27
  22436. **
  22437. ** The author disclaims copyright to this source code. In place of
  22438. ** a legal notice, here is a blessing:
  22439. **
  22440. ** May you do good and not evil.
  22441. ** May you find forgiveness for yourself and forgive others.
  22442. ** May you share freely, never taking more than you give.
  22443. **
  22444. ******************************************************************************
  22445. **
  22446. ** This file contains inline asm code for retrieving "high-performance"
  22447. ** counters for x86 class CPUs.
  22448. */
  22449. #ifndef _HWTIME_H_
  22450. #define _HWTIME_H_
  22451. /*
  22452. ** The following routine only works on pentium-class (or newer) processors.
  22453. ** It uses the RDTSC opcode to read the cycle count value out of the
  22454. ** processor and returns that value. This can be used for high-res
  22455. ** profiling.
  22456. */
  22457. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  22458. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  22459. #if defined(__GNUC__)
  22460. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22461. unsigned int lo, hi;
  22462. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  22463. return (sqlite_uint64)hi << 32 | lo;
  22464. }
  22465. #elif defined(_MSC_VER)
  22466. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  22467. __asm {
  22468. rdtsc
  22469. ret ; return value at EDX:EAX
  22470. }
  22471. }
  22472. #endif
  22473. #elif (defined(__GNUC__) && defined(__x86_64__))
  22474. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22475. unsigned long val;
  22476. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  22477. return val;
  22478. }
  22479. #elif (defined(__GNUC__) && defined(__ppc__))
  22480. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  22481. unsigned long long retval;
  22482. unsigned long junk;
  22483. __asm__ __volatile__ ("\n\
  22484. 1: mftbu %1\n\
  22485. mftb %L0\n\
  22486. mftbu %0\n\
  22487. cmpw %0,%1\n\
  22488. bne 1b"
  22489. : "=r" (retval), "=r" (junk));
  22490. return retval;
  22491. }
  22492. #else
  22493. #error Need implementation of sqlite3Hwtime() for your platform.
  22494. /*
  22495. ** To compile without implementing sqlite3Hwtime() for your platform,
  22496. ** you can remove the above #error and use the following
  22497. ** stub function. You will lose timing support for many
  22498. ** of the debugging and testing utilities, but it should at
  22499. ** least compile and run.
  22500. */
  22501. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  22502. #endif
  22503. #endif /* !defined(_HWTIME_H_) */
  22504. /************** End of hwtime.h **********************************************/
  22505. /************** Continuing where we left off in os_common.h ******************/
  22506. static sqlite_uint64 g_start;
  22507. static sqlite_uint64 g_elapsed;
  22508. #define TIMER_START g_start=sqlite3Hwtime()
  22509. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  22510. #define TIMER_ELAPSED g_elapsed
  22511. #else
  22512. #define TIMER_START
  22513. #define TIMER_END
  22514. #define TIMER_ELAPSED ((sqlite_uint64)0)
  22515. #endif
  22516. /*
  22517. ** If we compile with the SQLITE_TEST macro set, then the following block
  22518. ** of code will give us the ability to simulate a disk I/O error. This
  22519. ** is used for testing the I/O recovery logic.
  22520. */
  22521. #ifdef SQLITE_TEST
  22522. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  22523. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  22524. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  22525. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  22526. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  22527. SQLITE_API int sqlite3_diskfull_pending = 0;
  22528. SQLITE_API int sqlite3_diskfull = 0;
  22529. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  22530. #define SimulateIOError(CODE) \
  22531. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  22532. || sqlite3_io_error_pending-- == 1 ) \
  22533. { local_ioerr(); CODE; }
  22534. static void local_ioerr(){
  22535. IOTRACE(("IOERR\n"));
  22536. sqlite3_io_error_hit++;
  22537. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  22538. }
  22539. #define SimulateDiskfullError(CODE) \
  22540. if( sqlite3_diskfull_pending ){ \
  22541. if( sqlite3_diskfull_pending == 1 ){ \
  22542. local_ioerr(); \
  22543. sqlite3_diskfull = 1; \
  22544. sqlite3_io_error_hit = 1; \
  22545. CODE; \
  22546. }else{ \
  22547. sqlite3_diskfull_pending--; \
  22548. } \
  22549. }
  22550. #else
  22551. #define SimulateIOErrorBenign(X)
  22552. #define SimulateIOError(A)
  22553. #define SimulateDiskfullError(A)
  22554. #endif
  22555. /*
  22556. ** When testing, keep a count of the number of open files.
  22557. */
  22558. #ifdef SQLITE_TEST
  22559. SQLITE_API int sqlite3_open_file_count = 0;
  22560. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  22561. #else
  22562. #define OpenCounter(X)
  22563. #endif
  22564. #endif /* !defined(_OS_COMMON_H_) */
  22565. /************** End of os_common.h *******************************************/
  22566. /************** Continuing where we left off in os_unix.c ********************/
  22567. /*
  22568. ** Define various macros that are missing from some systems.
  22569. */
  22570. #ifndef O_LARGEFILE
  22571. # define O_LARGEFILE 0
  22572. #endif
  22573. #ifdef SQLITE_DISABLE_LFS
  22574. # undef O_LARGEFILE
  22575. # define O_LARGEFILE 0
  22576. #endif
  22577. #ifndef O_NOFOLLOW
  22578. # define O_NOFOLLOW 0
  22579. #endif
  22580. #ifndef O_BINARY
  22581. # define O_BINARY 0
  22582. #endif
  22583. /*
  22584. ** The threadid macro resolves to the thread-id or to 0. Used for
  22585. ** testing and debugging only.
  22586. */
  22587. #if SQLITE_THREADSAFE
  22588. #define threadid pthread_self()
  22589. #else
  22590. #define threadid 0
  22591. #endif
  22592. /*
  22593. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  22594. */
  22595. #if !defined(HAVE_MREMAP)
  22596. # if defined(__linux__) && defined(_GNU_SOURCE)
  22597. # define HAVE_MREMAP 1
  22598. # else
  22599. # define HAVE_MREMAP 0
  22600. # endif
  22601. #endif
  22602. /*
  22603. ** Different Unix systems declare open() in different ways. Same use
  22604. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  22605. ** The difference is important when using a pointer to the function.
  22606. **
  22607. ** The safest way to deal with the problem is to always use this wrapper
  22608. ** which always has the same well-defined interface.
  22609. */
  22610. static int posixOpen(const char *zFile, int flags, int mode){
  22611. return open(zFile, flags, mode);
  22612. }
  22613. /*
  22614. ** On some systems, calls to fchown() will trigger a message in a security
  22615. ** log if they come from non-root processes. So avoid calling fchown() if
  22616. ** we are not running as root.
  22617. */
  22618. static int posixFchown(int fd, uid_t uid, gid_t gid){
  22619. return geteuid() ? 0 : fchown(fd,uid,gid);
  22620. }
  22621. /* Forward reference */
  22622. static int openDirectory(const char*, int*);
  22623. /*
  22624. ** Many system calls are accessed through pointer-to-functions so that
  22625. ** they may be overridden at runtime to facilitate fault injection during
  22626. ** testing and sandboxing. The following array holds the names and pointers
  22627. ** to all overrideable system calls.
  22628. */
  22629. static struct unix_syscall {
  22630. const char *zName; /* Name of the system call */
  22631. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  22632. sqlite3_syscall_ptr pDefault; /* Default value */
  22633. } aSyscall[] = {
  22634. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  22635. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  22636. { "close", (sqlite3_syscall_ptr)close, 0 },
  22637. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  22638. { "access", (sqlite3_syscall_ptr)access, 0 },
  22639. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  22640. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  22641. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  22642. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  22643. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  22644. /*
  22645. ** The DJGPP compiler environment looks mostly like Unix, but it
  22646. ** lacks the fcntl() system call. So redefine fcntl() to be something
  22647. ** that always succeeds. This means that locking does not occur under
  22648. ** DJGPP. But it is DOS - what did you expect?
  22649. */
  22650. #ifdef __DJGPP__
  22651. { "fstat", 0, 0 },
  22652. #define osFstat(a,b,c) 0
  22653. #else
  22654. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  22655. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  22656. #endif
  22657. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  22658. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  22659. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  22660. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  22661. { "read", (sqlite3_syscall_ptr)read, 0 },
  22662. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  22663. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22664. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  22665. #else
  22666. { "pread", (sqlite3_syscall_ptr)0, 0 },
  22667. #endif
  22668. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  22669. #if defined(USE_PREAD64)
  22670. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  22671. #else
  22672. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  22673. #endif
  22674. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  22675. { "write", (sqlite3_syscall_ptr)write, 0 },
  22676. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  22677. #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
  22678. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  22679. #else
  22680. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  22681. #endif
  22682. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  22683. aSyscall[12].pCurrent)
  22684. #if defined(USE_PREAD64)
  22685. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  22686. #else
  22687. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  22688. #endif
  22689. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  22690. aSyscall[13].pCurrent)
  22691. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  22692. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  22693. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  22694. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  22695. #else
  22696. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  22697. #endif
  22698. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  22699. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  22700. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  22701. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  22702. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  22703. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  22704. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  22705. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  22706. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  22707. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  22708. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  22709. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  22710. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  22711. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  22712. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  22713. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  22714. #if HAVE_MREMAP
  22715. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  22716. #else
  22717. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  22718. #endif
  22719. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  22720. #endif
  22721. }; /* End of the overrideable system calls */
  22722. /*
  22723. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  22724. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  22725. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  22726. ** system call named zName.
  22727. */
  22728. static int unixSetSystemCall(
  22729. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  22730. const char *zName, /* Name of system call to override */
  22731. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  22732. ){
  22733. unsigned int i;
  22734. int rc = SQLITE_NOTFOUND;
  22735. UNUSED_PARAMETER(pNotUsed);
  22736. if( zName==0 ){
  22737. /* If no zName is given, restore all system calls to their default
  22738. ** settings and return NULL
  22739. */
  22740. rc = SQLITE_OK;
  22741. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22742. if( aSyscall[i].pDefault ){
  22743. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  22744. }
  22745. }
  22746. }else{
  22747. /* If zName is specified, operate on only the one system call
  22748. ** specified.
  22749. */
  22750. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22751. if( strcmp(zName, aSyscall[i].zName)==0 ){
  22752. if( aSyscall[i].pDefault==0 ){
  22753. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  22754. }
  22755. rc = SQLITE_OK;
  22756. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  22757. aSyscall[i].pCurrent = pNewFunc;
  22758. break;
  22759. }
  22760. }
  22761. }
  22762. return rc;
  22763. }
  22764. /*
  22765. ** Return the value of a system call. Return NULL if zName is not a
  22766. ** recognized system call name. NULL is also returned if the system call
  22767. ** is currently undefined.
  22768. */
  22769. static sqlite3_syscall_ptr unixGetSystemCall(
  22770. sqlite3_vfs *pNotUsed,
  22771. const char *zName
  22772. ){
  22773. unsigned int i;
  22774. UNUSED_PARAMETER(pNotUsed);
  22775. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  22776. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  22777. }
  22778. return 0;
  22779. }
  22780. /*
  22781. ** Return the name of the first system call after zName. If zName==NULL
  22782. ** then return the name of the first system call. Return NULL if zName
  22783. ** is the last system call or if zName is not the name of a valid
  22784. ** system call.
  22785. */
  22786. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  22787. int i = -1;
  22788. UNUSED_PARAMETER(p);
  22789. if( zName ){
  22790. for(i=0; i<ArraySize(aSyscall)-1; i++){
  22791. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  22792. }
  22793. }
  22794. for(i++; i<ArraySize(aSyscall); i++){
  22795. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  22796. }
  22797. return 0;
  22798. }
  22799. /*
  22800. ** Do not accept any file descriptor less than this value, in order to avoid
  22801. ** opening database file using file descriptors that are commonly used for
  22802. ** standard input, output, and error.
  22803. */
  22804. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  22805. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  22806. #endif
  22807. /*
  22808. ** Invoke open(). Do so multiple times, until it either succeeds or
  22809. ** fails for some reason other than EINTR.
  22810. **
  22811. ** If the file creation mode "m" is 0 then set it to the default for
  22812. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  22813. ** 0644) as modified by the system umask. If m is not 0, then
  22814. ** make the file creation mode be exactly m ignoring the umask.
  22815. **
  22816. ** The m parameter will be non-zero only when creating -wal, -journal,
  22817. ** and -shm files. We want those files to have *exactly* the same
  22818. ** permissions as their original database, unadulterated by the umask.
  22819. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  22820. ** transaction crashes and leaves behind hot journals, then any
  22821. ** process that is able to write to the database will also be able to
  22822. ** recover the hot journals.
  22823. */
  22824. static int robust_open(const char *z, int f, mode_t m){
  22825. int fd;
  22826. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  22827. while(1){
  22828. #if defined(O_CLOEXEC)
  22829. fd = osOpen(z,f|O_CLOEXEC,m2);
  22830. #else
  22831. fd = osOpen(z,f,m2);
  22832. #endif
  22833. if( fd<0 ){
  22834. if( errno==EINTR ) continue;
  22835. break;
  22836. }
  22837. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  22838. osClose(fd);
  22839. sqlite3_log(SQLITE_WARNING,
  22840. "attempt to open \"%s\" as file descriptor %d", z, fd);
  22841. fd = -1;
  22842. if( osOpen("/dev/null", f, m)<0 ) break;
  22843. }
  22844. if( fd>=0 ){
  22845. if( m!=0 ){
  22846. struct stat statbuf;
  22847. if( osFstat(fd, &statbuf)==0
  22848. && statbuf.st_size==0
  22849. && (statbuf.st_mode&0777)!=m
  22850. ){
  22851. osFchmod(fd, m);
  22852. }
  22853. }
  22854. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  22855. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  22856. #endif
  22857. }
  22858. return fd;
  22859. }
  22860. /*
  22861. ** Helper functions to obtain and relinquish the global mutex. The
  22862. ** global mutex is used to protect the unixInodeInfo and
  22863. ** vxworksFileId objects used by this file, all of which may be
  22864. ** shared by multiple threads.
  22865. **
  22866. ** Function unixMutexHeld() is used to assert() that the global mutex
  22867. ** is held when required. This function is only used as part of assert()
  22868. ** statements. e.g.
  22869. **
  22870. ** unixEnterMutex()
  22871. ** assert( unixMutexHeld() );
  22872. ** unixEnterLeave()
  22873. */
  22874. static void unixEnterMutex(void){
  22875. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22876. }
  22877. static void unixLeaveMutex(void){
  22878. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22879. }
  22880. #ifdef SQLITE_DEBUG
  22881. static int unixMutexHeld(void) {
  22882. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  22883. }
  22884. #endif
  22885. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  22886. /*
  22887. ** Helper function for printing out trace information from debugging
  22888. ** binaries. This returns the string represetation of the supplied
  22889. ** integer lock-type.
  22890. */
  22891. static const char *azFileLock(int eFileLock){
  22892. switch( eFileLock ){
  22893. case NO_LOCK: return "NONE";
  22894. case SHARED_LOCK: return "SHARED";
  22895. case RESERVED_LOCK: return "RESERVED";
  22896. case PENDING_LOCK: return "PENDING";
  22897. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  22898. }
  22899. return "ERROR";
  22900. }
  22901. #endif
  22902. #ifdef SQLITE_LOCK_TRACE
  22903. /*
  22904. ** Print out information about all locking operations.
  22905. **
  22906. ** This routine is used for troubleshooting locks on multithreaded
  22907. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  22908. ** command-line option on the compiler. This code is normally
  22909. ** turned off.
  22910. */
  22911. static int lockTrace(int fd, int op, struct flock *p){
  22912. char *zOpName, *zType;
  22913. int s;
  22914. int savedErrno;
  22915. if( op==F_GETLK ){
  22916. zOpName = "GETLK";
  22917. }else if( op==F_SETLK ){
  22918. zOpName = "SETLK";
  22919. }else{
  22920. s = osFcntl(fd, op, p);
  22921. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  22922. return s;
  22923. }
  22924. if( p->l_type==F_RDLCK ){
  22925. zType = "RDLCK";
  22926. }else if( p->l_type==F_WRLCK ){
  22927. zType = "WRLCK";
  22928. }else if( p->l_type==F_UNLCK ){
  22929. zType = "UNLCK";
  22930. }else{
  22931. assert( 0 );
  22932. }
  22933. assert( p->l_whence==SEEK_SET );
  22934. s = osFcntl(fd, op, p);
  22935. savedErrno = errno;
  22936. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  22937. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  22938. (int)p->l_pid, s);
  22939. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  22940. struct flock l2;
  22941. l2 = *p;
  22942. osFcntl(fd, F_GETLK, &l2);
  22943. if( l2.l_type==F_RDLCK ){
  22944. zType = "RDLCK";
  22945. }else if( l2.l_type==F_WRLCK ){
  22946. zType = "WRLCK";
  22947. }else if( l2.l_type==F_UNLCK ){
  22948. zType = "UNLCK";
  22949. }else{
  22950. assert( 0 );
  22951. }
  22952. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  22953. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  22954. }
  22955. errno = savedErrno;
  22956. return s;
  22957. }
  22958. #undef osFcntl
  22959. #define osFcntl lockTrace
  22960. #endif /* SQLITE_LOCK_TRACE */
  22961. /*
  22962. ** Retry ftruncate() calls that fail due to EINTR
  22963. */
  22964. static int robust_ftruncate(int h, sqlite3_int64 sz){
  22965. int rc;
  22966. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  22967. return rc;
  22968. }
  22969. /*
  22970. ** This routine translates a standard POSIX errno code into something
  22971. ** useful to the clients of the sqlite3 functions. Specifically, it is
  22972. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  22973. ** and a variety of "please close the file descriptor NOW" errors into
  22974. ** SQLITE_IOERR
  22975. **
  22976. ** Errors during initialization of locks, or file system support for locks,
  22977. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  22978. */
  22979. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  22980. switch (posixError) {
  22981. #if 0
  22982. /* At one point this code was not commented out. In theory, this branch
  22983. ** should never be hit, as this function should only be called after
  22984. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  22985. ** the value of errno as the first argument. Since a system call has failed,
  22986. ** errno should be non-zero.
  22987. **
  22988. ** Despite this, if errno really is zero, we still don't want to return
  22989. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  22990. ** propagated back to the caller. Commenting this branch out means errno==0
  22991. ** will be handled by the "default:" case below.
  22992. */
  22993. case 0:
  22994. return SQLITE_OK;
  22995. #endif
  22996. case EAGAIN:
  22997. case ETIMEDOUT:
  22998. case EBUSY:
  22999. case EINTR:
  23000. case ENOLCK:
  23001. /* random NFS retry error, unless during file system support
  23002. * introspection, in which it actually means what it says */
  23003. return SQLITE_BUSY;
  23004. case EACCES:
  23005. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  23006. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  23007. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  23008. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  23009. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  23010. return SQLITE_BUSY;
  23011. }
  23012. /* else fall through */
  23013. case EPERM:
  23014. return SQLITE_PERM;
  23015. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  23016. ** this module never makes such a call. And the code in SQLite itself
  23017. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  23018. ** this case is also commented out. If the system does set errno to EDEADLK,
  23019. ** the default SQLITE_IOERR_XXX code will be returned. */
  23020. #if 0
  23021. case EDEADLK:
  23022. return SQLITE_IOERR_BLOCKED;
  23023. #endif
  23024. #if EOPNOTSUPP!=ENOTSUP
  23025. case EOPNOTSUPP:
  23026. /* something went terribly awry, unless during file system support
  23027. * introspection, in which it actually means what it says */
  23028. #endif
  23029. #ifdef ENOTSUP
  23030. case ENOTSUP:
  23031. /* invalid fd, unless during file system support introspection, in which
  23032. * it actually means what it says */
  23033. #endif
  23034. case EIO:
  23035. case EBADF:
  23036. case EINVAL:
  23037. case ENOTCONN:
  23038. case ENODEV:
  23039. case ENXIO:
  23040. case ENOENT:
  23041. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  23042. case ESTALE:
  23043. #endif
  23044. case ENOSYS:
  23045. /* these should force the client to close the file and reconnect */
  23046. default:
  23047. return sqliteIOErr;
  23048. }
  23049. }
  23050. /******************************************************************************
  23051. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  23052. **
  23053. ** On most versions of unix, we can get a unique ID for a file by concatenating
  23054. ** the device number and the inode number. But this does not work on VxWorks.
  23055. ** On VxWorks, a unique file id must be based on the canonical filename.
  23056. **
  23057. ** A pointer to an instance of the following structure can be used as a
  23058. ** unique file ID in VxWorks. Each instance of this structure contains
  23059. ** a copy of the canonical filename. There is also a reference count.
  23060. ** The structure is reclaimed when the number of pointers to it drops to
  23061. ** zero.
  23062. **
  23063. ** There are never very many files open at one time and lookups are not
  23064. ** a performance-critical path, so it is sufficient to put these
  23065. ** structures on a linked list.
  23066. */
  23067. struct vxworksFileId {
  23068. struct vxworksFileId *pNext; /* Next in a list of them all */
  23069. int nRef; /* Number of references to this one */
  23070. int nName; /* Length of the zCanonicalName[] string */
  23071. char *zCanonicalName; /* Canonical filename */
  23072. };
  23073. #if OS_VXWORKS
  23074. /*
  23075. ** All unique filenames are held on a linked list headed by this
  23076. ** variable:
  23077. */
  23078. static struct vxworksFileId *vxworksFileList = 0;
  23079. /*
  23080. ** Simplify a filename into its canonical form
  23081. ** by making the following changes:
  23082. **
  23083. ** * removing any trailing and duplicate /
  23084. ** * convert /./ into just /
  23085. ** * convert /A/../ where A is any simple name into just /
  23086. **
  23087. ** Changes are made in-place. Return the new name length.
  23088. **
  23089. ** The original filename is in z[0..n-1]. Return the number of
  23090. ** characters in the simplified name.
  23091. */
  23092. static int vxworksSimplifyName(char *z, int n){
  23093. int i, j;
  23094. while( n>1 && z[n-1]=='/' ){ n--; }
  23095. for(i=j=0; i<n; i++){
  23096. if( z[i]=='/' ){
  23097. if( z[i+1]=='/' ) continue;
  23098. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  23099. i += 1;
  23100. continue;
  23101. }
  23102. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  23103. while( j>0 && z[j-1]!='/' ){ j--; }
  23104. if( j>0 ){ j--; }
  23105. i += 2;
  23106. continue;
  23107. }
  23108. }
  23109. z[j++] = z[i];
  23110. }
  23111. z[j] = 0;
  23112. return j;
  23113. }
  23114. /*
  23115. ** Find a unique file ID for the given absolute pathname. Return
  23116. ** a pointer to the vxworksFileId object. This pointer is the unique
  23117. ** file ID.
  23118. **
  23119. ** The nRef field of the vxworksFileId object is incremented before
  23120. ** the object is returned. A new vxworksFileId object is created
  23121. ** and added to the global list if necessary.
  23122. **
  23123. ** If a memory allocation error occurs, return NULL.
  23124. */
  23125. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  23126. struct vxworksFileId *pNew; /* search key and new file ID */
  23127. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  23128. int n; /* Length of zAbsoluteName string */
  23129. assert( zAbsoluteName[0]=='/' );
  23130. n = (int)strlen(zAbsoluteName);
  23131. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  23132. if( pNew==0 ) return 0;
  23133. pNew->zCanonicalName = (char*)&pNew[1];
  23134. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  23135. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  23136. /* Search for an existing entry that matching the canonical name.
  23137. ** If found, increment the reference count and return a pointer to
  23138. ** the existing file ID.
  23139. */
  23140. unixEnterMutex();
  23141. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  23142. if( pCandidate->nName==n
  23143. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  23144. ){
  23145. sqlite3_free(pNew);
  23146. pCandidate->nRef++;
  23147. unixLeaveMutex();
  23148. return pCandidate;
  23149. }
  23150. }
  23151. /* No match was found. We will make a new file ID */
  23152. pNew->nRef = 1;
  23153. pNew->nName = n;
  23154. pNew->pNext = vxworksFileList;
  23155. vxworksFileList = pNew;
  23156. unixLeaveMutex();
  23157. return pNew;
  23158. }
  23159. /*
  23160. ** Decrement the reference count on a vxworksFileId object. Free
  23161. ** the object when the reference count reaches zero.
  23162. */
  23163. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  23164. unixEnterMutex();
  23165. assert( pId->nRef>0 );
  23166. pId->nRef--;
  23167. if( pId->nRef==0 ){
  23168. struct vxworksFileId **pp;
  23169. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  23170. assert( *pp==pId );
  23171. *pp = pId->pNext;
  23172. sqlite3_free(pId);
  23173. }
  23174. unixLeaveMutex();
  23175. }
  23176. #endif /* OS_VXWORKS */
  23177. /*************** End of Unique File ID Utility Used By VxWorks ****************
  23178. ******************************************************************************/
  23179. /******************************************************************************
  23180. *************************** Posix Advisory Locking ****************************
  23181. **
  23182. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  23183. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  23184. ** sets or clears a lock, that operation overrides any prior locks set
  23185. ** by the same process. It does not explicitly say so, but this implies
  23186. ** that it overrides locks set by the same process using a different
  23187. ** file descriptor. Consider this test case:
  23188. **
  23189. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  23190. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  23191. **
  23192. ** Suppose ./file1 and ./file2 are really the same file (because
  23193. ** one is a hard or symbolic link to the other) then if you set
  23194. ** an exclusive lock on fd1, then try to get an exclusive lock
  23195. ** on fd2, it works. I would have expected the second lock to
  23196. ** fail since there was already a lock on the file due to fd1.
  23197. ** But not so. Since both locks came from the same process, the
  23198. ** second overrides the first, even though they were on different
  23199. ** file descriptors opened on different file names.
  23200. **
  23201. ** This means that we cannot use POSIX locks to synchronize file access
  23202. ** among competing threads of the same process. POSIX locks will work fine
  23203. ** to synchronize access for threads in separate processes, but not
  23204. ** threads within the same process.
  23205. **
  23206. ** To work around the problem, SQLite has to manage file locks internally
  23207. ** on its own. Whenever a new database is opened, we have to find the
  23208. ** specific inode of the database file (the inode is determined by the
  23209. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  23210. ** and check for locks already existing on that inode. When locks are
  23211. ** created or removed, we have to look at our own internal record of the
  23212. ** locks to see if another thread has previously set a lock on that same
  23213. ** inode.
  23214. **
  23215. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  23216. ** For VxWorks, we have to use the alternative unique ID system based on
  23217. ** canonical filename and implemented in the previous division.)
  23218. **
  23219. ** The sqlite3_file structure for POSIX is no longer just an integer file
  23220. ** descriptor. It is now a structure that holds the integer file
  23221. ** descriptor and a pointer to a structure that describes the internal
  23222. ** locks on the corresponding inode. There is one locking structure
  23223. ** per inode, so if the same inode is opened twice, both unixFile structures
  23224. ** point to the same locking structure. The locking structure keeps
  23225. ** a reference count (so we will know when to delete it) and a "cnt"
  23226. ** field that tells us its internal lock status. cnt==0 means the
  23227. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  23228. ** cnt>0 means there are cnt shared locks on the file.
  23229. **
  23230. ** Any attempt to lock or unlock a file first checks the locking
  23231. ** structure. The fcntl() system call is only invoked to set a
  23232. ** POSIX lock if the internal lock structure transitions between
  23233. ** a locked and an unlocked state.
  23234. **
  23235. ** But wait: there are yet more problems with POSIX advisory locks.
  23236. **
  23237. ** If you close a file descriptor that points to a file that has locks,
  23238. ** all locks on that file that are owned by the current process are
  23239. ** released. To work around this problem, each unixInodeInfo object
  23240. ** maintains a count of the number of pending locks on tha inode.
  23241. ** When an attempt is made to close an unixFile, if there are
  23242. ** other unixFile open on the same inode that are holding locks, the call
  23243. ** to close() the file descriptor is deferred until all of the locks clear.
  23244. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  23245. ** be closed and that list is walked (and cleared) when the last lock
  23246. ** clears.
  23247. **
  23248. ** Yet another problem: LinuxThreads do not play well with posix locks.
  23249. **
  23250. ** Many older versions of linux use the LinuxThreads library which is
  23251. ** not posix compliant. Under LinuxThreads, a lock created by thread
  23252. ** A cannot be modified or overridden by a different thread B.
  23253. ** Only thread A can modify the lock. Locking behavior is correct
  23254. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  23255. ** on linux - with NPTL a lock created by thread A can override locks
  23256. ** in thread B. But there is no way to know at compile-time which
  23257. ** threading library is being used. So there is no way to know at
  23258. ** compile-time whether or not thread A can override locks on thread B.
  23259. ** One has to do a run-time check to discover the behavior of the
  23260. ** current process.
  23261. **
  23262. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  23263. ** was dropped beginning with version 3.7.0. SQLite will still work with
  23264. ** LinuxThreads provided that (1) there is no more than one connection
  23265. ** per database file in the same process and (2) database connections
  23266. ** do not move across threads.
  23267. */
  23268. /*
  23269. ** An instance of the following structure serves as the key used
  23270. ** to locate a particular unixInodeInfo object.
  23271. */
  23272. struct unixFileId {
  23273. dev_t dev; /* Device number */
  23274. #if OS_VXWORKS
  23275. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  23276. #else
  23277. ino_t ino; /* Inode number */
  23278. #endif
  23279. };
  23280. /*
  23281. ** An instance of the following structure is allocated for each open
  23282. ** inode. Or, on LinuxThreads, there is one of these structures for
  23283. ** each inode opened by each thread.
  23284. **
  23285. ** A single inode can have multiple file descriptors, so each unixFile
  23286. ** structure contains a pointer to an instance of this object and this
  23287. ** object keeps a count of the number of unixFile pointing to it.
  23288. */
  23289. struct unixInodeInfo {
  23290. struct unixFileId fileId; /* The lookup key */
  23291. int nShared; /* Number of SHARED locks held */
  23292. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  23293. unsigned char bProcessLock; /* An exclusive process lock is held */
  23294. int nRef; /* Number of pointers to this structure */
  23295. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  23296. int nLock; /* Number of outstanding file locks */
  23297. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  23298. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  23299. unixInodeInfo *pPrev; /* .... doubly linked */
  23300. #if SQLITE_ENABLE_LOCKING_STYLE
  23301. unsigned long long sharedByte; /* for AFP simulated shared lock */
  23302. #endif
  23303. #if OS_VXWORKS
  23304. sem_t *pSem; /* Named POSIX semaphore */
  23305. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  23306. #endif
  23307. };
  23308. /*
  23309. ** A lists of all unixInodeInfo objects.
  23310. */
  23311. static unixInodeInfo *inodeList = 0;
  23312. /*
  23313. **
  23314. ** This function - unixLogError_x(), is only ever called via the macro
  23315. ** unixLogError().
  23316. **
  23317. ** It is invoked after an error occurs in an OS function and errno has been
  23318. ** set. It logs a message using sqlite3_log() containing the current value of
  23319. ** errno and, if possible, the human-readable equivalent from strerror() or
  23320. ** strerror_r().
  23321. **
  23322. ** The first argument passed to the macro should be the error code that
  23323. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  23324. ** The two subsequent arguments should be the name of the OS function that
  23325. ** failed (e.g. "unlink", "open") and the associated file-system path,
  23326. ** if any.
  23327. */
  23328. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  23329. static int unixLogErrorAtLine(
  23330. int errcode, /* SQLite error code */
  23331. const char *zFunc, /* Name of OS function that failed */
  23332. const char *zPath, /* File path associated with error */
  23333. int iLine /* Source line number where error occurred */
  23334. ){
  23335. char *zErr; /* Message from strerror() or equivalent */
  23336. int iErrno = errno; /* Saved syscall error number */
  23337. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  23338. ** the strerror() function to obtain the human-readable error message
  23339. ** equivalent to errno. Otherwise, use strerror_r().
  23340. */
  23341. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  23342. char aErr[80];
  23343. memset(aErr, 0, sizeof(aErr));
  23344. zErr = aErr;
  23345. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  23346. ** assume that the system provides the GNU version of strerror_r() that
  23347. ** returns a pointer to a buffer containing the error message. That pointer
  23348. ** may point to aErr[], or it may point to some static storage somewhere.
  23349. ** Otherwise, assume that the system provides the POSIX version of
  23350. ** strerror_r(), which always writes an error message into aErr[].
  23351. **
  23352. ** If the code incorrectly assumes that it is the POSIX version that is
  23353. ** available, the error message will often be an empty string. Not a
  23354. ** huge problem. Incorrectly concluding that the GNU version is available
  23355. ** could lead to a segfault though.
  23356. */
  23357. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  23358. zErr =
  23359. # endif
  23360. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  23361. #elif SQLITE_THREADSAFE
  23362. /* This is a threadsafe build, but strerror_r() is not available. */
  23363. zErr = "";
  23364. #else
  23365. /* Non-threadsafe build, use strerror(). */
  23366. zErr = strerror(iErrno);
  23367. #endif
  23368. if( zPath==0 ) zPath = "";
  23369. sqlite3_log(errcode,
  23370. "os_unix.c:%d: (%d) %s(%s) - %s",
  23371. iLine, iErrno, zFunc, zPath, zErr
  23372. );
  23373. return errcode;
  23374. }
  23375. /*
  23376. ** Close a file descriptor.
  23377. **
  23378. ** We assume that close() almost always works, since it is only in a
  23379. ** very sick application or on a very sick platform that it might fail.
  23380. ** If it does fail, simply leak the file descriptor, but do log the
  23381. ** error.
  23382. **
  23383. ** Note that it is not safe to retry close() after EINTR since the
  23384. ** file descriptor might have already been reused by another thread.
  23385. ** So we don't even try to recover from an EINTR. Just log the error
  23386. ** and move on.
  23387. */
  23388. static void robust_close(unixFile *pFile, int h, int lineno){
  23389. if( osClose(h) ){
  23390. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  23391. pFile ? pFile->zPath : 0, lineno);
  23392. }
  23393. }
  23394. /*
  23395. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  23396. */
  23397. static void closePendingFds(unixFile *pFile){
  23398. unixInodeInfo *pInode = pFile->pInode;
  23399. UnixUnusedFd *p;
  23400. UnixUnusedFd *pNext;
  23401. for(p=pInode->pUnused; p; p=pNext){
  23402. pNext = p->pNext;
  23403. robust_close(pFile, p->fd, __LINE__);
  23404. sqlite3_free(p);
  23405. }
  23406. pInode->pUnused = 0;
  23407. }
  23408. /*
  23409. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  23410. **
  23411. ** The mutex entered using the unixEnterMutex() function must be held
  23412. ** when this function is called.
  23413. */
  23414. static void releaseInodeInfo(unixFile *pFile){
  23415. unixInodeInfo *pInode = pFile->pInode;
  23416. assert( unixMutexHeld() );
  23417. if( ALWAYS(pInode) ){
  23418. pInode->nRef--;
  23419. if( pInode->nRef==0 ){
  23420. assert( pInode->pShmNode==0 );
  23421. closePendingFds(pFile);
  23422. if( pInode->pPrev ){
  23423. assert( pInode->pPrev->pNext==pInode );
  23424. pInode->pPrev->pNext = pInode->pNext;
  23425. }else{
  23426. assert( inodeList==pInode );
  23427. inodeList = pInode->pNext;
  23428. }
  23429. if( pInode->pNext ){
  23430. assert( pInode->pNext->pPrev==pInode );
  23431. pInode->pNext->pPrev = pInode->pPrev;
  23432. }
  23433. sqlite3_free(pInode);
  23434. }
  23435. }
  23436. }
  23437. /*
  23438. ** Given a file descriptor, locate the unixInodeInfo object that
  23439. ** describes that file descriptor. Create a new one if necessary. The
  23440. ** return value might be uninitialized if an error occurs.
  23441. **
  23442. ** The mutex entered using the unixEnterMutex() function must be held
  23443. ** when this function is called.
  23444. **
  23445. ** Return an appropriate error code.
  23446. */
  23447. static int findInodeInfo(
  23448. unixFile *pFile, /* Unix file with file desc used in the key */
  23449. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  23450. ){
  23451. int rc; /* System call return code */
  23452. int fd; /* The file descriptor for pFile */
  23453. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  23454. struct stat statbuf; /* Low-level file information */
  23455. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  23456. assert( unixMutexHeld() );
  23457. /* Get low-level information about the file that we can used to
  23458. ** create a unique name for the file.
  23459. */
  23460. fd = pFile->h;
  23461. rc = osFstat(fd, &statbuf);
  23462. if( rc!=0 ){
  23463. pFile->lastErrno = errno;
  23464. #ifdef EOVERFLOW
  23465. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  23466. #endif
  23467. return SQLITE_IOERR;
  23468. }
  23469. #ifdef __APPLE__
  23470. /* On OS X on an msdos filesystem, the inode number is reported
  23471. ** incorrectly for zero-size files. See ticket #3260. To work
  23472. ** around this problem (we consider it a bug in OS X, not SQLite)
  23473. ** we always increase the file size to 1 by writing a single byte
  23474. ** prior to accessing the inode number. The one byte written is
  23475. ** an ASCII 'S' character which also happens to be the first byte
  23476. ** in the header of every SQLite database. In this way, if there
  23477. ** is a race condition such that another thread has already populated
  23478. ** the first page of the database, no damage is done.
  23479. */
  23480. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  23481. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  23482. if( rc!=1 ){
  23483. pFile->lastErrno = errno;
  23484. return SQLITE_IOERR;
  23485. }
  23486. rc = osFstat(fd, &statbuf);
  23487. if( rc!=0 ){
  23488. pFile->lastErrno = errno;
  23489. return SQLITE_IOERR;
  23490. }
  23491. }
  23492. #endif
  23493. memset(&fileId, 0, sizeof(fileId));
  23494. fileId.dev = statbuf.st_dev;
  23495. #if OS_VXWORKS
  23496. fileId.pId = pFile->pId;
  23497. #else
  23498. fileId.ino = statbuf.st_ino;
  23499. #endif
  23500. pInode = inodeList;
  23501. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  23502. pInode = pInode->pNext;
  23503. }
  23504. if( pInode==0 ){
  23505. pInode = sqlite3_malloc( sizeof(*pInode) );
  23506. if( pInode==0 ){
  23507. return SQLITE_NOMEM;
  23508. }
  23509. memset(pInode, 0, sizeof(*pInode));
  23510. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  23511. pInode->nRef = 1;
  23512. pInode->pNext = inodeList;
  23513. pInode->pPrev = 0;
  23514. if( inodeList ) inodeList->pPrev = pInode;
  23515. inodeList = pInode;
  23516. }else{
  23517. pInode->nRef++;
  23518. }
  23519. *ppInode = pInode;
  23520. return SQLITE_OK;
  23521. }
  23522. /*
  23523. ** Check a unixFile that is a database. Verify the following:
  23524. **
  23525. ** (1) There is exactly one hard link on the file
  23526. ** (2) The file is not a symbolic link
  23527. ** (3) The file has not been renamed or unlinked
  23528. **
  23529. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  23530. */
  23531. static void verifyDbFile(unixFile *pFile){
  23532. struct stat buf;
  23533. int rc;
  23534. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  23535. /* One or more of the following warnings have already been issued. Do not
  23536. ** repeat them so as not to clutter the error log */
  23537. return;
  23538. }
  23539. rc = osFstat(pFile->h, &buf);
  23540. if( rc!=0 ){
  23541. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  23542. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23543. return;
  23544. }
  23545. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  23546. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  23547. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23548. return;
  23549. }
  23550. if( buf.st_nlink>1 ){
  23551. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  23552. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23553. return;
  23554. }
  23555. if( pFile->pInode!=0
  23556. && ((rc = osStat(pFile->zPath, &buf))!=0
  23557. || buf.st_ino!=pFile->pInode->fileId.ino)
  23558. ){
  23559. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  23560. pFile->ctrlFlags |= UNIXFILE_WARNED;
  23561. return;
  23562. }
  23563. }
  23564. /*
  23565. ** This routine checks if there is a RESERVED lock held on the specified
  23566. ** file by this or any other process. If such a lock is held, set *pResOut
  23567. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  23568. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  23569. */
  23570. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  23571. int rc = SQLITE_OK;
  23572. int reserved = 0;
  23573. unixFile *pFile = (unixFile*)id;
  23574. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  23575. assert( pFile );
  23576. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  23577. /* Check if a thread in this process holds such a lock */
  23578. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  23579. reserved = 1;
  23580. }
  23581. /* Otherwise see if some other process holds it.
  23582. */
  23583. #ifndef __DJGPP__
  23584. if( !reserved && !pFile->pInode->bProcessLock ){
  23585. struct flock lock;
  23586. lock.l_whence = SEEK_SET;
  23587. lock.l_start = RESERVED_BYTE;
  23588. lock.l_len = 1;
  23589. lock.l_type = F_WRLCK;
  23590. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  23591. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  23592. pFile->lastErrno = errno;
  23593. } else if( lock.l_type!=F_UNLCK ){
  23594. reserved = 1;
  23595. }
  23596. }
  23597. #endif
  23598. unixLeaveMutex();
  23599. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  23600. *pResOut = reserved;
  23601. return rc;
  23602. }
  23603. /*
  23604. ** Attempt to set a system-lock on the file pFile. The lock is
  23605. ** described by pLock.
  23606. **
  23607. ** If the pFile was opened read/write from unix-excl, then the only lock
  23608. ** ever obtained is an exclusive lock, and it is obtained exactly once
  23609. ** the first time any lock is attempted. All subsequent system locking
  23610. ** operations become no-ops. Locking operations still happen internally,
  23611. ** in order to coordinate access between separate database connections
  23612. ** within this process, but all of that is handled in memory and the
  23613. ** operating system does not participate.
  23614. **
  23615. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  23616. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  23617. ** and is read-only.
  23618. **
  23619. ** Zero is returned if the call completes successfully, or -1 if a call
  23620. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  23621. */
  23622. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  23623. int rc;
  23624. unixInodeInfo *pInode = pFile->pInode;
  23625. assert( unixMutexHeld() );
  23626. assert( pInode!=0 );
  23627. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  23628. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  23629. ){
  23630. if( pInode->bProcessLock==0 ){
  23631. struct flock lock;
  23632. assert( pInode->nLock==0 );
  23633. lock.l_whence = SEEK_SET;
  23634. lock.l_start = SHARED_FIRST;
  23635. lock.l_len = SHARED_SIZE;
  23636. lock.l_type = F_WRLCK;
  23637. rc = osFcntl(pFile->h, F_SETLK, &lock);
  23638. if( rc<0 ) return rc;
  23639. pInode->bProcessLock = 1;
  23640. pInode->nLock++;
  23641. }else{
  23642. rc = 0;
  23643. }
  23644. }else{
  23645. rc = osFcntl(pFile->h, F_SETLK, pLock);
  23646. }
  23647. return rc;
  23648. }
  23649. /*
  23650. ** Lock the file with the lock specified by parameter eFileLock - one
  23651. ** of the following:
  23652. **
  23653. ** (1) SHARED_LOCK
  23654. ** (2) RESERVED_LOCK
  23655. ** (3) PENDING_LOCK
  23656. ** (4) EXCLUSIVE_LOCK
  23657. **
  23658. ** Sometimes when requesting one lock state, additional lock states
  23659. ** are inserted in between. The locking might fail on one of the later
  23660. ** transitions leaving the lock state different from what it started but
  23661. ** still short of its goal. The following chart shows the allowed
  23662. ** transitions and the inserted intermediate states:
  23663. **
  23664. ** UNLOCKED -> SHARED
  23665. ** SHARED -> RESERVED
  23666. ** SHARED -> (PENDING) -> EXCLUSIVE
  23667. ** RESERVED -> (PENDING) -> EXCLUSIVE
  23668. ** PENDING -> EXCLUSIVE
  23669. **
  23670. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  23671. ** routine to lower a locking level.
  23672. */
  23673. static int unixLock(sqlite3_file *id, int eFileLock){
  23674. /* The following describes the implementation of the various locks and
  23675. ** lock transitions in terms of the POSIX advisory shared and exclusive
  23676. ** lock primitives (called read-locks and write-locks below, to avoid
  23677. ** confusion with SQLite lock names). The algorithms are complicated
  23678. ** slightly in order to be compatible with windows systems simultaneously
  23679. ** accessing the same database file, in case that is ever required.
  23680. **
  23681. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  23682. ** byte', each single bytes at well known offsets, and the 'shared byte
  23683. ** range', a range of 510 bytes at a well known offset.
  23684. **
  23685. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  23686. ** byte'. If this is successful, a random byte from the 'shared byte
  23687. ** range' is read-locked and the lock on the 'pending byte' released.
  23688. **
  23689. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  23690. ** A RESERVED lock is implemented by grabbing a write-lock on the
  23691. ** 'reserved byte'.
  23692. **
  23693. ** A process may only obtain a PENDING lock after it has obtained a
  23694. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  23695. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  23696. ** obtained, but existing SHARED locks are allowed to persist. A process
  23697. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  23698. ** This property is used by the algorithm for rolling back a journal file
  23699. ** after a crash.
  23700. **
  23701. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  23702. ** implemented by obtaining a write-lock on the entire 'shared byte
  23703. ** range'. Since all other locks require a read-lock on one of the bytes
  23704. ** within this range, this ensures that no other locks are held on the
  23705. ** database.
  23706. **
  23707. ** The reason a single byte cannot be used instead of the 'shared byte
  23708. ** range' is that some versions of windows do not support read-locks. By
  23709. ** locking a random byte from a range, concurrent SHARED locks may exist
  23710. ** even if the locking primitive used is always a write-lock.
  23711. */
  23712. int rc = SQLITE_OK;
  23713. unixFile *pFile = (unixFile*)id;
  23714. unixInodeInfo *pInode;
  23715. struct flock lock;
  23716. int tErrno = 0;
  23717. assert( pFile );
  23718. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  23719. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  23720. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  23721. /* If there is already a lock of this type or more restrictive on the
  23722. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  23723. ** unixEnterMutex() hasn't been called yet.
  23724. */
  23725. if( pFile->eFileLock>=eFileLock ){
  23726. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  23727. azFileLock(eFileLock)));
  23728. return SQLITE_OK;
  23729. }
  23730. /* Make sure the locking sequence is correct.
  23731. ** (1) We never move from unlocked to anything higher than shared lock.
  23732. ** (2) SQLite never explicitly requests a pendig lock.
  23733. ** (3) A shared lock is always held when a reserve lock is requested.
  23734. */
  23735. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  23736. assert( eFileLock!=PENDING_LOCK );
  23737. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  23738. /* This mutex is needed because pFile->pInode is shared across threads
  23739. */
  23740. unixEnterMutex();
  23741. pInode = pFile->pInode;
  23742. /* If some thread using this PID has a lock via a different unixFile*
  23743. ** handle that precludes the requested lock, return BUSY.
  23744. */
  23745. if( (pFile->eFileLock!=pInode->eFileLock &&
  23746. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  23747. ){
  23748. rc = SQLITE_BUSY;
  23749. goto end_lock;
  23750. }
  23751. /* If a SHARED lock is requested, and some thread using this PID already
  23752. ** has a SHARED or RESERVED lock, then increment reference counts and
  23753. ** return SQLITE_OK.
  23754. */
  23755. if( eFileLock==SHARED_LOCK &&
  23756. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  23757. assert( eFileLock==SHARED_LOCK );
  23758. assert( pFile->eFileLock==0 );
  23759. assert( pInode->nShared>0 );
  23760. pFile->eFileLock = SHARED_LOCK;
  23761. pInode->nShared++;
  23762. pInode->nLock++;
  23763. goto end_lock;
  23764. }
  23765. /* A PENDING lock is needed before acquiring a SHARED lock and before
  23766. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  23767. ** be released.
  23768. */
  23769. lock.l_len = 1L;
  23770. lock.l_whence = SEEK_SET;
  23771. if( eFileLock==SHARED_LOCK
  23772. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  23773. ){
  23774. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  23775. lock.l_start = PENDING_BYTE;
  23776. if( unixFileLock(pFile, &lock) ){
  23777. tErrno = errno;
  23778. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23779. if( rc!=SQLITE_BUSY ){
  23780. pFile->lastErrno = tErrno;
  23781. }
  23782. goto end_lock;
  23783. }
  23784. }
  23785. /* If control gets to this point, then actually go ahead and make
  23786. ** operating system calls for the specified lock.
  23787. */
  23788. if( eFileLock==SHARED_LOCK ){
  23789. assert( pInode->nShared==0 );
  23790. assert( pInode->eFileLock==0 );
  23791. assert( rc==SQLITE_OK );
  23792. /* Now get the read-lock */
  23793. lock.l_start = SHARED_FIRST;
  23794. lock.l_len = SHARED_SIZE;
  23795. if( unixFileLock(pFile, &lock) ){
  23796. tErrno = errno;
  23797. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23798. }
  23799. /* Drop the temporary PENDING lock */
  23800. lock.l_start = PENDING_BYTE;
  23801. lock.l_len = 1L;
  23802. lock.l_type = F_UNLCK;
  23803. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  23804. /* This could happen with a network mount */
  23805. tErrno = errno;
  23806. rc = SQLITE_IOERR_UNLOCK;
  23807. }
  23808. if( rc ){
  23809. if( rc!=SQLITE_BUSY ){
  23810. pFile->lastErrno = tErrno;
  23811. }
  23812. goto end_lock;
  23813. }else{
  23814. pFile->eFileLock = SHARED_LOCK;
  23815. pInode->nLock++;
  23816. pInode->nShared = 1;
  23817. }
  23818. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  23819. /* We are trying for an exclusive lock but another thread in this
  23820. ** same process is still holding a shared lock. */
  23821. rc = SQLITE_BUSY;
  23822. }else{
  23823. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  23824. ** assumed that there is a SHARED or greater lock on the file
  23825. ** already.
  23826. */
  23827. assert( 0!=pFile->eFileLock );
  23828. lock.l_type = F_WRLCK;
  23829. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  23830. if( eFileLock==RESERVED_LOCK ){
  23831. lock.l_start = RESERVED_BYTE;
  23832. lock.l_len = 1L;
  23833. }else{
  23834. lock.l_start = SHARED_FIRST;
  23835. lock.l_len = SHARED_SIZE;
  23836. }
  23837. if( unixFileLock(pFile, &lock) ){
  23838. tErrno = errno;
  23839. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  23840. if( rc!=SQLITE_BUSY ){
  23841. pFile->lastErrno = tErrno;
  23842. }
  23843. }
  23844. }
  23845. #ifdef SQLITE_DEBUG
  23846. /* Set up the transaction-counter change checking flags when
  23847. ** transitioning from a SHARED to a RESERVED lock. The change
  23848. ** from SHARED to RESERVED marks the beginning of a normal
  23849. ** write operation (not a hot journal rollback).
  23850. */
  23851. if( rc==SQLITE_OK
  23852. && pFile->eFileLock<=SHARED_LOCK
  23853. && eFileLock==RESERVED_LOCK
  23854. ){
  23855. pFile->transCntrChng = 0;
  23856. pFile->dbUpdate = 0;
  23857. pFile->inNormalWrite = 1;
  23858. }
  23859. #endif
  23860. if( rc==SQLITE_OK ){
  23861. pFile->eFileLock = eFileLock;
  23862. pInode->eFileLock = eFileLock;
  23863. }else if( eFileLock==EXCLUSIVE_LOCK ){
  23864. pFile->eFileLock = PENDING_LOCK;
  23865. pInode->eFileLock = PENDING_LOCK;
  23866. }
  23867. end_lock:
  23868. unixLeaveMutex();
  23869. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  23870. rc==SQLITE_OK ? "ok" : "failed"));
  23871. return rc;
  23872. }
  23873. /*
  23874. ** Add the file descriptor used by file handle pFile to the corresponding
  23875. ** pUnused list.
  23876. */
  23877. static void setPendingFd(unixFile *pFile){
  23878. unixInodeInfo *pInode = pFile->pInode;
  23879. UnixUnusedFd *p = pFile->pUnused;
  23880. p->pNext = pInode->pUnused;
  23881. pInode->pUnused = p;
  23882. pFile->h = -1;
  23883. pFile->pUnused = 0;
  23884. }
  23885. /*
  23886. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  23887. ** must be either NO_LOCK or SHARED_LOCK.
  23888. **
  23889. ** If the locking level of the file descriptor is already at or below
  23890. ** the requested locking level, this routine is a no-op.
  23891. **
  23892. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  23893. ** the byte range is divided into 2 parts and the first part is unlocked then
  23894. ** set to a read lock, then the other part is simply unlocked. This works
  23895. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  23896. ** remove the write lock on a region when a read lock is set.
  23897. */
  23898. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  23899. unixFile *pFile = (unixFile*)id;
  23900. unixInodeInfo *pInode;
  23901. struct flock lock;
  23902. int rc = SQLITE_OK;
  23903. assert( pFile );
  23904. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  23905. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  23906. getpid()));
  23907. assert( eFileLock<=SHARED_LOCK );
  23908. if( pFile->eFileLock<=eFileLock ){
  23909. return SQLITE_OK;
  23910. }
  23911. unixEnterMutex();
  23912. pInode = pFile->pInode;
  23913. assert( pInode->nShared!=0 );
  23914. if( pFile->eFileLock>SHARED_LOCK ){
  23915. assert( pInode->eFileLock==pFile->eFileLock );
  23916. #ifdef SQLITE_DEBUG
  23917. /* When reducing a lock such that other processes can start
  23918. ** reading the database file again, make sure that the
  23919. ** transaction counter was updated if any part of the database
  23920. ** file changed. If the transaction counter is not updated,
  23921. ** other connections to the same file might not realize that
  23922. ** the file has changed and hence might not know to flush their
  23923. ** cache. The use of a stale cache can lead to database corruption.
  23924. */
  23925. pFile->inNormalWrite = 0;
  23926. #endif
  23927. /* downgrading to a shared lock on NFS involves clearing the write lock
  23928. ** before establishing the readlock - to avoid a race condition we downgrade
  23929. ** the lock in 2 blocks, so that part of the range will be covered by a
  23930. ** write lock until the rest is covered by a read lock:
  23931. ** 1: [WWWWW]
  23932. ** 2: [....W]
  23933. ** 3: [RRRRW]
  23934. ** 4: [RRRR.]
  23935. */
  23936. if( eFileLock==SHARED_LOCK ){
  23937. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  23938. (void)handleNFSUnlock;
  23939. assert( handleNFSUnlock==0 );
  23940. #endif
  23941. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  23942. if( handleNFSUnlock ){
  23943. int tErrno; /* Error code from system call errors */
  23944. off_t divSize = SHARED_SIZE - 1;
  23945. lock.l_type = F_UNLCK;
  23946. lock.l_whence = SEEK_SET;
  23947. lock.l_start = SHARED_FIRST;
  23948. lock.l_len = divSize;
  23949. if( unixFileLock(pFile, &lock)==(-1) ){
  23950. tErrno = errno;
  23951. rc = SQLITE_IOERR_UNLOCK;
  23952. if( IS_LOCK_ERROR(rc) ){
  23953. pFile->lastErrno = tErrno;
  23954. }
  23955. goto end_unlock;
  23956. }
  23957. lock.l_type = F_RDLCK;
  23958. lock.l_whence = SEEK_SET;
  23959. lock.l_start = SHARED_FIRST;
  23960. lock.l_len = divSize;
  23961. if( unixFileLock(pFile, &lock)==(-1) ){
  23962. tErrno = errno;
  23963. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  23964. if( IS_LOCK_ERROR(rc) ){
  23965. pFile->lastErrno = tErrno;
  23966. }
  23967. goto end_unlock;
  23968. }
  23969. lock.l_type = F_UNLCK;
  23970. lock.l_whence = SEEK_SET;
  23971. lock.l_start = SHARED_FIRST+divSize;
  23972. lock.l_len = SHARED_SIZE-divSize;
  23973. if( unixFileLock(pFile, &lock)==(-1) ){
  23974. tErrno = errno;
  23975. rc = SQLITE_IOERR_UNLOCK;
  23976. if( IS_LOCK_ERROR(rc) ){
  23977. pFile->lastErrno = tErrno;
  23978. }
  23979. goto end_unlock;
  23980. }
  23981. }else
  23982. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  23983. {
  23984. lock.l_type = F_RDLCK;
  23985. lock.l_whence = SEEK_SET;
  23986. lock.l_start = SHARED_FIRST;
  23987. lock.l_len = SHARED_SIZE;
  23988. if( unixFileLock(pFile, &lock) ){
  23989. /* In theory, the call to unixFileLock() cannot fail because another
  23990. ** process is holding an incompatible lock. If it does, this
  23991. ** indicates that the other process is not following the locking
  23992. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  23993. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  23994. ** an assert to fail). */
  23995. rc = SQLITE_IOERR_RDLOCK;
  23996. pFile->lastErrno = errno;
  23997. goto end_unlock;
  23998. }
  23999. }
  24000. }
  24001. lock.l_type = F_UNLCK;
  24002. lock.l_whence = SEEK_SET;
  24003. lock.l_start = PENDING_BYTE;
  24004. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  24005. if( unixFileLock(pFile, &lock)==0 ){
  24006. pInode->eFileLock = SHARED_LOCK;
  24007. }else{
  24008. rc = SQLITE_IOERR_UNLOCK;
  24009. pFile->lastErrno = errno;
  24010. goto end_unlock;
  24011. }
  24012. }
  24013. if( eFileLock==NO_LOCK ){
  24014. /* Decrement the shared lock counter. Release the lock using an
  24015. ** OS call only when all threads in this same process have released
  24016. ** the lock.
  24017. */
  24018. pInode->nShared--;
  24019. if( pInode->nShared==0 ){
  24020. lock.l_type = F_UNLCK;
  24021. lock.l_whence = SEEK_SET;
  24022. lock.l_start = lock.l_len = 0L;
  24023. if( unixFileLock(pFile, &lock)==0 ){
  24024. pInode->eFileLock = NO_LOCK;
  24025. }else{
  24026. rc = SQLITE_IOERR_UNLOCK;
  24027. pFile->lastErrno = errno;
  24028. pInode->eFileLock = NO_LOCK;
  24029. pFile->eFileLock = NO_LOCK;
  24030. }
  24031. }
  24032. /* Decrement the count of locks against this same file. When the
  24033. ** count reaches zero, close any other file descriptors whose close
  24034. ** was deferred because of outstanding locks.
  24035. */
  24036. pInode->nLock--;
  24037. assert( pInode->nLock>=0 );
  24038. if( pInode->nLock==0 ){
  24039. closePendingFds(pFile);
  24040. }
  24041. }
  24042. end_unlock:
  24043. unixLeaveMutex();
  24044. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  24045. return rc;
  24046. }
  24047. /*
  24048. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24049. ** must be either NO_LOCK or SHARED_LOCK.
  24050. **
  24051. ** If the locking level of the file descriptor is already at or below
  24052. ** the requested locking level, this routine is a no-op.
  24053. */
  24054. static int unixUnlock(sqlite3_file *id, int eFileLock){
  24055. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  24056. return posixUnlock(id, eFileLock, 0);
  24057. }
  24058. #if SQLITE_MAX_MMAP_SIZE>0
  24059. static int unixMapfile(unixFile *pFd, i64 nByte);
  24060. static void unixUnmapfile(unixFile *pFd);
  24061. #endif
  24062. /*
  24063. ** This function performs the parts of the "close file" operation
  24064. ** common to all locking schemes. It closes the directory and file
  24065. ** handles, if they are valid, and sets all fields of the unixFile
  24066. ** structure to 0.
  24067. **
  24068. ** It is *not* necessary to hold the mutex when this routine is called,
  24069. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  24070. ** vxworksReleaseFileId() routine.
  24071. */
  24072. static int closeUnixFile(sqlite3_file *id){
  24073. unixFile *pFile = (unixFile*)id;
  24074. #if SQLITE_MAX_MMAP_SIZE>0
  24075. unixUnmapfile(pFile);
  24076. #endif
  24077. if( pFile->h>=0 ){
  24078. robust_close(pFile, pFile->h, __LINE__);
  24079. pFile->h = -1;
  24080. }
  24081. #if OS_VXWORKS
  24082. if( pFile->pId ){
  24083. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  24084. osUnlink(pFile->pId->zCanonicalName);
  24085. }
  24086. vxworksReleaseFileId(pFile->pId);
  24087. pFile->pId = 0;
  24088. }
  24089. #endif
  24090. OSTRACE(("CLOSE %-3d\n", pFile->h));
  24091. OpenCounter(-1);
  24092. sqlite3_free(pFile->pUnused);
  24093. memset(pFile, 0, sizeof(unixFile));
  24094. return SQLITE_OK;
  24095. }
  24096. /*
  24097. ** Close a file.
  24098. */
  24099. static int unixClose(sqlite3_file *id){
  24100. int rc = SQLITE_OK;
  24101. unixFile *pFile = (unixFile *)id;
  24102. verifyDbFile(pFile);
  24103. unixUnlock(id, NO_LOCK);
  24104. unixEnterMutex();
  24105. /* unixFile.pInode is always valid here. Otherwise, a different close
  24106. ** routine (e.g. nolockClose()) would be called instead.
  24107. */
  24108. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  24109. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  24110. /* If there are outstanding locks, do not actually close the file just
  24111. ** yet because that would clear those locks. Instead, add the file
  24112. ** descriptor to pInode->pUnused list. It will be automatically closed
  24113. ** when the last lock is cleared.
  24114. */
  24115. setPendingFd(pFile);
  24116. }
  24117. releaseInodeInfo(pFile);
  24118. rc = closeUnixFile(id);
  24119. unixLeaveMutex();
  24120. return rc;
  24121. }
  24122. /************** End of the posix advisory lock implementation *****************
  24123. ******************************************************************************/
  24124. /******************************************************************************
  24125. ****************************** No-op Locking **********************************
  24126. **
  24127. ** Of the various locking implementations available, this is by far the
  24128. ** simplest: locking is ignored. No attempt is made to lock the database
  24129. ** file for reading or writing.
  24130. **
  24131. ** This locking mode is appropriate for use on read-only databases
  24132. ** (ex: databases that are burned into CD-ROM, for example.) It can
  24133. ** also be used if the application employs some external mechanism to
  24134. ** prevent simultaneous access of the same database by two or more
  24135. ** database connections. But there is a serious risk of database
  24136. ** corruption if this locking mode is used in situations where multiple
  24137. ** database connections are accessing the same database file at the same
  24138. ** time and one or more of those connections are writing.
  24139. */
  24140. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  24141. UNUSED_PARAMETER(NotUsed);
  24142. *pResOut = 0;
  24143. return SQLITE_OK;
  24144. }
  24145. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  24146. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24147. return SQLITE_OK;
  24148. }
  24149. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  24150. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  24151. return SQLITE_OK;
  24152. }
  24153. /*
  24154. ** Close the file.
  24155. */
  24156. static int nolockClose(sqlite3_file *id) {
  24157. return closeUnixFile(id);
  24158. }
  24159. /******************* End of the no-op lock implementation *********************
  24160. ******************************************************************************/
  24161. /******************************************************************************
  24162. ************************* Begin dot-file Locking ******************************
  24163. **
  24164. ** The dotfile locking implementation uses the existence of separate lock
  24165. ** files (really a directory) to control access to the database. This works
  24166. ** on just about every filesystem imaginable. But there are serious downsides:
  24167. **
  24168. ** (1) There is zero concurrency. A single reader blocks all other
  24169. ** connections from reading or writing the database.
  24170. **
  24171. ** (2) An application crash or power loss can leave stale lock files
  24172. ** sitting around that need to be cleared manually.
  24173. **
  24174. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  24175. ** other locking strategy is available.
  24176. **
  24177. ** Dotfile locking works by creating a subdirectory in the same directory as
  24178. ** the database and with the same name but with a ".lock" extension added.
  24179. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  24180. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  24181. */
  24182. /*
  24183. ** The file suffix added to the data base filename in order to create the
  24184. ** lock directory.
  24185. */
  24186. #define DOTLOCK_SUFFIX ".lock"
  24187. /*
  24188. ** This routine checks if there is a RESERVED lock held on the specified
  24189. ** file by this or any other process. If such a lock is held, set *pResOut
  24190. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24191. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24192. **
  24193. ** In dotfile locking, either a lock exists or it does not. So in this
  24194. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  24195. ** is held on the file and false if the file is unlocked.
  24196. */
  24197. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24198. int rc = SQLITE_OK;
  24199. int reserved = 0;
  24200. unixFile *pFile = (unixFile*)id;
  24201. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24202. assert( pFile );
  24203. /* Check if a thread in this process holds such a lock */
  24204. if( pFile->eFileLock>SHARED_LOCK ){
  24205. /* Either this connection or some other connection in the same process
  24206. ** holds a lock on the file. No need to check further. */
  24207. reserved = 1;
  24208. }else{
  24209. /* The lock is held if and only if the lockfile exists */
  24210. const char *zLockFile = (const char*)pFile->lockingContext;
  24211. reserved = osAccess(zLockFile, 0)==0;
  24212. }
  24213. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  24214. *pResOut = reserved;
  24215. return rc;
  24216. }
  24217. /*
  24218. ** Lock the file with the lock specified by parameter eFileLock - one
  24219. ** of the following:
  24220. **
  24221. ** (1) SHARED_LOCK
  24222. ** (2) RESERVED_LOCK
  24223. ** (3) PENDING_LOCK
  24224. ** (4) EXCLUSIVE_LOCK
  24225. **
  24226. ** Sometimes when requesting one lock state, additional lock states
  24227. ** are inserted in between. The locking might fail on one of the later
  24228. ** transitions leaving the lock state different from what it started but
  24229. ** still short of its goal. The following chart shows the allowed
  24230. ** transitions and the inserted intermediate states:
  24231. **
  24232. ** UNLOCKED -> SHARED
  24233. ** SHARED -> RESERVED
  24234. ** SHARED -> (PENDING) -> EXCLUSIVE
  24235. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24236. ** PENDING -> EXCLUSIVE
  24237. **
  24238. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24239. ** routine to lower a locking level.
  24240. **
  24241. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  24242. ** But we track the other locking levels internally.
  24243. */
  24244. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  24245. unixFile *pFile = (unixFile*)id;
  24246. char *zLockFile = (char *)pFile->lockingContext;
  24247. int rc = SQLITE_OK;
  24248. /* If we have any lock, then the lock file already exists. All we have
  24249. ** to do is adjust our internal record of the lock level.
  24250. */
  24251. if( pFile->eFileLock > NO_LOCK ){
  24252. pFile->eFileLock = eFileLock;
  24253. /* Always update the timestamp on the old file */
  24254. #ifdef HAVE_UTIME
  24255. utime(zLockFile, NULL);
  24256. #else
  24257. utimes(zLockFile, NULL);
  24258. #endif
  24259. return SQLITE_OK;
  24260. }
  24261. /* grab an exclusive lock */
  24262. rc = osMkdir(zLockFile, 0777);
  24263. if( rc<0 ){
  24264. /* failed to open/create the lock directory */
  24265. int tErrno = errno;
  24266. if( EEXIST == tErrno ){
  24267. rc = SQLITE_BUSY;
  24268. } else {
  24269. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24270. if( IS_LOCK_ERROR(rc) ){
  24271. pFile->lastErrno = tErrno;
  24272. }
  24273. }
  24274. return rc;
  24275. }
  24276. /* got it, set the type and return ok */
  24277. pFile->eFileLock = eFileLock;
  24278. return rc;
  24279. }
  24280. /*
  24281. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24282. ** must be either NO_LOCK or SHARED_LOCK.
  24283. **
  24284. ** If the locking level of the file descriptor is already at or below
  24285. ** the requested locking level, this routine is a no-op.
  24286. **
  24287. ** When the locking level reaches NO_LOCK, delete the lock file.
  24288. */
  24289. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  24290. unixFile *pFile = (unixFile*)id;
  24291. char *zLockFile = (char *)pFile->lockingContext;
  24292. int rc;
  24293. assert( pFile );
  24294. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  24295. pFile->eFileLock, getpid()));
  24296. assert( eFileLock<=SHARED_LOCK );
  24297. /* no-op if possible */
  24298. if( pFile->eFileLock==eFileLock ){
  24299. return SQLITE_OK;
  24300. }
  24301. /* To downgrade to shared, simply update our internal notion of the
  24302. ** lock state. No need to mess with the file on disk.
  24303. */
  24304. if( eFileLock==SHARED_LOCK ){
  24305. pFile->eFileLock = SHARED_LOCK;
  24306. return SQLITE_OK;
  24307. }
  24308. /* To fully unlock the database, delete the lock file */
  24309. assert( eFileLock==NO_LOCK );
  24310. rc = osRmdir(zLockFile);
  24311. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  24312. if( rc<0 ){
  24313. int tErrno = errno;
  24314. rc = 0;
  24315. if( ENOENT != tErrno ){
  24316. rc = SQLITE_IOERR_UNLOCK;
  24317. }
  24318. if( IS_LOCK_ERROR(rc) ){
  24319. pFile->lastErrno = tErrno;
  24320. }
  24321. return rc;
  24322. }
  24323. pFile->eFileLock = NO_LOCK;
  24324. return SQLITE_OK;
  24325. }
  24326. /*
  24327. ** Close a file. Make sure the lock has been released before closing.
  24328. */
  24329. static int dotlockClose(sqlite3_file *id) {
  24330. int rc = SQLITE_OK;
  24331. if( id ){
  24332. unixFile *pFile = (unixFile*)id;
  24333. dotlockUnlock(id, NO_LOCK);
  24334. sqlite3_free(pFile->lockingContext);
  24335. rc = closeUnixFile(id);
  24336. }
  24337. return rc;
  24338. }
  24339. /****************** End of the dot-file lock implementation *******************
  24340. ******************************************************************************/
  24341. /******************************************************************************
  24342. ************************** Begin flock Locking ********************************
  24343. **
  24344. ** Use the flock() system call to do file locking.
  24345. **
  24346. ** flock() locking is like dot-file locking in that the various
  24347. ** fine-grain locking levels supported by SQLite are collapsed into
  24348. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  24349. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  24350. ** still works when you do this, but concurrency is reduced since
  24351. ** only a single process can be reading the database at a time.
  24352. **
  24353. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  24354. ** compiling for VXWORKS.
  24355. */
  24356. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  24357. /*
  24358. ** Retry flock() calls that fail with EINTR
  24359. */
  24360. #ifdef EINTR
  24361. static int robust_flock(int fd, int op){
  24362. int rc;
  24363. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  24364. return rc;
  24365. }
  24366. #else
  24367. # define robust_flock(a,b) flock(a,b)
  24368. #endif
  24369. /*
  24370. ** This routine checks if there is a RESERVED lock held on the specified
  24371. ** file by this or any other process. If such a lock is held, set *pResOut
  24372. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24373. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24374. */
  24375. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  24376. int rc = SQLITE_OK;
  24377. int reserved = 0;
  24378. unixFile *pFile = (unixFile*)id;
  24379. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24380. assert( pFile );
  24381. /* Check if a thread in this process holds such a lock */
  24382. if( pFile->eFileLock>SHARED_LOCK ){
  24383. reserved = 1;
  24384. }
  24385. /* Otherwise see if some other process holds it. */
  24386. if( !reserved ){
  24387. /* attempt to get the lock */
  24388. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  24389. if( !lrc ){
  24390. /* got the lock, unlock it */
  24391. lrc = robust_flock(pFile->h, LOCK_UN);
  24392. if ( lrc ) {
  24393. int tErrno = errno;
  24394. /* unlock failed with an error */
  24395. lrc = SQLITE_IOERR_UNLOCK;
  24396. if( IS_LOCK_ERROR(lrc) ){
  24397. pFile->lastErrno = tErrno;
  24398. rc = lrc;
  24399. }
  24400. }
  24401. } else {
  24402. int tErrno = errno;
  24403. reserved = 1;
  24404. /* someone else might have it reserved */
  24405. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24406. if( IS_LOCK_ERROR(lrc) ){
  24407. pFile->lastErrno = tErrno;
  24408. rc = lrc;
  24409. }
  24410. }
  24411. }
  24412. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  24413. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24414. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24415. rc = SQLITE_OK;
  24416. reserved=1;
  24417. }
  24418. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24419. *pResOut = reserved;
  24420. return rc;
  24421. }
  24422. /*
  24423. ** Lock the file with the lock specified by parameter eFileLock - one
  24424. ** of the following:
  24425. **
  24426. ** (1) SHARED_LOCK
  24427. ** (2) RESERVED_LOCK
  24428. ** (3) PENDING_LOCK
  24429. ** (4) EXCLUSIVE_LOCK
  24430. **
  24431. ** Sometimes when requesting one lock state, additional lock states
  24432. ** are inserted in between. The locking might fail on one of the later
  24433. ** transitions leaving the lock state different from what it started but
  24434. ** still short of its goal. The following chart shows the allowed
  24435. ** transitions and the inserted intermediate states:
  24436. **
  24437. ** UNLOCKED -> SHARED
  24438. ** SHARED -> RESERVED
  24439. ** SHARED -> (PENDING) -> EXCLUSIVE
  24440. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24441. ** PENDING -> EXCLUSIVE
  24442. **
  24443. ** flock() only really support EXCLUSIVE locks. We track intermediate
  24444. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24445. ** above are really EXCLUSIVE locks and exclude all other processes from
  24446. ** access the file.
  24447. **
  24448. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24449. ** routine to lower a locking level.
  24450. */
  24451. static int flockLock(sqlite3_file *id, int eFileLock) {
  24452. int rc = SQLITE_OK;
  24453. unixFile *pFile = (unixFile*)id;
  24454. assert( pFile );
  24455. /* if we already have a lock, it is exclusive.
  24456. ** Just adjust level and punt on outta here. */
  24457. if (pFile->eFileLock > NO_LOCK) {
  24458. pFile->eFileLock = eFileLock;
  24459. return SQLITE_OK;
  24460. }
  24461. /* grab an exclusive lock */
  24462. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  24463. int tErrno = errno;
  24464. /* didn't get, must be busy */
  24465. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24466. if( IS_LOCK_ERROR(rc) ){
  24467. pFile->lastErrno = tErrno;
  24468. }
  24469. } else {
  24470. /* got it, set the type and return ok */
  24471. pFile->eFileLock = eFileLock;
  24472. }
  24473. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  24474. rc==SQLITE_OK ? "ok" : "failed"));
  24475. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24476. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  24477. rc = SQLITE_BUSY;
  24478. }
  24479. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24480. return rc;
  24481. }
  24482. /*
  24483. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24484. ** must be either NO_LOCK or SHARED_LOCK.
  24485. **
  24486. ** If the locking level of the file descriptor is already at or below
  24487. ** the requested locking level, this routine is a no-op.
  24488. */
  24489. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  24490. unixFile *pFile = (unixFile*)id;
  24491. assert( pFile );
  24492. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  24493. pFile->eFileLock, getpid()));
  24494. assert( eFileLock<=SHARED_LOCK );
  24495. /* no-op if possible */
  24496. if( pFile->eFileLock==eFileLock ){
  24497. return SQLITE_OK;
  24498. }
  24499. /* shared can just be set because we always have an exclusive */
  24500. if (eFileLock==SHARED_LOCK) {
  24501. pFile->eFileLock = eFileLock;
  24502. return SQLITE_OK;
  24503. }
  24504. /* no, really, unlock. */
  24505. if( robust_flock(pFile->h, LOCK_UN) ){
  24506. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  24507. return SQLITE_OK;
  24508. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  24509. return SQLITE_IOERR_UNLOCK;
  24510. }else{
  24511. pFile->eFileLock = NO_LOCK;
  24512. return SQLITE_OK;
  24513. }
  24514. }
  24515. /*
  24516. ** Close a file.
  24517. */
  24518. static int flockClose(sqlite3_file *id) {
  24519. int rc = SQLITE_OK;
  24520. if( id ){
  24521. flockUnlock(id, NO_LOCK);
  24522. rc = closeUnixFile(id);
  24523. }
  24524. return rc;
  24525. }
  24526. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  24527. /******************* End of the flock lock implementation *********************
  24528. ******************************************************************************/
  24529. /******************************************************************************
  24530. ************************ Begin Named Semaphore Locking ************************
  24531. **
  24532. ** Named semaphore locking is only supported on VxWorks.
  24533. **
  24534. ** Semaphore locking is like dot-lock and flock in that it really only
  24535. ** supports EXCLUSIVE locking. Only a single process can read or write
  24536. ** the database file at a time. This reduces potential concurrency, but
  24537. ** makes the lock implementation much easier.
  24538. */
  24539. #if OS_VXWORKS
  24540. /*
  24541. ** This routine checks if there is a RESERVED lock held on the specified
  24542. ** file by this or any other process. If such a lock is held, set *pResOut
  24543. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24544. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24545. */
  24546. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  24547. int rc = SQLITE_OK;
  24548. int reserved = 0;
  24549. unixFile *pFile = (unixFile*)id;
  24550. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24551. assert( pFile );
  24552. /* Check if a thread in this process holds such a lock */
  24553. if( pFile->eFileLock>SHARED_LOCK ){
  24554. reserved = 1;
  24555. }
  24556. /* Otherwise see if some other process holds it. */
  24557. if( !reserved ){
  24558. sem_t *pSem = pFile->pInode->pSem;
  24559. struct stat statBuf;
  24560. if( sem_trywait(pSem)==-1 ){
  24561. int tErrno = errno;
  24562. if( EAGAIN != tErrno ){
  24563. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  24564. pFile->lastErrno = tErrno;
  24565. } else {
  24566. /* someone else has the lock when we are in NO_LOCK */
  24567. reserved = (pFile->eFileLock < SHARED_LOCK);
  24568. }
  24569. }else{
  24570. /* we could have it if we want it */
  24571. sem_post(pSem);
  24572. }
  24573. }
  24574. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  24575. *pResOut = reserved;
  24576. return rc;
  24577. }
  24578. /*
  24579. ** Lock the file with the lock specified by parameter eFileLock - one
  24580. ** of the following:
  24581. **
  24582. ** (1) SHARED_LOCK
  24583. ** (2) RESERVED_LOCK
  24584. ** (3) PENDING_LOCK
  24585. ** (4) EXCLUSIVE_LOCK
  24586. **
  24587. ** Sometimes when requesting one lock state, additional lock states
  24588. ** are inserted in between. The locking might fail on one of the later
  24589. ** transitions leaving the lock state different from what it started but
  24590. ** still short of its goal. The following chart shows the allowed
  24591. ** transitions and the inserted intermediate states:
  24592. **
  24593. ** UNLOCKED -> SHARED
  24594. ** SHARED -> RESERVED
  24595. ** SHARED -> (PENDING) -> EXCLUSIVE
  24596. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24597. ** PENDING -> EXCLUSIVE
  24598. **
  24599. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  24600. ** lock states in the sqlite3_file structure, but all locks SHARED or
  24601. ** above are really EXCLUSIVE locks and exclude all other processes from
  24602. ** access the file.
  24603. **
  24604. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24605. ** routine to lower a locking level.
  24606. */
  24607. static int semLock(sqlite3_file *id, int eFileLock) {
  24608. unixFile *pFile = (unixFile*)id;
  24609. int fd;
  24610. sem_t *pSem = pFile->pInode->pSem;
  24611. int rc = SQLITE_OK;
  24612. /* if we already have a lock, it is exclusive.
  24613. ** Just adjust level and punt on outta here. */
  24614. if (pFile->eFileLock > NO_LOCK) {
  24615. pFile->eFileLock = eFileLock;
  24616. rc = SQLITE_OK;
  24617. goto sem_end_lock;
  24618. }
  24619. /* lock semaphore now but bail out when already locked. */
  24620. if( sem_trywait(pSem)==-1 ){
  24621. rc = SQLITE_BUSY;
  24622. goto sem_end_lock;
  24623. }
  24624. /* got it, set the type and return ok */
  24625. pFile->eFileLock = eFileLock;
  24626. sem_end_lock:
  24627. return rc;
  24628. }
  24629. /*
  24630. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24631. ** must be either NO_LOCK or SHARED_LOCK.
  24632. **
  24633. ** If the locking level of the file descriptor is already at or below
  24634. ** the requested locking level, this routine is a no-op.
  24635. */
  24636. static int semUnlock(sqlite3_file *id, int eFileLock) {
  24637. unixFile *pFile = (unixFile*)id;
  24638. sem_t *pSem = pFile->pInode->pSem;
  24639. assert( pFile );
  24640. assert( pSem );
  24641. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  24642. pFile->eFileLock, getpid()));
  24643. assert( eFileLock<=SHARED_LOCK );
  24644. /* no-op if possible */
  24645. if( pFile->eFileLock==eFileLock ){
  24646. return SQLITE_OK;
  24647. }
  24648. /* shared can just be set because we always have an exclusive */
  24649. if (eFileLock==SHARED_LOCK) {
  24650. pFile->eFileLock = eFileLock;
  24651. return SQLITE_OK;
  24652. }
  24653. /* no, really unlock. */
  24654. if ( sem_post(pSem)==-1 ) {
  24655. int rc, tErrno = errno;
  24656. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  24657. if( IS_LOCK_ERROR(rc) ){
  24658. pFile->lastErrno = tErrno;
  24659. }
  24660. return rc;
  24661. }
  24662. pFile->eFileLock = NO_LOCK;
  24663. return SQLITE_OK;
  24664. }
  24665. /*
  24666. ** Close a file.
  24667. */
  24668. static int semClose(sqlite3_file *id) {
  24669. if( id ){
  24670. unixFile *pFile = (unixFile*)id;
  24671. semUnlock(id, NO_LOCK);
  24672. assert( pFile );
  24673. unixEnterMutex();
  24674. releaseInodeInfo(pFile);
  24675. unixLeaveMutex();
  24676. closeUnixFile(id);
  24677. }
  24678. return SQLITE_OK;
  24679. }
  24680. #endif /* OS_VXWORKS */
  24681. /*
  24682. ** Named semaphore locking is only available on VxWorks.
  24683. **
  24684. *************** End of the named semaphore lock implementation ****************
  24685. ******************************************************************************/
  24686. /******************************************************************************
  24687. *************************** Begin AFP Locking *********************************
  24688. **
  24689. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  24690. ** on Apple Macintosh computers - both OS9 and OSX.
  24691. **
  24692. ** Third-party implementations of AFP are available. But this code here
  24693. ** only works on OSX.
  24694. */
  24695. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  24696. /*
  24697. ** The afpLockingContext structure contains all afp lock specific state
  24698. */
  24699. typedef struct afpLockingContext afpLockingContext;
  24700. struct afpLockingContext {
  24701. int reserved;
  24702. const char *dbPath; /* Name of the open file */
  24703. };
  24704. struct ByteRangeLockPB2
  24705. {
  24706. unsigned long long offset; /* offset to first byte to lock */
  24707. unsigned long long length; /* nbr of bytes to lock */
  24708. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  24709. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  24710. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  24711. int fd; /* file desc to assoc this lock with */
  24712. };
  24713. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  24714. /*
  24715. ** This is a utility for setting or clearing a bit-range lock on an
  24716. ** AFP filesystem.
  24717. **
  24718. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  24719. */
  24720. static int afpSetLock(
  24721. const char *path, /* Name of the file to be locked or unlocked */
  24722. unixFile *pFile, /* Open file descriptor on path */
  24723. unsigned long long offset, /* First byte to be locked */
  24724. unsigned long long length, /* Number of bytes to lock */
  24725. int setLockFlag /* True to set lock. False to clear lock */
  24726. ){
  24727. struct ByteRangeLockPB2 pb;
  24728. int err;
  24729. pb.unLockFlag = setLockFlag ? 0 : 1;
  24730. pb.startEndFlag = 0;
  24731. pb.offset = offset;
  24732. pb.length = length;
  24733. pb.fd = pFile->h;
  24734. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  24735. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  24736. offset, length));
  24737. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  24738. if ( err==-1 ) {
  24739. int rc;
  24740. int tErrno = errno;
  24741. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  24742. path, tErrno, strerror(tErrno)));
  24743. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  24744. rc = SQLITE_BUSY;
  24745. #else
  24746. rc = sqliteErrorFromPosixError(tErrno,
  24747. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  24748. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  24749. if( IS_LOCK_ERROR(rc) ){
  24750. pFile->lastErrno = tErrno;
  24751. }
  24752. return rc;
  24753. } else {
  24754. return SQLITE_OK;
  24755. }
  24756. }
  24757. /*
  24758. ** This routine checks if there is a RESERVED lock held on the specified
  24759. ** file by this or any other process. If such a lock is held, set *pResOut
  24760. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24761. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24762. */
  24763. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  24764. int rc = SQLITE_OK;
  24765. int reserved = 0;
  24766. unixFile *pFile = (unixFile*)id;
  24767. afpLockingContext *context;
  24768. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24769. assert( pFile );
  24770. context = (afpLockingContext *) pFile->lockingContext;
  24771. if( context->reserved ){
  24772. *pResOut = 1;
  24773. return SQLITE_OK;
  24774. }
  24775. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24776. /* Check if a thread in this process holds such a lock */
  24777. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24778. reserved = 1;
  24779. }
  24780. /* Otherwise see if some other process holds it.
  24781. */
  24782. if( !reserved ){
  24783. /* lock the RESERVED byte */
  24784. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24785. if( SQLITE_OK==lrc ){
  24786. /* if we succeeded in taking the reserved lock, unlock it to restore
  24787. ** the original state */
  24788. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  24789. } else {
  24790. /* if we failed to get the lock then someone else must have it */
  24791. reserved = 1;
  24792. }
  24793. if( IS_LOCK_ERROR(lrc) ){
  24794. rc=lrc;
  24795. }
  24796. }
  24797. unixLeaveMutex();
  24798. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  24799. *pResOut = reserved;
  24800. return rc;
  24801. }
  24802. /*
  24803. ** Lock the file with the lock specified by parameter eFileLock - one
  24804. ** of the following:
  24805. **
  24806. ** (1) SHARED_LOCK
  24807. ** (2) RESERVED_LOCK
  24808. ** (3) PENDING_LOCK
  24809. ** (4) EXCLUSIVE_LOCK
  24810. **
  24811. ** Sometimes when requesting one lock state, additional lock states
  24812. ** are inserted in between. The locking might fail on one of the later
  24813. ** transitions leaving the lock state different from what it started but
  24814. ** still short of its goal. The following chart shows the allowed
  24815. ** transitions and the inserted intermediate states:
  24816. **
  24817. ** UNLOCKED -> SHARED
  24818. ** SHARED -> RESERVED
  24819. ** SHARED -> (PENDING) -> EXCLUSIVE
  24820. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24821. ** PENDING -> EXCLUSIVE
  24822. **
  24823. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24824. ** routine to lower a locking level.
  24825. */
  24826. static int afpLock(sqlite3_file *id, int eFileLock){
  24827. int rc = SQLITE_OK;
  24828. unixFile *pFile = (unixFile*)id;
  24829. unixInodeInfo *pInode = pFile->pInode;
  24830. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24831. assert( pFile );
  24832. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  24833. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24834. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  24835. /* If there is already a lock of this type or more restrictive on the
  24836. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  24837. ** unixEnterMutex() hasn't been called yet.
  24838. */
  24839. if( pFile->eFileLock>=eFileLock ){
  24840. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  24841. azFileLock(eFileLock)));
  24842. return SQLITE_OK;
  24843. }
  24844. /* Make sure the locking sequence is correct
  24845. ** (1) We never move from unlocked to anything higher than shared lock.
  24846. ** (2) SQLite never explicitly requests a pendig lock.
  24847. ** (3) A shared lock is always held when a reserve lock is requested.
  24848. */
  24849. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24850. assert( eFileLock!=PENDING_LOCK );
  24851. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24852. /* This mutex is needed because pFile->pInode is shared across threads
  24853. */
  24854. unixEnterMutex();
  24855. pInode = pFile->pInode;
  24856. /* If some thread using this PID has a lock via a different unixFile*
  24857. ** handle that precludes the requested lock, return BUSY.
  24858. */
  24859. if( (pFile->eFileLock!=pInode->eFileLock &&
  24860. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24861. ){
  24862. rc = SQLITE_BUSY;
  24863. goto afp_end_lock;
  24864. }
  24865. /* If a SHARED lock is requested, and some thread using this PID already
  24866. ** has a SHARED or RESERVED lock, then increment reference counts and
  24867. ** return SQLITE_OK.
  24868. */
  24869. if( eFileLock==SHARED_LOCK &&
  24870. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24871. assert( eFileLock==SHARED_LOCK );
  24872. assert( pFile->eFileLock==0 );
  24873. assert( pInode->nShared>0 );
  24874. pFile->eFileLock = SHARED_LOCK;
  24875. pInode->nShared++;
  24876. pInode->nLock++;
  24877. goto afp_end_lock;
  24878. }
  24879. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24880. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24881. ** be released.
  24882. */
  24883. if( eFileLock==SHARED_LOCK
  24884. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24885. ){
  24886. int failed;
  24887. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  24888. if (failed) {
  24889. rc = failed;
  24890. goto afp_end_lock;
  24891. }
  24892. }
  24893. /* If control gets to this point, then actually go ahead and make
  24894. ** operating system calls for the specified lock.
  24895. */
  24896. if( eFileLock==SHARED_LOCK ){
  24897. int lrc1, lrc2, lrc1Errno = 0;
  24898. long lk, mask;
  24899. assert( pInode->nShared==0 );
  24900. assert( pInode->eFileLock==0 );
  24901. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  24902. /* Now get the read-lock SHARED_LOCK */
  24903. /* note that the quality of the randomness doesn't matter that much */
  24904. lk = random();
  24905. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  24906. lrc1 = afpSetLock(context->dbPath, pFile,
  24907. SHARED_FIRST+pInode->sharedByte, 1, 1);
  24908. if( IS_LOCK_ERROR(lrc1) ){
  24909. lrc1Errno = pFile->lastErrno;
  24910. }
  24911. /* Drop the temporary PENDING lock */
  24912. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  24913. if( IS_LOCK_ERROR(lrc1) ) {
  24914. pFile->lastErrno = lrc1Errno;
  24915. rc = lrc1;
  24916. goto afp_end_lock;
  24917. } else if( IS_LOCK_ERROR(lrc2) ){
  24918. rc = lrc2;
  24919. goto afp_end_lock;
  24920. } else if( lrc1 != SQLITE_OK ) {
  24921. rc = lrc1;
  24922. } else {
  24923. pFile->eFileLock = SHARED_LOCK;
  24924. pInode->nLock++;
  24925. pInode->nShared = 1;
  24926. }
  24927. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  24928. /* We are trying for an exclusive lock but another thread in this
  24929. ** same process is still holding a shared lock. */
  24930. rc = SQLITE_BUSY;
  24931. }else{
  24932. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  24933. ** assumed that there is a SHARED or greater lock on the file
  24934. ** already.
  24935. */
  24936. int failed = 0;
  24937. assert( 0!=pFile->eFileLock );
  24938. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  24939. /* Acquire a RESERVED lock */
  24940. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  24941. if( !failed ){
  24942. context->reserved = 1;
  24943. }
  24944. }
  24945. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  24946. /* Acquire an EXCLUSIVE lock */
  24947. /* Remove the shared lock before trying the range. we'll need to
  24948. ** reestablish the shared lock if we can't get the afpUnlock
  24949. */
  24950. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  24951. pInode->sharedByte, 1, 0)) ){
  24952. int failed2 = SQLITE_OK;
  24953. /* now attemmpt to get the exclusive lock range */
  24954. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  24955. SHARED_SIZE, 1);
  24956. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  24957. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  24958. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  24959. ** a critical I/O error
  24960. */
  24961. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  24962. SQLITE_IOERR_LOCK;
  24963. goto afp_end_lock;
  24964. }
  24965. }else{
  24966. rc = failed;
  24967. }
  24968. }
  24969. if( failed ){
  24970. rc = failed;
  24971. }
  24972. }
  24973. if( rc==SQLITE_OK ){
  24974. pFile->eFileLock = eFileLock;
  24975. pInode->eFileLock = eFileLock;
  24976. }else if( eFileLock==EXCLUSIVE_LOCK ){
  24977. pFile->eFileLock = PENDING_LOCK;
  24978. pInode->eFileLock = PENDING_LOCK;
  24979. }
  24980. afp_end_lock:
  24981. unixLeaveMutex();
  24982. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  24983. rc==SQLITE_OK ? "ok" : "failed"));
  24984. return rc;
  24985. }
  24986. /*
  24987. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  24988. ** must be either NO_LOCK or SHARED_LOCK.
  24989. **
  24990. ** If the locking level of the file descriptor is already at or below
  24991. ** the requested locking level, this routine is a no-op.
  24992. */
  24993. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  24994. int rc = SQLITE_OK;
  24995. unixFile *pFile = (unixFile*)id;
  24996. unixInodeInfo *pInode;
  24997. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  24998. int skipShared = 0;
  24999. #ifdef SQLITE_TEST
  25000. int h = pFile->h;
  25001. #endif
  25002. assert( pFile );
  25003. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  25004. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25005. getpid()));
  25006. assert( eFileLock<=SHARED_LOCK );
  25007. if( pFile->eFileLock<=eFileLock ){
  25008. return SQLITE_OK;
  25009. }
  25010. unixEnterMutex();
  25011. pInode = pFile->pInode;
  25012. assert( pInode->nShared!=0 );
  25013. if( pFile->eFileLock>SHARED_LOCK ){
  25014. assert( pInode->eFileLock==pFile->eFileLock );
  25015. SimulateIOErrorBenign(1);
  25016. SimulateIOError( h=(-1) )
  25017. SimulateIOErrorBenign(0);
  25018. #ifdef SQLITE_DEBUG
  25019. /* When reducing a lock such that other processes can start
  25020. ** reading the database file again, make sure that the
  25021. ** transaction counter was updated if any part of the database
  25022. ** file changed. If the transaction counter is not updated,
  25023. ** other connections to the same file might not realize that
  25024. ** the file has changed and hence might not know to flush their
  25025. ** cache. The use of a stale cache can lead to database corruption.
  25026. */
  25027. assert( pFile->inNormalWrite==0
  25028. || pFile->dbUpdate==0
  25029. || pFile->transCntrChng==1 );
  25030. pFile->inNormalWrite = 0;
  25031. #endif
  25032. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  25033. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  25034. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  25035. /* only re-establish the shared lock if necessary */
  25036. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25037. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  25038. } else {
  25039. skipShared = 1;
  25040. }
  25041. }
  25042. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  25043. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  25044. }
  25045. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  25046. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  25047. if( !rc ){
  25048. context->reserved = 0;
  25049. }
  25050. }
  25051. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  25052. pInode->eFileLock = SHARED_LOCK;
  25053. }
  25054. }
  25055. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  25056. /* Decrement the shared lock counter. Release the lock using an
  25057. ** OS call only when all threads in this same process have released
  25058. ** the lock.
  25059. */
  25060. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  25061. pInode->nShared--;
  25062. if( pInode->nShared==0 ){
  25063. SimulateIOErrorBenign(1);
  25064. SimulateIOError( h=(-1) )
  25065. SimulateIOErrorBenign(0);
  25066. if( !skipShared ){
  25067. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  25068. }
  25069. if( !rc ){
  25070. pInode->eFileLock = NO_LOCK;
  25071. pFile->eFileLock = NO_LOCK;
  25072. }
  25073. }
  25074. if( rc==SQLITE_OK ){
  25075. pInode->nLock--;
  25076. assert( pInode->nLock>=0 );
  25077. if( pInode->nLock==0 ){
  25078. closePendingFds(pFile);
  25079. }
  25080. }
  25081. }
  25082. unixLeaveMutex();
  25083. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25084. return rc;
  25085. }
  25086. /*
  25087. ** Close a file & cleanup AFP specific locking context
  25088. */
  25089. static int afpClose(sqlite3_file *id) {
  25090. int rc = SQLITE_OK;
  25091. if( id ){
  25092. unixFile *pFile = (unixFile*)id;
  25093. afpUnlock(id, NO_LOCK);
  25094. unixEnterMutex();
  25095. if( pFile->pInode && pFile->pInode->nLock ){
  25096. /* If there are outstanding locks, do not actually close the file just
  25097. ** yet because that would clear those locks. Instead, add the file
  25098. ** descriptor to pInode->aPending. It will be automatically closed when
  25099. ** the last lock is cleared.
  25100. */
  25101. setPendingFd(pFile);
  25102. }
  25103. releaseInodeInfo(pFile);
  25104. sqlite3_free(pFile->lockingContext);
  25105. rc = closeUnixFile(id);
  25106. unixLeaveMutex();
  25107. }
  25108. return rc;
  25109. }
  25110. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25111. /*
  25112. ** The code above is the AFP lock implementation. The code is specific
  25113. ** to MacOSX and does not work on other unix platforms. No alternative
  25114. ** is available. If you don't compile for a mac, then the "unix-afp"
  25115. ** VFS is not available.
  25116. **
  25117. ********************* End of the AFP lock implementation **********************
  25118. ******************************************************************************/
  25119. /******************************************************************************
  25120. *************************** Begin NFS Locking ********************************/
  25121. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25122. /*
  25123. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25124. ** must be either NO_LOCK or SHARED_LOCK.
  25125. **
  25126. ** If the locking level of the file descriptor is already at or below
  25127. ** the requested locking level, this routine is a no-op.
  25128. */
  25129. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  25130. return posixUnlock(id, eFileLock, 1);
  25131. }
  25132. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25133. /*
  25134. ** The code above is the NFS lock implementation. The code is specific
  25135. ** to MacOSX and does not work on other unix platforms. No alternative
  25136. ** is available.
  25137. **
  25138. ********************* End of the NFS lock implementation **********************
  25139. ******************************************************************************/
  25140. /******************************************************************************
  25141. **************** Non-locking sqlite3_file methods *****************************
  25142. **
  25143. ** The next division contains implementations for all methods of the
  25144. ** sqlite3_file object other than the locking methods. The locking
  25145. ** methods were defined in divisions above (one locking method per
  25146. ** division). Those methods that are common to all locking modes
  25147. ** are gather together into this division.
  25148. */
  25149. /*
  25150. ** Seek to the offset passed as the second argument, then read cnt
  25151. ** bytes into pBuf. Return the number of bytes actually read.
  25152. **
  25153. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  25154. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  25155. ** one system to another. Since SQLite does not define USE_PREAD
  25156. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  25157. ** See tickets #2741 and #2681.
  25158. **
  25159. ** To avoid stomping the errno value on a failed read the lastErrno value
  25160. ** is set before returning.
  25161. */
  25162. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  25163. int got;
  25164. int prior = 0;
  25165. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  25166. i64 newOffset;
  25167. #endif
  25168. TIMER_START;
  25169. assert( cnt==(cnt&0x1ffff) );
  25170. assert( id->h>2 );
  25171. cnt &= 0x1ffff;
  25172. do{
  25173. #if defined(USE_PREAD)
  25174. got = osPread(id->h, pBuf, cnt, offset);
  25175. SimulateIOError( got = -1 );
  25176. #elif defined(USE_PREAD64)
  25177. got = osPread64(id->h, pBuf, cnt, offset);
  25178. SimulateIOError( got = -1 );
  25179. #else
  25180. newOffset = lseek(id->h, offset, SEEK_SET);
  25181. SimulateIOError( newOffset-- );
  25182. if( newOffset!=offset ){
  25183. if( newOffset == -1 ){
  25184. ((unixFile*)id)->lastErrno = errno;
  25185. }else{
  25186. ((unixFile*)id)->lastErrno = 0;
  25187. }
  25188. return -1;
  25189. }
  25190. got = osRead(id->h, pBuf, cnt);
  25191. #endif
  25192. if( got==cnt ) break;
  25193. if( got<0 ){
  25194. if( errno==EINTR ){ got = 1; continue; }
  25195. prior = 0;
  25196. ((unixFile*)id)->lastErrno = errno;
  25197. break;
  25198. }else if( got>0 ){
  25199. cnt -= got;
  25200. offset += got;
  25201. prior += got;
  25202. pBuf = (void*)(got + (char*)pBuf);
  25203. }
  25204. }while( got>0 );
  25205. TIMER_END;
  25206. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  25207. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  25208. return got+prior;
  25209. }
  25210. /*
  25211. ** Read data from a file into a buffer. Return SQLITE_OK if all
  25212. ** bytes were read successfully and SQLITE_IOERR if anything goes
  25213. ** wrong.
  25214. */
  25215. static int unixRead(
  25216. sqlite3_file *id,
  25217. void *pBuf,
  25218. int amt,
  25219. sqlite3_int64 offset
  25220. ){
  25221. unixFile *pFile = (unixFile *)id;
  25222. int got;
  25223. assert( id );
  25224. assert( offset>=0 );
  25225. assert( amt>0 );
  25226. /* If this is a database file (not a journal, master-journal or temp
  25227. ** file), the bytes in the locking range should never be read or written. */
  25228. #if 0
  25229. assert( pFile->pUnused==0
  25230. || offset>=PENDING_BYTE+512
  25231. || offset+amt<=PENDING_BYTE
  25232. );
  25233. #endif
  25234. #if SQLITE_MAX_MMAP_SIZE>0
  25235. /* Deal with as much of this read request as possible by transfering
  25236. ** data from the memory mapping using memcpy(). */
  25237. if( offset<pFile->mmapSize ){
  25238. if( offset+amt <= pFile->mmapSize ){
  25239. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  25240. return SQLITE_OK;
  25241. }else{
  25242. int nCopy = pFile->mmapSize - offset;
  25243. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  25244. pBuf = &((u8 *)pBuf)[nCopy];
  25245. amt -= nCopy;
  25246. offset += nCopy;
  25247. }
  25248. }
  25249. #endif
  25250. got = seekAndRead(pFile, offset, pBuf, amt);
  25251. if( got==amt ){
  25252. return SQLITE_OK;
  25253. }else if( got<0 ){
  25254. /* lastErrno set by seekAndRead */
  25255. return SQLITE_IOERR_READ;
  25256. }else{
  25257. pFile->lastErrno = 0; /* not a system error */
  25258. /* Unread parts of the buffer must be zero-filled */
  25259. memset(&((char*)pBuf)[got], 0, amt-got);
  25260. return SQLITE_IOERR_SHORT_READ;
  25261. }
  25262. }
  25263. /*
  25264. ** Attempt to seek the file-descriptor passed as the first argument to
  25265. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  25266. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  25267. ** return the actual number of bytes written (which may be less than
  25268. ** nBuf).
  25269. */
  25270. static int seekAndWriteFd(
  25271. int fd, /* File descriptor to write to */
  25272. i64 iOff, /* File offset to begin writing at */
  25273. const void *pBuf, /* Copy data from this buffer to the file */
  25274. int nBuf, /* Size of buffer pBuf in bytes */
  25275. int *piErrno /* OUT: Error number if error occurs */
  25276. ){
  25277. int rc = 0; /* Value returned by system call */
  25278. assert( nBuf==(nBuf&0x1ffff) );
  25279. assert( fd>2 );
  25280. nBuf &= 0x1ffff;
  25281. TIMER_START;
  25282. #if defined(USE_PREAD)
  25283. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  25284. #elif defined(USE_PREAD64)
  25285. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  25286. #else
  25287. do{
  25288. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  25289. SimulateIOError( iSeek-- );
  25290. if( iSeek!=iOff ){
  25291. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  25292. return -1;
  25293. }
  25294. rc = osWrite(fd, pBuf, nBuf);
  25295. }while( rc<0 && errno==EINTR );
  25296. #endif
  25297. TIMER_END;
  25298. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  25299. if( rc<0 && piErrno ) *piErrno = errno;
  25300. return rc;
  25301. }
  25302. /*
  25303. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  25304. ** Return the number of bytes actually read. Update the offset.
  25305. **
  25306. ** To avoid stomping the errno value on a failed write the lastErrno value
  25307. ** is set before returning.
  25308. */
  25309. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  25310. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  25311. }
  25312. /*
  25313. ** Write data from a buffer into a file. Return SQLITE_OK on success
  25314. ** or some other error code on failure.
  25315. */
  25316. static int unixWrite(
  25317. sqlite3_file *id,
  25318. const void *pBuf,
  25319. int amt,
  25320. sqlite3_int64 offset
  25321. ){
  25322. unixFile *pFile = (unixFile*)id;
  25323. int wrote = 0;
  25324. assert( id );
  25325. assert( amt>0 );
  25326. /* If this is a database file (not a journal, master-journal or temp
  25327. ** file), the bytes in the locking range should never be read or written. */
  25328. #if 0
  25329. assert( pFile->pUnused==0
  25330. || offset>=PENDING_BYTE+512
  25331. || offset+amt<=PENDING_BYTE
  25332. );
  25333. #endif
  25334. #ifdef SQLITE_DEBUG
  25335. /* If we are doing a normal write to a database file (as opposed to
  25336. ** doing a hot-journal rollback or a write to some file other than a
  25337. ** normal database file) then record the fact that the database
  25338. ** has changed. If the transaction counter is modified, record that
  25339. ** fact too.
  25340. */
  25341. if( pFile->inNormalWrite ){
  25342. pFile->dbUpdate = 1; /* The database has been modified */
  25343. if( offset<=24 && offset+amt>=27 ){
  25344. int rc;
  25345. char oldCntr[4];
  25346. SimulateIOErrorBenign(1);
  25347. rc = seekAndRead(pFile, 24, oldCntr, 4);
  25348. SimulateIOErrorBenign(0);
  25349. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  25350. pFile->transCntrChng = 1; /* The transaction counter has changed */
  25351. }
  25352. }
  25353. }
  25354. #endif
  25355. #if SQLITE_MAX_MMAP_SIZE>0
  25356. /* Deal with as much of this write request as possible by transfering
  25357. ** data from the memory mapping using memcpy(). */
  25358. if( offset<pFile->mmapSize ){
  25359. if( offset+amt <= pFile->mmapSize ){
  25360. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  25361. return SQLITE_OK;
  25362. }else{
  25363. int nCopy = pFile->mmapSize - offset;
  25364. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  25365. pBuf = &((u8 *)pBuf)[nCopy];
  25366. amt -= nCopy;
  25367. offset += nCopy;
  25368. }
  25369. }
  25370. #endif
  25371. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  25372. amt -= wrote;
  25373. offset += wrote;
  25374. pBuf = &((char*)pBuf)[wrote];
  25375. }
  25376. SimulateIOError(( wrote=(-1), amt=1 ));
  25377. SimulateDiskfullError(( wrote=0, amt=1 ));
  25378. if( amt>0 ){
  25379. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  25380. /* lastErrno set by seekAndWrite */
  25381. return SQLITE_IOERR_WRITE;
  25382. }else{
  25383. pFile->lastErrno = 0; /* not a system error */
  25384. return SQLITE_FULL;
  25385. }
  25386. }
  25387. return SQLITE_OK;
  25388. }
  25389. #ifdef SQLITE_TEST
  25390. /*
  25391. ** Count the number of fullsyncs and normal syncs. This is used to test
  25392. ** that syncs and fullsyncs are occurring at the right times.
  25393. */
  25394. SQLITE_API int sqlite3_sync_count = 0;
  25395. SQLITE_API int sqlite3_fullsync_count = 0;
  25396. #endif
  25397. /*
  25398. ** We do not trust systems to provide a working fdatasync(). Some do.
  25399. ** Others do no. To be safe, we will stick with the (slightly slower)
  25400. ** fsync(). If you know that your system does support fdatasync() correctly,
  25401. ** then simply compile with -Dfdatasync=fdatasync
  25402. */
  25403. #if !defined(fdatasync)
  25404. # define fdatasync fsync
  25405. #endif
  25406. /*
  25407. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  25408. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  25409. ** only available on Mac OS X. But that could change.
  25410. */
  25411. #ifdef F_FULLFSYNC
  25412. # define HAVE_FULLFSYNC 1
  25413. #else
  25414. # define HAVE_FULLFSYNC 0
  25415. #endif
  25416. /*
  25417. ** The fsync() system call does not work as advertised on many
  25418. ** unix systems. The following procedure is an attempt to make
  25419. ** it work better.
  25420. **
  25421. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  25422. ** for testing when we want to run through the test suite quickly.
  25423. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  25424. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  25425. ** or power failure will likely corrupt the database file.
  25426. **
  25427. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  25428. ** The idea behind dataOnly is that it should only write the file content
  25429. ** to disk, not the inode. We only set dataOnly if the file size is
  25430. ** unchanged since the file size is part of the inode. However,
  25431. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  25432. ** file size has changed. The only real difference between fdatasync()
  25433. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  25434. ** inode if the mtime or owner or other inode attributes have changed.
  25435. ** We only care about the file size, not the other file attributes, so
  25436. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  25437. ** So, we always use fdatasync() if it is available, regardless of
  25438. ** the value of the dataOnly flag.
  25439. */
  25440. static int full_fsync(int fd, int fullSync, int dataOnly){
  25441. int rc;
  25442. /* The following "ifdef/elif/else/" block has the same structure as
  25443. ** the one below. It is replicated here solely to avoid cluttering
  25444. ** up the real code with the UNUSED_PARAMETER() macros.
  25445. */
  25446. #ifdef SQLITE_NO_SYNC
  25447. UNUSED_PARAMETER(fd);
  25448. UNUSED_PARAMETER(fullSync);
  25449. UNUSED_PARAMETER(dataOnly);
  25450. #elif HAVE_FULLFSYNC
  25451. UNUSED_PARAMETER(dataOnly);
  25452. #else
  25453. UNUSED_PARAMETER(fullSync);
  25454. UNUSED_PARAMETER(dataOnly);
  25455. #endif
  25456. /* Record the number of times that we do a normal fsync() and
  25457. ** FULLSYNC. This is used during testing to verify that this procedure
  25458. ** gets called with the correct arguments.
  25459. */
  25460. #ifdef SQLITE_TEST
  25461. if( fullSync ) sqlite3_fullsync_count++;
  25462. sqlite3_sync_count++;
  25463. #endif
  25464. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  25465. ** no-op
  25466. */
  25467. #ifdef SQLITE_NO_SYNC
  25468. rc = SQLITE_OK;
  25469. #elif HAVE_FULLFSYNC
  25470. if( fullSync ){
  25471. rc = osFcntl(fd, F_FULLFSYNC, 0);
  25472. }else{
  25473. rc = 1;
  25474. }
  25475. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  25476. ** It shouldn't be possible for fullfsync to fail on the local
  25477. ** file system (on OSX), so failure indicates that FULLFSYNC
  25478. ** isn't supported for this file system. So, attempt an fsync
  25479. ** and (for now) ignore the overhead of a superfluous fcntl call.
  25480. ** It'd be better to detect fullfsync support once and avoid
  25481. ** the fcntl call every time sync is called.
  25482. */
  25483. if( rc ) rc = fsync(fd);
  25484. #elif defined(__APPLE__)
  25485. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  25486. ** so currently we default to the macro that redefines fdatasync to fsync
  25487. */
  25488. rc = fsync(fd);
  25489. #else
  25490. rc = fdatasync(fd);
  25491. #if OS_VXWORKS
  25492. if( rc==-1 && errno==ENOTSUP ){
  25493. rc = fsync(fd);
  25494. }
  25495. #endif /* OS_VXWORKS */
  25496. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  25497. if( OS_VXWORKS && rc!= -1 ){
  25498. rc = 0;
  25499. }
  25500. return rc;
  25501. }
  25502. /*
  25503. ** Open a file descriptor to the directory containing file zFilename.
  25504. ** If successful, *pFd is set to the opened file descriptor and
  25505. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  25506. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  25507. ** value.
  25508. **
  25509. ** The directory file descriptor is used for only one thing - to
  25510. ** fsync() a directory to make sure file creation and deletion events
  25511. ** are flushed to disk. Such fsyncs are not needed on newer
  25512. ** journaling filesystems, but are required on older filesystems.
  25513. **
  25514. ** This routine can be overridden using the xSetSysCall interface.
  25515. ** The ability to override this routine was added in support of the
  25516. ** chromium sandbox. Opening a directory is a security risk (we are
  25517. ** told) so making it overrideable allows the chromium sandbox to
  25518. ** replace this routine with a harmless no-op. To make this routine
  25519. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  25520. ** *pFd set to a negative number.
  25521. **
  25522. ** If SQLITE_OK is returned, the caller is responsible for closing
  25523. ** the file descriptor *pFd using close().
  25524. */
  25525. static int openDirectory(const char *zFilename, int *pFd){
  25526. int ii;
  25527. int fd = -1;
  25528. char zDirname[MAX_PATHNAME+1];
  25529. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  25530. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  25531. if( ii>0 ){
  25532. zDirname[ii] = '\0';
  25533. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  25534. if( fd>=0 ){
  25535. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  25536. }
  25537. }
  25538. *pFd = fd;
  25539. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  25540. }
  25541. /*
  25542. ** Make sure all writes to a particular file are committed to disk.
  25543. **
  25544. ** If dataOnly==0 then both the file itself and its metadata (file
  25545. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  25546. ** file data is synced.
  25547. **
  25548. ** Under Unix, also make sure that the directory entry for the file
  25549. ** has been created by fsync-ing the directory that contains the file.
  25550. ** If we do not do this and we encounter a power failure, the directory
  25551. ** entry for the journal might not exist after we reboot. The next
  25552. ** SQLite to access the file will not know that the journal exists (because
  25553. ** the directory entry for the journal was never created) and the transaction
  25554. ** will not roll back - possibly leading to database corruption.
  25555. */
  25556. static int unixSync(sqlite3_file *id, int flags){
  25557. int rc;
  25558. unixFile *pFile = (unixFile*)id;
  25559. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  25560. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  25561. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  25562. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  25563. || (flags&0x0F)==SQLITE_SYNC_FULL
  25564. );
  25565. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  25566. ** line is to test that doing so does not cause any problems.
  25567. */
  25568. SimulateDiskfullError( return SQLITE_FULL );
  25569. assert( pFile );
  25570. OSTRACE(("SYNC %-3d\n", pFile->h));
  25571. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  25572. SimulateIOError( rc=1 );
  25573. if( rc ){
  25574. pFile->lastErrno = errno;
  25575. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  25576. }
  25577. /* Also fsync the directory containing the file if the DIRSYNC flag
  25578. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  25579. ** are unable to fsync a directory, so ignore errors on the fsync.
  25580. */
  25581. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  25582. int dirfd;
  25583. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  25584. HAVE_FULLFSYNC, isFullsync));
  25585. rc = osOpenDirectory(pFile->zPath, &dirfd);
  25586. if( rc==SQLITE_OK && dirfd>=0 ){
  25587. full_fsync(dirfd, 0, 0);
  25588. robust_close(pFile, dirfd, __LINE__);
  25589. }else if( rc==SQLITE_CANTOPEN ){
  25590. rc = SQLITE_OK;
  25591. }
  25592. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  25593. }
  25594. return rc;
  25595. }
  25596. /*
  25597. ** Truncate an open file to a specified size
  25598. */
  25599. static int unixTruncate(sqlite3_file *id, i64 nByte){
  25600. unixFile *pFile = (unixFile *)id;
  25601. int rc;
  25602. assert( pFile );
  25603. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  25604. /* If the user has configured a chunk-size for this file, truncate the
  25605. ** file so that it consists of an integer number of chunks (i.e. the
  25606. ** actual file size after the operation may be larger than the requested
  25607. ** size).
  25608. */
  25609. if( pFile->szChunk>0 ){
  25610. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  25611. }
  25612. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  25613. if( rc ){
  25614. pFile->lastErrno = errno;
  25615. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25616. }else{
  25617. #ifdef SQLITE_DEBUG
  25618. /* If we are doing a normal write to a database file (as opposed to
  25619. ** doing a hot-journal rollback or a write to some file other than a
  25620. ** normal database file) and we truncate the file to zero length,
  25621. ** that effectively updates the change counter. This might happen
  25622. ** when restoring a database using the backup API from a zero-length
  25623. ** source.
  25624. */
  25625. if( pFile->inNormalWrite && nByte==0 ){
  25626. pFile->transCntrChng = 1;
  25627. }
  25628. #endif
  25629. #if SQLITE_MAX_MMAP_SIZE>0
  25630. /* If the file was just truncated to a size smaller than the currently
  25631. ** mapped region, reduce the effective mapping size as well. SQLite will
  25632. ** use read() and write() to access data beyond this point from now on.
  25633. */
  25634. if( nByte<pFile->mmapSize ){
  25635. pFile->mmapSize = nByte;
  25636. }
  25637. #endif
  25638. return SQLITE_OK;
  25639. }
  25640. }
  25641. /*
  25642. ** Determine the current size of a file in bytes
  25643. */
  25644. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  25645. int rc;
  25646. struct stat buf;
  25647. assert( id );
  25648. rc = osFstat(((unixFile*)id)->h, &buf);
  25649. SimulateIOError( rc=1 );
  25650. if( rc!=0 ){
  25651. ((unixFile*)id)->lastErrno = errno;
  25652. return SQLITE_IOERR_FSTAT;
  25653. }
  25654. *pSize = buf.st_size;
  25655. /* When opening a zero-size database, the findInodeInfo() procedure
  25656. ** writes a single byte into that file in order to work around a bug
  25657. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  25658. ** layers, we need to report this file size as zero even though it is
  25659. ** really 1. Ticket #3260.
  25660. */
  25661. if( *pSize==1 ) *pSize = 0;
  25662. return SQLITE_OK;
  25663. }
  25664. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25665. /*
  25666. ** Handler for proxy-locking file-control verbs. Defined below in the
  25667. ** proxying locking division.
  25668. */
  25669. static int proxyFileControl(sqlite3_file*,int,void*);
  25670. #endif
  25671. /*
  25672. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  25673. ** file-control operation. Enlarge the database to nBytes in size
  25674. ** (rounded up to the next chunk-size). If the database is already
  25675. ** nBytes or larger, this routine is a no-op.
  25676. */
  25677. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  25678. if( pFile->szChunk>0 ){
  25679. i64 nSize; /* Required file size */
  25680. struct stat buf; /* Used to hold return values of fstat() */
  25681. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  25682. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  25683. if( nSize>(i64)buf.st_size ){
  25684. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  25685. /* The code below is handling the return value of osFallocate()
  25686. ** correctly. posix_fallocate() is defined to "returns zero on success,
  25687. ** or an error number on failure". See the manpage for details. */
  25688. int err;
  25689. do{
  25690. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  25691. }while( err==EINTR );
  25692. if( err ) return SQLITE_IOERR_WRITE;
  25693. #else
  25694. /* If the OS does not have posix_fallocate(), fake it. First use
  25695. ** ftruncate() to set the file size, then write a single byte to
  25696. ** the last byte in each block within the extended region. This
  25697. ** is the same technique used by glibc to implement posix_fallocate()
  25698. ** on systems that do not have a real fallocate() system call.
  25699. */
  25700. int nBlk = buf.st_blksize; /* File-system block size */
  25701. i64 iWrite; /* Next offset to write to */
  25702. if( robust_ftruncate(pFile->h, nSize) ){
  25703. pFile->lastErrno = errno;
  25704. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25705. }
  25706. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  25707. while( iWrite<nSize ){
  25708. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  25709. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  25710. iWrite += nBlk;
  25711. }
  25712. #endif
  25713. }
  25714. }
  25715. #if SQLITE_MAX_MMAP_SIZE>0
  25716. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  25717. int rc;
  25718. if( pFile->szChunk<=0 ){
  25719. if( robust_ftruncate(pFile->h, nByte) ){
  25720. pFile->lastErrno = errno;
  25721. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  25722. }
  25723. }
  25724. rc = unixMapfile(pFile, nByte);
  25725. return rc;
  25726. }
  25727. #endif
  25728. return SQLITE_OK;
  25729. }
  25730. /*
  25731. ** If *pArg is inititially negative then this is a query. Set *pArg to
  25732. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  25733. **
  25734. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  25735. */
  25736. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  25737. if( *pArg<0 ){
  25738. *pArg = (pFile->ctrlFlags & mask)!=0;
  25739. }else if( (*pArg)==0 ){
  25740. pFile->ctrlFlags &= ~mask;
  25741. }else{
  25742. pFile->ctrlFlags |= mask;
  25743. }
  25744. }
  25745. /* Forward declaration */
  25746. static int unixGetTempname(int nBuf, char *zBuf);
  25747. /*
  25748. ** Information and control of an open file handle.
  25749. */
  25750. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  25751. unixFile *pFile = (unixFile*)id;
  25752. switch( op ){
  25753. case SQLITE_FCNTL_LOCKSTATE: {
  25754. *(int*)pArg = pFile->eFileLock;
  25755. return SQLITE_OK;
  25756. }
  25757. case SQLITE_LAST_ERRNO: {
  25758. *(int*)pArg = pFile->lastErrno;
  25759. return SQLITE_OK;
  25760. }
  25761. case SQLITE_FCNTL_CHUNK_SIZE: {
  25762. pFile->szChunk = *(int *)pArg;
  25763. return SQLITE_OK;
  25764. }
  25765. case SQLITE_FCNTL_SIZE_HINT: {
  25766. int rc;
  25767. SimulateIOErrorBenign(1);
  25768. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  25769. SimulateIOErrorBenign(0);
  25770. return rc;
  25771. }
  25772. case SQLITE_FCNTL_PERSIST_WAL: {
  25773. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  25774. return SQLITE_OK;
  25775. }
  25776. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  25777. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  25778. return SQLITE_OK;
  25779. }
  25780. case SQLITE_FCNTL_VFSNAME: {
  25781. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  25782. return SQLITE_OK;
  25783. }
  25784. case SQLITE_FCNTL_TEMPFILENAME: {
  25785. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  25786. if( zTFile ){
  25787. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  25788. *(char**)pArg = zTFile;
  25789. }
  25790. return SQLITE_OK;
  25791. }
  25792. #if SQLITE_MAX_MMAP_SIZE>0
  25793. case SQLITE_FCNTL_MMAP_SIZE: {
  25794. i64 newLimit = *(i64*)pArg;
  25795. int rc = SQLITE_OK;
  25796. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  25797. newLimit = sqlite3GlobalConfig.mxMmap;
  25798. }
  25799. *(i64*)pArg = pFile->mmapSizeMax;
  25800. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  25801. pFile->mmapSizeMax = newLimit;
  25802. if( pFile->mmapSize>0 ){
  25803. unixUnmapfile(pFile);
  25804. rc = unixMapfile(pFile, -1);
  25805. }
  25806. }
  25807. return rc;
  25808. }
  25809. #endif
  25810. #ifdef SQLITE_DEBUG
  25811. /* The pager calls this method to signal that it has done
  25812. ** a rollback and that the database is therefore unchanged and
  25813. ** it hence it is OK for the transaction change counter to be
  25814. ** unchanged.
  25815. */
  25816. case SQLITE_FCNTL_DB_UNCHANGED: {
  25817. ((unixFile*)id)->dbUpdate = 0;
  25818. return SQLITE_OK;
  25819. }
  25820. #endif
  25821. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  25822. case SQLITE_SET_LOCKPROXYFILE:
  25823. case SQLITE_GET_LOCKPROXYFILE: {
  25824. return proxyFileControl(id,op,pArg);
  25825. }
  25826. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  25827. }
  25828. return SQLITE_NOTFOUND;
  25829. }
  25830. /*
  25831. ** Return the sector size in bytes of the underlying block device for
  25832. ** the specified file. This is almost always 512 bytes, but may be
  25833. ** larger for some devices.
  25834. **
  25835. ** SQLite code assumes this function cannot fail. It also assumes that
  25836. ** if two files are created in the same file-system directory (i.e.
  25837. ** a database and its journal file) that the sector size will be the
  25838. ** same for both.
  25839. */
  25840. #ifndef __QNXNTO__
  25841. static int unixSectorSize(sqlite3_file *NotUsed){
  25842. UNUSED_PARAMETER(NotUsed);
  25843. return SQLITE_DEFAULT_SECTOR_SIZE;
  25844. }
  25845. #endif
  25846. /*
  25847. ** The following version of unixSectorSize() is optimized for QNX.
  25848. */
  25849. #ifdef __QNXNTO__
  25850. #include <sys/dcmd_blk.h>
  25851. #include <sys/statvfs.h>
  25852. static int unixSectorSize(sqlite3_file *id){
  25853. unixFile *pFile = (unixFile*)id;
  25854. if( pFile->sectorSize == 0 ){
  25855. struct statvfs fsInfo;
  25856. /* Set defaults for non-supported filesystems */
  25857. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25858. pFile->deviceCharacteristics = 0;
  25859. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  25860. return pFile->sectorSize;
  25861. }
  25862. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  25863. pFile->sectorSize = fsInfo.f_bsize;
  25864. pFile->deviceCharacteristics =
  25865. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  25866. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25867. ** the write succeeds */
  25868. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25869. ** so it is ordered */
  25870. 0;
  25871. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  25872. pFile->sectorSize = fsInfo.f_bsize;
  25873. pFile->deviceCharacteristics =
  25874. /* etfs cluster size writes are atomic */
  25875. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  25876. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25877. ** the write succeeds */
  25878. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25879. ** so it is ordered */
  25880. 0;
  25881. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  25882. pFile->sectorSize = fsInfo.f_bsize;
  25883. pFile->deviceCharacteristics =
  25884. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  25885. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25886. ** the write succeeds */
  25887. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25888. ** so it is ordered */
  25889. 0;
  25890. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  25891. pFile->sectorSize = fsInfo.f_bsize;
  25892. pFile->deviceCharacteristics =
  25893. /* full bitset of atomics from max sector size and smaller */
  25894. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25895. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25896. ** so it is ordered */
  25897. 0;
  25898. }else if( strstr(fsInfo.f_basetype, "dos") ){
  25899. pFile->sectorSize = fsInfo.f_bsize;
  25900. pFile->deviceCharacteristics =
  25901. /* full bitset of atomics from max sector size and smaller */
  25902. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  25903. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  25904. ** so it is ordered */
  25905. 0;
  25906. }else{
  25907. pFile->deviceCharacteristics =
  25908. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  25909. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  25910. ** the write succeeds */
  25911. 0;
  25912. }
  25913. }
  25914. /* Last chance verification. If the sector size isn't a multiple of 512
  25915. ** then it isn't valid.*/
  25916. if( pFile->sectorSize % 512 != 0 ){
  25917. pFile->deviceCharacteristics = 0;
  25918. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  25919. }
  25920. return pFile->sectorSize;
  25921. }
  25922. #endif /* __QNXNTO__ */
  25923. /*
  25924. ** Return the device characteristics for the file.
  25925. **
  25926. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  25927. ** However, that choice is contraversial since technically the underlying
  25928. ** file system does not always provide powersafe overwrites. (In other
  25929. ** words, after a power-loss event, parts of the file that were never
  25930. ** written might end up being altered.) However, non-PSOW behavior is very,
  25931. ** very rare. And asserting PSOW makes a large reduction in the amount
  25932. ** of required I/O for journaling, since a lot of padding is eliminated.
  25933. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  25934. ** available to turn it off and URI query parameter available to turn it off.
  25935. */
  25936. static int unixDeviceCharacteristics(sqlite3_file *id){
  25937. unixFile *p = (unixFile*)id;
  25938. int rc = 0;
  25939. #ifdef __QNXNTO__
  25940. if( p->sectorSize==0 ) unixSectorSize(id);
  25941. rc = p->deviceCharacteristics;
  25942. #endif
  25943. if( p->ctrlFlags & UNIXFILE_PSOW ){
  25944. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  25945. }
  25946. return rc;
  25947. }
  25948. #ifndef SQLITE_OMIT_WAL
  25949. /*
  25950. ** Object used to represent an shared memory buffer.
  25951. **
  25952. ** When multiple threads all reference the same wal-index, each thread
  25953. ** has its own unixShm object, but they all point to a single instance
  25954. ** of this unixShmNode object. In other words, each wal-index is opened
  25955. ** only once per process.
  25956. **
  25957. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  25958. ** We could coalesce this object into unixInodeInfo, but that would mean
  25959. ** every open file that does not use shared memory (in other words, most
  25960. ** open files) would have to carry around this extra information. So
  25961. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  25962. ** and the unixShmNode object is created only when needed.
  25963. **
  25964. ** unixMutexHeld() must be true when creating or destroying
  25965. ** this object or while reading or writing the following fields:
  25966. **
  25967. ** nRef
  25968. **
  25969. ** The following fields are read-only after the object is created:
  25970. **
  25971. ** fid
  25972. ** zFilename
  25973. **
  25974. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  25975. ** unixMutexHeld() is true when reading or writing any other field
  25976. ** in this structure.
  25977. */
  25978. struct unixShmNode {
  25979. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  25980. sqlite3_mutex *mutex; /* Mutex to access this object */
  25981. char *zFilename; /* Name of the mmapped file */
  25982. int h; /* Open file descriptor */
  25983. int szRegion; /* Size of shared-memory regions */
  25984. u16 nRegion; /* Size of array apRegion */
  25985. u8 isReadonly; /* True if read-only */
  25986. char **apRegion; /* Array of mapped shared-memory regions */
  25987. int nRef; /* Number of unixShm objects pointing to this */
  25988. unixShm *pFirst; /* All unixShm objects pointing to this */
  25989. #ifdef SQLITE_DEBUG
  25990. u8 exclMask; /* Mask of exclusive locks held */
  25991. u8 sharedMask; /* Mask of shared locks held */
  25992. u8 nextShmId; /* Next available unixShm.id value */
  25993. #endif
  25994. };
  25995. /*
  25996. ** Structure used internally by this VFS to record the state of an
  25997. ** open shared memory connection.
  25998. **
  25999. ** The following fields are initialized when this object is created and
  26000. ** are read-only thereafter:
  26001. **
  26002. ** unixShm.pFile
  26003. ** unixShm.id
  26004. **
  26005. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  26006. ** while accessing any read/write fields.
  26007. */
  26008. struct unixShm {
  26009. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  26010. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  26011. u8 hasMutex; /* True if holding the unixShmNode mutex */
  26012. u8 id; /* Id of this connection within its unixShmNode */
  26013. u16 sharedMask; /* Mask of shared locks held */
  26014. u16 exclMask; /* Mask of exclusive locks held */
  26015. };
  26016. /*
  26017. ** Constants used for locking
  26018. */
  26019. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  26020. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  26021. /*
  26022. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  26023. **
  26024. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  26025. ** otherwise.
  26026. */
  26027. static int unixShmSystemLock(
  26028. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  26029. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  26030. int ofst, /* First byte of the locking range */
  26031. int n /* Number of bytes to lock */
  26032. ){
  26033. struct flock f; /* The posix advisory locking structure */
  26034. int rc = SQLITE_OK; /* Result code form fcntl() */
  26035. /* Access to the unixShmNode object is serialized by the caller */
  26036. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  26037. /* Shared locks never span more than one byte */
  26038. assert( n==1 || lockType!=F_RDLCK );
  26039. /* Locks are within range */
  26040. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  26041. if( pShmNode->h>=0 ){
  26042. /* Initialize the locking parameters */
  26043. memset(&f, 0, sizeof(f));
  26044. f.l_type = lockType;
  26045. f.l_whence = SEEK_SET;
  26046. f.l_start = ofst;
  26047. f.l_len = n;
  26048. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  26049. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  26050. }
  26051. /* Update the global lock state and do debug tracing */
  26052. #ifdef SQLITE_DEBUG
  26053. { u16 mask;
  26054. OSTRACE(("SHM-LOCK "));
  26055. mask = (1<<(ofst+n)) - (1<<ofst);
  26056. if( rc==SQLITE_OK ){
  26057. if( lockType==F_UNLCK ){
  26058. OSTRACE(("unlock %d ok", ofst));
  26059. pShmNode->exclMask &= ~mask;
  26060. pShmNode->sharedMask &= ~mask;
  26061. }else if( lockType==F_RDLCK ){
  26062. OSTRACE(("read-lock %d ok", ofst));
  26063. pShmNode->exclMask &= ~mask;
  26064. pShmNode->sharedMask |= mask;
  26065. }else{
  26066. assert( lockType==F_WRLCK );
  26067. OSTRACE(("write-lock %d ok", ofst));
  26068. pShmNode->exclMask |= mask;
  26069. pShmNode->sharedMask &= ~mask;
  26070. }
  26071. }else{
  26072. if( lockType==F_UNLCK ){
  26073. OSTRACE(("unlock %d failed", ofst));
  26074. }else if( lockType==F_RDLCK ){
  26075. OSTRACE(("read-lock failed"));
  26076. }else{
  26077. assert( lockType==F_WRLCK );
  26078. OSTRACE(("write-lock %d failed", ofst));
  26079. }
  26080. }
  26081. OSTRACE((" - afterwards %03x,%03x\n",
  26082. pShmNode->sharedMask, pShmNode->exclMask));
  26083. }
  26084. #endif
  26085. return rc;
  26086. }
  26087. /*
  26088. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  26089. **
  26090. ** This is not a VFS shared-memory method; it is a utility function called
  26091. ** by VFS shared-memory methods.
  26092. */
  26093. static void unixShmPurge(unixFile *pFd){
  26094. unixShmNode *p = pFd->pInode->pShmNode;
  26095. assert( unixMutexHeld() );
  26096. if( p && p->nRef==0 ){
  26097. int i;
  26098. assert( p->pInode==pFd->pInode );
  26099. sqlite3_mutex_free(p->mutex);
  26100. for(i=0; i<p->nRegion; i++){
  26101. if( p->h>=0 ){
  26102. osMunmap(p->apRegion[i], p->szRegion);
  26103. }else{
  26104. sqlite3_free(p->apRegion[i]);
  26105. }
  26106. }
  26107. sqlite3_free(p->apRegion);
  26108. if( p->h>=0 ){
  26109. robust_close(pFd, p->h, __LINE__);
  26110. p->h = -1;
  26111. }
  26112. p->pInode->pShmNode = 0;
  26113. sqlite3_free(p);
  26114. }
  26115. }
  26116. /*
  26117. ** Open a shared-memory area associated with open database file pDbFd.
  26118. ** This particular implementation uses mmapped files.
  26119. **
  26120. ** The file used to implement shared-memory is in the same directory
  26121. ** as the open database file and has the same name as the open database
  26122. ** file with the "-shm" suffix added. For example, if the database file
  26123. ** is "/home/user1/config.db" then the file that is created and mmapped
  26124. ** for shared memory will be called "/home/user1/config.db-shm".
  26125. **
  26126. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  26127. ** some other tmpfs mount. But if a file in a different directory
  26128. ** from the database file is used, then differing access permissions
  26129. ** or a chroot() might cause two different processes on the same
  26130. ** database to end up using different files for shared memory -
  26131. ** meaning that their memory would not really be shared - resulting
  26132. ** in database corruption. Nevertheless, this tmpfs file usage
  26133. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  26134. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  26135. ** option results in an incompatible build of SQLite; builds of SQLite
  26136. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  26137. ** same database file at the same time, database corruption will likely
  26138. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  26139. ** "unsupported" and may go away in a future SQLite release.
  26140. **
  26141. ** When opening a new shared-memory file, if no other instances of that
  26142. ** file are currently open, in this process or in other processes, then
  26143. ** the file must be truncated to zero length or have its header cleared.
  26144. **
  26145. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  26146. ** that means that an exclusive lock is held on the database file and
  26147. ** that no other processes are able to read or write the database. In
  26148. ** that case, we do not really need shared memory. No shared memory
  26149. ** file is created. The shared memory will be simulated with heap memory.
  26150. */
  26151. static int unixOpenSharedMemory(unixFile *pDbFd){
  26152. struct unixShm *p = 0; /* The connection to be opened */
  26153. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  26154. int rc; /* Result code */
  26155. unixInodeInfo *pInode; /* The inode of fd */
  26156. char *zShmFilename; /* Name of the file used for SHM */
  26157. int nShmFilename; /* Size of the SHM filename in bytes */
  26158. /* Allocate space for the new unixShm object. */
  26159. p = sqlite3_malloc( sizeof(*p) );
  26160. if( p==0 ) return SQLITE_NOMEM;
  26161. memset(p, 0, sizeof(*p));
  26162. assert( pDbFd->pShm==0 );
  26163. /* Check to see if a unixShmNode object already exists. Reuse an existing
  26164. ** one if present. Create a new one if necessary.
  26165. */
  26166. unixEnterMutex();
  26167. pInode = pDbFd->pInode;
  26168. pShmNode = pInode->pShmNode;
  26169. if( pShmNode==0 ){
  26170. struct stat sStat; /* fstat() info for database file */
  26171. /* Call fstat() to figure out the permissions on the database file. If
  26172. ** a new *-shm file is created, an attempt will be made to create it
  26173. ** with the same permissions.
  26174. */
  26175. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  26176. rc = SQLITE_IOERR_FSTAT;
  26177. goto shm_open_err;
  26178. }
  26179. #ifdef SQLITE_SHM_DIRECTORY
  26180. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  26181. #else
  26182. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  26183. #endif
  26184. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  26185. if( pShmNode==0 ){
  26186. rc = SQLITE_NOMEM;
  26187. goto shm_open_err;
  26188. }
  26189. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  26190. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  26191. #ifdef SQLITE_SHM_DIRECTORY
  26192. sqlite3_snprintf(nShmFilename, zShmFilename,
  26193. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  26194. (u32)sStat.st_ino, (u32)sStat.st_dev);
  26195. #else
  26196. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  26197. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  26198. #endif
  26199. pShmNode->h = -1;
  26200. pDbFd->pInode->pShmNode = pShmNode;
  26201. pShmNode->pInode = pDbFd->pInode;
  26202. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  26203. if( pShmNode->mutex==0 ){
  26204. rc = SQLITE_NOMEM;
  26205. goto shm_open_err;
  26206. }
  26207. if( pInode->bProcessLock==0 ){
  26208. int openFlags = O_RDWR | O_CREAT;
  26209. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  26210. openFlags = O_RDONLY;
  26211. pShmNode->isReadonly = 1;
  26212. }
  26213. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  26214. if( pShmNode->h<0 ){
  26215. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  26216. goto shm_open_err;
  26217. }
  26218. /* If this process is running as root, make sure that the SHM file
  26219. ** is owned by the same user that owns the original database. Otherwise,
  26220. ** the original owner will not be able to connect.
  26221. */
  26222. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  26223. /* Check to see if another process is holding the dead-man switch.
  26224. ** If not, truncate the file to zero length.
  26225. */
  26226. rc = SQLITE_OK;
  26227. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  26228. if( robust_ftruncate(pShmNode->h, 0) ){
  26229. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  26230. }
  26231. }
  26232. if( rc==SQLITE_OK ){
  26233. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  26234. }
  26235. if( rc ) goto shm_open_err;
  26236. }
  26237. }
  26238. /* Make the new connection a child of the unixShmNode */
  26239. p->pShmNode = pShmNode;
  26240. #ifdef SQLITE_DEBUG
  26241. p->id = pShmNode->nextShmId++;
  26242. #endif
  26243. pShmNode->nRef++;
  26244. pDbFd->pShm = p;
  26245. unixLeaveMutex();
  26246. /* The reference count on pShmNode has already been incremented under
  26247. ** the cover of the unixEnterMutex() mutex and the pointer from the
  26248. ** new (struct unixShm) object to the pShmNode has been set. All that is
  26249. ** left to do is to link the new object into the linked list starting
  26250. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  26251. ** mutex.
  26252. */
  26253. sqlite3_mutex_enter(pShmNode->mutex);
  26254. p->pNext = pShmNode->pFirst;
  26255. pShmNode->pFirst = p;
  26256. sqlite3_mutex_leave(pShmNode->mutex);
  26257. return SQLITE_OK;
  26258. /* Jump here on any error */
  26259. shm_open_err:
  26260. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  26261. sqlite3_free(p);
  26262. unixLeaveMutex();
  26263. return rc;
  26264. }
  26265. /*
  26266. ** This function is called to obtain a pointer to region iRegion of the
  26267. ** shared-memory associated with the database file fd. Shared-memory regions
  26268. ** are numbered starting from zero. Each shared-memory region is szRegion
  26269. ** bytes in size.
  26270. **
  26271. ** If an error occurs, an error code is returned and *pp is set to NULL.
  26272. **
  26273. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  26274. ** region has not been allocated (by any client, including one running in a
  26275. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  26276. ** bExtend is non-zero and the requested shared-memory region has not yet
  26277. ** been allocated, it is allocated by this function.
  26278. **
  26279. ** If the shared-memory region has already been allocated or is allocated by
  26280. ** this call as described above, then it is mapped into this processes
  26281. ** address space (if it is not already), *pp is set to point to the mapped
  26282. ** memory and SQLITE_OK returned.
  26283. */
  26284. static int unixShmMap(
  26285. sqlite3_file *fd, /* Handle open on database file */
  26286. int iRegion, /* Region to retrieve */
  26287. int szRegion, /* Size of regions */
  26288. int bExtend, /* True to extend file if necessary */
  26289. void volatile **pp /* OUT: Mapped memory */
  26290. ){
  26291. unixFile *pDbFd = (unixFile*)fd;
  26292. unixShm *p;
  26293. unixShmNode *pShmNode;
  26294. int rc = SQLITE_OK;
  26295. /* If the shared-memory file has not yet been opened, open it now. */
  26296. if( pDbFd->pShm==0 ){
  26297. rc = unixOpenSharedMemory(pDbFd);
  26298. if( rc!=SQLITE_OK ) return rc;
  26299. }
  26300. p = pDbFd->pShm;
  26301. pShmNode = p->pShmNode;
  26302. sqlite3_mutex_enter(pShmNode->mutex);
  26303. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  26304. assert( pShmNode->pInode==pDbFd->pInode );
  26305. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26306. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26307. if( pShmNode->nRegion<=iRegion ){
  26308. char **apNew; /* New apRegion[] array */
  26309. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  26310. struct stat sStat; /* Used by fstat() */
  26311. pShmNode->szRegion = szRegion;
  26312. if( pShmNode->h>=0 ){
  26313. /* The requested region is not mapped into this processes address space.
  26314. ** Check to see if it has been allocated (i.e. if the wal-index file is
  26315. ** large enough to contain the requested region).
  26316. */
  26317. if( osFstat(pShmNode->h, &sStat) ){
  26318. rc = SQLITE_IOERR_SHMSIZE;
  26319. goto shmpage_out;
  26320. }
  26321. if( sStat.st_size<nByte ){
  26322. /* The requested memory region does not exist. If bExtend is set to
  26323. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  26324. */
  26325. if( !bExtend ){
  26326. goto shmpage_out;
  26327. }
  26328. /* Alternatively, if bExtend is true, extend the file. Do this by
  26329. ** writing a single byte to the end of each (OS) page being
  26330. ** allocated or extended. Technically, we need only write to the
  26331. ** last page in order to extend the file. But writing to all new
  26332. ** pages forces the OS to allocate them immediately, which reduces
  26333. ** the chances of SIGBUS while accessing the mapped region later on.
  26334. */
  26335. else{
  26336. static const int pgsz = 4096;
  26337. int iPg;
  26338. /* Write to the last byte of each newly allocated or extended page */
  26339. assert( (nByte % pgsz)==0 );
  26340. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  26341. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  26342. const char *zFile = pShmNode->zFilename;
  26343. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  26344. goto shmpage_out;
  26345. }
  26346. }
  26347. }
  26348. }
  26349. }
  26350. /* Map the requested memory region into this processes address space. */
  26351. apNew = (char **)sqlite3_realloc(
  26352. pShmNode->apRegion, (iRegion+1)*sizeof(char *)
  26353. );
  26354. if( !apNew ){
  26355. rc = SQLITE_IOERR_NOMEM;
  26356. goto shmpage_out;
  26357. }
  26358. pShmNode->apRegion = apNew;
  26359. while(pShmNode->nRegion<=iRegion){
  26360. void *pMem;
  26361. if( pShmNode->h>=0 ){
  26362. pMem = osMmap(0, szRegion,
  26363. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  26364. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  26365. );
  26366. if( pMem==MAP_FAILED ){
  26367. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  26368. goto shmpage_out;
  26369. }
  26370. }else{
  26371. pMem = sqlite3_malloc(szRegion);
  26372. if( pMem==0 ){
  26373. rc = SQLITE_NOMEM;
  26374. goto shmpage_out;
  26375. }
  26376. memset(pMem, 0, szRegion);
  26377. }
  26378. pShmNode->apRegion[pShmNode->nRegion] = pMem;
  26379. pShmNode->nRegion++;
  26380. }
  26381. }
  26382. shmpage_out:
  26383. if( pShmNode->nRegion>iRegion ){
  26384. *pp = pShmNode->apRegion[iRegion];
  26385. }else{
  26386. *pp = 0;
  26387. }
  26388. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  26389. sqlite3_mutex_leave(pShmNode->mutex);
  26390. return rc;
  26391. }
  26392. /*
  26393. ** Change the lock state for a shared-memory segment.
  26394. **
  26395. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  26396. ** different here than in posix. In xShmLock(), one can go from unlocked
  26397. ** to shared and back or from unlocked to exclusive and back. But one may
  26398. ** not go from shared to exclusive or from exclusive to shared.
  26399. */
  26400. static int unixShmLock(
  26401. sqlite3_file *fd, /* Database file holding the shared memory */
  26402. int ofst, /* First lock to acquire or release */
  26403. int n, /* Number of locks to acquire or release */
  26404. int flags /* What to do with the lock */
  26405. ){
  26406. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  26407. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  26408. unixShm *pX; /* For looping over all siblings */
  26409. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  26410. int rc = SQLITE_OK; /* Result code */
  26411. u16 mask; /* Mask of locks to take or release */
  26412. assert( pShmNode==pDbFd->pInode->pShmNode );
  26413. assert( pShmNode->pInode==pDbFd->pInode );
  26414. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  26415. assert( n>=1 );
  26416. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  26417. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  26418. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  26419. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  26420. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  26421. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  26422. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  26423. mask = (1<<(ofst+n)) - (1<<ofst);
  26424. assert( n>1 || mask==(1<<ofst) );
  26425. sqlite3_mutex_enter(pShmNode->mutex);
  26426. if( flags & SQLITE_SHM_UNLOCK ){
  26427. u16 allMask = 0; /* Mask of locks held by siblings */
  26428. /* See if any siblings hold this same lock */
  26429. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26430. if( pX==p ) continue;
  26431. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  26432. allMask |= pX->sharedMask;
  26433. }
  26434. /* Unlock the system-level locks */
  26435. if( (mask & allMask)==0 ){
  26436. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  26437. }else{
  26438. rc = SQLITE_OK;
  26439. }
  26440. /* Undo the local locks */
  26441. if( rc==SQLITE_OK ){
  26442. p->exclMask &= ~mask;
  26443. p->sharedMask &= ~mask;
  26444. }
  26445. }else if( flags & SQLITE_SHM_SHARED ){
  26446. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  26447. /* Find out which shared locks are already held by sibling connections.
  26448. ** If any sibling already holds an exclusive lock, go ahead and return
  26449. ** SQLITE_BUSY.
  26450. */
  26451. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26452. if( (pX->exclMask & mask)!=0 ){
  26453. rc = SQLITE_BUSY;
  26454. break;
  26455. }
  26456. allShared |= pX->sharedMask;
  26457. }
  26458. /* Get shared locks at the system level, if necessary */
  26459. if( rc==SQLITE_OK ){
  26460. if( (allShared & mask)==0 ){
  26461. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  26462. }else{
  26463. rc = SQLITE_OK;
  26464. }
  26465. }
  26466. /* Get the local shared locks */
  26467. if( rc==SQLITE_OK ){
  26468. p->sharedMask |= mask;
  26469. }
  26470. }else{
  26471. /* Make sure no sibling connections hold locks that will block this
  26472. ** lock. If any do, return SQLITE_BUSY right away.
  26473. */
  26474. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  26475. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  26476. rc = SQLITE_BUSY;
  26477. break;
  26478. }
  26479. }
  26480. /* Get the exclusive locks at the system level. Then if successful
  26481. ** also mark the local connection as being locked.
  26482. */
  26483. if( rc==SQLITE_OK ){
  26484. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  26485. if( rc==SQLITE_OK ){
  26486. assert( (p->sharedMask & mask)==0 );
  26487. p->exclMask |= mask;
  26488. }
  26489. }
  26490. }
  26491. sqlite3_mutex_leave(pShmNode->mutex);
  26492. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  26493. p->id, getpid(), p->sharedMask, p->exclMask));
  26494. return rc;
  26495. }
  26496. /*
  26497. ** Implement a memory barrier or memory fence on shared memory.
  26498. **
  26499. ** All loads and stores begun before the barrier must complete before
  26500. ** any load or store begun after the barrier.
  26501. */
  26502. static void unixShmBarrier(
  26503. sqlite3_file *fd /* Database file holding the shared memory */
  26504. ){
  26505. UNUSED_PARAMETER(fd);
  26506. unixEnterMutex();
  26507. unixLeaveMutex();
  26508. }
  26509. /*
  26510. ** Close a connection to shared-memory. Delete the underlying
  26511. ** storage if deleteFlag is true.
  26512. **
  26513. ** If there is no shared memory associated with the connection then this
  26514. ** routine is a harmless no-op.
  26515. */
  26516. static int unixShmUnmap(
  26517. sqlite3_file *fd, /* The underlying database file */
  26518. int deleteFlag /* Delete shared-memory if true */
  26519. ){
  26520. unixShm *p; /* The connection to be closed */
  26521. unixShmNode *pShmNode; /* The underlying shared-memory file */
  26522. unixShm **pp; /* For looping over sibling connections */
  26523. unixFile *pDbFd; /* The underlying database file */
  26524. pDbFd = (unixFile*)fd;
  26525. p = pDbFd->pShm;
  26526. if( p==0 ) return SQLITE_OK;
  26527. pShmNode = p->pShmNode;
  26528. assert( pShmNode==pDbFd->pInode->pShmNode );
  26529. assert( pShmNode->pInode==pDbFd->pInode );
  26530. /* Remove connection p from the set of connections associated
  26531. ** with pShmNode */
  26532. sqlite3_mutex_enter(pShmNode->mutex);
  26533. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  26534. *pp = p->pNext;
  26535. /* Free the connection p */
  26536. sqlite3_free(p);
  26537. pDbFd->pShm = 0;
  26538. sqlite3_mutex_leave(pShmNode->mutex);
  26539. /* If pShmNode->nRef has reached 0, then close the underlying
  26540. ** shared-memory file, too */
  26541. unixEnterMutex();
  26542. assert( pShmNode->nRef>0 );
  26543. pShmNode->nRef--;
  26544. if( pShmNode->nRef==0 ){
  26545. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  26546. unixShmPurge(pDbFd);
  26547. }
  26548. unixLeaveMutex();
  26549. return SQLITE_OK;
  26550. }
  26551. #else
  26552. # define unixShmMap 0
  26553. # define unixShmLock 0
  26554. # define unixShmBarrier 0
  26555. # define unixShmUnmap 0
  26556. #endif /* #ifndef SQLITE_OMIT_WAL */
  26557. #if SQLITE_MAX_MMAP_SIZE>0
  26558. /*
  26559. ** If it is currently memory mapped, unmap file pFd.
  26560. */
  26561. static void unixUnmapfile(unixFile *pFd){
  26562. assert( pFd->nFetchOut==0 );
  26563. if( pFd->pMapRegion ){
  26564. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  26565. pFd->pMapRegion = 0;
  26566. pFd->mmapSize = 0;
  26567. pFd->mmapSizeActual = 0;
  26568. }
  26569. }
  26570. /*
  26571. ** Return the system page size.
  26572. */
  26573. static int unixGetPagesize(void){
  26574. #if HAVE_MREMAP
  26575. return 512;
  26576. #elif defined(_BSD_SOURCE)
  26577. return getpagesize();
  26578. #else
  26579. return (int)sysconf(_SC_PAGESIZE);
  26580. #endif
  26581. }
  26582. /*
  26583. ** Attempt to set the size of the memory mapping maintained by file
  26584. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  26585. **
  26586. ** If successful, this function sets the following variables:
  26587. **
  26588. ** unixFile.pMapRegion
  26589. ** unixFile.mmapSize
  26590. ** unixFile.mmapSizeActual
  26591. **
  26592. ** If unsuccessful, an error message is logged via sqlite3_log() and
  26593. ** the three variables above are zeroed. In this case SQLite should
  26594. ** continue accessing the database using the xRead() and xWrite()
  26595. ** methods.
  26596. */
  26597. static void unixRemapfile(
  26598. unixFile *pFd, /* File descriptor object */
  26599. i64 nNew /* Required mapping size */
  26600. ){
  26601. const char *zErr = "mmap";
  26602. int h = pFd->h; /* File descriptor open on db file */
  26603. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  26604. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  26605. u8 *pNew = 0; /* Location of new mapping */
  26606. int flags = PROT_READ; /* Flags to pass to mmap() */
  26607. assert( pFd->nFetchOut==0 );
  26608. assert( nNew>pFd->mmapSize );
  26609. assert( nNew<=pFd->mmapSizeMax );
  26610. assert( nNew>0 );
  26611. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  26612. assert( MAP_FAILED!=0 );
  26613. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  26614. if( pOrig ){
  26615. const int szSyspage = unixGetPagesize();
  26616. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  26617. u8 *pReq = &pOrig[nReuse];
  26618. /* Unmap any pages of the existing mapping that cannot be reused. */
  26619. if( nReuse!=nOrig ){
  26620. osMunmap(pReq, nOrig-nReuse);
  26621. }
  26622. #if HAVE_MREMAP
  26623. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  26624. zErr = "mremap";
  26625. #else
  26626. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  26627. if( pNew!=MAP_FAILED ){
  26628. if( pNew!=pReq ){
  26629. osMunmap(pNew, nNew - nReuse);
  26630. pNew = 0;
  26631. }else{
  26632. pNew = pOrig;
  26633. }
  26634. }
  26635. #endif
  26636. /* The attempt to extend the existing mapping failed. Free it. */
  26637. if( pNew==MAP_FAILED || pNew==0 ){
  26638. osMunmap(pOrig, nReuse);
  26639. }
  26640. }
  26641. /* If pNew is still NULL, try to create an entirely new mapping. */
  26642. if( pNew==0 ){
  26643. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  26644. }
  26645. if( pNew==MAP_FAILED ){
  26646. pNew = 0;
  26647. nNew = 0;
  26648. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  26649. /* If the mmap() above failed, assume that all subsequent mmap() calls
  26650. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  26651. ** in this case. */
  26652. pFd->mmapSizeMax = 0;
  26653. }
  26654. pFd->pMapRegion = (void *)pNew;
  26655. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  26656. }
  26657. /*
  26658. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  26659. ** is already mapped, the existing mapping is replaced by the new). Or, if
  26660. ** there already exists a mapping for this file, and there are still
  26661. ** outstanding xFetch() references to it, this function is a no-op.
  26662. **
  26663. ** If parameter nByte is non-negative, then it is the requested size of
  26664. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  26665. ** requested size is the size of the file on disk. The actual size of the
  26666. ** created mapping is either the requested size or the value configured
  26667. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  26668. **
  26669. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  26670. ** recreated as a result of outstanding references) or an SQLite error
  26671. ** code otherwise.
  26672. */
  26673. static int unixMapfile(unixFile *pFd, i64 nByte){
  26674. i64 nMap = nByte;
  26675. int rc;
  26676. assert( nMap>=0 || pFd->nFetchOut==0 );
  26677. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  26678. if( nMap<0 ){
  26679. struct stat statbuf; /* Low-level file information */
  26680. rc = osFstat(pFd->h, &statbuf);
  26681. if( rc!=SQLITE_OK ){
  26682. return SQLITE_IOERR_FSTAT;
  26683. }
  26684. nMap = statbuf.st_size;
  26685. }
  26686. if( nMap>pFd->mmapSizeMax ){
  26687. nMap = pFd->mmapSizeMax;
  26688. }
  26689. if( nMap!=pFd->mmapSize ){
  26690. if( nMap>0 ){
  26691. unixRemapfile(pFd, nMap);
  26692. }else{
  26693. unixUnmapfile(pFd);
  26694. }
  26695. }
  26696. return SQLITE_OK;
  26697. }
  26698. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  26699. /*
  26700. ** If possible, return a pointer to a mapping of file fd starting at offset
  26701. ** iOff. The mapping must be valid for at least nAmt bytes.
  26702. **
  26703. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  26704. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  26705. ** Finally, if an error does occur, return an SQLite error code. The final
  26706. ** value of *pp is undefined in this case.
  26707. **
  26708. ** If this function does return a pointer, the caller must eventually
  26709. ** release the reference by calling unixUnfetch().
  26710. */
  26711. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  26712. #if SQLITE_MAX_MMAP_SIZE>0
  26713. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26714. #endif
  26715. *pp = 0;
  26716. #if SQLITE_MAX_MMAP_SIZE>0
  26717. if( pFd->mmapSizeMax>0 ){
  26718. if( pFd->pMapRegion==0 ){
  26719. int rc = unixMapfile(pFd, -1);
  26720. if( rc!=SQLITE_OK ) return rc;
  26721. }
  26722. if( pFd->mmapSize >= iOff+nAmt ){
  26723. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  26724. pFd->nFetchOut++;
  26725. }
  26726. }
  26727. #endif
  26728. return SQLITE_OK;
  26729. }
  26730. /*
  26731. ** If the third argument is non-NULL, then this function releases a
  26732. ** reference obtained by an earlier call to unixFetch(). The second
  26733. ** argument passed to this function must be the same as the corresponding
  26734. ** argument that was passed to the unixFetch() invocation.
  26735. **
  26736. ** Or, if the third argument is NULL, then this function is being called
  26737. ** to inform the VFS layer that, according to POSIX, any existing mapping
  26738. ** may now be invalid and should be unmapped.
  26739. */
  26740. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  26741. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  26742. UNUSED_PARAMETER(iOff);
  26743. #if SQLITE_MAX_MMAP_SIZE>0
  26744. /* If p==0 (unmap the entire file) then there must be no outstanding
  26745. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  26746. ** then there must be at least one outstanding. */
  26747. assert( (p==0)==(pFd->nFetchOut==0) );
  26748. /* If p!=0, it must match the iOff value. */
  26749. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  26750. if( p ){
  26751. pFd->nFetchOut--;
  26752. }else{
  26753. unixUnmapfile(pFd);
  26754. }
  26755. assert( pFd->nFetchOut>=0 );
  26756. #endif
  26757. return SQLITE_OK;
  26758. }
  26759. /*
  26760. ** Here ends the implementation of all sqlite3_file methods.
  26761. **
  26762. ********************** End sqlite3_file Methods *******************************
  26763. ******************************************************************************/
  26764. /*
  26765. ** This division contains definitions of sqlite3_io_methods objects that
  26766. ** implement various file locking strategies. It also contains definitions
  26767. ** of "finder" functions. A finder-function is used to locate the appropriate
  26768. ** sqlite3_io_methods object for a particular database file. The pAppData
  26769. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  26770. ** the correct finder-function for that VFS.
  26771. **
  26772. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  26773. ** object. The only interesting finder-function is autolockIoFinder, which
  26774. ** looks at the filesystem type and tries to guess the best locking
  26775. ** strategy from that.
  26776. **
  26777. ** For finder-funtion F, two objects are created:
  26778. **
  26779. ** (1) The real finder-function named "FImpt()".
  26780. **
  26781. ** (2) A constant pointer to this function named just "F".
  26782. **
  26783. **
  26784. ** A pointer to the F pointer is used as the pAppData value for VFS
  26785. ** objects. We have to do this instead of letting pAppData point
  26786. ** directly at the finder-function since C90 rules prevent a void*
  26787. ** from be cast into a function pointer.
  26788. **
  26789. **
  26790. ** Each instance of this macro generates two objects:
  26791. **
  26792. ** * A constant sqlite3_io_methods object call METHOD that has locking
  26793. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  26794. **
  26795. ** * An I/O method finder function called FINDER that returns a pointer
  26796. ** to the METHOD object in the previous bullet.
  26797. */
  26798. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  26799. static const sqlite3_io_methods METHOD = { \
  26800. VERSION, /* iVersion */ \
  26801. CLOSE, /* xClose */ \
  26802. unixRead, /* xRead */ \
  26803. unixWrite, /* xWrite */ \
  26804. unixTruncate, /* xTruncate */ \
  26805. unixSync, /* xSync */ \
  26806. unixFileSize, /* xFileSize */ \
  26807. LOCK, /* xLock */ \
  26808. UNLOCK, /* xUnlock */ \
  26809. CKLOCK, /* xCheckReservedLock */ \
  26810. unixFileControl, /* xFileControl */ \
  26811. unixSectorSize, /* xSectorSize */ \
  26812. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  26813. unixShmMap, /* xShmMap */ \
  26814. unixShmLock, /* xShmLock */ \
  26815. unixShmBarrier, /* xShmBarrier */ \
  26816. unixShmUnmap, /* xShmUnmap */ \
  26817. unixFetch, /* xFetch */ \
  26818. unixUnfetch, /* xUnfetch */ \
  26819. }; \
  26820. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  26821. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  26822. return &METHOD; \
  26823. } \
  26824. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  26825. = FINDER##Impl;
  26826. /*
  26827. ** Here are all of the sqlite3_io_methods objects for each of the
  26828. ** locking strategies. Functions that return pointers to these methods
  26829. ** are also created.
  26830. */
  26831. IOMETHODS(
  26832. posixIoFinder, /* Finder function name */
  26833. posixIoMethods, /* sqlite3_io_methods object name */
  26834. 3, /* shared memory and mmap are enabled */
  26835. unixClose, /* xClose method */
  26836. unixLock, /* xLock method */
  26837. unixUnlock, /* xUnlock method */
  26838. unixCheckReservedLock /* xCheckReservedLock method */
  26839. )
  26840. IOMETHODS(
  26841. nolockIoFinder, /* Finder function name */
  26842. nolockIoMethods, /* sqlite3_io_methods object name */
  26843. 1, /* shared memory is disabled */
  26844. nolockClose, /* xClose method */
  26845. nolockLock, /* xLock method */
  26846. nolockUnlock, /* xUnlock method */
  26847. nolockCheckReservedLock /* xCheckReservedLock method */
  26848. )
  26849. IOMETHODS(
  26850. dotlockIoFinder, /* Finder function name */
  26851. dotlockIoMethods, /* sqlite3_io_methods object name */
  26852. 1, /* shared memory is disabled */
  26853. dotlockClose, /* xClose method */
  26854. dotlockLock, /* xLock method */
  26855. dotlockUnlock, /* xUnlock method */
  26856. dotlockCheckReservedLock /* xCheckReservedLock method */
  26857. )
  26858. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  26859. IOMETHODS(
  26860. flockIoFinder, /* Finder function name */
  26861. flockIoMethods, /* sqlite3_io_methods object name */
  26862. 1, /* shared memory is disabled */
  26863. flockClose, /* xClose method */
  26864. flockLock, /* xLock method */
  26865. flockUnlock, /* xUnlock method */
  26866. flockCheckReservedLock /* xCheckReservedLock method */
  26867. )
  26868. #endif
  26869. #if OS_VXWORKS
  26870. IOMETHODS(
  26871. semIoFinder, /* Finder function name */
  26872. semIoMethods, /* sqlite3_io_methods object name */
  26873. 1, /* shared memory is disabled */
  26874. semClose, /* xClose method */
  26875. semLock, /* xLock method */
  26876. semUnlock, /* xUnlock method */
  26877. semCheckReservedLock /* xCheckReservedLock method */
  26878. )
  26879. #endif
  26880. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26881. IOMETHODS(
  26882. afpIoFinder, /* Finder function name */
  26883. afpIoMethods, /* sqlite3_io_methods object name */
  26884. 1, /* shared memory is disabled */
  26885. afpClose, /* xClose method */
  26886. afpLock, /* xLock method */
  26887. afpUnlock, /* xUnlock method */
  26888. afpCheckReservedLock /* xCheckReservedLock method */
  26889. )
  26890. #endif
  26891. /*
  26892. ** The proxy locking method is a "super-method" in the sense that it
  26893. ** opens secondary file descriptors for the conch and lock files and
  26894. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  26895. ** secondary files. For this reason, the division that implements
  26896. ** proxy locking is located much further down in the file. But we need
  26897. ** to go ahead and define the sqlite3_io_methods and finder function
  26898. ** for proxy locking here. So we forward declare the I/O methods.
  26899. */
  26900. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26901. static int proxyClose(sqlite3_file*);
  26902. static int proxyLock(sqlite3_file*, int);
  26903. static int proxyUnlock(sqlite3_file*, int);
  26904. static int proxyCheckReservedLock(sqlite3_file*, int*);
  26905. IOMETHODS(
  26906. proxyIoFinder, /* Finder function name */
  26907. proxyIoMethods, /* sqlite3_io_methods object name */
  26908. 1, /* shared memory is disabled */
  26909. proxyClose, /* xClose method */
  26910. proxyLock, /* xLock method */
  26911. proxyUnlock, /* xUnlock method */
  26912. proxyCheckReservedLock /* xCheckReservedLock method */
  26913. )
  26914. #endif
  26915. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  26916. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26917. IOMETHODS(
  26918. nfsIoFinder, /* Finder function name */
  26919. nfsIoMethods, /* sqlite3_io_methods object name */
  26920. 1, /* shared memory is disabled */
  26921. unixClose, /* xClose method */
  26922. unixLock, /* xLock method */
  26923. nfsUnlock, /* xUnlock method */
  26924. unixCheckReservedLock /* xCheckReservedLock method */
  26925. )
  26926. #endif
  26927. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26928. /*
  26929. ** This "finder" function attempts to determine the best locking strategy
  26930. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26931. ** object that implements that strategy.
  26932. **
  26933. ** This is for MacOSX only.
  26934. */
  26935. static const sqlite3_io_methods *autolockIoFinderImpl(
  26936. const char *filePath, /* name of the database file */
  26937. unixFile *pNew /* open file object for the database file */
  26938. ){
  26939. static const struct Mapping {
  26940. const char *zFilesystem; /* Filesystem type name */
  26941. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  26942. } aMap[] = {
  26943. { "hfs", &posixIoMethods },
  26944. { "ufs", &posixIoMethods },
  26945. { "afpfs", &afpIoMethods },
  26946. { "smbfs", &afpIoMethods },
  26947. { "webdav", &nolockIoMethods },
  26948. { 0, 0 }
  26949. };
  26950. int i;
  26951. struct statfs fsInfo;
  26952. struct flock lockInfo;
  26953. if( !filePath ){
  26954. /* If filePath==NULL that means we are dealing with a transient file
  26955. ** that does not need to be locked. */
  26956. return &nolockIoMethods;
  26957. }
  26958. if( statfs(filePath, &fsInfo) != -1 ){
  26959. if( fsInfo.f_flags & MNT_RDONLY ){
  26960. return &nolockIoMethods;
  26961. }
  26962. for(i=0; aMap[i].zFilesystem; i++){
  26963. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  26964. return aMap[i].pMethods;
  26965. }
  26966. }
  26967. }
  26968. /* Default case. Handles, amongst others, "nfs".
  26969. ** Test byte-range lock using fcntl(). If the call succeeds,
  26970. ** assume that the file-system supports POSIX style locks.
  26971. */
  26972. lockInfo.l_len = 1;
  26973. lockInfo.l_start = 0;
  26974. lockInfo.l_whence = SEEK_SET;
  26975. lockInfo.l_type = F_RDLCK;
  26976. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  26977. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  26978. return &nfsIoMethods;
  26979. } else {
  26980. return &posixIoMethods;
  26981. }
  26982. }else{
  26983. return &dotlockIoMethods;
  26984. }
  26985. }
  26986. static const sqlite3_io_methods
  26987. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  26988. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26989. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  26990. /*
  26991. ** This "finder" function attempts to determine the best locking strategy
  26992. ** for the database file "filePath". It then returns the sqlite3_io_methods
  26993. ** object that implements that strategy.
  26994. **
  26995. ** This is for VXWorks only.
  26996. */
  26997. static const sqlite3_io_methods *autolockIoFinderImpl(
  26998. const char *filePath, /* name of the database file */
  26999. unixFile *pNew /* the open file object */
  27000. ){
  27001. struct flock lockInfo;
  27002. if( !filePath ){
  27003. /* If filePath==NULL that means we are dealing with a transient file
  27004. ** that does not need to be locked. */
  27005. return &nolockIoMethods;
  27006. }
  27007. /* Test if fcntl() is supported and use POSIX style locks.
  27008. ** Otherwise fall back to the named semaphore method.
  27009. */
  27010. lockInfo.l_len = 1;
  27011. lockInfo.l_start = 0;
  27012. lockInfo.l_whence = SEEK_SET;
  27013. lockInfo.l_type = F_RDLCK;
  27014. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  27015. return &posixIoMethods;
  27016. }else{
  27017. return &semIoMethods;
  27018. }
  27019. }
  27020. static const sqlite3_io_methods
  27021. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  27022. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  27023. /*
  27024. ** An abstract type for a pointer to a IO method finder function:
  27025. */
  27026. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  27027. /****************************************************************************
  27028. **************************** sqlite3_vfs methods ****************************
  27029. **
  27030. ** This division contains the implementation of methods on the
  27031. ** sqlite3_vfs object.
  27032. */
  27033. /*
  27034. ** Initialize the contents of the unixFile structure pointed to by pId.
  27035. */
  27036. static int fillInUnixFile(
  27037. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27038. int h, /* Open file descriptor of file being opened */
  27039. sqlite3_file *pId, /* Write to the unixFile structure here */
  27040. const char *zFilename, /* Name of the file being opened */
  27041. int ctrlFlags /* Zero or more UNIXFILE_* values */
  27042. ){
  27043. const sqlite3_io_methods *pLockingStyle;
  27044. unixFile *pNew = (unixFile *)pId;
  27045. int rc = SQLITE_OK;
  27046. assert( pNew->pInode==NULL );
  27047. /* Usually the path zFilename should not be a relative pathname. The
  27048. ** exception is when opening the proxy "conch" file in builds that
  27049. ** include the special Apple locking styles.
  27050. */
  27051. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27052. assert( zFilename==0 || zFilename[0]=='/'
  27053. || pVfs->pAppData==(void*)&autolockIoFinder );
  27054. #else
  27055. assert( zFilename==0 || zFilename[0]=='/' );
  27056. #endif
  27057. /* No locking occurs in temporary files */
  27058. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  27059. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  27060. pNew->h = h;
  27061. pNew->pVfs = pVfs;
  27062. pNew->zPath = zFilename;
  27063. pNew->ctrlFlags = (u8)ctrlFlags;
  27064. #if SQLITE_MAX_MMAP_SIZE>0
  27065. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  27066. #endif
  27067. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  27068. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  27069. pNew->ctrlFlags |= UNIXFILE_PSOW;
  27070. }
  27071. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  27072. pNew->ctrlFlags |= UNIXFILE_EXCL;
  27073. }
  27074. #if OS_VXWORKS
  27075. pNew->pId = vxworksFindFileId(zFilename);
  27076. if( pNew->pId==0 ){
  27077. ctrlFlags |= UNIXFILE_NOLOCK;
  27078. rc = SQLITE_NOMEM;
  27079. }
  27080. #endif
  27081. if( ctrlFlags & UNIXFILE_NOLOCK ){
  27082. pLockingStyle = &nolockIoMethods;
  27083. }else{
  27084. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  27085. #if SQLITE_ENABLE_LOCKING_STYLE
  27086. /* Cache zFilename in the locking context (AFP and dotlock override) for
  27087. ** proxyLock activation is possible (remote proxy is based on db name)
  27088. ** zFilename remains valid until file is closed, to support */
  27089. pNew->lockingContext = (void*)zFilename;
  27090. #endif
  27091. }
  27092. if( pLockingStyle == &posixIoMethods
  27093. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  27094. || pLockingStyle == &nfsIoMethods
  27095. #endif
  27096. ){
  27097. unixEnterMutex();
  27098. rc = findInodeInfo(pNew, &pNew->pInode);
  27099. if( rc!=SQLITE_OK ){
  27100. /* If an error occurred in findInodeInfo(), close the file descriptor
  27101. ** immediately, before releasing the mutex. findInodeInfo() may fail
  27102. ** in two scenarios:
  27103. **
  27104. ** (a) A call to fstat() failed.
  27105. ** (b) A malloc failed.
  27106. **
  27107. ** Scenario (b) may only occur if the process is holding no other
  27108. ** file descriptors open on the same file. If there were other file
  27109. ** descriptors on this file, then no malloc would be required by
  27110. ** findInodeInfo(). If this is the case, it is quite safe to close
  27111. ** handle h - as it is guaranteed that no posix locks will be released
  27112. ** by doing so.
  27113. **
  27114. ** If scenario (a) caused the error then things are not so safe. The
  27115. ** implicit assumption here is that if fstat() fails, things are in
  27116. ** such bad shape that dropping a lock or two doesn't matter much.
  27117. */
  27118. robust_close(pNew, h, __LINE__);
  27119. h = -1;
  27120. }
  27121. unixLeaveMutex();
  27122. }
  27123. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27124. else if( pLockingStyle == &afpIoMethods ){
  27125. /* AFP locking uses the file path so it needs to be included in
  27126. ** the afpLockingContext.
  27127. */
  27128. afpLockingContext *pCtx;
  27129. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  27130. if( pCtx==0 ){
  27131. rc = SQLITE_NOMEM;
  27132. }else{
  27133. /* NB: zFilename exists and remains valid until the file is closed
  27134. ** according to requirement F11141. So we do not need to make a
  27135. ** copy of the filename. */
  27136. pCtx->dbPath = zFilename;
  27137. pCtx->reserved = 0;
  27138. srandomdev();
  27139. unixEnterMutex();
  27140. rc = findInodeInfo(pNew, &pNew->pInode);
  27141. if( rc!=SQLITE_OK ){
  27142. sqlite3_free(pNew->lockingContext);
  27143. robust_close(pNew, h, __LINE__);
  27144. h = -1;
  27145. }
  27146. unixLeaveMutex();
  27147. }
  27148. }
  27149. #endif
  27150. else if( pLockingStyle == &dotlockIoMethods ){
  27151. /* Dotfile locking uses the file path so it needs to be included in
  27152. ** the dotlockLockingContext
  27153. */
  27154. char *zLockFile;
  27155. int nFilename;
  27156. assert( zFilename!=0 );
  27157. nFilename = (int)strlen(zFilename) + 6;
  27158. zLockFile = (char *)sqlite3_malloc(nFilename);
  27159. if( zLockFile==0 ){
  27160. rc = SQLITE_NOMEM;
  27161. }else{
  27162. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  27163. }
  27164. pNew->lockingContext = zLockFile;
  27165. }
  27166. #if OS_VXWORKS
  27167. else if( pLockingStyle == &semIoMethods ){
  27168. /* Named semaphore locking uses the file path so it needs to be
  27169. ** included in the semLockingContext
  27170. */
  27171. unixEnterMutex();
  27172. rc = findInodeInfo(pNew, &pNew->pInode);
  27173. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  27174. char *zSemName = pNew->pInode->aSemName;
  27175. int n;
  27176. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  27177. pNew->pId->zCanonicalName);
  27178. for( n=1; zSemName[n]; n++ )
  27179. if( zSemName[n]=='/' ) zSemName[n] = '_';
  27180. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  27181. if( pNew->pInode->pSem == SEM_FAILED ){
  27182. rc = SQLITE_NOMEM;
  27183. pNew->pInode->aSemName[0] = '\0';
  27184. }
  27185. }
  27186. unixLeaveMutex();
  27187. }
  27188. #endif
  27189. pNew->lastErrno = 0;
  27190. #if OS_VXWORKS
  27191. if( rc!=SQLITE_OK ){
  27192. if( h>=0 ) robust_close(pNew, h, __LINE__);
  27193. h = -1;
  27194. osUnlink(zFilename);
  27195. pNew->ctrlFlags |= UNIXFILE_DELETE;
  27196. }
  27197. #endif
  27198. if( rc!=SQLITE_OK ){
  27199. if( h>=0 ) robust_close(pNew, h, __LINE__);
  27200. }else{
  27201. pNew->pMethod = pLockingStyle;
  27202. OpenCounter(+1);
  27203. verifyDbFile(pNew);
  27204. }
  27205. return rc;
  27206. }
  27207. /*
  27208. ** Return the name of a directory in which to put temporary files.
  27209. ** If no suitable temporary file directory can be found, return NULL.
  27210. */
  27211. static const char *unixTempFileDir(void){
  27212. static const char *azDirs[] = {
  27213. 0,
  27214. 0,
  27215. 0,
  27216. "/var/tmp",
  27217. "/usr/tmp",
  27218. "/tmp",
  27219. 0 /* List terminator */
  27220. };
  27221. unsigned int i;
  27222. struct stat buf;
  27223. const char *zDir = 0;
  27224. azDirs[0] = sqlite3_temp_directory;
  27225. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  27226. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  27227. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  27228. if( zDir==0 ) continue;
  27229. if( osStat(zDir, &buf) ) continue;
  27230. if( !S_ISDIR(buf.st_mode) ) continue;
  27231. if( osAccess(zDir, 07) ) continue;
  27232. break;
  27233. }
  27234. return zDir;
  27235. }
  27236. /*
  27237. ** Create a temporary file name in zBuf. zBuf must be allocated
  27238. ** by the calling process and must be big enough to hold at least
  27239. ** pVfs->mxPathname bytes.
  27240. */
  27241. static int unixGetTempname(int nBuf, char *zBuf){
  27242. static const unsigned char zChars[] =
  27243. "abcdefghijklmnopqrstuvwxyz"
  27244. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  27245. "0123456789";
  27246. unsigned int i, j;
  27247. const char *zDir;
  27248. /* It's odd to simulate an io-error here, but really this is just
  27249. ** using the io-error infrastructure to test that SQLite handles this
  27250. ** function failing.
  27251. */
  27252. SimulateIOError( return SQLITE_IOERR );
  27253. zDir = unixTempFileDir();
  27254. if( zDir==0 ) zDir = ".";
  27255. /* Check that the output buffer is large enough for the temporary file
  27256. ** name. If it is not, return SQLITE_ERROR.
  27257. */
  27258. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  27259. return SQLITE_ERROR;
  27260. }
  27261. do{
  27262. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  27263. j = (int)strlen(zBuf);
  27264. sqlite3_randomness(15, &zBuf[j]);
  27265. for(i=0; i<15; i++, j++){
  27266. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  27267. }
  27268. zBuf[j] = 0;
  27269. zBuf[j+1] = 0;
  27270. }while( osAccess(zBuf,0)==0 );
  27271. return SQLITE_OK;
  27272. }
  27273. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27274. /*
  27275. ** Routine to transform a unixFile into a proxy-locking unixFile.
  27276. ** Implementation in the proxy-lock division, but used by unixOpen()
  27277. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  27278. */
  27279. static int proxyTransformUnixFile(unixFile*, const char*);
  27280. #endif
  27281. /*
  27282. ** Search for an unused file descriptor that was opened on the database
  27283. ** file (not a journal or master-journal file) identified by pathname
  27284. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  27285. ** argument to this function.
  27286. **
  27287. ** Such a file descriptor may exist if a database connection was closed
  27288. ** but the associated file descriptor could not be closed because some
  27289. ** other file descriptor open on the same file is holding a file-lock.
  27290. ** Refer to comments in the unixClose() function and the lengthy comment
  27291. ** describing "Posix Advisory Locking" at the start of this file for
  27292. ** further details. Also, ticket #4018.
  27293. **
  27294. ** If a suitable file descriptor is found, then it is returned. If no
  27295. ** such file descriptor is located, -1 is returned.
  27296. */
  27297. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  27298. UnixUnusedFd *pUnused = 0;
  27299. /* Do not search for an unused file descriptor on vxworks. Not because
  27300. ** vxworks would not benefit from the change (it might, we're not sure),
  27301. ** but because no way to test it is currently available. It is better
  27302. ** not to risk breaking vxworks support for the sake of such an obscure
  27303. ** feature. */
  27304. #if !OS_VXWORKS
  27305. struct stat sStat; /* Results of stat() call */
  27306. /* A stat() call may fail for various reasons. If this happens, it is
  27307. ** almost certain that an open() call on the same path will also fail.
  27308. ** For this reason, if an error occurs in the stat() call here, it is
  27309. ** ignored and -1 is returned. The caller will try to open a new file
  27310. ** descriptor on the same path, fail, and return an error to SQLite.
  27311. **
  27312. ** Even if a subsequent open() call does succeed, the consequences of
  27313. ** not searching for a resusable file descriptor are not dire. */
  27314. if( 0==osStat(zPath, &sStat) ){
  27315. unixInodeInfo *pInode;
  27316. unixEnterMutex();
  27317. pInode = inodeList;
  27318. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  27319. || pInode->fileId.ino!=sStat.st_ino) ){
  27320. pInode = pInode->pNext;
  27321. }
  27322. if( pInode ){
  27323. UnixUnusedFd **pp;
  27324. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  27325. pUnused = *pp;
  27326. if( pUnused ){
  27327. *pp = pUnused->pNext;
  27328. }
  27329. }
  27330. unixLeaveMutex();
  27331. }
  27332. #endif /* if !OS_VXWORKS */
  27333. return pUnused;
  27334. }
  27335. /*
  27336. ** This function is called by unixOpen() to determine the unix permissions
  27337. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  27338. ** and a value suitable for passing as the third argument to open(2) is
  27339. ** written to *pMode. If an IO error occurs, an SQLite error code is
  27340. ** returned and the value of *pMode is not modified.
  27341. **
  27342. ** In most cases cases, this routine sets *pMode to 0, which will become
  27343. ** an indication to robust_open() to create the file using
  27344. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  27345. ** But if the file being opened is a WAL or regular journal file, then
  27346. ** this function queries the file-system for the permissions on the
  27347. ** corresponding database file and sets *pMode to this value. Whenever
  27348. ** possible, WAL and journal files are created using the same permissions
  27349. ** as the associated database file.
  27350. **
  27351. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  27352. ** original filename is unavailable. But 8_3_NAMES is only used for
  27353. ** FAT filesystems and permissions do not matter there, so just use
  27354. ** the default permissions.
  27355. */
  27356. static int findCreateFileMode(
  27357. const char *zPath, /* Path of file (possibly) being created */
  27358. int flags, /* Flags passed as 4th argument to xOpen() */
  27359. mode_t *pMode, /* OUT: Permissions to open file with */
  27360. uid_t *pUid, /* OUT: uid to set on the file */
  27361. gid_t *pGid /* OUT: gid to set on the file */
  27362. ){
  27363. int rc = SQLITE_OK; /* Return Code */
  27364. *pMode = 0;
  27365. *pUid = 0;
  27366. *pGid = 0;
  27367. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27368. char zDb[MAX_PATHNAME+1]; /* Database file path */
  27369. int nDb; /* Number of valid bytes in zDb */
  27370. struct stat sStat; /* Output of stat() on database file */
  27371. /* zPath is a path to a WAL or journal file. The following block derives
  27372. ** the path to the associated database file from zPath. This block handles
  27373. ** the following naming conventions:
  27374. **
  27375. ** "<path to db>-journal"
  27376. ** "<path to db>-wal"
  27377. ** "<path to db>-journalNN"
  27378. ** "<path to db>-walNN"
  27379. **
  27380. ** where NN is a decimal number. The NN naming schemes are
  27381. ** used by the test_multiplex.c module.
  27382. */
  27383. nDb = sqlite3Strlen30(zPath) - 1;
  27384. #ifdef SQLITE_ENABLE_8_3_NAMES
  27385. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  27386. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  27387. #else
  27388. while( zPath[nDb]!='-' ){
  27389. assert( nDb>0 );
  27390. assert( zPath[nDb]!='\n' );
  27391. nDb--;
  27392. }
  27393. #endif
  27394. memcpy(zDb, zPath, nDb);
  27395. zDb[nDb] = '\0';
  27396. if( 0==osStat(zDb, &sStat) ){
  27397. *pMode = sStat.st_mode & 0777;
  27398. *pUid = sStat.st_uid;
  27399. *pGid = sStat.st_gid;
  27400. }else{
  27401. rc = SQLITE_IOERR_FSTAT;
  27402. }
  27403. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  27404. *pMode = 0600;
  27405. }
  27406. return rc;
  27407. }
  27408. /*
  27409. ** Open the file zPath.
  27410. **
  27411. ** Previously, the SQLite OS layer used three functions in place of this
  27412. ** one:
  27413. **
  27414. ** sqlite3OsOpenReadWrite();
  27415. ** sqlite3OsOpenReadOnly();
  27416. ** sqlite3OsOpenExclusive();
  27417. **
  27418. ** These calls correspond to the following combinations of flags:
  27419. **
  27420. ** ReadWrite() -> (READWRITE | CREATE)
  27421. ** ReadOnly() -> (READONLY)
  27422. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  27423. **
  27424. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  27425. ** true, the file was configured to be automatically deleted when the
  27426. ** file handle closed. To achieve the same effect using this new
  27427. ** interface, add the DELETEONCLOSE flag to those specified above for
  27428. ** OpenExclusive().
  27429. */
  27430. static int unixOpen(
  27431. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  27432. const char *zPath, /* Pathname of file to be opened */
  27433. sqlite3_file *pFile, /* The file descriptor to be filled in */
  27434. int flags, /* Input flags to control the opening */
  27435. int *pOutFlags /* Output flags returned to SQLite core */
  27436. ){
  27437. unixFile *p = (unixFile *)pFile;
  27438. int fd = -1; /* File descriptor returned by open() */
  27439. int openFlags = 0; /* Flags to pass to open() */
  27440. int eType = flags&0xFFFFFF00; /* Type of file to open */
  27441. int noLock; /* True to omit locking primitives */
  27442. int rc = SQLITE_OK; /* Function Return Code */
  27443. int ctrlFlags = 0; /* UNIXFILE_* flags */
  27444. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  27445. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  27446. int isCreate = (flags & SQLITE_OPEN_CREATE);
  27447. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  27448. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  27449. #if SQLITE_ENABLE_LOCKING_STYLE
  27450. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  27451. #endif
  27452. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27453. struct statfs fsInfo;
  27454. #endif
  27455. /* If creating a master or main-file journal, this function will open
  27456. ** a file-descriptor on the directory too. The first time unixSync()
  27457. ** is called the directory file descriptor will be fsync()ed and close()d.
  27458. */
  27459. int syncDir = (isCreate && (
  27460. eType==SQLITE_OPEN_MASTER_JOURNAL
  27461. || eType==SQLITE_OPEN_MAIN_JOURNAL
  27462. || eType==SQLITE_OPEN_WAL
  27463. ));
  27464. /* If argument zPath is a NULL pointer, this function is required to open
  27465. ** a temporary file. Use this buffer to store the file name in.
  27466. */
  27467. char zTmpname[MAX_PATHNAME+2];
  27468. const char *zName = zPath;
  27469. /* Check the following statements are true:
  27470. **
  27471. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  27472. ** (b) if CREATE is set, then READWRITE must also be set, and
  27473. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  27474. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  27475. */
  27476. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  27477. assert(isCreate==0 || isReadWrite);
  27478. assert(isExclusive==0 || isCreate);
  27479. assert(isDelete==0 || isCreate);
  27480. /* The main DB, main journal, WAL file and master journal are never
  27481. ** automatically deleted. Nor are they ever temporary files. */
  27482. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  27483. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  27484. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  27485. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  27486. /* Assert that the upper layer has set one of the "file-type" flags. */
  27487. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  27488. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  27489. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  27490. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  27491. );
  27492. memset(p, 0, sizeof(unixFile));
  27493. if( eType==SQLITE_OPEN_MAIN_DB ){
  27494. UnixUnusedFd *pUnused;
  27495. pUnused = findReusableFd(zName, flags);
  27496. if( pUnused ){
  27497. fd = pUnused->fd;
  27498. }else{
  27499. pUnused = sqlite3_malloc(sizeof(*pUnused));
  27500. if( !pUnused ){
  27501. return SQLITE_NOMEM;
  27502. }
  27503. }
  27504. p->pUnused = pUnused;
  27505. /* Database filenames are double-zero terminated if they are not
  27506. ** URIs with parameters. Hence, they can always be passed into
  27507. ** sqlite3_uri_parameter(). */
  27508. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  27509. }else if( !zName ){
  27510. /* If zName is NULL, the upper layer is requesting a temp file. */
  27511. assert(isDelete && !syncDir);
  27512. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  27513. if( rc!=SQLITE_OK ){
  27514. return rc;
  27515. }
  27516. zName = zTmpname;
  27517. /* Generated temporary filenames are always double-zero terminated
  27518. ** for use by sqlite3_uri_parameter(). */
  27519. assert( zName[strlen(zName)+1]==0 );
  27520. }
  27521. /* Determine the value of the flags parameter passed to POSIX function
  27522. ** open(). These must be calculated even if open() is not called, as
  27523. ** they may be stored as part of the file handle and used by the
  27524. ** 'conch file' locking functions later on. */
  27525. if( isReadonly ) openFlags |= O_RDONLY;
  27526. if( isReadWrite ) openFlags |= O_RDWR;
  27527. if( isCreate ) openFlags |= O_CREAT;
  27528. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  27529. openFlags |= (O_LARGEFILE|O_BINARY);
  27530. if( fd<0 ){
  27531. mode_t openMode; /* Permissions to create file with */
  27532. uid_t uid; /* Userid for the file */
  27533. gid_t gid; /* Groupid for the file */
  27534. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  27535. if( rc!=SQLITE_OK ){
  27536. assert( !p->pUnused );
  27537. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  27538. return rc;
  27539. }
  27540. fd = robust_open(zName, openFlags, openMode);
  27541. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  27542. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  27543. /* Failed to open the file for read/write access. Try read-only. */
  27544. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  27545. openFlags &= ~(O_RDWR|O_CREAT);
  27546. flags |= SQLITE_OPEN_READONLY;
  27547. openFlags |= O_RDONLY;
  27548. isReadonly = 1;
  27549. fd = robust_open(zName, openFlags, openMode);
  27550. }
  27551. if( fd<0 ){
  27552. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  27553. goto open_finished;
  27554. }
  27555. /* If this process is running as root and if creating a new rollback
  27556. ** journal or WAL file, set the ownership of the journal or WAL to be
  27557. ** the same as the original database.
  27558. */
  27559. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  27560. osFchown(fd, uid, gid);
  27561. }
  27562. }
  27563. assert( fd>=0 );
  27564. if( pOutFlags ){
  27565. *pOutFlags = flags;
  27566. }
  27567. if( p->pUnused ){
  27568. p->pUnused->fd = fd;
  27569. p->pUnused->flags = flags;
  27570. }
  27571. if( isDelete ){
  27572. #if OS_VXWORKS
  27573. zPath = zName;
  27574. #else
  27575. osUnlink(zName);
  27576. #endif
  27577. }
  27578. #if SQLITE_ENABLE_LOCKING_STYLE
  27579. else{
  27580. p->openFlags = openFlags;
  27581. }
  27582. #endif
  27583. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  27584. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  27585. if( fstatfs(fd, &fsInfo) == -1 ){
  27586. ((unixFile*)pFile)->lastErrno = errno;
  27587. robust_close(p, fd, __LINE__);
  27588. return SQLITE_IOERR_ACCESS;
  27589. }
  27590. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  27591. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  27592. }
  27593. #endif
  27594. /* Set up appropriate ctrlFlags */
  27595. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  27596. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  27597. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  27598. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  27599. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  27600. #if SQLITE_ENABLE_LOCKING_STYLE
  27601. #if SQLITE_PREFER_PROXY_LOCKING
  27602. isAutoProxy = 1;
  27603. #endif
  27604. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  27605. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  27606. int useProxy = 0;
  27607. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  27608. ** never use proxy, NULL means use proxy for non-local files only. */
  27609. if( envforce!=NULL ){
  27610. useProxy = atoi(envforce)>0;
  27611. }else{
  27612. if( statfs(zPath, &fsInfo) == -1 ){
  27613. /* In theory, the close(fd) call is sub-optimal. If the file opened
  27614. ** with fd is a database file, and there are other connections open
  27615. ** on that file that are currently holding advisory locks on it,
  27616. ** then the call to close() will cancel those locks. In practice,
  27617. ** we're assuming that statfs() doesn't fail very often. At least
  27618. ** not while other file descriptors opened by the same process on
  27619. ** the same file are working. */
  27620. p->lastErrno = errno;
  27621. robust_close(p, fd, __LINE__);
  27622. rc = SQLITE_IOERR_ACCESS;
  27623. goto open_finished;
  27624. }
  27625. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  27626. }
  27627. if( useProxy ){
  27628. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27629. if( rc==SQLITE_OK ){
  27630. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  27631. if( rc!=SQLITE_OK ){
  27632. /* Use unixClose to clean up the resources added in fillInUnixFile
  27633. ** and clear all the structure's references. Specifically,
  27634. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  27635. */
  27636. unixClose(pFile);
  27637. return rc;
  27638. }
  27639. }
  27640. goto open_finished;
  27641. }
  27642. }
  27643. #endif
  27644. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  27645. open_finished:
  27646. if( rc!=SQLITE_OK ){
  27647. sqlite3_free(p->pUnused);
  27648. }
  27649. return rc;
  27650. }
  27651. /*
  27652. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  27653. ** the directory after deleting the file.
  27654. */
  27655. static int unixDelete(
  27656. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  27657. const char *zPath, /* Name of file to be deleted */
  27658. int dirSync /* If true, fsync() directory after deleting file */
  27659. ){
  27660. int rc = SQLITE_OK;
  27661. UNUSED_PARAMETER(NotUsed);
  27662. SimulateIOError(return SQLITE_IOERR_DELETE);
  27663. if( osUnlink(zPath)==(-1) ){
  27664. if( errno==ENOENT ){
  27665. rc = SQLITE_IOERR_DELETE_NOENT;
  27666. }else{
  27667. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  27668. }
  27669. return rc;
  27670. }
  27671. #ifndef SQLITE_DISABLE_DIRSYNC
  27672. if( (dirSync & 1)!=0 ){
  27673. int fd;
  27674. rc = osOpenDirectory(zPath, &fd);
  27675. if( rc==SQLITE_OK ){
  27676. #if OS_VXWORKS
  27677. if( fsync(fd)==-1 )
  27678. #else
  27679. if( fsync(fd) )
  27680. #endif
  27681. {
  27682. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  27683. }
  27684. robust_close(0, fd, __LINE__);
  27685. }else if( rc==SQLITE_CANTOPEN ){
  27686. rc = SQLITE_OK;
  27687. }
  27688. }
  27689. #endif
  27690. return rc;
  27691. }
  27692. /*
  27693. ** Test the existence of or access permissions of file zPath. The
  27694. ** test performed depends on the value of flags:
  27695. **
  27696. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  27697. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  27698. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  27699. **
  27700. ** Otherwise return 0.
  27701. */
  27702. static int unixAccess(
  27703. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  27704. const char *zPath, /* Path of the file to examine */
  27705. int flags, /* What do we want to learn about the zPath file? */
  27706. int *pResOut /* Write result boolean here */
  27707. ){
  27708. int amode = 0;
  27709. UNUSED_PARAMETER(NotUsed);
  27710. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  27711. switch( flags ){
  27712. case SQLITE_ACCESS_EXISTS:
  27713. amode = F_OK;
  27714. break;
  27715. case SQLITE_ACCESS_READWRITE:
  27716. amode = W_OK|R_OK;
  27717. break;
  27718. case SQLITE_ACCESS_READ:
  27719. amode = R_OK;
  27720. break;
  27721. default:
  27722. assert(!"Invalid flags argument");
  27723. }
  27724. *pResOut = (osAccess(zPath, amode)==0);
  27725. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  27726. struct stat buf;
  27727. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  27728. *pResOut = 0;
  27729. }
  27730. }
  27731. return SQLITE_OK;
  27732. }
  27733. /*
  27734. ** Turn a relative pathname into a full pathname. The relative path
  27735. ** is stored as a nul-terminated string in the buffer pointed to by
  27736. ** zPath.
  27737. **
  27738. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  27739. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  27740. ** this buffer before returning.
  27741. */
  27742. static int unixFullPathname(
  27743. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  27744. const char *zPath, /* Possibly relative input path */
  27745. int nOut, /* Size of output buffer in bytes */
  27746. char *zOut /* Output buffer */
  27747. ){
  27748. /* It's odd to simulate an io-error here, but really this is just
  27749. ** using the io-error infrastructure to test that SQLite handles this
  27750. ** function failing. This function could fail if, for example, the
  27751. ** current working directory has been unlinked.
  27752. */
  27753. SimulateIOError( return SQLITE_ERROR );
  27754. assert( pVfs->mxPathname==MAX_PATHNAME );
  27755. UNUSED_PARAMETER(pVfs);
  27756. zOut[nOut-1] = '\0';
  27757. if( zPath[0]=='/' ){
  27758. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  27759. }else{
  27760. int nCwd;
  27761. if( osGetcwd(zOut, nOut-1)==0 ){
  27762. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  27763. }
  27764. nCwd = (int)strlen(zOut);
  27765. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  27766. }
  27767. return SQLITE_OK;
  27768. }
  27769. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  27770. /*
  27771. ** Interfaces for opening a shared library, finding entry points
  27772. ** within the shared library, and closing the shared library.
  27773. */
  27774. #include <dlfcn.h>
  27775. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  27776. UNUSED_PARAMETER(NotUsed);
  27777. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  27778. }
  27779. /*
  27780. ** SQLite calls this function immediately after a call to unixDlSym() or
  27781. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  27782. ** message is available, it is written to zBufOut. If no error message
  27783. ** is available, zBufOut is left unmodified and SQLite uses a default
  27784. ** error message.
  27785. */
  27786. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  27787. const char *zErr;
  27788. UNUSED_PARAMETER(NotUsed);
  27789. unixEnterMutex();
  27790. zErr = dlerror();
  27791. if( zErr ){
  27792. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  27793. }
  27794. unixLeaveMutex();
  27795. }
  27796. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  27797. /*
  27798. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  27799. ** cast into a pointer to a function. And yet the library dlsym() routine
  27800. ** returns a void* which is really a pointer to a function. So how do we
  27801. ** use dlsym() with -pedantic-errors?
  27802. **
  27803. ** Variable x below is defined to be a pointer to a function taking
  27804. ** parameters void* and const char* and returning a pointer to a function.
  27805. ** We initialize x by assigning it a pointer to the dlsym() function.
  27806. ** (That assignment requires a cast.) Then we call the function that
  27807. ** x points to.
  27808. **
  27809. ** This work-around is unlikely to work correctly on any system where
  27810. ** you really cannot cast a function pointer into void*. But then, on the
  27811. ** other hand, dlsym() will not work on such a system either, so we have
  27812. ** not really lost anything.
  27813. */
  27814. void (*(*x)(void*,const char*))(void);
  27815. UNUSED_PARAMETER(NotUsed);
  27816. x = (void(*(*)(void*,const char*))(void))dlsym;
  27817. return (*x)(p, zSym);
  27818. }
  27819. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  27820. UNUSED_PARAMETER(NotUsed);
  27821. dlclose(pHandle);
  27822. }
  27823. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  27824. #define unixDlOpen 0
  27825. #define unixDlError 0
  27826. #define unixDlSym 0
  27827. #define unixDlClose 0
  27828. #endif
  27829. /*
  27830. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  27831. */
  27832. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  27833. UNUSED_PARAMETER(NotUsed);
  27834. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  27835. /* We have to initialize zBuf to prevent valgrind from reporting
  27836. ** errors. The reports issued by valgrind are incorrect - we would
  27837. ** prefer that the randomness be increased by making use of the
  27838. ** uninitialized space in zBuf - but valgrind errors tend to worry
  27839. ** some users. Rather than argue, it seems easier just to initialize
  27840. ** the whole array and silence valgrind, even if that means less randomness
  27841. ** in the random seed.
  27842. **
  27843. ** When testing, initializing zBuf[] to zero is all we do. That means
  27844. ** that we always use the same random number sequence. This makes the
  27845. ** tests repeatable.
  27846. */
  27847. memset(zBuf, 0, nBuf);
  27848. #if !defined(SQLITE_TEST)
  27849. {
  27850. int pid, fd, got;
  27851. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  27852. if( fd<0 ){
  27853. time_t t;
  27854. time(&t);
  27855. memcpy(zBuf, &t, sizeof(t));
  27856. pid = getpid();
  27857. memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
  27858. assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
  27859. nBuf = sizeof(t) + sizeof(pid);
  27860. }else{
  27861. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  27862. robust_close(0, fd, __LINE__);
  27863. }
  27864. }
  27865. #endif
  27866. return nBuf;
  27867. }
  27868. /*
  27869. ** Sleep for a little while. Return the amount of time slept.
  27870. ** The argument is the number of microseconds we want to sleep.
  27871. ** The return value is the number of microseconds of sleep actually
  27872. ** requested from the underlying operating system, a number which
  27873. ** might be greater than or equal to the argument, but not less
  27874. ** than the argument.
  27875. */
  27876. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  27877. #if OS_VXWORKS
  27878. struct timespec sp;
  27879. sp.tv_sec = microseconds / 1000000;
  27880. sp.tv_nsec = (microseconds % 1000000) * 1000;
  27881. nanosleep(&sp, NULL);
  27882. UNUSED_PARAMETER(NotUsed);
  27883. return microseconds;
  27884. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  27885. usleep(microseconds);
  27886. UNUSED_PARAMETER(NotUsed);
  27887. return microseconds;
  27888. #else
  27889. int seconds = (microseconds+999999)/1000000;
  27890. sleep(seconds);
  27891. UNUSED_PARAMETER(NotUsed);
  27892. return seconds*1000000;
  27893. #endif
  27894. }
  27895. /*
  27896. ** The following variable, if set to a non-zero value, is interpreted as
  27897. ** the number of seconds since 1970 and is used to set the result of
  27898. ** sqlite3OsCurrentTime() during testing.
  27899. */
  27900. #ifdef SQLITE_TEST
  27901. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  27902. #endif
  27903. /*
  27904. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  27905. ** the current time and date as a Julian Day number times 86_400_000. In
  27906. ** other words, write into *piNow the number of milliseconds since the Julian
  27907. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  27908. ** proleptic Gregorian calendar.
  27909. **
  27910. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  27911. ** cannot be found.
  27912. */
  27913. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  27914. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  27915. int rc = SQLITE_OK;
  27916. #if defined(NO_GETTOD)
  27917. time_t t;
  27918. time(&t);
  27919. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  27920. #elif OS_VXWORKS
  27921. struct timespec sNow;
  27922. clock_gettime(CLOCK_REALTIME, &sNow);
  27923. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  27924. #else
  27925. struct timeval sNow;
  27926. if( gettimeofday(&sNow, 0)==0 ){
  27927. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  27928. }else{
  27929. rc = SQLITE_ERROR;
  27930. }
  27931. #endif
  27932. #ifdef SQLITE_TEST
  27933. if( sqlite3_current_time ){
  27934. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  27935. }
  27936. #endif
  27937. UNUSED_PARAMETER(NotUsed);
  27938. return rc;
  27939. }
  27940. /*
  27941. ** Find the current time (in Universal Coordinated Time). Write the
  27942. ** current time and date as a Julian Day number into *prNow and
  27943. ** return 0. Return 1 if the time and date cannot be found.
  27944. */
  27945. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  27946. sqlite3_int64 i = 0;
  27947. int rc;
  27948. UNUSED_PARAMETER(NotUsed);
  27949. rc = unixCurrentTimeInt64(0, &i);
  27950. *prNow = i/86400000.0;
  27951. return rc;
  27952. }
  27953. /*
  27954. ** We added the xGetLastError() method with the intention of providing
  27955. ** better low-level error messages when operating-system problems come up
  27956. ** during SQLite operation. But so far, none of that has been implemented
  27957. ** in the core. So this routine is never called. For now, it is merely
  27958. ** a place-holder.
  27959. */
  27960. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  27961. UNUSED_PARAMETER(NotUsed);
  27962. UNUSED_PARAMETER(NotUsed2);
  27963. UNUSED_PARAMETER(NotUsed3);
  27964. return 0;
  27965. }
  27966. /*
  27967. ************************ End of sqlite3_vfs methods ***************************
  27968. ******************************************************************************/
  27969. /******************************************************************************
  27970. ************************** Begin Proxy Locking ********************************
  27971. **
  27972. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  27973. ** other locking methods on secondary lock files. Proxy locking is a
  27974. ** meta-layer over top of the primitive locking implemented above. For
  27975. ** this reason, the division that implements of proxy locking is deferred
  27976. ** until late in the file (here) after all of the other I/O methods have
  27977. ** been defined - so that the primitive locking methods are available
  27978. ** as services to help with the implementation of proxy locking.
  27979. **
  27980. ****
  27981. **
  27982. ** The default locking schemes in SQLite use byte-range locks on the
  27983. ** database file to coordinate safe, concurrent access by multiple readers
  27984. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  27985. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  27986. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  27987. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  27988. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  27989. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  27990. ** address in the shared range is taken for a SHARED lock, the entire
  27991. ** shared range is taken for an EXCLUSIVE lock):
  27992. **
  27993. ** PENDING_BYTE 0x40000000
  27994. ** RESERVED_BYTE 0x40000001
  27995. ** SHARED_RANGE 0x40000002 -> 0x40000200
  27996. **
  27997. ** This works well on the local file system, but shows a nearly 100x
  27998. ** slowdown in read performance on AFP because the AFP client disables
  27999. ** the read cache when byte-range locks are present. Enabling the read
  28000. ** cache exposes a cache coherency problem that is present on all OS X
  28001. ** supported network file systems. NFS and AFP both observe the
  28002. ** close-to-open semantics for ensuring cache coherency
  28003. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  28004. ** address the requirements for concurrent database access by multiple
  28005. ** readers and writers
  28006. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  28007. **
  28008. ** To address the performance and cache coherency issues, proxy file locking
  28009. ** changes the way database access is controlled by limiting access to a
  28010. ** single host at a time and moving file locks off of the database file
  28011. ** and onto a proxy file on the local file system.
  28012. **
  28013. **
  28014. ** Using proxy locks
  28015. ** -----------------
  28016. **
  28017. ** C APIs
  28018. **
  28019. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  28020. ** <proxy_path> | ":auto:");
  28021. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  28022. **
  28023. **
  28024. ** SQL pragmas
  28025. **
  28026. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  28027. ** PRAGMA [database.]lock_proxy_file
  28028. **
  28029. ** Specifying ":auto:" means that if there is a conch file with a matching
  28030. ** host ID in it, the proxy path in the conch file will be used, otherwise
  28031. ** a proxy path based on the user's temp dir
  28032. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  28033. ** actual proxy file name is generated from the name and path of the
  28034. ** database file. For example:
  28035. **
  28036. ** For database path "/Users/me/foo.db"
  28037. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  28038. **
  28039. ** Once a lock proxy is configured for a database connection, it can not
  28040. ** be removed, however it may be switched to a different proxy path via
  28041. ** the above APIs (assuming the conch file is not being held by another
  28042. ** connection or process).
  28043. **
  28044. **
  28045. ** How proxy locking works
  28046. ** -----------------------
  28047. **
  28048. ** Proxy file locking relies primarily on two new supporting files:
  28049. **
  28050. ** * conch file to limit access to the database file to a single host
  28051. ** at a time
  28052. **
  28053. ** * proxy file to act as a proxy for the advisory locks normally
  28054. ** taken on the database
  28055. **
  28056. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  28057. ** by taking an sqlite-style shared lock on the conch file, reading the
  28058. ** contents and comparing the host's unique host ID (see below) and lock
  28059. ** proxy path against the values stored in the conch. The conch file is
  28060. ** stored in the same directory as the database file and the file name
  28061. ** is patterned after the database file name as ".<databasename>-conch".
  28062. ** If the conch file does not exist, or it's contents do not match the
  28063. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  28064. ** lock and the conch file contents is updated with the host ID and proxy
  28065. ** path and the lock is downgraded to a shared lock again. If the conch
  28066. ** is held by another process (with a shared lock), the exclusive lock
  28067. ** will fail and SQLITE_BUSY is returned.
  28068. **
  28069. ** The proxy file - a single-byte file used for all advisory file locks
  28070. ** normally taken on the database file. This allows for safe sharing
  28071. ** of the database file for multiple readers and writers on the same
  28072. ** host (the conch ensures that they all use the same local lock file).
  28073. **
  28074. ** Requesting the lock proxy does not immediately take the conch, it is
  28075. ** only taken when the first request to lock database file is made.
  28076. ** This matches the semantics of the traditional locking behavior, where
  28077. ** opening a connection to a database file does not take a lock on it.
  28078. ** The shared lock and an open file descriptor are maintained until
  28079. ** the connection to the database is closed.
  28080. **
  28081. ** The proxy file and the lock file are never deleted so they only need
  28082. ** to be created the first time they are used.
  28083. **
  28084. ** Configuration options
  28085. ** ---------------------
  28086. **
  28087. ** SQLITE_PREFER_PROXY_LOCKING
  28088. **
  28089. ** Database files accessed on non-local file systems are
  28090. ** automatically configured for proxy locking, lock files are
  28091. ** named automatically using the same logic as
  28092. ** PRAGMA lock_proxy_file=":auto:"
  28093. **
  28094. ** SQLITE_PROXY_DEBUG
  28095. **
  28096. ** Enables the logging of error messages during host id file
  28097. ** retrieval and creation
  28098. **
  28099. ** LOCKPROXYDIR
  28100. **
  28101. ** Overrides the default directory used for lock proxy files that
  28102. ** are named automatically via the ":auto:" setting
  28103. **
  28104. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  28105. **
  28106. ** Permissions to use when creating a directory for storing the
  28107. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  28108. **
  28109. **
  28110. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  28111. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  28112. ** force proxy locking to be used for every database file opened, and 0
  28113. ** will force automatic proxy locking to be disabled for all database
  28114. ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
  28115. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  28116. */
  28117. /*
  28118. ** Proxy locking is only available on MacOSX
  28119. */
  28120. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28121. /*
  28122. ** The proxyLockingContext has the path and file structures for the remote
  28123. ** and local proxy files in it
  28124. */
  28125. typedef struct proxyLockingContext proxyLockingContext;
  28126. struct proxyLockingContext {
  28127. unixFile *conchFile; /* Open conch file */
  28128. char *conchFilePath; /* Name of the conch file */
  28129. unixFile *lockProxy; /* Open proxy lock file */
  28130. char *lockProxyPath; /* Name of the proxy lock file */
  28131. char *dbPath; /* Name of the open file */
  28132. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  28133. void *oldLockingContext; /* Original lockingcontext to restore on close */
  28134. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  28135. };
  28136. /*
  28137. ** The proxy lock file path for the database at dbPath is written into lPath,
  28138. ** which must point to valid, writable memory large enough for a maxLen length
  28139. ** file path.
  28140. */
  28141. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  28142. int len;
  28143. int dbLen;
  28144. int i;
  28145. #ifdef LOCKPROXYDIR
  28146. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  28147. #else
  28148. # ifdef _CS_DARWIN_USER_TEMP_DIR
  28149. {
  28150. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  28151. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  28152. lPath, errno, getpid()));
  28153. return SQLITE_IOERR_LOCK;
  28154. }
  28155. len = strlcat(lPath, "sqliteplocks", maxLen);
  28156. }
  28157. # else
  28158. len = strlcpy(lPath, "/tmp/", maxLen);
  28159. # endif
  28160. #endif
  28161. if( lPath[len-1]!='/' ){
  28162. len = strlcat(lPath, "/", maxLen);
  28163. }
  28164. /* transform the db path to a unique cache name */
  28165. dbLen = (int)strlen(dbPath);
  28166. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  28167. char c = dbPath[i];
  28168. lPath[i+len] = (c=='/')?'_':c;
  28169. }
  28170. lPath[i+len]='\0';
  28171. strlcat(lPath, ":auto:", maxLen);
  28172. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  28173. return SQLITE_OK;
  28174. }
  28175. /*
  28176. ** Creates the lock file and any missing directories in lockPath
  28177. */
  28178. static int proxyCreateLockPath(const char *lockPath){
  28179. int i, len;
  28180. char buf[MAXPATHLEN];
  28181. int start = 0;
  28182. assert(lockPath!=NULL);
  28183. /* try to create all the intermediate directories */
  28184. len = (int)strlen(lockPath);
  28185. buf[0] = lockPath[0];
  28186. for( i=1; i<len; i++ ){
  28187. if( lockPath[i] == '/' && (i - start > 0) ){
  28188. /* only mkdir if leaf dir != "." or "/" or ".." */
  28189. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  28190. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  28191. buf[i]='\0';
  28192. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  28193. int err=errno;
  28194. if( err!=EEXIST ) {
  28195. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  28196. "'%s' proxy lock path=%s pid=%d\n",
  28197. buf, strerror(err), lockPath, getpid()));
  28198. return err;
  28199. }
  28200. }
  28201. }
  28202. start=i+1;
  28203. }
  28204. buf[i] = lockPath[i];
  28205. }
  28206. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  28207. return 0;
  28208. }
  28209. /*
  28210. ** Create a new VFS file descriptor (stored in memory obtained from
  28211. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  28212. **
  28213. ** The caller is responsible not only for closing the file descriptor
  28214. ** but also for freeing the memory associated with the file descriptor.
  28215. */
  28216. static int proxyCreateUnixFile(
  28217. const char *path, /* path for the new unixFile */
  28218. unixFile **ppFile, /* unixFile created and returned by ref */
  28219. int islockfile /* if non zero missing dirs will be created */
  28220. ) {
  28221. int fd = -1;
  28222. unixFile *pNew;
  28223. int rc = SQLITE_OK;
  28224. int openFlags = O_RDWR | O_CREAT;
  28225. sqlite3_vfs dummyVfs;
  28226. int terrno = 0;
  28227. UnixUnusedFd *pUnused = NULL;
  28228. /* 1. first try to open/create the file
  28229. ** 2. if that fails, and this is a lock file (not-conch), try creating
  28230. ** the parent directories and then try again.
  28231. ** 3. if that fails, try to open the file read-only
  28232. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  28233. */
  28234. pUnused = findReusableFd(path, openFlags);
  28235. if( pUnused ){
  28236. fd = pUnused->fd;
  28237. }else{
  28238. pUnused = sqlite3_malloc(sizeof(*pUnused));
  28239. if( !pUnused ){
  28240. return SQLITE_NOMEM;
  28241. }
  28242. }
  28243. if( fd<0 ){
  28244. fd = robust_open(path, openFlags, 0);
  28245. terrno = errno;
  28246. if( fd<0 && errno==ENOENT && islockfile ){
  28247. if( proxyCreateLockPath(path) == SQLITE_OK ){
  28248. fd = robust_open(path, openFlags, 0);
  28249. }
  28250. }
  28251. }
  28252. if( fd<0 ){
  28253. openFlags = O_RDONLY;
  28254. fd = robust_open(path, openFlags, 0);
  28255. terrno = errno;
  28256. }
  28257. if( fd<0 ){
  28258. if( islockfile ){
  28259. return SQLITE_BUSY;
  28260. }
  28261. switch (terrno) {
  28262. case EACCES:
  28263. return SQLITE_PERM;
  28264. case EIO:
  28265. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  28266. default:
  28267. return SQLITE_CANTOPEN_BKPT;
  28268. }
  28269. }
  28270. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  28271. if( pNew==NULL ){
  28272. rc = SQLITE_NOMEM;
  28273. goto end_create_proxy;
  28274. }
  28275. memset(pNew, 0, sizeof(unixFile));
  28276. pNew->openFlags = openFlags;
  28277. memset(&dummyVfs, 0, sizeof(dummyVfs));
  28278. dummyVfs.pAppData = (void*)&autolockIoFinder;
  28279. dummyVfs.zName = "dummy";
  28280. pUnused->fd = fd;
  28281. pUnused->flags = openFlags;
  28282. pNew->pUnused = pUnused;
  28283. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  28284. if( rc==SQLITE_OK ){
  28285. *ppFile = pNew;
  28286. return SQLITE_OK;
  28287. }
  28288. end_create_proxy:
  28289. robust_close(pNew, fd, __LINE__);
  28290. sqlite3_free(pNew);
  28291. sqlite3_free(pUnused);
  28292. return rc;
  28293. }
  28294. #ifdef SQLITE_TEST
  28295. /* simulate multiple hosts by creating unique hostid file paths */
  28296. SQLITE_API int sqlite3_hostid_num = 0;
  28297. #endif
  28298. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  28299. /* Not always defined in the headers as it ought to be */
  28300. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  28301. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  28302. ** bytes of writable memory.
  28303. */
  28304. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  28305. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  28306. memset(pHostID, 0, PROXY_HOSTIDLEN);
  28307. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  28308. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  28309. {
  28310. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  28311. if( gethostuuid(pHostID, &timeout) ){
  28312. int err = errno;
  28313. if( pError ){
  28314. *pError = err;
  28315. }
  28316. return SQLITE_IOERR;
  28317. }
  28318. }
  28319. #else
  28320. UNUSED_PARAMETER(pError);
  28321. #endif
  28322. #ifdef SQLITE_TEST
  28323. /* simulate multiple hosts by creating unique hostid file paths */
  28324. if( sqlite3_hostid_num != 0){
  28325. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  28326. }
  28327. #endif
  28328. return SQLITE_OK;
  28329. }
  28330. /* The conch file contains the header, host id and lock file path
  28331. */
  28332. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  28333. #define PROXY_HEADERLEN 1 /* conch file header length */
  28334. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  28335. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  28336. /*
  28337. ** Takes an open conch file, copies the contents to a new path and then moves
  28338. ** it back. The newly created file's file descriptor is assigned to the
  28339. ** conch file structure and finally the original conch file descriptor is
  28340. ** closed. Returns zero if successful.
  28341. */
  28342. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  28343. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28344. unixFile *conchFile = pCtx->conchFile;
  28345. char tPath[MAXPATHLEN];
  28346. char buf[PROXY_MAXCONCHLEN];
  28347. char *cPath = pCtx->conchFilePath;
  28348. size_t readLen = 0;
  28349. size_t pathLen = 0;
  28350. char errmsg[64] = "";
  28351. int fd = -1;
  28352. int rc = -1;
  28353. UNUSED_PARAMETER(myHostID);
  28354. /* create a new path by replace the trailing '-conch' with '-break' */
  28355. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  28356. if( pathLen>MAXPATHLEN || pathLen<6 ||
  28357. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  28358. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  28359. goto end_breaklock;
  28360. }
  28361. /* read the conch content */
  28362. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  28363. if( readLen<PROXY_PATHINDEX ){
  28364. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  28365. goto end_breaklock;
  28366. }
  28367. /* write it out to the temporary break file */
  28368. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  28369. if( fd<0 ){
  28370. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  28371. goto end_breaklock;
  28372. }
  28373. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  28374. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  28375. goto end_breaklock;
  28376. }
  28377. if( rename(tPath, cPath) ){
  28378. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  28379. goto end_breaklock;
  28380. }
  28381. rc = 0;
  28382. fprintf(stderr, "broke stale lock on %s\n", cPath);
  28383. robust_close(pFile, conchFile->h, __LINE__);
  28384. conchFile->h = fd;
  28385. conchFile->openFlags = O_RDWR | O_CREAT;
  28386. end_breaklock:
  28387. if( rc ){
  28388. if( fd>=0 ){
  28389. osUnlink(tPath);
  28390. robust_close(pFile, fd, __LINE__);
  28391. }
  28392. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  28393. }
  28394. return rc;
  28395. }
  28396. /* Take the requested lock on the conch file and break a stale lock if the
  28397. ** host id matches.
  28398. */
  28399. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  28400. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28401. unixFile *conchFile = pCtx->conchFile;
  28402. int rc = SQLITE_OK;
  28403. int nTries = 0;
  28404. struct timespec conchModTime;
  28405. memset(&conchModTime, 0, sizeof(conchModTime));
  28406. do {
  28407. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28408. nTries ++;
  28409. if( rc==SQLITE_BUSY ){
  28410. /* If the lock failed (busy):
  28411. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  28412. * 2nd try: fail if the mod time changed or host id is different, wait
  28413. * 10 sec and try again
  28414. * 3rd try: break the lock unless the mod time has changed.
  28415. */
  28416. struct stat buf;
  28417. if( osFstat(conchFile->h, &buf) ){
  28418. pFile->lastErrno = errno;
  28419. return SQLITE_IOERR_LOCK;
  28420. }
  28421. if( nTries==1 ){
  28422. conchModTime = buf.st_mtimespec;
  28423. usleep(500000); /* wait 0.5 sec and try the lock again*/
  28424. continue;
  28425. }
  28426. assert( nTries>1 );
  28427. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  28428. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  28429. return SQLITE_BUSY;
  28430. }
  28431. if( nTries==2 ){
  28432. char tBuf[PROXY_MAXCONCHLEN];
  28433. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  28434. if( len<0 ){
  28435. pFile->lastErrno = errno;
  28436. return SQLITE_IOERR_LOCK;
  28437. }
  28438. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  28439. /* don't break the lock if the host id doesn't match */
  28440. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  28441. return SQLITE_BUSY;
  28442. }
  28443. }else{
  28444. /* don't break the lock on short read or a version mismatch */
  28445. return SQLITE_BUSY;
  28446. }
  28447. usleep(10000000); /* wait 10 sec and try the lock again */
  28448. continue;
  28449. }
  28450. assert( nTries==3 );
  28451. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  28452. rc = SQLITE_OK;
  28453. if( lockType==EXCLUSIVE_LOCK ){
  28454. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  28455. }
  28456. if( !rc ){
  28457. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  28458. }
  28459. }
  28460. }
  28461. } while( rc==SQLITE_BUSY && nTries<3 );
  28462. return rc;
  28463. }
  28464. /* Takes the conch by taking a shared lock and read the contents conch, if
  28465. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  28466. ** lockPath means that the lockPath in the conch file will be used if the
  28467. ** host IDs match, or a new lock path will be generated automatically
  28468. ** and written to the conch file.
  28469. */
  28470. static int proxyTakeConch(unixFile *pFile){
  28471. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28472. if( pCtx->conchHeld!=0 ){
  28473. return SQLITE_OK;
  28474. }else{
  28475. unixFile *conchFile = pCtx->conchFile;
  28476. uuid_t myHostID;
  28477. int pError = 0;
  28478. char readBuf[PROXY_MAXCONCHLEN];
  28479. char lockPath[MAXPATHLEN];
  28480. char *tempLockPath = NULL;
  28481. int rc = SQLITE_OK;
  28482. int createConch = 0;
  28483. int hostIdMatch = 0;
  28484. int readLen = 0;
  28485. int tryOldLockPath = 0;
  28486. int forceNewLockPath = 0;
  28487. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  28488. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  28489. rc = proxyGetHostID(myHostID, &pError);
  28490. if( (rc&0xff)==SQLITE_IOERR ){
  28491. pFile->lastErrno = pError;
  28492. goto end_takeconch;
  28493. }
  28494. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  28495. if( rc!=SQLITE_OK ){
  28496. goto end_takeconch;
  28497. }
  28498. /* read the existing conch file */
  28499. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  28500. if( readLen<0 ){
  28501. /* I/O error: lastErrno set by seekAndRead */
  28502. pFile->lastErrno = conchFile->lastErrno;
  28503. rc = SQLITE_IOERR_READ;
  28504. goto end_takeconch;
  28505. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  28506. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  28507. /* a short read or version format mismatch means we need to create a new
  28508. ** conch file.
  28509. */
  28510. createConch = 1;
  28511. }
  28512. /* if the host id matches and the lock path already exists in the conch
  28513. ** we'll try to use the path there, if we can't open that path, we'll
  28514. ** retry with a new auto-generated path
  28515. */
  28516. do { /* in case we need to try again for an :auto: named lock file */
  28517. if( !createConch && !forceNewLockPath ){
  28518. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  28519. PROXY_HOSTIDLEN);
  28520. /* if the conch has data compare the contents */
  28521. if( !pCtx->lockProxyPath ){
  28522. /* for auto-named local lock file, just check the host ID and we'll
  28523. ** use the local lock file path that's already in there
  28524. */
  28525. if( hostIdMatch ){
  28526. size_t pathLen = (readLen - PROXY_PATHINDEX);
  28527. if( pathLen>=MAXPATHLEN ){
  28528. pathLen=MAXPATHLEN-1;
  28529. }
  28530. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  28531. lockPath[pathLen] = 0;
  28532. tempLockPath = lockPath;
  28533. tryOldLockPath = 1;
  28534. /* create a copy of the lock path if the conch is taken */
  28535. goto end_takeconch;
  28536. }
  28537. }else if( hostIdMatch
  28538. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  28539. readLen-PROXY_PATHINDEX)
  28540. ){
  28541. /* conch host and lock path match */
  28542. goto end_takeconch;
  28543. }
  28544. }
  28545. /* if the conch isn't writable and doesn't match, we can't take it */
  28546. if( (conchFile->openFlags&O_RDWR) == 0 ){
  28547. rc = SQLITE_BUSY;
  28548. goto end_takeconch;
  28549. }
  28550. /* either the conch didn't match or we need to create a new one */
  28551. if( !pCtx->lockProxyPath ){
  28552. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  28553. tempLockPath = lockPath;
  28554. /* create a copy of the lock path _only_ if the conch is taken */
  28555. }
  28556. /* update conch with host and path (this will fail if other process
  28557. ** has a shared lock already), if the host id matches, use the big
  28558. ** stick.
  28559. */
  28560. futimes(conchFile->h, NULL);
  28561. if( hostIdMatch && !createConch ){
  28562. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  28563. /* We are trying for an exclusive lock but another thread in this
  28564. ** same process is still holding a shared lock. */
  28565. rc = SQLITE_BUSY;
  28566. } else {
  28567. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  28568. }
  28569. }else{
  28570. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  28571. }
  28572. if( rc==SQLITE_OK ){
  28573. char writeBuffer[PROXY_MAXCONCHLEN];
  28574. int writeSize = 0;
  28575. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  28576. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  28577. if( pCtx->lockProxyPath!=NULL ){
  28578. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  28579. }else{
  28580. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  28581. }
  28582. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  28583. robust_ftruncate(conchFile->h, writeSize);
  28584. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  28585. fsync(conchFile->h);
  28586. /* If we created a new conch file (not just updated the contents of a
  28587. ** valid conch file), try to match the permissions of the database
  28588. */
  28589. if( rc==SQLITE_OK && createConch ){
  28590. struct stat buf;
  28591. int err = osFstat(pFile->h, &buf);
  28592. if( err==0 ){
  28593. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  28594. S_IROTH|S_IWOTH);
  28595. /* try to match the database file R/W permissions, ignore failure */
  28596. #ifndef SQLITE_PROXY_DEBUG
  28597. osFchmod(conchFile->h, cmode);
  28598. #else
  28599. do{
  28600. rc = osFchmod(conchFile->h, cmode);
  28601. }while( rc==(-1) && errno==EINTR );
  28602. if( rc!=0 ){
  28603. int code = errno;
  28604. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  28605. cmode, code, strerror(code));
  28606. } else {
  28607. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  28608. }
  28609. }else{
  28610. int code = errno;
  28611. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  28612. err, code, strerror(code));
  28613. #endif
  28614. }
  28615. }
  28616. }
  28617. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  28618. end_takeconch:
  28619. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  28620. if( rc==SQLITE_OK && pFile->openFlags ){
  28621. int fd;
  28622. if( pFile->h>=0 ){
  28623. robust_close(pFile, pFile->h, __LINE__);
  28624. }
  28625. pFile->h = -1;
  28626. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  28627. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  28628. if( fd>=0 ){
  28629. pFile->h = fd;
  28630. }else{
  28631. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  28632. during locking */
  28633. }
  28634. }
  28635. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  28636. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  28637. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  28638. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  28639. /* we couldn't create the proxy lock file with the old lock file path
  28640. ** so try again via auto-naming
  28641. */
  28642. forceNewLockPath = 1;
  28643. tryOldLockPath = 0;
  28644. continue; /* go back to the do {} while start point, try again */
  28645. }
  28646. }
  28647. if( rc==SQLITE_OK ){
  28648. /* Need to make a copy of path if we extracted the value
  28649. ** from the conch file or the path was allocated on the stack
  28650. */
  28651. if( tempLockPath ){
  28652. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  28653. if( !pCtx->lockProxyPath ){
  28654. rc = SQLITE_NOMEM;
  28655. }
  28656. }
  28657. }
  28658. if( rc==SQLITE_OK ){
  28659. pCtx->conchHeld = 1;
  28660. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  28661. afpLockingContext *afpCtx;
  28662. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  28663. afpCtx->dbPath = pCtx->lockProxyPath;
  28664. }
  28665. } else {
  28666. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28667. }
  28668. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  28669. rc==SQLITE_OK?"ok":"failed"));
  28670. return rc;
  28671. } while (1); /* in case we need to retry the :auto: lock file -
  28672. ** we should never get here except via the 'continue' call. */
  28673. }
  28674. }
  28675. /*
  28676. ** If pFile holds a lock on a conch file, then release that lock.
  28677. */
  28678. static int proxyReleaseConch(unixFile *pFile){
  28679. int rc = SQLITE_OK; /* Subroutine return code */
  28680. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  28681. unixFile *conchFile; /* Name of the conch file */
  28682. pCtx = (proxyLockingContext *)pFile->lockingContext;
  28683. conchFile = pCtx->conchFile;
  28684. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  28685. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  28686. getpid()));
  28687. if( pCtx->conchHeld>0 ){
  28688. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  28689. }
  28690. pCtx->conchHeld = 0;
  28691. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  28692. (rc==SQLITE_OK ? "ok" : "failed")));
  28693. return rc;
  28694. }
  28695. /*
  28696. ** Given the name of a database file, compute the name of its conch file.
  28697. ** Store the conch filename in memory obtained from sqlite3_malloc().
  28698. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  28699. ** or SQLITE_NOMEM if unable to obtain memory.
  28700. **
  28701. ** The caller is responsible for ensuring that the allocated memory
  28702. ** space is eventually freed.
  28703. **
  28704. ** *pConchPath is set to NULL if a memory allocation error occurs.
  28705. */
  28706. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  28707. int i; /* Loop counter */
  28708. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  28709. char *conchPath; /* buffer in which to construct conch name */
  28710. /* Allocate space for the conch filename and initialize the name to
  28711. ** the name of the original database file. */
  28712. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  28713. if( conchPath==0 ){
  28714. return SQLITE_NOMEM;
  28715. }
  28716. memcpy(conchPath, dbPath, len+1);
  28717. /* now insert a "." before the last / character */
  28718. for( i=(len-1); i>=0; i-- ){
  28719. if( conchPath[i]=='/' ){
  28720. i++;
  28721. break;
  28722. }
  28723. }
  28724. conchPath[i]='.';
  28725. while ( i<len ){
  28726. conchPath[i+1]=dbPath[i];
  28727. i++;
  28728. }
  28729. /* append the "-conch" suffix to the file */
  28730. memcpy(&conchPath[i+1], "-conch", 7);
  28731. assert( (int)strlen(conchPath) == len+7 );
  28732. return SQLITE_OK;
  28733. }
  28734. /* Takes a fully configured proxy locking-style unix file and switches
  28735. ** the local lock file path
  28736. */
  28737. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  28738. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28739. char *oldPath = pCtx->lockProxyPath;
  28740. int rc = SQLITE_OK;
  28741. if( pFile->eFileLock!=NO_LOCK ){
  28742. return SQLITE_BUSY;
  28743. }
  28744. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  28745. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  28746. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  28747. return SQLITE_OK;
  28748. }else{
  28749. unixFile *lockProxy = pCtx->lockProxy;
  28750. pCtx->lockProxy=NULL;
  28751. pCtx->conchHeld = 0;
  28752. if( lockProxy!=NULL ){
  28753. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  28754. if( rc ) return rc;
  28755. sqlite3_free(lockProxy);
  28756. }
  28757. sqlite3_free(oldPath);
  28758. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  28759. }
  28760. return rc;
  28761. }
  28762. /*
  28763. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  28764. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  28765. **
  28766. ** This routine find the filename associated with pFile and writes it
  28767. ** int dbPath.
  28768. */
  28769. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  28770. #if defined(__APPLE__)
  28771. if( pFile->pMethod == &afpIoMethods ){
  28772. /* afp style keeps a reference to the db path in the filePath field
  28773. ** of the struct */
  28774. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28775. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  28776. } else
  28777. #endif
  28778. if( pFile->pMethod == &dotlockIoMethods ){
  28779. /* dot lock style uses the locking context to store the dot lock
  28780. ** file path */
  28781. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  28782. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  28783. }else{
  28784. /* all other styles use the locking context to store the db file path */
  28785. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  28786. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  28787. }
  28788. return SQLITE_OK;
  28789. }
  28790. /*
  28791. ** Takes an already filled in unix file and alters it so all file locking
  28792. ** will be performed on the local proxy lock file. The following fields
  28793. ** are preserved in the locking context so that they can be restored and
  28794. ** the unix structure properly cleaned up at close time:
  28795. ** ->lockingContext
  28796. ** ->pMethod
  28797. */
  28798. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  28799. proxyLockingContext *pCtx;
  28800. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  28801. char *lockPath=NULL;
  28802. int rc = SQLITE_OK;
  28803. if( pFile->eFileLock!=NO_LOCK ){
  28804. return SQLITE_BUSY;
  28805. }
  28806. proxyGetDbPathForUnixFile(pFile, dbPath);
  28807. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  28808. lockPath=NULL;
  28809. }else{
  28810. lockPath=(char *)path;
  28811. }
  28812. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  28813. (lockPath ? lockPath : ":auto:"), getpid()));
  28814. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28815. if( pCtx==0 ){
  28816. return SQLITE_NOMEM;
  28817. }
  28818. memset(pCtx, 0, sizeof(*pCtx));
  28819. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  28820. if( rc==SQLITE_OK ){
  28821. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  28822. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  28823. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  28824. ** (c) the file system is read-only, then enable no-locking access.
  28825. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  28826. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  28827. */
  28828. struct statfs fsInfo;
  28829. struct stat conchInfo;
  28830. int goLockless = 0;
  28831. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  28832. int err = errno;
  28833. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  28834. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  28835. }
  28836. }
  28837. if( goLockless ){
  28838. pCtx->conchHeld = -1; /* read only FS/ lockless */
  28839. rc = SQLITE_OK;
  28840. }
  28841. }
  28842. }
  28843. if( rc==SQLITE_OK && lockPath ){
  28844. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  28845. }
  28846. if( rc==SQLITE_OK ){
  28847. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  28848. if( pCtx->dbPath==NULL ){
  28849. rc = SQLITE_NOMEM;
  28850. }
  28851. }
  28852. if( rc==SQLITE_OK ){
  28853. /* all memory is allocated, proxys are created and assigned,
  28854. ** switch the locking context and pMethod then return.
  28855. */
  28856. pCtx->oldLockingContext = pFile->lockingContext;
  28857. pFile->lockingContext = pCtx;
  28858. pCtx->pOldMethod = pFile->pMethod;
  28859. pFile->pMethod = &proxyIoMethods;
  28860. }else{
  28861. if( pCtx->conchFile ){
  28862. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  28863. sqlite3_free(pCtx->conchFile);
  28864. }
  28865. sqlite3DbFree(0, pCtx->lockProxyPath);
  28866. sqlite3_free(pCtx->conchFilePath);
  28867. sqlite3_free(pCtx);
  28868. }
  28869. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  28870. (rc==SQLITE_OK ? "ok" : "failed")));
  28871. return rc;
  28872. }
  28873. /*
  28874. ** This routine handles sqlite3_file_control() calls that are specific
  28875. ** to proxy locking.
  28876. */
  28877. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  28878. switch( op ){
  28879. case SQLITE_GET_LOCKPROXYFILE: {
  28880. unixFile *pFile = (unixFile*)id;
  28881. if( pFile->pMethod == &proxyIoMethods ){
  28882. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  28883. proxyTakeConch(pFile);
  28884. if( pCtx->lockProxyPath ){
  28885. *(const char **)pArg = pCtx->lockProxyPath;
  28886. }else{
  28887. *(const char **)pArg = ":auto: (not held)";
  28888. }
  28889. } else {
  28890. *(const char **)pArg = NULL;
  28891. }
  28892. return SQLITE_OK;
  28893. }
  28894. case SQLITE_SET_LOCKPROXYFILE: {
  28895. unixFile *pFile = (unixFile*)id;
  28896. int rc = SQLITE_OK;
  28897. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  28898. if( pArg==NULL || (const char *)pArg==0 ){
  28899. if( isProxyStyle ){
  28900. /* turn off proxy locking - not supported */
  28901. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  28902. }else{
  28903. /* turn off proxy locking - already off - NOOP */
  28904. rc = SQLITE_OK;
  28905. }
  28906. }else{
  28907. const char *proxyPath = (const char *)pArg;
  28908. if( isProxyStyle ){
  28909. proxyLockingContext *pCtx =
  28910. (proxyLockingContext*)pFile->lockingContext;
  28911. if( !strcmp(pArg, ":auto:")
  28912. || (pCtx->lockProxyPath &&
  28913. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  28914. ){
  28915. rc = SQLITE_OK;
  28916. }else{
  28917. rc = switchLockProxyPath(pFile, proxyPath);
  28918. }
  28919. }else{
  28920. /* turn on proxy file locking */
  28921. rc = proxyTransformUnixFile(pFile, proxyPath);
  28922. }
  28923. }
  28924. return rc;
  28925. }
  28926. default: {
  28927. assert( 0 ); /* The call assures that only valid opcodes are sent */
  28928. }
  28929. }
  28930. /*NOTREACHED*/
  28931. return SQLITE_ERROR;
  28932. }
  28933. /*
  28934. ** Within this division (the proxying locking implementation) the procedures
  28935. ** above this point are all utilities. The lock-related methods of the
  28936. ** proxy-locking sqlite3_io_method object follow.
  28937. */
  28938. /*
  28939. ** This routine checks if there is a RESERVED lock held on the specified
  28940. ** file by this or any other process. If such a lock is held, set *pResOut
  28941. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  28942. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  28943. */
  28944. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  28945. unixFile *pFile = (unixFile*)id;
  28946. int rc = proxyTakeConch(pFile);
  28947. if( rc==SQLITE_OK ){
  28948. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28949. if( pCtx->conchHeld>0 ){
  28950. unixFile *proxy = pCtx->lockProxy;
  28951. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  28952. }else{ /* conchHeld < 0 is lockless */
  28953. pResOut=0;
  28954. }
  28955. }
  28956. return rc;
  28957. }
  28958. /*
  28959. ** Lock the file with the lock specified by parameter eFileLock - one
  28960. ** of the following:
  28961. **
  28962. ** (1) SHARED_LOCK
  28963. ** (2) RESERVED_LOCK
  28964. ** (3) PENDING_LOCK
  28965. ** (4) EXCLUSIVE_LOCK
  28966. **
  28967. ** Sometimes when requesting one lock state, additional lock states
  28968. ** are inserted in between. The locking might fail on one of the later
  28969. ** transitions leaving the lock state different from what it started but
  28970. ** still short of its goal. The following chart shows the allowed
  28971. ** transitions and the inserted intermediate states:
  28972. **
  28973. ** UNLOCKED -> SHARED
  28974. ** SHARED -> RESERVED
  28975. ** SHARED -> (PENDING) -> EXCLUSIVE
  28976. ** RESERVED -> (PENDING) -> EXCLUSIVE
  28977. ** PENDING -> EXCLUSIVE
  28978. **
  28979. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  28980. ** routine to lower a locking level.
  28981. */
  28982. static int proxyLock(sqlite3_file *id, int eFileLock) {
  28983. unixFile *pFile = (unixFile*)id;
  28984. int rc = proxyTakeConch(pFile);
  28985. if( rc==SQLITE_OK ){
  28986. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  28987. if( pCtx->conchHeld>0 ){
  28988. unixFile *proxy = pCtx->lockProxy;
  28989. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  28990. pFile->eFileLock = proxy->eFileLock;
  28991. }else{
  28992. /* conchHeld < 0 is lockless */
  28993. }
  28994. }
  28995. return rc;
  28996. }
  28997. /*
  28998. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  28999. ** must be either NO_LOCK or SHARED_LOCK.
  29000. **
  29001. ** If the locking level of the file descriptor is already at or below
  29002. ** the requested locking level, this routine is a no-op.
  29003. */
  29004. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  29005. unixFile *pFile = (unixFile*)id;
  29006. int rc = proxyTakeConch(pFile);
  29007. if( rc==SQLITE_OK ){
  29008. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29009. if( pCtx->conchHeld>0 ){
  29010. unixFile *proxy = pCtx->lockProxy;
  29011. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  29012. pFile->eFileLock = proxy->eFileLock;
  29013. }else{
  29014. /* conchHeld < 0 is lockless */
  29015. }
  29016. }
  29017. return rc;
  29018. }
  29019. /*
  29020. ** Close a file that uses proxy locks.
  29021. */
  29022. static int proxyClose(sqlite3_file *id) {
  29023. if( id ){
  29024. unixFile *pFile = (unixFile*)id;
  29025. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29026. unixFile *lockProxy = pCtx->lockProxy;
  29027. unixFile *conchFile = pCtx->conchFile;
  29028. int rc = SQLITE_OK;
  29029. if( lockProxy ){
  29030. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  29031. if( rc ) return rc;
  29032. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  29033. if( rc ) return rc;
  29034. sqlite3_free(lockProxy);
  29035. pCtx->lockProxy = 0;
  29036. }
  29037. if( conchFile ){
  29038. if( pCtx->conchHeld ){
  29039. rc = proxyReleaseConch(pFile);
  29040. if( rc ) return rc;
  29041. }
  29042. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  29043. if( rc ) return rc;
  29044. sqlite3_free(conchFile);
  29045. }
  29046. sqlite3DbFree(0, pCtx->lockProxyPath);
  29047. sqlite3_free(pCtx->conchFilePath);
  29048. sqlite3DbFree(0, pCtx->dbPath);
  29049. /* restore the original locking context and pMethod then close it */
  29050. pFile->lockingContext = pCtx->oldLockingContext;
  29051. pFile->pMethod = pCtx->pOldMethod;
  29052. sqlite3_free(pCtx);
  29053. return pFile->pMethod->xClose(id);
  29054. }
  29055. return SQLITE_OK;
  29056. }
  29057. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  29058. /*
  29059. ** The proxy locking style is intended for use with AFP filesystems.
  29060. ** And since AFP is only supported on MacOSX, the proxy locking is also
  29061. ** restricted to MacOSX.
  29062. **
  29063. **
  29064. ******************* End of the proxy lock implementation **********************
  29065. ******************************************************************************/
  29066. /*
  29067. ** Initialize the operating system interface.
  29068. **
  29069. ** This routine registers all VFS implementations for unix-like operating
  29070. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  29071. ** should be the only routines in this file that are visible from other
  29072. ** files.
  29073. **
  29074. ** This routine is called once during SQLite initialization and by a
  29075. ** single thread. The memory allocation and mutex subsystems have not
  29076. ** necessarily been initialized when this routine is called, and so they
  29077. ** should not be used.
  29078. */
  29079. SQLITE_API int sqlite3_os_init(void){
  29080. /*
  29081. ** The following macro defines an initializer for an sqlite3_vfs object.
  29082. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  29083. ** to the "finder" function. (pAppData is a pointer to a pointer because
  29084. ** silly C90 rules prohibit a void* from being cast to a function pointer
  29085. ** and so we have to go through the intermediate pointer to avoid problems
  29086. ** when compiling with -pedantic-errors on GCC.)
  29087. **
  29088. ** The FINDER parameter to this macro is the name of the pointer to the
  29089. ** finder-function. The finder-function returns a pointer to the
  29090. ** sqlite_io_methods object that implements the desired locking
  29091. ** behaviors. See the division above that contains the IOMETHODS
  29092. ** macro for addition information on finder-functions.
  29093. **
  29094. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  29095. ** object. But the "autolockIoFinder" available on MacOSX does a little
  29096. ** more than that; it looks at the filesystem type that hosts the
  29097. ** database file and tries to choose an locking method appropriate for
  29098. ** that filesystem time.
  29099. */
  29100. #define UNIXVFS(VFSNAME, FINDER) { \
  29101. 3, /* iVersion */ \
  29102. sizeof(unixFile), /* szOsFile */ \
  29103. MAX_PATHNAME, /* mxPathname */ \
  29104. 0, /* pNext */ \
  29105. VFSNAME, /* zName */ \
  29106. (void*)&FINDER, /* pAppData */ \
  29107. unixOpen, /* xOpen */ \
  29108. unixDelete, /* xDelete */ \
  29109. unixAccess, /* xAccess */ \
  29110. unixFullPathname, /* xFullPathname */ \
  29111. unixDlOpen, /* xDlOpen */ \
  29112. unixDlError, /* xDlError */ \
  29113. unixDlSym, /* xDlSym */ \
  29114. unixDlClose, /* xDlClose */ \
  29115. unixRandomness, /* xRandomness */ \
  29116. unixSleep, /* xSleep */ \
  29117. unixCurrentTime, /* xCurrentTime */ \
  29118. unixGetLastError, /* xGetLastError */ \
  29119. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  29120. unixSetSystemCall, /* xSetSystemCall */ \
  29121. unixGetSystemCall, /* xGetSystemCall */ \
  29122. unixNextSystemCall, /* xNextSystemCall */ \
  29123. }
  29124. /*
  29125. ** All default VFSes for unix are contained in the following array.
  29126. **
  29127. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  29128. ** by the SQLite core when the VFS is registered. So the following
  29129. ** array cannot be const.
  29130. */
  29131. static sqlite3_vfs aVfs[] = {
  29132. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  29133. UNIXVFS("unix", autolockIoFinder ),
  29134. #else
  29135. UNIXVFS("unix", posixIoFinder ),
  29136. #endif
  29137. UNIXVFS("unix-none", nolockIoFinder ),
  29138. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  29139. UNIXVFS("unix-excl", posixIoFinder ),
  29140. #if OS_VXWORKS
  29141. UNIXVFS("unix-namedsem", semIoFinder ),
  29142. #endif
  29143. #if SQLITE_ENABLE_LOCKING_STYLE
  29144. UNIXVFS("unix-posix", posixIoFinder ),
  29145. #if !OS_VXWORKS
  29146. UNIXVFS("unix-flock", flockIoFinder ),
  29147. #endif
  29148. #endif
  29149. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  29150. UNIXVFS("unix-afp", afpIoFinder ),
  29151. UNIXVFS("unix-nfs", nfsIoFinder ),
  29152. UNIXVFS("unix-proxy", proxyIoFinder ),
  29153. #endif
  29154. };
  29155. unsigned int i; /* Loop counter */
  29156. /* Double-check that the aSyscall[] array has been constructed
  29157. ** correctly. See ticket [bb3a86e890c8e96ab] */
  29158. assert( ArraySize(aSyscall)==24 );
  29159. /* Register all VFSes defined in the aVfs[] array */
  29160. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  29161. sqlite3_vfs_register(&aVfs[i], i==0);
  29162. }
  29163. return SQLITE_OK;
  29164. }
  29165. /*
  29166. ** Shutdown the operating system interface.
  29167. **
  29168. ** Some operating systems might need to do some cleanup in this routine,
  29169. ** to release dynamically allocated objects. But not on unix.
  29170. ** This routine is a no-op for unix.
  29171. */
  29172. SQLITE_API int sqlite3_os_end(void){
  29173. return SQLITE_OK;
  29174. }
  29175. #endif /* SQLITE_OS_UNIX */
  29176. /************** End of os_unix.c *********************************************/
  29177. /************** Begin file os_win.c ******************************************/
  29178. /*
  29179. ** 2004 May 22
  29180. **
  29181. ** The author disclaims copyright to this source code. In place of
  29182. ** a legal notice, here is a blessing:
  29183. **
  29184. ** May you do good and not evil.
  29185. ** May you find forgiveness for yourself and forgive others.
  29186. ** May you share freely, never taking more than you give.
  29187. **
  29188. ******************************************************************************
  29189. **
  29190. ** This file contains code that is specific to Windows.
  29191. */
  29192. #if SQLITE_OS_WIN /* This file is used for Windows only */
  29193. #ifdef __CYGWIN__
  29194. # include <sys/cygwin.h>
  29195. # include <errno.h> /* amalgamator: keep */
  29196. #endif
  29197. /*
  29198. ** Include code that is common to all os_*.c files
  29199. */
  29200. /************** Include os_common.h in the middle of os_win.c ****************/
  29201. /************** Begin file os_common.h ***************************************/
  29202. /*
  29203. ** 2004 May 22
  29204. **
  29205. ** The author disclaims copyright to this source code. In place of
  29206. ** a legal notice, here is a blessing:
  29207. **
  29208. ** May you do good and not evil.
  29209. ** May you find forgiveness for yourself and forgive others.
  29210. ** May you share freely, never taking more than you give.
  29211. **
  29212. ******************************************************************************
  29213. **
  29214. ** This file contains macros and a little bit of code that is common to
  29215. ** all of the platform-specific files (os_*.c) and is #included into those
  29216. ** files.
  29217. **
  29218. ** This file should be #included by the os_*.c files only. It is not a
  29219. ** general purpose header file.
  29220. */
  29221. #ifndef _OS_COMMON_H_
  29222. #define _OS_COMMON_H_
  29223. /*
  29224. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  29225. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  29226. ** switch. The following code should catch this problem at compile-time.
  29227. */
  29228. #ifdef MEMORY_DEBUG
  29229. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  29230. #endif
  29231. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  29232. # ifndef SQLITE_DEBUG_OS_TRACE
  29233. # define SQLITE_DEBUG_OS_TRACE 0
  29234. # endif
  29235. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  29236. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  29237. #else
  29238. # define OSTRACE(X)
  29239. #endif
  29240. /*
  29241. ** Macros for performance tracing. Normally turned off. Only works
  29242. ** on i486 hardware.
  29243. */
  29244. #ifdef SQLITE_PERFORMANCE_TRACE
  29245. /*
  29246. ** hwtime.h contains inline assembler code for implementing
  29247. ** high-performance timing routines.
  29248. */
  29249. /************** Include hwtime.h in the middle of os_common.h ****************/
  29250. /************** Begin file hwtime.h ******************************************/
  29251. /*
  29252. ** 2008 May 27
  29253. **
  29254. ** The author disclaims copyright to this source code. In place of
  29255. ** a legal notice, here is a blessing:
  29256. **
  29257. ** May you do good and not evil.
  29258. ** May you find forgiveness for yourself and forgive others.
  29259. ** May you share freely, never taking more than you give.
  29260. **
  29261. ******************************************************************************
  29262. **
  29263. ** This file contains inline asm code for retrieving "high-performance"
  29264. ** counters for x86 class CPUs.
  29265. */
  29266. #ifndef _HWTIME_H_
  29267. #define _HWTIME_H_
  29268. /*
  29269. ** The following routine only works on pentium-class (or newer) processors.
  29270. ** It uses the RDTSC opcode to read the cycle count value out of the
  29271. ** processor and returns that value. This can be used for high-res
  29272. ** profiling.
  29273. */
  29274. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  29275. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  29276. #if defined(__GNUC__)
  29277. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29278. unsigned int lo, hi;
  29279. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  29280. return (sqlite_uint64)hi << 32 | lo;
  29281. }
  29282. #elif defined(_MSC_VER)
  29283. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  29284. __asm {
  29285. rdtsc
  29286. ret ; return value at EDX:EAX
  29287. }
  29288. }
  29289. #endif
  29290. #elif (defined(__GNUC__) && defined(__x86_64__))
  29291. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29292. unsigned long val;
  29293. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  29294. return val;
  29295. }
  29296. #elif (defined(__GNUC__) && defined(__ppc__))
  29297. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  29298. unsigned long long retval;
  29299. unsigned long junk;
  29300. __asm__ __volatile__ ("\n\
  29301. 1: mftbu %1\n\
  29302. mftb %L0\n\
  29303. mftbu %0\n\
  29304. cmpw %0,%1\n\
  29305. bne 1b"
  29306. : "=r" (retval), "=r" (junk));
  29307. return retval;
  29308. }
  29309. #else
  29310. #error Need implementation of sqlite3Hwtime() for your platform.
  29311. /*
  29312. ** To compile without implementing sqlite3Hwtime() for your platform,
  29313. ** you can remove the above #error and use the following
  29314. ** stub function. You will lose timing support for many
  29315. ** of the debugging and testing utilities, but it should at
  29316. ** least compile and run.
  29317. */
  29318. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  29319. #endif
  29320. #endif /* !defined(_HWTIME_H_) */
  29321. /************** End of hwtime.h **********************************************/
  29322. /************** Continuing where we left off in os_common.h ******************/
  29323. static sqlite_uint64 g_start;
  29324. static sqlite_uint64 g_elapsed;
  29325. #define TIMER_START g_start=sqlite3Hwtime()
  29326. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  29327. #define TIMER_ELAPSED g_elapsed
  29328. #else
  29329. #define TIMER_START
  29330. #define TIMER_END
  29331. #define TIMER_ELAPSED ((sqlite_uint64)0)
  29332. #endif
  29333. /*
  29334. ** If we compile with the SQLITE_TEST macro set, then the following block
  29335. ** of code will give us the ability to simulate a disk I/O error. This
  29336. ** is used for testing the I/O recovery logic.
  29337. */
  29338. #ifdef SQLITE_TEST
  29339. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  29340. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  29341. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  29342. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  29343. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  29344. SQLITE_API int sqlite3_diskfull_pending = 0;
  29345. SQLITE_API int sqlite3_diskfull = 0;
  29346. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  29347. #define SimulateIOError(CODE) \
  29348. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  29349. || sqlite3_io_error_pending-- == 1 ) \
  29350. { local_ioerr(); CODE; }
  29351. static void local_ioerr(){
  29352. IOTRACE(("IOERR\n"));
  29353. sqlite3_io_error_hit++;
  29354. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  29355. }
  29356. #define SimulateDiskfullError(CODE) \
  29357. if( sqlite3_diskfull_pending ){ \
  29358. if( sqlite3_diskfull_pending == 1 ){ \
  29359. local_ioerr(); \
  29360. sqlite3_diskfull = 1; \
  29361. sqlite3_io_error_hit = 1; \
  29362. CODE; \
  29363. }else{ \
  29364. sqlite3_diskfull_pending--; \
  29365. } \
  29366. }
  29367. #else
  29368. #define SimulateIOErrorBenign(X)
  29369. #define SimulateIOError(A)
  29370. #define SimulateDiskfullError(A)
  29371. #endif
  29372. /*
  29373. ** When testing, keep a count of the number of open files.
  29374. */
  29375. #ifdef SQLITE_TEST
  29376. SQLITE_API int sqlite3_open_file_count = 0;
  29377. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  29378. #else
  29379. #define OpenCounter(X)
  29380. #endif
  29381. #endif /* !defined(_OS_COMMON_H_) */
  29382. /************** End of os_common.h *******************************************/
  29383. /************** Continuing where we left off in os_win.c *********************/
  29384. /*
  29385. ** Compiling and using WAL mode requires several APIs that are only
  29386. ** available in Windows platforms based on the NT kernel.
  29387. */
  29388. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  29389. # error "WAL mode requires support from the Windows NT kernel, compile\
  29390. with SQLITE_OMIT_WAL."
  29391. #endif
  29392. /*
  29393. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  29394. ** based on the sub-platform)?
  29395. */
  29396. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  29397. # define SQLITE_WIN32_HAS_ANSI
  29398. #endif
  29399. /*
  29400. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  29401. ** based on the sub-platform)?
  29402. */
  29403. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  29404. !defined(SQLITE_WIN32_NO_WIDE)
  29405. # define SQLITE_WIN32_HAS_WIDE
  29406. #endif
  29407. /*
  29408. ** Make sure at least one set of Win32 APIs is available.
  29409. */
  29410. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  29411. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  29412. must be defined."
  29413. #endif
  29414. /*
  29415. ** Maximum pathname length (in chars) for Win32. This should normally be
  29416. ** MAX_PATH.
  29417. */
  29418. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  29419. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  29420. #endif
  29421. /*
  29422. ** Maximum pathname length (in chars) for WinNT. This should normally be
  29423. ** 32767.
  29424. */
  29425. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  29426. # define SQLITE_WINNT_MAX_PATH_CHARS (32767)
  29427. #endif
  29428. /*
  29429. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  29430. ** characters, so we allocate 3 bytes per character assuming worst-case of
  29431. ** 4-bytes-per-character for UTF8.
  29432. */
  29433. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  29434. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  29435. #endif
  29436. /*
  29437. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  29438. ** 32767 * sizeof(WCHAR).
  29439. */
  29440. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  29441. # define SQLITE_WINNT_MAX_PATH_BYTES \
  29442. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  29443. #endif
  29444. /*
  29445. ** Maximum error message length (in chars) for WinRT.
  29446. */
  29447. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  29448. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  29449. #endif
  29450. /*
  29451. ** Returns non-zero if the character should be treated as a directory
  29452. ** separator.
  29453. */
  29454. #ifndef winIsDirSep
  29455. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  29456. #endif
  29457. /*
  29458. ** This macro is used when a local variable is set to a value that is
  29459. ** [sometimes] not used by the code (e.g. via conditional compilation).
  29460. */
  29461. #ifndef UNUSED_VARIABLE_VALUE
  29462. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  29463. #endif
  29464. /*
  29465. ** Returns the string that should be used as the directory separator.
  29466. */
  29467. #ifndef winGetDirDep
  29468. # ifdef __CYGWIN__
  29469. # define winGetDirDep() "/"
  29470. # else
  29471. # define winGetDirDep() "\\"
  29472. # endif
  29473. #endif
  29474. /*
  29475. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  29476. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  29477. ** are not present in the header file)?
  29478. */
  29479. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  29480. /*
  29481. ** Two of the file mapping APIs are different under WinRT. Figure out which
  29482. ** set we need.
  29483. */
  29484. #if SQLITE_OS_WINRT
  29485. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  29486. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  29487. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  29488. #else
  29489. #if defined(SQLITE_WIN32_HAS_ANSI)
  29490. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  29491. DWORD, DWORD, DWORD, LPCSTR);
  29492. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  29493. #if defined(SQLITE_WIN32_HAS_WIDE)
  29494. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  29495. DWORD, DWORD, DWORD, LPCWSTR);
  29496. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  29497. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  29498. #endif /* SQLITE_OS_WINRT */
  29499. /*
  29500. ** This file mapping API is common to both Win32 and WinRT.
  29501. */
  29502. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  29503. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  29504. /*
  29505. ** Some Microsoft compilers lack this definition.
  29506. */
  29507. #ifndef INVALID_FILE_ATTRIBUTES
  29508. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  29509. #endif
  29510. #ifndef FILE_FLAG_MASK
  29511. # define FILE_FLAG_MASK (0xFF3C0000)
  29512. #endif
  29513. #ifndef FILE_ATTRIBUTE_MASK
  29514. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  29515. #endif
  29516. #ifndef SQLITE_OMIT_WAL
  29517. /* Forward references to structures used for WAL */
  29518. typedef struct winShm winShm; /* A connection to shared-memory */
  29519. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  29520. #endif
  29521. /*
  29522. ** WinCE lacks native support for file locking so we have to fake it
  29523. ** with some code of our own.
  29524. */
  29525. #if SQLITE_OS_WINCE
  29526. typedef struct winceLock {
  29527. int nReaders; /* Number of reader locks obtained */
  29528. BOOL bPending; /* Indicates a pending lock has been obtained */
  29529. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  29530. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  29531. } winceLock;
  29532. #endif
  29533. /*
  29534. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  29535. ** portability layer.
  29536. */
  29537. typedef struct winFile winFile;
  29538. struct winFile {
  29539. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  29540. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  29541. HANDLE h; /* Handle for accessing the file */
  29542. u8 locktype; /* Type of lock currently held on this file */
  29543. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  29544. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  29545. DWORD lastErrno; /* The Windows errno from the last I/O error */
  29546. #ifndef SQLITE_OMIT_WAL
  29547. winShm *pShm; /* Instance of shared memory on this file */
  29548. #endif
  29549. const char *zPath; /* Full pathname of this file */
  29550. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  29551. #if SQLITE_OS_WINCE
  29552. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  29553. HANDLE hMutex; /* Mutex used to control access to shared lock */
  29554. HANDLE hShared; /* Shared memory segment used for locking */
  29555. winceLock local; /* Locks obtained by this instance of winFile */
  29556. winceLock *shared; /* Global shared lock memory for the file */
  29557. #endif
  29558. #if SQLITE_MAX_MMAP_SIZE>0
  29559. int nFetchOut; /* Number of outstanding xFetch references */
  29560. HANDLE hMap; /* Handle for accessing memory mapping */
  29561. void *pMapRegion; /* Area memory mapped */
  29562. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  29563. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  29564. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  29565. #endif
  29566. };
  29567. /*
  29568. ** Allowed values for winFile.ctrlFlags
  29569. */
  29570. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  29571. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  29572. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  29573. /*
  29574. * The size of the buffer used by sqlite3_win32_write_debug().
  29575. */
  29576. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  29577. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  29578. #endif
  29579. /*
  29580. * The value used with sqlite3_win32_set_directory() to specify that
  29581. * the data directory should be changed.
  29582. */
  29583. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  29584. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  29585. #endif
  29586. /*
  29587. * The value used with sqlite3_win32_set_directory() to specify that
  29588. * the temporary directory should be changed.
  29589. */
  29590. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  29591. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  29592. #endif
  29593. /*
  29594. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  29595. * various Win32 API heap functions instead of our own.
  29596. */
  29597. #ifdef SQLITE_WIN32_MALLOC
  29598. /*
  29599. * If this is non-zero, an isolated heap will be created by the native Win32
  29600. * allocator subsystem; otherwise, the default process heap will be used. This
  29601. * setting has no effect when compiling for WinRT. By default, this is enabled
  29602. * and an isolated heap will be created to store all allocated data.
  29603. *
  29604. ******************************************************************************
  29605. * WARNING: It is important to note that when this setting is non-zero and the
  29606. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  29607. * function), all data that was allocated using the isolated heap will
  29608. * be freed immediately and any attempt to access any of that freed
  29609. * data will almost certainly result in an immediate access violation.
  29610. ******************************************************************************
  29611. */
  29612. #ifndef SQLITE_WIN32_HEAP_CREATE
  29613. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  29614. #endif
  29615. /*
  29616. * The initial size of the Win32-specific heap. This value may be zero.
  29617. */
  29618. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  29619. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  29620. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  29621. #endif
  29622. /*
  29623. * The maximum size of the Win32-specific heap. This value may be zero.
  29624. */
  29625. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  29626. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  29627. #endif
  29628. /*
  29629. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  29630. * zero for the default behavior.
  29631. */
  29632. #ifndef SQLITE_WIN32_HEAP_FLAGS
  29633. # define SQLITE_WIN32_HEAP_FLAGS (0)
  29634. #endif
  29635. /*
  29636. ** The winMemData structure stores information required by the Win32-specific
  29637. ** sqlite3_mem_methods implementation.
  29638. */
  29639. typedef struct winMemData winMemData;
  29640. struct winMemData {
  29641. #ifndef NDEBUG
  29642. u32 magic; /* Magic number to detect structure corruption. */
  29643. #endif
  29644. HANDLE hHeap; /* The handle to our heap. */
  29645. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  29646. };
  29647. #ifndef NDEBUG
  29648. #define WINMEM_MAGIC 0x42b2830b
  29649. #endif
  29650. static struct winMemData win_mem_data = {
  29651. #ifndef NDEBUG
  29652. WINMEM_MAGIC,
  29653. #endif
  29654. NULL, FALSE
  29655. };
  29656. #ifndef NDEBUG
  29657. #define winMemAssertMagic() assert( win_mem_data.magic==WINMEM_MAGIC )
  29658. #else
  29659. #define winMemAssertMagic()
  29660. #endif
  29661. #define winMemGetHeap() win_mem_data.hHeap
  29662. static void *winMemMalloc(int nBytes);
  29663. static void winMemFree(void *pPrior);
  29664. static void *winMemRealloc(void *pPrior, int nBytes);
  29665. static int winMemSize(void *p);
  29666. static int winMemRoundup(int n);
  29667. static int winMemInit(void *pAppData);
  29668. static void winMemShutdown(void *pAppData);
  29669. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  29670. #endif /* SQLITE_WIN32_MALLOC */
  29671. /*
  29672. ** The following variable is (normally) set once and never changes
  29673. ** thereafter. It records whether the operating system is Win9x
  29674. ** or WinNT.
  29675. **
  29676. ** 0: Operating system unknown.
  29677. ** 1: Operating system is Win9x.
  29678. ** 2: Operating system is WinNT.
  29679. **
  29680. ** In order to facilitate testing on a WinNT system, the test fixture
  29681. ** can manually set this value to 1 to emulate Win98 behavior.
  29682. */
  29683. #ifdef SQLITE_TEST
  29684. SQLITE_API int sqlite3_os_type = 0;
  29685. #elif !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  29686. defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_HAS_WIDE)
  29687. static int sqlite3_os_type = 0;
  29688. #endif
  29689. #ifndef SYSCALL
  29690. # define SYSCALL sqlite3_syscall_ptr
  29691. #endif
  29692. /*
  29693. ** This function is not available on Windows CE or WinRT.
  29694. */
  29695. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  29696. # define osAreFileApisANSI() 1
  29697. #endif
  29698. /*
  29699. ** Many system calls are accessed through pointer-to-functions so that
  29700. ** they may be overridden at runtime to facilitate fault injection during
  29701. ** testing and sandboxing. The following array holds the names and pointers
  29702. ** to all overrideable system calls.
  29703. */
  29704. static struct win_syscall {
  29705. const char *zName; /* Name of the system call */
  29706. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  29707. sqlite3_syscall_ptr pDefault; /* Default value */
  29708. } aSyscall[] = {
  29709. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29710. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  29711. #else
  29712. { "AreFileApisANSI", (SYSCALL)0, 0 },
  29713. #endif
  29714. #ifndef osAreFileApisANSI
  29715. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  29716. #endif
  29717. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29718. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  29719. #else
  29720. { "CharLowerW", (SYSCALL)0, 0 },
  29721. #endif
  29722. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  29723. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  29724. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  29725. #else
  29726. { "CharUpperW", (SYSCALL)0, 0 },
  29727. #endif
  29728. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  29729. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  29730. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  29731. #if defined(SQLITE_WIN32_HAS_ANSI)
  29732. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  29733. #else
  29734. { "CreateFileA", (SYSCALL)0, 0 },
  29735. #endif
  29736. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  29737. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  29738. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29739. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  29740. #else
  29741. { "CreateFileW", (SYSCALL)0, 0 },
  29742. #endif
  29743. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  29744. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  29745. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  29746. !defined(SQLITE_OMIT_WAL))
  29747. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  29748. #else
  29749. { "CreateFileMappingA", (SYSCALL)0, 0 },
  29750. #endif
  29751. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29752. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  29753. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29754. !defined(SQLITE_OMIT_WAL))
  29755. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  29756. #else
  29757. { "CreateFileMappingW", (SYSCALL)0, 0 },
  29758. #endif
  29759. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  29760. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  29761. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29762. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  29763. #else
  29764. { "CreateMutexW", (SYSCALL)0, 0 },
  29765. #endif
  29766. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  29767. LPCWSTR))aSyscall[8].pCurrent)
  29768. #if defined(SQLITE_WIN32_HAS_ANSI)
  29769. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  29770. #else
  29771. { "DeleteFileA", (SYSCALL)0, 0 },
  29772. #endif
  29773. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  29774. #if defined(SQLITE_WIN32_HAS_WIDE)
  29775. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  29776. #else
  29777. { "DeleteFileW", (SYSCALL)0, 0 },
  29778. #endif
  29779. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  29780. #if SQLITE_OS_WINCE
  29781. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  29782. #else
  29783. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  29784. #endif
  29785. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29786. LPFILETIME))aSyscall[11].pCurrent)
  29787. #if SQLITE_OS_WINCE
  29788. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  29789. #else
  29790. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  29791. #endif
  29792. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  29793. LPSYSTEMTIME))aSyscall[12].pCurrent)
  29794. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  29795. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  29796. #if defined(SQLITE_WIN32_HAS_ANSI)
  29797. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  29798. #else
  29799. { "FormatMessageA", (SYSCALL)0, 0 },
  29800. #endif
  29801. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  29802. DWORD,va_list*))aSyscall[14].pCurrent)
  29803. #if defined(SQLITE_WIN32_HAS_WIDE)
  29804. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  29805. #else
  29806. { "FormatMessageW", (SYSCALL)0, 0 },
  29807. #endif
  29808. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  29809. DWORD,va_list*))aSyscall[15].pCurrent)
  29810. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29811. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  29812. #else
  29813. { "FreeLibrary", (SYSCALL)0, 0 },
  29814. #endif
  29815. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  29816. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  29817. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  29818. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29819. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  29820. #else
  29821. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  29822. #endif
  29823. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  29824. LPDWORD))aSyscall[18].pCurrent)
  29825. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29826. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  29827. #else
  29828. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  29829. #endif
  29830. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  29831. LPDWORD))aSyscall[19].pCurrent)
  29832. #if defined(SQLITE_WIN32_HAS_ANSI)
  29833. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  29834. #else
  29835. { "GetFileAttributesA", (SYSCALL)0, 0 },
  29836. #endif
  29837. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  29838. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29839. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  29840. #else
  29841. { "GetFileAttributesW", (SYSCALL)0, 0 },
  29842. #endif
  29843. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  29844. #if defined(SQLITE_WIN32_HAS_WIDE)
  29845. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  29846. #else
  29847. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  29848. #endif
  29849. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  29850. LPVOID))aSyscall[22].pCurrent)
  29851. #if !SQLITE_OS_WINRT
  29852. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  29853. #else
  29854. { "GetFileSize", (SYSCALL)0, 0 },
  29855. #endif
  29856. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  29857. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  29858. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  29859. #else
  29860. { "GetFullPathNameA", (SYSCALL)0, 0 },
  29861. #endif
  29862. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  29863. LPSTR*))aSyscall[24].pCurrent)
  29864. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29865. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  29866. #else
  29867. { "GetFullPathNameW", (SYSCALL)0, 0 },
  29868. #endif
  29869. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  29870. LPWSTR*))aSyscall[25].pCurrent)
  29871. { "GetLastError", (SYSCALL)GetLastError, 0 },
  29872. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  29873. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29874. #if SQLITE_OS_WINCE
  29875. /* The GetProcAddressA() routine is only available on Windows CE. */
  29876. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  29877. #else
  29878. /* All other Windows platforms expect GetProcAddress() to take
  29879. ** an ANSI string regardless of the _UNICODE setting */
  29880. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  29881. #endif
  29882. #else
  29883. { "GetProcAddressA", (SYSCALL)0, 0 },
  29884. #endif
  29885. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  29886. LPCSTR))aSyscall[27].pCurrent)
  29887. #if !SQLITE_OS_WINRT
  29888. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  29889. #else
  29890. { "GetSystemInfo", (SYSCALL)0, 0 },
  29891. #endif
  29892. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  29893. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  29894. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  29895. #if !SQLITE_OS_WINCE
  29896. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  29897. #else
  29898. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  29899. #endif
  29900. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  29901. LPFILETIME))aSyscall[30].pCurrent)
  29902. #if defined(SQLITE_WIN32_HAS_ANSI)
  29903. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  29904. #else
  29905. { "GetTempPathA", (SYSCALL)0, 0 },
  29906. #endif
  29907. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  29908. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29909. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  29910. #else
  29911. { "GetTempPathW", (SYSCALL)0, 0 },
  29912. #endif
  29913. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  29914. #if !SQLITE_OS_WINRT
  29915. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  29916. #else
  29917. { "GetTickCount", (SYSCALL)0, 0 },
  29918. #endif
  29919. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  29920. #if defined(SQLITE_WIN32_HAS_ANSI)
  29921. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  29922. #else
  29923. { "GetVersionExA", (SYSCALL)0, 0 },
  29924. #endif
  29925. #define osGetVersionExA ((BOOL(WINAPI*)( \
  29926. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  29927. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  29928. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  29929. #else
  29930. { "GetVersionExW", (SYSCALL)0, 0 },
  29931. #endif
  29932. #define osGetVersionExW ((BOOL(WINAPI*)( \
  29933. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  29934. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  29935. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  29936. SIZE_T))aSyscall[36].pCurrent)
  29937. #if !SQLITE_OS_WINRT
  29938. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  29939. #else
  29940. { "HeapCreate", (SYSCALL)0, 0 },
  29941. #endif
  29942. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  29943. SIZE_T))aSyscall[37].pCurrent)
  29944. #if !SQLITE_OS_WINRT
  29945. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  29946. #else
  29947. { "HeapDestroy", (SYSCALL)0, 0 },
  29948. #endif
  29949. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  29950. { "HeapFree", (SYSCALL)HeapFree, 0 },
  29951. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  29952. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  29953. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  29954. SIZE_T))aSyscall[40].pCurrent)
  29955. { "HeapSize", (SYSCALL)HeapSize, 0 },
  29956. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  29957. LPCVOID))aSyscall[41].pCurrent)
  29958. #if !SQLITE_OS_WINRT
  29959. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  29960. #else
  29961. { "HeapValidate", (SYSCALL)0, 0 },
  29962. #endif
  29963. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  29964. LPCVOID))aSyscall[42].pCurrent)
  29965. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29966. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  29967. #else
  29968. { "LoadLibraryA", (SYSCALL)0, 0 },
  29969. #endif
  29970. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[43].pCurrent)
  29971. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  29972. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  29973. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  29974. #else
  29975. { "LoadLibraryW", (SYSCALL)0, 0 },
  29976. #endif
  29977. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[44].pCurrent)
  29978. #if !SQLITE_OS_WINRT
  29979. { "LocalFree", (SYSCALL)LocalFree, 0 },
  29980. #else
  29981. { "LocalFree", (SYSCALL)0, 0 },
  29982. #endif
  29983. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[45].pCurrent)
  29984. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  29985. { "LockFile", (SYSCALL)LockFile, 0 },
  29986. #else
  29987. { "LockFile", (SYSCALL)0, 0 },
  29988. #endif
  29989. #ifndef osLockFile
  29990. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  29991. DWORD))aSyscall[46].pCurrent)
  29992. #endif
  29993. #if !SQLITE_OS_WINCE
  29994. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  29995. #else
  29996. { "LockFileEx", (SYSCALL)0, 0 },
  29997. #endif
  29998. #ifndef osLockFileEx
  29999. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  30000. LPOVERLAPPED))aSyscall[47].pCurrent)
  30001. #endif
  30002. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  30003. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  30004. #else
  30005. { "MapViewOfFile", (SYSCALL)0, 0 },
  30006. #endif
  30007. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30008. SIZE_T))aSyscall[48].pCurrent)
  30009. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  30010. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  30011. int))aSyscall[49].pCurrent)
  30012. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  30013. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  30014. LARGE_INTEGER*))aSyscall[50].pCurrent)
  30015. { "ReadFile", (SYSCALL)ReadFile, 0 },
  30016. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  30017. LPOVERLAPPED))aSyscall[51].pCurrent)
  30018. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  30019. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[52].pCurrent)
  30020. #if !SQLITE_OS_WINRT
  30021. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  30022. #else
  30023. { "SetFilePointer", (SYSCALL)0, 0 },
  30024. #endif
  30025. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  30026. DWORD))aSyscall[53].pCurrent)
  30027. #if !SQLITE_OS_WINRT
  30028. { "Sleep", (SYSCALL)Sleep, 0 },
  30029. #else
  30030. { "Sleep", (SYSCALL)0, 0 },
  30031. #endif
  30032. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[54].pCurrent)
  30033. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  30034. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  30035. LPFILETIME))aSyscall[55].pCurrent)
  30036. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  30037. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  30038. #else
  30039. { "UnlockFile", (SYSCALL)0, 0 },
  30040. #endif
  30041. #ifndef osUnlockFile
  30042. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30043. DWORD))aSyscall[56].pCurrent)
  30044. #endif
  30045. #if !SQLITE_OS_WINCE
  30046. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  30047. #else
  30048. { "UnlockFileEx", (SYSCALL)0, 0 },
  30049. #endif
  30050. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  30051. LPOVERLAPPED))aSyscall[57].pCurrent)
  30052. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  30053. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  30054. #else
  30055. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  30056. #endif
  30057. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[58].pCurrent)
  30058. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  30059. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  30060. LPCSTR,LPBOOL))aSyscall[59].pCurrent)
  30061. { "WriteFile", (SYSCALL)WriteFile, 0 },
  30062. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  30063. LPOVERLAPPED))aSyscall[60].pCurrent)
  30064. #if SQLITE_OS_WINRT
  30065. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  30066. #else
  30067. { "CreateEventExW", (SYSCALL)0, 0 },
  30068. #endif
  30069. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  30070. DWORD,DWORD))aSyscall[61].pCurrent)
  30071. #if !SQLITE_OS_WINRT
  30072. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  30073. #else
  30074. { "WaitForSingleObject", (SYSCALL)0, 0 },
  30075. #endif
  30076. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  30077. DWORD))aSyscall[62].pCurrent)
  30078. #if SQLITE_OS_WINRT
  30079. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  30080. #else
  30081. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  30082. #endif
  30083. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  30084. BOOL))aSyscall[63].pCurrent)
  30085. #if SQLITE_OS_WINRT
  30086. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  30087. #else
  30088. { "SetFilePointerEx", (SYSCALL)0, 0 },
  30089. #endif
  30090. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  30091. PLARGE_INTEGER,DWORD))aSyscall[64].pCurrent)
  30092. #if SQLITE_OS_WINRT
  30093. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  30094. #else
  30095. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  30096. #endif
  30097. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  30098. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[65].pCurrent)
  30099. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  30100. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  30101. #else
  30102. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  30103. #endif
  30104. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  30105. SIZE_T))aSyscall[66].pCurrent)
  30106. #if SQLITE_OS_WINRT
  30107. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  30108. #else
  30109. { "CreateFile2", (SYSCALL)0, 0 },
  30110. #endif
  30111. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  30112. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[67].pCurrent)
  30113. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  30114. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  30115. #else
  30116. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  30117. #endif
  30118. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  30119. DWORD))aSyscall[68].pCurrent)
  30120. #if SQLITE_OS_WINRT
  30121. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  30122. #else
  30123. { "GetTickCount64", (SYSCALL)0, 0 },
  30124. #endif
  30125. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[69].pCurrent)
  30126. #if SQLITE_OS_WINRT
  30127. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  30128. #else
  30129. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  30130. #endif
  30131. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  30132. LPSYSTEM_INFO))aSyscall[70].pCurrent)
  30133. #if defined(SQLITE_WIN32_HAS_ANSI)
  30134. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  30135. #else
  30136. { "OutputDebugStringA", (SYSCALL)0, 0 },
  30137. #endif
  30138. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[71].pCurrent)
  30139. #if defined(SQLITE_WIN32_HAS_WIDE)
  30140. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  30141. #else
  30142. { "OutputDebugStringW", (SYSCALL)0, 0 },
  30143. #endif
  30144. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[72].pCurrent)
  30145. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  30146. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[73].pCurrent)
  30147. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  30148. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  30149. #else
  30150. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  30151. #endif
  30152. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  30153. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[74].pCurrent)
  30154. }; /* End of the overrideable system calls */
  30155. /*
  30156. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  30157. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  30158. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  30159. ** system call named zName.
  30160. */
  30161. static int winSetSystemCall(
  30162. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  30163. const char *zName, /* Name of system call to override */
  30164. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  30165. ){
  30166. unsigned int i;
  30167. int rc = SQLITE_NOTFOUND;
  30168. UNUSED_PARAMETER(pNotUsed);
  30169. if( zName==0 ){
  30170. /* If no zName is given, restore all system calls to their default
  30171. ** settings and return NULL
  30172. */
  30173. rc = SQLITE_OK;
  30174. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30175. if( aSyscall[i].pDefault ){
  30176. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  30177. }
  30178. }
  30179. }else{
  30180. /* If zName is specified, operate on only the one system call
  30181. ** specified.
  30182. */
  30183. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30184. if( strcmp(zName, aSyscall[i].zName)==0 ){
  30185. if( aSyscall[i].pDefault==0 ){
  30186. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  30187. }
  30188. rc = SQLITE_OK;
  30189. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  30190. aSyscall[i].pCurrent = pNewFunc;
  30191. break;
  30192. }
  30193. }
  30194. }
  30195. return rc;
  30196. }
  30197. /*
  30198. ** Return the value of a system call. Return NULL if zName is not a
  30199. ** recognized system call name. NULL is also returned if the system call
  30200. ** is currently undefined.
  30201. */
  30202. static sqlite3_syscall_ptr winGetSystemCall(
  30203. sqlite3_vfs *pNotUsed,
  30204. const char *zName
  30205. ){
  30206. unsigned int i;
  30207. UNUSED_PARAMETER(pNotUsed);
  30208. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  30209. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  30210. }
  30211. return 0;
  30212. }
  30213. /*
  30214. ** Return the name of the first system call after zName. If zName==NULL
  30215. ** then return the name of the first system call. Return NULL if zName
  30216. ** is the last system call or if zName is not the name of a valid
  30217. ** system call.
  30218. */
  30219. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  30220. int i = -1;
  30221. UNUSED_PARAMETER(p);
  30222. if( zName ){
  30223. for(i=0; i<ArraySize(aSyscall)-1; i++){
  30224. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  30225. }
  30226. }
  30227. for(i++; i<ArraySize(aSyscall); i++){
  30228. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  30229. }
  30230. return 0;
  30231. }
  30232. /*
  30233. ** This function outputs the specified (ANSI) string to the Win32 debugger
  30234. ** (if available).
  30235. */
  30236. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  30237. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  30238. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  30239. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  30240. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  30241. #if defined(SQLITE_WIN32_HAS_ANSI)
  30242. if( nMin>0 ){
  30243. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30244. memcpy(zDbgBuf, zBuf, nMin);
  30245. osOutputDebugStringA(zDbgBuf);
  30246. }else{
  30247. osOutputDebugStringA(zBuf);
  30248. }
  30249. #elif defined(SQLITE_WIN32_HAS_WIDE)
  30250. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30251. if ( osMultiByteToWideChar(
  30252. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  30253. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  30254. return;
  30255. }
  30256. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  30257. #else
  30258. if( nMin>0 ){
  30259. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  30260. memcpy(zDbgBuf, zBuf, nMin);
  30261. fprintf(stderr, "%s", zDbgBuf);
  30262. }else{
  30263. fprintf(stderr, "%s", zBuf);
  30264. }
  30265. #endif
  30266. }
  30267. /*
  30268. ** The following routine suspends the current thread for at least ms
  30269. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  30270. */
  30271. #if SQLITE_OS_WINRT
  30272. static HANDLE sleepObj = NULL;
  30273. #endif
  30274. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  30275. #if SQLITE_OS_WINRT
  30276. if ( sleepObj==NULL ){
  30277. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  30278. SYNCHRONIZE);
  30279. }
  30280. assert( sleepObj!=NULL );
  30281. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  30282. #else
  30283. osSleep(milliseconds);
  30284. #endif
  30285. }
  30286. /*
  30287. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  30288. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  30289. **
  30290. ** Here is an interesting observation: Win95, Win98, and WinME lack
  30291. ** the LockFileEx() API. But we can still statically link against that
  30292. ** API as long as we don't call it when running Win95/98/ME. A call to
  30293. ** this routine is used to determine if the host is Win95/98/ME or
  30294. ** WinNT/2K/XP so that we will know whether or not we can safely call
  30295. ** the LockFileEx() API.
  30296. */
  30297. #ifndef NTDDI_WIN8
  30298. # define NTDDI_WIN8 0x06020000
  30299. #endif
  30300. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  30301. # define osIsNT() (1)
  30302. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  30303. # define osIsNT() (0)
  30304. #else
  30305. static int osIsNT(void){
  30306. if( sqlite3_os_type==0 ){
  30307. #if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WIN8
  30308. OSVERSIONINFOW sInfo;
  30309. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  30310. osGetVersionExW(&sInfo);
  30311. #else
  30312. OSVERSIONINFOA sInfo;
  30313. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  30314. osGetVersionExA(&sInfo);
  30315. #endif
  30316. sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  30317. }
  30318. return sqlite3_os_type==2;
  30319. }
  30320. #endif
  30321. #ifdef SQLITE_WIN32_MALLOC
  30322. /*
  30323. ** Allocate nBytes of memory.
  30324. */
  30325. static void *winMemMalloc(int nBytes){
  30326. HANDLE hHeap;
  30327. void *p;
  30328. winMemAssertMagic();
  30329. hHeap = winMemGetHeap();
  30330. assert( hHeap!=0 );
  30331. assert( hHeap!=INVALID_HANDLE_VALUE );
  30332. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30333. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30334. #endif
  30335. assert( nBytes>=0 );
  30336. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  30337. if( !p ){
  30338. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  30339. nBytes, osGetLastError(), (void*)hHeap);
  30340. }
  30341. return p;
  30342. }
  30343. /*
  30344. ** Free memory.
  30345. */
  30346. static void winMemFree(void *pPrior){
  30347. HANDLE hHeap;
  30348. winMemAssertMagic();
  30349. hHeap = winMemGetHeap();
  30350. assert( hHeap!=0 );
  30351. assert( hHeap!=INVALID_HANDLE_VALUE );
  30352. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30353. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30354. #endif
  30355. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  30356. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  30357. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  30358. pPrior, osGetLastError(), (void*)hHeap);
  30359. }
  30360. }
  30361. /*
  30362. ** Change the size of an existing memory allocation
  30363. */
  30364. static void *winMemRealloc(void *pPrior, int nBytes){
  30365. HANDLE hHeap;
  30366. void *p;
  30367. winMemAssertMagic();
  30368. hHeap = winMemGetHeap();
  30369. assert( hHeap!=0 );
  30370. assert( hHeap!=INVALID_HANDLE_VALUE );
  30371. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30372. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  30373. #endif
  30374. assert( nBytes>=0 );
  30375. if( !pPrior ){
  30376. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  30377. }else{
  30378. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  30379. }
  30380. if( !p ){
  30381. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  30382. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  30383. (void*)hHeap);
  30384. }
  30385. return p;
  30386. }
  30387. /*
  30388. ** Return the size of an outstanding allocation, in bytes.
  30389. */
  30390. static int winMemSize(void *p){
  30391. HANDLE hHeap;
  30392. SIZE_T n;
  30393. winMemAssertMagic();
  30394. hHeap = winMemGetHeap();
  30395. assert( hHeap!=0 );
  30396. assert( hHeap!=INVALID_HANDLE_VALUE );
  30397. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30398. assert ( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30399. #endif
  30400. if( !p ) return 0;
  30401. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  30402. if( n==(SIZE_T)-1 ){
  30403. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  30404. p, osGetLastError(), (void*)hHeap);
  30405. return 0;
  30406. }
  30407. return (int)n;
  30408. }
  30409. /*
  30410. ** Round up a request size to the next valid allocation size.
  30411. */
  30412. static int winMemRoundup(int n){
  30413. return n;
  30414. }
  30415. /*
  30416. ** Initialize this module.
  30417. */
  30418. static int winMemInit(void *pAppData){
  30419. winMemData *pWinMemData = (winMemData *)pAppData;
  30420. if( !pWinMemData ) return SQLITE_ERROR;
  30421. assert( pWinMemData->magic==WINMEM_MAGIC );
  30422. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  30423. if( !pWinMemData->hHeap ){
  30424. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  30425. SQLITE_WIN32_HEAP_INIT_SIZE,
  30426. SQLITE_WIN32_HEAP_MAX_SIZE);
  30427. if( !pWinMemData->hHeap ){
  30428. sqlite3_log(SQLITE_NOMEM,
  30429. "failed to HeapCreate (%lu), flags=%u, initSize=%u, maxSize=%u",
  30430. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS,
  30431. SQLITE_WIN32_HEAP_INIT_SIZE, SQLITE_WIN32_HEAP_MAX_SIZE);
  30432. return SQLITE_NOMEM;
  30433. }
  30434. pWinMemData->bOwned = TRUE;
  30435. assert( pWinMemData->bOwned );
  30436. }
  30437. #else
  30438. pWinMemData->hHeap = osGetProcessHeap();
  30439. if( !pWinMemData->hHeap ){
  30440. sqlite3_log(SQLITE_NOMEM,
  30441. "failed to GetProcessHeap (%lu)", osGetLastError());
  30442. return SQLITE_NOMEM;
  30443. }
  30444. pWinMemData->bOwned = FALSE;
  30445. assert( !pWinMemData->bOwned );
  30446. #endif
  30447. assert( pWinMemData->hHeap!=0 );
  30448. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30449. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30450. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30451. #endif
  30452. return SQLITE_OK;
  30453. }
  30454. /*
  30455. ** Deinitialize this module.
  30456. */
  30457. static void winMemShutdown(void *pAppData){
  30458. winMemData *pWinMemData = (winMemData *)pAppData;
  30459. if( !pWinMemData ) return;
  30460. if( pWinMemData->hHeap ){
  30461. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  30462. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  30463. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  30464. #endif
  30465. if( pWinMemData->bOwned ){
  30466. if( !osHeapDestroy(pWinMemData->hHeap) ){
  30467. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  30468. osGetLastError(), (void*)pWinMemData->hHeap);
  30469. }
  30470. pWinMemData->bOwned = FALSE;
  30471. }
  30472. pWinMemData->hHeap = NULL;
  30473. }
  30474. }
  30475. /*
  30476. ** Populate the low-level memory allocation function pointers in
  30477. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  30478. ** arguments specify the block of memory to manage.
  30479. **
  30480. ** This routine is only called by sqlite3_config(), and therefore
  30481. ** is not required to be threadsafe (it is not).
  30482. */
  30483. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  30484. static const sqlite3_mem_methods winMemMethods = {
  30485. winMemMalloc,
  30486. winMemFree,
  30487. winMemRealloc,
  30488. winMemSize,
  30489. winMemRoundup,
  30490. winMemInit,
  30491. winMemShutdown,
  30492. &win_mem_data
  30493. };
  30494. return &winMemMethods;
  30495. }
  30496. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  30497. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  30498. }
  30499. #endif /* SQLITE_WIN32_MALLOC */
  30500. /*
  30501. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  30502. **
  30503. ** Space to hold the returned string is obtained from malloc.
  30504. */
  30505. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  30506. int nChar;
  30507. LPWSTR zWideFilename;
  30508. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  30509. if( nChar==0 ){
  30510. return 0;
  30511. }
  30512. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  30513. if( zWideFilename==0 ){
  30514. return 0;
  30515. }
  30516. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  30517. nChar);
  30518. if( nChar==0 ){
  30519. sqlite3_free(zWideFilename);
  30520. zWideFilename = 0;
  30521. }
  30522. return zWideFilename;
  30523. }
  30524. /*
  30525. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  30526. ** obtained from sqlite3_malloc().
  30527. */
  30528. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  30529. int nByte;
  30530. char *zFilename;
  30531. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  30532. if( nByte == 0 ){
  30533. return 0;
  30534. }
  30535. zFilename = sqlite3MallocZero( nByte );
  30536. if( zFilename==0 ){
  30537. return 0;
  30538. }
  30539. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  30540. 0, 0);
  30541. if( nByte == 0 ){
  30542. sqlite3_free(zFilename);
  30543. zFilename = 0;
  30544. }
  30545. return zFilename;
  30546. }
  30547. /*
  30548. ** Convert an ANSI string to Microsoft Unicode, based on the
  30549. ** current codepage settings for file apis.
  30550. **
  30551. ** Space to hold the returned string is obtained
  30552. ** from sqlite3_malloc.
  30553. */
  30554. static LPWSTR winMbcsToUnicode(const char *zFilename){
  30555. int nByte;
  30556. LPWSTR zMbcsFilename;
  30557. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30558. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  30559. 0)*sizeof(WCHAR);
  30560. if( nByte==0 ){
  30561. return 0;
  30562. }
  30563. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  30564. if( zMbcsFilename==0 ){
  30565. return 0;
  30566. }
  30567. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  30568. nByte);
  30569. if( nByte==0 ){
  30570. sqlite3_free(zMbcsFilename);
  30571. zMbcsFilename = 0;
  30572. }
  30573. return zMbcsFilename;
  30574. }
  30575. /*
  30576. ** Convert Microsoft Unicode to multi-byte character string, based on the
  30577. ** user's ANSI codepage.
  30578. **
  30579. ** Space to hold the returned string is obtained from
  30580. ** sqlite3_malloc().
  30581. */
  30582. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  30583. int nByte;
  30584. char *zFilename;
  30585. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  30586. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  30587. if( nByte == 0 ){
  30588. return 0;
  30589. }
  30590. zFilename = sqlite3MallocZero( nByte );
  30591. if( zFilename==0 ){
  30592. return 0;
  30593. }
  30594. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  30595. nByte, 0, 0);
  30596. if( nByte == 0 ){
  30597. sqlite3_free(zFilename);
  30598. zFilename = 0;
  30599. }
  30600. return zFilename;
  30601. }
  30602. /*
  30603. ** Convert multibyte character string to UTF-8. Space to hold the
  30604. ** returned string is obtained from sqlite3_malloc().
  30605. */
  30606. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  30607. char *zFilenameUtf8;
  30608. LPWSTR zTmpWide;
  30609. zTmpWide = winMbcsToUnicode(zFilename);
  30610. if( zTmpWide==0 ){
  30611. return 0;
  30612. }
  30613. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  30614. sqlite3_free(zTmpWide);
  30615. return zFilenameUtf8;
  30616. }
  30617. /*
  30618. ** Convert UTF-8 to multibyte character string. Space to hold the
  30619. ** returned string is obtained from sqlite3_malloc().
  30620. */
  30621. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  30622. char *zFilenameMbcs;
  30623. LPWSTR zTmpWide;
  30624. zTmpWide = winUtf8ToUnicode(zFilename);
  30625. if( zTmpWide==0 ){
  30626. return 0;
  30627. }
  30628. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  30629. sqlite3_free(zTmpWide);
  30630. return zFilenameMbcs;
  30631. }
  30632. /*
  30633. ** This function sets the data directory or the temporary directory based on
  30634. ** the provided arguments. The type argument must be 1 in order to set the
  30635. ** data directory or 2 in order to set the temporary directory. The zValue
  30636. ** argument is the name of the directory to use. The return value will be
  30637. ** SQLITE_OK if successful.
  30638. */
  30639. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  30640. char **ppDirectory = 0;
  30641. #ifndef SQLITE_OMIT_AUTOINIT
  30642. int rc = sqlite3_initialize();
  30643. if( rc ) return rc;
  30644. #endif
  30645. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  30646. ppDirectory = &sqlite3_data_directory;
  30647. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  30648. ppDirectory = &sqlite3_temp_directory;
  30649. }
  30650. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30651. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30652. );
  30653. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  30654. if( ppDirectory ){
  30655. char *zValueUtf8 = 0;
  30656. if( zValue && zValue[0] ){
  30657. zValueUtf8 = winUnicodeToUtf8(zValue);
  30658. if ( zValueUtf8==0 ){
  30659. return SQLITE_NOMEM;
  30660. }
  30661. }
  30662. sqlite3_free(*ppDirectory);
  30663. *ppDirectory = zValueUtf8;
  30664. return SQLITE_OK;
  30665. }
  30666. return SQLITE_ERROR;
  30667. }
  30668. /*
  30669. ** The return value of winGetLastErrorMsg
  30670. ** is zero if the error message fits in the buffer, or non-zero
  30671. ** otherwise (if the message was truncated).
  30672. */
  30673. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  30674. /* FormatMessage returns 0 on failure. Otherwise it
  30675. ** returns the number of TCHARs written to the output
  30676. ** buffer, excluding the terminating null char.
  30677. */
  30678. DWORD dwLen = 0;
  30679. char *zOut = 0;
  30680. if( osIsNT() ){
  30681. #if SQLITE_OS_WINRT
  30682. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  30683. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  30684. FORMAT_MESSAGE_IGNORE_INSERTS,
  30685. NULL,
  30686. lastErrno,
  30687. 0,
  30688. zTempWide,
  30689. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  30690. 0);
  30691. #else
  30692. LPWSTR zTempWide = NULL;
  30693. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30694. FORMAT_MESSAGE_FROM_SYSTEM |
  30695. FORMAT_MESSAGE_IGNORE_INSERTS,
  30696. NULL,
  30697. lastErrno,
  30698. 0,
  30699. (LPWSTR) &zTempWide,
  30700. 0,
  30701. 0);
  30702. #endif
  30703. if( dwLen > 0 ){
  30704. /* allocate a buffer and convert to UTF8 */
  30705. sqlite3BeginBenignMalloc();
  30706. zOut = winUnicodeToUtf8(zTempWide);
  30707. sqlite3EndBenignMalloc();
  30708. #if !SQLITE_OS_WINRT
  30709. /* free the system buffer allocated by FormatMessage */
  30710. osLocalFree(zTempWide);
  30711. #endif
  30712. }
  30713. }
  30714. #ifdef SQLITE_WIN32_HAS_ANSI
  30715. else{
  30716. char *zTemp = NULL;
  30717. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  30718. FORMAT_MESSAGE_FROM_SYSTEM |
  30719. FORMAT_MESSAGE_IGNORE_INSERTS,
  30720. NULL,
  30721. lastErrno,
  30722. 0,
  30723. (LPSTR) &zTemp,
  30724. 0,
  30725. 0);
  30726. if( dwLen > 0 ){
  30727. /* allocate a buffer and convert to UTF8 */
  30728. sqlite3BeginBenignMalloc();
  30729. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  30730. sqlite3EndBenignMalloc();
  30731. /* free the system buffer allocated by FormatMessage */
  30732. osLocalFree(zTemp);
  30733. }
  30734. }
  30735. #endif
  30736. if( 0 == dwLen ){
  30737. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  30738. }else{
  30739. /* copy a maximum of nBuf chars to output buffer */
  30740. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  30741. /* free the UTF8 buffer */
  30742. sqlite3_free(zOut);
  30743. }
  30744. return 0;
  30745. }
  30746. /*
  30747. **
  30748. ** This function - winLogErrorAtLine() - is only ever called via the macro
  30749. ** winLogError().
  30750. **
  30751. ** This routine is invoked after an error occurs in an OS function.
  30752. ** It logs a message using sqlite3_log() containing the current value of
  30753. ** error code and, if possible, the human-readable equivalent from
  30754. ** FormatMessage.
  30755. **
  30756. ** The first argument passed to the macro should be the error code that
  30757. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  30758. ** The two subsequent arguments should be the name of the OS function that
  30759. ** failed and the associated file-system path, if any.
  30760. */
  30761. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  30762. static int winLogErrorAtLine(
  30763. int errcode, /* SQLite error code */
  30764. DWORD lastErrno, /* Win32 last error */
  30765. const char *zFunc, /* Name of OS function that failed */
  30766. const char *zPath, /* File path associated with error */
  30767. int iLine /* Source line number where error occurred */
  30768. ){
  30769. char zMsg[500]; /* Human readable error text */
  30770. int i; /* Loop counter */
  30771. zMsg[0] = 0;
  30772. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  30773. assert( errcode!=SQLITE_OK );
  30774. if( zPath==0 ) zPath = "";
  30775. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  30776. zMsg[i] = 0;
  30777. sqlite3_log(errcode,
  30778. "os_win.c:%d: (%lu) %s(%s) - %s",
  30779. iLine, lastErrno, zFunc, zPath, zMsg
  30780. );
  30781. return errcode;
  30782. }
  30783. /*
  30784. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  30785. ** will be retried following a locking error - probably caused by
  30786. ** antivirus software. Also the initial delay before the first retry.
  30787. ** The delay increases linearly with each retry.
  30788. */
  30789. #ifndef SQLITE_WIN32_IOERR_RETRY
  30790. # define SQLITE_WIN32_IOERR_RETRY 10
  30791. #endif
  30792. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  30793. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  30794. #endif
  30795. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  30796. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  30797. /*
  30798. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  30799. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  30800. ** to give up with an error.
  30801. */
  30802. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  30803. DWORD e = osGetLastError();
  30804. if( *pnRetry>=winIoerrRetry ){
  30805. if( pError ){
  30806. *pError = e;
  30807. }
  30808. return 0;
  30809. }
  30810. if( e==ERROR_ACCESS_DENIED ||
  30811. e==ERROR_LOCK_VIOLATION ||
  30812. e==ERROR_SHARING_VIOLATION ){
  30813. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  30814. ++*pnRetry;
  30815. return 1;
  30816. }
  30817. if( pError ){
  30818. *pError = e;
  30819. }
  30820. return 0;
  30821. }
  30822. /*
  30823. ** Log a I/O error retry episode.
  30824. */
  30825. static void winLogIoerr(int nRetry){
  30826. if( nRetry ){
  30827. sqlite3_log(SQLITE_IOERR,
  30828. "delayed %dms for lock/sharing conflict",
  30829. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  30830. );
  30831. }
  30832. }
  30833. #if SQLITE_OS_WINCE
  30834. /*************************************************************************
  30835. ** This section contains code for WinCE only.
  30836. */
  30837. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  30838. /*
  30839. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  30840. ** create a substitute.
  30841. */
  30842. /* #include <time.h> */
  30843. struct tm *__cdecl localtime(const time_t *t)
  30844. {
  30845. static struct tm y;
  30846. FILETIME uTm, lTm;
  30847. SYSTEMTIME pTm;
  30848. sqlite3_int64 t64;
  30849. t64 = *t;
  30850. t64 = (t64 + 11644473600)*10000000;
  30851. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  30852. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  30853. osFileTimeToLocalFileTime(&uTm,&lTm);
  30854. osFileTimeToSystemTime(&lTm,&pTm);
  30855. y.tm_year = pTm.wYear - 1900;
  30856. y.tm_mon = pTm.wMonth - 1;
  30857. y.tm_wday = pTm.wDayOfWeek;
  30858. y.tm_mday = pTm.wDay;
  30859. y.tm_hour = pTm.wHour;
  30860. y.tm_min = pTm.wMinute;
  30861. y.tm_sec = pTm.wSecond;
  30862. return &y;
  30863. }
  30864. #endif
  30865. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  30866. /*
  30867. ** Acquire a lock on the handle h
  30868. */
  30869. static void winceMutexAcquire(HANDLE h){
  30870. DWORD dwErr;
  30871. do {
  30872. dwErr = osWaitForSingleObject(h, INFINITE);
  30873. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  30874. }
  30875. /*
  30876. ** Release a lock acquired by winceMutexAcquire()
  30877. */
  30878. #define winceMutexRelease(h) ReleaseMutex(h)
  30879. /*
  30880. ** Create the mutex and shared memory used for locking in the file
  30881. ** descriptor pFile
  30882. */
  30883. static int winceCreateLock(const char *zFilename, winFile *pFile){
  30884. LPWSTR zTok;
  30885. LPWSTR zName;
  30886. DWORD lastErrno;
  30887. BOOL bLogged = FALSE;
  30888. BOOL bInit = TRUE;
  30889. zName = winUtf8ToUnicode(zFilename);
  30890. if( zName==0 ){
  30891. /* out of memory */
  30892. return SQLITE_IOERR_NOMEM;
  30893. }
  30894. /* Initialize the local lockdata */
  30895. memset(&pFile->local, 0, sizeof(pFile->local));
  30896. /* Replace the backslashes from the filename and lowercase it
  30897. ** to derive a mutex name. */
  30898. zTok = osCharLowerW(zName);
  30899. for (;*zTok;zTok++){
  30900. if (*zTok == '\\') *zTok = '_';
  30901. }
  30902. /* Create/open the named mutex */
  30903. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  30904. if (!pFile->hMutex){
  30905. pFile->lastErrno = osGetLastError();
  30906. sqlite3_free(zName);
  30907. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  30908. "winceCreateLock1", zFilename);
  30909. }
  30910. /* Acquire the mutex before continuing */
  30911. winceMutexAcquire(pFile->hMutex);
  30912. /* Since the names of named mutexes, semaphores, file mappings etc are
  30913. ** case-sensitive, take advantage of that by uppercasing the mutex name
  30914. ** and using that as the shared filemapping name.
  30915. */
  30916. osCharUpperW(zName);
  30917. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  30918. PAGE_READWRITE, 0, sizeof(winceLock),
  30919. zName);
  30920. /* Set a flag that indicates we're the first to create the memory so it
  30921. ** must be zero-initialized */
  30922. lastErrno = osGetLastError();
  30923. if (lastErrno == ERROR_ALREADY_EXISTS){
  30924. bInit = FALSE;
  30925. }
  30926. sqlite3_free(zName);
  30927. /* If we succeeded in making the shared memory handle, map it. */
  30928. if( pFile->hShared ){
  30929. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  30930. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  30931. /* If mapping failed, close the shared memory handle and erase it */
  30932. if( !pFile->shared ){
  30933. pFile->lastErrno = osGetLastError();
  30934. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30935. "winceCreateLock2", zFilename);
  30936. bLogged = TRUE;
  30937. osCloseHandle(pFile->hShared);
  30938. pFile->hShared = NULL;
  30939. }
  30940. }
  30941. /* If shared memory could not be created, then close the mutex and fail */
  30942. if( pFile->hShared==NULL ){
  30943. if( !bLogged ){
  30944. pFile->lastErrno = lastErrno;
  30945. winLogError(SQLITE_IOERR, pFile->lastErrno,
  30946. "winceCreateLock3", zFilename);
  30947. bLogged = TRUE;
  30948. }
  30949. winceMutexRelease(pFile->hMutex);
  30950. osCloseHandle(pFile->hMutex);
  30951. pFile->hMutex = NULL;
  30952. return SQLITE_IOERR;
  30953. }
  30954. /* Initialize the shared memory if we're supposed to */
  30955. if( bInit ){
  30956. memset(pFile->shared, 0, sizeof(winceLock));
  30957. }
  30958. winceMutexRelease(pFile->hMutex);
  30959. return SQLITE_OK;
  30960. }
  30961. /*
  30962. ** Destroy the part of winFile that deals with wince locks
  30963. */
  30964. static void winceDestroyLock(winFile *pFile){
  30965. if (pFile->hMutex){
  30966. /* Acquire the mutex */
  30967. winceMutexAcquire(pFile->hMutex);
  30968. /* The following blocks should probably assert in debug mode, but they
  30969. are to cleanup in case any locks remained open */
  30970. if (pFile->local.nReaders){
  30971. pFile->shared->nReaders --;
  30972. }
  30973. if (pFile->local.bReserved){
  30974. pFile->shared->bReserved = FALSE;
  30975. }
  30976. if (pFile->local.bPending){
  30977. pFile->shared->bPending = FALSE;
  30978. }
  30979. if (pFile->local.bExclusive){
  30980. pFile->shared->bExclusive = FALSE;
  30981. }
  30982. /* De-reference and close our copy of the shared memory handle */
  30983. osUnmapViewOfFile(pFile->shared);
  30984. osCloseHandle(pFile->hShared);
  30985. /* Done with the mutex */
  30986. winceMutexRelease(pFile->hMutex);
  30987. osCloseHandle(pFile->hMutex);
  30988. pFile->hMutex = NULL;
  30989. }
  30990. }
  30991. /*
  30992. ** An implementation of the LockFile() API of Windows for CE
  30993. */
  30994. static BOOL winceLockFile(
  30995. LPHANDLE phFile,
  30996. DWORD dwFileOffsetLow,
  30997. DWORD dwFileOffsetHigh,
  30998. DWORD nNumberOfBytesToLockLow,
  30999. DWORD nNumberOfBytesToLockHigh
  31000. ){
  31001. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  31002. BOOL bReturn = FALSE;
  31003. UNUSED_PARAMETER(dwFileOffsetHigh);
  31004. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  31005. if (!pFile->hMutex) return TRUE;
  31006. winceMutexAcquire(pFile->hMutex);
  31007. /* Wanting an exclusive lock? */
  31008. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  31009. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  31010. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  31011. pFile->shared->bExclusive = TRUE;
  31012. pFile->local.bExclusive = TRUE;
  31013. bReturn = TRUE;
  31014. }
  31015. }
  31016. /* Want a read-only lock? */
  31017. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  31018. nNumberOfBytesToLockLow == 1){
  31019. if (pFile->shared->bExclusive == 0){
  31020. pFile->local.nReaders ++;
  31021. if (pFile->local.nReaders == 1){
  31022. pFile->shared->nReaders ++;
  31023. }
  31024. bReturn = TRUE;
  31025. }
  31026. }
  31027. /* Want a pending lock? */
  31028. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  31029. && nNumberOfBytesToLockLow == 1){
  31030. /* If no pending lock has been acquired, then acquire it */
  31031. if (pFile->shared->bPending == 0) {
  31032. pFile->shared->bPending = TRUE;
  31033. pFile->local.bPending = TRUE;
  31034. bReturn = TRUE;
  31035. }
  31036. }
  31037. /* Want a reserved lock? */
  31038. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  31039. && nNumberOfBytesToLockLow == 1){
  31040. if (pFile->shared->bReserved == 0) {
  31041. pFile->shared->bReserved = TRUE;
  31042. pFile->local.bReserved = TRUE;
  31043. bReturn = TRUE;
  31044. }
  31045. }
  31046. winceMutexRelease(pFile->hMutex);
  31047. return bReturn;
  31048. }
  31049. /*
  31050. ** An implementation of the UnlockFile API of Windows for CE
  31051. */
  31052. static BOOL winceUnlockFile(
  31053. LPHANDLE phFile,
  31054. DWORD dwFileOffsetLow,
  31055. DWORD dwFileOffsetHigh,
  31056. DWORD nNumberOfBytesToUnlockLow,
  31057. DWORD nNumberOfBytesToUnlockHigh
  31058. ){
  31059. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  31060. BOOL bReturn = FALSE;
  31061. UNUSED_PARAMETER(dwFileOffsetHigh);
  31062. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  31063. if (!pFile->hMutex) return TRUE;
  31064. winceMutexAcquire(pFile->hMutex);
  31065. /* Releasing a reader lock or an exclusive lock */
  31066. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  31067. /* Did we have an exclusive lock? */
  31068. if (pFile->local.bExclusive){
  31069. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  31070. pFile->local.bExclusive = FALSE;
  31071. pFile->shared->bExclusive = FALSE;
  31072. bReturn = TRUE;
  31073. }
  31074. /* Did we just have a reader lock? */
  31075. else if (pFile->local.nReaders){
  31076. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  31077. || nNumberOfBytesToUnlockLow == 1);
  31078. pFile->local.nReaders --;
  31079. if (pFile->local.nReaders == 0)
  31080. {
  31081. pFile->shared->nReaders --;
  31082. }
  31083. bReturn = TRUE;
  31084. }
  31085. }
  31086. /* Releasing a pending lock */
  31087. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  31088. && nNumberOfBytesToUnlockLow == 1){
  31089. if (pFile->local.bPending){
  31090. pFile->local.bPending = FALSE;
  31091. pFile->shared->bPending = FALSE;
  31092. bReturn = TRUE;
  31093. }
  31094. }
  31095. /* Releasing a reserved lock */
  31096. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  31097. && nNumberOfBytesToUnlockLow == 1){
  31098. if (pFile->local.bReserved) {
  31099. pFile->local.bReserved = FALSE;
  31100. pFile->shared->bReserved = FALSE;
  31101. bReturn = TRUE;
  31102. }
  31103. }
  31104. winceMutexRelease(pFile->hMutex);
  31105. return bReturn;
  31106. }
  31107. /*
  31108. ** End of the special code for wince
  31109. *****************************************************************************/
  31110. #endif /* SQLITE_OS_WINCE */
  31111. /*
  31112. ** Lock a file region.
  31113. */
  31114. static BOOL winLockFile(
  31115. LPHANDLE phFile,
  31116. DWORD flags,
  31117. DWORD offsetLow,
  31118. DWORD offsetHigh,
  31119. DWORD numBytesLow,
  31120. DWORD numBytesHigh
  31121. ){
  31122. #if SQLITE_OS_WINCE
  31123. /*
  31124. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31125. ** API LockFile.
  31126. */
  31127. return winceLockFile(phFile, offsetLow, offsetHigh,
  31128. numBytesLow, numBytesHigh);
  31129. #else
  31130. if( osIsNT() ){
  31131. OVERLAPPED ovlp;
  31132. memset(&ovlp, 0, sizeof(OVERLAPPED));
  31133. ovlp.Offset = offsetLow;
  31134. ovlp.OffsetHigh = offsetHigh;
  31135. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  31136. }else{
  31137. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  31138. numBytesHigh);
  31139. }
  31140. #endif
  31141. }
  31142. /*
  31143. ** Unlock a file region.
  31144. */
  31145. static BOOL winUnlockFile(
  31146. LPHANDLE phFile,
  31147. DWORD offsetLow,
  31148. DWORD offsetHigh,
  31149. DWORD numBytesLow,
  31150. DWORD numBytesHigh
  31151. ){
  31152. #if SQLITE_OS_WINCE
  31153. /*
  31154. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31155. ** API UnlockFile.
  31156. */
  31157. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  31158. numBytesLow, numBytesHigh);
  31159. #else
  31160. if( osIsNT() ){
  31161. OVERLAPPED ovlp;
  31162. memset(&ovlp, 0, sizeof(OVERLAPPED));
  31163. ovlp.Offset = offsetLow;
  31164. ovlp.OffsetHigh = offsetHigh;
  31165. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  31166. }else{
  31167. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  31168. numBytesHigh);
  31169. }
  31170. #endif
  31171. }
  31172. /*****************************************************************************
  31173. ** The next group of routines implement the I/O methods specified
  31174. ** by the sqlite3_io_methods object.
  31175. ******************************************************************************/
  31176. /*
  31177. ** Some Microsoft compilers lack this definition.
  31178. */
  31179. #ifndef INVALID_SET_FILE_POINTER
  31180. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  31181. #endif
  31182. /*
  31183. ** Move the current position of the file handle passed as the first
  31184. ** argument to offset iOffset within the file. If successful, return 0.
  31185. ** Otherwise, set pFile->lastErrno and return non-zero.
  31186. */
  31187. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  31188. #if !SQLITE_OS_WINRT
  31189. LONG upperBits; /* Most sig. 32 bits of new offset */
  31190. LONG lowerBits; /* Least sig. 32 bits of new offset */
  31191. DWORD dwRet; /* Value returned by SetFilePointer() */
  31192. DWORD lastErrno; /* Value returned by GetLastError() */
  31193. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  31194. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  31195. lowerBits = (LONG)(iOffset & 0xffffffff);
  31196. /* API oddity: If successful, SetFilePointer() returns a dword
  31197. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  31198. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  31199. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  31200. ** whether an error has actually occurred, it is also necessary to call
  31201. ** GetLastError().
  31202. */
  31203. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  31204. if( (dwRet==INVALID_SET_FILE_POINTER
  31205. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  31206. pFile->lastErrno = lastErrno;
  31207. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  31208. "winSeekFile", pFile->zPath);
  31209. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  31210. return 1;
  31211. }
  31212. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  31213. return 0;
  31214. #else
  31215. /*
  31216. ** Same as above, except that this implementation works for WinRT.
  31217. */
  31218. LARGE_INTEGER x; /* The new offset */
  31219. BOOL bRet; /* Value returned by SetFilePointerEx() */
  31220. x.QuadPart = iOffset;
  31221. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  31222. if(!bRet){
  31223. pFile->lastErrno = osGetLastError();
  31224. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  31225. "winSeekFile", pFile->zPath);
  31226. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  31227. return 1;
  31228. }
  31229. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  31230. return 0;
  31231. #endif
  31232. }
  31233. #if SQLITE_MAX_MMAP_SIZE>0
  31234. /* Forward references to VFS helper methods used for memory mapped files */
  31235. static int winMapfile(winFile*, sqlite3_int64);
  31236. static int winUnmapfile(winFile*);
  31237. #endif
  31238. /*
  31239. ** Close a file.
  31240. **
  31241. ** It is reported that an attempt to close a handle might sometimes
  31242. ** fail. This is a very unreasonable result, but Windows is notorious
  31243. ** for being unreasonable so I do not doubt that it might happen. If
  31244. ** the close fails, we pause for 100 milliseconds and try again. As
  31245. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  31246. ** giving up and returning an error.
  31247. */
  31248. #define MX_CLOSE_ATTEMPT 3
  31249. static int winClose(sqlite3_file *id){
  31250. int rc, cnt = 0;
  31251. winFile *pFile = (winFile*)id;
  31252. assert( id!=0 );
  31253. #ifndef SQLITE_OMIT_WAL
  31254. assert( pFile->pShm==0 );
  31255. #endif
  31256. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  31257. OSTRACE(("CLOSE file=%p\n", pFile->h));
  31258. #if SQLITE_MAX_MMAP_SIZE>0
  31259. winUnmapfile(pFile);
  31260. #endif
  31261. do{
  31262. rc = osCloseHandle(pFile->h);
  31263. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  31264. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  31265. #if SQLITE_OS_WINCE
  31266. #define WINCE_DELETION_ATTEMPTS 3
  31267. winceDestroyLock(pFile);
  31268. if( pFile->zDeleteOnClose ){
  31269. int cnt = 0;
  31270. while(
  31271. osDeleteFileW(pFile->zDeleteOnClose)==0
  31272. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  31273. && cnt++ < WINCE_DELETION_ATTEMPTS
  31274. ){
  31275. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  31276. }
  31277. sqlite3_free(pFile->zDeleteOnClose);
  31278. }
  31279. #endif
  31280. if( rc ){
  31281. pFile->h = NULL;
  31282. }
  31283. OpenCounter(-1);
  31284. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  31285. return rc ? SQLITE_OK
  31286. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  31287. "winClose", pFile->zPath);
  31288. }
  31289. /*
  31290. ** Read data from a file into a buffer. Return SQLITE_OK if all
  31291. ** bytes were read successfully and SQLITE_IOERR if anything goes
  31292. ** wrong.
  31293. */
  31294. static int winRead(
  31295. sqlite3_file *id, /* File to read from */
  31296. void *pBuf, /* Write content into this buffer */
  31297. int amt, /* Number of bytes to read */
  31298. sqlite3_int64 offset /* Begin reading at this offset */
  31299. ){
  31300. #if !SQLITE_OS_WINCE
  31301. OVERLAPPED overlapped; /* The offset for ReadFile. */
  31302. #endif
  31303. winFile *pFile = (winFile*)id; /* file handle */
  31304. DWORD nRead; /* Number of bytes actually read from file */
  31305. int nRetry = 0; /* Number of retrys */
  31306. assert( id!=0 );
  31307. assert( amt>0 );
  31308. assert( offset>=0 );
  31309. SimulateIOError(return SQLITE_IOERR_READ);
  31310. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  31311. pFile->h, pBuf, amt, offset, pFile->locktype));
  31312. #if SQLITE_MAX_MMAP_SIZE>0
  31313. /* Deal with as much of this read request as possible by transfering
  31314. ** data from the memory mapping using memcpy(). */
  31315. if( offset<pFile->mmapSize ){
  31316. if( offset+amt <= pFile->mmapSize ){
  31317. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  31318. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  31319. return SQLITE_OK;
  31320. }else{
  31321. int nCopy = (int)(pFile->mmapSize - offset);
  31322. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  31323. pBuf = &((u8 *)pBuf)[nCopy];
  31324. amt -= nCopy;
  31325. offset += nCopy;
  31326. }
  31327. }
  31328. #endif
  31329. #if SQLITE_OS_WINCE
  31330. if( winSeekFile(pFile, offset) ){
  31331. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  31332. return SQLITE_FULL;
  31333. }
  31334. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  31335. #else
  31336. memset(&overlapped, 0, sizeof(OVERLAPPED));
  31337. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31338. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31339. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  31340. osGetLastError()!=ERROR_HANDLE_EOF ){
  31341. #endif
  31342. DWORD lastErrno;
  31343. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  31344. pFile->lastErrno = lastErrno;
  31345. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  31346. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  31347. "winRead", pFile->zPath);
  31348. }
  31349. winLogIoerr(nRetry);
  31350. if( nRead<(DWORD)amt ){
  31351. /* Unread parts of the buffer must be zero-filled */
  31352. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  31353. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  31354. return SQLITE_IOERR_SHORT_READ;
  31355. }
  31356. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  31357. return SQLITE_OK;
  31358. }
  31359. /*
  31360. ** Write data from a buffer into a file. Return SQLITE_OK on success
  31361. ** or some other error code on failure.
  31362. */
  31363. static int winWrite(
  31364. sqlite3_file *id, /* File to write into */
  31365. const void *pBuf, /* The bytes to be written */
  31366. int amt, /* Number of bytes to write */
  31367. sqlite3_int64 offset /* Offset into the file to begin writing at */
  31368. ){
  31369. int rc = 0; /* True if error has occurred, else false */
  31370. winFile *pFile = (winFile*)id; /* File handle */
  31371. int nRetry = 0; /* Number of retries */
  31372. assert( amt>0 );
  31373. assert( pFile );
  31374. SimulateIOError(return SQLITE_IOERR_WRITE);
  31375. SimulateDiskfullError(return SQLITE_FULL);
  31376. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  31377. pFile->h, pBuf, amt, offset, pFile->locktype));
  31378. #if SQLITE_MAX_MMAP_SIZE>0
  31379. /* Deal with as much of this write request as possible by transfering
  31380. ** data from the memory mapping using memcpy(). */
  31381. if( offset<pFile->mmapSize ){
  31382. if( offset+amt <= pFile->mmapSize ){
  31383. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  31384. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  31385. return SQLITE_OK;
  31386. }else{
  31387. int nCopy = (int)(pFile->mmapSize - offset);
  31388. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  31389. pBuf = &((u8 *)pBuf)[nCopy];
  31390. amt -= nCopy;
  31391. offset += nCopy;
  31392. }
  31393. }
  31394. #endif
  31395. #if SQLITE_OS_WINCE
  31396. rc = winSeekFile(pFile, offset);
  31397. if( rc==0 ){
  31398. #else
  31399. {
  31400. #endif
  31401. #if !SQLITE_OS_WINCE
  31402. OVERLAPPED overlapped; /* The offset for WriteFile. */
  31403. #endif
  31404. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  31405. int nRem = amt; /* Number of bytes yet to be written */
  31406. DWORD nWrite; /* Bytes written by each WriteFile() call */
  31407. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  31408. #if !SQLITE_OS_WINCE
  31409. memset(&overlapped, 0, sizeof(OVERLAPPED));
  31410. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31411. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31412. #endif
  31413. while( nRem>0 ){
  31414. #if SQLITE_OS_WINCE
  31415. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  31416. #else
  31417. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  31418. #endif
  31419. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  31420. break;
  31421. }
  31422. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  31423. if( nWrite==0 || nWrite>(DWORD)nRem ){
  31424. lastErrno = osGetLastError();
  31425. break;
  31426. }
  31427. #if !SQLITE_OS_WINCE
  31428. offset += nWrite;
  31429. overlapped.Offset = (LONG)(offset & 0xffffffff);
  31430. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  31431. #endif
  31432. aRem += nWrite;
  31433. nRem -= nWrite;
  31434. }
  31435. if( nRem>0 ){
  31436. pFile->lastErrno = lastErrno;
  31437. rc = 1;
  31438. }
  31439. }
  31440. if( rc ){
  31441. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  31442. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  31443. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  31444. return winLogError(SQLITE_FULL, pFile->lastErrno,
  31445. "winWrite1", pFile->zPath);
  31446. }
  31447. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  31448. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  31449. "winWrite2", pFile->zPath);
  31450. }else{
  31451. winLogIoerr(nRetry);
  31452. }
  31453. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  31454. return SQLITE_OK;
  31455. }
  31456. /*
  31457. ** Truncate an open file to a specified size
  31458. */
  31459. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  31460. winFile *pFile = (winFile*)id; /* File handle object */
  31461. int rc = SQLITE_OK; /* Return code for this function */
  31462. DWORD lastErrno;
  31463. assert( pFile );
  31464. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  31465. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  31466. pFile->h, nByte, pFile->locktype));
  31467. /* If the user has configured a chunk-size for this file, truncate the
  31468. ** file so that it consists of an integer number of chunks (i.e. the
  31469. ** actual file size after the operation may be larger than the requested
  31470. ** size).
  31471. */
  31472. if( pFile->szChunk>0 ){
  31473. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  31474. }
  31475. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  31476. if( winSeekFile(pFile, nByte) ){
  31477. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31478. "winTruncate1", pFile->zPath);
  31479. }else if( 0==osSetEndOfFile(pFile->h) &&
  31480. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  31481. pFile->lastErrno = lastErrno;
  31482. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  31483. "winTruncate2", pFile->zPath);
  31484. }
  31485. #if SQLITE_MAX_MMAP_SIZE>0
  31486. /* If the file was truncated to a size smaller than the currently
  31487. ** mapped region, reduce the effective mapping size as well. SQLite will
  31488. ** use read() and write() to access data beyond this point from now on.
  31489. */
  31490. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  31491. pFile->mmapSize = nByte;
  31492. }
  31493. #endif
  31494. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31495. return rc;
  31496. }
  31497. #ifdef SQLITE_TEST
  31498. /*
  31499. ** Count the number of fullsyncs and normal syncs. This is used to test
  31500. ** that syncs and fullsyncs are occuring at the right times.
  31501. */
  31502. SQLITE_API int sqlite3_sync_count = 0;
  31503. SQLITE_API int sqlite3_fullsync_count = 0;
  31504. #endif
  31505. /*
  31506. ** Make sure all writes to a particular file are committed to disk.
  31507. */
  31508. static int winSync(sqlite3_file *id, int flags){
  31509. #ifndef SQLITE_NO_SYNC
  31510. /*
  31511. ** Used only when SQLITE_NO_SYNC is not defined.
  31512. */
  31513. BOOL rc;
  31514. #endif
  31515. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  31516. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  31517. /*
  31518. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  31519. ** OSTRACE() macros.
  31520. */
  31521. winFile *pFile = (winFile*)id;
  31522. #else
  31523. UNUSED_PARAMETER(id);
  31524. #endif
  31525. assert( pFile );
  31526. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  31527. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  31528. || (flags&0x0F)==SQLITE_SYNC_FULL
  31529. );
  31530. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  31531. ** line is to test that doing so does not cause any problems.
  31532. */
  31533. SimulateDiskfullError( return SQLITE_FULL );
  31534. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  31535. pFile->h, flags, pFile->locktype));
  31536. #ifndef SQLITE_TEST
  31537. UNUSED_PARAMETER(flags);
  31538. #else
  31539. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  31540. sqlite3_fullsync_count++;
  31541. }
  31542. sqlite3_sync_count++;
  31543. #endif
  31544. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  31545. ** no-op
  31546. */
  31547. #ifdef SQLITE_NO_SYNC
  31548. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  31549. return SQLITE_OK;
  31550. #else
  31551. rc = osFlushFileBuffers(pFile->h);
  31552. SimulateIOError( rc=FALSE );
  31553. if( rc ){
  31554. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  31555. return SQLITE_OK;
  31556. }else{
  31557. pFile->lastErrno = osGetLastError();
  31558. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  31559. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  31560. "winSync", pFile->zPath);
  31561. }
  31562. #endif
  31563. }
  31564. /*
  31565. ** Determine the current size of a file in bytes
  31566. */
  31567. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  31568. winFile *pFile = (winFile*)id;
  31569. int rc = SQLITE_OK;
  31570. assert( id!=0 );
  31571. assert( pSize!=0 );
  31572. SimulateIOError(return SQLITE_IOERR_FSTAT);
  31573. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  31574. #if SQLITE_OS_WINRT
  31575. {
  31576. FILE_STANDARD_INFO info;
  31577. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  31578. &info, sizeof(info)) ){
  31579. *pSize = info.EndOfFile.QuadPart;
  31580. }else{
  31581. pFile->lastErrno = osGetLastError();
  31582. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31583. "winFileSize", pFile->zPath);
  31584. }
  31585. }
  31586. #else
  31587. {
  31588. DWORD upperBits;
  31589. DWORD lowerBits;
  31590. DWORD lastErrno;
  31591. lowerBits = osGetFileSize(pFile->h, &upperBits);
  31592. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  31593. if( (lowerBits == INVALID_FILE_SIZE)
  31594. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  31595. pFile->lastErrno = lastErrno;
  31596. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  31597. "winFileSize", pFile->zPath);
  31598. }
  31599. }
  31600. #endif
  31601. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  31602. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  31603. return rc;
  31604. }
  31605. /*
  31606. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  31607. */
  31608. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  31609. # define LOCKFILE_FAIL_IMMEDIATELY 1
  31610. #endif
  31611. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  31612. # define LOCKFILE_EXCLUSIVE_LOCK 2
  31613. #endif
  31614. /*
  31615. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  31616. ** When the LockFile function was used, it was always expected to fail
  31617. ** immediately if the lock could not be obtained. Also, it always expected to
  31618. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  31619. ** and reflect those expectations; therefore, they should not be changed.
  31620. */
  31621. #ifndef SQLITE_LOCKFILE_FLAGS
  31622. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  31623. LOCKFILE_EXCLUSIVE_LOCK)
  31624. #endif
  31625. /*
  31626. ** Currently, SQLite never calls the LockFileEx function without wanting the
  31627. ** call to fail immediately if the lock cannot be obtained.
  31628. */
  31629. #ifndef SQLITE_LOCKFILEEX_FLAGS
  31630. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  31631. #endif
  31632. /*
  31633. ** Acquire a reader lock.
  31634. ** Different API routines are called depending on whether or not this
  31635. ** is Win9x or WinNT.
  31636. */
  31637. static int winGetReadLock(winFile *pFile){
  31638. int res;
  31639. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31640. if( osIsNT() ){
  31641. #if SQLITE_OS_WINCE
  31642. /*
  31643. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  31644. ** API LockFileEx.
  31645. */
  31646. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  31647. #else
  31648. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  31649. SHARED_SIZE, 0);
  31650. #endif
  31651. }
  31652. #ifdef SQLITE_WIN32_HAS_ANSI
  31653. else{
  31654. int lk;
  31655. sqlite3_randomness(sizeof(lk), &lk);
  31656. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  31657. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31658. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31659. }
  31660. #endif
  31661. if( res == 0 ){
  31662. pFile->lastErrno = osGetLastError();
  31663. /* No need to log a failure to lock */
  31664. }
  31665. OSTRACE(("READ-LOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31666. return res;
  31667. }
  31668. /*
  31669. ** Undo a readlock
  31670. */
  31671. static int winUnlockReadLock(winFile *pFile){
  31672. int res;
  31673. DWORD lastErrno;
  31674. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  31675. if( osIsNT() ){
  31676. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31677. }
  31678. #ifdef SQLITE_WIN32_HAS_ANSI
  31679. else{
  31680. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  31681. }
  31682. #endif
  31683. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  31684. pFile->lastErrno = lastErrno;
  31685. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  31686. "winUnlockReadLock", pFile->zPath);
  31687. }
  31688. OSTRACE(("READ-UNLOCK file=%p, rc=%s\n", pFile->h, sqlite3ErrName(res)));
  31689. return res;
  31690. }
  31691. /*
  31692. ** Lock the file with the lock specified by parameter locktype - one
  31693. ** of the following:
  31694. **
  31695. ** (1) SHARED_LOCK
  31696. ** (2) RESERVED_LOCK
  31697. ** (3) PENDING_LOCK
  31698. ** (4) EXCLUSIVE_LOCK
  31699. **
  31700. ** Sometimes when requesting one lock state, additional lock states
  31701. ** are inserted in between. The locking might fail on one of the later
  31702. ** transitions leaving the lock state different from what it started but
  31703. ** still short of its goal. The following chart shows the allowed
  31704. ** transitions and the inserted intermediate states:
  31705. **
  31706. ** UNLOCKED -> SHARED
  31707. ** SHARED -> RESERVED
  31708. ** SHARED -> (PENDING) -> EXCLUSIVE
  31709. ** RESERVED -> (PENDING) -> EXCLUSIVE
  31710. ** PENDING -> EXCLUSIVE
  31711. **
  31712. ** This routine will only increase a lock. The winUnlock() routine
  31713. ** erases all locks at once and returns us immediately to locking level 0.
  31714. ** It is not possible to lower the locking level one step at a time. You
  31715. ** must go straight to locking level 0.
  31716. */
  31717. static int winLock(sqlite3_file *id, int locktype){
  31718. int rc = SQLITE_OK; /* Return code from subroutines */
  31719. int res = 1; /* Result of a Windows lock call */
  31720. int newLocktype; /* Set pFile->locktype to this value before exiting */
  31721. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  31722. winFile *pFile = (winFile*)id;
  31723. DWORD lastErrno = NO_ERROR;
  31724. assert( id!=0 );
  31725. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31726. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31727. /* If there is already a lock of this type or more restrictive on the
  31728. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  31729. ** sqlite3OsEnterMutex() hasn't been called yet.
  31730. */
  31731. if( pFile->locktype>=locktype ){
  31732. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  31733. return SQLITE_OK;
  31734. }
  31735. /* Make sure the locking sequence is correct
  31736. */
  31737. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  31738. assert( locktype!=PENDING_LOCK );
  31739. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  31740. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  31741. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  31742. ** the PENDING_LOCK byte is temporary.
  31743. */
  31744. newLocktype = pFile->locktype;
  31745. if( (pFile->locktype==NO_LOCK)
  31746. || ( (locktype==EXCLUSIVE_LOCK)
  31747. && (pFile->locktype==RESERVED_LOCK))
  31748. ){
  31749. int cnt = 3;
  31750. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  31751. PENDING_BYTE, 0, 1, 0))==0 ){
  31752. /* Try 3 times to get the pending lock. This is needed to work
  31753. ** around problems caused by indexing and/or anti-virus software on
  31754. ** Windows systems.
  31755. ** If you are using this code as a model for alternative VFSes, do not
  31756. ** copy this retry logic. It is a hack intended for Windows only.
  31757. */
  31758. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, rc=%s\n",
  31759. pFile->h, cnt, sqlite3ErrName(res)));
  31760. if( cnt ) sqlite3_win32_sleep(1);
  31761. }
  31762. gotPendingLock = res;
  31763. if( !res ){
  31764. lastErrno = osGetLastError();
  31765. }
  31766. }
  31767. /* Acquire a shared lock
  31768. */
  31769. if( locktype==SHARED_LOCK && res ){
  31770. assert( pFile->locktype==NO_LOCK );
  31771. res = winGetReadLock(pFile);
  31772. if( res ){
  31773. newLocktype = SHARED_LOCK;
  31774. }else{
  31775. lastErrno = osGetLastError();
  31776. }
  31777. }
  31778. /* Acquire a RESERVED lock
  31779. */
  31780. if( locktype==RESERVED_LOCK && res ){
  31781. assert( pFile->locktype==SHARED_LOCK );
  31782. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  31783. if( res ){
  31784. newLocktype = RESERVED_LOCK;
  31785. }else{
  31786. lastErrno = osGetLastError();
  31787. }
  31788. }
  31789. /* Acquire a PENDING lock
  31790. */
  31791. if( locktype==EXCLUSIVE_LOCK && res ){
  31792. newLocktype = PENDING_LOCK;
  31793. gotPendingLock = 0;
  31794. }
  31795. /* Acquire an EXCLUSIVE lock
  31796. */
  31797. if( locktype==EXCLUSIVE_LOCK && res ){
  31798. assert( pFile->locktype>=SHARED_LOCK );
  31799. res = winUnlockReadLock(pFile);
  31800. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  31801. SHARED_SIZE, 0);
  31802. if( res ){
  31803. newLocktype = EXCLUSIVE_LOCK;
  31804. }else{
  31805. lastErrno = osGetLastError();
  31806. winGetReadLock(pFile);
  31807. }
  31808. }
  31809. /* If we are holding a PENDING lock that ought to be released, then
  31810. ** release it now.
  31811. */
  31812. if( gotPendingLock && locktype==SHARED_LOCK ){
  31813. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31814. }
  31815. /* Update the state of the lock has held in the file descriptor then
  31816. ** return the appropriate result code.
  31817. */
  31818. if( res ){
  31819. rc = SQLITE_OK;
  31820. }else{
  31821. pFile->lastErrno = lastErrno;
  31822. rc = SQLITE_BUSY;
  31823. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  31824. pFile->h, locktype, newLocktype));
  31825. }
  31826. pFile->locktype = (u8)newLocktype;
  31827. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  31828. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31829. return rc;
  31830. }
  31831. /*
  31832. ** This routine checks if there is a RESERVED lock held on the specified
  31833. ** file by this or any other process. If such a lock is held, return
  31834. ** non-zero, otherwise zero.
  31835. */
  31836. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  31837. int rc;
  31838. winFile *pFile = (winFile*)id;
  31839. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  31840. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  31841. assert( id!=0 );
  31842. if( pFile->locktype>=RESERVED_LOCK ){
  31843. rc = 1;
  31844. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (local)\n", pFile->h, rc));
  31845. }else{
  31846. rc = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  31847. if( rc ){
  31848. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31849. }
  31850. rc = !rc;
  31851. OSTRACE(("TEST-WR-LOCK file=%p, rc=%d (remote)\n", pFile->h, rc));
  31852. }
  31853. *pResOut = rc;
  31854. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  31855. pFile->h, pResOut, *pResOut));
  31856. return SQLITE_OK;
  31857. }
  31858. /*
  31859. ** Lower the locking level on file descriptor id to locktype. locktype
  31860. ** must be either NO_LOCK or SHARED_LOCK.
  31861. **
  31862. ** If the locking level of the file descriptor is already at or below
  31863. ** the requested locking level, this routine is a no-op.
  31864. **
  31865. ** It is not possible for this routine to fail if the second argument
  31866. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  31867. ** might return SQLITE_IOERR;
  31868. */
  31869. static int winUnlock(sqlite3_file *id, int locktype){
  31870. int type;
  31871. winFile *pFile = (winFile*)id;
  31872. int rc = SQLITE_OK;
  31873. assert( pFile!=0 );
  31874. assert( locktype<=SHARED_LOCK );
  31875. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  31876. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  31877. type = pFile->locktype;
  31878. if( type>=EXCLUSIVE_LOCK ){
  31879. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  31880. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  31881. /* This should never happen. We should always be able to
  31882. ** reacquire the read lock */
  31883. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  31884. "winUnlock", pFile->zPath);
  31885. }
  31886. }
  31887. if( type>=RESERVED_LOCK ){
  31888. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  31889. }
  31890. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  31891. winUnlockReadLock(pFile);
  31892. }
  31893. if( type>=PENDING_LOCK ){
  31894. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  31895. }
  31896. pFile->locktype = (u8)locktype;
  31897. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  31898. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  31899. return rc;
  31900. }
  31901. /*
  31902. ** If *pArg is inititially negative then this is a query. Set *pArg to
  31903. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  31904. **
  31905. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  31906. */
  31907. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  31908. if( *pArg<0 ){
  31909. *pArg = (pFile->ctrlFlags & mask)!=0;
  31910. }else if( (*pArg)==0 ){
  31911. pFile->ctrlFlags &= ~mask;
  31912. }else{
  31913. pFile->ctrlFlags |= mask;
  31914. }
  31915. }
  31916. /* Forward references to VFS helper methods used for temporary files */
  31917. static int winGetTempname(sqlite3_vfs *, char **);
  31918. static int winIsDir(const void *);
  31919. static BOOL winIsDriveLetterAndColon(const char *);
  31920. /*
  31921. ** Control and query of the open file handle.
  31922. */
  31923. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  31924. winFile *pFile = (winFile*)id;
  31925. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  31926. switch( op ){
  31927. case SQLITE_FCNTL_LOCKSTATE: {
  31928. *(int*)pArg = pFile->locktype;
  31929. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31930. return SQLITE_OK;
  31931. }
  31932. case SQLITE_LAST_ERRNO: {
  31933. *(int*)pArg = (int)pFile->lastErrno;
  31934. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31935. return SQLITE_OK;
  31936. }
  31937. case SQLITE_FCNTL_CHUNK_SIZE: {
  31938. pFile->szChunk = *(int *)pArg;
  31939. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31940. return SQLITE_OK;
  31941. }
  31942. case SQLITE_FCNTL_SIZE_HINT: {
  31943. if( pFile->szChunk>0 ){
  31944. sqlite3_int64 oldSz;
  31945. int rc = winFileSize(id, &oldSz);
  31946. if( rc==SQLITE_OK ){
  31947. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  31948. if( newSz>oldSz ){
  31949. SimulateIOErrorBenign(1);
  31950. rc = winTruncate(id, newSz);
  31951. SimulateIOErrorBenign(0);
  31952. }
  31953. }
  31954. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31955. return rc;
  31956. }
  31957. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31958. return SQLITE_OK;
  31959. }
  31960. case SQLITE_FCNTL_PERSIST_WAL: {
  31961. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  31962. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31963. return SQLITE_OK;
  31964. }
  31965. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  31966. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  31967. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31968. return SQLITE_OK;
  31969. }
  31970. case SQLITE_FCNTL_VFSNAME: {
  31971. *(char**)pArg = sqlite3_mprintf("win32");
  31972. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31973. return SQLITE_OK;
  31974. }
  31975. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  31976. int *a = (int*)pArg;
  31977. if( a[0]>0 ){
  31978. winIoerrRetry = a[0];
  31979. }else{
  31980. a[0] = winIoerrRetry;
  31981. }
  31982. if( a[1]>0 ){
  31983. winIoerrRetryDelay = a[1];
  31984. }else{
  31985. a[1] = winIoerrRetryDelay;
  31986. }
  31987. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  31988. return SQLITE_OK;
  31989. }
  31990. case SQLITE_FCNTL_TEMPFILENAME: {
  31991. char *zTFile = 0;
  31992. int rc = winGetTempname(pFile->pVfs, &zTFile);
  31993. if( rc==SQLITE_OK ){
  31994. *(char**)pArg = zTFile;
  31995. }
  31996. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  31997. return rc;
  31998. }
  31999. #if SQLITE_MAX_MMAP_SIZE>0
  32000. case SQLITE_FCNTL_MMAP_SIZE: {
  32001. i64 newLimit = *(i64*)pArg;
  32002. int rc = SQLITE_OK;
  32003. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  32004. newLimit = sqlite3GlobalConfig.mxMmap;
  32005. }
  32006. *(i64*)pArg = pFile->mmapSizeMax;
  32007. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  32008. pFile->mmapSizeMax = newLimit;
  32009. if( pFile->mmapSize>0 ){
  32010. winUnmapfile(pFile);
  32011. rc = winMapfile(pFile, -1);
  32012. }
  32013. }
  32014. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  32015. return rc;
  32016. }
  32017. #endif
  32018. }
  32019. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  32020. return SQLITE_NOTFOUND;
  32021. }
  32022. /*
  32023. ** Return the sector size in bytes of the underlying block device for
  32024. ** the specified file. This is almost always 512 bytes, but may be
  32025. ** larger for some devices.
  32026. **
  32027. ** SQLite code assumes this function cannot fail. It also assumes that
  32028. ** if two files are created in the same file-system directory (i.e.
  32029. ** a database and its journal file) that the sector size will be the
  32030. ** same for both.
  32031. */
  32032. static int winSectorSize(sqlite3_file *id){
  32033. (void)id;
  32034. return SQLITE_DEFAULT_SECTOR_SIZE;
  32035. }
  32036. /*
  32037. ** Return a vector of device characteristics.
  32038. */
  32039. static int winDeviceCharacteristics(sqlite3_file *id){
  32040. winFile *p = (winFile*)id;
  32041. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  32042. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  32043. }
  32044. /*
  32045. ** Windows will only let you create file view mappings
  32046. ** on allocation size granularity boundaries.
  32047. ** During sqlite3_os_init() we do a GetSystemInfo()
  32048. ** to get the granularity size.
  32049. */
  32050. SYSTEM_INFO winSysInfo;
  32051. #ifndef SQLITE_OMIT_WAL
  32052. /*
  32053. ** Helper functions to obtain and relinquish the global mutex. The
  32054. ** global mutex is used to protect the winLockInfo objects used by
  32055. ** this file, all of which may be shared by multiple threads.
  32056. **
  32057. ** Function winShmMutexHeld() is used to assert() that the global mutex
  32058. ** is held when required. This function is only used as part of assert()
  32059. ** statements. e.g.
  32060. **
  32061. ** winShmEnterMutex()
  32062. ** assert( winShmMutexHeld() );
  32063. ** winShmLeaveMutex()
  32064. */
  32065. static void winShmEnterMutex(void){
  32066. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32067. }
  32068. static void winShmLeaveMutex(void){
  32069. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32070. }
  32071. #ifdef SQLITE_DEBUG
  32072. static int winShmMutexHeld(void) {
  32073. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  32074. }
  32075. #endif
  32076. /*
  32077. ** Object used to represent a single file opened and mmapped to provide
  32078. ** shared memory. When multiple threads all reference the same
  32079. ** log-summary, each thread has its own winFile object, but they all
  32080. ** point to a single instance of this object. In other words, each
  32081. ** log-summary is opened only once per process.
  32082. **
  32083. ** winShmMutexHeld() must be true when creating or destroying
  32084. ** this object or while reading or writing the following fields:
  32085. **
  32086. ** nRef
  32087. ** pNext
  32088. **
  32089. ** The following fields are read-only after the object is created:
  32090. **
  32091. ** fid
  32092. ** zFilename
  32093. **
  32094. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  32095. ** winShmMutexHeld() is true when reading or writing any other field
  32096. ** in this structure.
  32097. **
  32098. */
  32099. struct winShmNode {
  32100. sqlite3_mutex *mutex; /* Mutex to access this object */
  32101. char *zFilename; /* Name of the file */
  32102. winFile hFile; /* File handle from winOpen */
  32103. int szRegion; /* Size of shared-memory regions */
  32104. int nRegion; /* Size of array apRegion */
  32105. struct ShmRegion {
  32106. HANDLE hMap; /* File handle from CreateFileMapping */
  32107. void *pMap;
  32108. } *aRegion;
  32109. DWORD lastErrno; /* The Windows errno from the last I/O error */
  32110. int nRef; /* Number of winShm objects pointing to this */
  32111. winShm *pFirst; /* All winShm objects pointing to this */
  32112. winShmNode *pNext; /* Next in list of all winShmNode objects */
  32113. #ifdef SQLITE_DEBUG
  32114. u8 nextShmId; /* Next available winShm.id value */
  32115. #endif
  32116. };
  32117. /*
  32118. ** A global array of all winShmNode objects.
  32119. **
  32120. ** The winShmMutexHeld() must be true while reading or writing this list.
  32121. */
  32122. static winShmNode *winShmNodeList = 0;
  32123. /*
  32124. ** Structure used internally by this VFS to record the state of an
  32125. ** open shared memory connection.
  32126. **
  32127. ** The following fields are initialized when this object is created and
  32128. ** are read-only thereafter:
  32129. **
  32130. ** winShm.pShmNode
  32131. ** winShm.id
  32132. **
  32133. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  32134. ** while accessing any read/write fields.
  32135. */
  32136. struct winShm {
  32137. winShmNode *pShmNode; /* The underlying winShmNode object */
  32138. winShm *pNext; /* Next winShm with the same winShmNode */
  32139. u8 hasMutex; /* True if holding the winShmNode mutex */
  32140. u16 sharedMask; /* Mask of shared locks held */
  32141. u16 exclMask; /* Mask of exclusive locks held */
  32142. #ifdef SQLITE_DEBUG
  32143. u8 id; /* Id of this connection with its winShmNode */
  32144. #endif
  32145. };
  32146. /*
  32147. ** Constants used for locking
  32148. */
  32149. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  32150. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  32151. /*
  32152. ** Apply advisory locks for all n bytes beginning at ofst.
  32153. */
  32154. #define _SHM_UNLCK 1
  32155. #define _SHM_RDLCK 2
  32156. #define _SHM_WRLCK 3
  32157. static int winShmSystemLock(
  32158. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  32159. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  32160. int ofst, /* Offset to first byte to be locked/unlocked */
  32161. int nByte /* Number of bytes to lock or unlock */
  32162. ){
  32163. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  32164. /* Access to the winShmNode object is serialized by the caller */
  32165. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  32166. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  32167. pFile->hFile.h, lockType, ofst, nByte));
  32168. /* Release/Acquire the system-level lock */
  32169. if( lockType==_SHM_UNLCK ){
  32170. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  32171. }else{
  32172. /* Initialize the locking parameters */
  32173. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  32174. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  32175. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  32176. }
  32177. if( rc!= 0 ){
  32178. rc = SQLITE_OK;
  32179. }else{
  32180. pFile->lastErrno = osGetLastError();
  32181. rc = SQLITE_BUSY;
  32182. }
  32183. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  32184. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  32185. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  32186. return rc;
  32187. }
  32188. /* Forward references to VFS methods */
  32189. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  32190. static int winDelete(sqlite3_vfs *,const char*,int);
  32191. /*
  32192. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  32193. **
  32194. ** This is not a VFS shared-memory method; it is a utility function called
  32195. ** by VFS shared-memory methods.
  32196. */
  32197. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  32198. winShmNode **pp;
  32199. winShmNode *p;
  32200. assert( winShmMutexHeld() );
  32201. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  32202. osGetCurrentProcessId(), deleteFlag));
  32203. pp = &winShmNodeList;
  32204. while( (p = *pp)!=0 ){
  32205. if( p->nRef==0 ){
  32206. int i;
  32207. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  32208. for(i=0; i<p->nRegion; i++){
  32209. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  32210. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  32211. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  32212. UNUSED_VARIABLE_VALUE(bRc);
  32213. bRc = osCloseHandle(p->aRegion[i].hMap);
  32214. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  32215. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  32216. UNUSED_VARIABLE_VALUE(bRc);
  32217. }
  32218. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  32219. SimulateIOErrorBenign(1);
  32220. winClose((sqlite3_file *)&p->hFile);
  32221. SimulateIOErrorBenign(0);
  32222. }
  32223. if( deleteFlag ){
  32224. SimulateIOErrorBenign(1);
  32225. sqlite3BeginBenignMalloc();
  32226. winDelete(pVfs, p->zFilename, 0);
  32227. sqlite3EndBenignMalloc();
  32228. SimulateIOErrorBenign(0);
  32229. }
  32230. *pp = p->pNext;
  32231. sqlite3_free(p->aRegion);
  32232. sqlite3_free(p);
  32233. }else{
  32234. pp = &p->pNext;
  32235. }
  32236. }
  32237. }
  32238. /*
  32239. ** Open the shared-memory area associated with database file pDbFd.
  32240. **
  32241. ** When opening a new shared-memory file, if no other instances of that
  32242. ** file are currently open, in this process or in other processes, then
  32243. ** the file must be truncated to zero length or have its header cleared.
  32244. */
  32245. static int winOpenSharedMemory(winFile *pDbFd){
  32246. struct winShm *p; /* The connection to be opened */
  32247. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  32248. int rc; /* Result code */
  32249. struct winShmNode *pNew; /* Newly allocated winShmNode */
  32250. int nName; /* Size of zName in bytes */
  32251. assert( pDbFd->pShm==0 ); /* Not previously opened */
  32252. /* Allocate space for the new sqlite3_shm object. Also speculatively
  32253. ** allocate space for a new winShmNode and filename.
  32254. */
  32255. p = sqlite3MallocZero( sizeof(*p) );
  32256. if( p==0 ) return SQLITE_IOERR_NOMEM;
  32257. nName = sqlite3Strlen30(pDbFd->zPath);
  32258. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  32259. if( pNew==0 ){
  32260. sqlite3_free(p);
  32261. return SQLITE_IOERR_NOMEM;
  32262. }
  32263. pNew->zFilename = (char*)&pNew[1];
  32264. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  32265. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  32266. /* Look to see if there is an existing winShmNode that can be used.
  32267. ** If no matching winShmNode currently exists, create a new one.
  32268. */
  32269. winShmEnterMutex();
  32270. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  32271. /* TBD need to come up with better match here. Perhaps
  32272. ** use FILE_ID_BOTH_DIR_INFO Structure.
  32273. */
  32274. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  32275. }
  32276. if( pShmNode ){
  32277. sqlite3_free(pNew);
  32278. }else{
  32279. pShmNode = pNew;
  32280. pNew = 0;
  32281. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  32282. pShmNode->pNext = winShmNodeList;
  32283. winShmNodeList = pShmNode;
  32284. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  32285. if( pShmNode->mutex==0 ){
  32286. rc = SQLITE_IOERR_NOMEM;
  32287. goto shm_open_err;
  32288. }
  32289. rc = winOpen(pDbFd->pVfs,
  32290. pShmNode->zFilename, /* Name of the file (UTF-8) */
  32291. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  32292. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  32293. 0);
  32294. if( SQLITE_OK!=rc ){
  32295. goto shm_open_err;
  32296. }
  32297. /* Check to see if another process is holding the dead-man switch.
  32298. ** If not, truncate the file to zero length.
  32299. */
  32300. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  32301. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  32302. if( rc!=SQLITE_OK ){
  32303. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  32304. "winOpenShm", pDbFd->zPath);
  32305. }
  32306. }
  32307. if( rc==SQLITE_OK ){
  32308. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  32309. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  32310. }
  32311. if( rc ) goto shm_open_err;
  32312. }
  32313. /* Make the new connection a child of the winShmNode */
  32314. p->pShmNode = pShmNode;
  32315. #ifdef SQLITE_DEBUG
  32316. p->id = pShmNode->nextShmId++;
  32317. #endif
  32318. pShmNode->nRef++;
  32319. pDbFd->pShm = p;
  32320. winShmLeaveMutex();
  32321. /* The reference count on pShmNode has already been incremented under
  32322. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  32323. ** new (struct winShm) object to the pShmNode has been set. All that is
  32324. ** left to do is to link the new object into the linked list starting
  32325. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  32326. ** mutex.
  32327. */
  32328. sqlite3_mutex_enter(pShmNode->mutex);
  32329. p->pNext = pShmNode->pFirst;
  32330. pShmNode->pFirst = p;
  32331. sqlite3_mutex_leave(pShmNode->mutex);
  32332. return SQLITE_OK;
  32333. /* Jump here on any error */
  32334. shm_open_err:
  32335. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  32336. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  32337. sqlite3_free(p);
  32338. sqlite3_free(pNew);
  32339. winShmLeaveMutex();
  32340. return rc;
  32341. }
  32342. /*
  32343. ** Close a connection to shared-memory. Delete the underlying
  32344. ** storage if deleteFlag is true.
  32345. */
  32346. static int winShmUnmap(
  32347. sqlite3_file *fd, /* Database holding shared memory */
  32348. int deleteFlag /* Delete after closing if true */
  32349. ){
  32350. winFile *pDbFd; /* Database holding shared-memory */
  32351. winShm *p; /* The connection to be closed */
  32352. winShmNode *pShmNode; /* The underlying shared-memory file */
  32353. winShm **pp; /* For looping over sibling connections */
  32354. pDbFd = (winFile*)fd;
  32355. p = pDbFd->pShm;
  32356. if( p==0 ) return SQLITE_OK;
  32357. pShmNode = p->pShmNode;
  32358. /* Remove connection p from the set of connections associated
  32359. ** with pShmNode */
  32360. sqlite3_mutex_enter(pShmNode->mutex);
  32361. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  32362. *pp = p->pNext;
  32363. /* Free the connection p */
  32364. sqlite3_free(p);
  32365. pDbFd->pShm = 0;
  32366. sqlite3_mutex_leave(pShmNode->mutex);
  32367. /* If pShmNode->nRef has reached 0, then close the underlying
  32368. ** shared-memory file, too */
  32369. winShmEnterMutex();
  32370. assert( pShmNode->nRef>0 );
  32371. pShmNode->nRef--;
  32372. if( pShmNode->nRef==0 ){
  32373. winShmPurge(pDbFd->pVfs, deleteFlag);
  32374. }
  32375. winShmLeaveMutex();
  32376. return SQLITE_OK;
  32377. }
  32378. /*
  32379. ** Change the lock state for a shared-memory segment.
  32380. */
  32381. static int winShmLock(
  32382. sqlite3_file *fd, /* Database file holding the shared memory */
  32383. int ofst, /* First lock to acquire or release */
  32384. int n, /* Number of locks to acquire or release */
  32385. int flags /* What to do with the lock */
  32386. ){
  32387. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  32388. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  32389. winShm *pX; /* For looping over all siblings */
  32390. winShmNode *pShmNode = p->pShmNode;
  32391. int rc = SQLITE_OK; /* Result code */
  32392. u16 mask; /* Mask of locks to take or release */
  32393. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  32394. assert( n>=1 );
  32395. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  32396. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  32397. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  32398. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  32399. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  32400. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  32401. assert( n>1 || mask==(1<<ofst) );
  32402. sqlite3_mutex_enter(pShmNode->mutex);
  32403. if( flags & SQLITE_SHM_UNLOCK ){
  32404. u16 allMask = 0; /* Mask of locks held by siblings */
  32405. /* See if any siblings hold this same lock */
  32406. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32407. if( pX==p ) continue;
  32408. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  32409. allMask |= pX->sharedMask;
  32410. }
  32411. /* Unlock the system-level locks */
  32412. if( (mask & allMask)==0 ){
  32413. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  32414. }else{
  32415. rc = SQLITE_OK;
  32416. }
  32417. /* Undo the local locks */
  32418. if( rc==SQLITE_OK ){
  32419. p->exclMask &= ~mask;
  32420. p->sharedMask &= ~mask;
  32421. }
  32422. }else if( flags & SQLITE_SHM_SHARED ){
  32423. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  32424. /* Find out which shared locks are already held by sibling connections.
  32425. ** If any sibling already holds an exclusive lock, go ahead and return
  32426. ** SQLITE_BUSY.
  32427. */
  32428. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32429. if( (pX->exclMask & mask)!=0 ){
  32430. rc = SQLITE_BUSY;
  32431. break;
  32432. }
  32433. allShared |= pX->sharedMask;
  32434. }
  32435. /* Get shared locks at the system level, if necessary */
  32436. if( rc==SQLITE_OK ){
  32437. if( (allShared & mask)==0 ){
  32438. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  32439. }else{
  32440. rc = SQLITE_OK;
  32441. }
  32442. }
  32443. /* Get the local shared locks */
  32444. if( rc==SQLITE_OK ){
  32445. p->sharedMask |= mask;
  32446. }
  32447. }else{
  32448. /* Make sure no sibling connections hold locks that will block this
  32449. ** lock. If any do, return SQLITE_BUSY right away.
  32450. */
  32451. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  32452. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  32453. rc = SQLITE_BUSY;
  32454. break;
  32455. }
  32456. }
  32457. /* Get the exclusive locks at the system level. Then if successful
  32458. ** also mark the local connection as being locked.
  32459. */
  32460. if( rc==SQLITE_OK ){
  32461. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  32462. if( rc==SQLITE_OK ){
  32463. assert( (p->sharedMask & mask)==0 );
  32464. p->exclMask |= mask;
  32465. }
  32466. }
  32467. }
  32468. sqlite3_mutex_leave(pShmNode->mutex);
  32469. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  32470. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  32471. sqlite3ErrName(rc)));
  32472. return rc;
  32473. }
  32474. /*
  32475. ** Implement a memory barrier or memory fence on shared memory.
  32476. **
  32477. ** All loads and stores begun before the barrier must complete before
  32478. ** any load or store begun after the barrier.
  32479. */
  32480. static void winShmBarrier(
  32481. sqlite3_file *fd /* Database holding the shared memory */
  32482. ){
  32483. UNUSED_PARAMETER(fd);
  32484. /* MemoryBarrier(); // does not work -- do not know why not */
  32485. winShmEnterMutex();
  32486. winShmLeaveMutex();
  32487. }
  32488. /*
  32489. ** This function is called to obtain a pointer to region iRegion of the
  32490. ** shared-memory associated with the database file fd. Shared-memory regions
  32491. ** are numbered starting from zero. Each shared-memory region is szRegion
  32492. ** bytes in size.
  32493. **
  32494. ** If an error occurs, an error code is returned and *pp is set to NULL.
  32495. **
  32496. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  32497. ** region has not been allocated (by any client, including one running in a
  32498. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  32499. ** isWrite is non-zero and the requested shared-memory region has not yet
  32500. ** been allocated, it is allocated by this function.
  32501. **
  32502. ** If the shared-memory region has already been allocated or is allocated by
  32503. ** this call as described above, then it is mapped into this processes
  32504. ** address space (if it is not already), *pp is set to point to the mapped
  32505. ** memory and SQLITE_OK returned.
  32506. */
  32507. static int winShmMap(
  32508. sqlite3_file *fd, /* Handle open on database file */
  32509. int iRegion, /* Region to retrieve */
  32510. int szRegion, /* Size of regions */
  32511. int isWrite, /* True to extend file if necessary */
  32512. void volatile **pp /* OUT: Mapped memory */
  32513. ){
  32514. winFile *pDbFd = (winFile*)fd;
  32515. winShm *p = pDbFd->pShm;
  32516. winShmNode *pShmNode;
  32517. int rc = SQLITE_OK;
  32518. if( !p ){
  32519. rc = winOpenSharedMemory(pDbFd);
  32520. if( rc!=SQLITE_OK ) return rc;
  32521. p = pDbFd->pShm;
  32522. }
  32523. pShmNode = p->pShmNode;
  32524. sqlite3_mutex_enter(pShmNode->mutex);
  32525. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  32526. if( pShmNode->nRegion<=iRegion ){
  32527. struct ShmRegion *apNew; /* New aRegion[] array */
  32528. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  32529. sqlite3_int64 sz; /* Current size of wal-index file */
  32530. pShmNode->szRegion = szRegion;
  32531. /* The requested region is not mapped into this processes address space.
  32532. ** Check to see if it has been allocated (i.e. if the wal-index file is
  32533. ** large enough to contain the requested region).
  32534. */
  32535. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  32536. if( rc!=SQLITE_OK ){
  32537. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32538. "winShmMap1", pDbFd->zPath);
  32539. goto shmpage_out;
  32540. }
  32541. if( sz<nByte ){
  32542. /* The requested memory region does not exist. If isWrite is set to
  32543. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  32544. **
  32545. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  32546. ** the requested memory region.
  32547. */
  32548. if( !isWrite ) goto shmpage_out;
  32549. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  32550. if( rc!=SQLITE_OK ){
  32551. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  32552. "winShmMap2", pDbFd->zPath);
  32553. goto shmpage_out;
  32554. }
  32555. }
  32556. /* Map the requested memory region into this processes address space. */
  32557. apNew = (struct ShmRegion *)sqlite3_realloc(
  32558. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  32559. );
  32560. if( !apNew ){
  32561. rc = SQLITE_IOERR_NOMEM;
  32562. goto shmpage_out;
  32563. }
  32564. pShmNode->aRegion = apNew;
  32565. while( pShmNode->nRegion<=iRegion ){
  32566. HANDLE hMap = NULL; /* file-mapping handle */
  32567. void *pMap = 0; /* Mapped memory region */
  32568. #if SQLITE_OS_WINRT
  32569. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  32570. NULL, PAGE_READWRITE, nByte, NULL
  32571. );
  32572. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32573. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  32574. NULL, PAGE_READWRITE, 0, nByte, NULL
  32575. );
  32576. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32577. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  32578. NULL, PAGE_READWRITE, 0, nByte, NULL
  32579. );
  32580. #endif
  32581. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  32582. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  32583. hMap ? "ok" : "failed"));
  32584. if( hMap ){
  32585. int iOffset = pShmNode->nRegion*szRegion;
  32586. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32587. #if SQLITE_OS_WINRT
  32588. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32589. iOffset - iOffsetShift, szRegion + iOffsetShift
  32590. );
  32591. #else
  32592. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  32593. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  32594. );
  32595. #endif
  32596. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  32597. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  32598. szRegion, pMap ? "ok" : "failed"));
  32599. }
  32600. if( !pMap ){
  32601. pShmNode->lastErrno = osGetLastError();
  32602. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  32603. "winShmMap3", pDbFd->zPath);
  32604. if( hMap ) osCloseHandle(hMap);
  32605. goto shmpage_out;
  32606. }
  32607. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  32608. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  32609. pShmNode->nRegion++;
  32610. }
  32611. }
  32612. shmpage_out:
  32613. if( pShmNode->nRegion>iRegion ){
  32614. int iOffset = iRegion*szRegion;
  32615. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  32616. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  32617. *pp = (void *)&p[iOffsetShift];
  32618. }else{
  32619. *pp = 0;
  32620. }
  32621. sqlite3_mutex_leave(pShmNode->mutex);
  32622. return rc;
  32623. }
  32624. #else
  32625. # define winShmMap 0
  32626. # define winShmLock 0
  32627. # define winShmBarrier 0
  32628. # define winShmUnmap 0
  32629. #endif /* #ifndef SQLITE_OMIT_WAL */
  32630. /*
  32631. ** Cleans up the mapped region of the specified file, if any.
  32632. */
  32633. #if SQLITE_MAX_MMAP_SIZE>0
  32634. static int winUnmapfile(winFile *pFile){
  32635. assert( pFile!=0 );
  32636. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  32637. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  32638. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  32639. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  32640. if( pFile->pMapRegion ){
  32641. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  32642. pFile->lastErrno = osGetLastError();
  32643. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  32644. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  32645. pFile->pMapRegion));
  32646. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32647. "winUnmapfile1", pFile->zPath);
  32648. }
  32649. pFile->pMapRegion = 0;
  32650. pFile->mmapSize = 0;
  32651. pFile->mmapSizeActual = 0;
  32652. }
  32653. if( pFile->hMap!=NULL ){
  32654. if( !osCloseHandle(pFile->hMap) ){
  32655. pFile->lastErrno = osGetLastError();
  32656. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  32657. osGetCurrentProcessId(), pFile, pFile->hMap));
  32658. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  32659. "winUnmapfile2", pFile->zPath);
  32660. }
  32661. pFile->hMap = NULL;
  32662. }
  32663. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32664. osGetCurrentProcessId(), pFile));
  32665. return SQLITE_OK;
  32666. }
  32667. /*
  32668. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  32669. ** is already mapped, the existing mapping is replaced by the new). Or, if
  32670. ** there already exists a mapping for this file, and there are still
  32671. ** outstanding xFetch() references to it, this function is a no-op.
  32672. **
  32673. ** If parameter nByte is non-negative, then it is the requested size of
  32674. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  32675. ** requested size is the size of the file on disk. The actual size of the
  32676. ** created mapping is either the requested size or the value configured
  32677. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  32678. **
  32679. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  32680. ** recreated as a result of outstanding references) or an SQLite error
  32681. ** code otherwise.
  32682. */
  32683. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  32684. sqlite3_int64 nMap = nByte;
  32685. int rc;
  32686. assert( nMap>=0 || pFd->nFetchOut==0 );
  32687. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  32688. osGetCurrentProcessId(), pFd, nByte));
  32689. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  32690. if( nMap<0 ){
  32691. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  32692. if( rc ){
  32693. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  32694. osGetCurrentProcessId(), pFd));
  32695. return SQLITE_IOERR_FSTAT;
  32696. }
  32697. }
  32698. if( nMap>pFd->mmapSizeMax ){
  32699. nMap = pFd->mmapSizeMax;
  32700. }
  32701. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  32702. if( nMap==0 && pFd->mmapSize>0 ){
  32703. winUnmapfile(pFd);
  32704. }
  32705. if( nMap!=pFd->mmapSize ){
  32706. void *pNew = 0;
  32707. DWORD protect = PAGE_READONLY;
  32708. DWORD flags = FILE_MAP_READ;
  32709. winUnmapfile(pFd);
  32710. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  32711. protect = PAGE_READWRITE;
  32712. flags |= FILE_MAP_WRITE;
  32713. }
  32714. #if SQLITE_OS_WINRT
  32715. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  32716. #elif defined(SQLITE_WIN32_HAS_WIDE)
  32717. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  32718. (DWORD)((nMap>>32) & 0xffffffff),
  32719. (DWORD)(nMap & 0xffffffff), NULL);
  32720. #elif defined(SQLITE_WIN32_HAS_ANSI)
  32721. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  32722. (DWORD)((nMap>>32) & 0xffffffff),
  32723. (DWORD)(nMap & 0xffffffff), NULL);
  32724. #endif
  32725. if( pFd->hMap==NULL ){
  32726. pFd->lastErrno = osGetLastError();
  32727. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32728. "winMapfile1", pFd->zPath);
  32729. /* Log the error, but continue normal operation using xRead/xWrite */
  32730. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  32731. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32732. return SQLITE_OK;
  32733. }
  32734. assert( (nMap % winSysInfo.dwPageSize)==0 );
  32735. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  32736. #if SQLITE_OS_WINRT
  32737. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  32738. #else
  32739. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  32740. #endif
  32741. if( pNew==NULL ){
  32742. osCloseHandle(pFd->hMap);
  32743. pFd->hMap = NULL;
  32744. pFd->lastErrno = osGetLastError();
  32745. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  32746. "winMapfile2", pFd->zPath);
  32747. /* Log the error, but continue normal operation using xRead/xWrite */
  32748. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  32749. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32750. return SQLITE_OK;
  32751. }
  32752. pFd->pMapRegion = pNew;
  32753. pFd->mmapSize = nMap;
  32754. pFd->mmapSizeActual = nMap;
  32755. }
  32756. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32757. osGetCurrentProcessId(), pFd));
  32758. return SQLITE_OK;
  32759. }
  32760. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  32761. /*
  32762. ** If possible, return a pointer to a mapping of file fd starting at offset
  32763. ** iOff. The mapping must be valid for at least nAmt bytes.
  32764. **
  32765. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  32766. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  32767. ** Finally, if an error does occur, return an SQLite error code. The final
  32768. ** value of *pp is undefined in this case.
  32769. **
  32770. ** If this function does return a pointer, the caller must eventually
  32771. ** release the reference by calling winUnfetch().
  32772. */
  32773. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  32774. #if SQLITE_MAX_MMAP_SIZE>0
  32775. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32776. #endif
  32777. *pp = 0;
  32778. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  32779. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  32780. #if SQLITE_MAX_MMAP_SIZE>0
  32781. if( pFd->mmapSizeMax>0 ){
  32782. if( pFd->pMapRegion==0 ){
  32783. int rc = winMapfile(pFd, -1);
  32784. if( rc!=SQLITE_OK ){
  32785. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  32786. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  32787. return rc;
  32788. }
  32789. }
  32790. if( pFd->mmapSize >= iOff+nAmt ){
  32791. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  32792. pFd->nFetchOut++;
  32793. }
  32794. }
  32795. #endif
  32796. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  32797. osGetCurrentProcessId(), fd, pp, *pp));
  32798. return SQLITE_OK;
  32799. }
  32800. /*
  32801. ** If the third argument is non-NULL, then this function releases a
  32802. ** reference obtained by an earlier call to winFetch(). The second
  32803. ** argument passed to this function must be the same as the corresponding
  32804. ** argument that was passed to the winFetch() invocation.
  32805. **
  32806. ** Or, if the third argument is NULL, then this function is being called
  32807. ** to inform the VFS layer that, according to POSIX, any existing mapping
  32808. ** may now be invalid and should be unmapped.
  32809. */
  32810. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  32811. #if SQLITE_MAX_MMAP_SIZE>0
  32812. winFile *pFd = (winFile*)fd; /* The underlying database file */
  32813. /* If p==0 (unmap the entire file) then there must be no outstanding
  32814. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  32815. ** then there must be at least one outstanding. */
  32816. assert( (p==0)==(pFd->nFetchOut==0) );
  32817. /* If p!=0, it must match the iOff value. */
  32818. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  32819. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  32820. osGetCurrentProcessId(), pFd, iOff, p));
  32821. if( p ){
  32822. pFd->nFetchOut--;
  32823. }else{
  32824. /* FIXME: If Windows truly always prevents truncating or deleting a
  32825. ** file while a mapping is held, then the following winUnmapfile() call
  32826. ** is unnecessary can can be omitted - potentially improving
  32827. ** performance. */
  32828. winUnmapfile(pFd);
  32829. }
  32830. assert( pFd->nFetchOut>=0 );
  32831. #endif
  32832. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  32833. osGetCurrentProcessId(), fd));
  32834. return SQLITE_OK;
  32835. }
  32836. /*
  32837. ** Here ends the implementation of all sqlite3_file methods.
  32838. **
  32839. ********************** End sqlite3_file Methods *******************************
  32840. ******************************************************************************/
  32841. /*
  32842. ** This vector defines all the methods that can operate on an
  32843. ** sqlite3_file for win32.
  32844. */
  32845. static const sqlite3_io_methods winIoMethod = {
  32846. 3, /* iVersion */
  32847. winClose, /* xClose */
  32848. winRead, /* xRead */
  32849. winWrite, /* xWrite */
  32850. winTruncate, /* xTruncate */
  32851. winSync, /* xSync */
  32852. winFileSize, /* xFileSize */
  32853. winLock, /* xLock */
  32854. winUnlock, /* xUnlock */
  32855. winCheckReservedLock, /* xCheckReservedLock */
  32856. winFileControl, /* xFileControl */
  32857. winSectorSize, /* xSectorSize */
  32858. winDeviceCharacteristics, /* xDeviceCharacteristics */
  32859. winShmMap, /* xShmMap */
  32860. winShmLock, /* xShmLock */
  32861. winShmBarrier, /* xShmBarrier */
  32862. winShmUnmap, /* xShmUnmap */
  32863. winFetch, /* xFetch */
  32864. winUnfetch /* xUnfetch */
  32865. };
  32866. /****************************************************************************
  32867. **************************** sqlite3_vfs methods ****************************
  32868. **
  32869. ** This division contains the implementation of methods on the
  32870. ** sqlite3_vfs object.
  32871. */
  32872. #if 0
  32873. /*
  32874. ** Convert a filename from whatever the underlying operating system
  32875. ** supports for filenames into UTF-8. Space to hold the result is
  32876. ** obtained from malloc and must be freed by the calling function.
  32877. */
  32878. static char *winConvertToUtf8Filename(const void *zFilename){
  32879. char *zConverted = 0;
  32880. if( osIsNT() ){
  32881. zConverted = winUnicodeToUtf8(zFilename);
  32882. }
  32883. #ifdef SQLITE_WIN32_HAS_ANSI
  32884. else{
  32885. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  32886. }
  32887. #endif
  32888. /* caller will handle out of memory */
  32889. return zConverted;
  32890. }
  32891. #endif
  32892. /*
  32893. ** Convert a UTF-8 filename into whatever form the underlying
  32894. ** operating system wants filenames in. Space to hold the result
  32895. ** is obtained from malloc and must be freed by the calling
  32896. ** function.
  32897. */
  32898. static void *winConvertFromUtf8Filename(const char *zFilename){
  32899. void *zConverted = 0;
  32900. if( osIsNT() ){
  32901. zConverted = winUtf8ToUnicode(zFilename);
  32902. }
  32903. #ifdef SQLITE_WIN32_HAS_ANSI
  32904. else{
  32905. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  32906. }
  32907. #endif
  32908. /* caller will handle out of memory */
  32909. return zConverted;
  32910. }
  32911. /*
  32912. ** This function returns non-zero if the specified UTF-8 string buffer
  32913. ** ends with a directory separator character.
  32914. */
  32915. static int winEndsInDirSep(char *zBuf){
  32916. if( zBuf ){
  32917. int nLen = sqlite3Strlen30(zBuf);
  32918. return nLen>0 && winIsDirSep(zBuf[nLen-1]);
  32919. }
  32920. return 0;
  32921. }
  32922. /*
  32923. ** Create a temporary file name and store the resulting pointer into pzBuf.
  32924. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  32925. */
  32926. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  32927. static char zChars[] =
  32928. "abcdefghijklmnopqrstuvwxyz"
  32929. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  32930. "0123456789";
  32931. size_t i, j;
  32932. int nBuf, nLen;
  32933. char *zBuf;
  32934. /* It's odd to simulate an io-error here, but really this is just
  32935. ** using the io-error infrastructure to test that SQLite handles this
  32936. ** function failing.
  32937. */
  32938. SimulateIOError( return SQLITE_IOERR );
  32939. /* Allocate a temporary buffer to store the fully qualified file
  32940. ** name for the temporary file. If this fails, we cannot continue.
  32941. */
  32942. nBuf = pVfs->mxPathname;
  32943. zBuf = sqlite3MallocZero( nBuf+2 );
  32944. if( !zBuf ){
  32945. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32946. return SQLITE_IOERR_NOMEM;
  32947. }
  32948. /* Figure out the effective temporary directory. First, check if one
  32949. ** has been explicitly set by the application; otherwise, use the one
  32950. ** configured by the operating system.
  32951. */
  32952. assert( nBuf>30 );
  32953. if( sqlite3_temp_directory ){
  32954. sqlite3_snprintf(nBuf-30, zBuf, "%s%s", sqlite3_temp_directory,
  32955. winEndsInDirSep(sqlite3_temp_directory) ? "" :
  32956. winGetDirDep());
  32957. }
  32958. #if defined(__CYGWIN__)
  32959. else{
  32960. static const char *azDirs[] = {
  32961. 0, /* getenv("SQLITE_TMPDIR") */
  32962. 0, /* getenv("TMPDIR") */
  32963. 0, /* getenv("TMP") */
  32964. 0, /* getenv("TEMP") */
  32965. 0, /* getenv("USERPROFILE") */
  32966. "/var/tmp",
  32967. "/usr/tmp",
  32968. "/tmp",
  32969. ".",
  32970. 0 /* List terminator */
  32971. };
  32972. unsigned int i;
  32973. const char *zDir = 0;
  32974. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  32975. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  32976. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  32977. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  32978. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  32979. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  32980. void *zConverted;
  32981. if( zDir==0 ) continue;
  32982. /* If the path starts with a drive letter followed by the colon
  32983. ** character, assume it is already a native Win32 path; otherwise,
  32984. ** it must be converted to a native Win32 path prior via the Cygwin
  32985. ** API prior to using it.
  32986. */
  32987. if( winIsDriveLetterAndColon(zDir) ){
  32988. zConverted = winConvertFromUtf8Filename(zDir);
  32989. if( !zConverted ){
  32990. sqlite3_free(zBuf);
  32991. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  32992. return SQLITE_IOERR_NOMEM;
  32993. }
  32994. if( winIsDir(zConverted) ){
  32995. sqlite3_snprintf(nBuf-30, zBuf, "%s", zDir);
  32996. sqlite3_free(zConverted);
  32997. break;
  32998. }
  32999. sqlite3_free(zConverted);
  33000. }else{
  33001. zConverted = sqlite3MallocZero( nBuf+1 );
  33002. if( !zConverted ){
  33003. sqlite3_free(zBuf);
  33004. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33005. return SQLITE_IOERR_NOMEM;
  33006. }
  33007. if( cygwin_conv_path(
  33008. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  33009. zConverted, nBuf+1)<0 ){
  33010. sqlite3_free(zConverted);
  33011. sqlite3_free(zBuf);
  33012. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  33013. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  33014. "winGetTempname1", zDir);
  33015. }
  33016. if( winIsDir(zConverted) ){
  33017. /* At this point, we know the candidate directory exists and should
  33018. ** be used. However, we may need to convert the string containing
  33019. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  33020. */
  33021. if( osIsNT() ){
  33022. char *zUtf8 = winUnicodeToUtf8(zConverted);
  33023. if( !zUtf8 ){
  33024. sqlite3_free(zConverted);
  33025. sqlite3_free(zBuf);
  33026. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33027. return SQLITE_IOERR_NOMEM;
  33028. }
  33029. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  33030. sqlite3_free(zUtf8);
  33031. sqlite3_free(zConverted);
  33032. break;
  33033. }else{
  33034. sqlite3_snprintf(nBuf-30, zBuf, "%s", zConverted);
  33035. sqlite3_free(zConverted);
  33036. break;
  33037. }
  33038. }
  33039. sqlite3_free(zConverted);
  33040. }
  33041. }
  33042. }
  33043. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  33044. else if( osIsNT() ){
  33045. char *zMulti;
  33046. LPWSTR zWidePath = sqlite3MallocZero( nBuf*sizeof(WCHAR) );
  33047. if( !zWidePath ){
  33048. sqlite3_free(zBuf);
  33049. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33050. return SQLITE_IOERR_NOMEM;
  33051. }
  33052. if( osGetTempPathW(nBuf, zWidePath)==0 ){
  33053. sqlite3_free(zWidePath);
  33054. sqlite3_free(zBuf);
  33055. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  33056. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  33057. "winGetTempname1", 0);
  33058. }
  33059. zMulti = winUnicodeToUtf8(zWidePath);
  33060. if( zMulti ){
  33061. sqlite3_snprintf(nBuf-30, zBuf, "%s", zMulti);
  33062. sqlite3_free(zMulti);
  33063. sqlite3_free(zWidePath);
  33064. }else{
  33065. sqlite3_free(zWidePath);
  33066. sqlite3_free(zBuf);
  33067. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33068. return SQLITE_IOERR_NOMEM;
  33069. }
  33070. }
  33071. #ifdef SQLITE_WIN32_HAS_ANSI
  33072. else{
  33073. char *zUtf8;
  33074. char *zMbcsPath = sqlite3MallocZero( nBuf );
  33075. if( !zMbcsPath ){
  33076. sqlite3_free(zBuf);
  33077. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33078. return SQLITE_IOERR_NOMEM;
  33079. }
  33080. if( osGetTempPathA(nBuf, zMbcsPath)==0 ){
  33081. sqlite3_free(zBuf);
  33082. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  33083. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  33084. "winGetTempname2", 0);
  33085. }
  33086. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  33087. if( zUtf8 ){
  33088. sqlite3_snprintf(nBuf-30, zBuf, "%s", zUtf8);
  33089. sqlite3_free(zUtf8);
  33090. }else{
  33091. sqlite3_free(zBuf);
  33092. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  33093. return SQLITE_IOERR_NOMEM;
  33094. }
  33095. }
  33096. #endif /* SQLITE_WIN32_HAS_ANSI */
  33097. #endif /* !SQLITE_OS_WINRT */
  33098. /* Check that the output buffer is large enough for the temporary file
  33099. ** name. If it is not, return SQLITE_ERROR.
  33100. */
  33101. nLen = sqlite3Strlen30(zBuf);
  33102. if( (nLen + sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX) + 18) >= nBuf ){
  33103. sqlite3_free(zBuf);
  33104. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  33105. return winLogError(SQLITE_ERROR, 0, "winGetTempname3", 0);
  33106. }
  33107. sqlite3_snprintf(nBuf-18-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  33108. j = sqlite3Strlen30(zBuf);
  33109. sqlite3_randomness(15, &zBuf[j]);
  33110. for(i=0; i<15; i++, j++){
  33111. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  33112. }
  33113. zBuf[j] = 0;
  33114. zBuf[j+1] = 0;
  33115. *pzBuf = zBuf;
  33116. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  33117. return SQLITE_OK;
  33118. }
  33119. /*
  33120. ** Return TRUE if the named file is really a directory. Return false if
  33121. ** it is something other than a directory, or if there is any kind of memory
  33122. ** allocation failure.
  33123. */
  33124. static int winIsDir(const void *zConverted){
  33125. DWORD attr;
  33126. int rc = 0;
  33127. DWORD lastErrno;
  33128. if( osIsNT() ){
  33129. int cnt = 0;
  33130. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33131. memset(&sAttrData, 0, sizeof(sAttrData));
  33132. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  33133. GetFileExInfoStandard,
  33134. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  33135. if( !rc ){
  33136. return 0; /* Invalid name? */
  33137. }
  33138. attr = sAttrData.dwFileAttributes;
  33139. #if SQLITE_OS_WINCE==0
  33140. }else{
  33141. attr = osGetFileAttributesA((char*)zConverted);
  33142. #endif
  33143. }
  33144. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  33145. }
  33146. /*
  33147. ** Open a file.
  33148. */
  33149. static int winOpen(
  33150. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  33151. const char *zName, /* Name of the file (UTF-8) */
  33152. sqlite3_file *id, /* Write the SQLite file handle here */
  33153. int flags, /* Open mode flags */
  33154. int *pOutFlags /* Status return flags */
  33155. ){
  33156. HANDLE h;
  33157. DWORD lastErrno;
  33158. DWORD dwDesiredAccess;
  33159. DWORD dwShareMode;
  33160. DWORD dwCreationDisposition;
  33161. DWORD dwFlagsAndAttributes = 0;
  33162. #if SQLITE_OS_WINCE
  33163. int isTemp = 0;
  33164. #endif
  33165. winFile *pFile = (winFile*)id;
  33166. void *zConverted; /* Filename in OS encoding */
  33167. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  33168. int cnt = 0;
  33169. /* If argument zPath is a NULL pointer, this function is required to open
  33170. ** a temporary file. Use this buffer to store the file name in.
  33171. */
  33172. char *zTmpname = 0; /* For temporary filename, if necessary. */
  33173. int rc = SQLITE_OK; /* Function Return Code */
  33174. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  33175. int eType = flags&0xFFFFFF00; /* Type of file to open */
  33176. #endif
  33177. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  33178. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  33179. int isCreate = (flags & SQLITE_OPEN_CREATE);
  33180. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  33181. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  33182. #ifndef NDEBUG
  33183. int isOpenJournal = (isCreate && (
  33184. eType==SQLITE_OPEN_MASTER_JOURNAL
  33185. || eType==SQLITE_OPEN_MAIN_JOURNAL
  33186. || eType==SQLITE_OPEN_WAL
  33187. ));
  33188. #endif
  33189. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  33190. zUtf8Name, id, flags, pOutFlags));
  33191. /* Check the following statements are true:
  33192. **
  33193. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  33194. ** (b) if CREATE is set, then READWRITE must also be set, and
  33195. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  33196. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  33197. */
  33198. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  33199. assert(isCreate==0 || isReadWrite);
  33200. assert(isExclusive==0 || isCreate);
  33201. assert(isDelete==0 || isCreate);
  33202. /* The main DB, main journal, WAL file and master journal are never
  33203. ** automatically deleted. Nor are they ever temporary files. */
  33204. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  33205. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  33206. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  33207. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  33208. /* Assert that the upper layer has set one of the "file-type" flags. */
  33209. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  33210. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  33211. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  33212. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  33213. );
  33214. assert( pFile!=0 );
  33215. memset(pFile, 0, sizeof(winFile));
  33216. pFile->h = INVALID_HANDLE_VALUE;
  33217. #if SQLITE_OS_WINRT
  33218. if( !zUtf8Name && !sqlite3_temp_directory ){
  33219. sqlite3_log(SQLITE_ERROR,
  33220. "sqlite3_temp_directory variable should be set for WinRT");
  33221. }
  33222. #endif
  33223. /* If the second argument to this function is NULL, generate a
  33224. ** temporary file name to use
  33225. */
  33226. if( !zUtf8Name ){
  33227. assert( isDelete && !isOpenJournal );
  33228. rc = winGetTempname(pVfs, &zTmpname);
  33229. if( rc!=SQLITE_OK ){
  33230. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  33231. return rc;
  33232. }
  33233. zUtf8Name = zTmpname;
  33234. }
  33235. /* Database filenames are double-zero terminated if they are not
  33236. ** URIs with parameters. Hence, they can always be passed into
  33237. ** sqlite3_uri_parameter().
  33238. */
  33239. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  33240. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  33241. /* Convert the filename to the system encoding. */
  33242. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  33243. if( zConverted==0 ){
  33244. sqlite3_free(zTmpname);
  33245. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  33246. return SQLITE_IOERR_NOMEM;
  33247. }
  33248. if( winIsDir(zConverted) ){
  33249. sqlite3_free(zConverted);
  33250. sqlite3_free(zTmpname);
  33251. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  33252. return SQLITE_CANTOPEN_ISDIR;
  33253. }
  33254. if( isReadWrite ){
  33255. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  33256. }else{
  33257. dwDesiredAccess = GENERIC_READ;
  33258. }
  33259. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  33260. ** created. SQLite doesn't use it to indicate "exclusive access"
  33261. ** as it is usually understood.
  33262. */
  33263. if( isExclusive ){
  33264. /* Creates a new file, only if it does not already exist. */
  33265. /* If the file exists, it fails. */
  33266. dwCreationDisposition = CREATE_NEW;
  33267. }else if( isCreate ){
  33268. /* Open existing file, or create if it doesn't exist */
  33269. dwCreationDisposition = OPEN_ALWAYS;
  33270. }else{
  33271. /* Opens a file, only if it exists. */
  33272. dwCreationDisposition = OPEN_EXISTING;
  33273. }
  33274. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  33275. if( isDelete ){
  33276. #if SQLITE_OS_WINCE
  33277. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  33278. isTemp = 1;
  33279. #else
  33280. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  33281. | FILE_ATTRIBUTE_HIDDEN
  33282. | FILE_FLAG_DELETE_ON_CLOSE;
  33283. #endif
  33284. }else{
  33285. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  33286. }
  33287. /* Reports from the internet are that performance is always
  33288. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  33289. #if SQLITE_OS_WINCE
  33290. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  33291. #endif
  33292. if( osIsNT() ){
  33293. #if SQLITE_OS_WINRT
  33294. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  33295. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  33296. extendedParameters.dwFileAttributes =
  33297. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  33298. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  33299. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  33300. extendedParameters.lpSecurityAttributes = NULL;
  33301. extendedParameters.hTemplateFile = NULL;
  33302. while( (h = osCreateFile2((LPCWSTR)zConverted,
  33303. dwDesiredAccess,
  33304. dwShareMode,
  33305. dwCreationDisposition,
  33306. &extendedParameters))==INVALID_HANDLE_VALUE &&
  33307. winRetryIoerr(&cnt, &lastErrno) ){
  33308. /* Noop */
  33309. }
  33310. #else
  33311. while( (h = osCreateFileW((LPCWSTR)zConverted,
  33312. dwDesiredAccess,
  33313. dwShareMode, NULL,
  33314. dwCreationDisposition,
  33315. dwFlagsAndAttributes,
  33316. NULL))==INVALID_HANDLE_VALUE &&
  33317. winRetryIoerr(&cnt, &lastErrno) ){
  33318. /* Noop */
  33319. }
  33320. #endif
  33321. }
  33322. #ifdef SQLITE_WIN32_HAS_ANSI
  33323. else{
  33324. while( (h = osCreateFileA((LPCSTR)zConverted,
  33325. dwDesiredAccess,
  33326. dwShareMode, NULL,
  33327. dwCreationDisposition,
  33328. dwFlagsAndAttributes,
  33329. NULL))==INVALID_HANDLE_VALUE &&
  33330. winRetryIoerr(&cnt, &lastErrno) ){
  33331. /* Noop */
  33332. }
  33333. }
  33334. #endif
  33335. winLogIoerr(cnt);
  33336. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  33337. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  33338. if( h==INVALID_HANDLE_VALUE ){
  33339. pFile->lastErrno = lastErrno;
  33340. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  33341. sqlite3_free(zConverted);
  33342. sqlite3_free(zTmpname);
  33343. if( isReadWrite && !isExclusive ){
  33344. return winOpen(pVfs, zName, id,
  33345. ((flags|SQLITE_OPEN_READONLY) &
  33346. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  33347. pOutFlags);
  33348. }else{
  33349. return SQLITE_CANTOPEN_BKPT;
  33350. }
  33351. }
  33352. if( pOutFlags ){
  33353. if( isReadWrite ){
  33354. *pOutFlags = SQLITE_OPEN_READWRITE;
  33355. }else{
  33356. *pOutFlags = SQLITE_OPEN_READONLY;
  33357. }
  33358. }
  33359. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  33360. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  33361. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  33362. #if SQLITE_OS_WINCE
  33363. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  33364. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  33365. ){
  33366. osCloseHandle(h);
  33367. sqlite3_free(zConverted);
  33368. sqlite3_free(zTmpname);
  33369. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  33370. return rc;
  33371. }
  33372. if( isTemp ){
  33373. pFile->zDeleteOnClose = zConverted;
  33374. }else
  33375. #endif
  33376. {
  33377. sqlite3_free(zConverted);
  33378. }
  33379. sqlite3_free(zTmpname);
  33380. pFile->pMethod = &winIoMethod;
  33381. pFile->pVfs = pVfs;
  33382. pFile->h = h;
  33383. if( isReadonly ){
  33384. pFile->ctrlFlags |= WINFILE_RDONLY;
  33385. }
  33386. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  33387. pFile->ctrlFlags |= WINFILE_PSOW;
  33388. }
  33389. pFile->lastErrno = NO_ERROR;
  33390. pFile->zPath = zName;
  33391. #if SQLITE_MAX_MMAP_SIZE>0
  33392. pFile->hMap = NULL;
  33393. pFile->pMapRegion = 0;
  33394. pFile->mmapSize = 0;
  33395. pFile->mmapSizeActual = 0;
  33396. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  33397. #endif
  33398. OpenCounter(+1);
  33399. return rc;
  33400. }
  33401. /*
  33402. ** Delete the named file.
  33403. **
  33404. ** Note that Windows does not allow a file to be deleted if some other
  33405. ** process has it open. Sometimes a virus scanner or indexing program
  33406. ** will open a journal file shortly after it is created in order to do
  33407. ** whatever it does. While this other process is holding the
  33408. ** file open, we will be unable to delete it. To work around this
  33409. ** problem, we delay 100 milliseconds and try to delete again. Up
  33410. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  33411. ** up and returning an error.
  33412. */
  33413. static int winDelete(
  33414. sqlite3_vfs *pVfs, /* Not used on win32 */
  33415. const char *zFilename, /* Name of file to delete */
  33416. int syncDir /* Not used on win32 */
  33417. ){
  33418. int cnt = 0;
  33419. int rc;
  33420. DWORD attr;
  33421. DWORD lastErrno;
  33422. void *zConverted;
  33423. UNUSED_PARAMETER(pVfs);
  33424. UNUSED_PARAMETER(syncDir);
  33425. SimulateIOError(return SQLITE_IOERR_DELETE);
  33426. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  33427. zConverted = winConvertFromUtf8Filename(zFilename);
  33428. if( zConverted==0 ){
  33429. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33430. return SQLITE_IOERR_NOMEM;
  33431. }
  33432. if( osIsNT() ){
  33433. do {
  33434. #if SQLITE_OS_WINRT
  33435. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33436. memset(&sAttrData, 0, sizeof(sAttrData));
  33437. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  33438. &sAttrData) ){
  33439. attr = sAttrData.dwFileAttributes;
  33440. }else{
  33441. lastErrno = osGetLastError();
  33442. if( lastErrno==ERROR_FILE_NOT_FOUND
  33443. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33444. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33445. }else{
  33446. rc = SQLITE_ERROR;
  33447. }
  33448. break;
  33449. }
  33450. #else
  33451. attr = osGetFileAttributesW(zConverted);
  33452. #endif
  33453. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33454. lastErrno = osGetLastError();
  33455. if( lastErrno==ERROR_FILE_NOT_FOUND
  33456. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33457. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33458. }else{
  33459. rc = SQLITE_ERROR;
  33460. }
  33461. break;
  33462. }
  33463. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33464. rc = SQLITE_ERROR; /* Files only. */
  33465. break;
  33466. }
  33467. if ( osDeleteFileW(zConverted) ){
  33468. rc = SQLITE_OK; /* Deleted OK. */
  33469. break;
  33470. }
  33471. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33472. rc = SQLITE_ERROR; /* No more retries. */
  33473. break;
  33474. }
  33475. } while(1);
  33476. }
  33477. #ifdef SQLITE_WIN32_HAS_ANSI
  33478. else{
  33479. do {
  33480. attr = osGetFileAttributesA(zConverted);
  33481. if ( attr==INVALID_FILE_ATTRIBUTES ){
  33482. lastErrno = osGetLastError();
  33483. if( lastErrno==ERROR_FILE_NOT_FOUND
  33484. || lastErrno==ERROR_PATH_NOT_FOUND ){
  33485. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  33486. }else{
  33487. rc = SQLITE_ERROR;
  33488. }
  33489. break;
  33490. }
  33491. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  33492. rc = SQLITE_ERROR; /* Files only. */
  33493. break;
  33494. }
  33495. if ( osDeleteFileA(zConverted) ){
  33496. rc = SQLITE_OK; /* Deleted OK. */
  33497. break;
  33498. }
  33499. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  33500. rc = SQLITE_ERROR; /* No more retries. */
  33501. break;
  33502. }
  33503. } while(1);
  33504. }
  33505. #endif
  33506. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  33507. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  33508. }else{
  33509. winLogIoerr(cnt);
  33510. }
  33511. sqlite3_free(zConverted);
  33512. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  33513. return rc;
  33514. }
  33515. /*
  33516. ** Check the existence and status of a file.
  33517. */
  33518. static int winAccess(
  33519. sqlite3_vfs *pVfs, /* Not used on win32 */
  33520. const char *zFilename, /* Name of file to check */
  33521. int flags, /* Type of test to make on this file */
  33522. int *pResOut /* OUT: Result */
  33523. ){
  33524. DWORD attr;
  33525. int rc = 0;
  33526. DWORD lastErrno;
  33527. void *zConverted;
  33528. UNUSED_PARAMETER(pVfs);
  33529. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  33530. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  33531. zFilename, flags, pResOut));
  33532. zConverted = winConvertFromUtf8Filename(zFilename);
  33533. if( zConverted==0 ){
  33534. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  33535. return SQLITE_IOERR_NOMEM;
  33536. }
  33537. if( osIsNT() ){
  33538. int cnt = 0;
  33539. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  33540. memset(&sAttrData, 0, sizeof(sAttrData));
  33541. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  33542. GetFileExInfoStandard,
  33543. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  33544. if( rc ){
  33545. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  33546. ** as if it does not exist.
  33547. */
  33548. if( flags==SQLITE_ACCESS_EXISTS
  33549. && sAttrData.nFileSizeHigh==0
  33550. && sAttrData.nFileSizeLow==0 ){
  33551. attr = INVALID_FILE_ATTRIBUTES;
  33552. }else{
  33553. attr = sAttrData.dwFileAttributes;
  33554. }
  33555. }else{
  33556. winLogIoerr(cnt);
  33557. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  33558. sqlite3_free(zConverted);
  33559. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  33560. zFilename);
  33561. }else{
  33562. attr = INVALID_FILE_ATTRIBUTES;
  33563. }
  33564. }
  33565. }
  33566. #ifdef SQLITE_WIN32_HAS_ANSI
  33567. else{
  33568. attr = osGetFileAttributesA((char*)zConverted);
  33569. }
  33570. #endif
  33571. sqlite3_free(zConverted);
  33572. switch( flags ){
  33573. case SQLITE_ACCESS_READ:
  33574. case SQLITE_ACCESS_EXISTS:
  33575. rc = attr!=INVALID_FILE_ATTRIBUTES;
  33576. break;
  33577. case SQLITE_ACCESS_READWRITE:
  33578. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  33579. (attr & FILE_ATTRIBUTE_READONLY)==0;
  33580. break;
  33581. default:
  33582. assert(!"Invalid flags argument");
  33583. }
  33584. *pResOut = rc;
  33585. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  33586. zFilename, pResOut, *pResOut));
  33587. return SQLITE_OK;
  33588. }
  33589. /*
  33590. ** Returns non-zero if the specified path name starts with a drive letter
  33591. ** followed by a colon character.
  33592. */
  33593. static BOOL winIsDriveLetterAndColon(
  33594. const char *zPathname
  33595. ){
  33596. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  33597. }
  33598. /*
  33599. ** Returns non-zero if the specified path name should be used verbatim. If
  33600. ** non-zero is returned from this function, the calling function must simply
  33601. ** use the provided path name verbatim -OR- resolve it into a full path name
  33602. ** using the GetFullPathName Win32 API function (if available).
  33603. */
  33604. static BOOL winIsVerbatimPathname(
  33605. const char *zPathname
  33606. ){
  33607. /*
  33608. ** If the path name starts with a forward slash or a backslash, it is either
  33609. ** a legal UNC name, a volume relative path, or an absolute path name in the
  33610. ** "Unix" format on Windows. There is no easy way to differentiate between
  33611. ** the final two cases; therefore, we return the safer return value of TRUE
  33612. ** so that callers of this function will simply use it verbatim.
  33613. */
  33614. if ( winIsDirSep(zPathname[0]) ){
  33615. return TRUE;
  33616. }
  33617. /*
  33618. ** If the path name starts with a letter and a colon it is either a volume
  33619. ** relative path or an absolute path. Callers of this function must not
  33620. ** attempt to treat it as a relative path name (i.e. they should simply use
  33621. ** it verbatim).
  33622. */
  33623. if ( winIsDriveLetterAndColon(zPathname) ){
  33624. return TRUE;
  33625. }
  33626. /*
  33627. ** If we get to this point, the path name should almost certainly be a purely
  33628. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  33629. */
  33630. return FALSE;
  33631. }
  33632. /*
  33633. ** Turn a relative pathname into a full pathname. Write the full
  33634. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  33635. ** bytes in size.
  33636. */
  33637. static int winFullPathname(
  33638. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  33639. const char *zRelative, /* Possibly relative input path */
  33640. int nFull, /* Size of output buffer in bytes */
  33641. char *zFull /* Output buffer */
  33642. ){
  33643. #if defined(__CYGWIN__)
  33644. SimulateIOError( return SQLITE_ERROR );
  33645. UNUSED_PARAMETER(nFull);
  33646. assert( nFull>=pVfs->mxPathname );
  33647. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33648. /*
  33649. ** NOTE: We are dealing with a relative path name and the data
  33650. ** directory has been set. Therefore, use it as the basis
  33651. ** for converting the relative path name to an absolute
  33652. ** one by prepending the data directory and a slash.
  33653. */
  33654. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  33655. if( !zOut ){
  33656. return SQLITE_IOERR_NOMEM;
  33657. }
  33658. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A|CCP_RELATIVE, zRelative, zOut,
  33659. pVfs->mxPathname+1)<0 ){
  33660. sqlite3_free(zOut);
  33661. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33662. "winFullPathname1", zRelative);
  33663. }
  33664. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33665. sqlite3_data_directory, winGetDirDep(), zOut);
  33666. sqlite3_free(zOut);
  33667. }else{
  33668. if( cygwin_conv_path(CCP_POSIX_TO_WIN_A, zRelative, zFull, nFull)<0 ){
  33669. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  33670. "winFullPathname2", zRelative);
  33671. }
  33672. }
  33673. return SQLITE_OK;
  33674. #endif
  33675. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  33676. SimulateIOError( return SQLITE_ERROR );
  33677. /* WinCE has no concept of a relative pathname, or so I am told. */
  33678. /* WinRT has no way to convert a relative path to an absolute one. */
  33679. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33680. /*
  33681. ** NOTE: We are dealing with a relative path name and the data
  33682. ** directory has been set. Therefore, use it as the basis
  33683. ** for converting the relative path name to an absolute
  33684. ** one by prepending the data directory and a backslash.
  33685. */
  33686. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33687. sqlite3_data_directory, winGetDirDep(), zRelative);
  33688. }else{
  33689. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  33690. }
  33691. return SQLITE_OK;
  33692. #endif
  33693. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  33694. DWORD nByte;
  33695. void *zConverted;
  33696. char *zOut;
  33697. /* If this path name begins with "/X:", where "X" is any alphabetic
  33698. ** character, discard the initial "/" from the pathname.
  33699. */
  33700. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  33701. zRelative++;
  33702. }
  33703. /* It's odd to simulate an io-error here, but really this is just
  33704. ** using the io-error infrastructure to test that SQLite handles this
  33705. ** function failing. This function could fail if, for example, the
  33706. ** current working directory has been unlinked.
  33707. */
  33708. SimulateIOError( return SQLITE_ERROR );
  33709. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  33710. /*
  33711. ** NOTE: We are dealing with a relative path name and the data
  33712. ** directory has been set. Therefore, use it as the basis
  33713. ** for converting the relative path name to an absolute
  33714. ** one by prepending the data directory and a backslash.
  33715. */
  33716. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%s%s",
  33717. sqlite3_data_directory, winGetDirDep(), zRelative);
  33718. return SQLITE_OK;
  33719. }
  33720. zConverted = winConvertFromUtf8Filename(zRelative);
  33721. if( zConverted==0 ){
  33722. return SQLITE_IOERR_NOMEM;
  33723. }
  33724. if( osIsNT() ){
  33725. LPWSTR zTemp;
  33726. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  33727. if( nByte==0 ){
  33728. sqlite3_free(zConverted);
  33729. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33730. "winFullPathname1", zRelative);
  33731. }
  33732. nByte += 3;
  33733. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33734. if( zTemp==0 ){
  33735. sqlite3_free(zConverted);
  33736. return SQLITE_IOERR_NOMEM;
  33737. }
  33738. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  33739. if( nByte==0 ){
  33740. sqlite3_free(zConverted);
  33741. sqlite3_free(zTemp);
  33742. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33743. "winFullPathname2", zRelative);
  33744. }
  33745. sqlite3_free(zConverted);
  33746. zOut = winUnicodeToUtf8(zTemp);
  33747. sqlite3_free(zTemp);
  33748. }
  33749. #ifdef SQLITE_WIN32_HAS_ANSI
  33750. else{
  33751. char *zTemp;
  33752. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  33753. if( nByte==0 ){
  33754. sqlite3_free(zConverted);
  33755. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33756. "winFullPathname3", zRelative);
  33757. }
  33758. nByte += 3;
  33759. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  33760. if( zTemp==0 ){
  33761. sqlite3_free(zConverted);
  33762. return SQLITE_IOERR_NOMEM;
  33763. }
  33764. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  33765. if( nByte==0 ){
  33766. sqlite3_free(zConverted);
  33767. sqlite3_free(zTemp);
  33768. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  33769. "winFullPathname4", zRelative);
  33770. }
  33771. sqlite3_free(zConverted);
  33772. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  33773. sqlite3_free(zTemp);
  33774. }
  33775. #endif
  33776. if( zOut ){
  33777. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  33778. sqlite3_free(zOut);
  33779. return SQLITE_OK;
  33780. }else{
  33781. return SQLITE_IOERR_NOMEM;
  33782. }
  33783. #endif
  33784. }
  33785. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  33786. /*
  33787. ** Interfaces for opening a shared library, finding entry points
  33788. ** within the shared library, and closing the shared library.
  33789. */
  33790. /*
  33791. ** Interfaces for opening a shared library, finding entry points
  33792. ** within the shared library, and closing the shared library.
  33793. */
  33794. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  33795. HANDLE h;
  33796. void *zConverted = winConvertFromUtf8Filename(zFilename);
  33797. UNUSED_PARAMETER(pVfs);
  33798. if( zConverted==0 ){
  33799. return 0;
  33800. }
  33801. if( osIsNT() ){
  33802. #if SQLITE_OS_WINRT
  33803. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  33804. #else
  33805. h = osLoadLibraryW((LPCWSTR)zConverted);
  33806. #endif
  33807. }
  33808. #ifdef SQLITE_WIN32_HAS_ANSI
  33809. else{
  33810. h = osLoadLibraryA((char*)zConverted);
  33811. }
  33812. #endif
  33813. sqlite3_free(zConverted);
  33814. return (void*)h;
  33815. }
  33816. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  33817. UNUSED_PARAMETER(pVfs);
  33818. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  33819. }
  33820. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  33821. UNUSED_PARAMETER(pVfs);
  33822. return (void(*)(void))osGetProcAddressA((HANDLE)pH, zSym);
  33823. }
  33824. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  33825. UNUSED_PARAMETER(pVfs);
  33826. osFreeLibrary((HANDLE)pHandle);
  33827. }
  33828. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  33829. #define winDlOpen 0
  33830. #define winDlError 0
  33831. #define winDlSym 0
  33832. #define winDlClose 0
  33833. #endif
  33834. /*
  33835. ** Write up to nBuf bytes of randomness into zBuf.
  33836. */
  33837. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33838. int n = 0;
  33839. UNUSED_PARAMETER(pVfs);
  33840. #if defined(SQLITE_TEST)
  33841. n = nBuf;
  33842. memset(zBuf, 0, nBuf);
  33843. #else
  33844. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  33845. SYSTEMTIME x;
  33846. osGetSystemTime(&x);
  33847. memcpy(&zBuf[n], &x, sizeof(x));
  33848. n += sizeof(x);
  33849. }
  33850. if( sizeof(DWORD)<=nBuf-n ){
  33851. DWORD pid = osGetCurrentProcessId();
  33852. memcpy(&zBuf[n], &pid, sizeof(pid));
  33853. n += sizeof(pid);
  33854. }
  33855. #if SQLITE_OS_WINRT
  33856. if( sizeof(ULONGLONG)<=nBuf-n ){
  33857. ULONGLONG cnt = osGetTickCount64();
  33858. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33859. n += sizeof(cnt);
  33860. }
  33861. #else
  33862. if( sizeof(DWORD)<=nBuf-n ){
  33863. DWORD cnt = osGetTickCount();
  33864. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  33865. n += sizeof(cnt);
  33866. }
  33867. #endif
  33868. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  33869. LARGE_INTEGER i;
  33870. osQueryPerformanceCounter(&i);
  33871. memcpy(&zBuf[n], &i, sizeof(i));
  33872. n += sizeof(i);
  33873. }
  33874. #endif
  33875. return n;
  33876. }
  33877. /*
  33878. ** Sleep for a little while. Return the amount of time slept.
  33879. */
  33880. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  33881. sqlite3_win32_sleep((microsec+999)/1000);
  33882. UNUSED_PARAMETER(pVfs);
  33883. return ((microsec+999)/1000)*1000;
  33884. }
  33885. /*
  33886. ** The following variable, if set to a non-zero value, is interpreted as
  33887. ** the number of seconds since 1970 and is used to set the result of
  33888. ** sqlite3OsCurrentTime() during testing.
  33889. */
  33890. #ifdef SQLITE_TEST
  33891. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  33892. #endif
  33893. /*
  33894. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  33895. ** the current time and date as a Julian Day number times 86_400_000. In
  33896. ** other words, write into *piNow the number of milliseconds since the Julian
  33897. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  33898. ** proleptic Gregorian calendar.
  33899. **
  33900. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  33901. ** cannot be found.
  33902. */
  33903. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  33904. /* FILETIME structure is a 64-bit value representing the number of
  33905. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  33906. */
  33907. FILETIME ft;
  33908. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  33909. #ifdef SQLITE_TEST
  33910. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  33911. #endif
  33912. /* 2^32 - to avoid use of LL and warnings in gcc */
  33913. static const sqlite3_int64 max32BitValue =
  33914. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  33915. (sqlite3_int64)294967296;
  33916. #if SQLITE_OS_WINCE
  33917. SYSTEMTIME time;
  33918. osGetSystemTime(&time);
  33919. /* if SystemTimeToFileTime() fails, it returns zero. */
  33920. if (!osSystemTimeToFileTime(&time,&ft)){
  33921. return SQLITE_ERROR;
  33922. }
  33923. #else
  33924. osGetSystemTimeAsFileTime( &ft );
  33925. #endif
  33926. *piNow = winFiletimeEpoch +
  33927. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  33928. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  33929. #ifdef SQLITE_TEST
  33930. if( sqlite3_current_time ){
  33931. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  33932. }
  33933. #endif
  33934. UNUSED_PARAMETER(pVfs);
  33935. return SQLITE_OK;
  33936. }
  33937. /*
  33938. ** Find the current time (in Universal Coordinated Time). Write the
  33939. ** current time and date as a Julian Day number into *prNow and
  33940. ** return 0. Return 1 if the time and date cannot be found.
  33941. */
  33942. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  33943. int rc;
  33944. sqlite3_int64 i;
  33945. rc = winCurrentTimeInt64(pVfs, &i);
  33946. if( !rc ){
  33947. *prNow = i/86400000.0;
  33948. }
  33949. return rc;
  33950. }
  33951. /*
  33952. ** The idea is that this function works like a combination of
  33953. ** GetLastError() and FormatMessage() on Windows (or errno and
  33954. ** strerror_r() on Unix). After an error is returned by an OS
  33955. ** function, SQLite calls this function with zBuf pointing to
  33956. ** a buffer of nBuf bytes. The OS layer should populate the
  33957. ** buffer with a nul-terminated UTF-8 encoded error message
  33958. ** describing the last IO error to have occurred within the calling
  33959. ** thread.
  33960. **
  33961. ** If the error message is too large for the supplied buffer,
  33962. ** it should be truncated. The return value of xGetLastError
  33963. ** is zero if the error message fits in the buffer, or non-zero
  33964. ** otherwise (if the message was truncated). If non-zero is returned,
  33965. ** then it is not necessary to include the nul-terminator character
  33966. ** in the output buffer.
  33967. **
  33968. ** Not supplying an error message will have no adverse effect
  33969. ** on SQLite. It is fine to have an implementation that never
  33970. ** returns an error message:
  33971. **
  33972. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33973. ** assert(zBuf[0]=='\0');
  33974. ** return 0;
  33975. ** }
  33976. **
  33977. ** However if an error message is supplied, it will be incorporated
  33978. ** by sqlite into the error message available to the user using
  33979. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  33980. */
  33981. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  33982. UNUSED_PARAMETER(pVfs);
  33983. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  33984. }
  33985. /*
  33986. ** Initialize and deinitialize the operating system interface.
  33987. */
  33988. SQLITE_API int sqlite3_os_init(void){
  33989. static sqlite3_vfs winVfs = {
  33990. 3, /* iVersion */
  33991. sizeof(winFile), /* szOsFile */
  33992. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  33993. 0, /* pNext */
  33994. "win32", /* zName */
  33995. 0, /* pAppData */
  33996. winOpen, /* xOpen */
  33997. winDelete, /* xDelete */
  33998. winAccess, /* xAccess */
  33999. winFullPathname, /* xFullPathname */
  34000. winDlOpen, /* xDlOpen */
  34001. winDlError, /* xDlError */
  34002. winDlSym, /* xDlSym */
  34003. winDlClose, /* xDlClose */
  34004. winRandomness, /* xRandomness */
  34005. winSleep, /* xSleep */
  34006. winCurrentTime, /* xCurrentTime */
  34007. winGetLastError, /* xGetLastError */
  34008. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  34009. winSetSystemCall, /* xSetSystemCall */
  34010. winGetSystemCall, /* xGetSystemCall */
  34011. winNextSystemCall, /* xNextSystemCall */
  34012. };
  34013. #if defined(SQLITE_WIN32_HAS_WIDE)
  34014. static sqlite3_vfs winLongPathVfs = {
  34015. 3, /* iVersion */
  34016. sizeof(winFile), /* szOsFile */
  34017. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  34018. 0, /* pNext */
  34019. "win32-longpath", /* zName */
  34020. 0, /* pAppData */
  34021. winOpen, /* xOpen */
  34022. winDelete, /* xDelete */
  34023. winAccess, /* xAccess */
  34024. winFullPathname, /* xFullPathname */
  34025. winDlOpen, /* xDlOpen */
  34026. winDlError, /* xDlError */
  34027. winDlSym, /* xDlSym */
  34028. winDlClose, /* xDlClose */
  34029. winRandomness, /* xRandomness */
  34030. winSleep, /* xSleep */
  34031. winCurrentTime, /* xCurrentTime */
  34032. winGetLastError, /* xGetLastError */
  34033. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  34034. winSetSystemCall, /* xSetSystemCall */
  34035. winGetSystemCall, /* xGetSystemCall */
  34036. winNextSystemCall, /* xNextSystemCall */
  34037. };
  34038. #endif
  34039. /* Double-check that the aSyscall[] array has been constructed
  34040. ** correctly. See ticket [bb3a86e890c8e96ab] */
  34041. assert( ArraySize(aSyscall)==75 );
  34042. /* get memory map allocation granularity */
  34043. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  34044. #if SQLITE_OS_WINRT
  34045. osGetNativeSystemInfo(&winSysInfo);
  34046. #else
  34047. osGetSystemInfo(&winSysInfo);
  34048. #endif
  34049. assert( winSysInfo.dwAllocationGranularity>0 );
  34050. assert( winSysInfo.dwPageSize>0 );
  34051. sqlite3_vfs_register(&winVfs, 1);
  34052. #if defined(SQLITE_WIN32_HAS_WIDE)
  34053. sqlite3_vfs_register(&winLongPathVfs, 0);
  34054. #endif
  34055. return SQLITE_OK;
  34056. }
  34057. SQLITE_API int sqlite3_os_end(void){
  34058. #if SQLITE_OS_WINRT
  34059. if( sleepObj!=NULL ){
  34060. osCloseHandle(sleepObj);
  34061. sleepObj = NULL;
  34062. }
  34063. #endif
  34064. return SQLITE_OK;
  34065. }
  34066. #endif /* SQLITE_OS_WIN */
  34067. /************** End of os_win.c **********************************************/
  34068. /************** Begin file os_rtt.c ******************************************/
  34069. /*
  34070. ** 2004 May 22
  34071. **
  34072. ** The author disclaims copyright to this source code. In place of
  34073. ** a legal notice, here is a blessing:
  34074. **
  34075. ** May you do good and not evil.
  34076. ** May you find forgiveness for yourself and forgive others.
  34077. ** May you share freely, never taking more than you give.
  34078. **
  34079. ******************************************************************************
  34080. **
  34081. ** This file contains code that is specific to Windows.
  34082. */
  34083. #if SQLITE_OS_RTT /* This file is used for rt-thread only */
  34084. /* #include <rtthread.h> */
  34085. /*
  34086. ** Include code that is common to all os_*.c files
  34087. */
  34088. /************** Include os_common.h in the middle of os_rtt.c ****************/
  34089. /************** Begin file os_common.h ***************************************/
  34090. /*
  34091. ** 2004 May 22
  34092. **
  34093. ** The author disclaims copyright to this source code. In place of
  34094. ** a legal notice, here is a blessing:
  34095. **
  34096. ** May you do good and not evil.
  34097. ** May you find forgiveness for yourself and forgive others.
  34098. ** May you share freely, never taking more than you give.
  34099. **
  34100. ******************************************************************************
  34101. **
  34102. ** This file contains macros and a little bit of code that is common to
  34103. ** all of the platform-specific files (os_*.c) and is #included into those
  34104. ** files.
  34105. **
  34106. ** This file should be #included by the os_*.c files only. It is not a
  34107. ** general purpose header file.
  34108. */
  34109. #ifndef _OS_COMMON_H_
  34110. #define _OS_COMMON_H_
  34111. /*
  34112. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  34113. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  34114. ** switch. The following code should catch this problem at compile-time.
  34115. */
  34116. #ifdef MEMORY_DEBUG
  34117. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  34118. #endif
  34119. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  34120. # ifndef SQLITE_DEBUG_OS_TRACE
  34121. # define SQLITE_DEBUG_OS_TRACE 0
  34122. # endif
  34123. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  34124. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  34125. #else
  34126. # define OSTRACE(X)
  34127. #endif
  34128. /*
  34129. ** Macros for performance tracing. Normally turned off. Only works
  34130. ** on i486 hardware.
  34131. */
  34132. #ifdef SQLITE_PERFORMANCE_TRACE
  34133. /*
  34134. ** hwtime.h contains inline assembler code for implementing
  34135. ** high-performance timing routines.
  34136. */
  34137. /************** Include hwtime.h in the middle of os_common.h ****************/
  34138. /************** Begin file hwtime.h ******************************************/
  34139. /*
  34140. ** 2008 May 27
  34141. **
  34142. ** The author disclaims copyright to this source code. In place of
  34143. ** a legal notice, here is a blessing:
  34144. **
  34145. ** May you do good and not evil.
  34146. ** May you find forgiveness for yourself and forgive others.
  34147. ** May you share freely, never taking more than you give.
  34148. **
  34149. ******************************************************************************
  34150. **
  34151. ** This file contains inline asm code for retrieving "high-performance"
  34152. ** counters for x86 class CPUs.
  34153. */
  34154. #ifndef _HWTIME_H_
  34155. #define _HWTIME_H_
  34156. /*
  34157. ** The following routine only works on pentium-class (or newer) processors.
  34158. ** It uses the RDTSC opcode to read the cycle count value out of the
  34159. ** processor and returns that value. This can be used for high-res
  34160. ** profiling.
  34161. */
  34162. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  34163. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  34164. #if defined(__GNUC__)
  34165. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34166. unsigned int lo, hi;
  34167. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  34168. return (sqlite_uint64)hi << 32 | lo;
  34169. }
  34170. #elif defined(_MSC_VER)
  34171. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  34172. __asm {
  34173. rdtsc
  34174. ret ; return value at EDX:EAX
  34175. }
  34176. }
  34177. #endif
  34178. #elif (defined(__GNUC__) && defined(__x86_64__))
  34179. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34180. unsigned long val;
  34181. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  34182. return val;
  34183. }
  34184. #elif (defined(__GNUC__) && defined(__ppc__))
  34185. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  34186. unsigned long long retval;
  34187. unsigned long junk;
  34188. __asm__ __volatile__ ("\n\
  34189. 1: mftbu %1\n\
  34190. mftb %L0\n\
  34191. mftbu %0\n\
  34192. cmpw %0,%1\n\
  34193. bne 1b"
  34194. : "=r" (retval), "=r" (junk));
  34195. return retval;
  34196. }
  34197. #else
  34198. #error Need implementation of sqlite3Hwtime() for your platform.
  34199. /*
  34200. ** To compile without implementing sqlite3Hwtime() for your platform,
  34201. ** you can remove the above #error and use the following
  34202. ** stub function. You will lose timing support for many
  34203. ** of the debugging and testing utilities, but it should at
  34204. ** least compile and run.
  34205. */
  34206. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  34207. #endif
  34208. #endif /* !defined(_HWTIME_H_) */
  34209. /************** End of hwtime.h **********************************************/
  34210. /************** Continuing where we left off in os_common.h ******************/
  34211. static sqlite_uint64 g_start;
  34212. static sqlite_uint64 g_elapsed;
  34213. #define TIMER_START g_start=sqlite3Hwtime()
  34214. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  34215. #define TIMER_ELAPSED g_elapsed
  34216. #else
  34217. #define TIMER_START
  34218. #define TIMER_END
  34219. #define TIMER_ELAPSED ((sqlite_uint64)0)
  34220. #endif
  34221. /*
  34222. ** If we compile with the SQLITE_TEST macro set, then the following block
  34223. ** of code will give us the ability to simulate a disk I/O error. This
  34224. ** is used for testing the I/O recovery logic.
  34225. */
  34226. #ifdef SQLITE_TEST
  34227. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  34228. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  34229. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  34230. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  34231. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  34232. SQLITE_API int sqlite3_diskfull_pending = 0;
  34233. SQLITE_API int sqlite3_diskfull = 0;
  34234. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  34235. #define SimulateIOError(CODE) \
  34236. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  34237. || sqlite3_io_error_pending-- == 1 ) \
  34238. { local_ioerr(); CODE; }
  34239. static void local_ioerr(){
  34240. IOTRACE(("IOERR\n"));
  34241. sqlite3_io_error_hit++;
  34242. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  34243. }
  34244. #define SimulateDiskfullError(CODE) \
  34245. if( sqlite3_diskfull_pending ){ \
  34246. if( sqlite3_diskfull_pending == 1 ){ \
  34247. local_ioerr(); \
  34248. sqlite3_diskfull = 1; \
  34249. sqlite3_io_error_hit = 1; \
  34250. CODE; \
  34251. }else{ \
  34252. sqlite3_diskfull_pending--; \
  34253. } \
  34254. }
  34255. #else
  34256. #define SimulateIOErrorBenign(X)
  34257. #define SimulateIOError(A)
  34258. #define SimulateDiskfullError(A)
  34259. #endif
  34260. /*
  34261. ** When testing, keep a count of the number of open files.
  34262. */
  34263. #ifdef SQLITE_TEST
  34264. SQLITE_API int sqlite3_open_file_count = 0;
  34265. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  34266. #else
  34267. #define OpenCounter(X)
  34268. #endif
  34269. #endif /* !defined(_OS_COMMON_H_) */
  34270. /************** End of os_common.h *******************************************/
  34271. /************** Continuing where we left off in os_rtt.c *********************/
  34272. /*
  34273. ** Compiling and using WAL mode requires several APIs that are not
  34274. ** available in rt-thread.
  34275. */
  34276. #if !defined(SQLITE_OMIT_WAL)
  34277. # error "WAL mode requires not support from the rt-thread, compile\
  34278. with SQLITE_OMIT_WAL."
  34279. #endif
  34280. /*
  34281. ** Are most of the rtt ANSI APIs available (i.e. with certain exceptions
  34282. ** based on the sub-platform)?
  34283. */
  34284. #if !defined(SQLITE_RTT_NO_ANSI)
  34285. # warning "please ensure rtt ANSI APIs is available, otherwise compile with\
  34286. SQLITE_RTT_NO_ANSI"
  34287. # define SQLITE_RTT_HAS_ANSI
  34288. #endif
  34289. /*
  34290. ** Are most of the rtt Unicode APIs available (i.e. with certain exceptions
  34291. ** based on the sub-platform)?
  34292. */
  34293. #if !defined(SQLITE_RTT_NO_WIDE)
  34294. # error "rtt not support Unicode APIs"
  34295. # define SQLITE_RTT_HAS_WIDE
  34296. #endif
  34297. /*
  34298. ** Make sure at least one set of rtt APIs is available.
  34299. */
  34300. #if !defined(SQLITE_RTT_HAS_ANSI) && !defined(SQLITE_RTT_HAS_WIDE)
  34301. # error "At least one of SQLITE_RTT_HAS_ANSI and SQLITE_RTT_HAS_WIDE\
  34302. must be defined."
  34303. #endif
  34304. /*
  34305. ** Maximum pathname length (in chars) for rtt. This should normally be
  34306. ** MAX_PATH.
  34307. */
  34308. #ifndef SQLITE_RTT_MAX_PATH_CHARS
  34309. # warning "default Maximum pathname length be 255, otherwise compile with\
  34310. SQLITE_RTT_MAX_PATH_CHARS=?"
  34311. # define SQLITE_RTT_MAX_PATH_CHARS (255)
  34312. #endif
  34313. /*
  34314. ** Maximum supported path-length.
  34315. */
  34316. #define MAX_PATHNAME 512
  34317. /*
  34318. ** Returns non-zero if the character should be treated as a directory
  34319. ** separator.
  34320. */
  34321. #ifndef rttIsDirSep
  34322. # define rttIsDirSep(a) ((a) == '/')
  34323. #endif
  34324. /*
  34325. ** This macro is used when a local variable is set to a value that is
  34326. ** [sometimes] not used by the code (e.g. via conditional compilation).
  34327. */
  34328. #ifndef UNUSED_VARIABLE_VALUE
  34329. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  34330. #endif
  34331. /*
  34332. ** Returns the string that should be used as the directory separator.
  34333. */
  34334. #ifndef rttGetDirDep
  34335. # define rttGetDirDep() "/"
  34336. #endif
  34337. /*
  34338. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  34339. ** portability layer.
  34340. */
  34341. typedef struct rttFile rttFile;
  34342. struct rttFile {
  34343. sqlite3_io_methods const *pMethod; /* Always the first entry */
  34344. sqlite3_vfs *pVfs; /* The VFS that created this rttFile */
  34345. int h; /* The file descriptor */
  34346. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  34347. unsigned char eFileLock; /* The type of lock held on this fd */
  34348. int lastErrno; /* The unix errno from last I/O error */
  34349. void *lockingContext; /* Locking style specific state */
  34350. const char *zPath; /* Name of the file */
  34351. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  34352. #if SQLITE_ENABLE_LOCKING_STYLE
  34353. int openFlags; /* The flags specified at open() */
  34354. #endif
  34355. #if SQLITE_ENABLE_LOCKING_STYLE
  34356. unsigned fsFlags; /* cached details from statfs() */
  34357. #endif
  34358. #ifdef SQLITE_DEBUG
  34359. /* The next group of variables are used to track whether or not the
  34360. ** transaction counter in bytes 24-27 of database files are updated
  34361. ** whenever any part of the database changes. An assertion fault will
  34362. ** occur if a file is updated without also updating the transaction
  34363. ** counter. This test is made to avoid new problems similar to the
  34364. ** one described by ticket #3584.
  34365. */
  34366. unsigned char transCntrChng; /* True if the transaction counter changed */
  34367. unsigned char dbUpdate; /* True if any part of database file changed */
  34368. unsigned char inNormalWrite; /* True if in a normal write operation */
  34369. #endif
  34370. #ifdef SQLITE_TEST
  34371. /* In test mode, increase the size of this structure a bit so that
  34372. ** it is larger than the struct CrashFile defined in test6.c.
  34373. */
  34374. char aPadding[32];
  34375. #endif
  34376. };
  34377. /*
  34378. ** Allowed values for the rttFile.ctrlFlags bitmask:
  34379. */
  34380. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  34381. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  34382. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  34383. #ifndef SQLITE_DISABLE_DIRSYNC
  34384. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  34385. #else
  34386. # define UNIXFILE_DIRSYNC 0x00
  34387. #endif
  34388. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  34389. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  34390. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  34391. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  34392. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  34393. /*
  34394. ** The following variable is (normally) set once and never changes
  34395. ** thereafter. It records whether the operating system is Win9x
  34396. ** or WinNT.
  34397. **
  34398. ** 0: Operating system unknown.
  34399. ** 1: Operating system is rtt.
  34400. **
  34401. ** In order to facilitate testing on a rtt system, the test fixture
  34402. ** can manually set this value to 1 to emulate Win98 behavior.
  34403. */
  34404. #ifdef SQLITE_TEST
  34405. SQLITE_API int sqlite3_os_type = 0;
  34406. #elif !SQLITE_OS_RTT && \
  34407. defined(SQLITE_RTT_HAS_ANSI) && defined(SQLITE_RTT_HAS_WIDE)
  34408. static int sqlite3_os_type = 0;
  34409. #endif
  34410. #ifndef SYSCALL
  34411. # define SYSCALL sqlite3_syscall_ptr
  34412. #endif
  34413. #include <dfs_posix.h>
  34414. static int _Access(const char *pathname, int mode)
  34415. {
  34416. int fd;
  34417. fd = open(pathname, O_RDONLY, mode);
  34418. if (fd >= 0)
  34419. {
  34420. close(fd);
  34421. return 0;
  34422. }
  34423. return -1;
  34424. }
  34425. /*
  34426. ** Invoke open(). Do so multiple times, until it either succeeds or
  34427. ** fails for some reason other than EINTR.
  34428. **
  34429. ** If the file creation mode "m" is 0 then set it to the default for
  34430. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  34431. ** 0644) as modified by the system umask. If m is not 0, then
  34432. ** make the file creation mode be exactly m ignoring the umask.
  34433. **
  34434. ** The m parameter will be non-zero only when creating -wal, -journal,
  34435. ** and -shm files. We want those files to have *exactly* the same
  34436. ** permissions as their original database, unadulterated by the umask.
  34437. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  34438. ** transaction crashes and leaves behind hot journals, then any
  34439. ** process that is able to write to the database will also be able to
  34440. ** recover the hot journals.
  34441. */
  34442. static int robust_open(const char *z, int f, mode_t m);
  34443. /*
  34444. ** Open a file descriptor to the directory containing file zFilename.
  34445. ** If successful, *pFd is set to the opened file descriptor and
  34446. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34447. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34448. ** value.
  34449. **
  34450. ** The directory file descriptor is used for only one thing - to
  34451. ** fsync() a directory to make sure file creation and deletion events
  34452. ** are flushed to disk. Such fsyncs are not needed on newer
  34453. ** journaling filesystems, but are required on older filesystems.
  34454. **
  34455. ** This routine can be overridden using the xSetSysCall interface.
  34456. ** The ability to override this routine was added in support of the
  34457. ** chromium sandbox. Opening a directory is a security risk (we are
  34458. ** told) so making it overrideable allows the chromium sandbox to
  34459. ** replace this routine with a harmless no-op. To make this routine
  34460. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34461. ** *pFd set to a negative number.
  34462. **
  34463. ** If SQLITE_OK is returned, the caller is responsible for closing
  34464. ** the file descriptor *pFd using close().
  34465. */
  34466. static int openDirectory(const char *zFilename, int *pFd);
  34467. /*
  34468. ** Many system calls are accessed through pointer-to-functions so that
  34469. ** they may be overridden at runtime to facilitate fault injection during
  34470. ** testing and sandboxing. The following array holds the names and pointers
  34471. ** to all overrideable system calls.
  34472. */
  34473. static struct rtt_syscall {
  34474. const char *zName; /* Name of the system call */
  34475. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  34476. sqlite3_syscall_ptr pDefault; /* Default value */
  34477. } aSyscall[] = {
  34478. {"sleep", (sqlite3_syscall_ptr)rt_thread_delay, 0},
  34479. #define osSleep ((rt_err_t(*)(rt_tick_t))aSyscall[0].pCurrent)
  34480. { "open", (sqlite3_syscall_ptr)open, 0 },
  34481. #define osOpen ((int(*)(const char*,int,int))aSyscall[1].pCurrent)
  34482. { "close", (sqlite3_syscall_ptr)close, 0 },
  34483. #define osClose ((int(*)(int))aSyscall[2].pCurrent)
  34484. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  34485. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  34486. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  34487. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  34488. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  34489. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  34490. { "read", (sqlite3_syscall_ptr)read, 0 },
  34491. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[6].pCurrent)
  34492. { "write", (sqlite3_syscall_ptr)write, 0 },
  34493. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[7].pCurrent)
  34494. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  34495. #define osUnlink ((int(*)(const char*))aSyscall[8].pCurrent)
  34496. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  34497. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[9].pCurrent)
  34498. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  34499. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[10].pCurrent)
  34500. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  34501. #define osRmdir ((int(*)(const char*))aSyscall[11].pCurrent)
  34502. {"access", (sqlite3_syscall_ptr)_Access, 0 },
  34503. #define osAccess ((int(*)(const char*, int))aSyscall[12].pCurrent)
  34504. }; /* End of the overrideable system calls */
  34505. /*
  34506. ** Do not accept any file descriptor less than this value, in order to avoid
  34507. ** opening database file using file descriptors that are commonly used for
  34508. ** standard input, output, and error.
  34509. */
  34510. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  34511. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  34512. #endif
  34513. /*
  34514. ** Invoke open(). Do so multiple times, until it either succeeds or
  34515. ** fails for some reason other than EINTR.
  34516. **
  34517. ** If the file creation mode "m" is 0 then set it to the default for
  34518. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  34519. ** 0644) as modified by the system umask. If m is not 0, then
  34520. ** make the file creation mode be exactly m ignoring the umask.
  34521. **
  34522. ** The m parameter will be non-zero only when creating -wal, -journal,
  34523. ** and -shm files. We want those files to have *exactly* the same
  34524. ** permissions as their original database, unadulterated by the umask.
  34525. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  34526. ** transaction crashes and leaves behind hot journals, then any
  34527. ** process that is able to write to the database will also be able to
  34528. ** recover the hot journals.
  34529. */
  34530. static int robust_open(const char *z, int f, mode_t m){
  34531. int fd;
  34532. mode_t m2 = m ;
  34533. while(1){
  34534. #if defined(O_CLOEXEC)
  34535. fd = osOpen(z,f|O_CLOEXEC,m2);
  34536. #else
  34537. fd = osOpen(z,f,m2);
  34538. #endif
  34539. if( fd<0 ){
  34540. if( errno==EINTR ) continue;
  34541. break;
  34542. }
  34543. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  34544. osClose(fd);
  34545. sqlite3_log(SQLITE_WARNING,
  34546. "attempt to open \"%s\" as file descriptor %d", z, fd);
  34547. fd = -1;
  34548. if( osOpen("/dev/null", f, m)<0 ) break;
  34549. }
  34550. return fd;
  34551. }
  34552. /*
  34553. ** Open a file descriptor to the directory containing file zFilename.
  34554. ** If successful, *pFd is set to the opened file descriptor and
  34555. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  34556. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  34557. ** value.
  34558. **
  34559. ** The directory file descriptor is used for only one thing - to
  34560. ** fsync() a directory to make sure file creation and deletion events
  34561. ** are flushed to disk. Such fsyncs are not needed on newer
  34562. ** journaling filesystems, but are required on older filesystems.
  34563. **
  34564. ** This routine can be overridden using the xSetSysCall interface.
  34565. ** The ability to override this routine was added in support of the
  34566. ** chromium sandbox. Opening a directory is a security risk (we are
  34567. ** told) so making it overrideable allows the chromium sandbox to
  34568. ** replace this routine with a harmless no-op. To make this routine
  34569. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  34570. ** *pFd set to a negative number.
  34571. **
  34572. ** If SQLITE_OK is returned, the caller is responsible for closing
  34573. ** the file descriptor *pFd using close().
  34574. */
  34575. static int openDirectory(const char *zFilename, int *pFd){
  34576. int ii;
  34577. int fd = -1;
  34578. char zDirname[MAX_PATHNAME+1];
  34579. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  34580. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  34581. if( ii>0 ){
  34582. zDirname[ii] = '\0';
  34583. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  34584. if( fd>=0 ){
  34585. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  34586. }
  34587. }
  34588. *pFd = fd;
  34589. return (fd>=0?SQLITE_OK:rttLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  34590. }
  34591. /*
  34592. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  34593. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  34594. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  34595. ** system call named zName.
  34596. */
  34597. static int rttSetSystemCall(
  34598. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  34599. const char *zName, /* Name of system call to override */
  34600. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  34601. ){
  34602. unsigned int i;
  34603. int rc = SQLITE_NOTFOUND;
  34604. UNUSED_PARAMETER(pNotUsed);
  34605. if( zName==0 ){
  34606. /* If no zName is given, restore all system calls to their default
  34607. ** settings and return NULL
  34608. */
  34609. rc = SQLITE_OK;
  34610. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34611. if( aSyscall[i].pDefault ){
  34612. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  34613. }
  34614. }
  34615. }else{
  34616. /* If zName is specified, operate on only the one system call
  34617. ** specified.
  34618. */
  34619. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34620. if( strcmp(zName, aSyscall[i].zName)==0 ){
  34621. if( aSyscall[i].pDefault==0 ){
  34622. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  34623. }
  34624. rc = SQLITE_OK;
  34625. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  34626. aSyscall[i].pCurrent = pNewFunc;
  34627. break;
  34628. }
  34629. }
  34630. }
  34631. return rc;
  34632. }
  34633. /*
  34634. ** Return the value of a system call. Return NULL if zName is not a
  34635. ** recognized system call name. NULL is also returned if the system call
  34636. ** is currently undefined.
  34637. */
  34638. static sqlite3_syscall_ptr rttGetSystemCall(
  34639. sqlite3_vfs *pNotUsed,
  34640. const char *zName
  34641. ){
  34642. unsigned int i;
  34643. UNUSED_PARAMETER(pNotUsed);
  34644. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  34645. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  34646. }
  34647. return 0;
  34648. }
  34649. /*
  34650. ** Return the name of the first system call after zName. If zName==NULL
  34651. ** then return the name of the first system call. Return NULL if zName
  34652. ** is the last system call or if zName is not the name of a valid
  34653. ** system call.
  34654. */
  34655. static const char *rttNextSystemCall(sqlite3_vfs *p, const char *zName){
  34656. int i = -1;
  34657. UNUSED_PARAMETER(p);
  34658. if( zName ){
  34659. for(i=0; i<ArraySize(aSyscall)-1; i++){
  34660. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  34661. }
  34662. }
  34663. for(i++; i<ArraySize(aSyscall); i++){
  34664. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  34665. }
  34666. return 0;
  34667. }
  34668. /*
  34669. ** The following routine suspends the current thread for at least ms
  34670. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  34671. */
  34672. SQLITE_API void sqlite3_rtt_sleep(int milliseconds){
  34673. rt_tick_t sleep_tick;
  34674. if (milliseconds <= 0)
  34675. return;
  34676. sleep_tick = rt_tick_from_millisecond(milliseconds);
  34677. osSleep(sleep_tick);
  34678. }
  34679. /*
  34680. ** Helper functions to obtain and relinquish the global mutex. The
  34681. ** global mutex is used to protect the unixInodeInfo and
  34682. ** vxworksFileId objects used by this file, all of which may be
  34683. ** shared by multiple threads.
  34684. **
  34685. ** Function unixMutexHeld() is used to assert() that the global mutex
  34686. ** is held when required. This function is only used as part of assert()
  34687. ** statements. e.g.
  34688. **
  34689. ** unixEnterMutex()
  34690. ** assert( unixMutexHeld() );
  34691. ** unixEnterLeave()
  34692. */
  34693. static void rttEnterMutex(void){
  34694. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34695. }
  34696. static void rttLeaveMutex(void){
  34697. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34698. }
  34699. #ifdef SQLITE_DEBUG
  34700. static int rttMutexHeld(void) {
  34701. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  34702. }
  34703. #endif
  34704. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  34705. /*
  34706. ** Helper function for printing out trace information from debugging
  34707. ** binaries. This returns the string represetation of the supplied
  34708. ** integer lock-type.
  34709. */
  34710. static const char *azFileLock(int eFileLock){
  34711. switch( eFileLock ){
  34712. case NO_LOCK: return "NONE";
  34713. case SHARED_LOCK: return "SHARED";
  34714. case RESERVED_LOCK: return "RESERVED";
  34715. case PENDING_LOCK: return "PENDING";
  34716. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  34717. }
  34718. return "ERROR";
  34719. }
  34720. #endif
  34721. /*
  34722. ** This routine translates a standard POSIX errno code into something
  34723. ** useful to the clients of the sqlite3 functions. Specifically, it is
  34724. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  34725. ** and a variety of "please close the file descriptor NOW" errors into
  34726. ** SQLITE_IOERR
  34727. **
  34728. ** Errors during initialization of locks, or file system support for locks,
  34729. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  34730. */
  34731. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  34732. switch (posixError) {
  34733. #if 0
  34734. /* At one point this code was not commented out. In theory, this branch
  34735. ** should never be hit, as this function should only be called after
  34736. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  34737. ** the value of errno as the first argument. Since a system call has failed,
  34738. ** errno should be non-zero.
  34739. **
  34740. ** Despite this, if errno really is zero, we still don't want to return
  34741. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  34742. ** propagated back to the caller. Commenting this branch out means errno==0
  34743. ** will be handled by the "default:" case below.
  34744. */
  34745. case 0:
  34746. return SQLITE_OK;
  34747. #endif
  34748. case EAGAIN:
  34749. case ETIMEDOUT:
  34750. case EBUSY:
  34751. case EINTR:
  34752. case ENOLCK:
  34753. /* random NFS retry error, unless during file system support
  34754. * introspection, in which it actually means what it says */
  34755. return SQLITE_BUSY;
  34756. case EACCES:
  34757. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  34758. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  34759. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  34760. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  34761. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  34762. return SQLITE_BUSY;
  34763. }
  34764. /* else fall through */
  34765. case EPERM:
  34766. return SQLITE_PERM;
  34767. /* EDEADLK is only possible if a call to fcntl(F_SETLKW) is made. And
  34768. ** this module never makes such a call. And the code in SQLite itself
  34769. ** asserts that SQLITE_IOERR_BLOCKED is never returned. For these reasons
  34770. ** this case is also commented out. If the system does set errno to EDEADLK,
  34771. ** the default SQLITE_IOERR_XXX code will be returned. */
  34772. #if 0
  34773. case EDEADLK:
  34774. return SQLITE_IOERR_BLOCKED;
  34775. #endif
  34776. #if EOPNOTSUPP!=ENOTSUP
  34777. case EOPNOTSUPP:
  34778. /* something went terribly awry, unless during file system support
  34779. * introspection, in which it actually means what it says */
  34780. #endif
  34781. #ifdef ENOTSUP
  34782. case ENOTSUP:
  34783. /* invalid fd, unless during file system support introspection, in which
  34784. * it actually means what it says */
  34785. #endif
  34786. case EIO:
  34787. case EBADF:
  34788. case EINVAL:
  34789. case ENOTCONN:
  34790. case ENODEV:
  34791. case ENXIO:
  34792. case ENOENT:
  34793. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  34794. case ESTALE:
  34795. #endif
  34796. case ENOSYS:
  34797. /* these should force the client to close the file and reconnect */
  34798. default:
  34799. return sqliteIOErr;
  34800. }
  34801. }
  34802. /*
  34803. **
  34804. ** This function - unixLogError_x(), is only ever called via the macro
  34805. ** unixLogError().
  34806. **
  34807. ** It is invoked after an error occurs in an OS function and errno has been
  34808. ** set. It logs a message using sqlite3_log() containing the current value of
  34809. ** errno and, if possible, the human-readable equivalent from strerror() or
  34810. ** strerror_r().
  34811. **
  34812. ** The first argument passed to the macro should be the error code that
  34813. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  34814. ** The two subsequent arguments should be the name of the OS function that
  34815. ** failed (e.g. "unlink", "open") and the associated file-system path,
  34816. ** if any.
  34817. */
  34818. #define rttLogError(a,b,c) rttLogErrorAtLine(a,b,c,__LINE__)
  34819. static int rttLogErrorAtLine(
  34820. int errcode, /* SQLite error code */
  34821. const char *zFunc, /* Name of OS function that failed */
  34822. const char *zPath, /* File path associated with error */
  34823. int iLine /* Source line number where error occurred */
  34824. ){
  34825. char *zErr; /* Message from strerror() or equivalent */
  34826. int iErrno = errno; /* Saved syscall error number */
  34827. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  34828. ** the strerror() function to obtain the human-readable error message
  34829. ** equivalent to errno. Otherwise, use strerror_r().
  34830. */
  34831. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  34832. char aErr[80];
  34833. memset(aErr, 0, sizeof(aErr));
  34834. zErr = aErr;
  34835. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  34836. ** assume that the system provides the GNU version of strerror_r() that
  34837. ** returns a pointer to a buffer containing the error message. That pointer
  34838. ** may point to aErr[], or it may point to some static storage somewhere.
  34839. ** Otherwise, assume that the system provides the POSIX version of
  34840. ** strerror_r(), which always writes an error message into aErr[].
  34841. **
  34842. ** If the code incorrectly assumes that it is the POSIX version that is
  34843. ** available, the error message will often be an empty string. Not a
  34844. ** huge problem. Incorrectly concluding that the GNU version is available
  34845. ** could lead to a segfault though.
  34846. */
  34847. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  34848. zErr =
  34849. # endif
  34850. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  34851. #elif SQLITE_THREADSAFE
  34852. /* This is a threadsafe build, but strerror_r() is not available. */
  34853. zErr = "";
  34854. #else
  34855. /* Non-threadsafe build, use strerror(). */
  34856. zErr = strerror(iErrno);
  34857. #endif
  34858. if( zPath==0 ) zPath = "";
  34859. sqlite3_log(errcode,
  34860. "os_rtt.c:%d: (%d) %s(%s) - %s",
  34861. iLine, iErrno, zFunc, zPath, zErr
  34862. );
  34863. return errcode;
  34864. }
  34865. static int robust_ftruncate(int h, sqlite3_int64 sz){
  34866. int rc;
  34867. rc = -1;
  34868. return rc;
  34869. }
  34870. /*
  34871. ** Close a file descriptor.
  34872. **
  34873. ** We assume that close() almost always works, since it is only in a
  34874. ** very sick application or on a very sick platform that it might fail.
  34875. ** If it does fail, simply leak the file descriptor, but do log the
  34876. ** error.
  34877. **
  34878. ** Note that it is not safe to retry close() after EINTR since the
  34879. ** file descriptor might have already been reused by another thread.
  34880. ** So we don't even try to recover from an EINTR. Just log the error
  34881. ** and move on.
  34882. */
  34883. static void robust_close(rttFile *pFile, int h, int lineno){
  34884. if( osClose(h) ){
  34885. rttLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  34886. pFile ? pFile->zPath : 0, lineno);
  34887. }
  34888. }
  34889. /*
  34890. ** Check a rttFile that is a database. Verify the following:
  34891. **
  34892. ** (1) There is exactly one hard link on the file
  34893. ** (2) The file is not a symbolic link
  34894. ** (3) The file has not been renamed or unlinked
  34895. **
  34896. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  34897. */
  34898. static void verifyDbFile(rttFile *pFile){
  34899. struct stat buf;
  34900. int rc;
  34901. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  34902. /* One or more of the following warnings have already been issued. Do not
  34903. ** repeat them so as not to clutter the error log */
  34904. return;
  34905. }
  34906. rc = osFstat(pFile->h, &buf);
  34907. if( rc!=0 ){
  34908. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  34909. pFile->ctrlFlags |= UNIXFILE_WARNED;
  34910. return;
  34911. }
  34912. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  34913. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  34914. pFile->ctrlFlags |= UNIXFILE_WARNED;
  34915. return;
  34916. }
  34917. }
  34918. /*
  34919. ** This function performs the parts of the "close file" operation
  34920. ** common to all locking schemes. It closes the directory and file
  34921. ** handles, if they are valid, and sets all fields of the rttFile
  34922. ** structure to 0.
  34923. **
  34924. ** It is *not* necessary to hold the mutex when this routine is called,
  34925. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  34926. ** vxworksReleaseFileId() routine.
  34927. */
  34928. static int closeRttFile(sqlite3_file *id){
  34929. rttFile *pFile = (rttFile*)id;
  34930. if( pFile->h>=0 ){
  34931. robust_close(pFile, pFile->h, __LINE__);
  34932. pFile->h = -1;
  34933. }
  34934. OSTRACE(("CLOSE %-3d\n", pFile->h));
  34935. OpenCounter(-1);
  34936. memset(pFile, 0, sizeof(rttFile));
  34937. return SQLITE_OK;
  34938. }
  34939. /************** End of the posix advisory lock implementation *****************
  34940. ******************************************************************************/
  34941. /******************************************************************************
  34942. ****************************** No-op Locking **********************************
  34943. **
  34944. ** Of the various locking implementations available, this is by far the
  34945. ** simplest: locking is ignored. No attempt is made to lock the database
  34946. ** file for reading or writing.
  34947. **
  34948. ** This locking mode is appropriate for use on read-only databases
  34949. ** (ex: databases that are burned into CD-ROM, for example.) It can
  34950. ** also be used if the application employs some external mechanism to
  34951. ** prevent simultaneous access of the same database by two or more
  34952. ** database connections. But there is a serious risk of database
  34953. ** corruption if this locking mode is used in situations where multiple
  34954. ** database connections are accessing the same database file at the same
  34955. ** time and one or more of those connections are writing.
  34956. */
  34957. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  34958. UNUSED_PARAMETER(NotUsed);
  34959. *pResOut = 0;
  34960. return SQLITE_OK;
  34961. }
  34962. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  34963. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  34964. return SQLITE_OK;
  34965. }
  34966. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  34967. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  34968. return SQLITE_OK;
  34969. }
  34970. /*
  34971. ** Close the file.
  34972. */
  34973. static int nolockClose(sqlite3_file *id) {
  34974. return closeRttFile(id);
  34975. }
  34976. /******************* End of the no-op lock implementation *********************
  34977. ******************************************************************************/
  34978. /******************************************************************************
  34979. ************************* Begin dot-file Locking ******************************
  34980. **
  34981. ** The dotfile locking implementation uses the existence of separate lock
  34982. ** files (really a directory) to control access to the database. This works
  34983. ** on just about every filesystem imaginable. But there are serious downsides:
  34984. **
  34985. ** (1) There is zero concurrency. A single reader blocks all other
  34986. ** connections from reading or writing the database.
  34987. **
  34988. ** (2) An application crash or power loss can leave stale lock files
  34989. ** sitting around that need to be cleared manually.
  34990. **
  34991. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  34992. ** other locking strategy is available.
  34993. **
  34994. ** Dotfile locking works by creating a subdirectory in the same directory as
  34995. ** the database and with the same name but with a ".lock" extension added.
  34996. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  34997. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  34998. */
  34999. /*
  35000. ** The file suffix added to the data base filename in order to create the
  35001. ** lock directory.
  35002. */
  35003. #define DOTLOCK_SUFFIX ".lock"
  35004. /*
  35005. ** This routine checks if there is a RESERVED lock held on the specified
  35006. ** file by this or any other process. If such a lock is held, set *pResOut
  35007. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35008. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35009. **
  35010. ** In dotfile locking, either a lock exists or it does not. So in this
  35011. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  35012. ** is held on the file and false if the file is unlocked.
  35013. */
  35014. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  35015. int rc = SQLITE_OK;
  35016. int reserved = 0;
  35017. rttFile *pFile = (rttFile*)id;
  35018. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35019. assert( pFile );
  35020. /* Check if a thread in this process holds such a lock */
  35021. if( pFile->eFileLock>SHARED_LOCK ){
  35022. /* Either this connection or some other connection in the same process
  35023. ** holds a lock on the file. No need to check further. */
  35024. reserved = 1;
  35025. }else{
  35026. /* The lock is held if and only if the lockfile exists */
  35027. const char *zLockFile = (const char*)pFile->lockingContext;
  35028. reserved = 0;
  35029. }
  35030. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  35031. *pResOut = reserved;
  35032. return rc;
  35033. }
  35034. /*
  35035. ** Lock the file with the lock specified by parameter eFileLock - one
  35036. ** of the following:
  35037. **
  35038. ** (1) SHARED_LOCK
  35039. ** (2) RESERVED_LOCK
  35040. ** (3) PENDING_LOCK
  35041. ** (4) EXCLUSIVE_LOCK
  35042. **
  35043. ** Sometimes when requesting one lock state, additional lock states
  35044. ** are inserted in between. The locking might fail on one of the later
  35045. ** transitions leaving the lock state different from what it started but
  35046. ** still short of its goal. The following chart shows the allowed
  35047. ** transitions and the inserted intermediate states:
  35048. **
  35049. ** UNLOCKED -> SHARED
  35050. ** SHARED -> RESERVED
  35051. ** SHARED -> (PENDING) -> EXCLUSIVE
  35052. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35053. ** PENDING -> EXCLUSIVE
  35054. **
  35055. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35056. ** routine to lower a locking level.
  35057. **
  35058. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  35059. ** But we track the other locking levels internally.
  35060. */
  35061. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  35062. rttFile *pFile = (rttFile*)id;
  35063. char *zLockFile = (char *)pFile->lockingContext;
  35064. int rc = SQLITE_OK;
  35065. /* If we have any lock, then the lock file already exists. All we have
  35066. ** to do is adjust our internal record of the lock level.
  35067. */
  35068. if( pFile->eFileLock > NO_LOCK ){
  35069. pFile->eFileLock = eFileLock;
  35070. return SQLITE_OK;
  35071. }
  35072. /* grab an exclusive lock */
  35073. rc = osMkdir(zLockFile, 0777);
  35074. if( rc<0 ){
  35075. /* failed to open/create the lock directory */
  35076. int tErrno = errno;
  35077. if( EEXIST == tErrno ){
  35078. rc = SQLITE_BUSY;
  35079. } else {
  35080. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35081. if( IS_LOCK_ERROR(rc) ){
  35082. pFile->lastErrno = tErrno;
  35083. }
  35084. }
  35085. return rc;
  35086. }
  35087. /* got it, set the type and return ok */
  35088. pFile->eFileLock = eFileLock;
  35089. return rc;
  35090. }
  35091. /*
  35092. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35093. ** must be either NO_LOCK or SHARED_LOCK.
  35094. **
  35095. ** If the locking level of the file descriptor is already at or below
  35096. ** the requested locking level, this routine is a no-op.
  35097. **
  35098. ** When the locking level reaches NO_LOCK, delete the lock file.
  35099. */
  35100. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  35101. rttFile *pFile = (rttFile*)id;
  35102. char *zLockFile = (char *)pFile->lockingContext;
  35103. int rc;
  35104. assert( pFile );
  35105. OSTRACE(("UNLOCK %d %d was %d tnm=%s (dotlock)\n", pFile->h, eFileLock,
  35106. pFile->eFileLock, rt_thread_self()->name ));
  35107. assert( eFileLock<=SHARED_LOCK );
  35108. /* no-op if possible */
  35109. if( pFile->eFileLock==eFileLock ){
  35110. return SQLITE_OK;
  35111. }
  35112. /* To downgrade to shared, simply update our internal notion of the
  35113. ** lock state. No need to mess with the file on disk.
  35114. */
  35115. if( eFileLock==SHARED_LOCK ){
  35116. pFile->eFileLock = SHARED_LOCK;
  35117. return SQLITE_OK;
  35118. }
  35119. /* To fully unlock the database, delete the lock file */
  35120. assert( eFileLock==NO_LOCK );
  35121. rc = osRmdir(zLockFile);
  35122. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  35123. if( rc<0 ){
  35124. int tErrno = errno;
  35125. rc = 0;
  35126. if( ENOENT != tErrno ){
  35127. rc = SQLITE_IOERR_UNLOCK;
  35128. }
  35129. if( IS_LOCK_ERROR(rc) ){
  35130. pFile->lastErrno = tErrno;
  35131. }
  35132. return rc;
  35133. }
  35134. pFile->eFileLock = NO_LOCK;
  35135. return SQLITE_OK;
  35136. }
  35137. /*
  35138. ** Close a file. Make sure the lock has been released before closing.
  35139. */
  35140. static int dotlockClose(sqlite3_file *id) {
  35141. int rc = SQLITE_OK;
  35142. if( id ){
  35143. rttFile *pFile = (rttFile*)id;
  35144. dotlockUnlock(id, NO_LOCK);
  35145. sqlite3_free(pFile->lockingContext);
  35146. rc = closeRttFile(id);
  35147. }
  35148. return rc;
  35149. }
  35150. /****************** End of the dot-file lock implementation *******************
  35151. ******************************************************************************/
  35152. /******************************************************************************
  35153. ************************** Begin flock Locking ********************************
  35154. **
  35155. ** Use the flock() system call to do file locking.
  35156. **
  35157. ** flock() locking is like dot-file locking in that the various
  35158. ** fine-grain locking levels supported by SQLite are collapsed into
  35159. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  35160. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  35161. ** still works when you do this, but concurrency is reduced since
  35162. ** only a single process can be reading the database at a time.
  35163. **
  35164. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  35165. ** compiling for VXWORKS.
  35166. */
  35167. #if SQLITE_ENABLE_LOCKING_STYLE
  35168. #warning "rtt file lock not available"
  35169. /*
  35170. ** Retry flock() calls that fail with EINTR
  35171. */
  35172. static int robust_flock(int fd, int op){
  35173. int rc = 0;
  35174. return rc;
  35175. }
  35176. /*
  35177. ** This routine checks if there is a RESERVED lock held on the specified
  35178. ** file by this or any other process. If such a lock is held, set *pResOut
  35179. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  35180. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  35181. */
  35182. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  35183. int rc = SQLITE_OK;
  35184. int reserved = 0;
  35185. rttFile *pFile = (rttFile*)id;
  35186. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  35187. assert( pFile );
  35188. /* Check if a thread in this process holds such a lock */
  35189. if( pFile->eFileLock>SHARED_LOCK ){
  35190. reserved = 1;
  35191. }
  35192. /* Otherwise see if some other process holds it. */
  35193. if( !reserved ){
  35194. /* attempt to get the lock */
  35195. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  35196. if( !lrc ){
  35197. /* got the lock, unlock it */
  35198. lrc = robust_flock(pFile->h, LOCK_UN);
  35199. if ( lrc ) {
  35200. int tErrno = errno;
  35201. /* unlock failed with an error */
  35202. lrc = SQLITE_IOERR_UNLOCK;
  35203. if( IS_LOCK_ERROR(lrc) ){
  35204. pFile->lastErrno = tErrno;
  35205. rc = lrc;
  35206. }
  35207. }
  35208. } else {
  35209. int tErrno = errno;
  35210. reserved = 1;
  35211. /* someone else might have it reserved */
  35212. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35213. if( IS_LOCK_ERROR(lrc) ){
  35214. pFile->lastErrno = tErrno;
  35215. rc = lrc;
  35216. }
  35217. }
  35218. }
  35219. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  35220. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35221. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  35222. rc = SQLITE_OK;
  35223. reserved=1;
  35224. }
  35225. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35226. *pResOut = reserved;
  35227. return rc;
  35228. }
  35229. /*
  35230. ** Lock the file with the lock specified by parameter eFileLock - one
  35231. ** of the following:
  35232. **
  35233. ** (1) SHARED_LOCK
  35234. ** (2) RESERVED_LOCK
  35235. ** (3) PENDING_LOCK
  35236. ** (4) EXCLUSIVE_LOCK
  35237. **
  35238. ** Sometimes when requesting one lock state, additional lock states
  35239. ** are inserted in between. The locking might fail on one of the later
  35240. ** transitions leaving the lock state different from what it started but
  35241. ** still short of its goal. The following chart shows the allowed
  35242. ** transitions and the inserted intermediate states:
  35243. **
  35244. ** UNLOCKED -> SHARED
  35245. ** SHARED -> RESERVED
  35246. ** SHARED -> (PENDING) -> EXCLUSIVE
  35247. ** RESERVED -> (PENDING) -> EXCLUSIVE
  35248. ** PENDING -> EXCLUSIVE
  35249. **
  35250. ** flock() only really support EXCLUSIVE locks. We track intermediate
  35251. ** lock states in the sqlite3_file structure, but all locks SHARED or
  35252. ** above are really EXCLUSIVE locks and exclude all other processes from
  35253. ** access the file.
  35254. **
  35255. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  35256. ** routine to lower a locking level.
  35257. */
  35258. static int flockLock(sqlite3_file *id, int eFileLock) {
  35259. int rc = SQLITE_OK;
  35260. rttFile *pFile = (rttFile*)id;
  35261. assert( pFile );
  35262. /* if we already have a lock, it is exclusive.
  35263. ** Just adjust level and punt on outta here. */
  35264. if (pFile->eFileLock > NO_LOCK) {
  35265. pFile->eFileLock = eFileLock;
  35266. return SQLITE_OK;
  35267. }
  35268. /* grab an exclusive lock */
  35269. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  35270. int tErrno = errno;
  35271. /* didn't get, must be busy */
  35272. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  35273. if( IS_LOCK_ERROR(rc) ){
  35274. pFile->lastErrno = tErrno;
  35275. }
  35276. } else {
  35277. /* got it, set the type and return ok */
  35278. pFile->eFileLock = eFileLock;
  35279. }
  35280. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  35281. rc==SQLITE_OK ? "ok" : "failed"));
  35282. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35283. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  35284. rc = SQLITE_BUSY;
  35285. }
  35286. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35287. return rc;
  35288. }
  35289. /*
  35290. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  35291. ** must be either NO_LOCK or SHARED_LOCK.
  35292. **
  35293. ** If the locking level of the file descriptor is already at or below
  35294. ** the requested locking level, this routine is a no-op.
  35295. */
  35296. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  35297. rttFile *pFile = (rttFile*)id;
  35298. assert( pFile );
  35299. OSTRACE(("UNLOCK %d %d was %d tnm=%s (flock)\n", pFile->h, eFileLock,
  35300. pFile->eFileLock, rt_thread_self()->name));
  35301. assert( eFileLock<=SHARED_LOCK );
  35302. /* no-op if possible */
  35303. if( pFile->eFileLock==eFileLock ){
  35304. return SQLITE_OK;
  35305. }
  35306. /* shared can just be set because we always have an exclusive */
  35307. if (eFileLock==SHARED_LOCK) {
  35308. pFile->eFileLock = eFileLock;
  35309. return SQLITE_OK;
  35310. }
  35311. /* no, really, unlock. */
  35312. if( robust_flock(pFile->h, LOCK_UN) ){
  35313. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  35314. return SQLITE_OK;
  35315. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  35316. return SQLITE_IOERR_UNLOCK;
  35317. }else{
  35318. pFile->eFileLock = NO_LOCK;
  35319. return SQLITE_OK;
  35320. }
  35321. }
  35322. /*
  35323. ** Close a file.
  35324. */
  35325. static int flockClose(sqlite3_file *id) {
  35326. int rc = SQLITE_OK;
  35327. if( id ){
  35328. flockUnlock(id, NO_LOCK);
  35329. rc = closeRttFile(id);
  35330. }
  35331. return rc;
  35332. }
  35333. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  35334. /******************* End of the flock lock implementation *********************
  35335. ******************************************************************************/
  35336. /******************************************************************************
  35337. **************** Non-locking sqlite3_file methods *****************************
  35338. **
  35339. ** The next division contains implementations for all methods of the
  35340. ** sqlite3_file object other than the locking methods. The locking
  35341. ** methods were defined in divisions above (one locking method per
  35342. ** division). Those methods that are common to all locking modes
  35343. ** are gather together into this division.
  35344. */
  35345. /*
  35346. ** Seek to the offset passed as the second argument, then read cnt
  35347. ** bytes into pBuf. Return the number of bytes actually read.
  35348. **
  35349. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  35350. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  35351. ** one system to another. Since SQLite does not define USE_PREAD
  35352. ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
  35353. ** See tickets #2741 and #2681.
  35354. **
  35355. ** To avoid stomping the errno value on a failed read the lastErrno value
  35356. ** is set before returning.
  35357. */
  35358. static int seekAndRead(rttFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  35359. int got;
  35360. int prior = 0;
  35361. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  35362. i64 newOffset;
  35363. #endif
  35364. TIMER_START;
  35365. assert( cnt==(cnt&0x1ffff) );
  35366. assert( id->h>2 );
  35367. cnt &= 0x1ffff;
  35368. do{
  35369. #if defined(USE_PREAD)
  35370. #error "rtt pread not support"
  35371. got = osPread(id->h, pBuf, cnt, offset);
  35372. SimulateIOError( got = -1 );
  35373. #elif defined(USE_PREAD64)
  35374. #error "rtt pread64 not support"
  35375. got = osPread64(id->h, pBuf, cnt, offset);
  35376. SimulateIOError( got = -1 );
  35377. #else
  35378. newOffset = lseek(id->h, offset, SEEK_SET);
  35379. SimulateIOError( newOffset-- );
  35380. if( newOffset!=offset ){
  35381. if( newOffset == -1 ){
  35382. ((rttFile*)id)->lastErrno = errno;
  35383. }else{
  35384. ((rttFile*)id)->lastErrno = 0;
  35385. }
  35386. return -1;
  35387. }
  35388. got = osRead(id->h, pBuf, cnt);
  35389. #endif
  35390. if( got==cnt ) break;
  35391. if( got<0 ){
  35392. if( errno==EINTR ){ got = 1; continue; }
  35393. prior = 0;
  35394. ((rttFile*)id)->lastErrno = errno;
  35395. break;
  35396. }else if( got>0 ){
  35397. cnt -= got;
  35398. offset += got;
  35399. prior += got;
  35400. pBuf = (void*)(got + (char*)pBuf);
  35401. }
  35402. }while( got>0 );
  35403. TIMER_END;
  35404. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  35405. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  35406. return got+prior;
  35407. }
  35408. /*
  35409. ** Read data from a file into a buffer. Return SQLITE_OK if all
  35410. ** bytes were read successfully and SQLITE_IOERR if anything goes
  35411. ** wrong.
  35412. */
  35413. static int rttRead(
  35414. sqlite3_file *id,
  35415. void *pBuf,
  35416. int amt,
  35417. sqlite3_int64 offset
  35418. ){
  35419. rttFile *pFile = (rttFile *)id;
  35420. int got;
  35421. assert( id );
  35422. assert( offset>=0 );
  35423. assert( amt>0 );
  35424. got = seekAndRead(pFile, offset, pBuf, amt);
  35425. if( got==amt ){
  35426. return SQLITE_OK;
  35427. }else if( got<0 ){
  35428. /* lastErrno set by seekAndRead */
  35429. return SQLITE_IOERR_READ;
  35430. }else{
  35431. pFile->lastErrno = 0; /* not a system error */
  35432. /* Unread parts of the buffer must be zero-filled */
  35433. memset(&((char*)pBuf)[got], 0, amt-got);
  35434. return SQLITE_IOERR_SHORT_READ;
  35435. }
  35436. }
  35437. /*
  35438. ** Attempt to seek the file-descriptor passed as the first argument to
  35439. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  35440. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  35441. ** return the actual number of bytes written (which may be less than
  35442. ** nBuf).
  35443. */
  35444. static int seekAndWriteFd(
  35445. int fd, /* File descriptor to write to */
  35446. i64 iOff, /* File offset to begin writing at */
  35447. const void *pBuf, /* Copy data from this buffer to the file */
  35448. int nBuf, /* Size of buffer pBuf in bytes */
  35449. int *piErrno /* OUT: Error number if error occurs */
  35450. ){
  35451. int rc = 0; /* Value returned by system call */
  35452. assert( nBuf==(nBuf&0x1ffff) );
  35453. assert( fd>2 );
  35454. nBuf &= 0x1ffff;
  35455. TIMER_START;
  35456. #if defined(USE_PREAD)
  35457. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  35458. #elif defined(USE_PREAD64)
  35459. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  35460. #else
  35461. do{
  35462. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  35463. SimulateIOError( iSeek-- );
  35464. if( iSeek!=iOff ){
  35465. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  35466. return -1;
  35467. }
  35468. rc = osWrite(fd, pBuf, nBuf);
  35469. }while( rc<0 && errno==EINTR );
  35470. #endif
  35471. TIMER_END;
  35472. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  35473. if( rc<0 && piErrno ) *piErrno = errno;
  35474. return rc;
  35475. }
  35476. /*
  35477. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  35478. ** Return the number of bytes actually read. Update the offset.
  35479. **
  35480. ** To avoid stomping the errno value on a failed write the lastErrno value
  35481. ** is set before returning.
  35482. */
  35483. static int seekAndWrite(rttFile *id, i64 offset, const void *pBuf, int cnt){
  35484. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  35485. }
  35486. /*
  35487. ** Write data from a buffer into a file. Return SQLITE_OK on success
  35488. ** or some other error code on failure.
  35489. */
  35490. static int rttWrite(
  35491. sqlite3_file *id,
  35492. const void *pBuf,
  35493. int amt,
  35494. sqlite3_int64 offset
  35495. ){
  35496. rttFile *pFile = (rttFile*)id;
  35497. int wrote = 0;
  35498. assert( id );
  35499. assert( amt>0 );
  35500. #ifdef SQLITE_DEBUG
  35501. /* If we are doing a normal write to a database file (as opposed to
  35502. ** doing a hot-journal rollback or a write to some file other than a
  35503. ** normal database file) then record the fact that the database
  35504. ** has changed. If the transaction counter is modified, record that
  35505. ** fact too.
  35506. */
  35507. if( pFile->inNormalWrite ){
  35508. pFile->dbUpdate = 1; /* The database has been modified */
  35509. if( offset<=24 && offset+amt>=27 ){
  35510. int rc;
  35511. char oldCntr[4];
  35512. SimulateIOErrorBenign(1);
  35513. rc = seekAndRead(pFile, 24, oldCntr, 4);
  35514. SimulateIOErrorBenign(0);
  35515. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  35516. pFile->transCntrChng = 1; /* The transaction counter has changed */
  35517. }
  35518. }
  35519. }
  35520. #endif
  35521. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  35522. amt -= wrote;
  35523. offset += wrote;
  35524. pBuf = &((char*)pBuf)[wrote];
  35525. }
  35526. SimulateIOError(( wrote=(-1), amt=1 ));
  35527. SimulateDiskfullError(( wrote=0, amt=1 ));
  35528. if( amt>0 ){
  35529. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  35530. /* lastErrno set by seekAndWrite */
  35531. return SQLITE_IOERR_WRITE;
  35532. }else{
  35533. pFile->lastErrno = 0; /* not a system error */
  35534. return SQLITE_FULL;
  35535. }
  35536. }
  35537. return SQLITE_OK;
  35538. }
  35539. #ifdef SQLITE_TEST
  35540. /*
  35541. ** Count the number of fullsyncs and normal syncs. This is used to test
  35542. ** that syncs and fullsyncs are occurring at the right times.
  35543. */
  35544. SQLITE_API int sqlite3_sync_count = 0;
  35545. SQLITE_API int sqlite3_fullsync_count = 0;
  35546. #endif
  35547. /*
  35548. ** We do not trust systems to provide a working fdatasync(). Some do.
  35549. ** Others do no. To be safe, we will stick with the (slightly slower)
  35550. ** fsync(). If you know that your system does support fdatasync() correctly,
  35551. ** then simply compile with -Dfdatasync=fdatasync
  35552. */
  35553. #if !defined(fdatasync)
  35554. #include "dfs.h"
  35555. #include "dfs_file.h"
  35556. int fdatasync(fd)
  35557. {
  35558. struct dfs_fd *dfs_fd;
  35559. dfs_fd = fd_get(fd);
  35560. return dfs_file_flush(dfs_fd);
  35561. }
  35562. #endif
  35563. /*
  35564. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  35565. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  35566. ** only available on Mac OS X. But that could change.
  35567. */
  35568. #ifdef F_FULLFSYNC
  35569. # define HAVE_FULLFSYNC 0
  35570. #endif
  35571. /*
  35572. ** The fsync() system call does not work as advertised on many
  35573. ** unix systems. The following procedure is an attempt to make
  35574. ** it work better.
  35575. **
  35576. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  35577. ** for testing when we want to run through the test suite quickly.
  35578. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  35579. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  35580. ** or power failure will likely corrupt the database file.
  35581. **
  35582. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  35583. ** The idea behind dataOnly is that it should only write the file content
  35584. ** to disk, not the inode. We only set dataOnly if the file size is
  35585. ** unchanged since the file size is part of the inode. However,
  35586. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  35587. ** file size has changed. The only real difference between fdatasync()
  35588. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  35589. ** inode if the mtime or owner or other inode attributes have changed.
  35590. ** We only care about the file size, not the other file attributes, so
  35591. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  35592. ** So, we always use fdatasync() if it is available, regardless of
  35593. ** the value of the dataOnly flag.
  35594. */
  35595. static int full_fsync(int fd, int fullSync, int dataOnly){
  35596. int rc;
  35597. /* The following "ifdef/elif/else/" block has the same structure as
  35598. ** the one below. It is replicated here solely to avoid cluttering
  35599. ** up the real code with the UNUSED_PARAMETER() macros.
  35600. */
  35601. #ifdef SQLITE_NO_SYNC
  35602. UNUSED_PARAMETER(fd);
  35603. UNUSED_PARAMETER(fullSync);
  35604. UNUSED_PARAMETER(dataOnly);
  35605. #elif HAVE_FULLFSYNC
  35606. UNUSED_PARAMETER(dataOnly);
  35607. #else
  35608. UNUSED_PARAMETER(fullSync);
  35609. UNUSED_PARAMETER(dataOnly);
  35610. #endif
  35611. /* Record the number of times that we do a normal fsync() and
  35612. ** FULLSYNC. This is used during testing to verify that this procedure
  35613. ** gets called with the correct arguments.
  35614. */
  35615. #ifdef SQLITE_TEST
  35616. if( fullSync ) sqlite3_fullsync_count++;
  35617. sqlite3_sync_count++;
  35618. #endif
  35619. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  35620. ** no-op
  35621. */
  35622. #ifdef SQLITE_NO_SYNC
  35623. rc = SQLITE_OK;
  35624. #elif HAVE_FULLFSYNC
  35625. #error "rtt not support FULLFSYNC"
  35626. #else
  35627. rc = fdatasync(fd);
  35628. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  35629. return rc;
  35630. }
  35631. /*
  35632. ** Make sure all writes to a particular file are committed to disk.
  35633. **
  35634. ** If dataOnly==0 then both the file itself and its metadata (file
  35635. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  35636. ** file data is synced.
  35637. **
  35638. ** Under Rtt, also make sure that the directory entry for the file
  35639. ** has been created by fsync-ing the directory that contains the file.
  35640. ** If we do not do this and we encounter a power failure, the directory
  35641. ** entry for the journal might not exist after we reboot. The next
  35642. ** SQLite to access the file will not know that the journal exists (because
  35643. ** the directory entry for the journal was never created) and the transaction
  35644. ** will not roll back - possibly leading to database corruption.
  35645. */
  35646. static int rttSync(sqlite3_file *id, int flags){
  35647. int rc;
  35648. rttFile *pFile = (rttFile*)id;
  35649. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  35650. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  35651. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  35652. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  35653. || (flags&0x0F)==SQLITE_SYNC_FULL
  35654. );
  35655. /* Rtt cannot, but some systems may return SQLITE_FULL from here. This
  35656. ** line is to test that doing so does not cause any problems.
  35657. */
  35658. SimulateDiskfullError( return SQLITE_FULL );
  35659. assert( pFile );
  35660. OSTRACE(("SYNC %-3d\n", pFile->h));
  35661. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  35662. SimulateIOError( rc=1 );
  35663. if( rc ){
  35664. pFile->lastErrno = errno;
  35665. return rttLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  35666. }
  35667. /* Also fsync the directory containing the file if the DIRSYNC flag
  35668. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  35669. ** are unable to fsync a directory, so ignore errors on the fsync.
  35670. */
  35671. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  35672. int dirfd;
  35673. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  35674. HAVE_FULLFSYNC, isFullsync));
  35675. rc = osOpenDirectory(pFile->zPath, &dirfd);
  35676. if( rc==SQLITE_OK && dirfd>=0 ){
  35677. full_fsync(dirfd, 0, 0);
  35678. robust_close(pFile, dirfd, __LINE__);
  35679. }else if( rc==SQLITE_CANTOPEN ){
  35680. rc = SQLITE_OK;
  35681. }
  35682. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  35683. }
  35684. return rc;
  35685. }
  35686. /*
  35687. ** Truncate an open file to a specified size
  35688. */
  35689. static int rttTruncate(sqlite3_file *id, i64 nByte){
  35690. rttFile *pFile = (rttFile *)id;
  35691. int rc;
  35692. assert( pFile );
  35693. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  35694. /* If the user has configured a chunk-size for this file, truncate the
  35695. ** file so that it consists of an integer number of chunks (i.e. the
  35696. ** actual file size after the operation may be larger than the requested
  35697. ** size).
  35698. */
  35699. if( pFile->szChunk>0 ){
  35700. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  35701. }
  35702. rc = robust_ftruncate(pFile->h, (off_t)nByte);
  35703. if( rc ){
  35704. pFile->lastErrno = errno;
  35705. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35706. }else{
  35707. #ifdef SQLITE_DEBUG
  35708. /* If we are doing a normal write to a database file (as opposed to
  35709. ** doing a hot-journal rollback or a write to some file other than a
  35710. ** normal database file) and we truncate the file to zero length,
  35711. ** that effectively updates the change counter. This might happen
  35712. ** when restoring a database using the backup API from a zero-length
  35713. ** source.
  35714. */
  35715. if( pFile->inNormalWrite && nByte==0 ){
  35716. pFile->transCntrChng = 1;
  35717. }
  35718. #endif
  35719. return SQLITE_OK;
  35720. }
  35721. }
  35722. /*
  35723. ** Determine the current size of a file in bytes
  35724. */
  35725. static int rttFileSize(sqlite3_file *id, i64 *pSize){
  35726. int rc;
  35727. struct stat buf;
  35728. assert( id );
  35729. rc = osFstat(((rttFile*)id)->h, &buf);
  35730. SimulateIOError( rc=1 );
  35731. if( rc!=0 ){
  35732. ((rttFile*)id)->lastErrno = errno;
  35733. return SQLITE_IOERR_FSTAT;
  35734. }
  35735. *pSize = buf.st_size;
  35736. /* When opening a zero-size database, the findInodeInfo() procedure
  35737. ** writes a single byte into that file in order to work around a bug
  35738. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  35739. ** layers, we need to report this file size as zero even though it is
  35740. ** really 1. Ticket #3260.
  35741. */
  35742. if( *pSize==1 ) *pSize = 0;
  35743. return SQLITE_OK;
  35744. }
  35745. /*
  35746. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  35747. ** file-control operation. Enlarge the database to nBytes in size
  35748. ** (rounded up to the next chunk-size). If the database is already
  35749. ** nBytes or larger, this routine is a no-op.
  35750. */
  35751. static int fcntlSizeHint(rttFile *pFile, i64 nByte){
  35752. if( pFile->szChunk>0 ){
  35753. i64 nSize; /* Required file size */
  35754. struct stat buf; /* Used to hold return values of fstat() */
  35755. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  35756. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  35757. if( nSize>(i64)buf.st_size ){
  35758. /* If the OS does not have posix_fallocate(), fake it. First use
  35759. ** ftruncate() to set the file size, then write a single byte to
  35760. ** the last byte in each block within the extended region. This
  35761. ** is the same technique used by glibc to implement posix_fallocate()
  35762. ** on systems that do not have a real fallocate() system call.
  35763. */
  35764. int nBlk = buf.st_blksize; /* File-system block size */
  35765. i64 iWrite; /* Next offset to write to */
  35766. if( robust_ftruncate(pFile->h, nSize) ){
  35767. pFile->lastErrno = errno;
  35768. return rttLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  35769. }
  35770. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  35771. while( iWrite<nSize ){
  35772. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  35773. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  35774. iWrite += nBlk;
  35775. }
  35776. }
  35777. }
  35778. return SQLITE_OK;
  35779. }
  35780. /*
  35781. ** If *pArg is inititially negative then this is a query. Set *pArg to
  35782. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  35783. **
  35784. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  35785. */
  35786. static void rttModeBit(rttFile *pFile, unsigned char mask, int *pArg){
  35787. if( *pArg<0 ){
  35788. *pArg = (pFile->ctrlFlags & mask)!=0;
  35789. }else if( (*pArg)==0 ){
  35790. pFile->ctrlFlags &= ~mask;
  35791. }else{
  35792. pFile->ctrlFlags |= mask;
  35793. }
  35794. }
  35795. /* Forward declaration */
  35796. static int rttGetTempname(int nBuf, char *zBuf);
  35797. /*
  35798. ** Information and control of an open file handle.
  35799. */
  35800. static int rttFileControl(sqlite3_file *id, int op, void *pArg){
  35801. rttFile *pFile = (rttFile*)id;
  35802. switch( op ){
  35803. case SQLITE_FCNTL_LOCKSTATE: {
  35804. *(int*)pArg = pFile->eFileLock;
  35805. return SQLITE_OK;
  35806. }
  35807. case SQLITE_LAST_ERRNO: {
  35808. *(int*)pArg = pFile->lastErrno;
  35809. return SQLITE_OK;
  35810. }
  35811. case SQLITE_FCNTL_CHUNK_SIZE: {
  35812. pFile->szChunk = *(int *)pArg;
  35813. return SQLITE_OK;
  35814. }
  35815. case SQLITE_FCNTL_SIZE_HINT: {
  35816. int rc;
  35817. SimulateIOErrorBenign(1);
  35818. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  35819. SimulateIOErrorBenign(0);
  35820. return rc;
  35821. }
  35822. case SQLITE_FCNTL_PERSIST_WAL: {
  35823. rttModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  35824. return SQLITE_OK;
  35825. }
  35826. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  35827. rttModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  35828. return SQLITE_OK;
  35829. }
  35830. case SQLITE_FCNTL_VFSNAME: {
  35831. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  35832. return SQLITE_OK;
  35833. }
  35834. case SQLITE_FCNTL_TEMPFILENAME: {
  35835. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  35836. if( zTFile ){
  35837. rttGetTempname(pFile->pVfs->mxPathname, zTFile);
  35838. *(char**)pArg = zTFile;
  35839. }
  35840. return SQLITE_OK;
  35841. }
  35842. #ifdef SQLITE_DEBUG
  35843. /* The pager calls this method to signal that it has done
  35844. ** a rollback and that the database is therefore unchanged and
  35845. ** it hence it is OK for the transaction change counter to be
  35846. ** unchanged.
  35847. */
  35848. case SQLITE_FCNTL_DB_UNCHANGED: {
  35849. ((rttFile*)id)->dbUpdate = 0;
  35850. return SQLITE_OK;
  35851. }
  35852. #endif
  35853. }
  35854. return SQLITE_NOTFOUND;
  35855. }
  35856. /*
  35857. ** Return the sector size in bytes of the underlying block device for
  35858. ** the specified file. This is almost always 512 bytes, but may be
  35859. ** larger for some devices.
  35860. **
  35861. ** SQLite code assumes this function cannot fail. It also assumes that
  35862. ** if two files are created in the same file-system directory (i.e.
  35863. ** a database and its journal file) that the sector size will be the
  35864. ** same for both.
  35865. */
  35866. static int rttSectorSize(sqlite3_file *NotUsed){
  35867. UNUSED_PARAMETER(NotUsed);
  35868. return SQLITE_DEFAULT_SECTOR_SIZE;
  35869. }
  35870. /*
  35871. ** Return the device characteristics for the file.
  35872. **
  35873. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  35874. ** However, that choice is contraversial since technically the underlying
  35875. ** file system does not always provide powersafe overwrites. (In other
  35876. ** words, after a power-loss event, parts of the file that were never
  35877. ** written might end up being altered.) However, non-PSOW behavior is very,
  35878. ** very rare. And asserting PSOW makes a large reduction in the amount
  35879. ** of required I/O for journaling, since a lot of padding is eliminated.
  35880. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  35881. ** available to turn it off and URI query parameter available to turn it off.
  35882. */
  35883. static int rttDeviceCharacteristics(sqlite3_file *id){
  35884. rttFile *p = (rttFile*)id;
  35885. int rc = 0;
  35886. if( p->ctrlFlags & UNIXFILE_PSOW ){
  35887. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  35888. }
  35889. return rc;
  35890. }
  35891. #ifndef SQLITE_OMIT_WAL
  35892. # error "WAL mode requires not support from the rt-thread, compile\
  35893. with SQLITE_OMIT_WAL."
  35894. #else
  35895. # define rttShmMap 0
  35896. # define rttShmLock 0
  35897. # define rttShmBarrier 0
  35898. # define rttShmUnmap 0
  35899. #endif /* #ifndef SQLITE_OMIT_WAL */
  35900. #if SQLITE_MAX_MMAP_SIZE>0
  35901. #error "rtt not spportt mmap"
  35902. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  35903. /*
  35904. ** If possible, return a pointer to a mapping of file fd starting at offset
  35905. ** iOff. The mapping must be valid for at least nAmt bytes.
  35906. **
  35907. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  35908. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  35909. ** Finally, if an error does occur, return an SQLite error code. The final
  35910. ** value of *pp is undefined in this case.
  35911. **
  35912. ** If this function does return a pointer, the caller must eventually
  35913. ** release the reference by calling unixUnfetch().
  35914. */
  35915. static int rttFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  35916. *pp = 0;
  35917. return SQLITE_OK;
  35918. }
  35919. /*
  35920. ** If the third argument is non-NULL, then this function releases a
  35921. ** reference obtained by an earlier call to unixFetch(). The second
  35922. ** argument passed to this function must be the same as the corresponding
  35923. ** argument that was passed to the unixFetch() invocation.
  35924. **
  35925. ** Or, if the third argument is NULL, then this function is being called
  35926. ** to inform the VFS layer that, according to POSIX, any existing mapping
  35927. ** may now be invalid and should be unmapped.
  35928. */
  35929. static int rttUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  35930. rttFile *pFd = (rttFile *)fd; /* The underlying database file */
  35931. UNUSED_PARAMETER(iOff);
  35932. return SQLITE_OK;
  35933. }
  35934. /*
  35935. ** Here ends the implementation of all sqlite3_file methods.
  35936. **
  35937. ********************** End sqlite3_file Methods *******************************
  35938. ******************************************************************************/
  35939. /*
  35940. ** This division contains definitions of sqlite3_io_methods objects that
  35941. ** implement various file locking strategies. It also contains definitions
  35942. ** of "finder" functions. A finder-function is used to locate the appropriate
  35943. ** sqlite3_io_methods object for a particular database file. The pAppData
  35944. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  35945. ** the correct finder-function for that VFS.
  35946. **
  35947. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  35948. ** object. The only interesting finder-function is autolockIoFinder, which
  35949. ** looks at the filesystem type and tries to guess the best locking
  35950. ** strategy from that.
  35951. **
  35952. ** For finder-funtion F, two objects are created:
  35953. **
  35954. ** (1) The real finder-function named "FImpt()".
  35955. **
  35956. ** (2) A constant pointer to this function named just "F".
  35957. **
  35958. **
  35959. ** A pointer to the F pointer is used as the pAppData value for VFS
  35960. ** objects. We have to do this instead of letting pAppData point
  35961. ** directly at the finder-function since C90 rules prevent a void*
  35962. ** from be cast into a function pointer.
  35963. **
  35964. **
  35965. ** Each instance of this macro generates two objects:
  35966. **
  35967. ** * A constant sqlite3_io_methods object call METHOD that has locking
  35968. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  35969. **
  35970. ** * An I/O method finder function called FINDER that returns a pointer
  35971. ** to the METHOD object in the previous bullet.
  35972. */
  35973. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK) \
  35974. static const sqlite3_io_methods METHOD = { \
  35975. VERSION, /* iVersion */ \
  35976. CLOSE, /* xClose */ \
  35977. rttRead, /* xRead */ \
  35978. rttWrite, /* xWrite */ \
  35979. rttTruncate, /* xTruncate */ \
  35980. rttSync, /* xSync */ \
  35981. rttFileSize, /* xFileSize */ \
  35982. LOCK, /* xLock */ \
  35983. UNLOCK, /* xUnlock */ \
  35984. CKLOCK, /* xCheckReservedLock */ \
  35985. rttFileControl, /* xFileControl */ \
  35986. rttSectorSize, /* xSectorSize */ \
  35987. rttDeviceCharacteristics, /* xDeviceCapabilities */ \
  35988. rttShmMap, /* xShmMap */ \
  35989. rttShmLock, /* xShmLock */ \
  35990. rttShmBarrier, /* xShmBarrier */ \
  35991. rttShmUnmap, /* xShmUnmap */ \
  35992. rttFetch, /* xFetch */ \
  35993. rttUnfetch, /* xUnfetch */ \
  35994. }; \
  35995. static const sqlite3_io_methods *FINDER##Impl(const char *z, rttFile *p){ \
  35996. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  35997. return &METHOD; \
  35998. } \
  35999. static const sqlite3_io_methods *(*const FINDER)(const char*,rttFile *p) \
  36000. = FINDER##Impl;
  36001. /*
  36002. ** Here are all of the sqlite3_io_methods objects for each of the
  36003. ** locking strategies. Functions that return pointers to these methods
  36004. ** are also created.
  36005. */
  36006. IOMETHODS(
  36007. nolockIoFinder, /* Finder function name */
  36008. nolockIoMethods, /* sqlite3_io_methods object name */
  36009. 1, /* shared memory is disabled */
  36010. nolockClose, /* xClose method */
  36011. nolockLock, /* xLock method */
  36012. nolockUnlock, /* xUnlock method */
  36013. nolockCheckReservedLock /* xCheckReservedLock method */
  36014. )
  36015. IOMETHODS(
  36016. dotlockIoFinder, /* Finder function name */
  36017. dotlockIoMethods, /* sqlite3_io_methods object name */
  36018. 1, /* shared memory is disabled */
  36019. dotlockClose, /* xClose method */
  36020. dotlockLock, /* xLock method */
  36021. dotlockUnlock, /* xUnlock method */
  36022. dotlockCheckReservedLock /* xCheckReservedLock method */
  36023. )
  36024. #if SQLITE_ENABLE_LOCKING_STYLE
  36025. IOMETHODS(
  36026. flockIoFinder, /* Finder function name */
  36027. flockIoMethods, /* sqlite3_io_methods object name */
  36028. 1, /* shared memory is disabled */
  36029. flockClose, /* xClose method */
  36030. flockLock, /* xLock method */
  36031. flockUnlock, /* xUnlock method */
  36032. flockCheckReservedLock /* xCheckReservedLock method */
  36033. )
  36034. #endif
  36035. /*
  36036. ** An abstract type for a pointer to a IO method finder function:
  36037. */
  36038. typedef const sqlite3_io_methods *(*finder_type)(const char*,rttFile*);
  36039. /****************************************************************************
  36040. **************************** sqlite3_vfs methods ****************************
  36041. **
  36042. ** This division contains the implementation of methods on the
  36043. ** sqlite3_vfs object.
  36044. */
  36045. /*
  36046. ** Initialize the contents of the rttFile structure pointed to by pId.
  36047. */
  36048. static int fillInRttFile(
  36049. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36050. int h, /* Open file descriptor of file being opened */
  36051. sqlite3_file *pId, /* Write to the rttFile structure here */
  36052. const char *zFilename, /* Name of the file being opened */
  36053. int ctrlFlags /* Zero or more UNIXFILE_* values */
  36054. ){
  36055. const sqlite3_io_methods *pLockingStyle;
  36056. rttFile *pNew = (rttFile *)pId;
  36057. int rc = SQLITE_OK;
  36058. assert( pNew->pInode==NULL );
  36059. /* Usually the path zFilename should not be a relative pathname. The
  36060. ** exception is when opening the proxy "conch" file in builds that
  36061. ** include the special Apple locking styles.
  36062. */
  36063. assert( zFilename==0 || zFilename[0]=='/' );
  36064. /* No locking occurs in temporary files */
  36065. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  36066. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  36067. pNew->h = h;
  36068. pNew->pVfs = pVfs;
  36069. pNew->zPath = zFilename;
  36070. pNew->ctrlFlags = (u8)ctrlFlags;
  36071. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  36072. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  36073. pNew->ctrlFlags |= UNIXFILE_PSOW;
  36074. }
  36075. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  36076. pNew->ctrlFlags |= UNIXFILE_EXCL;
  36077. }
  36078. if( ctrlFlags & UNIXFILE_NOLOCK ){
  36079. pLockingStyle = &nolockIoMethods;
  36080. }else{
  36081. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  36082. #if SQLITE_ENABLE_LOCKING_STYLE
  36083. /* Cache zFilename in the locking context (AFP and dotlock override) for
  36084. ** proxyLock activation is possible (remote proxy is based on db name)
  36085. ** zFilename remains valid until file is closed, to support */
  36086. pNew->lockingContext = (void*)zFilename;
  36087. #endif
  36088. }
  36089. if( pLockingStyle == &dotlockIoMethods ){
  36090. /* Dotfile locking uses the file path so it needs to be included in
  36091. ** the dotlockLockingContext
  36092. */
  36093. char *zLockFile;
  36094. int nFilename;
  36095. assert( zFilename!=0 );
  36096. nFilename = (int)strlen(zFilename) + 6;
  36097. zLockFile = (char *)sqlite3_malloc(nFilename);
  36098. if( zLockFile==0 ){
  36099. rc = SQLITE_NOMEM;
  36100. }else{
  36101. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  36102. }
  36103. pNew->lockingContext = zLockFile;
  36104. }
  36105. pNew->lastErrno = 0;
  36106. if( rc!=SQLITE_OK ){
  36107. if( h>=0 ) robust_close(pNew, h, __LINE__);
  36108. }else{
  36109. pNew->pMethod = pLockingStyle;
  36110. OpenCounter(+1);
  36111. verifyDbFile(pNew);
  36112. }
  36113. return rc;
  36114. }
  36115. /*
  36116. ** Return the name of a directory in which to put temporary files.
  36117. ** If no suitable temporary file directory can be found, return NULL.
  36118. */
  36119. static const char *rttTempFileDir(void){
  36120. static const char *azDirs[] = {
  36121. 0,
  36122. "/sql",
  36123. "/sql/tmp"
  36124. "/tmp",
  36125. 0 /* List terminator */
  36126. };
  36127. unsigned int i;
  36128. struct stat buf;
  36129. const char *zDir = 0;
  36130. azDirs[0] = sqlite3_temp_directory;
  36131. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  36132. if( zDir==0 ) continue;
  36133. if( osStat(zDir, &buf) ) continue;
  36134. if( !S_ISDIR(buf.st_mode) ) continue;
  36135. break;
  36136. }
  36137. return zDir;
  36138. }
  36139. /*
  36140. ** Create a temporary file name in zBuf. zBuf must be allocated
  36141. ** by the calling process and must be big enough to hold at least
  36142. ** pVfs->mxPathname bytes.
  36143. */
  36144. static int rttGetTempname(int nBuf, char *zBuf){
  36145. static const unsigned char zChars[] =
  36146. "abcdefghijklmnopqrstuvwxyz"
  36147. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  36148. "0123456789";
  36149. unsigned int i, j;
  36150. const char *zDir;
  36151. /* It's odd to simulate an io-error here, but really this is just
  36152. ** using the io-error infrastructure to test that SQLite handles this
  36153. ** function failing.
  36154. */
  36155. SimulateIOError( return SQLITE_IOERR );
  36156. zDir = rttTempFileDir();
  36157. if( zDir==0 ) zDir = ".";
  36158. /* Check that the output buffer is large enough for the temporary file
  36159. ** name. If it is not, return SQLITE_ERROR.
  36160. */
  36161. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  36162. return SQLITE_ERROR;
  36163. }
  36164. do{
  36165. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  36166. j = (int)strlen(zBuf);
  36167. sqlite3_randomness(15, &zBuf[j]);
  36168. for(i=0; i<15; i++, j++){
  36169. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  36170. }
  36171. zBuf[j] = 0;
  36172. zBuf[j+1] = 0;
  36173. }while( osAccess(zBuf,0)==0 );
  36174. return SQLITE_OK;
  36175. }
  36176. /*
  36177. ** Open the file zPath.
  36178. **
  36179. ** Previously, the SQLite OS layer used three functions in place of this
  36180. ** one:
  36181. **
  36182. ** sqlite3OsOpenReadWrite();
  36183. ** sqlite3OsOpenReadOnly();
  36184. ** sqlite3OsOpenExclusive();
  36185. **
  36186. ** These calls correspond to the following combinations of flags:
  36187. **
  36188. ** ReadWrite() -> (READWRITE | CREATE)
  36189. ** ReadOnly() -> (READONLY)
  36190. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  36191. **
  36192. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  36193. ** true, the file was configured to be automatically deleted when the
  36194. ** file handle closed. To achieve the same effect using this new
  36195. ** interface, add the DELETEONCLOSE flag to those specified above for
  36196. ** OpenExclusive().
  36197. */
  36198. static int rttOpen(
  36199. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  36200. const char *zPath, /* Pathname of file to be opened */
  36201. sqlite3_file *pFile, /* The file descriptor to be filled in */
  36202. int flags, /* Input flags to control the opening */
  36203. int *pOutFlags /* Output flags returned to SQLite core */
  36204. ){
  36205. rttFile *p = (rttFile *)pFile;
  36206. int fd = -1; /* File descriptor returned by open() */
  36207. int openFlags = 0; /* Flags to pass to open() */
  36208. int eType = flags&0xFFFFFF00; /* Type of file to open */
  36209. int noLock; /* True to omit locking primitives */
  36210. int rc = SQLITE_OK; /* Function Return Code */
  36211. int ctrlFlags = 0; /* UNIXFILE_* flags */
  36212. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  36213. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  36214. int isCreate = (flags & SQLITE_OPEN_CREATE);
  36215. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  36216. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  36217. #if SQLITE_ENABLE_LOCKING_STYLE
  36218. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  36219. #endif
  36220. /* If creating a master or main-file journal, this function will open
  36221. ** a file-descriptor on the directory too. The first time unixSync()
  36222. ** is called the directory file descriptor will be fsync()ed and close()d.
  36223. */
  36224. int syncDir = (isCreate && (
  36225. eType==SQLITE_OPEN_MASTER_JOURNAL
  36226. || eType==SQLITE_OPEN_MAIN_JOURNAL
  36227. || eType==SQLITE_OPEN_WAL
  36228. ));
  36229. /* If argument zPath is a NULL pointer, this function is required to open
  36230. ** a temporary file. Use this buffer to store the file name in.
  36231. */
  36232. char zTmpname[MAX_PATHNAME+2];
  36233. const char *zName = zPath;
  36234. /* Check the following statements are true:
  36235. **
  36236. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  36237. ** (b) if CREATE is set, then READWRITE must also be set, and
  36238. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  36239. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  36240. */
  36241. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  36242. assert(isCreate==0 || isReadWrite);
  36243. assert(isExclusive==0 || isCreate);
  36244. assert(isDelete==0 || isCreate);
  36245. /* The main DB, main journal, WAL file and master journal are never
  36246. ** automatically deleted. Nor are they ever temporary files. */
  36247. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  36248. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  36249. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  36250. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  36251. /* Assert that the upper layer has set one of the "file-type" flags. */
  36252. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  36253. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  36254. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  36255. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  36256. );
  36257. memset(p, 0, sizeof(rttFile));
  36258. if( !zName ){
  36259. /* If zName is NULL, the upper layer is requesting a temp file. */
  36260. assert(isDelete && !syncDir);
  36261. rc = rttGetTempname(MAX_PATHNAME+2, zTmpname);
  36262. if( rc!=SQLITE_OK ){
  36263. return rc;
  36264. }
  36265. zName = zTmpname;
  36266. /* Generated temporary filenames are always double-zero terminated
  36267. ** for use by sqlite3_uri_parameter(). */
  36268. assert( zName[strlen(zName)+1]==0 );
  36269. }
  36270. /* Determine the value of the flags parameter passed to POSIX function
  36271. ** open(). These must be calculated even if open() is not called, as
  36272. ** they may be stored as part of the file handle and used by the
  36273. ** 'conch file' locking functions later on. */
  36274. if( isReadonly ) openFlags |= O_RDONLY;
  36275. if( isReadWrite ) openFlags |= O_RDWR;
  36276. if( isCreate ) openFlags |= O_CREAT;
  36277. if( isExclusive ) openFlags |= (O_EXCL|0/*O_NOFOLLOW8*/);
  36278. openFlags |= (0/*O_LARGEFILE*/|O_BINARY);
  36279. if( fd<0 ){
  36280. mode_t openMode = 0; /* Permissions to create file with */
  36281. fd = robust_open(zName, openFlags, openMode);
  36282. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  36283. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  36284. /* Failed to open the file for read/write access. Try read-only. */
  36285. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  36286. openFlags &= ~(O_RDWR|O_CREAT);
  36287. flags |= SQLITE_OPEN_READONLY;
  36288. openFlags |= O_RDONLY;
  36289. isReadonly = 1;
  36290. fd = robust_open(zName, openFlags, openMode);
  36291. }
  36292. if( fd<0 ){
  36293. rc = rttLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  36294. goto open_finished;
  36295. }
  36296. }
  36297. assert( fd>=0 );
  36298. if( pOutFlags ){
  36299. *pOutFlags = flags;
  36300. }
  36301. if( isDelete ){
  36302. osUnlink(zName);
  36303. }
  36304. #if SQLITE_ENABLE_LOCKING_STYLE
  36305. else{
  36306. p->openFlags = openFlags;
  36307. }
  36308. #endif
  36309. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  36310. /* Set up appropriate ctrlFlags */
  36311. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  36312. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  36313. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  36314. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  36315. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  36316. rc = fillInRttFile(pVfs, fd, pFile, zPath, ctrlFlags);
  36317. open_finished:
  36318. return rc;
  36319. }
  36320. /*
  36321. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  36322. ** the directory after deleting the file.
  36323. */
  36324. static int rttDelete(
  36325. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  36326. const char *zPath, /* Name of file to be deleted */
  36327. int dirSync /* If true, fsync() directory after deleting file */
  36328. ){
  36329. int rc = SQLITE_OK;
  36330. UNUSED_PARAMETER(NotUsed);
  36331. SimulateIOError(return SQLITE_IOERR_DELETE);
  36332. if( osUnlink(zPath)==(-1) ){
  36333. if( errno==ENOENT ){
  36334. rc = SQLITE_IOERR_DELETE_NOENT;
  36335. }else{
  36336. rc = rttLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  36337. }
  36338. return rc;
  36339. }
  36340. #ifndef SQLITE_DISABLE_DIRSYNC
  36341. if( (dirSync & 1)!=0 ){
  36342. int fd;
  36343. rc = osOpenDirectory(zPath, &fd);
  36344. if( rc==SQLITE_OK ){
  36345. robust_close(0, fd, __LINE__);
  36346. }else if( rc==SQLITE_CANTOPEN ){
  36347. rc = SQLITE_OK;
  36348. }
  36349. }
  36350. #endif
  36351. return rc;
  36352. }
  36353. /*
  36354. ** Test the existence of or access permissions of file zPath. The
  36355. ** test performed depends on the value of flags:
  36356. **
  36357. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  36358. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  36359. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  36360. **
  36361. ** Otherwise return 0.
  36362. */
  36363. static int rttAccess(
  36364. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  36365. const char *zPath, /* Path of the file to examine */
  36366. int flags, /* What do we want to learn about the zPath file? */
  36367. int *pResOut /* Write result boolean here */
  36368. ){
  36369. int amode = 0;
  36370. UNUSED_PARAMETER(NotUsed);
  36371. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  36372. switch( flags ){
  36373. case SQLITE_ACCESS_EXISTS:
  36374. amode = F_OK;
  36375. break;
  36376. case SQLITE_ACCESS_READWRITE:
  36377. amode = W_OK|R_OK;
  36378. break;
  36379. case SQLITE_ACCESS_READ:
  36380. amode = R_OK;
  36381. break;
  36382. default:
  36383. assert(!"Invalid flags argument");
  36384. }
  36385. *pResOut = (osAccess(zPath, amode)==0);
  36386. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  36387. struct stat buf;
  36388. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  36389. *pResOut = 0;
  36390. }
  36391. }
  36392. return SQLITE_OK;
  36393. }
  36394. /*
  36395. ** Turn a relative pathname into a full pathname. The relative path
  36396. ** is stored as a nul-terminated string in the buffer pointed to by
  36397. ** zPath.
  36398. **
  36399. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  36400. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  36401. ** this buffer before returning.
  36402. */
  36403. static int rttFullPathname(
  36404. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  36405. const char *zPath, /* Possibly relative input path */
  36406. int nOut, /* Size of output buffer in bytes */
  36407. char *zOut /* Output buffer */
  36408. ){
  36409. /* It's odd to simulate an io-error here, but really this is just
  36410. ** using the io-error infrastructure to test that SQLite handles this
  36411. ** function failing. This function could fail if, for example, the
  36412. ** current working directory has been unlinked.
  36413. */
  36414. SimulateIOError( return SQLITE_ERROR );
  36415. assert( pVfs->mxPathname==MAX_PATHNAME );
  36416. UNUSED_PARAMETER(pVfs);
  36417. zOut[nOut-1] = '\0';
  36418. if( zPath[0]=='/' ){
  36419. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  36420. }else{
  36421. int nCwd;
  36422. if( osGetcwd(zOut, nOut-1)==0 ){
  36423. return rttLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  36424. }
  36425. nCwd = (int)strlen(zOut);
  36426. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  36427. }
  36428. return SQLITE_OK;
  36429. }
  36430. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  36431. # error "rtt not support load extension, compile with SQLITE_OMIT_WAL."
  36432. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  36433. #define rttDlOpen 0
  36434. #define rttDlError 0
  36435. #define rttDlSym 0
  36436. #define rttDlClose 0
  36437. #endif
  36438. /*
  36439. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  36440. */
  36441. static int rttRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  36442. UNUSED_PARAMETER(NotUsed);
  36443. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  36444. /* We have to initialize zBuf to prevent valgrind from reporting
  36445. ** errors. The reports issued by valgrind are incorrect - we would
  36446. ** prefer that the randomness be increased by making use of the
  36447. ** uninitialized space in zBuf - but valgrind errors tend to worry
  36448. ** some users. Rather than argue, it seems easier just to initialize
  36449. ** the whole array and silence valgrind, even if that means less randomness
  36450. ** in the random seed.
  36451. **
  36452. ** When testing, initializing zBuf[] to zero is all we do. That means
  36453. ** that we always use the same random number sequence. This makes the
  36454. ** tests repeatable.
  36455. */
  36456. memset(zBuf, 0, nBuf);
  36457. {
  36458. int i;
  36459. char tick8, tick16;
  36460. tick8 = (char)rt_tick_get();
  36461. tick16 = (char)(rt_tick_get() >> 8);
  36462. for (i=0; i<nBuf; i++)
  36463. {
  36464. zBuf[i] = (char)(i ^ tick8 ^ tick16);
  36465. tick8 = zBuf[i];
  36466. tick16 = ~(tick8 ^ tick16);
  36467. }
  36468. }
  36469. return nBuf;
  36470. }
  36471. /*
  36472. ** Sleep for a little while. Return the amount of time slept.
  36473. ** The argument is the number of microseconds we want to sleep.
  36474. ** The return value is the number of microseconds of sleep actually
  36475. ** requested from the underlying operating system, a number which
  36476. ** might be greater than or equal to the argument, but not less
  36477. ** than the argument.
  36478. */
  36479. static int rttSleep(sqlite3_vfs *NotUsed, int microseconds){
  36480. int seconds = (microseconds+999999)/1000000;
  36481. osSleep(seconds * 1000);
  36482. UNUSED_PARAMETER(NotUsed);
  36483. return seconds*1000000;
  36484. }
  36485. /*
  36486. ** The following variable, if set to a non-zero value, is interpreted as
  36487. ** the number of seconds since 1970 and is used to set the result of
  36488. ** sqlite3OsCurrentTime() during testing.
  36489. */
  36490. #ifdef SQLITE_TEST
  36491. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  36492. #endif
  36493. #ifndef NO_GETTOD
  36494. #define NO_GETTOD 1
  36495. #endif
  36496. /*
  36497. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  36498. ** the current time and date as a Julian Day number times 86_400_000. In
  36499. ** other words, write into *piNow the number of milliseconds since the Julian
  36500. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  36501. ** proleptic Gregorian calendar.
  36502. **
  36503. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  36504. ** cannot be found.
  36505. */
  36506. static int rttCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  36507. static const sqlite3_int64 rttEpoch = 24405875*(sqlite3_int64)8640000;
  36508. int rc = SQLITE_OK;
  36509. #if defined(NO_GETTOD)
  36510. time_t t;
  36511. time(&t);
  36512. *piNow = ((sqlite3_int64)t)*1000 + rttEpoch;
  36513. #else
  36514. struct timeval sNow;
  36515. if( gettimeofday(&sNow, 0)==0 ){
  36516. *piNow = rttEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  36517. }else{
  36518. rc = SQLITE_ERROR;
  36519. }
  36520. #endif
  36521. #ifdef SQLITE_TEST
  36522. if( sqlite3_current_time ){
  36523. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + rttEpoch;
  36524. }
  36525. #endif
  36526. UNUSED_PARAMETER(NotUsed);
  36527. return rc;
  36528. }
  36529. /*
  36530. ** Find the current time (in Universal Coordinated Time). Write the
  36531. ** current time and date as a Julian Day number into *prNow and
  36532. ** return 0. Return 1 if the time and date cannot be found.
  36533. */
  36534. static int rttCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  36535. sqlite3_int64 i = 0;
  36536. int rc;
  36537. UNUSED_PARAMETER(NotUsed);
  36538. rc = rttCurrentTimeInt64(0, &i);
  36539. *prNow = i/86400000.0;
  36540. return rc;
  36541. }
  36542. /*
  36543. ** We added the xGetLastError() method with the intention of providing
  36544. ** better low-level error messages when operating-system problems come up
  36545. ** during SQLite operation. But so far, none of that has been implemented
  36546. ** in the core. So this routine is never called. For now, it is merely
  36547. ** a place-holder.
  36548. */
  36549. static int rttGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  36550. UNUSED_PARAMETER(NotUsed);
  36551. UNUSED_PARAMETER(NotUsed2);
  36552. UNUSED_PARAMETER(NotUsed3);
  36553. return 0;
  36554. }
  36555. /*
  36556. ************************ End of sqlite3_vfs methods ***************************
  36557. ******************************************************************************/
  36558. /*
  36559. ** Initialize the operating system interface.
  36560. **
  36561. ** This routine registers all VFS implementations for unix-like operating
  36562. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  36563. ** should be the only routines in this file that are visible from other
  36564. ** files.
  36565. **
  36566. ** This routine is called once during SQLite initialization and by a
  36567. ** single thread. The memory allocation and mutex subsystems have not
  36568. ** necessarily been initialized when this routine is called, and so they
  36569. ** should not be used.
  36570. */
  36571. /*
  36572. ** The following macro defines an initializer for an sqlite3_vfs object.
  36573. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  36574. ** to the "finder" function. (pAppData is a pointer to a pointer because
  36575. ** silly C90 rules prohibit a void* from being cast to a function pointer
  36576. ** and so we have to go through the intermediate pointer to avoid problems
  36577. ** when compiling with -pedantic-errors on GCC.)
  36578. **
  36579. ** The FINDER parameter to this macro is the name of the pointer to the
  36580. ** finder-function. The finder-function returns a pointer to the
  36581. ** sqlite_io_methods object that implements the desired locking
  36582. ** behaviors. See the division above that contains the IOMETHODS
  36583. ** macro for addition information on finder-functions.
  36584. **
  36585. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  36586. ** object. But the "autolockIoFinder" available on MacOSX does a little
  36587. ** more than that; it looks at the filesystem type that hosts the
  36588. ** database file and tries to choose an locking method appropriate for
  36589. ** that filesystem time.
  36590. */
  36591. #define UNIXVFS(VFSNAME, FINDER) { \
  36592. 3, /* iVersion */ \
  36593. sizeof(rttFile), /* szOsFile */ \
  36594. MAX_PATHNAME, /* mxPathname */ \
  36595. 0, /* pNext */ \
  36596. VFSNAME, /* zName */ \
  36597. (void*)&FINDER, /* pAppData */ \
  36598. rttOpen, /* xOpen */ \
  36599. rttDelete, /* xDelete */ \
  36600. rttAccess, /* xAccess */ \
  36601. rttFullPathname, /* xFullPathname */ \
  36602. rttDlOpen, /* xDlOpen */ \
  36603. rttDlError, /* xDlError */ \
  36604. rttDlSym, /* xDlSym */ \
  36605. rttDlClose, /* xDlClose */ \
  36606. rttRandomness, /* xRandomness */ \
  36607. rttSleep, /* xSleep */ \
  36608. rttCurrentTime, /* xCurrentTime */ \
  36609. rttGetLastError, /* xGetLastError */ \
  36610. rttCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  36611. rttSetSystemCall, /* xSetSystemCall */ \
  36612. rttGetSystemCall, /* xGetSystemCall */ \
  36613. rttNextSystemCall, /* xNextSystemCall */ \
  36614. }
  36615. SQLITE_API int sqlite3_os_init(void){
  36616. /*
  36617. ** All default VFSes for unix are contained in the following array.
  36618. **
  36619. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  36620. ** by the SQLite core when the VFS is registered. So the following
  36621. ** array cannot be const.
  36622. */
  36623. static sqlite3_vfs aVfs[] = {
  36624. UNIXVFS("unix-none", nolockIoFinder ),
  36625. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  36626. #if SQLITE_ENABLE_LOCKING_STYLE
  36627. UNIXVFS("unix-flock", flockIoFinder ),
  36628. #endif
  36629. };
  36630. unsigned int i; /* Loop counter */
  36631. /* Double-check that the aSyscall[] array has been constructed
  36632. ** correctly. See ticket [bb3a86e890c8e96ab] */
  36633. assert( ArraySize(aSyscall)==24 );
  36634. /* Register all VFSes defined in the aVfs[] array */
  36635. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  36636. sqlite3_vfs_register(&aVfs[i], i==0);
  36637. }
  36638. return SQLITE_OK;
  36639. }
  36640. /*
  36641. ** Shutdown the operating system interface.
  36642. **
  36643. ** Some operating systems might need to do some cleanup in this routine,
  36644. ** to release dynamically allocated objects. But not on unix.
  36645. ** This routine is a no-op for unix.
  36646. */
  36647. SQLITE_API int sqlite3_os_end(void){
  36648. return SQLITE_OK;
  36649. }
  36650. #endif /* SQLITE_OS_RTT */
  36651. /************** End of os_rtt.c **********************************************/
  36652. /************** Begin file bitvec.c ******************************************/
  36653. /*
  36654. ** 2008 February 16
  36655. **
  36656. ** The author disclaims copyright to this source code. In place of
  36657. ** a legal notice, here is a blessing:
  36658. **
  36659. ** May you do good and not evil.
  36660. ** May you find forgiveness for yourself and forgive others.
  36661. ** May you share freely, never taking more than you give.
  36662. **
  36663. *************************************************************************
  36664. ** This file implements an object that represents a fixed-length
  36665. ** bitmap. Bits are numbered starting with 1.
  36666. **
  36667. ** A bitmap is used to record which pages of a database file have been
  36668. ** journalled during a transaction, or which pages have the "dont-write"
  36669. ** property. Usually only a few pages are meet either condition.
  36670. ** So the bitmap is usually sparse and has low cardinality.
  36671. ** But sometimes (for example when during a DROP of a large table) most
  36672. ** or all of the pages in a database can get journalled. In those cases,
  36673. ** the bitmap becomes dense with high cardinality. The algorithm needs
  36674. ** to handle both cases well.
  36675. **
  36676. ** The size of the bitmap is fixed when the object is created.
  36677. **
  36678. ** All bits are clear when the bitmap is created. Individual bits
  36679. ** may be set or cleared one at a time.
  36680. **
  36681. ** Test operations are about 100 times more common that set operations.
  36682. ** Clear operations are exceedingly rare. There are usually between
  36683. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  36684. ** sometimes grow into tens of thousands or larger. The size of the
  36685. ** Bitvec object is the number of pages in the database file at the
  36686. ** start of a transaction, and is thus usually less than a few thousand,
  36687. ** but can be as large as 2 billion for a really big database.
  36688. */
  36689. /* Size of the Bitvec structure in bytes. */
  36690. #define BITVEC_SZ 512
  36691. /* Round the union size down to the nearest pointer boundary, since that's how
  36692. ** it will be aligned within the Bitvec struct. */
  36693. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  36694. /* Type of the array "element" for the bitmap representation.
  36695. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  36696. ** Setting this to the "natural word" size of your CPU may improve
  36697. ** performance. */
  36698. #define BITVEC_TELEM u8
  36699. /* Size, in bits, of the bitmap element. */
  36700. #define BITVEC_SZELEM 8
  36701. /* Number of elements in a bitmap array. */
  36702. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  36703. /* Number of bits in the bitmap array. */
  36704. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  36705. /* Number of u32 values in hash table. */
  36706. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  36707. /* Maximum number of entries in hash table before
  36708. ** sub-dividing and re-hashing. */
  36709. #define BITVEC_MXHASH (BITVEC_NINT/2)
  36710. /* Hashing function for the aHash representation.
  36711. ** Empirical testing showed that the *37 multiplier
  36712. ** (an arbitrary prime)in the hash function provided
  36713. ** no fewer collisions than the no-op *1. */
  36714. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  36715. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  36716. /*
  36717. ** A bitmap is an instance of the following structure.
  36718. **
  36719. ** This bitmap records the existence of zero or more bits
  36720. ** with values between 1 and iSize, inclusive.
  36721. **
  36722. ** There are three possible representations of the bitmap.
  36723. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  36724. ** bitmap. The least significant bit is bit 1.
  36725. **
  36726. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  36727. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  36728. **
  36729. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  36730. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  36731. ** handles up to iDivisor separate values of i. apSub[0] holds
  36732. ** values between 1 and iDivisor. apSub[1] holds values between
  36733. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  36734. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  36735. ** to hold deal with values between 1 and iDivisor.
  36736. */
  36737. struct Bitvec {
  36738. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  36739. u32 nSet; /* Number of bits that are set - only valid for aHash
  36740. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  36741. ** this would be 125. */
  36742. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  36743. /* Should >=0 for apSub element. */
  36744. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  36745. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  36746. union {
  36747. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  36748. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  36749. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  36750. } u;
  36751. };
  36752. /*
  36753. ** Create a new bitmap object able to handle bits between 0 and iSize,
  36754. ** inclusive. Return a pointer to the new object. Return NULL if
  36755. ** malloc fails.
  36756. */
  36757. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  36758. Bitvec *p;
  36759. assert( sizeof(*p)==BITVEC_SZ );
  36760. p = sqlite3MallocZero( sizeof(*p) );
  36761. if( p ){
  36762. p->iSize = iSize;
  36763. }
  36764. return p;
  36765. }
  36766. /*
  36767. ** Check to see if the i-th bit is set. Return true or false.
  36768. ** If p is NULL (if the bitmap has not been created) or if
  36769. ** i is out of range, then return false.
  36770. */
  36771. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  36772. if( p==0 ) return 0;
  36773. if( i>p->iSize || i==0 ) return 0;
  36774. i--;
  36775. while( p->iDivisor ){
  36776. u32 bin = i/p->iDivisor;
  36777. i = i%p->iDivisor;
  36778. p = p->u.apSub[bin];
  36779. if (!p) {
  36780. return 0;
  36781. }
  36782. }
  36783. if( p->iSize<=BITVEC_NBIT ){
  36784. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  36785. } else{
  36786. u32 h = BITVEC_HASH(i++);
  36787. while( p->u.aHash[h] ){
  36788. if( p->u.aHash[h]==i ) return 1;
  36789. h = (h+1) % BITVEC_NINT;
  36790. }
  36791. return 0;
  36792. }
  36793. }
  36794. /*
  36795. ** Set the i-th bit. Return 0 on success and an error code if
  36796. ** anything goes wrong.
  36797. **
  36798. ** This routine might cause sub-bitmaps to be allocated. Failing
  36799. ** to get the memory needed to hold the sub-bitmap is the only
  36800. ** that can go wrong with an insert, assuming p and i are valid.
  36801. **
  36802. ** The calling function must ensure that p is a valid Bitvec object
  36803. ** and that the value for "i" is within range of the Bitvec object.
  36804. ** Otherwise the behavior is undefined.
  36805. */
  36806. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  36807. u32 h;
  36808. if( p==0 ) return SQLITE_OK;
  36809. assert( i>0 );
  36810. assert( i<=p->iSize );
  36811. i--;
  36812. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  36813. u32 bin = i/p->iDivisor;
  36814. i = i%p->iDivisor;
  36815. if( p->u.apSub[bin]==0 ){
  36816. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  36817. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  36818. }
  36819. p = p->u.apSub[bin];
  36820. }
  36821. if( p->iSize<=BITVEC_NBIT ){
  36822. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  36823. return SQLITE_OK;
  36824. }
  36825. h = BITVEC_HASH(i++);
  36826. /* if there wasn't a hash collision, and this doesn't */
  36827. /* completely fill the hash, then just add it without */
  36828. /* worring about sub-dividing and re-hashing. */
  36829. if( !p->u.aHash[h] ){
  36830. if (p->nSet<(BITVEC_NINT-1)) {
  36831. goto bitvec_set_end;
  36832. } else {
  36833. goto bitvec_set_rehash;
  36834. }
  36835. }
  36836. /* there was a collision, check to see if it's already */
  36837. /* in hash, if not, try to find a spot for it */
  36838. do {
  36839. if( p->u.aHash[h]==i ) return SQLITE_OK;
  36840. h++;
  36841. if( h>=BITVEC_NINT ) h = 0;
  36842. } while( p->u.aHash[h] );
  36843. /* we didn't find it in the hash. h points to the first */
  36844. /* available free spot. check to see if this is going to */
  36845. /* make our hash too "full". */
  36846. bitvec_set_rehash:
  36847. if( p->nSet>=BITVEC_MXHASH ){
  36848. unsigned int j;
  36849. int rc;
  36850. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  36851. if( aiValues==0 ){
  36852. return SQLITE_NOMEM;
  36853. }else{
  36854. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36855. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  36856. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  36857. rc = sqlite3BitvecSet(p, i);
  36858. for(j=0; j<BITVEC_NINT; j++){
  36859. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  36860. }
  36861. sqlite3StackFree(0, aiValues);
  36862. return rc;
  36863. }
  36864. }
  36865. bitvec_set_end:
  36866. p->nSet++;
  36867. p->u.aHash[h] = i;
  36868. return SQLITE_OK;
  36869. }
  36870. /*
  36871. ** Clear the i-th bit.
  36872. **
  36873. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  36874. ** that BitvecClear can use to rebuilt its hash table.
  36875. */
  36876. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  36877. if( p==0 ) return;
  36878. assert( i>0 );
  36879. i--;
  36880. while( p->iDivisor ){
  36881. u32 bin = i/p->iDivisor;
  36882. i = i%p->iDivisor;
  36883. p = p->u.apSub[bin];
  36884. if (!p) {
  36885. return;
  36886. }
  36887. }
  36888. if( p->iSize<=BITVEC_NBIT ){
  36889. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  36890. }else{
  36891. unsigned int j;
  36892. u32 *aiValues = pBuf;
  36893. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  36894. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  36895. p->nSet = 0;
  36896. for(j=0; j<BITVEC_NINT; j++){
  36897. if( aiValues[j] && aiValues[j]!=(i+1) ){
  36898. u32 h = BITVEC_HASH(aiValues[j]-1);
  36899. p->nSet++;
  36900. while( p->u.aHash[h] ){
  36901. h++;
  36902. if( h>=BITVEC_NINT ) h = 0;
  36903. }
  36904. p->u.aHash[h] = aiValues[j];
  36905. }
  36906. }
  36907. }
  36908. }
  36909. /*
  36910. ** Destroy a bitmap object. Reclaim all memory used.
  36911. */
  36912. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  36913. if( p==0 ) return;
  36914. if( p->iDivisor ){
  36915. unsigned int i;
  36916. for(i=0; i<BITVEC_NPTR; i++){
  36917. sqlite3BitvecDestroy(p->u.apSub[i]);
  36918. }
  36919. }
  36920. sqlite3_free(p);
  36921. }
  36922. /*
  36923. ** Return the value of the iSize parameter specified when Bitvec *p
  36924. ** was created.
  36925. */
  36926. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  36927. return p->iSize;
  36928. }
  36929. #ifndef SQLITE_OMIT_BUILTIN_TEST
  36930. /*
  36931. ** Let V[] be an array of unsigned characters sufficient to hold
  36932. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  36933. ** Then the following macros can be used to set, clear, or test
  36934. ** individual bits within V.
  36935. */
  36936. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  36937. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  36938. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  36939. /*
  36940. ** This routine runs an extensive test of the Bitvec code.
  36941. **
  36942. ** The input is an array of integers that acts as a program
  36943. ** to test the Bitvec. The integers are opcodes followed
  36944. ** by 0, 1, or 3 operands, depending on the opcode. Another
  36945. ** opcode follows immediately after the last operand.
  36946. **
  36947. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  36948. ** "halt" opcode and causes the test to end.
  36949. **
  36950. ** 0 Halt and return the number of errors
  36951. ** 1 N S X Set N bits beginning with S and incrementing by X
  36952. ** 2 N S X Clear N bits beginning with S and incrementing by X
  36953. ** 3 N Set N randomly chosen bits
  36954. ** 4 N Clear N randomly chosen bits
  36955. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  36956. **
  36957. ** The opcodes 1 through 4 perform set and clear operations are performed
  36958. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  36959. ** Opcode 5 works on the linear array only, not on the Bitvec.
  36960. ** Opcode 5 is used to deliberately induce a fault in order to
  36961. ** confirm that error detection works.
  36962. **
  36963. ** At the conclusion of the test the linear array is compared
  36964. ** against the Bitvec object. If there are any differences,
  36965. ** an error is returned. If they are the same, zero is returned.
  36966. **
  36967. ** If a memory allocation error occurs, return -1.
  36968. */
  36969. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  36970. Bitvec *pBitvec = 0;
  36971. unsigned char *pV = 0;
  36972. int rc = -1;
  36973. int i, nx, pc, op;
  36974. void *pTmpSpace;
  36975. /* Allocate the Bitvec to be tested and a linear array of
  36976. ** bits to act as the reference */
  36977. pBitvec = sqlite3BitvecCreate( sz );
  36978. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  36979. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  36980. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  36981. /* NULL pBitvec tests */
  36982. sqlite3BitvecSet(0, 1);
  36983. sqlite3BitvecClear(0, 1, pTmpSpace);
  36984. /* Run the program */
  36985. pc = 0;
  36986. while( (op = aOp[pc])!=0 ){
  36987. switch( op ){
  36988. case 1:
  36989. case 2:
  36990. case 5: {
  36991. nx = 4;
  36992. i = aOp[pc+2] - 1;
  36993. aOp[pc+2] += aOp[pc+3];
  36994. break;
  36995. }
  36996. case 3:
  36997. case 4:
  36998. default: {
  36999. nx = 2;
  37000. sqlite3_randomness(sizeof(i), &i);
  37001. break;
  37002. }
  37003. }
  37004. if( (--aOp[pc+1]) > 0 ) nx = 0;
  37005. pc += nx;
  37006. i = (i & 0x7fffffff)%sz;
  37007. if( (op & 1)!=0 ){
  37008. SETBIT(pV, (i+1));
  37009. if( op!=5 ){
  37010. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  37011. }
  37012. }else{
  37013. CLEARBIT(pV, (i+1));
  37014. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  37015. }
  37016. }
  37017. /* Test to make sure the linear array exactly matches the
  37018. ** Bitvec object. Start with the assumption that they do
  37019. ** match (rc==0). Change rc to non-zero if a discrepancy
  37020. ** is found.
  37021. */
  37022. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  37023. + sqlite3BitvecTest(pBitvec, 0)
  37024. + (sqlite3BitvecSize(pBitvec) - sz);
  37025. for(i=1; i<=sz; i++){
  37026. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  37027. rc = i;
  37028. break;
  37029. }
  37030. }
  37031. /* Free allocated structure */
  37032. bitvec_end:
  37033. sqlite3_free(pTmpSpace);
  37034. sqlite3_free(pV);
  37035. sqlite3BitvecDestroy(pBitvec);
  37036. return rc;
  37037. }
  37038. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  37039. /************** End of bitvec.c **********************************************/
  37040. /************** Begin file pcache.c ******************************************/
  37041. /*
  37042. ** 2008 August 05
  37043. **
  37044. ** The author disclaims copyright to this source code. In place of
  37045. ** a legal notice, here is a blessing:
  37046. **
  37047. ** May you do good and not evil.
  37048. ** May you find forgiveness for yourself and forgive others.
  37049. ** May you share freely, never taking more than you give.
  37050. **
  37051. *************************************************************************
  37052. ** This file implements that page cache.
  37053. */
  37054. /*
  37055. ** A complete page cache is an instance of this structure.
  37056. */
  37057. struct PCache {
  37058. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  37059. PgHdr *pSynced; /* Last synced page in dirty page list */
  37060. int nRef; /* Number of referenced pages */
  37061. int szCache; /* Configured cache size */
  37062. int szPage; /* Size of every page in this cache */
  37063. int szExtra; /* Size of extra space for each page */
  37064. int bPurgeable; /* True if pages are on backing store */
  37065. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  37066. void *pStress; /* Argument to xStress */
  37067. sqlite3_pcache *pCache; /* Pluggable cache module */
  37068. PgHdr *pPage1; /* Reference to page 1 */
  37069. };
  37070. /*
  37071. ** Some of the assert() macros in this code are too expensive to run
  37072. ** even during normal debugging. Use them only rarely on long-running
  37073. ** tests. Enable the expensive asserts using the
  37074. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  37075. */
  37076. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  37077. # define expensive_assert(X) assert(X)
  37078. #else
  37079. # define expensive_assert(X)
  37080. #endif
  37081. /********************************** Linked List Management ********************/
  37082. #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
  37083. /*
  37084. ** Check that the pCache->pSynced variable is set correctly. If it
  37085. ** is not, either fail an assert or return zero. Otherwise, return
  37086. ** non-zero. This is only used in debugging builds, as follows:
  37087. **
  37088. ** expensive_assert( pcacheCheckSynced(pCache) );
  37089. */
  37090. static int pcacheCheckSynced(PCache *pCache){
  37091. PgHdr *p;
  37092. for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
  37093. assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
  37094. }
  37095. return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
  37096. }
  37097. #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
  37098. /*
  37099. ** Remove page pPage from the list of dirty pages.
  37100. */
  37101. static void pcacheRemoveFromDirtyList(PgHdr *pPage){
  37102. PCache *p = pPage->pCache;
  37103. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  37104. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  37105. /* Update the PCache1.pSynced variable if necessary. */
  37106. if( p->pSynced==pPage ){
  37107. PgHdr *pSynced = pPage->pDirtyPrev;
  37108. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  37109. pSynced = pSynced->pDirtyPrev;
  37110. }
  37111. p->pSynced = pSynced;
  37112. }
  37113. if( pPage->pDirtyNext ){
  37114. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  37115. }else{
  37116. assert( pPage==p->pDirtyTail );
  37117. p->pDirtyTail = pPage->pDirtyPrev;
  37118. }
  37119. if( pPage->pDirtyPrev ){
  37120. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  37121. }else{
  37122. assert( pPage==p->pDirty );
  37123. p->pDirty = pPage->pDirtyNext;
  37124. }
  37125. pPage->pDirtyNext = 0;
  37126. pPage->pDirtyPrev = 0;
  37127. expensive_assert( pcacheCheckSynced(p) );
  37128. }
  37129. /*
  37130. ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
  37131. ** pPage).
  37132. */
  37133. static void pcacheAddToDirtyList(PgHdr *pPage){
  37134. PCache *p = pPage->pCache;
  37135. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  37136. pPage->pDirtyNext = p->pDirty;
  37137. if( pPage->pDirtyNext ){
  37138. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  37139. pPage->pDirtyNext->pDirtyPrev = pPage;
  37140. }
  37141. p->pDirty = pPage;
  37142. if( !p->pDirtyTail ){
  37143. p->pDirtyTail = pPage;
  37144. }
  37145. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  37146. p->pSynced = pPage;
  37147. }
  37148. expensive_assert( pcacheCheckSynced(p) );
  37149. }
  37150. /*
  37151. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  37152. ** being used for an in-memory database, this function is a no-op.
  37153. */
  37154. static void pcacheUnpin(PgHdr *p){
  37155. PCache *pCache = p->pCache;
  37156. if( pCache->bPurgeable ){
  37157. if( p->pgno==1 ){
  37158. pCache->pPage1 = 0;
  37159. }
  37160. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 0);
  37161. }
  37162. }
  37163. /*************************************************** General Interfaces ******
  37164. **
  37165. ** Initialize and shutdown the page cache subsystem. Neither of these
  37166. ** functions are threadsafe.
  37167. */
  37168. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  37169. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  37170. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  37171. ** built-in default page cache is used instead of the application defined
  37172. ** page cache. */
  37173. sqlite3PCacheSetDefault();
  37174. }
  37175. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  37176. }
  37177. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  37178. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  37179. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  37180. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  37181. }
  37182. }
  37183. /*
  37184. ** Return the size in bytes of a PCache object.
  37185. */
  37186. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  37187. /*
  37188. ** Create a new PCache object. Storage space to hold the object
  37189. ** has already been allocated and is passed in as the p pointer.
  37190. ** The caller discovers how much space needs to be allocated by
  37191. ** calling sqlite3PcacheSize().
  37192. */
  37193. SQLITE_PRIVATE void sqlite3PcacheOpen(
  37194. int szPage, /* Size of every page */
  37195. int szExtra, /* Extra space associated with each page */
  37196. int bPurgeable, /* True if pages are on backing store */
  37197. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  37198. void *pStress, /* Argument to xStress */
  37199. PCache *p /* Preallocated space for the PCache */
  37200. ){
  37201. memset(p, 0, sizeof(PCache));
  37202. p->szPage = szPage;
  37203. p->szExtra = szExtra;
  37204. p->bPurgeable = bPurgeable;
  37205. p->xStress = xStress;
  37206. p->pStress = pStress;
  37207. p->szCache = 100;
  37208. }
  37209. /*
  37210. ** Change the page size for PCache object. The caller must ensure that there
  37211. ** are no outstanding page references when this function is called.
  37212. */
  37213. SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  37214. assert( pCache->nRef==0 && pCache->pDirty==0 );
  37215. if( pCache->pCache ){
  37216. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37217. pCache->pCache = 0;
  37218. pCache->pPage1 = 0;
  37219. }
  37220. pCache->szPage = szPage;
  37221. }
  37222. /*
  37223. ** Compute the number of pages of cache requested.
  37224. */
  37225. static int numberOfCachePages(PCache *p){
  37226. if( p->szCache>=0 ){
  37227. return p->szCache;
  37228. }else{
  37229. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  37230. }
  37231. }
  37232. /*
  37233. ** Try to obtain a page from the cache.
  37234. */
  37235. SQLITE_PRIVATE int sqlite3PcacheFetch(
  37236. PCache *pCache, /* Obtain the page from this cache */
  37237. Pgno pgno, /* Page number to obtain */
  37238. int createFlag, /* If true, create page if it does not exist already */
  37239. PgHdr **ppPage /* Write the page here */
  37240. ){
  37241. sqlite3_pcache_page *pPage = 0;
  37242. PgHdr *pPgHdr = 0;
  37243. int eCreate;
  37244. assert( pCache!=0 );
  37245. assert( createFlag==1 || createFlag==0 );
  37246. assert( pgno>0 );
  37247. /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
  37248. ** allocate it now.
  37249. */
  37250. if( !pCache->pCache && createFlag ){
  37251. sqlite3_pcache *p;
  37252. p = sqlite3GlobalConfig.pcache2.xCreate(
  37253. pCache->szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  37254. );
  37255. if( !p ){
  37256. return SQLITE_NOMEM;
  37257. }
  37258. sqlite3GlobalConfig.pcache2.xCachesize(p, numberOfCachePages(pCache));
  37259. pCache->pCache = p;
  37260. }
  37261. eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
  37262. if( pCache->pCache ){
  37263. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  37264. }
  37265. if( !pPage && eCreate==1 ){
  37266. PgHdr *pPg;
  37267. /* Find a dirty page to write-out and recycle. First try to find a
  37268. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  37269. ** cleared), but if that is not possible settle for any other
  37270. ** unreferenced dirty page.
  37271. */
  37272. expensive_assert( pcacheCheckSynced(pCache) );
  37273. for(pPg=pCache->pSynced;
  37274. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  37275. pPg=pPg->pDirtyPrev
  37276. );
  37277. pCache->pSynced = pPg;
  37278. if( !pPg ){
  37279. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  37280. }
  37281. if( pPg ){
  37282. int rc;
  37283. #ifdef SQLITE_LOG_CACHE_SPILL
  37284. sqlite3_log(SQLITE_FULL,
  37285. "spill page %d making room for %d - cache used: %d/%d",
  37286. pPg->pgno, pgno,
  37287. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  37288. numberOfCachePages(pCache));
  37289. #endif
  37290. rc = pCache->xStress(pCache->pStress, pPg);
  37291. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  37292. return rc;
  37293. }
  37294. }
  37295. pPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  37296. }
  37297. if( pPage ){
  37298. pPgHdr = (PgHdr *)pPage->pExtra;
  37299. if( !pPgHdr->pPage ){
  37300. memset(pPgHdr, 0, sizeof(PgHdr));
  37301. pPgHdr->pPage = pPage;
  37302. pPgHdr->pData = pPage->pBuf;
  37303. pPgHdr->pExtra = (void *)&pPgHdr[1];
  37304. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  37305. pPgHdr->pCache = pCache;
  37306. pPgHdr->pgno = pgno;
  37307. }
  37308. assert( pPgHdr->pCache==pCache );
  37309. assert( pPgHdr->pgno==pgno );
  37310. assert( pPgHdr->pData==pPage->pBuf );
  37311. assert( pPgHdr->pExtra==(void *)&pPgHdr[1] );
  37312. if( 0==pPgHdr->nRef ){
  37313. pCache->nRef++;
  37314. }
  37315. pPgHdr->nRef++;
  37316. if( pgno==1 ){
  37317. pCache->pPage1 = pPgHdr;
  37318. }
  37319. }
  37320. *ppPage = pPgHdr;
  37321. return (pPgHdr==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
  37322. }
  37323. /*
  37324. ** Decrement the reference count on a page. If the page is clean and the
  37325. ** reference count drops to 0, then it is made elible for recycling.
  37326. */
  37327. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
  37328. assert( p->nRef>0 );
  37329. p->nRef--;
  37330. if( p->nRef==0 ){
  37331. PCache *pCache = p->pCache;
  37332. pCache->nRef--;
  37333. if( (p->flags&PGHDR_DIRTY)==0 ){
  37334. pcacheUnpin(p);
  37335. }else{
  37336. /* Move the page to the head of the dirty list. */
  37337. pcacheRemoveFromDirtyList(p);
  37338. pcacheAddToDirtyList(p);
  37339. }
  37340. }
  37341. }
  37342. /*
  37343. ** Increase the reference count of a supplied page by 1.
  37344. */
  37345. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  37346. assert(p->nRef>0);
  37347. p->nRef++;
  37348. }
  37349. /*
  37350. ** Drop a page from the cache. There must be exactly one reference to the
  37351. ** page. This function deletes that reference, so after it returns the
  37352. ** page pointed to by p is invalid.
  37353. */
  37354. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  37355. PCache *pCache;
  37356. assert( p->nRef==1 );
  37357. if( p->flags&PGHDR_DIRTY ){
  37358. pcacheRemoveFromDirtyList(p);
  37359. }
  37360. pCache = p->pCache;
  37361. pCache->nRef--;
  37362. if( p->pgno==1 ){
  37363. pCache->pPage1 = 0;
  37364. }
  37365. sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, p->pPage, 1);
  37366. }
  37367. /*
  37368. ** Make sure the page is marked as dirty. If it isn't dirty already,
  37369. ** make it so.
  37370. */
  37371. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  37372. p->flags &= ~PGHDR_DONT_WRITE;
  37373. assert( p->nRef>0 );
  37374. if( 0==(p->flags & PGHDR_DIRTY) ){
  37375. p->flags |= PGHDR_DIRTY;
  37376. pcacheAddToDirtyList( p);
  37377. }
  37378. }
  37379. /*
  37380. ** Make sure the page is marked as clean. If it isn't clean already,
  37381. ** make it so.
  37382. */
  37383. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  37384. if( (p->flags & PGHDR_DIRTY) ){
  37385. pcacheRemoveFromDirtyList(p);
  37386. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  37387. if( p->nRef==0 ){
  37388. pcacheUnpin(p);
  37389. }
  37390. }
  37391. }
  37392. /*
  37393. ** Make every page in the cache clean.
  37394. */
  37395. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  37396. PgHdr *p;
  37397. while( (p = pCache->pDirty)!=0 ){
  37398. sqlite3PcacheMakeClean(p);
  37399. }
  37400. }
  37401. /*
  37402. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  37403. */
  37404. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  37405. PgHdr *p;
  37406. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37407. p->flags &= ~PGHDR_NEED_SYNC;
  37408. }
  37409. pCache->pSynced = pCache->pDirtyTail;
  37410. }
  37411. /*
  37412. ** Change the page number of page p to newPgno.
  37413. */
  37414. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  37415. PCache *pCache = p->pCache;
  37416. assert( p->nRef>0 );
  37417. assert( newPgno>0 );
  37418. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  37419. p->pgno = newPgno;
  37420. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  37421. pcacheRemoveFromDirtyList(p);
  37422. pcacheAddToDirtyList(p);
  37423. }
  37424. }
  37425. /*
  37426. ** Drop every cache entry whose page number is greater than "pgno". The
  37427. ** caller must ensure that there are no outstanding references to any pages
  37428. ** other than page 1 with a page number greater than pgno.
  37429. **
  37430. ** If there is a reference to page 1 and the pgno parameter passed to this
  37431. ** function is 0, then the data area associated with page 1 is zeroed, but
  37432. ** the page object is not dropped.
  37433. */
  37434. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  37435. if( pCache->pCache ){
  37436. PgHdr *p;
  37437. PgHdr *pNext;
  37438. for(p=pCache->pDirty; p; p=pNext){
  37439. pNext = p->pDirtyNext;
  37440. /* This routine never gets call with a positive pgno except right
  37441. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  37442. ** it must be that pgno==0.
  37443. */
  37444. assert( p->pgno>0 );
  37445. if( ALWAYS(p->pgno>pgno) ){
  37446. assert( p->flags&PGHDR_DIRTY );
  37447. sqlite3PcacheMakeClean(p);
  37448. }
  37449. }
  37450. if( pgno==0 && pCache->pPage1 ){
  37451. memset(pCache->pPage1->pData, 0, pCache->szPage);
  37452. pgno = 1;
  37453. }
  37454. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  37455. }
  37456. }
  37457. /*
  37458. ** Close a cache.
  37459. */
  37460. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  37461. if( pCache->pCache ){
  37462. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  37463. }
  37464. }
  37465. /*
  37466. ** Discard the contents of the cache.
  37467. */
  37468. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  37469. sqlite3PcacheTruncate(pCache, 0);
  37470. }
  37471. /*
  37472. ** Merge two lists of pages connected by pDirty and in pgno order.
  37473. ** Do not both fixing the pDirtyPrev pointers.
  37474. */
  37475. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  37476. PgHdr result, *pTail;
  37477. pTail = &result;
  37478. while( pA && pB ){
  37479. if( pA->pgno<pB->pgno ){
  37480. pTail->pDirty = pA;
  37481. pTail = pA;
  37482. pA = pA->pDirty;
  37483. }else{
  37484. pTail->pDirty = pB;
  37485. pTail = pB;
  37486. pB = pB->pDirty;
  37487. }
  37488. }
  37489. if( pA ){
  37490. pTail->pDirty = pA;
  37491. }else if( pB ){
  37492. pTail->pDirty = pB;
  37493. }else{
  37494. pTail->pDirty = 0;
  37495. }
  37496. return result.pDirty;
  37497. }
  37498. /*
  37499. ** Sort the list of pages in accending order by pgno. Pages are
  37500. ** connected by pDirty pointers. The pDirtyPrev pointers are
  37501. ** corrupted by this sort.
  37502. **
  37503. ** Since there cannot be more than 2^31 distinct pages in a database,
  37504. ** there cannot be more than 31 buckets required by the merge sorter.
  37505. ** One extra bucket is added to catch overflow in case something
  37506. ** ever changes to make the previous sentence incorrect.
  37507. */
  37508. #define N_SORT_BUCKET 32
  37509. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  37510. PgHdr *a[N_SORT_BUCKET], *p;
  37511. int i;
  37512. memset(a, 0, sizeof(a));
  37513. while( pIn ){
  37514. p = pIn;
  37515. pIn = p->pDirty;
  37516. p->pDirty = 0;
  37517. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  37518. if( a[i]==0 ){
  37519. a[i] = p;
  37520. break;
  37521. }else{
  37522. p = pcacheMergeDirtyList(a[i], p);
  37523. a[i] = 0;
  37524. }
  37525. }
  37526. if( NEVER(i==N_SORT_BUCKET-1) ){
  37527. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  37528. ** the input list. But that is impossible.
  37529. */
  37530. a[i] = pcacheMergeDirtyList(a[i], p);
  37531. }
  37532. }
  37533. p = a[0];
  37534. for(i=1; i<N_SORT_BUCKET; i++){
  37535. p = pcacheMergeDirtyList(p, a[i]);
  37536. }
  37537. return p;
  37538. }
  37539. /*
  37540. ** Return a list of all dirty pages in the cache, sorted by page number.
  37541. */
  37542. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  37543. PgHdr *p;
  37544. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  37545. p->pDirty = p->pDirtyNext;
  37546. }
  37547. return pcacheSortDirtyList(pCache->pDirty);
  37548. }
  37549. /*
  37550. ** Return the total number of referenced pages held by the cache.
  37551. */
  37552. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  37553. return pCache->nRef;
  37554. }
  37555. /*
  37556. ** Return the number of references to the page supplied as an argument.
  37557. */
  37558. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  37559. return p->nRef;
  37560. }
  37561. /*
  37562. ** Return the total number of pages in the cache.
  37563. */
  37564. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  37565. int nPage = 0;
  37566. if( pCache->pCache ){
  37567. nPage = sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  37568. }
  37569. return nPage;
  37570. }
  37571. #ifdef SQLITE_TEST
  37572. /*
  37573. ** Get the suggested cache-size value.
  37574. */
  37575. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  37576. return numberOfCachePages(pCache);
  37577. }
  37578. #endif
  37579. /*
  37580. ** Set the suggested cache-size value.
  37581. */
  37582. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  37583. pCache->szCache = mxPage;
  37584. if( pCache->pCache ){
  37585. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  37586. numberOfCachePages(pCache));
  37587. }
  37588. }
  37589. /*
  37590. ** Free up as much memory as possible from the page cache.
  37591. */
  37592. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  37593. if( pCache->pCache ){
  37594. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  37595. }
  37596. }
  37597. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  37598. /*
  37599. ** For all dirty pages currently in the cache, invoke the specified
  37600. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  37601. ** defined.
  37602. */
  37603. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  37604. PgHdr *pDirty;
  37605. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  37606. xIter(pDirty);
  37607. }
  37608. }
  37609. #endif
  37610. /************** End of pcache.c **********************************************/
  37611. /************** Begin file pcache1.c *****************************************/
  37612. /*
  37613. ** 2008 November 05
  37614. **
  37615. ** The author disclaims copyright to this source code. In place of
  37616. ** a legal notice, here is a blessing:
  37617. **
  37618. ** May you do good and not evil.
  37619. ** May you find forgiveness for yourself and forgive others.
  37620. ** May you share freely, never taking more than you give.
  37621. **
  37622. *************************************************************************
  37623. **
  37624. ** This file implements the default page cache implementation (the
  37625. ** sqlite3_pcache interface). It also contains part of the implementation
  37626. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  37627. ** If the default page cache implementation is overriden, then neither of
  37628. ** these two features are available.
  37629. */
  37630. typedef struct PCache1 PCache1;
  37631. typedef struct PgHdr1 PgHdr1;
  37632. typedef struct PgFreeslot PgFreeslot;
  37633. typedef struct PGroup PGroup;
  37634. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  37635. ** of one or more PCaches that are able to recycle each others unpinned
  37636. ** pages when they are under memory pressure. A PGroup is an instance of
  37637. ** the following object.
  37638. **
  37639. ** This page cache implementation works in one of two modes:
  37640. **
  37641. ** (1) Every PCache is the sole member of its own PGroup. There is
  37642. ** one PGroup per PCache.
  37643. **
  37644. ** (2) There is a single global PGroup that all PCaches are a member
  37645. ** of.
  37646. **
  37647. ** Mode 1 uses more memory (since PCache instances are not able to rob
  37648. ** unused pages from other PCaches) but it also operates without a mutex,
  37649. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  37650. ** threadsafe, but recycles pages more efficiently.
  37651. **
  37652. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  37653. ** PGroup which is the pcache1.grp global variable and its mutex is
  37654. ** SQLITE_MUTEX_STATIC_LRU.
  37655. */
  37656. struct PGroup {
  37657. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  37658. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  37659. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  37660. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  37661. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  37662. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  37663. };
  37664. /* Each page cache is an instance of the following object. Every
  37665. ** open database file (including each in-memory database and each
  37666. ** temporary or transient database) has a single page cache which
  37667. ** is an instance of this object.
  37668. **
  37669. ** Pointers to structures of this type are cast and returned as
  37670. ** opaque sqlite3_pcache* handles.
  37671. */
  37672. struct PCache1 {
  37673. /* Cache configuration parameters. Page size (szPage) and the purgeable
  37674. ** flag (bPurgeable) are set when the cache is created. nMax may be
  37675. ** modified at any time by a call to the pcache1Cachesize() method.
  37676. ** The PGroup mutex must be held when accessing nMax.
  37677. */
  37678. PGroup *pGroup; /* PGroup this cache belongs to */
  37679. int szPage; /* Size of allocated pages in bytes */
  37680. int szExtra; /* Size of extra space in bytes */
  37681. int bPurgeable; /* True if cache is purgeable */
  37682. unsigned int nMin; /* Minimum number of pages reserved */
  37683. unsigned int nMax; /* Configured "cache_size" value */
  37684. unsigned int n90pct; /* nMax*9/10 */
  37685. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  37686. /* Hash table of all pages. The following variables may only be accessed
  37687. ** when the accessor is holding the PGroup mutex.
  37688. */
  37689. unsigned int nRecyclable; /* Number of pages in the LRU list */
  37690. unsigned int nPage; /* Total number of pages in apHash */
  37691. unsigned int nHash; /* Number of slots in apHash[] */
  37692. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  37693. };
  37694. /*
  37695. ** Each cache entry is represented by an instance of the following
  37696. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  37697. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  37698. ** in memory.
  37699. */
  37700. struct PgHdr1 {
  37701. sqlite3_pcache_page page;
  37702. unsigned int iKey; /* Key value (page number) */
  37703. PgHdr1 *pNext; /* Next in hash table chain */
  37704. PCache1 *pCache; /* Cache that currently owns this page */
  37705. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  37706. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  37707. };
  37708. /*
  37709. ** Free slots in the allocator used to divide up the buffer provided using
  37710. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  37711. */
  37712. struct PgFreeslot {
  37713. PgFreeslot *pNext; /* Next free slot */
  37714. };
  37715. /*
  37716. ** Global data used by this cache.
  37717. */
  37718. static SQLITE_WSD struct PCacheGlobal {
  37719. PGroup grp; /* The global PGroup for mode (2) */
  37720. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  37721. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  37722. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  37723. ** The nFreeSlot and pFree values do require mutex protection.
  37724. */
  37725. int isInit; /* True if initialized */
  37726. int szSlot; /* Size of each free slot */
  37727. int nSlot; /* The number of pcache slots */
  37728. int nReserve; /* Try to keep nFreeSlot above this */
  37729. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  37730. /* Above requires no mutex. Use mutex below for variable that follow. */
  37731. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  37732. PgFreeslot *pFree; /* Free page blocks */
  37733. int nFreeSlot; /* Number of unused pcache slots */
  37734. /* The following value requires a mutex to change. We skip the mutex on
  37735. ** reading because (1) most platforms read a 32-bit integer atomically and
  37736. ** (2) even if an incorrect value is read, no great harm is done since this
  37737. ** is really just an optimization. */
  37738. int bUnderPressure; /* True if low on PAGECACHE memory */
  37739. } pcache1_g;
  37740. /*
  37741. ** All code in this file should access the global structure above via the
  37742. ** alias "pcache1". This ensures that the WSD emulation is used when
  37743. ** compiling for systems that do not support real WSD.
  37744. */
  37745. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  37746. /*
  37747. ** Macros to enter and leave the PCache LRU mutex.
  37748. */
  37749. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  37750. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  37751. /******************************************************************************/
  37752. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  37753. /*
  37754. ** This function is called during initialization if a static buffer is
  37755. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  37756. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  37757. ** enough to contain 'n' buffers of 'sz' bytes each.
  37758. **
  37759. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  37760. ** to be serialized already. There is no need for further mutexing.
  37761. */
  37762. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  37763. if( pcache1.isInit ){
  37764. PgFreeslot *p;
  37765. sz = ROUNDDOWN8(sz);
  37766. pcache1.szSlot = sz;
  37767. pcache1.nSlot = pcache1.nFreeSlot = n;
  37768. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  37769. pcache1.pStart = pBuf;
  37770. pcache1.pFree = 0;
  37771. pcache1.bUnderPressure = 0;
  37772. while( n-- ){
  37773. p = (PgFreeslot*)pBuf;
  37774. p->pNext = pcache1.pFree;
  37775. pcache1.pFree = p;
  37776. pBuf = (void*)&((char*)pBuf)[sz];
  37777. }
  37778. pcache1.pEnd = pBuf;
  37779. }
  37780. }
  37781. /*
  37782. ** Malloc function used within this file to allocate space from the buffer
  37783. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  37784. ** such buffer exists or there is no space left in it, this function falls
  37785. ** back to sqlite3Malloc().
  37786. **
  37787. ** Multiple threads can run this routine at the same time. Global variables
  37788. ** in pcache1 need to be protected via mutex.
  37789. */
  37790. static void *pcache1Alloc(int nByte){
  37791. void *p = 0;
  37792. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  37793. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  37794. if( nByte<=pcache1.szSlot ){
  37795. sqlite3_mutex_enter(pcache1.mutex);
  37796. p = (PgHdr1 *)pcache1.pFree;
  37797. if( p ){
  37798. pcache1.pFree = pcache1.pFree->pNext;
  37799. pcache1.nFreeSlot--;
  37800. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37801. assert( pcache1.nFreeSlot>=0 );
  37802. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  37803. }
  37804. sqlite3_mutex_leave(pcache1.mutex);
  37805. }
  37806. if( p==0 ){
  37807. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  37808. ** it from sqlite3Malloc instead.
  37809. */
  37810. p = sqlite3Malloc(nByte);
  37811. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37812. if( p ){
  37813. int sz = sqlite3MallocSize(p);
  37814. sqlite3_mutex_enter(pcache1.mutex);
  37815. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  37816. sqlite3_mutex_leave(pcache1.mutex);
  37817. }
  37818. #endif
  37819. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37820. }
  37821. return p;
  37822. }
  37823. /*
  37824. ** Free an allocated buffer obtained from pcache1Alloc().
  37825. */
  37826. static int pcache1Free(void *p){
  37827. int nFreed = 0;
  37828. if( p==0 ) return 0;
  37829. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37830. PgFreeslot *pSlot;
  37831. sqlite3_mutex_enter(pcache1.mutex);
  37832. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  37833. pSlot = (PgFreeslot*)p;
  37834. pSlot->pNext = pcache1.pFree;
  37835. pcache1.pFree = pSlot;
  37836. pcache1.nFreeSlot++;
  37837. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  37838. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  37839. sqlite3_mutex_leave(pcache1.mutex);
  37840. }else{
  37841. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37842. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37843. nFreed = sqlite3MallocSize(p);
  37844. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  37845. sqlite3_mutex_enter(pcache1.mutex);
  37846. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  37847. sqlite3_mutex_leave(pcache1.mutex);
  37848. #endif
  37849. sqlite3_free(p);
  37850. }
  37851. return nFreed;
  37852. }
  37853. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  37854. /*
  37855. ** Return the size of a pcache allocation
  37856. */
  37857. static int pcache1MemSize(void *p){
  37858. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  37859. return pcache1.szSlot;
  37860. }else{
  37861. int iSize;
  37862. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  37863. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  37864. iSize = sqlite3MallocSize(p);
  37865. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  37866. return iSize;
  37867. }
  37868. }
  37869. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  37870. /*
  37871. ** Allocate a new page object initially associated with cache pCache.
  37872. */
  37873. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  37874. PgHdr1 *p = 0;
  37875. void *pPg;
  37876. /* The group mutex must be released before pcache1Alloc() is called. This
  37877. ** is because it may call sqlite3_release_memory(), which assumes that
  37878. ** this mutex is not held. */
  37879. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37880. pcache1LeaveMutex(pCache->pGroup);
  37881. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37882. pPg = pcache1Alloc(pCache->szPage);
  37883. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  37884. if( !pPg || !p ){
  37885. pcache1Free(pPg);
  37886. sqlite3_free(p);
  37887. pPg = 0;
  37888. }
  37889. #else
  37890. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  37891. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  37892. #endif
  37893. pcache1EnterMutex(pCache->pGroup);
  37894. if( pPg ){
  37895. p->page.pBuf = pPg;
  37896. p->page.pExtra = &p[1];
  37897. if( pCache->bPurgeable ){
  37898. pCache->pGroup->nCurrentPage++;
  37899. }
  37900. return p;
  37901. }
  37902. return 0;
  37903. }
  37904. /*
  37905. ** Free a page object allocated by pcache1AllocPage().
  37906. **
  37907. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  37908. ** that the current implementation happens to never call this routine
  37909. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  37910. */
  37911. static void pcache1FreePage(PgHdr1 *p){
  37912. if( ALWAYS(p) ){
  37913. PCache1 *pCache = p->pCache;
  37914. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  37915. pcache1Free(p->page.pBuf);
  37916. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37917. sqlite3_free(p);
  37918. #endif
  37919. if( pCache->bPurgeable ){
  37920. pCache->pGroup->nCurrentPage--;
  37921. }
  37922. }
  37923. }
  37924. /*
  37925. ** Malloc function used by SQLite to obtain space from the buffer configured
  37926. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  37927. ** exists, this function falls back to sqlite3Malloc().
  37928. */
  37929. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  37930. return pcache1Alloc(sz);
  37931. }
  37932. /*
  37933. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  37934. */
  37935. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  37936. pcache1Free(p);
  37937. }
  37938. /*
  37939. ** Return true if it desirable to avoid allocating a new page cache
  37940. ** entry.
  37941. **
  37942. ** If memory was allocated specifically to the page cache using
  37943. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  37944. ** it is desirable to avoid allocating a new page cache entry because
  37945. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  37946. ** for all page cache needs and we should not need to spill the
  37947. ** allocation onto the heap.
  37948. **
  37949. ** Or, the heap is used for all page cache memory but the heap is
  37950. ** under memory pressure, then again it is desirable to avoid
  37951. ** allocating a new page cache entry in order to avoid stressing
  37952. ** the heap even further.
  37953. */
  37954. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  37955. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  37956. return pcache1.bUnderPressure;
  37957. }else{
  37958. return sqlite3HeapNearlyFull();
  37959. }
  37960. }
  37961. /******************************************************************************/
  37962. /******** General Implementation Functions ************************************/
  37963. /*
  37964. ** This function is used to resize the hash table used by the cache passed
  37965. ** as the first argument.
  37966. **
  37967. ** The PCache mutex must be held when this function is called.
  37968. */
  37969. static int pcache1ResizeHash(PCache1 *p){
  37970. PgHdr1 **apNew;
  37971. unsigned int nNew;
  37972. unsigned int i;
  37973. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  37974. nNew = p->nHash*2;
  37975. if( nNew<256 ){
  37976. nNew = 256;
  37977. }
  37978. pcache1LeaveMutex(p->pGroup);
  37979. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  37980. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  37981. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  37982. pcache1EnterMutex(p->pGroup);
  37983. if( apNew ){
  37984. for(i=0; i<p->nHash; i++){
  37985. PgHdr1 *pPage;
  37986. PgHdr1 *pNext = p->apHash[i];
  37987. while( (pPage = pNext)!=0 ){
  37988. unsigned int h = pPage->iKey % nNew;
  37989. pNext = pPage->pNext;
  37990. pPage->pNext = apNew[h];
  37991. apNew[h] = pPage;
  37992. }
  37993. }
  37994. sqlite3_free(p->apHash);
  37995. p->apHash = apNew;
  37996. p->nHash = nNew;
  37997. }
  37998. return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
  37999. }
  38000. /*
  38001. ** This function is used internally to remove the page pPage from the
  38002. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  38003. ** LRU list, then this function is a no-op.
  38004. **
  38005. ** The PGroup mutex must be held when this function is called.
  38006. **
  38007. ** If pPage is NULL then this routine is a no-op.
  38008. */
  38009. static void pcache1PinPage(PgHdr1 *pPage){
  38010. PCache1 *pCache;
  38011. PGroup *pGroup;
  38012. if( pPage==0 ) return;
  38013. pCache = pPage->pCache;
  38014. pGroup = pCache->pGroup;
  38015. assert( sqlite3_mutex_held(pGroup->mutex) );
  38016. if( pPage->pLruNext || pPage==pGroup->pLruTail ){
  38017. if( pPage->pLruPrev ){
  38018. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  38019. }
  38020. if( pPage->pLruNext ){
  38021. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  38022. }
  38023. if( pGroup->pLruHead==pPage ){
  38024. pGroup->pLruHead = pPage->pLruNext;
  38025. }
  38026. if( pGroup->pLruTail==pPage ){
  38027. pGroup->pLruTail = pPage->pLruPrev;
  38028. }
  38029. pPage->pLruNext = 0;
  38030. pPage->pLruPrev = 0;
  38031. pPage->pCache->nRecyclable--;
  38032. }
  38033. }
  38034. /*
  38035. ** Remove the page supplied as an argument from the hash table
  38036. ** (PCache1.apHash structure) that it is currently stored in.
  38037. **
  38038. ** The PGroup mutex must be held when this function is called.
  38039. */
  38040. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  38041. unsigned int h;
  38042. PCache1 *pCache = pPage->pCache;
  38043. PgHdr1 **pp;
  38044. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38045. h = pPage->iKey % pCache->nHash;
  38046. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  38047. *pp = (*pp)->pNext;
  38048. pCache->nPage--;
  38049. }
  38050. /*
  38051. ** If there are currently more than nMaxPage pages allocated, try
  38052. ** to recycle pages to reduce the number allocated to nMaxPage.
  38053. */
  38054. static void pcache1EnforceMaxPage(PGroup *pGroup){
  38055. assert( sqlite3_mutex_held(pGroup->mutex) );
  38056. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  38057. PgHdr1 *p = pGroup->pLruTail;
  38058. assert( p->pCache->pGroup==pGroup );
  38059. pcache1PinPage(p);
  38060. pcache1RemoveFromHash(p);
  38061. pcache1FreePage(p);
  38062. }
  38063. }
  38064. /*
  38065. ** Discard all pages from cache pCache with a page number (key value)
  38066. ** greater than or equal to iLimit. Any pinned pages that meet this
  38067. ** criteria are unpinned before they are discarded.
  38068. **
  38069. ** The PCache mutex must be held when this function is called.
  38070. */
  38071. static void pcache1TruncateUnsafe(
  38072. PCache1 *pCache, /* The cache to truncate */
  38073. unsigned int iLimit /* Drop pages with this pgno or larger */
  38074. ){
  38075. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  38076. unsigned int h;
  38077. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  38078. for(h=0; h<pCache->nHash; h++){
  38079. PgHdr1 **pp = &pCache->apHash[h];
  38080. PgHdr1 *pPage;
  38081. while( (pPage = *pp)!=0 ){
  38082. if( pPage->iKey>=iLimit ){
  38083. pCache->nPage--;
  38084. *pp = pPage->pNext;
  38085. pcache1PinPage(pPage);
  38086. pcache1FreePage(pPage);
  38087. }else{
  38088. pp = &pPage->pNext;
  38089. TESTONLY( nPage++; )
  38090. }
  38091. }
  38092. }
  38093. assert( pCache->nPage==nPage );
  38094. }
  38095. /******************************************************************************/
  38096. /******** sqlite3_pcache Methods **********************************************/
  38097. /*
  38098. ** Implementation of the sqlite3_pcache.xInit method.
  38099. */
  38100. static int pcache1Init(void *NotUsed){
  38101. UNUSED_PARAMETER(NotUsed);
  38102. assert( pcache1.isInit==0 );
  38103. memset(&pcache1, 0, sizeof(pcache1));
  38104. if( sqlite3GlobalConfig.bCoreMutex ){
  38105. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  38106. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  38107. }
  38108. pcache1.grp.mxPinned = 10;
  38109. pcache1.isInit = 1;
  38110. return SQLITE_OK;
  38111. }
  38112. /*
  38113. ** Implementation of the sqlite3_pcache.xShutdown method.
  38114. ** Note that the static mutex allocated in xInit does
  38115. ** not need to be freed.
  38116. */
  38117. static void pcache1Shutdown(void *NotUsed){
  38118. UNUSED_PARAMETER(NotUsed);
  38119. assert( pcache1.isInit!=0 );
  38120. memset(&pcache1, 0, sizeof(pcache1));
  38121. }
  38122. /*
  38123. ** Implementation of the sqlite3_pcache.xCreate method.
  38124. **
  38125. ** Allocate a new cache.
  38126. */
  38127. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  38128. PCache1 *pCache; /* The newly created page cache */
  38129. PGroup *pGroup; /* The group the new page cache will belong to */
  38130. int sz; /* Bytes of memory required to allocate the new cache */
  38131. /*
  38132. ** The separateCache variable is true if each PCache has its own private
  38133. ** PGroup. In other words, separateCache is true for mode (1) where no
  38134. ** mutexing is required.
  38135. **
  38136. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  38137. **
  38138. ** * Always use a unified cache in single-threaded applications
  38139. **
  38140. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  38141. ** use separate caches (mode-1)
  38142. */
  38143. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  38144. const int separateCache = 0;
  38145. #else
  38146. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  38147. #endif
  38148. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  38149. assert( szExtra < 300 );
  38150. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  38151. pCache = (PCache1 *)sqlite3MallocZero(sz);
  38152. if( pCache ){
  38153. if( separateCache ){
  38154. pGroup = (PGroup*)&pCache[1];
  38155. pGroup->mxPinned = 10;
  38156. }else{
  38157. pGroup = &pcache1.grp;
  38158. }
  38159. pCache->pGroup = pGroup;
  38160. pCache->szPage = szPage;
  38161. pCache->szExtra = szExtra;
  38162. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  38163. if( bPurgeable ){
  38164. pCache->nMin = 10;
  38165. pcache1EnterMutex(pGroup);
  38166. pGroup->nMinPage += pCache->nMin;
  38167. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38168. pcache1LeaveMutex(pGroup);
  38169. }
  38170. }
  38171. return (sqlite3_pcache *)pCache;
  38172. }
  38173. /*
  38174. ** Implementation of the sqlite3_pcache.xCachesize method.
  38175. **
  38176. ** Configure the cache_size limit for a cache.
  38177. */
  38178. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  38179. PCache1 *pCache = (PCache1 *)p;
  38180. if( pCache->bPurgeable ){
  38181. PGroup *pGroup = pCache->pGroup;
  38182. pcache1EnterMutex(pGroup);
  38183. pGroup->nMaxPage += (nMax - pCache->nMax);
  38184. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38185. pCache->nMax = nMax;
  38186. pCache->n90pct = pCache->nMax*9/10;
  38187. pcache1EnforceMaxPage(pGroup);
  38188. pcache1LeaveMutex(pGroup);
  38189. }
  38190. }
  38191. /*
  38192. ** Implementation of the sqlite3_pcache.xShrink method.
  38193. **
  38194. ** Free up as much memory as possible.
  38195. */
  38196. static void pcache1Shrink(sqlite3_pcache *p){
  38197. PCache1 *pCache = (PCache1*)p;
  38198. if( pCache->bPurgeable ){
  38199. PGroup *pGroup = pCache->pGroup;
  38200. int savedMaxPage;
  38201. pcache1EnterMutex(pGroup);
  38202. savedMaxPage = pGroup->nMaxPage;
  38203. pGroup->nMaxPage = 0;
  38204. pcache1EnforceMaxPage(pGroup);
  38205. pGroup->nMaxPage = savedMaxPage;
  38206. pcache1LeaveMutex(pGroup);
  38207. }
  38208. }
  38209. /*
  38210. ** Implementation of the sqlite3_pcache.xPagecount method.
  38211. */
  38212. static int pcache1Pagecount(sqlite3_pcache *p){
  38213. int n;
  38214. PCache1 *pCache = (PCache1*)p;
  38215. pcache1EnterMutex(pCache->pGroup);
  38216. n = pCache->nPage;
  38217. pcache1LeaveMutex(pCache->pGroup);
  38218. return n;
  38219. }
  38220. /*
  38221. ** Implementation of the sqlite3_pcache.xFetch method.
  38222. **
  38223. ** Fetch a page by key value.
  38224. **
  38225. ** Whether or not a new page may be allocated by this function depends on
  38226. ** the value of the createFlag argument. 0 means do not allocate a new
  38227. ** page. 1 means allocate a new page if space is easily available. 2
  38228. ** means to try really hard to allocate a new page.
  38229. **
  38230. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  38231. ** database) there is really no difference between createFlag 1 and 2. So
  38232. ** the calling function (pcache.c) will never have a createFlag of 1 on
  38233. ** a non-purgeable cache.
  38234. **
  38235. ** There are three different approaches to obtaining space for a page,
  38236. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  38237. **
  38238. ** 1. Regardless of the value of createFlag, the cache is searched for a
  38239. ** copy of the requested page. If one is found, it is returned.
  38240. **
  38241. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  38242. ** returned.
  38243. **
  38244. ** 3. If createFlag is 1, and the page is not already in the cache, then
  38245. ** return NULL (do not allocate a new page) if any of the following
  38246. ** conditions are true:
  38247. **
  38248. ** (a) the number of pages pinned by the cache is greater than
  38249. ** PCache1.nMax, or
  38250. **
  38251. ** (b) the number of pages pinned by the cache is greater than
  38252. ** the sum of nMax for all purgeable caches, less the sum of
  38253. ** nMin for all other purgeable caches, or
  38254. **
  38255. ** 4. If none of the first three conditions apply and the cache is marked
  38256. ** as purgeable, and if one of the following is true:
  38257. **
  38258. ** (a) The number of pages allocated for the cache is already
  38259. ** PCache1.nMax, or
  38260. **
  38261. ** (b) The number of pages allocated for all purgeable caches is
  38262. ** already equal to or greater than the sum of nMax for all
  38263. ** purgeable caches,
  38264. **
  38265. ** (c) The system is under memory pressure and wants to avoid
  38266. ** unnecessary pages cache entry allocations
  38267. **
  38268. ** then attempt to recycle a page from the LRU list. If it is the right
  38269. ** size, return the recycled buffer. Otherwise, free the buffer and
  38270. ** proceed to step 5.
  38271. **
  38272. ** 5. Otherwise, allocate and return a new page buffer.
  38273. */
  38274. static sqlite3_pcache_page *pcache1Fetch(
  38275. sqlite3_pcache *p,
  38276. unsigned int iKey,
  38277. int createFlag
  38278. ){
  38279. unsigned int nPinned;
  38280. PCache1 *pCache = (PCache1 *)p;
  38281. PGroup *pGroup;
  38282. PgHdr1 *pPage = 0;
  38283. assert( pCache->bPurgeable || createFlag!=1 );
  38284. assert( pCache->bPurgeable || pCache->nMin==0 );
  38285. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  38286. assert( pCache->nMin==0 || pCache->bPurgeable );
  38287. pcache1EnterMutex(pGroup = pCache->pGroup);
  38288. /* Step 1: Search the hash table for an existing entry. */
  38289. if( pCache->nHash>0 ){
  38290. unsigned int h = iKey % pCache->nHash;
  38291. for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
  38292. }
  38293. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  38294. if( pPage || createFlag==0 ){
  38295. pcache1PinPage(pPage);
  38296. goto fetch_out;
  38297. }
  38298. /* The pGroup local variable will normally be initialized by the
  38299. ** pcache1EnterMutex() macro above. But if SQLITE_MUTEX_OMIT is defined,
  38300. ** then pcache1EnterMutex() is a no-op, so we have to initialize the
  38301. ** local variable here. Delaying the initialization of pGroup is an
  38302. ** optimization: The common case is to exit the module before reaching
  38303. ** this point.
  38304. */
  38305. #ifdef SQLITE_MUTEX_OMIT
  38306. pGroup = pCache->pGroup;
  38307. #endif
  38308. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  38309. assert( pCache->nPage >= pCache->nRecyclable );
  38310. nPinned = pCache->nPage - pCache->nRecyclable;
  38311. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  38312. assert( pCache->n90pct == pCache->nMax*9/10 );
  38313. if( createFlag==1 && (
  38314. nPinned>=pGroup->mxPinned
  38315. || nPinned>=pCache->n90pct
  38316. || pcache1UnderMemoryPressure(pCache)
  38317. )){
  38318. goto fetch_out;
  38319. }
  38320. if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
  38321. goto fetch_out;
  38322. }
  38323. assert( pCache->nHash>0 && pCache->apHash );
  38324. /* Step 4. Try to recycle a page. */
  38325. if( pCache->bPurgeable && pGroup->pLruTail && (
  38326. (pCache->nPage+1>=pCache->nMax)
  38327. || pGroup->nCurrentPage>=pGroup->nMaxPage
  38328. || pcache1UnderMemoryPressure(pCache)
  38329. )){
  38330. PCache1 *pOther;
  38331. pPage = pGroup->pLruTail;
  38332. pcache1RemoveFromHash(pPage);
  38333. pcache1PinPage(pPage);
  38334. pOther = pPage->pCache;
  38335. /* We want to verify that szPage and szExtra are the same for pOther
  38336. ** and pCache. Assert that we can verify this by comparing sums. */
  38337. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  38338. assert( pCache->szExtra<512 );
  38339. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  38340. assert( pOther->szExtra<512 );
  38341. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  38342. pcache1FreePage(pPage);
  38343. pPage = 0;
  38344. }else{
  38345. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  38346. }
  38347. }
  38348. /* Step 5. If a usable page buffer has still not been found,
  38349. ** attempt to allocate a new one.
  38350. */
  38351. if( !pPage ){
  38352. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  38353. pPage = pcache1AllocPage(pCache);
  38354. if( createFlag==1 ) sqlite3EndBenignMalloc();
  38355. }
  38356. if( pPage ){
  38357. unsigned int h = iKey % pCache->nHash;
  38358. pCache->nPage++;
  38359. pPage->iKey = iKey;
  38360. pPage->pNext = pCache->apHash[h];
  38361. pPage->pCache = pCache;
  38362. pPage->pLruPrev = 0;
  38363. pPage->pLruNext = 0;
  38364. *(void **)pPage->page.pExtra = 0;
  38365. pCache->apHash[h] = pPage;
  38366. }
  38367. fetch_out:
  38368. if( pPage && iKey>pCache->iMaxKey ){
  38369. pCache->iMaxKey = iKey;
  38370. }
  38371. pcache1LeaveMutex(pGroup);
  38372. return &pPage->page;
  38373. }
  38374. /*
  38375. ** Implementation of the sqlite3_pcache.xUnpin method.
  38376. **
  38377. ** Mark a page as unpinned (eligible for asynchronous recycling).
  38378. */
  38379. static void pcache1Unpin(
  38380. sqlite3_pcache *p,
  38381. sqlite3_pcache_page *pPg,
  38382. int reuseUnlikely
  38383. ){
  38384. PCache1 *pCache = (PCache1 *)p;
  38385. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38386. PGroup *pGroup = pCache->pGroup;
  38387. assert( pPage->pCache==pCache );
  38388. pcache1EnterMutex(pGroup);
  38389. /* It is an error to call this function if the page is already
  38390. ** part of the PGroup LRU list.
  38391. */
  38392. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  38393. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  38394. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  38395. pcache1RemoveFromHash(pPage);
  38396. pcache1FreePage(pPage);
  38397. }else{
  38398. /* Add the page to the PGroup LRU list. */
  38399. if( pGroup->pLruHead ){
  38400. pGroup->pLruHead->pLruPrev = pPage;
  38401. pPage->pLruNext = pGroup->pLruHead;
  38402. pGroup->pLruHead = pPage;
  38403. }else{
  38404. pGroup->pLruTail = pPage;
  38405. pGroup->pLruHead = pPage;
  38406. }
  38407. pCache->nRecyclable++;
  38408. }
  38409. pcache1LeaveMutex(pCache->pGroup);
  38410. }
  38411. /*
  38412. ** Implementation of the sqlite3_pcache.xRekey method.
  38413. */
  38414. static void pcache1Rekey(
  38415. sqlite3_pcache *p,
  38416. sqlite3_pcache_page *pPg,
  38417. unsigned int iOld,
  38418. unsigned int iNew
  38419. ){
  38420. PCache1 *pCache = (PCache1 *)p;
  38421. PgHdr1 *pPage = (PgHdr1 *)pPg;
  38422. PgHdr1 **pp;
  38423. unsigned int h;
  38424. assert( pPage->iKey==iOld );
  38425. assert( pPage->pCache==pCache );
  38426. pcache1EnterMutex(pCache->pGroup);
  38427. h = iOld%pCache->nHash;
  38428. pp = &pCache->apHash[h];
  38429. while( (*pp)!=pPage ){
  38430. pp = &(*pp)->pNext;
  38431. }
  38432. *pp = pPage->pNext;
  38433. h = iNew%pCache->nHash;
  38434. pPage->iKey = iNew;
  38435. pPage->pNext = pCache->apHash[h];
  38436. pCache->apHash[h] = pPage;
  38437. if( iNew>pCache->iMaxKey ){
  38438. pCache->iMaxKey = iNew;
  38439. }
  38440. pcache1LeaveMutex(pCache->pGroup);
  38441. }
  38442. /*
  38443. ** Implementation of the sqlite3_pcache.xTruncate method.
  38444. **
  38445. ** Discard all unpinned pages in the cache with a page number equal to
  38446. ** or greater than parameter iLimit. Any pinned pages with a page number
  38447. ** equal to or greater than iLimit are implicitly unpinned.
  38448. */
  38449. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  38450. PCache1 *pCache = (PCache1 *)p;
  38451. pcache1EnterMutex(pCache->pGroup);
  38452. if( iLimit<=pCache->iMaxKey ){
  38453. pcache1TruncateUnsafe(pCache, iLimit);
  38454. pCache->iMaxKey = iLimit-1;
  38455. }
  38456. pcache1LeaveMutex(pCache->pGroup);
  38457. }
  38458. /*
  38459. ** Implementation of the sqlite3_pcache.xDestroy method.
  38460. **
  38461. ** Destroy a cache allocated using pcache1Create().
  38462. */
  38463. static void pcache1Destroy(sqlite3_pcache *p){
  38464. PCache1 *pCache = (PCache1 *)p;
  38465. PGroup *pGroup = pCache->pGroup;
  38466. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  38467. pcache1EnterMutex(pGroup);
  38468. pcache1TruncateUnsafe(pCache, 0);
  38469. assert( pGroup->nMaxPage >= pCache->nMax );
  38470. pGroup->nMaxPage -= pCache->nMax;
  38471. assert( pGroup->nMinPage >= pCache->nMin );
  38472. pGroup->nMinPage -= pCache->nMin;
  38473. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  38474. pcache1EnforceMaxPage(pGroup);
  38475. pcache1LeaveMutex(pGroup);
  38476. sqlite3_free(pCache->apHash);
  38477. sqlite3_free(pCache);
  38478. }
  38479. /*
  38480. ** This function is called during initialization (sqlite3_initialize()) to
  38481. ** install the default pluggable cache module, assuming the user has not
  38482. ** already provided an alternative.
  38483. */
  38484. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  38485. static const sqlite3_pcache_methods2 defaultMethods = {
  38486. 1, /* iVersion */
  38487. 0, /* pArg */
  38488. pcache1Init, /* xInit */
  38489. pcache1Shutdown, /* xShutdown */
  38490. pcache1Create, /* xCreate */
  38491. pcache1Cachesize, /* xCachesize */
  38492. pcache1Pagecount, /* xPagecount */
  38493. pcache1Fetch, /* xFetch */
  38494. pcache1Unpin, /* xUnpin */
  38495. pcache1Rekey, /* xRekey */
  38496. pcache1Truncate, /* xTruncate */
  38497. pcache1Destroy, /* xDestroy */
  38498. pcache1Shrink /* xShrink */
  38499. };
  38500. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  38501. }
  38502. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  38503. /*
  38504. ** This function is called to free superfluous dynamically allocated memory
  38505. ** held by the pager system. Memory in use by any SQLite pager allocated
  38506. ** by the current thread may be sqlite3_free()ed.
  38507. **
  38508. ** nReq is the number of bytes of memory required. Once this much has
  38509. ** been released, the function returns. The return value is the total number
  38510. ** of bytes of memory released.
  38511. */
  38512. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  38513. int nFree = 0;
  38514. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  38515. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  38516. if( pcache1.pStart==0 ){
  38517. PgHdr1 *p;
  38518. pcache1EnterMutex(&pcache1.grp);
  38519. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  38520. nFree += pcache1MemSize(p->page.pBuf);
  38521. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  38522. nFree += sqlite3MemSize(p);
  38523. #endif
  38524. pcache1PinPage(p);
  38525. pcache1RemoveFromHash(p);
  38526. pcache1FreePage(p);
  38527. }
  38528. pcache1LeaveMutex(&pcache1.grp);
  38529. }
  38530. return nFree;
  38531. }
  38532. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  38533. #ifdef SQLITE_TEST
  38534. /*
  38535. ** This function is used by test procedures to inspect the internal state
  38536. ** of the global cache.
  38537. */
  38538. SQLITE_PRIVATE void sqlite3PcacheStats(
  38539. int *pnCurrent, /* OUT: Total number of pages cached */
  38540. int *pnMax, /* OUT: Global maximum cache size */
  38541. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  38542. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  38543. ){
  38544. PgHdr1 *p;
  38545. int nRecyclable = 0;
  38546. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  38547. nRecyclable++;
  38548. }
  38549. *pnCurrent = pcache1.grp.nCurrentPage;
  38550. *pnMax = (int)pcache1.grp.nMaxPage;
  38551. *pnMin = (int)pcache1.grp.nMinPage;
  38552. *pnRecyclable = nRecyclable;
  38553. }
  38554. #endif
  38555. /************** End of pcache1.c *********************************************/
  38556. /************** Begin file rowset.c ******************************************/
  38557. /*
  38558. ** 2008 December 3
  38559. **
  38560. ** The author disclaims copyright to this source code. In place of
  38561. ** a legal notice, here is a blessing:
  38562. **
  38563. ** May you do good and not evil.
  38564. ** May you find forgiveness for yourself and forgive others.
  38565. ** May you share freely, never taking more than you give.
  38566. **
  38567. *************************************************************************
  38568. **
  38569. ** This module implements an object we call a "RowSet".
  38570. **
  38571. ** The RowSet object is a collection of rowids. Rowids
  38572. ** are inserted into the RowSet in an arbitrary order. Inserts
  38573. ** can be intermixed with tests to see if a given rowid has been
  38574. ** previously inserted into the RowSet.
  38575. **
  38576. ** After all inserts are finished, it is possible to extract the
  38577. ** elements of the RowSet in sorted order. Once this extraction
  38578. ** process has started, no new elements may be inserted.
  38579. **
  38580. ** Hence, the primitive operations for a RowSet are:
  38581. **
  38582. ** CREATE
  38583. ** INSERT
  38584. ** TEST
  38585. ** SMALLEST
  38586. ** DESTROY
  38587. **
  38588. ** The CREATE and DESTROY primitives are the constructor and destructor,
  38589. ** obviously. The INSERT primitive adds a new element to the RowSet.
  38590. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  38591. ** extracts the least value from the RowSet.
  38592. **
  38593. ** The INSERT primitive might allocate additional memory. Memory is
  38594. ** allocated in chunks so most INSERTs do no allocation. There is an
  38595. ** upper bound on the size of allocated memory. No memory is freed
  38596. ** until DESTROY.
  38597. **
  38598. ** The TEST primitive includes a "batch" number. The TEST primitive
  38599. ** will only see elements that were inserted before the last change
  38600. ** in the batch number. In other words, if an INSERT occurs between
  38601. ** two TESTs where the TESTs have the same batch nubmer, then the
  38602. ** value added by the INSERT will not be visible to the second TEST.
  38603. ** The initial batch number is zero, so if the very first TEST contains
  38604. ** a non-zero batch number, it will see all prior INSERTs.
  38605. **
  38606. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  38607. ** that is attempted.
  38608. **
  38609. ** The cost of an INSERT is roughly constant. (Sometime new memory
  38610. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  38611. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  38612. ** The cost of a TEST using the same batch number is O(logN). The cost
  38613. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  38614. ** primitives are constant time. The cost of DESTROY is O(N).
  38615. **
  38616. ** There is an added cost of O(N) when switching between TEST and
  38617. ** SMALLEST primitives.
  38618. */
  38619. /*
  38620. ** Target size for allocation chunks.
  38621. */
  38622. #define ROWSET_ALLOCATION_SIZE 1024
  38623. /*
  38624. ** The number of rowset entries per allocation chunk.
  38625. */
  38626. #define ROWSET_ENTRY_PER_CHUNK \
  38627. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  38628. /*
  38629. ** Each entry in a RowSet is an instance of the following object.
  38630. **
  38631. ** This same object is reused to store a linked list of trees of RowSetEntry
  38632. ** objects. In that alternative use, pRight points to the next entry
  38633. ** in the list, pLeft points to the tree, and v is unused. The
  38634. ** RowSet.pForest value points to the head of this forest list.
  38635. */
  38636. struct RowSetEntry {
  38637. i64 v; /* ROWID value for this entry */
  38638. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  38639. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  38640. };
  38641. /*
  38642. ** RowSetEntry objects are allocated in large chunks (instances of the
  38643. ** following structure) to reduce memory allocation overhead. The
  38644. ** chunks are kept on a linked list so that they can be deallocated
  38645. ** when the RowSet is destroyed.
  38646. */
  38647. struct RowSetChunk {
  38648. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  38649. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  38650. };
  38651. /*
  38652. ** A RowSet in an instance of the following structure.
  38653. **
  38654. ** A typedef of this structure if found in sqliteInt.h.
  38655. */
  38656. struct RowSet {
  38657. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  38658. sqlite3 *db; /* The database connection */
  38659. struct RowSetEntry *pEntry; /* List of entries using pRight */
  38660. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  38661. struct RowSetEntry *pFresh; /* Source of new entry objects */
  38662. struct RowSetEntry *pForest; /* List of binary trees of entries */
  38663. u16 nFresh; /* Number of objects on pFresh */
  38664. u8 rsFlags; /* Various flags */
  38665. u8 iBatch; /* Current insert batch */
  38666. };
  38667. /*
  38668. ** Allowed values for RowSet.rsFlags
  38669. */
  38670. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  38671. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  38672. /*
  38673. ** Turn bulk memory into a RowSet object. N bytes of memory
  38674. ** are available at pSpace. The db pointer is used as a memory context
  38675. ** for any subsequent allocations that need to occur.
  38676. ** Return a pointer to the new RowSet object.
  38677. **
  38678. ** It must be the case that N is sufficient to make a Rowset. If not
  38679. ** an assertion fault occurs.
  38680. **
  38681. ** If N is larger than the minimum, use the surplus as an initial
  38682. ** allocation of entries available to be filled.
  38683. */
  38684. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  38685. RowSet *p;
  38686. assert( N >= ROUND8(sizeof(*p)) );
  38687. p = pSpace;
  38688. p->pChunk = 0;
  38689. p->db = db;
  38690. p->pEntry = 0;
  38691. p->pLast = 0;
  38692. p->pForest = 0;
  38693. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  38694. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  38695. p->rsFlags = ROWSET_SORTED;
  38696. p->iBatch = 0;
  38697. return p;
  38698. }
  38699. /*
  38700. ** Deallocate all chunks from a RowSet. This frees all memory that
  38701. ** the RowSet has allocated over its lifetime. This routine is
  38702. ** the destructor for the RowSet.
  38703. */
  38704. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  38705. struct RowSetChunk *pChunk, *pNextChunk;
  38706. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  38707. pNextChunk = pChunk->pNextChunk;
  38708. sqlite3DbFree(p->db, pChunk);
  38709. }
  38710. p->pChunk = 0;
  38711. p->nFresh = 0;
  38712. p->pEntry = 0;
  38713. p->pLast = 0;
  38714. p->pForest = 0;
  38715. p->rsFlags = ROWSET_SORTED;
  38716. }
  38717. /*
  38718. ** Allocate a new RowSetEntry object that is associated with the
  38719. ** given RowSet. Return a pointer to the new and completely uninitialized
  38720. ** objected.
  38721. **
  38722. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  38723. ** routine returns NULL.
  38724. */
  38725. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  38726. assert( p!=0 );
  38727. if( p->nFresh==0 ){
  38728. struct RowSetChunk *pNew;
  38729. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  38730. if( pNew==0 ){
  38731. return 0;
  38732. }
  38733. pNew->pNextChunk = p->pChunk;
  38734. p->pChunk = pNew;
  38735. p->pFresh = pNew->aEntry;
  38736. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  38737. }
  38738. p->nFresh--;
  38739. return p->pFresh++;
  38740. }
  38741. /*
  38742. ** Insert a new value into a RowSet.
  38743. **
  38744. ** The mallocFailed flag of the database connection is set if a
  38745. ** memory allocation fails.
  38746. */
  38747. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  38748. struct RowSetEntry *pEntry; /* The new entry */
  38749. struct RowSetEntry *pLast; /* The last prior entry */
  38750. /* This routine is never called after sqlite3RowSetNext() */
  38751. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38752. pEntry = rowSetEntryAlloc(p);
  38753. if( pEntry==0 ) return;
  38754. pEntry->v = rowid;
  38755. pEntry->pRight = 0;
  38756. pLast = p->pLast;
  38757. if( pLast ){
  38758. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  38759. p->rsFlags &= ~ROWSET_SORTED;
  38760. }
  38761. pLast->pRight = pEntry;
  38762. }else{
  38763. p->pEntry = pEntry;
  38764. }
  38765. p->pLast = pEntry;
  38766. }
  38767. /*
  38768. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  38769. **
  38770. ** The input lists are connected via pRight pointers and are
  38771. ** assumed to each already be in sorted order.
  38772. */
  38773. static struct RowSetEntry *rowSetEntryMerge(
  38774. struct RowSetEntry *pA, /* First sorted list to be merged */
  38775. struct RowSetEntry *pB /* Second sorted list to be merged */
  38776. ){
  38777. struct RowSetEntry head;
  38778. struct RowSetEntry *pTail;
  38779. pTail = &head;
  38780. while( pA && pB ){
  38781. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38782. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  38783. if( pA->v<pB->v ){
  38784. pTail->pRight = pA;
  38785. pA = pA->pRight;
  38786. pTail = pTail->pRight;
  38787. }else if( pB->v<pA->v ){
  38788. pTail->pRight = pB;
  38789. pB = pB->pRight;
  38790. pTail = pTail->pRight;
  38791. }else{
  38792. pA = pA->pRight;
  38793. }
  38794. }
  38795. if( pA ){
  38796. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  38797. pTail->pRight = pA;
  38798. }else{
  38799. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  38800. pTail->pRight = pB;
  38801. }
  38802. return head.pRight;
  38803. }
  38804. /*
  38805. ** Sort all elements on the list of RowSetEntry objects into order of
  38806. ** increasing v.
  38807. */
  38808. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  38809. unsigned int i;
  38810. struct RowSetEntry *pNext, *aBucket[40];
  38811. memset(aBucket, 0, sizeof(aBucket));
  38812. while( pIn ){
  38813. pNext = pIn->pRight;
  38814. pIn->pRight = 0;
  38815. for(i=0; aBucket[i]; i++){
  38816. pIn = rowSetEntryMerge(aBucket[i], pIn);
  38817. aBucket[i] = 0;
  38818. }
  38819. aBucket[i] = pIn;
  38820. pIn = pNext;
  38821. }
  38822. pIn = 0;
  38823. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  38824. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  38825. }
  38826. return pIn;
  38827. }
  38828. /*
  38829. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  38830. ** Convert this tree into a linked list connected by the pRight pointers
  38831. ** and return pointers to the first and last elements of the new list.
  38832. */
  38833. static void rowSetTreeToList(
  38834. struct RowSetEntry *pIn, /* Root of the input tree */
  38835. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  38836. struct RowSetEntry **ppLast /* Write tail of the output list here */
  38837. ){
  38838. assert( pIn!=0 );
  38839. if( pIn->pLeft ){
  38840. struct RowSetEntry *p;
  38841. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  38842. p->pRight = pIn;
  38843. }else{
  38844. *ppFirst = pIn;
  38845. }
  38846. if( pIn->pRight ){
  38847. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  38848. }else{
  38849. *ppLast = pIn;
  38850. }
  38851. assert( (*ppLast)->pRight==0 );
  38852. }
  38853. /*
  38854. ** Convert a sorted list of elements (connected by pRight) into a binary
  38855. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  38856. ** node taken from the head of *ppList. A depth of 2 means a tree with
  38857. ** three nodes. And so forth.
  38858. **
  38859. ** Use as many entries from the input list as required and update the
  38860. ** *ppList to point to the unused elements of the list. If the input
  38861. ** list contains too few elements, then construct an incomplete tree
  38862. ** and leave *ppList set to NULL.
  38863. **
  38864. ** Return a pointer to the root of the constructed binary tree.
  38865. */
  38866. static struct RowSetEntry *rowSetNDeepTree(
  38867. struct RowSetEntry **ppList,
  38868. int iDepth
  38869. ){
  38870. struct RowSetEntry *p; /* Root of the new tree */
  38871. struct RowSetEntry *pLeft; /* Left subtree */
  38872. if( *ppList==0 ){
  38873. return 0;
  38874. }
  38875. if( iDepth==1 ){
  38876. p = *ppList;
  38877. *ppList = p->pRight;
  38878. p->pLeft = p->pRight = 0;
  38879. return p;
  38880. }
  38881. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  38882. p = *ppList;
  38883. if( p==0 ){
  38884. return pLeft;
  38885. }
  38886. p->pLeft = pLeft;
  38887. *ppList = p->pRight;
  38888. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  38889. return p;
  38890. }
  38891. /*
  38892. ** Convert a sorted list of elements into a binary tree. Make the tree
  38893. ** as deep as it needs to be in order to contain the entire list.
  38894. */
  38895. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  38896. int iDepth; /* Depth of the tree so far */
  38897. struct RowSetEntry *p; /* Current tree root */
  38898. struct RowSetEntry *pLeft; /* Left subtree */
  38899. assert( pList!=0 );
  38900. p = pList;
  38901. pList = p->pRight;
  38902. p->pLeft = p->pRight = 0;
  38903. for(iDepth=1; pList; iDepth++){
  38904. pLeft = p;
  38905. p = pList;
  38906. pList = p->pRight;
  38907. p->pLeft = pLeft;
  38908. p->pRight = rowSetNDeepTree(&pList, iDepth);
  38909. }
  38910. return p;
  38911. }
  38912. /*
  38913. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  38914. ** sort them all together into one big ordered list on p->pEntry.
  38915. **
  38916. ** This routine should only be called once in the life of a RowSet.
  38917. */
  38918. static void rowSetToList(RowSet *p){
  38919. /* This routine is called only once */
  38920. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  38921. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  38922. p->pEntry = rowSetEntrySort(p->pEntry);
  38923. }
  38924. /* While this module could theoretically support it, sqlite3RowSetNext()
  38925. ** is never called after sqlite3RowSetText() for the same RowSet. So
  38926. ** there is never a forest to deal with. Should this change, simply
  38927. ** remove the assert() and the #if 0. */
  38928. assert( p->pForest==0 );
  38929. #if 0
  38930. while( p->pForest ){
  38931. struct RowSetEntry *pTree = p->pForest->pLeft;
  38932. if( pTree ){
  38933. struct RowSetEntry *pHead, *pTail;
  38934. rowSetTreeToList(pTree, &pHead, &pTail);
  38935. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  38936. }
  38937. p->pForest = p->pForest->pRight;
  38938. }
  38939. #endif
  38940. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  38941. }
  38942. /*
  38943. ** Extract the smallest element from the RowSet.
  38944. ** Write the element into *pRowid. Return 1 on success. Return
  38945. ** 0 if the RowSet is already empty.
  38946. **
  38947. ** After this routine has been called, the sqlite3RowSetInsert()
  38948. ** routine may not be called again.
  38949. */
  38950. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  38951. assert( p!=0 );
  38952. /* Merge the forest into a single sorted list on first call */
  38953. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  38954. /* Return the next entry on the list */
  38955. if( p->pEntry ){
  38956. *pRowid = p->pEntry->v;
  38957. p->pEntry = p->pEntry->pRight;
  38958. if( p->pEntry==0 ){
  38959. sqlite3RowSetClear(p);
  38960. }
  38961. return 1;
  38962. }else{
  38963. return 0;
  38964. }
  38965. }
  38966. /*
  38967. ** Check to see if element iRowid was inserted into the rowset as
  38968. ** part of any insert batch prior to iBatch. Return 1 or 0.
  38969. **
  38970. ** If this is the first test of a new batch and if there exist entires
  38971. ** on pRowSet->pEntry, then sort those entires into the forest at
  38972. ** pRowSet->pForest so that they can be tested.
  38973. */
  38974. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
  38975. struct RowSetEntry *p, *pTree;
  38976. /* This routine is never called after sqlite3RowSetNext() */
  38977. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  38978. /* Sort entries into the forest on the first test of a new batch
  38979. */
  38980. if( iBatch!=pRowSet->iBatch ){
  38981. p = pRowSet->pEntry;
  38982. if( p ){
  38983. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  38984. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  38985. p = rowSetEntrySort(p);
  38986. }
  38987. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38988. ppPrevTree = &pTree->pRight;
  38989. if( pTree->pLeft==0 ){
  38990. pTree->pLeft = rowSetListToTree(p);
  38991. break;
  38992. }else{
  38993. struct RowSetEntry *pAux, *pTail;
  38994. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  38995. pTree->pLeft = 0;
  38996. p = rowSetEntryMerge(pAux, p);
  38997. }
  38998. }
  38999. if( pTree==0 ){
  39000. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  39001. if( pTree ){
  39002. pTree->v = 0;
  39003. pTree->pRight = 0;
  39004. pTree->pLeft = rowSetListToTree(p);
  39005. }
  39006. }
  39007. pRowSet->pEntry = 0;
  39008. pRowSet->pLast = 0;
  39009. pRowSet->rsFlags |= ROWSET_SORTED;
  39010. }
  39011. pRowSet->iBatch = iBatch;
  39012. }
  39013. /* Test to see if the iRowid value appears anywhere in the forest.
  39014. ** Return 1 if it does and 0 if not.
  39015. */
  39016. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  39017. p = pTree->pLeft;
  39018. while( p ){
  39019. if( p->v<iRowid ){
  39020. p = p->pRight;
  39021. }else if( p->v>iRowid ){
  39022. p = p->pLeft;
  39023. }else{
  39024. return 1;
  39025. }
  39026. }
  39027. }
  39028. return 0;
  39029. }
  39030. /************** End of rowset.c **********************************************/
  39031. /************** Begin file pager.c *******************************************/
  39032. /*
  39033. ** 2001 September 15
  39034. **
  39035. ** The author disclaims copyright to this source code. In place of
  39036. ** a legal notice, here is a blessing:
  39037. **
  39038. ** May you do good and not evil.
  39039. ** May you find forgiveness for yourself and forgive others.
  39040. ** May you share freely, never taking more than you give.
  39041. **
  39042. *************************************************************************
  39043. ** This is the implementation of the page cache subsystem or "pager".
  39044. **
  39045. ** The pager is used to access a database disk file. It implements
  39046. ** atomic commit and rollback through the use of a journal file that
  39047. ** is separate from the database file. The pager also implements file
  39048. ** locking to prevent two processes from writing the same database
  39049. ** file simultaneously, or one process from reading the database while
  39050. ** another is writing.
  39051. */
  39052. #ifndef SQLITE_OMIT_DISKIO
  39053. /************** Include wal.h in the middle of pager.c ***********************/
  39054. /************** Begin file wal.h *********************************************/
  39055. /*
  39056. ** 2010 February 1
  39057. **
  39058. ** The author disclaims copyright to this source code. In place of
  39059. ** a legal notice, here is a blessing:
  39060. **
  39061. ** May you do good and not evil.
  39062. ** May you find forgiveness for yourself and forgive others.
  39063. ** May you share freely, never taking more than you give.
  39064. **
  39065. *************************************************************************
  39066. ** This header file defines the interface to the write-ahead logging
  39067. ** system. Refer to the comments below and the header comment attached to
  39068. ** the implementation of each function in log.c for further details.
  39069. */
  39070. #ifndef _WAL_H_
  39071. #define _WAL_H_
  39072. /* Additional values that can be added to the sync_flags argument of
  39073. ** sqlite3WalFrames():
  39074. */
  39075. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  39076. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  39077. #ifdef SQLITE_OMIT_WAL
  39078. # define sqlite3WalOpen(x,y,z) 0
  39079. # define sqlite3WalLimit(x,y)
  39080. # define sqlite3WalClose(w,x,y,z) 0
  39081. # define sqlite3WalBeginReadTransaction(y,z) 0
  39082. # define sqlite3WalEndReadTransaction(z)
  39083. # define sqlite3WalDbsize(y) 0
  39084. # define sqlite3WalBeginWriteTransaction(y) 0
  39085. # define sqlite3WalEndWriteTransaction(x) 0
  39086. # define sqlite3WalUndo(x,y,z) 0
  39087. # define sqlite3WalSavepoint(y,z)
  39088. # define sqlite3WalSavepointUndo(y,z) 0
  39089. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  39090. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  39091. # define sqlite3WalCallback(z) 0
  39092. # define sqlite3WalExclusiveMode(y,z) 0
  39093. # define sqlite3WalHeapMemory(z) 0
  39094. # define sqlite3WalFramesize(z) 0
  39095. # define sqlite3WalFindFrame(x,y,z) 0
  39096. #else
  39097. #define WAL_SAVEPOINT_NDATA 4
  39098. /* Connection to a write-ahead log (WAL) file.
  39099. ** There is one object of this type for each pager.
  39100. */
  39101. typedef struct Wal Wal;
  39102. /* Open and close a connection to a write-ahead log. */
  39103. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  39104. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  39105. /* Set the limiting size of a WAL file. */
  39106. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  39107. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  39108. ** snapshot is like a read-transaction. It is the state of the database
  39109. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  39110. ** preserves the current state even if the other threads or processes
  39111. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  39112. ** transaction and releases the lock.
  39113. */
  39114. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  39115. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  39116. /* Read a page from the write-ahead log, if it is present. */
  39117. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  39118. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  39119. /* If the WAL is not empty, return the size of the database. */
  39120. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  39121. /* Obtain or release the WRITER lock. */
  39122. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  39123. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  39124. /* Undo any frames written (but not committed) to the log */
  39125. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  39126. /* Return an integer that records the current (uncommitted) write
  39127. ** position in the WAL */
  39128. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  39129. /* Move the write position of the WAL back to iFrame. Called in
  39130. ** response to a ROLLBACK TO command. */
  39131. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  39132. /* Write a frame or frames to the log. */
  39133. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  39134. /* Copy pages from the log to the database file */
  39135. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  39136. Wal *pWal, /* Write-ahead log connection */
  39137. int eMode, /* One of PASSIVE, FULL and RESTART */
  39138. int (*xBusy)(void*), /* Function to call when busy */
  39139. void *pBusyArg, /* Context argument for xBusyHandler */
  39140. int sync_flags, /* Flags to sync db file with (or 0) */
  39141. int nBuf, /* Size of buffer nBuf */
  39142. u8 *zBuf, /* Temporary buffer to use */
  39143. int *pnLog, /* OUT: Number of frames in WAL */
  39144. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  39145. );
  39146. /* Return the value to pass to a sqlite3_wal_hook callback, the
  39147. ** number of frames in the WAL at the point of the last commit since
  39148. ** sqlite3WalCallback() was called. If no commits have occurred since
  39149. ** the last call, then return 0.
  39150. */
  39151. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  39152. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  39153. ** by the pager layer on the database file.
  39154. */
  39155. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  39156. /* Return true if the argument is non-NULL and the WAL module is using
  39157. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  39158. ** WAL module is using shared-memory, return false.
  39159. */
  39160. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  39161. #ifdef SQLITE_ENABLE_ZIPVFS
  39162. /* If the WAL file is not empty, return the number of bytes of content
  39163. ** stored in each frame (i.e. the db page-size when the WAL was created).
  39164. */
  39165. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  39166. #endif
  39167. #endif /* ifndef SQLITE_OMIT_WAL */
  39168. #endif /* _WAL_H_ */
  39169. /************** End of wal.h *************************************************/
  39170. /************** Continuing where we left off in pager.c **********************/
  39171. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  39172. **
  39173. ** This comment block describes invariants that hold when using a rollback
  39174. ** journal. These invariants do not apply for journal_mode=WAL,
  39175. ** journal_mode=MEMORY, or journal_mode=OFF.
  39176. **
  39177. ** Within this comment block, a page is deemed to have been synced
  39178. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  39179. ** Otherwise, the page is not synced until the xSync method of the VFS
  39180. ** is called successfully on the file containing the page.
  39181. **
  39182. ** Definition: A page of the database file is said to be "overwriteable" if
  39183. ** one or more of the following are true about the page:
  39184. **
  39185. ** (a) The original content of the page as it was at the beginning of
  39186. ** the transaction has been written into the rollback journal and
  39187. ** synced.
  39188. **
  39189. ** (b) The page was a freelist leaf page at the start of the transaction.
  39190. **
  39191. ** (c) The page number is greater than the largest page that existed in
  39192. ** the database file at the start of the transaction.
  39193. **
  39194. ** (1) A page of the database file is never overwritten unless one of the
  39195. ** following are true:
  39196. **
  39197. ** (a) The page and all other pages on the same sector are overwriteable.
  39198. **
  39199. ** (b) The atomic page write optimization is enabled, and the entire
  39200. ** transaction other than the update of the transaction sequence
  39201. ** number consists of a single page change.
  39202. **
  39203. ** (2) The content of a page written into the rollback journal exactly matches
  39204. ** both the content in the database when the rollback journal was written
  39205. ** and the content in the database at the beginning of the current
  39206. ** transaction.
  39207. **
  39208. ** (3) Writes to the database file are an integer multiple of the page size
  39209. ** in length and are aligned on a page boundary.
  39210. **
  39211. ** (4) Reads from the database file are either aligned on a page boundary and
  39212. ** an integer multiple of the page size in length or are taken from the
  39213. ** first 100 bytes of the database file.
  39214. **
  39215. ** (5) All writes to the database file are synced prior to the rollback journal
  39216. ** being deleted, truncated, or zeroed.
  39217. **
  39218. ** (6) If a master journal file is used, then all writes to the database file
  39219. ** are synced prior to the master journal being deleted.
  39220. **
  39221. ** Definition: Two databases (or the same database at two points it time)
  39222. ** are said to be "logically equivalent" if they give the same answer to
  39223. ** all queries. Note in particular the content of freelist leaf
  39224. ** pages can be changed arbitarily without effecting the logical equivalence
  39225. ** of the database.
  39226. **
  39227. ** (7) At any time, if any subset, including the empty set and the total set,
  39228. ** of the unsynced changes to a rollback journal are removed and the
  39229. ** journal is rolled back, the resulting database file will be logical
  39230. ** equivalent to the database file at the beginning of the transaction.
  39231. **
  39232. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  39233. ** is called to restore the database file to the same size it was at
  39234. ** the beginning of the transaction. (In some VFSes, the xTruncate
  39235. ** method is a no-op, but that does not change the fact the SQLite will
  39236. ** invoke it.)
  39237. **
  39238. ** (9) Whenever the database file is modified, at least one bit in the range
  39239. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  39240. ** the EXCLUSIVE lock, thus signaling other connections on the same
  39241. ** database to flush their caches.
  39242. **
  39243. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  39244. ** than one billion transactions.
  39245. **
  39246. ** (11) A database file is well-formed at the beginning and at the conclusion
  39247. ** of every transaction.
  39248. **
  39249. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  39250. ** the database file.
  39251. **
  39252. ** (13) A SHARED lock is held on the database file while reading any
  39253. ** content out of the database file.
  39254. **
  39255. ******************************************************************************/
  39256. /*
  39257. ** Macros for troubleshooting. Normally turned off
  39258. */
  39259. #if 0
  39260. int sqlite3PagerTrace=1; /* True to enable tracing */
  39261. #define sqlite3DebugPrintf printf
  39262. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  39263. #else
  39264. #define PAGERTRACE(X)
  39265. #endif
  39266. /*
  39267. ** The following two macros are used within the PAGERTRACE() macros above
  39268. ** to print out file-descriptors.
  39269. **
  39270. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  39271. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  39272. ** struct as its argument.
  39273. */
  39274. #define PAGERID(p) ((int)(p->fd))
  39275. #define FILEHANDLEID(fd) ((int)fd)
  39276. /*
  39277. ** The Pager.eState variable stores the current 'state' of a pager. A
  39278. ** pager may be in any one of the seven states shown in the following
  39279. ** state diagram.
  39280. **
  39281. ** OPEN <------+------+
  39282. ** | | |
  39283. ** V | |
  39284. ** +---------> READER-------+ |
  39285. ** | | |
  39286. ** | V |
  39287. ** |<-------WRITER_LOCKED------> ERROR
  39288. ** | | ^
  39289. ** | V |
  39290. ** |<------WRITER_CACHEMOD-------->|
  39291. ** | | |
  39292. ** | V |
  39293. ** |<-------WRITER_DBMOD---------->|
  39294. ** | | |
  39295. ** | V |
  39296. ** +<------WRITER_FINISHED-------->+
  39297. **
  39298. **
  39299. ** List of state transitions and the C [function] that performs each:
  39300. **
  39301. ** OPEN -> READER [sqlite3PagerSharedLock]
  39302. ** READER -> OPEN [pager_unlock]
  39303. **
  39304. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  39305. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  39306. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  39307. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  39308. ** WRITER_*** -> READER [pager_end_transaction]
  39309. **
  39310. ** WRITER_*** -> ERROR [pager_error]
  39311. ** ERROR -> OPEN [pager_unlock]
  39312. **
  39313. **
  39314. ** OPEN:
  39315. **
  39316. ** The pager starts up in this state. Nothing is guaranteed in this
  39317. ** state - the file may or may not be locked and the database size is
  39318. ** unknown. The database may not be read or written.
  39319. **
  39320. ** * No read or write transaction is active.
  39321. ** * Any lock, or no lock at all, may be held on the database file.
  39322. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  39323. **
  39324. ** READER:
  39325. **
  39326. ** In this state all the requirements for reading the database in
  39327. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  39328. ** was) in exclusive-locking mode, a user-level read transaction is
  39329. ** open. The database size is known in this state.
  39330. **
  39331. ** A connection running with locking_mode=normal enters this state when
  39332. ** it opens a read-transaction on the database and returns to state
  39333. ** OPEN after the read-transaction is completed. However a connection
  39334. ** running in locking_mode=exclusive (including temp databases) remains in
  39335. ** this state even after the read-transaction is closed. The only way
  39336. ** a locking_mode=exclusive connection can transition from READER to OPEN
  39337. ** is via the ERROR state (see below).
  39338. **
  39339. ** * A read transaction may be active (but a write-transaction cannot).
  39340. ** * A SHARED or greater lock is held on the database file.
  39341. ** * The dbSize variable may be trusted (even if a user-level read
  39342. ** transaction is not active). The dbOrigSize and dbFileSize variables
  39343. ** may not be trusted at this point.
  39344. ** * If the database is a WAL database, then the WAL connection is open.
  39345. ** * Even if a read-transaction is not open, it is guaranteed that
  39346. ** there is no hot-journal in the file-system.
  39347. **
  39348. ** WRITER_LOCKED:
  39349. **
  39350. ** The pager moves to this state from READER when a write-transaction
  39351. ** is first opened on the database. In WRITER_LOCKED state, all locks
  39352. ** required to start a write-transaction are held, but no actual
  39353. ** modifications to the cache or database have taken place.
  39354. **
  39355. ** In rollback mode, a RESERVED or (if the transaction was opened with
  39356. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  39357. ** moving to this state, but the journal file is not written to or opened
  39358. ** to in this state. If the transaction is committed or rolled back while
  39359. ** in WRITER_LOCKED state, all that is required is to unlock the database
  39360. ** file.
  39361. **
  39362. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  39363. ** If the connection is running with locking_mode=exclusive, an attempt
  39364. ** is made to obtain an EXCLUSIVE lock on the database file.
  39365. **
  39366. ** * A write transaction is active.
  39367. ** * If the connection is open in rollback-mode, a RESERVED or greater
  39368. ** lock is held on the database file.
  39369. ** * If the connection is open in WAL-mode, a WAL write transaction
  39370. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  39371. ** called).
  39372. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  39373. ** * The contents of the pager cache have not been modified.
  39374. ** * The journal file may or may not be open.
  39375. ** * Nothing (not even the first header) has been written to the journal.
  39376. **
  39377. ** WRITER_CACHEMOD:
  39378. **
  39379. ** A pager moves from WRITER_LOCKED state to this state when a page is
  39380. ** first modified by the upper layer. In rollback mode the journal file
  39381. ** is opened (if it is not already open) and a header written to the
  39382. ** start of it. The database file on disk has not been modified.
  39383. **
  39384. ** * A write transaction is active.
  39385. ** * A RESERVED or greater lock is held on the database file.
  39386. ** * The journal file is open and the first header has been written
  39387. ** to it, but the header has not been synced to disk.
  39388. ** * The contents of the page cache have been modified.
  39389. **
  39390. ** WRITER_DBMOD:
  39391. **
  39392. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  39393. ** when it modifies the contents of the database file. WAL connections
  39394. ** never enter this state (since they do not modify the database file,
  39395. ** just the log file).
  39396. **
  39397. ** * A write transaction is active.
  39398. ** * An EXCLUSIVE or greater lock is held on the database file.
  39399. ** * The journal file is open and the first header has been written
  39400. ** and synced to disk.
  39401. ** * The contents of the page cache have been modified (and possibly
  39402. ** written to disk).
  39403. **
  39404. ** WRITER_FINISHED:
  39405. **
  39406. ** It is not possible for a WAL connection to enter this state.
  39407. **
  39408. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  39409. ** state after the entire transaction has been successfully written into the
  39410. ** database file. In this state the transaction may be committed simply
  39411. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  39412. ** not possible to modify the database further. At this point, the upper
  39413. ** layer must either commit or rollback the transaction.
  39414. **
  39415. ** * A write transaction is active.
  39416. ** * An EXCLUSIVE or greater lock is held on the database file.
  39417. ** * All writing and syncing of journal and database data has finished.
  39418. ** If no error occurred, all that remains is to finalize the journal to
  39419. ** commit the transaction. If an error did occur, the caller will need
  39420. ** to rollback the transaction.
  39421. **
  39422. ** ERROR:
  39423. **
  39424. ** The ERROR state is entered when an IO or disk-full error (including
  39425. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  39426. ** difficult to be sure that the in-memory pager state (cache contents,
  39427. ** db size etc.) are consistent with the contents of the file-system.
  39428. **
  39429. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  39430. ** cannot.
  39431. **
  39432. ** For example, if an IO error occurs while performing a rollback,
  39433. ** the contents of the page-cache may be left in an inconsistent state.
  39434. ** At this point it would be dangerous to change back to READER state
  39435. ** (as usually happens after a rollback). Any subsequent readers might
  39436. ** report database corruption (due to the inconsistent cache), and if
  39437. ** they upgrade to writers, they may inadvertently corrupt the database
  39438. ** file. To avoid this hazard, the pager switches into the ERROR state
  39439. ** instead of READER following such an error.
  39440. **
  39441. ** Once it has entered the ERROR state, any attempt to use the pager
  39442. ** to read or write data returns an error. Eventually, once all
  39443. ** outstanding transactions have been abandoned, the pager is able to
  39444. ** transition back to OPEN state, discarding the contents of the
  39445. ** page-cache and any other in-memory state at the same time. Everything
  39446. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  39447. ** when a read-transaction is next opened on the pager (transitioning
  39448. ** the pager into READER state). At that point the system has recovered
  39449. ** from the error.
  39450. **
  39451. ** Specifically, the pager jumps into the ERROR state if:
  39452. **
  39453. ** 1. An error occurs while attempting a rollback. This happens in
  39454. ** function sqlite3PagerRollback().
  39455. **
  39456. ** 2. An error occurs while attempting to finalize a journal file
  39457. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  39458. **
  39459. ** 3. An error occurs while attempting to write to the journal or
  39460. ** database file in function pagerStress() in order to free up
  39461. ** memory.
  39462. **
  39463. ** In other cases, the error is returned to the b-tree layer. The b-tree
  39464. ** layer then attempts a rollback operation. If the error condition
  39465. ** persists, the pager enters the ERROR state via condition (1) above.
  39466. **
  39467. ** Condition (3) is necessary because it can be triggered by a read-only
  39468. ** statement executed within a transaction. In this case, if the error
  39469. ** code were simply returned to the user, the b-tree layer would not
  39470. ** automatically attempt a rollback, as it assumes that an error in a
  39471. ** read-only statement cannot leave the pager in an internally inconsistent
  39472. ** state.
  39473. **
  39474. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  39475. ** * There are one or more outstanding references to pages (after the
  39476. ** last reference is dropped the pager should move back to OPEN state).
  39477. ** * The pager is not an in-memory pager.
  39478. **
  39479. **
  39480. ** Notes:
  39481. **
  39482. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  39483. ** connection is open in WAL mode. A WAL connection is always in one
  39484. ** of the first four states.
  39485. **
  39486. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  39487. ** state. There are two exceptions: immediately after exclusive-mode has
  39488. ** been turned on (and before any read or write transactions are
  39489. ** executed), and when the pager is leaving the "error state".
  39490. **
  39491. ** * See also: assert_pager_state().
  39492. */
  39493. #define PAGER_OPEN 0
  39494. #define PAGER_READER 1
  39495. #define PAGER_WRITER_LOCKED 2
  39496. #define PAGER_WRITER_CACHEMOD 3
  39497. #define PAGER_WRITER_DBMOD 4
  39498. #define PAGER_WRITER_FINISHED 5
  39499. #define PAGER_ERROR 6
  39500. /*
  39501. ** The Pager.eLock variable is almost always set to one of the
  39502. ** following locking-states, according to the lock currently held on
  39503. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39504. ** This variable is kept up to date as locks are taken and released by
  39505. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  39506. **
  39507. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  39508. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  39509. ** the operation was successful. In these circumstances pagerLockDb() and
  39510. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  39511. ** when unlocking the file, and only updated when locking the file if the
  39512. ** VFS call is successful. This way, the Pager.eLock variable may be set
  39513. ** to a less exclusive (lower) value than the lock that is actually held
  39514. ** at the system level, but it is never set to a more exclusive value.
  39515. **
  39516. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  39517. ** be a few redundant xLock() calls or a lock may be held for longer than
  39518. ** required, but nothing really goes wrong.
  39519. **
  39520. ** The exception is when the database file is unlocked as the pager moves
  39521. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  39522. ** in the file-system that needs to be rolled back (as part of a OPEN->SHARED
  39523. ** transition, by the same pager or any other). If the call to xUnlock()
  39524. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  39525. ** can confuse the call to xCheckReservedLock() call made later as part
  39526. ** of hot-journal detection.
  39527. **
  39528. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  39529. ** lock held by this process or any others". So xCheckReservedLock may
  39530. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  39531. ** doesn't know it because of a previous error in xUnlock). If this happens
  39532. ** a hot-journal may be mistaken for a journal being created by an active
  39533. ** transaction in another process, causing SQLite to read from the database
  39534. ** without rolling it back.
  39535. **
  39536. ** To work around this, if a call to xUnlock() fails when unlocking the
  39537. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  39538. ** is only changed back to a real locking state after a successful call
  39539. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  39540. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  39541. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  39542. ** lock on the database file before attempting to roll it back. See function
  39543. ** PagerSharedLock() for more detail.
  39544. **
  39545. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  39546. ** PAGER_OPEN state.
  39547. */
  39548. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  39549. /*
  39550. ** A macro used for invoking the codec if there is one
  39551. */
  39552. #ifdef SQLITE_HAS_CODEC
  39553. # define CODEC1(P,D,N,X,E) \
  39554. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  39555. # define CODEC2(P,D,N,X,E,O) \
  39556. if( P->xCodec==0 ){ O=(char*)D; }else \
  39557. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  39558. #else
  39559. # define CODEC1(P,D,N,X,E) /* NO-OP */
  39560. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  39561. #endif
  39562. /*
  39563. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  39564. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  39565. ** This could conceivably cause corruption following a power failure on
  39566. ** such a system. This is currently an undocumented limit.
  39567. */
  39568. #define MAX_SECTOR_SIZE 0x10000
  39569. /*
  39570. ** An instance of the following structure is allocated for each active
  39571. ** savepoint and statement transaction in the system. All such structures
  39572. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  39573. ** resized using sqlite3Realloc().
  39574. **
  39575. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  39576. ** set to 0. If a journal-header is written into the main journal while
  39577. ** the savepoint is active, then iHdrOffset is set to the byte offset
  39578. ** immediately following the last journal record written into the main
  39579. ** journal before the journal-header. This is required during savepoint
  39580. ** rollback (see pagerPlaybackSavepoint()).
  39581. */
  39582. typedef struct PagerSavepoint PagerSavepoint;
  39583. struct PagerSavepoint {
  39584. i64 iOffset; /* Starting offset in main journal */
  39585. i64 iHdrOffset; /* See above */
  39586. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  39587. Pgno nOrig; /* Original number of pages in file */
  39588. Pgno iSubRec; /* Index of first record in sub-journal */
  39589. #ifndef SQLITE_OMIT_WAL
  39590. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  39591. #endif
  39592. };
  39593. /*
  39594. ** Bits of the Pager.doNotSpill flag. See further description below.
  39595. */
  39596. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  39597. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  39598. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  39599. /*
  39600. ** A open page cache is an instance of struct Pager. A description of
  39601. ** some of the more important member variables follows:
  39602. **
  39603. ** eState
  39604. **
  39605. ** The current 'state' of the pager object. See the comment and state
  39606. ** diagram above for a description of the pager state.
  39607. **
  39608. ** eLock
  39609. **
  39610. ** For a real on-disk database, the current lock held on the database file -
  39611. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  39612. **
  39613. ** For a temporary or in-memory database (neither of which require any
  39614. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  39615. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  39616. ** logic into thinking that it already has all the locks it will ever
  39617. ** need (and no reason to release them).
  39618. **
  39619. ** In some (obscure) circumstances, this variable may also be set to
  39620. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  39621. ** details.
  39622. **
  39623. ** changeCountDone
  39624. **
  39625. ** This boolean variable is used to make sure that the change-counter
  39626. ** (the 4-byte header field at byte offset 24 of the database file) is
  39627. ** not updated more often than necessary.
  39628. **
  39629. ** It is set to true when the change-counter field is updated, which
  39630. ** can only happen if an exclusive lock is held on the database file.
  39631. ** It is cleared (set to false) whenever an exclusive lock is
  39632. ** relinquished on the database file. Each time a transaction is committed,
  39633. ** The changeCountDone flag is inspected. If it is true, the work of
  39634. ** updating the change-counter is omitted for the current transaction.
  39635. **
  39636. ** This mechanism means that when running in exclusive mode, a connection
  39637. ** need only update the change-counter once, for the first transaction
  39638. ** committed.
  39639. **
  39640. ** setMaster
  39641. **
  39642. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  39643. ** (or may not) specify a master-journal name to be written into the
  39644. ** journal file before it is synced to disk.
  39645. **
  39646. ** Whether or not a journal file contains a master-journal pointer affects
  39647. ** the way in which the journal file is finalized after the transaction is
  39648. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  39649. ** If a journal file does not contain a master-journal pointer, it is
  39650. ** finalized by overwriting the first journal header with zeroes. If
  39651. ** it does contain a master-journal pointer the journal file is finalized
  39652. ** by truncating it to zero bytes, just as if the connection were
  39653. ** running in "journal_mode=truncate" mode.
  39654. **
  39655. ** Journal files that contain master journal pointers cannot be finalized
  39656. ** simply by overwriting the first journal-header with zeroes, as the
  39657. ** master journal pointer could interfere with hot-journal rollback of any
  39658. ** subsequently interrupted transaction that reuses the journal file.
  39659. **
  39660. ** The flag is cleared as soon as the journal file is finalized (either
  39661. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  39662. ** journal file from being successfully finalized, the setMaster flag
  39663. ** is cleared anyway (and the pager will move to ERROR state).
  39664. **
  39665. ** doNotSpill
  39666. **
  39667. ** This variables control the behavior of cache-spills (calls made by
  39668. ** the pcache module to the pagerStress() routine to write cached data
  39669. ** to the file-system in order to free up memory).
  39670. **
  39671. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  39672. ** writing to the database from pagerStress() is disabled altogether.
  39673. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  39674. ** comes up during savepoint rollback that requires the pcache module
  39675. ** to allocate a new page to prevent the journal file from being written
  39676. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  39677. ** case is a user preference.
  39678. **
  39679. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  39680. ** is permitted, but syncing the journal file is not. This flag is set
  39681. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  39682. ** the database page-size in order to prevent a journal sync from happening
  39683. ** in between the journalling of two pages on the same sector.
  39684. **
  39685. ** subjInMemory
  39686. **
  39687. ** This is a boolean variable. If true, then any required sub-journal
  39688. ** is opened as an in-memory journal file. If false, then in-memory
  39689. ** sub-journals are only used for in-memory pager files.
  39690. **
  39691. ** This variable is updated by the upper layer each time a new
  39692. ** write-transaction is opened.
  39693. **
  39694. ** dbSize, dbOrigSize, dbFileSize
  39695. **
  39696. ** Variable dbSize is set to the number of pages in the database file.
  39697. ** It is valid in PAGER_READER and higher states (all states except for
  39698. ** OPEN and ERROR).
  39699. **
  39700. ** dbSize is set based on the size of the database file, which may be
  39701. ** larger than the size of the database (the value stored at offset
  39702. ** 28 of the database header by the btree). If the size of the file
  39703. ** is not an integer multiple of the page-size, the value stored in
  39704. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  39705. ** Except, any file that is greater than 0 bytes in size is considered
  39706. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  39707. ** to dbSize==1).
  39708. **
  39709. ** During a write-transaction, if pages with page-numbers greater than
  39710. ** dbSize are modified in the cache, dbSize is updated accordingly.
  39711. ** Similarly, if the database is truncated using PagerTruncateImage(),
  39712. ** dbSize is updated.
  39713. **
  39714. ** Variables dbOrigSize and dbFileSize are valid in states
  39715. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  39716. ** variable at the start of the transaction. It is used during rollback,
  39717. ** and to determine whether or not pages need to be journalled before
  39718. ** being modified.
  39719. **
  39720. ** Throughout a write-transaction, dbFileSize contains the size of
  39721. ** the file on disk in pages. It is set to a copy of dbSize when the
  39722. ** write-transaction is first opened, and updated when VFS calls are made
  39723. ** to write or truncate the database file on disk.
  39724. **
  39725. ** The only reason the dbFileSize variable is required is to suppress
  39726. ** unnecessary calls to xTruncate() after committing a transaction. If,
  39727. ** when a transaction is committed, the dbFileSize variable indicates
  39728. ** that the database file is larger than the database image (Pager.dbSize),
  39729. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  39730. ** to measure the database file on disk, and then truncates it if required.
  39731. ** dbFileSize is not used when rolling back a transaction. In this case
  39732. ** pager_truncate() is called unconditionally (which means there may be
  39733. ** a call to xFilesize() that is not strictly required). In either case,
  39734. ** pager_truncate() may cause the file to become smaller or larger.
  39735. **
  39736. ** dbHintSize
  39737. **
  39738. ** The dbHintSize variable is used to limit the number of calls made to
  39739. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  39740. **
  39741. ** dbHintSize is set to a copy of the dbSize variable when a
  39742. ** write-transaction is opened (at the same time as dbFileSize and
  39743. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  39744. ** dbHintSize is increased to the number of pages that correspond to the
  39745. ** size-hint passed to the method call. See pager_write_pagelist() for
  39746. ** details.
  39747. **
  39748. ** errCode
  39749. **
  39750. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  39751. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  39752. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  39753. ** sub-codes.
  39754. */
  39755. struct Pager {
  39756. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  39757. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  39758. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  39759. u8 useJournal; /* Use a rollback journal on this file */
  39760. u8 noSync; /* Do not sync the journal if true */
  39761. u8 fullSync; /* Do extra syncs of the journal for robustness */
  39762. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  39763. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  39764. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  39765. u8 tempFile; /* zFilename is a temporary file */
  39766. u8 readOnly; /* True for a read-only database */
  39767. u8 memDb; /* True to inhibit all file I/O */
  39768. /**************************************************************************
  39769. ** The following block contains those class members that change during
  39770. ** routine opertion. Class members not in this block are either fixed
  39771. ** when the pager is first created or else only change when there is a
  39772. ** significant mode change (such as changing the page_size, locking_mode,
  39773. ** or the journal_mode). From another view, these class members describe
  39774. ** the "state" of the pager, while other class members describe the
  39775. ** "configuration" of the pager.
  39776. */
  39777. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  39778. u8 eLock; /* Current lock held on database file */
  39779. u8 changeCountDone; /* Set after incrementing the change-counter */
  39780. u8 setMaster; /* True if a m-j name has been written to jrnl */
  39781. u8 doNotSpill; /* Do not spill the cache when non-zero */
  39782. u8 subjInMemory; /* True to use in-memory sub-journals */
  39783. Pgno dbSize; /* Number of pages in the database */
  39784. Pgno dbOrigSize; /* dbSize before the current transaction */
  39785. Pgno dbFileSize; /* Number of pages in the database file */
  39786. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  39787. int errCode; /* One of several kinds of errors */
  39788. int nRec; /* Pages journalled since last j-header written */
  39789. u32 cksumInit; /* Quasi-random value added to every checksum */
  39790. u32 nSubRec; /* Number of records written to sub-journal */
  39791. Bitvec *pInJournal; /* One bit for each page in the database file */
  39792. sqlite3_file *fd; /* File descriptor for database */
  39793. sqlite3_file *jfd; /* File descriptor for main journal */
  39794. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  39795. i64 journalOff; /* Current write offset in the journal file */
  39796. i64 journalHdr; /* Byte offset to previous journal header */
  39797. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  39798. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  39799. int nSavepoint; /* Number of elements in aSavepoint[] */
  39800. char dbFileVers[16]; /* Changes whenever database file changes */
  39801. u8 bUseFetch; /* True to use xFetch() */
  39802. int nMmapOut; /* Number of mmap pages currently outstanding */
  39803. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  39804. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  39805. /*
  39806. ** End of the routinely-changing class members
  39807. ***************************************************************************/
  39808. u16 nExtra; /* Add this many bytes to each in-memory page */
  39809. i16 nReserve; /* Number of unused bytes at end of each page */
  39810. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  39811. u32 sectorSize; /* Assumed sector size during rollback */
  39812. int pageSize; /* Number of bytes in a page */
  39813. Pgno mxPgno; /* Maximum allowed size of the database */
  39814. i64 journalSizeLimit; /* Size limit for persistent journal files */
  39815. char *zFilename; /* Name of the database file */
  39816. char *zJournal; /* Name of the journal file */
  39817. int (*xBusyHandler)(void*); /* Function to call when busy */
  39818. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  39819. int aStat[3]; /* Total cache hits, misses and writes */
  39820. #ifdef SQLITE_TEST
  39821. int nRead; /* Database pages read */
  39822. #endif
  39823. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  39824. #ifdef SQLITE_HAS_CODEC
  39825. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  39826. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  39827. void (*xCodecFree)(void*); /* Destructor for the codec */
  39828. void *pCodec; /* First argument to xCodec... methods */
  39829. #endif
  39830. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  39831. PCache *pPCache; /* Pointer to page cache object */
  39832. #ifndef SQLITE_OMIT_WAL
  39833. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  39834. char *zWal; /* File name for write-ahead log */
  39835. #endif
  39836. };
  39837. /*
  39838. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  39839. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  39840. ** or CACHE_WRITE to sqlite3_db_status().
  39841. */
  39842. #define PAGER_STAT_HIT 0
  39843. #define PAGER_STAT_MISS 1
  39844. #define PAGER_STAT_WRITE 2
  39845. /*
  39846. ** The following global variables hold counters used for
  39847. ** testing purposes only. These variables do not exist in
  39848. ** a non-testing build. These variables are not thread-safe.
  39849. */
  39850. #ifdef SQLITE_TEST
  39851. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  39852. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  39853. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  39854. # define PAGER_INCR(v) v++
  39855. #else
  39856. # define PAGER_INCR(v)
  39857. #endif
  39858. /*
  39859. ** Journal files begin with the following magic string. The data
  39860. ** was obtained from /dev/random. It is used only as a sanity check.
  39861. **
  39862. ** Since version 2.8.0, the journal format contains additional sanity
  39863. ** checking information. If the power fails while the journal is being
  39864. ** written, semi-random garbage data might appear in the journal
  39865. ** file after power is restored. If an attempt is then made
  39866. ** to roll the journal back, the database could be corrupted. The additional
  39867. ** sanity checking data is an attempt to discover the garbage in the
  39868. ** journal and ignore it.
  39869. **
  39870. ** The sanity checking information for the new journal format consists
  39871. ** of a 32-bit checksum on each page of data. The checksum covers both
  39872. ** the page number and the pPager->pageSize bytes of data for the page.
  39873. ** This cksum is initialized to a 32-bit random value that appears in the
  39874. ** journal file right after the header. The random initializer is important,
  39875. ** because garbage data that appears at the end of a journal is likely
  39876. ** data that was once in other files that have now been deleted. If the
  39877. ** garbage data came from an obsolete journal file, the checksums might
  39878. ** be correct. But by initializing the checksum to random value which
  39879. ** is different for every journal, we minimize that risk.
  39880. */
  39881. static const unsigned char aJournalMagic[] = {
  39882. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  39883. };
  39884. /*
  39885. ** The size of the of each page record in the journal is given by
  39886. ** the following macro.
  39887. */
  39888. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  39889. /*
  39890. ** The journal header size for this pager. This is usually the same
  39891. ** size as a single disk sector. See also setSectorSize().
  39892. */
  39893. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  39894. /*
  39895. ** The macro MEMDB is true if we are dealing with an in-memory database.
  39896. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  39897. ** the value of MEMDB will be a constant and the compiler will optimize
  39898. ** out code that would never execute.
  39899. */
  39900. #ifdef SQLITE_OMIT_MEMORYDB
  39901. # define MEMDB 0
  39902. #else
  39903. # define MEMDB pPager->memDb
  39904. #endif
  39905. /*
  39906. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  39907. ** interfaces to access the database using memory-mapped I/O.
  39908. */
  39909. #if SQLITE_MAX_MMAP_SIZE>0
  39910. # define USEFETCH(x) ((x)->bUseFetch)
  39911. #else
  39912. # define USEFETCH(x) 0
  39913. #endif
  39914. /*
  39915. ** The maximum legal page number is (2^31 - 1).
  39916. */
  39917. #define PAGER_MAX_PGNO 2147483647
  39918. /*
  39919. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  39920. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  39921. **
  39922. ** This is so that expressions can be written as:
  39923. **
  39924. ** if( isOpen(pPager->jfd) ){ ...
  39925. **
  39926. ** instead of
  39927. **
  39928. ** if( pPager->jfd->pMethods ){ ...
  39929. */
  39930. #define isOpen(pFd) ((pFd)->pMethods)
  39931. /*
  39932. ** Return true if this pager uses a write-ahead log instead of the usual
  39933. ** rollback journal. Otherwise false.
  39934. */
  39935. #ifndef SQLITE_OMIT_WAL
  39936. static int pagerUseWal(Pager *pPager){
  39937. return (pPager->pWal!=0);
  39938. }
  39939. #else
  39940. # define pagerUseWal(x) 0
  39941. # define pagerRollbackWal(x) 0
  39942. # define pagerWalFrames(v,w,x,y) 0
  39943. # define pagerOpenWalIfPresent(z) SQLITE_OK
  39944. # define pagerBeginReadTransaction(z) SQLITE_OK
  39945. #endif
  39946. #ifndef NDEBUG
  39947. /*
  39948. ** Usage:
  39949. **
  39950. ** assert( assert_pager_state(pPager) );
  39951. **
  39952. ** This function runs many asserts to try to find inconsistencies in
  39953. ** the internal state of the Pager object.
  39954. */
  39955. static int assert_pager_state(Pager *p){
  39956. Pager *pPager = p;
  39957. /* State must be valid. */
  39958. assert( p->eState==PAGER_OPEN
  39959. || p->eState==PAGER_READER
  39960. || p->eState==PAGER_WRITER_LOCKED
  39961. || p->eState==PAGER_WRITER_CACHEMOD
  39962. || p->eState==PAGER_WRITER_DBMOD
  39963. || p->eState==PAGER_WRITER_FINISHED
  39964. || p->eState==PAGER_ERROR
  39965. );
  39966. /* Regardless of the current state, a temp-file connection always behaves
  39967. ** as if it has an exclusive lock on the database file. It never updates
  39968. ** the change-counter field, so the changeCountDone flag is always set.
  39969. */
  39970. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  39971. assert( p->tempFile==0 || pPager->changeCountDone );
  39972. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  39973. ** And if the journal-mode is "OFF", the journal file must not be open.
  39974. */
  39975. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  39976. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  39977. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  39978. ** this means an in-memory pager performs no IO at all, it cannot encounter
  39979. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  39980. ** a journal file. (although the in-memory journal implementation may
  39981. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  39982. ** is therefore not possible for an in-memory pager to enter the ERROR
  39983. ** state.
  39984. */
  39985. if( MEMDB ){
  39986. assert( p->noSync );
  39987. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  39988. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  39989. );
  39990. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  39991. assert( pagerUseWal(p)==0 );
  39992. }
  39993. /* If changeCountDone is set, a RESERVED lock or greater must be held
  39994. ** on the file.
  39995. */
  39996. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  39997. assert( p->eLock!=PENDING_LOCK );
  39998. switch( p->eState ){
  39999. case PAGER_OPEN:
  40000. assert( !MEMDB );
  40001. assert( pPager->errCode==SQLITE_OK );
  40002. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  40003. break;
  40004. case PAGER_READER:
  40005. assert( pPager->errCode==SQLITE_OK );
  40006. assert( p->eLock!=UNKNOWN_LOCK );
  40007. assert( p->eLock>=SHARED_LOCK );
  40008. break;
  40009. case PAGER_WRITER_LOCKED:
  40010. assert( p->eLock!=UNKNOWN_LOCK );
  40011. assert( pPager->errCode==SQLITE_OK );
  40012. if( !pagerUseWal(pPager) ){
  40013. assert( p->eLock>=RESERVED_LOCK );
  40014. }
  40015. assert( pPager->dbSize==pPager->dbOrigSize );
  40016. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40017. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40018. assert( pPager->setMaster==0 );
  40019. break;
  40020. case PAGER_WRITER_CACHEMOD:
  40021. assert( p->eLock!=UNKNOWN_LOCK );
  40022. assert( pPager->errCode==SQLITE_OK );
  40023. if( !pagerUseWal(pPager) ){
  40024. /* It is possible that if journal_mode=wal here that neither the
  40025. ** journal file nor the WAL file are open. This happens during
  40026. ** a rollback transaction that switches from journal_mode=off
  40027. ** to journal_mode=wal.
  40028. */
  40029. assert( p->eLock>=RESERVED_LOCK );
  40030. assert( isOpen(p->jfd)
  40031. || p->journalMode==PAGER_JOURNALMODE_OFF
  40032. || p->journalMode==PAGER_JOURNALMODE_WAL
  40033. );
  40034. }
  40035. assert( pPager->dbOrigSize==pPager->dbFileSize );
  40036. assert( pPager->dbOrigSize==pPager->dbHintSize );
  40037. break;
  40038. case PAGER_WRITER_DBMOD:
  40039. assert( p->eLock==EXCLUSIVE_LOCK );
  40040. assert( pPager->errCode==SQLITE_OK );
  40041. assert( !pagerUseWal(pPager) );
  40042. assert( p->eLock>=EXCLUSIVE_LOCK );
  40043. assert( isOpen(p->jfd)
  40044. || p->journalMode==PAGER_JOURNALMODE_OFF
  40045. || p->journalMode==PAGER_JOURNALMODE_WAL
  40046. );
  40047. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  40048. break;
  40049. case PAGER_WRITER_FINISHED:
  40050. assert( p->eLock==EXCLUSIVE_LOCK );
  40051. assert( pPager->errCode==SQLITE_OK );
  40052. assert( !pagerUseWal(pPager) );
  40053. assert( isOpen(p->jfd)
  40054. || p->journalMode==PAGER_JOURNALMODE_OFF
  40055. || p->journalMode==PAGER_JOURNALMODE_WAL
  40056. );
  40057. break;
  40058. case PAGER_ERROR:
  40059. /* There must be at least one outstanding reference to the pager if
  40060. ** in ERROR state. Otherwise the pager should have already dropped
  40061. ** back to OPEN state.
  40062. */
  40063. assert( pPager->errCode!=SQLITE_OK );
  40064. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  40065. break;
  40066. }
  40067. return 1;
  40068. }
  40069. #endif /* ifndef NDEBUG */
  40070. #ifdef SQLITE_DEBUG
  40071. /*
  40072. ** Return a pointer to a human readable string in a static buffer
  40073. ** containing the state of the Pager object passed as an argument. This
  40074. ** is intended to be used within debuggers. For example, as an alternative
  40075. ** to "print *pPager" in gdb:
  40076. **
  40077. ** (gdb) printf "%s", print_pager_state(pPager)
  40078. */
  40079. static char *print_pager_state(Pager *p){
  40080. static char zRet[1024];
  40081. sqlite3_snprintf(1024, zRet,
  40082. "Filename: %s\n"
  40083. "State: %s errCode=%d\n"
  40084. "Lock: %s\n"
  40085. "Locking mode: locking_mode=%s\n"
  40086. "Journal mode: journal_mode=%s\n"
  40087. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  40088. "Journal: journalOff=%lld journalHdr=%lld\n"
  40089. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  40090. , p->zFilename
  40091. , p->eState==PAGER_OPEN ? "OPEN" :
  40092. p->eState==PAGER_READER ? "READER" :
  40093. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  40094. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  40095. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  40096. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  40097. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  40098. , (int)p->errCode
  40099. , p->eLock==NO_LOCK ? "NO_LOCK" :
  40100. p->eLock==RESERVED_LOCK ? "RESERVED" :
  40101. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  40102. p->eLock==SHARED_LOCK ? "SHARED" :
  40103. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  40104. , p->exclusiveMode ? "exclusive" : "normal"
  40105. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  40106. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  40107. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  40108. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  40109. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  40110. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  40111. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  40112. , p->journalOff, p->journalHdr
  40113. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  40114. );
  40115. return zRet;
  40116. }
  40117. #endif
  40118. /*
  40119. ** Return true if it is necessary to write page *pPg into the sub-journal.
  40120. ** A page needs to be written into the sub-journal if there exists one
  40121. ** or more open savepoints for which:
  40122. **
  40123. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  40124. ** * The bit corresponding to the page-number is not set in
  40125. ** PagerSavepoint.pInSavepoint.
  40126. */
  40127. static int subjRequiresPage(PgHdr *pPg){
  40128. Pager *pPager = pPg->pPager;
  40129. PagerSavepoint *p;
  40130. Pgno pgno;
  40131. int i;
  40132. if( pPager->nSavepoint ){
  40133. pgno = pPg->pgno;
  40134. for(i=0; i<pPager->nSavepoint; i++){
  40135. p = &pPager->aSavepoint[i];
  40136. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  40137. return 1;
  40138. }
  40139. }
  40140. }
  40141. return 0;
  40142. }
  40143. /*
  40144. ** Return true if the page is already in the journal file.
  40145. */
  40146. static int pageInJournal(PgHdr *pPg){
  40147. return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
  40148. }
  40149. /*
  40150. ** Read a 32-bit integer from the given file descriptor. Store the integer
  40151. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  40152. ** error code is something goes wrong.
  40153. **
  40154. ** All values are stored on disk as big-endian.
  40155. */
  40156. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  40157. unsigned char ac[4];
  40158. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  40159. if( rc==SQLITE_OK ){
  40160. *pRes = sqlite3Get4byte(ac);
  40161. }
  40162. return rc;
  40163. }
  40164. /*
  40165. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  40166. */
  40167. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  40168. /*
  40169. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  40170. ** on success or an error code is something goes wrong.
  40171. */
  40172. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  40173. char ac[4];
  40174. put32bits(ac, val);
  40175. return sqlite3OsWrite(fd, ac, 4, offset);
  40176. }
  40177. /*
  40178. ** Unlock the database file to level eLock, which must be either NO_LOCK
  40179. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  40180. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  40181. **
  40182. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40183. ** called, do not modify it. See the comment above the #define of
  40184. ** UNKNOWN_LOCK for an explanation of this.
  40185. */
  40186. static int pagerUnlockDb(Pager *pPager, int eLock){
  40187. int rc = SQLITE_OK;
  40188. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  40189. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  40190. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  40191. if( isOpen(pPager->fd) ){
  40192. assert( pPager->eLock>=eLock );
  40193. rc = sqlite3OsUnlock(pPager->fd, eLock);
  40194. if( pPager->eLock!=UNKNOWN_LOCK ){
  40195. pPager->eLock = (u8)eLock;
  40196. }
  40197. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  40198. }
  40199. return rc;
  40200. }
  40201. /*
  40202. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  40203. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  40204. ** Pager.eLock variable to the new locking state.
  40205. **
  40206. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  40207. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  40208. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  40209. ** of this.
  40210. */
  40211. static int pagerLockDb(Pager *pPager, int eLock){
  40212. int rc = SQLITE_OK;
  40213. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  40214. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  40215. rc = sqlite3OsLock(pPager->fd, eLock);
  40216. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  40217. pPager->eLock = (u8)eLock;
  40218. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  40219. }
  40220. }
  40221. return rc;
  40222. }
  40223. /*
  40224. ** This function determines whether or not the atomic-write optimization
  40225. ** can be used with this pager. The optimization can be used if:
  40226. **
  40227. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  40228. ** a database page may be written atomically, and
  40229. ** (b) the value returned by OsSectorSize() is less than or equal
  40230. ** to the page size.
  40231. **
  40232. ** The optimization is also always enabled for temporary files. It is
  40233. ** an error to call this function if pPager is opened on an in-memory
  40234. ** database.
  40235. **
  40236. ** If the optimization cannot be used, 0 is returned. If it can be used,
  40237. ** then the value returned is the size of the journal file when it
  40238. ** contains rollback data for exactly one page.
  40239. */
  40240. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  40241. static int jrnlBufferSize(Pager *pPager){
  40242. assert( !MEMDB );
  40243. if( !pPager->tempFile ){
  40244. int dc; /* Device characteristics */
  40245. int nSector; /* Sector size */
  40246. int szPage; /* Page size */
  40247. assert( isOpen(pPager->fd) );
  40248. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  40249. nSector = pPager->sectorSize;
  40250. szPage = pPager->pageSize;
  40251. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  40252. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  40253. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  40254. return 0;
  40255. }
  40256. }
  40257. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  40258. }
  40259. #endif
  40260. /*
  40261. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  40262. ** on the cache using a hash function. This is used for testing
  40263. ** and debugging only.
  40264. */
  40265. #ifdef SQLITE_CHECK_PAGES
  40266. /*
  40267. ** Return a 32-bit hash of the page data for pPage.
  40268. */
  40269. static u32 pager_datahash(int nByte, unsigned char *pData){
  40270. u32 hash = 0;
  40271. int i;
  40272. for(i=0; i<nByte; i++){
  40273. hash = (hash*1039) + pData[i];
  40274. }
  40275. return hash;
  40276. }
  40277. static u32 pager_pagehash(PgHdr *pPage){
  40278. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  40279. }
  40280. static void pager_set_pagehash(PgHdr *pPage){
  40281. pPage->pageHash = pager_pagehash(pPage);
  40282. }
  40283. /*
  40284. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  40285. ** is defined, and NDEBUG is not defined, an assert() statement checks
  40286. ** that the page is either dirty or still matches the calculated page-hash.
  40287. */
  40288. #define CHECK_PAGE(x) checkPage(x)
  40289. static void checkPage(PgHdr *pPg){
  40290. Pager *pPager = pPg->pPager;
  40291. assert( pPager->eState!=PAGER_ERROR );
  40292. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  40293. }
  40294. #else
  40295. #define pager_datahash(X,Y) 0
  40296. #define pager_pagehash(X) 0
  40297. #define pager_set_pagehash(X)
  40298. #define CHECK_PAGE(x)
  40299. #endif /* SQLITE_CHECK_PAGES */
  40300. /*
  40301. ** When this is called the journal file for pager pPager must be open.
  40302. ** This function attempts to read a master journal file name from the
  40303. ** end of the file and, if successful, copies it into memory supplied
  40304. ** by the caller. See comments above writeMasterJournal() for the format
  40305. ** used to store a master journal file name at the end of a journal file.
  40306. **
  40307. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  40308. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  40309. ** enough space to write the master journal name). If the master journal
  40310. ** name in the journal is longer than nMaster bytes (including a
  40311. ** nul-terminator), then this is handled as if no master journal name
  40312. ** were present in the journal.
  40313. **
  40314. ** If a master journal file name is present at the end of the journal
  40315. ** file, then it is copied into the buffer pointed to by zMaster. A
  40316. ** nul-terminator byte is appended to the buffer following the master
  40317. ** journal file name.
  40318. **
  40319. ** If it is determined that no master journal file name is present
  40320. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  40321. **
  40322. ** If an error occurs while reading from the journal file, an SQLite
  40323. ** error code is returned.
  40324. */
  40325. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  40326. int rc; /* Return code */
  40327. u32 len; /* Length in bytes of master journal name */
  40328. i64 szJ; /* Total size in bytes of journal file pJrnl */
  40329. u32 cksum; /* MJ checksum value read from journal */
  40330. u32 u; /* Unsigned loop counter */
  40331. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40332. zMaster[0] = '\0';
  40333. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  40334. || szJ<16
  40335. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  40336. || len>=nMaster
  40337. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  40338. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  40339. || memcmp(aMagic, aJournalMagic, 8)
  40340. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  40341. ){
  40342. return rc;
  40343. }
  40344. /* See if the checksum matches the master journal name */
  40345. for(u=0; u<len; u++){
  40346. cksum -= zMaster[u];
  40347. }
  40348. if( cksum ){
  40349. /* If the checksum doesn't add up, then one or more of the disk sectors
  40350. ** containing the master journal filename is corrupted. This means
  40351. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  40352. ** master-journal filename.
  40353. */
  40354. len = 0;
  40355. }
  40356. zMaster[len] = '\0';
  40357. return SQLITE_OK;
  40358. }
  40359. /*
  40360. ** Return the offset of the sector boundary at or immediately
  40361. ** following the value in pPager->journalOff, assuming a sector
  40362. ** size of pPager->sectorSize bytes.
  40363. **
  40364. ** i.e for a sector size of 512:
  40365. **
  40366. ** Pager.journalOff Return value
  40367. ** ---------------------------------------
  40368. ** 0 0
  40369. ** 512 512
  40370. ** 100 512
  40371. ** 2000 2048
  40372. **
  40373. */
  40374. static i64 journalHdrOffset(Pager *pPager){
  40375. i64 offset = 0;
  40376. i64 c = pPager->journalOff;
  40377. if( c ){
  40378. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  40379. }
  40380. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  40381. assert( offset>=c );
  40382. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  40383. return offset;
  40384. }
  40385. /*
  40386. ** The journal file must be open when this function is called.
  40387. **
  40388. ** This function is a no-op if the journal file has not been written to
  40389. ** within the current transaction (i.e. if Pager.journalOff==0).
  40390. **
  40391. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  40392. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  40393. ** zero the 28-byte header at the start of the journal file. In either case,
  40394. ** if the pager is not in no-sync mode, sync the journal file immediately
  40395. ** after writing or truncating it.
  40396. **
  40397. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  40398. ** following the truncation or zeroing described above the size of the
  40399. ** journal file in bytes is larger than this value, then truncate the
  40400. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  40401. ** not need to be synced following this operation.
  40402. **
  40403. ** If an IO error occurs, abandon processing and return the IO error code.
  40404. ** Otherwise, return SQLITE_OK.
  40405. */
  40406. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  40407. int rc = SQLITE_OK; /* Return code */
  40408. assert( isOpen(pPager->jfd) );
  40409. if( pPager->journalOff ){
  40410. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  40411. IOTRACE(("JZEROHDR %p\n", pPager))
  40412. if( doTruncate || iLimit==0 ){
  40413. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40414. }else{
  40415. static const char zeroHdr[28] = {0};
  40416. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  40417. }
  40418. if( rc==SQLITE_OK && !pPager->noSync ){
  40419. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  40420. }
  40421. /* At this point the transaction is committed but the write lock
  40422. ** is still held on the file. If there is a size limit configured for
  40423. ** the persistent journal and the journal file currently consumes more
  40424. ** space than that limit allows for, truncate it now. There is no need
  40425. ** to sync the file following this operation.
  40426. */
  40427. if( rc==SQLITE_OK && iLimit>0 ){
  40428. i64 sz;
  40429. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  40430. if( rc==SQLITE_OK && sz>iLimit ){
  40431. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  40432. }
  40433. }
  40434. }
  40435. return rc;
  40436. }
  40437. /*
  40438. ** The journal file must be open when this routine is called. A journal
  40439. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  40440. ** current location.
  40441. **
  40442. ** The format for the journal header is as follows:
  40443. ** - 8 bytes: Magic identifying journal format.
  40444. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  40445. ** - 4 bytes: Random number used for page hash.
  40446. ** - 4 bytes: Initial database page count.
  40447. ** - 4 bytes: Sector size used by the process that wrote this journal.
  40448. ** - 4 bytes: Database page size.
  40449. **
  40450. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  40451. */
  40452. static int writeJournalHdr(Pager *pPager){
  40453. int rc = SQLITE_OK; /* Return code */
  40454. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  40455. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  40456. u32 nWrite; /* Bytes of header sector written */
  40457. int ii; /* Loop counter */
  40458. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40459. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  40460. nHeader = JOURNAL_HDR_SZ(pPager);
  40461. }
  40462. /* If there are active savepoints and any of them were created
  40463. ** since the most recent journal header was written, update the
  40464. ** PagerSavepoint.iHdrOffset fields now.
  40465. */
  40466. for(ii=0; ii<pPager->nSavepoint; ii++){
  40467. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  40468. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  40469. }
  40470. }
  40471. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  40472. /*
  40473. ** Write the nRec Field - the number of page records that follow this
  40474. ** journal header. Normally, zero is written to this value at this time.
  40475. ** After the records are added to the journal (and the journal synced,
  40476. ** if in full-sync mode), the zero is overwritten with the true number
  40477. ** of records (see syncJournal()).
  40478. **
  40479. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  40480. ** reading the journal this value tells SQLite to assume that the
  40481. ** rest of the journal file contains valid page records. This assumption
  40482. ** is dangerous, as if a failure occurred whilst writing to the journal
  40483. ** file it may contain some garbage data. There are two scenarios
  40484. ** where this risk can be ignored:
  40485. **
  40486. ** * When the pager is in no-sync mode. Corruption can follow a
  40487. ** power failure in this case anyway.
  40488. **
  40489. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  40490. ** that garbage data is never appended to the journal file.
  40491. */
  40492. assert( isOpen(pPager->fd) || pPager->noSync );
  40493. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  40494. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  40495. ){
  40496. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  40497. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  40498. }else{
  40499. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  40500. }
  40501. /* The random check-hash initializer */
  40502. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  40503. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  40504. /* The initial database size */
  40505. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  40506. /* The assumed sector size for this process */
  40507. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  40508. /* The page size */
  40509. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  40510. /* Initializing the tail of the buffer is not necessary. Everything
  40511. ** works find if the following memset() is omitted. But initializing
  40512. ** the memory prevents valgrind from complaining, so we are willing to
  40513. ** take the performance hit.
  40514. */
  40515. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  40516. nHeader-(sizeof(aJournalMagic)+20));
  40517. /* In theory, it is only necessary to write the 28 bytes that the
  40518. ** journal header consumes to the journal file here. Then increment the
  40519. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  40520. ** record is written to the following sector (leaving a gap in the file
  40521. ** that will be implicitly filled in by the OS).
  40522. **
  40523. ** However it has been discovered that on some systems this pattern can
  40524. ** be significantly slower than contiguously writing data to the file,
  40525. ** even if that means explicitly writing data to the block of
  40526. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  40527. ** is done.
  40528. **
  40529. ** The loop is required here in case the sector-size is larger than the
  40530. ** database page size. Since the zHeader buffer is only Pager.pageSize
  40531. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  40532. ** to populate the entire journal header sector.
  40533. */
  40534. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  40535. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  40536. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  40537. assert( pPager->journalHdr <= pPager->journalOff );
  40538. pPager->journalOff += nHeader;
  40539. }
  40540. return rc;
  40541. }
  40542. /*
  40543. ** The journal file must be open when this is called. A journal header file
  40544. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  40545. ** file. The current location in the journal file is given by
  40546. ** pPager->journalOff. See comments above function writeJournalHdr() for
  40547. ** a description of the journal header format.
  40548. **
  40549. ** If the header is read successfully, *pNRec is set to the number of
  40550. ** page records following this header and *pDbSize is set to the size of the
  40551. ** database before the transaction began, in pages. Also, pPager->cksumInit
  40552. ** is set to the value read from the journal header. SQLITE_OK is returned
  40553. ** in this case.
  40554. **
  40555. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  40556. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  40557. ** cannot be read from the journal file an error code is returned.
  40558. */
  40559. static int readJournalHdr(
  40560. Pager *pPager, /* Pager object */
  40561. int isHot,
  40562. i64 journalSize, /* Size of the open journal file in bytes */
  40563. u32 *pNRec, /* OUT: Value read from the nRec field */
  40564. u32 *pDbSize /* OUT: Value of original database size field */
  40565. ){
  40566. int rc; /* Return code */
  40567. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  40568. i64 iHdrOff; /* Offset of journal header being read */
  40569. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  40570. /* Advance Pager.journalOff to the start of the next sector. If the
  40571. ** journal file is too small for there to be a header stored at this
  40572. ** point, return SQLITE_DONE.
  40573. */
  40574. pPager->journalOff = journalHdrOffset(pPager);
  40575. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  40576. return SQLITE_DONE;
  40577. }
  40578. iHdrOff = pPager->journalOff;
  40579. /* Read in the first 8 bytes of the journal header. If they do not match
  40580. ** the magic string found at the start of each journal header, return
  40581. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  40582. ** proceed.
  40583. */
  40584. if( isHot || iHdrOff!=pPager->journalHdr ){
  40585. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  40586. if( rc ){
  40587. return rc;
  40588. }
  40589. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  40590. return SQLITE_DONE;
  40591. }
  40592. }
  40593. /* Read the first three 32-bit fields of the journal header: The nRec
  40594. ** field, the checksum-initializer and the database size at the start
  40595. ** of the transaction. Return an error code if anything goes wrong.
  40596. */
  40597. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  40598. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  40599. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  40600. ){
  40601. return rc;
  40602. }
  40603. if( pPager->journalOff==0 ){
  40604. u32 iPageSize; /* Page-size field of journal header */
  40605. u32 iSectorSize; /* Sector-size field of journal header */
  40606. /* Read the page-size and sector-size journal header fields. */
  40607. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  40608. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  40609. ){
  40610. return rc;
  40611. }
  40612. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  40613. ** journal header to zero. In this case, assume that the Pager.pageSize
  40614. ** variable is already set to the correct page size.
  40615. */
  40616. if( iPageSize==0 ){
  40617. iPageSize = pPager->pageSize;
  40618. }
  40619. /* Check that the values read from the page-size and sector-size fields
  40620. ** are within range. To be 'in range', both values need to be a power
  40621. ** of two greater than or equal to 512 or 32, and not greater than their
  40622. ** respective compile time maximum limits.
  40623. */
  40624. if( iPageSize<512 || iSectorSize<32
  40625. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  40626. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  40627. ){
  40628. /* If the either the page-size or sector-size in the journal-header is
  40629. ** invalid, then the process that wrote the journal-header must have
  40630. ** crashed before the header was synced. In this case stop reading
  40631. ** the journal file here.
  40632. */
  40633. return SQLITE_DONE;
  40634. }
  40635. /* Update the page-size to match the value read from the journal.
  40636. ** Use a testcase() macro to make sure that malloc failure within
  40637. ** PagerSetPagesize() is tested.
  40638. */
  40639. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  40640. testcase( rc!=SQLITE_OK );
  40641. /* Update the assumed sector-size to match the value used by
  40642. ** the process that created this journal. If this journal was
  40643. ** created by a process other than this one, then this routine
  40644. ** is being called from within pager_playback(). The local value
  40645. ** of Pager.sectorSize is restored at the end of that routine.
  40646. */
  40647. pPager->sectorSize = iSectorSize;
  40648. }
  40649. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  40650. return rc;
  40651. }
  40652. /*
  40653. ** Write the supplied master journal name into the journal file for pager
  40654. ** pPager at the current location. The master journal name must be the last
  40655. ** thing written to a journal file. If the pager is in full-sync mode, the
  40656. ** journal file descriptor is advanced to the next sector boundary before
  40657. ** anything is written. The format is:
  40658. **
  40659. ** + 4 bytes: PAGER_MJ_PGNO.
  40660. ** + N bytes: Master journal filename in utf-8.
  40661. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  40662. ** + 4 bytes: Master journal name checksum.
  40663. ** + 8 bytes: aJournalMagic[].
  40664. **
  40665. ** The master journal page checksum is the sum of the bytes in the master
  40666. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  40667. **
  40668. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  40669. ** this call is a no-op.
  40670. */
  40671. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  40672. int rc; /* Return code */
  40673. int nMaster; /* Length of string zMaster */
  40674. i64 iHdrOff; /* Offset of header in journal file */
  40675. i64 jrnlSize; /* Size of journal file on disk */
  40676. u32 cksum = 0; /* Checksum of string zMaster */
  40677. assert( pPager->setMaster==0 );
  40678. assert( !pagerUseWal(pPager) );
  40679. if( !zMaster
  40680. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40681. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  40682. ){
  40683. return SQLITE_OK;
  40684. }
  40685. pPager->setMaster = 1;
  40686. assert( isOpen(pPager->jfd) );
  40687. assert( pPager->journalHdr <= pPager->journalOff );
  40688. /* Calculate the length in bytes and the checksum of zMaster */
  40689. for(nMaster=0; zMaster[nMaster]; nMaster++){
  40690. cksum += zMaster[nMaster];
  40691. }
  40692. /* If in full-sync mode, advance to the next disk sector before writing
  40693. ** the master journal name. This is in case the previous page written to
  40694. ** the journal has already been synced.
  40695. */
  40696. if( pPager->fullSync ){
  40697. pPager->journalOff = journalHdrOffset(pPager);
  40698. }
  40699. iHdrOff = pPager->journalOff;
  40700. /* Write the master journal data to the end of the journal file. If
  40701. ** an error occurs, return the error code to the caller.
  40702. */
  40703. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  40704. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  40705. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  40706. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  40707. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  40708. ){
  40709. return rc;
  40710. }
  40711. pPager->journalOff += (nMaster+20);
  40712. /* If the pager is in peristent-journal mode, then the physical
  40713. ** journal-file may extend past the end of the master-journal name
  40714. ** and 8 bytes of magic data just written to the file. This is
  40715. ** dangerous because the code to rollback a hot-journal file
  40716. ** will not be able to find the master-journal name to determine
  40717. ** whether or not the journal is hot.
  40718. **
  40719. ** Easiest thing to do in this scenario is to truncate the journal
  40720. ** file to the required size.
  40721. */
  40722. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  40723. && jrnlSize>pPager->journalOff
  40724. ){
  40725. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  40726. }
  40727. return rc;
  40728. }
  40729. /*
  40730. ** Find a page in the hash table given its page number. Return
  40731. ** a pointer to the page or NULL if the requested page is not
  40732. ** already in memory.
  40733. */
  40734. static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  40735. PgHdr *p; /* Return value */
  40736. /* It is not possible for a call to PcacheFetch() with createFlag==0 to
  40737. ** fail, since no attempt to allocate dynamic memory will be made.
  40738. */
  40739. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
  40740. return p;
  40741. }
  40742. /*
  40743. ** Discard the entire contents of the in-memory page-cache.
  40744. */
  40745. static void pager_reset(Pager *pPager){
  40746. sqlite3BackupRestart(pPager->pBackup);
  40747. sqlite3PcacheClear(pPager->pPCache);
  40748. }
  40749. /*
  40750. ** Free all structures in the Pager.aSavepoint[] array and set both
  40751. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  40752. ** if it is open and the pager is not in exclusive mode.
  40753. */
  40754. static void releaseAllSavepoints(Pager *pPager){
  40755. int ii; /* Iterator for looping through Pager.aSavepoint */
  40756. for(ii=0; ii<pPager->nSavepoint; ii++){
  40757. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  40758. }
  40759. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  40760. sqlite3OsClose(pPager->sjfd);
  40761. }
  40762. sqlite3_free(pPager->aSavepoint);
  40763. pPager->aSavepoint = 0;
  40764. pPager->nSavepoint = 0;
  40765. pPager->nSubRec = 0;
  40766. }
  40767. /*
  40768. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  40769. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  40770. ** or SQLITE_NOMEM if a malloc failure occurs.
  40771. */
  40772. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  40773. int ii; /* Loop counter */
  40774. int rc = SQLITE_OK; /* Result code */
  40775. for(ii=0; ii<pPager->nSavepoint; ii++){
  40776. PagerSavepoint *p = &pPager->aSavepoint[ii];
  40777. if( pgno<=p->nOrig ){
  40778. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  40779. testcase( rc==SQLITE_NOMEM );
  40780. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  40781. }
  40782. }
  40783. return rc;
  40784. }
  40785. /*
  40786. ** This function is a no-op if the pager is in exclusive mode and not
  40787. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  40788. ** state.
  40789. **
  40790. ** If the pager is not in exclusive-access mode, the database file is
  40791. ** completely unlocked. If the file is unlocked and the file-system does
  40792. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  40793. ** closed (if it is open).
  40794. **
  40795. ** If the pager is in ERROR state when this function is called, the
  40796. ** contents of the pager cache are discarded before switching back to
  40797. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  40798. ** or not, any journal file left in the file-system will be treated
  40799. ** as a hot-journal and rolled back the next time a read-transaction
  40800. ** is opened (by this or by any other connection).
  40801. */
  40802. static void pager_unlock(Pager *pPager){
  40803. assert( pPager->eState==PAGER_READER
  40804. || pPager->eState==PAGER_OPEN
  40805. || pPager->eState==PAGER_ERROR
  40806. );
  40807. sqlite3BitvecDestroy(pPager->pInJournal);
  40808. pPager->pInJournal = 0;
  40809. releaseAllSavepoints(pPager);
  40810. if( pagerUseWal(pPager) ){
  40811. assert( !isOpen(pPager->jfd) );
  40812. sqlite3WalEndReadTransaction(pPager->pWal);
  40813. pPager->eState = PAGER_OPEN;
  40814. }else if( !pPager->exclusiveMode ){
  40815. int rc; /* Error code returned by pagerUnlockDb() */
  40816. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  40817. /* If the operating system support deletion of open files, then
  40818. ** close the journal file when dropping the database lock. Otherwise
  40819. ** another connection with journal_mode=delete might delete the file
  40820. ** out from under us.
  40821. */
  40822. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  40823. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  40824. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  40825. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  40826. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  40827. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  40828. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  40829. || 1!=(pPager->journalMode & 5)
  40830. ){
  40831. sqlite3OsClose(pPager->jfd);
  40832. }
  40833. /* If the pager is in the ERROR state and the call to unlock the database
  40834. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  40835. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  40836. ** is necessary.
  40837. */
  40838. rc = pagerUnlockDb(pPager, NO_LOCK);
  40839. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  40840. pPager->eLock = UNKNOWN_LOCK;
  40841. }
  40842. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  40843. ** without clearing the error code. This is intentional - the error
  40844. ** code is cleared and the cache reset in the block below.
  40845. */
  40846. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  40847. pPager->changeCountDone = 0;
  40848. pPager->eState = PAGER_OPEN;
  40849. }
  40850. /* If Pager.errCode is set, the contents of the pager cache cannot be
  40851. ** trusted. Now that there are no outstanding references to the pager,
  40852. ** it can safely move back to PAGER_OPEN state. This happens in both
  40853. ** normal and exclusive-locking mode.
  40854. */
  40855. if( pPager->errCode ){
  40856. assert( !MEMDB );
  40857. pager_reset(pPager);
  40858. pPager->changeCountDone = pPager->tempFile;
  40859. pPager->eState = PAGER_OPEN;
  40860. pPager->errCode = SQLITE_OK;
  40861. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  40862. }
  40863. pPager->journalOff = 0;
  40864. pPager->journalHdr = 0;
  40865. pPager->setMaster = 0;
  40866. }
  40867. /*
  40868. ** This function is called whenever an IOERR or FULL error that requires
  40869. ** the pager to transition into the ERROR state may ahve occurred.
  40870. ** The first argument is a pointer to the pager structure, the second
  40871. ** the error-code about to be returned by a pager API function. The
  40872. ** value returned is a copy of the second argument to this function.
  40873. **
  40874. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  40875. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  40876. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  40877. ** all major API calls on the Pager will immediately return Pager.errCode.
  40878. **
  40879. ** The ERROR state indicates that the contents of the pager-cache
  40880. ** cannot be trusted. This state can be cleared by completely discarding
  40881. ** the contents of the pager-cache. If a transaction was active when
  40882. ** the persistent error occurred, then the rollback journal may need
  40883. ** to be replayed to restore the contents of the database file (as if
  40884. ** it were a hot-journal).
  40885. */
  40886. static int pager_error(Pager *pPager, int rc){
  40887. int rc2 = rc & 0xff;
  40888. assert( rc==SQLITE_OK || !MEMDB );
  40889. assert(
  40890. pPager->errCode==SQLITE_FULL ||
  40891. pPager->errCode==SQLITE_OK ||
  40892. (pPager->errCode & 0xff)==SQLITE_IOERR
  40893. );
  40894. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  40895. pPager->errCode = rc;
  40896. pPager->eState = PAGER_ERROR;
  40897. }
  40898. return rc;
  40899. }
  40900. static int pager_truncate(Pager *pPager, Pgno nPage);
  40901. /*
  40902. ** This routine ends a transaction. A transaction is usually ended by
  40903. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  40904. ** after rollback of a hot-journal, or if an error occurs while opening
  40905. ** the journal file or writing the very first journal-header of a
  40906. ** database transaction.
  40907. **
  40908. ** This routine is never called in PAGER_ERROR state. If it is called
  40909. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  40910. ** exclusive than a RESERVED lock, it is a no-op.
  40911. **
  40912. ** Otherwise, any active savepoints are released.
  40913. **
  40914. ** If the journal file is open, then it is "finalized". Once a journal
  40915. ** file has been finalized it is not possible to use it to roll back a
  40916. ** transaction. Nor will it be considered to be a hot-journal by this
  40917. ** or any other database connection. Exactly how a journal is finalized
  40918. ** depends on whether or not the pager is running in exclusive mode and
  40919. ** the current journal-mode (Pager.journalMode value), as follows:
  40920. **
  40921. ** journalMode==MEMORY
  40922. ** Journal file descriptor is simply closed. This destroys an
  40923. ** in-memory journal.
  40924. **
  40925. ** journalMode==TRUNCATE
  40926. ** Journal file is truncated to zero bytes in size.
  40927. **
  40928. ** journalMode==PERSIST
  40929. ** The first 28 bytes of the journal file are zeroed. This invalidates
  40930. ** the first journal header in the file, and hence the entire journal
  40931. ** file. An invalid journal file cannot be rolled back.
  40932. **
  40933. ** journalMode==DELETE
  40934. ** The journal file is closed and deleted using sqlite3OsDelete().
  40935. **
  40936. ** If the pager is running in exclusive mode, this method of finalizing
  40937. ** the journal file is never used. Instead, if the journalMode is
  40938. ** DELETE and the pager is in exclusive mode, the method described under
  40939. ** journalMode==PERSIST is used instead.
  40940. **
  40941. ** After the journal is finalized, the pager moves to PAGER_READER state.
  40942. ** If running in non-exclusive rollback mode, the lock on the file is
  40943. ** downgraded to a SHARED_LOCK.
  40944. **
  40945. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  40946. ** any of the IO operations to finalize the journal file or unlock the
  40947. ** database then the IO error code is returned to the user. If the
  40948. ** operation to finalize the journal file fails, then the code still
  40949. ** tries to unlock the database file if not in exclusive mode. If the
  40950. ** unlock operation fails as well, then the first error code related
  40951. ** to the first error encountered (the journal finalization one) is
  40952. ** returned.
  40953. */
  40954. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  40955. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  40956. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  40957. /* Do nothing if the pager does not have an open write transaction
  40958. ** or at least a RESERVED lock. This function may be called when there
  40959. ** is no write-transaction active but a RESERVED or greater lock is
  40960. ** held under two circumstances:
  40961. **
  40962. ** 1. After a successful hot-journal rollback, it is called with
  40963. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  40964. **
  40965. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  40966. ** lock switches back to locking_mode=normal and then executes a
  40967. ** read-transaction, this function is called with eState==PAGER_READER
  40968. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  40969. */
  40970. assert( assert_pager_state(pPager) );
  40971. assert( pPager->eState!=PAGER_ERROR );
  40972. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  40973. return SQLITE_OK;
  40974. }
  40975. releaseAllSavepoints(pPager);
  40976. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  40977. if( isOpen(pPager->jfd) ){
  40978. assert( !pagerUseWal(pPager) );
  40979. /* Finalize the journal file. */
  40980. if( sqlite3IsMemJournal(pPager->jfd) ){
  40981. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  40982. sqlite3OsClose(pPager->jfd);
  40983. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  40984. if( pPager->journalOff==0 ){
  40985. rc = SQLITE_OK;
  40986. }else{
  40987. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40988. }
  40989. pPager->journalOff = 0;
  40990. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40991. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  40992. ){
  40993. rc = zeroJournalHdr(pPager, hasMaster);
  40994. pPager->journalOff = 0;
  40995. }else{
  40996. /* This branch may be executed with Pager.journalMode==MEMORY if
  40997. ** a hot-journal was just rolled back. In this case the journal
  40998. ** file should be closed and deleted. If this connection writes to
  40999. ** the database file, it will do so using an in-memory journal.
  41000. */
  41001. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  41002. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  41003. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  41004. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  41005. );
  41006. sqlite3OsClose(pPager->jfd);
  41007. if( bDelete ){
  41008. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  41009. }
  41010. }
  41011. }
  41012. #ifdef SQLITE_CHECK_PAGES
  41013. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  41014. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  41015. PgHdr *p = pager_lookup(pPager, 1);
  41016. if( p ){
  41017. p->pageHash = 0;
  41018. sqlite3PagerUnref(p);
  41019. }
  41020. }
  41021. #endif
  41022. sqlite3BitvecDestroy(pPager->pInJournal);
  41023. pPager->pInJournal = 0;
  41024. pPager->nRec = 0;
  41025. sqlite3PcacheCleanAll(pPager->pPCache);
  41026. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  41027. if( pagerUseWal(pPager) ){
  41028. /* Drop the WAL write-lock, if any. Also, if the connection was in
  41029. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  41030. ** lock held on the database file.
  41031. */
  41032. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  41033. assert( rc2==SQLITE_OK );
  41034. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  41035. /* This branch is taken when committing a transaction in rollback-journal
  41036. ** mode if the database file on disk is larger than the database image.
  41037. ** At this point the journal has been finalized and the transaction
  41038. ** successfully committed, but the EXCLUSIVE lock is still held on the
  41039. ** file. So it is safe to truncate the database file to its minimum
  41040. ** required size. */
  41041. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41042. rc = pager_truncate(pPager, pPager->dbSize);
  41043. }
  41044. if( !pPager->exclusiveMode
  41045. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  41046. ){
  41047. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  41048. pPager->changeCountDone = 0;
  41049. }
  41050. pPager->eState = PAGER_READER;
  41051. pPager->setMaster = 0;
  41052. return (rc==SQLITE_OK?rc2:rc);
  41053. }
  41054. /*
  41055. ** Execute a rollback if a transaction is active and unlock the
  41056. ** database file.
  41057. **
  41058. ** If the pager has already entered the ERROR state, do not attempt
  41059. ** the rollback at this time. Instead, pager_unlock() is called. The
  41060. ** call to pager_unlock() will discard all in-memory pages, unlock
  41061. ** the database file and move the pager back to OPEN state. If this
  41062. ** means that there is a hot-journal left in the file-system, the next
  41063. ** connection to obtain a shared lock on the pager (which may be this one)
  41064. ** will roll it back.
  41065. **
  41066. ** If the pager has not already entered the ERROR state, but an IO or
  41067. ** malloc error occurs during a rollback, then this will itself cause
  41068. ** the pager to enter the ERROR state. Which will be cleared by the
  41069. ** call to pager_unlock(), as described above.
  41070. */
  41071. static void pagerUnlockAndRollback(Pager *pPager){
  41072. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  41073. assert( assert_pager_state(pPager) );
  41074. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  41075. sqlite3BeginBenignMalloc();
  41076. sqlite3PagerRollback(pPager);
  41077. sqlite3EndBenignMalloc();
  41078. }else if( !pPager->exclusiveMode ){
  41079. assert( pPager->eState==PAGER_READER );
  41080. pager_end_transaction(pPager, 0, 0);
  41081. }
  41082. }
  41083. pager_unlock(pPager);
  41084. }
  41085. /*
  41086. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  41087. ** of data. Compute and return a checksum based ont the contents of the
  41088. ** page of data and the current value of pPager->cksumInit.
  41089. **
  41090. ** This is not a real checksum. It is really just the sum of the
  41091. ** random initial value (pPager->cksumInit) and every 200th byte
  41092. ** of the page data, starting with byte offset (pPager->pageSize%200).
  41093. ** Each byte is interpreted as an 8-bit unsigned integer.
  41094. **
  41095. ** Changing the formula used to compute this checksum results in an
  41096. ** incompatible journal file format.
  41097. **
  41098. ** If journal corruption occurs due to a power failure, the most likely
  41099. ** scenario is that one end or the other of the record will be changed.
  41100. ** It is much less likely that the two ends of the journal record will be
  41101. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  41102. ** though fast and simple, catches the mostly likely kind of corruption.
  41103. */
  41104. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  41105. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  41106. int i = pPager->pageSize-200; /* Loop counter */
  41107. while( i>0 ){
  41108. cksum += aData[i];
  41109. i -= 200;
  41110. }
  41111. return cksum;
  41112. }
  41113. /*
  41114. ** Report the current page size and number of reserved bytes back
  41115. ** to the codec.
  41116. */
  41117. #ifdef SQLITE_HAS_CODEC
  41118. static void pagerReportSize(Pager *pPager){
  41119. if( pPager->xCodecSizeChng ){
  41120. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  41121. (int)pPager->nReserve);
  41122. }
  41123. }
  41124. #else
  41125. # define pagerReportSize(X) /* No-op if we do not support a codec */
  41126. #endif
  41127. /*
  41128. ** Read a single page from either the journal file (if isMainJrnl==1) or
  41129. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  41130. ** The page begins at offset *pOffset into the file. The *pOffset
  41131. ** value is increased to the start of the next page in the journal.
  41132. **
  41133. ** The main rollback journal uses checksums - the statement journal does
  41134. ** not.
  41135. **
  41136. ** If the page number of the page record read from the (sub-)journal file
  41137. ** is greater than the current value of Pager.dbSize, then playback is
  41138. ** skipped and SQLITE_OK is returned.
  41139. **
  41140. ** If pDone is not NULL, then it is a record of pages that have already
  41141. ** been played back. If the page at *pOffset has already been played back
  41142. ** (if the corresponding pDone bit is set) then skip the playback.
  41143. ** Make sure the pDone bit corresponding to the *pOffset page is set
  41144. ** prior to returning.
  41145. **
  41146. ** If the page record is successfully read from the (sub-)journal file
  41147. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  41148. ** while reading the record from the (sub-)journal file or while writing
  41149. ** to the database file, then the IO error code is returned. If data
  41150. ** is successfully read from the (sub-)journal file but appears to be
  41151. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  41152. ** two circumstances:
  41153. **
  41154. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  41155. ** * If the record is being rolled back from the main journal file
  41156. ** and the checksum field does not match the record content.
  41157. **
  41158. ** Neither of these two scenarios are possible during a savepoint rollback.
  41159. **
  41160. ** If this is a savepoint rollback, then memory may have to be dynamically
  41161. ** allocated by this function. If this is the case and an allocation fails,
  41162. ** SQLITE_NOMEM is returned.
  41163. */
  41164. static int pager_playback_one_page(
  41165. Pager *pPager, /* The pager being played back */
  41166. i64 *pOffset, /* Offset of record to playback */
  41167. Bitvec *pDone, /* Bitvec of pages already played back */
  41168. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  41169. int isSavepnt /* True for a savepoint rollback */
  41170. ){
  41171. int rc;
  41172. PgHdr *pPg; /* An existing page in the cache */
  41173. Pgno pgno; /* The page number of a page in journal */
  41174. u32 cksum; /* Checksum used for sanity checking */
  41175. char *aData; /* Temporary storage for the page */
  41176. sqlite3_file *jfd; /* The file descriptor for the journal file */
  41177. int isSynced; /* True if journal page is synced */
  41178. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  41179. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  41180. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  41181. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  41182. aData = pPager->pTmpSpace;
  41183. assert( aData ); /* Temp storage must have already been allocated */
  41184. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  41185. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  41186. ** or savepoint rollback done at the request of the caller) or this is
  41187. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  41188. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  41189. ** only reads from the main journal, not the sub-journal.
  41190. */
  41191. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  41192. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  41193. );
  41194. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  41195. /* Read the page number and page data from the journal or sub-journal
  41196. ** file. Return an error code to the caller if an IO error occurs.
  41197. */
  41198. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  41199. rc = read32bits(jfd, *pOffset, &pgno);
  41200. if( rc!=SQLITE_OK ) return rc;
  41201. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  41202. if( rc!=SQLITE_OK ) return rc;
  41203. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  41204. /* Sanity checking on the page. This is more important that I originally
  41205. ** thought. If a power failure occurs while the journal is being written,
  41206. ** it could cause invalid data to be written into the journal. We need to
  41207. ** detect this invalid data (with high probability) and ignore it.
  41208. */
  41209. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  41210. assert( !isSavepnt );
  41211. return SQLITE_DONE;
  41212. }
  41213. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  41214. return SQLITE_OK;
  41215. }
  41216. if( isMainJrnl ){
  41217. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  41218. if( rc ) return rc;
  41219. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  41220. return SQLITE_DONE;
  41221. }
  41222. }
  41223. /* If this page has already been played by before during the current
  41224. ** rollback, then don't bother to play it back again.
  41225. */
  41226. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  41227. return rc;
  41228. }
  41229. /* When playing back page 1, restore the nReserve setting
  41230. */
  41231. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  41232. pPager->nReserve = ((u8*)aData)[20];
  41233. pagerReportSize(pPager);
  41234. }
  41235. /* If the pager is in CACHEMOD state, then there must be a copy of this
  41236. ** page in the pager cache. In this case just update the pager cache,
  41237. ** not the database file. The page is left marked dirty in this case.
  41238. **
  41239. ** An exception to the above rule: If the database is in no-sync mode
  41240. ** and a page is moved during an incremental vacuum then the page may
  41241. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  41242. ** during a Movepage() call, then the page may not be in the cache
  41243. ** either. So the condition described in the above paragraph is not
  41244. ** assert()able.
  41245. **
  41246. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  41247. ** pager cache if it exists and the main file. The page is then marked
  41248. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  41249. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  41250. ** if the pager is in OPEN state.
  41251. **
  41252. ** Ticket #1171: The statement journal might contain page content that is
  41253. ** different from the page content at the start of the transaction.
  41254. ** This occurs when a page is changed prior to the start of a statement
  41255. ** then changed again within the statement. When rolling back such a
  41256. ** statement we must not write to the original database unless we know
  41257. ** for certain that original page contents are synced into the main rollback
  41258. ** journal. Otherwise, a power loss might leave modified data in the
  41259. ** database file without an entry in the rollback journal that can
  41260. ** restore the database to its original form. Two conditions must be
  41261. ** met before writing to the database files. (1) the database must be
  41262. ** locked. (2) we know that the original page content is fully synced
  41263. ** in the main journal either because the page is not in cache or else
  41264. ** the page is marked as needSync==0.
  41265. **
  41266. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  41267. ** is possible to fail a statement on a database that does not yet exist.
  41268. ** Do not attempt to write if database file has never been opened.
  41269. */
  41270. if( pagerUseWal(pPager) ){
  41271. pPg = 0;
  41272. }else{
  41273. pPg = pager_lookup(pPager, pgno);
  41274. }
  41275. assert( pPg || !MEMDB );
  41276. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  41277. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  41278. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  41279. (isMainJrnl?"main-journal":"sub-journal")
  41280. ));
  41281. if( isMainJrnl ){
  41282. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  41283. }else{
  41284. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  41285. }
  41286. if( isOpen(pPager->fd)
  41287. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41288. && isSynced
  41289. ){
  41290. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  41291. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  41292. assert( !pagerUseWal(pPager) );
  41293. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  41294. if( pgno>pPager->dbFileSize ){
  41295. pPager->dbFileSize = pgno;
  41296. }
  41297. if( pPager->pBackup ){
  41298. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  41299. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  41300. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  41301. }
  41302. }else if( !isMainJrnl && pPg==0 ){
  41303. /* If this is a rollback of a savepoint and data was not written to
  41304. ** the database and the page is not in-memory, there is a potential
  41305. ** problem. When the page is next fetched by the b-tree layer, it
  41306. ** will be read from the database file, which may or may not be
  41307. ** current.
  41308. **
  41309. ** There are a couple of different ways this can happen. All are quite
  41310. ** obscure. When running in synchronous mode, this can only happen
  41311. ** if the page is on the free-list at the start of the transaction, then
  41312. ** populated, then moved using sqlite3PagerMovepage().
  41313. **
  41314. ** The solution is to add an in-memory page to the cache containing
  41315. ** the data just read from the sub-journal. Mark the page as dirty
  41316. ** and if the pager requires a journal-sync, then mark the page as
  41317. ** requiring a journal-sync before it is written.
  41318. */
  41319. assert( isSavepnt );
  41320. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  41321. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  41322. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  41323. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  41324. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  41325. if( rc!=SQLITE_OK ) return rc;
  41326. pPg->flags &= ~PGHDR_NEED_READ;
  41327. sqlite3PcacheMakeDirty(pPg);
  41328. }
  41329. if( pPg ){
  41330. /* No page should ever be explicitly rolled back that is in use, except
  41331. ** for page 1 which is held in use in order to keep the lock on the
  41332. ** database active. However such a page may be rolled back as a result
  41333. ** of an internal error resulting in an automatic call to
  41334. ** sqlite3PagerRollback().
  41335. */
  41336. void *pData;
  41337. pData = pPg->pData;
  41338. memcpy(pData, (u8*)aData, pPager->pageSize);
  41339. pPager->xReiniter(pPg);
  41340. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  41341. /* If the contents of this page were just restored from the main
  41342. ** journal file, then its content must be as they were when the
  41343. ** transaction was first opened. In this case we can mark the page
  41344. ** as clean, since there will be no need to write it out to the
  41345. ** database.
  41346. **
  41347. ** There is one exception to this rule. If the page is being rolled
  41348. ** back as part of a savepoint (or statement) rollback from an
  41349. ** unsynced portion of the main journal file, then it is not safe
  41350. ** to mark the page as clean. This is because marking the page as
  41351. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  41352. ** already in the journal file (recorded in Pager.pInJournal) and
  41353. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  41354. ** again within this transaction, it will be marked as dirty but
  41355. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  41356. ** be written out into the database file before its journal file
  41357. ** segment is synced. If a crash occurs during or following this,
  41358. ** database corruption may ensue.
  41359. */
  41360. assert( !pagerUseWal(pPager) );
  41361. sqlite3PcacheMakeClean(pPg);
  41362. }
  41363. pager_set_pagehash(pPg);
  41364. /* If this was page 1, then restore the value of Pager.dbFileVers.
  41365. ** Do this before any decoding. */
  41366. if( pgno==1 ){
  41367. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  41368. }
  41369. /* Decode the page just read from disk */
  41370. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  41371. sqlite3PcacheRelease(pPg);
  41372. }
  41373. return rc;
  41374. }
  41375. /*
  41376. ** Parameter zMaster is the name of a master journal file. A single journal
  41377. ** file that referred to the master journal file has just been rolled back.
  41378. ** This routine checks if it is possible to delete the master journal file,
  41379. ** and does so if it is.
  41380. **
  41381. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  41382. ** available for use within this function.
  41383. **
  41384. ** When a master journal file is created, it is populated with the names
  41385. ** of all of its child journals, one after another, formatted as utf-8
  41386. ** encoded text. The end of each child journal file is marked with a
  41387. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  41388. ** file for a transaction involving two databases might be:
  41389. **
  41390. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  41391. **
  41392. ** A master journal file may only be deleted once all of its child
  41393. ** journals have been rolled back.
  41394. **
  41395. ** This function reads the contents of the master-journal file into
  41396. ** memory and loops through each of the child journal names. For
  41397. ** each child journal, it checks if:
  41398. **
  41399. ** * if the child journal exists, and if so
  41400. ** * if the child journal contains a reference to master journal
  41401. ** file zMaster
  41402. **
  41403. ** If a child journal can be found that matches both of the criteria
  41404. ** above, this function returns without doing anything. Otherwise, if
  41405. ** no such child journal can be found, file zMaster is deleted from
  41406. ** the file-system using sqlite3OsDelete().
  41407. **
  41408. ** If an IO error within this function, an error code is returned. This
  41409. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  41410. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  41411. ** occur, SQLITE_OK is returned.
  41412. **
  41413. ** TODO: This function allocates a single block of memory to load
  41414. ** the entire contents of the master journal file. This could be
  41415. ** a couple of kilobytes or so - potentially larger than the page
  41416. ** size.
  41417. */
  41418. static int pager_delmaster(Pager *pPager, const char *zMaster){
  41419. sqlite3_vfs *pVfs = pPager->pVfs;
  41420. int rc; /* Return code */
  41421. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  41422. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  41423. char *zMasterJournal = 0; /* Contents of master journal file */
  41424. i64 nMasterJournal; /* Size of master journal file */
  41425. char *zJournal; /* Pointer to one journal within MJ file */
  41426. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  41427. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  41428. /* Allocate space for both the pJournal and pMaster file descriptors.
  41429. ** If successful, open the master journal file for reading.
  41430. */
  41431. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  41432. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  41433. if( !pMaster ){
  41434. rc = SQLITE_NOMEM;
  41435. }else{
  41436. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  41437. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  41438. }
  41439. if( rc!=SQLITE_OK ) goto delmaster_out;
  41440. /* Load the entire master journal file into space obtained from
  41441. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  41442. ** sufficient space (in zMasterPtr) to hold the names of master
  41443. ** journal files extracted from regular rollback-journals.
  41444. */
  41445. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  41446. if( rc!=SQLITE_OK ) goto delmaster_out;
  41447. nMasterPtr = pVfs->mxPathname+1;
  41448. zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
  41449. if( !zMasterJournal ){
  41450. rc = SQLITE_NOMEM;
  41451. goto delmaster_out;
  41452. }
  41453. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  41454. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  41455. if( rc!=SQLITE_OK ) goto delmaster_out;
  41456. zMasterJournal[nMasterJournal] = 0;
  41457. zJournal = zMasterJournal;
  41458. while( (zJournal-zMasterJournal)<nMasterJournal ){
  41459. int exists;
  41460. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  41461. if( rc!=SQLITE_OK ){
  41462. goto delmaster_out;
  41463. }
  41464. if( exists ){
  41465. /* One of the journals pointed to by the master journal exists.
  41466. ** Open it and check if it points at the master journal. If
  41467. ** so, return without deleting the master journal file.
  41468. */
  41469. int c;
  41470. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  41471. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  41472. if( rc!=SQLITE_OK ){
  41473. goto delmaster_out;
  41474. }
  41475. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  41476. sqlite3OsClose(pJournal);
  41477. if( rc!=SQLITE_OK ){
  41478. goto delmaster_out;
  41479. }
  41480. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  41481. if( c ){
  41482. /* We have a match. Do not delete the master journal file. */
  41483. goto delmaster_out;
  41484. }
  41485. }
  41486. zJournal += (sqlite3Strlen30(zJournal)+1);
  41487. }
  41488. sqlite3OsClose(pMaster);
  41489. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  41490. delmaster_out:
  41491. sqlite3_free(zMasterJournal);
  41492. if( pMaster ){
  41493. sqlite3OsClose(pMaster);
  41494. assert( !isOpen(pJournal) );
  41495. sqlite3_free(pMaster);
  41496. }
  41497. return rc;
  41498. }
  41499. /*
  41500. ** This function is used to change the actual size of the database
  41501. ** file in the file-system. This only happens when committing a transaction,
  41502. ** or rolling back a transaction (including rolling back a hot-journal).
  41503. **
  41504. ** If the main database file is not open, or the pager is not in either
  41505. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  41506. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  41507. ** If the file on disk is currently larger than nPage pages, then use the VFS
  41508. ** xTruncate() method to truncate it.
  41509. **
  41510. ** Or, it might might be the case that the file on disk is smaller than
  41511. ** nPage pages. Some operating system implementations can get confused if
  41512. ** you try to truncate a file to some size that is larger than it
  41513. ** currently is, so detect this case and write a single zero byte to
  41514. ** the end of the new file instead.
  41515. **
  41516. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  41517. ** the database file, return the error code to the caller.
  41518. */
  41519. static int pager_truncate(Pager *pPager, Pgno nPage){
  41520. int rc = SQLITE_OK;
  41521. assert( pPager->eState!=PAGER_ERROR );
  41522. assert( pPager->eState!=PAGER_READER );
  41523. if( isOpen(pPager->fd)
  41524. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41525. ){
  41526. i64 currentSize, newSize;
  41527. int szPage = pPager->pageSize;
  41528. assert( pPager->eLock==EXCLUSIVE_LOCK );
  41529. /* TODO: Is it safe to use Pager.dbFileSize here? */
  41530. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  41531. newSize = szPage*(i64)nPage;
  41532. if( rc==SQLITE_OK && currentSize!=newSize ){
  41533. if( currentSize>newSize ){
  41534. rc = sqlite3OsTruncate(pPager->fd, newSize);
  41535. }else if( (currentSize+szPage)<=newSize ){
  41536. char *pTmp = pPager->pTmpSpace;
  41537. memset(pTmp, 0, szPage);
  41538. testcase( (newSize-szPage) == currentSize );
  41539. testcase( (newSize-szPage) > currentSize );
  41540. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  41541. }
  41542. if( rc==SQLITE_OK ){
  41543. pPager->dbFileSize = nPage;
  41544. }
  41545. }
  41546. }
  41547. return rc;
  41548. }
  41549. /*
  41550. ** Return a sanitized version of the sector-size of OS file pFile. The
  41551. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  41552. */
  41553. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  41554. int iRet = sqlite3OsSectorSize(pFile);
  41555. if( iRet<32 ){
  41556. iRet = 512;
  41557. }else if( iRet>MAX_SECTOR_SIZE ){
  41558. assert( MAX_SECTOR_SIZE>=512 );
  41559. iRet = MAX_SECTOR_SIZE;
  41560. }
  41561. return iRet;
  41562. }
  41563. /*
  41564. ** Set the value of the Pager.sectorSize variable for the given
  41565. ** pager based on the value returned by the xSectorSize method
  41566. ** of the open database file. The sector size will be used used
  41567. ** to determine the size and alignment of journal header and
  41568. ** master journal pointers within created journal files.
  41569. **
  41570. ** For temporary files the effective sector size is always 512 bytes.
  41571. **
  41572. ** Otherwise, for non-temporary files, the effective sector size is
  41573. ** the value returned by the xSectorSize() method rounded up to 32 if
  41574. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  41575. ** is greater than MAX_SECTOR_SIZE.
  41576. **
  41577. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  41578. ** the effective sector size to its minimum value (512). The purpose of
  41579. ** pPager->sectorSize is to define the "blast radius" of bytes that
  41580. ** might change if a crash occurs while writing to a single byte in
  41581. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  41582. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  41583. ** size. For backwards compatibility of the rollback journal file format,
  41584. ** we cannot reduce the effective sector size below 512.
  41585. */
  41586. static void setSectorSize(Pager *pPager){
  41587. assert( isOpen(pPager->fd) || pPager->tempFile );
  41588. if( pPager->tempFile
  41589. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  41590. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  41591. ){
  41592. /* Sector size doesn't matter for temporary files. Also, the file
  41593. ** may not have been opened yet, in which case the OsSectorSize()
  41594. ** call will segfault. */
  41595. pPager->sectorSize = 512;
  41596. }else{
  41597. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  41598. }
  41599. }
  41600. /*
  41601. ** Playback the journal and thus restore the database file to
  41602. ** the state it was in before we started making changes.
  41603. **
  41604. ** The journal file format is as follows:
  41605. **
  41606. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  41607. ** (2) 4 byte big-endian integer which is the number of valid page records
  41608. ** in the journal. If this value is 0xffffffff, then compute the
  41609. ** number of page records from the journal size.
  41610. ** (3) 4 byte big-endian integer which is the initial value for the
  41611. ** sanity checksum.
  41612. ** (4) 4 byte integer which is the number of pages to truncate the
  41613. ** database to during a rollback.
  41614. ** (5) 4 byte big-endian integer which is the sector size. The header
  41615. ** is this many bytes in size.
  41616. ** (6) 4 byte big-endian integer which is the page size.
  41617. ** (7) zero padding out to the next sector size.
  41618. ** (8) Zero or more pages instances, each as follows:
  41619. ** + 4 byte page number.
  41620. ** + pPager->pageSize bytes of data.
  41621. ** + 4 byte checksum
  41622. **
  41623. ** When we speak of the journal header, we mean the first 7 items above.
  41624. ** Each entry in the journal is an instance of the 8th item.
  41625. **
  41626. ** Call the value from the second bullet "nRec". nRec is the number of
  41627. ** valid page entries in the journal. In most cases, you can compute the
  41628. ** value of nRec from the size of the journal file. But if a power
  41629. ** failure occurred while the journal was being written, it could be the
  41630. ** case that the size of the journal file had already been increased but
  41631. ** the extra entries had not yet made it safely to disk. In such a case,
  41632. ** the value of nRec computed from the file size would be too large. For
  41633. ** that reason, we always use the nRec value in the header.
  41634. **
  41635. ** If the nRec value is 0xffffffff it means that nRec should be computed
  41636. ** from the file size. This value is used when the user selects the
  41637. ** no-sync option for the journal. A power failure could lead to corruption
  41638. ** in this case. But for things like temporary table (which will be
  41639. ** deleted when the power is restored) we don't care.
  41640. **
  41641. ** If the file opened as the journal file is not a well-formed
  41642. ** journal file then all pages up to the first corrupted page are rolled
  41643. ** back (or no pages if the journal header is corrupted). The journal file
  41644. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  41645. ** been encountered.
  41646. **
  41647. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  41648. ** and an error code is returned.
  41649. **
  41650. ** The isHot parameter indicates that we are trying to rollback a journal
  41651. ** that might be a hot journal. Or, it could be that the journal is
  41652. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  41653. ** If the journal really is hot, reset the pager cache prior rolling
  41654. ** back any content. If the journal is merely persistent, no reset is
  41655. ** needed.
  41656. */
  41657. static int pager_playback(Pager *pPager, int isHot){
  41658. sqlite3_vfs *pVfs = pPager->pVfs;
  41659. i64 szJ; /* Size of the journal file in bytes */
  41660. u32 nRec; /* Number of Records in the journal */
  41661. u32 u; /* Unsigned loop counter */
  41662. Pgno mxPg = 0; /* Size of the original file in pages */
  41663. int rc; /* Result code of a subroutine */
  41664. int res = 1; /* Value returned by sqlite3OsAccess() */
  41665. char *zMaster = 0; /* Name of master journal file if any */
  41666. int needPagerReset; /* True to reset page prior to first page rollback */
  41667. int nPlayback = 0; /* Total number of pages restored from journal */
  41668. /* Figure out how many records are in the journal. Abort early if
  41669. ** the journal is empty.
  41670. */
  41671. assert( isOpen(pPager->jfd) );
  41672. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  41673. if( rc!=SQLITE_OK ){
  41674. goto end_playback;
  41675. }
  41676. /* Read the master journal name from the journal, if it is present.
  41677. ** If a master journal file name is specified, but the file is not
  41678. ** present on disk, then the journal is not hot and does not need to be
  41679. ** played back.
  41680. **
  41681. ** TODO: Technically the following is an error because it assumes that
  41682. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  41683. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  41684. ** mxPathname is 512, which is the same as the minimum allowable value
  41685. ** for pageSize.
  41686. */
  41687. zMaster = pPager->pTmpSpace;
  41688. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41689. if( rc==SQLITE_OK && zMaster[0] ){
  41690. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  41691. }
  41692. zMaster = 0;
  41693. if( rc!=SQLITE_OK || !res ){
  41694. goto end_playback;
  41695. }
  41696. pPager->journalOff = 0;
  41697. needPagerReset = isHot;
  41698. /* This loop terminates either when a readJournalHdr() or
  41699. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  41700. ** occurs.
  41701. */
  41702. while( 1 ){
  41703. /* Read the next journal header from the journal file. If there are
  41704. ** not enough bytes left in the journal file for a complete header, or
  41705. ** it is corrupted, then a process must have failed while writing it.
  41706. ** This indicates nothing more needs to be rolled back.
  41707. */
  41708. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  41709. if( rc!=SQLITE_OK ){
  41710. if( rc==SQLITE_DONE ){
  41711. rc = SQLITE_OK;
  41712. }
  41713. goto end_playback;
  41714. }
  41715. /* If nRec is 0xffffffff, then this journal was created by a process
  41716. ** working in no-sync mode. This means that the rest of the journal
  41717. ** file consists of pages, there are no more journal headers. Compute
  41718. ** the value of nRec based on this assumption.
  41719. */
  41720. if( nRec==0xffffffff ){
  41721. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  41722. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  41723. }
  41724. /* If nRec is 0 and this rollback is of a transaction created by this
  41725. ** process and if this is the final header in the journal, then it means
  41726. ** that this part of the journal was being filled but has not yet been
  41727. ** synced to disk. Compute the number of pages based on the remaining
  41728. ** size of the file.
  41729. **
  41730. ** The third term of the test was added to fix ticket #2565.
  41731. ** When rolling back a hot journal, nRec==0 always means that the next
  41732. ** chunk of the journal contains zero pages to be rolled back. But
  41733. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  41734. ** the journal, it means that the journal might contain additional
  41735. ** pages that need to be rolled back and that the number of pages
  41736. ** should be computed based on the journal file size.
  41737. */
  41738. if( nRec==0 && !isHot &&
  41739. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  41740. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  41741. }
  41742. /* If this is the first header read from the journal, truncate the
  41743. ** database file back to its original size.
  41744. */
  41745. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  41746. rc = pager_truncate(pPager, mxPg);
  41747. if( rc!=SQLITE_OK ){
  41748. goto end_playback;
  41749. }
  41750. pPager->dbSize = mxPg;
  41751. }
  41752. /* Copy original pages out of the journal and back into the
  41753. ** database file and/or page cache.
  41754. */
  41755. for(u=0; u<nRec; u++){
  41756. if( needPagerReset ){
  41757. pager_reset(pPager);
  41758. needPagerReset = 0;
  41759. }
  41760. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  41761. if( rc==SQLITE_OK ){
  41762. nPlayback++;
  41763. }else{
  41764. if( rc==SQLITE_DONE ){
  41765. pPager->journalOff = szJ;
  41766. break;
  41767. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  41768. /* If the journal has been truncated, simply stop reading and
  41769. ** processing the journal. This might happen if the journal was
  41770. ** not completely written and synced prior to a crash. In that
  41771. ** case, the database should have never been written in the
  41772. ** first place so it is OK to simply abandon the rollback. */
  41773. rc = SQLITE_OK;
  41774. goto end_playback;
  41775. }else{
  41776. /* If we are unable to rollback, quit and return the error
  41777. ** code. This will cause the pager to enter the error state
  41778. ** so that no further harm will be done. Perhaps the next
  41779. ** process to come along will be able to rollback the database.
  41780. */
  41781. goto end_playback;
  41782. }
  41783. }
  41784. }
  41785. }
  41786. /*NOTREACHED*/
  41787. assert( 0 );
  41788. end_playback:
  41789. /* Following a rollback, the database file should be back in its original
  41790. ** state prior to the start of the transaction, so invoke the
  41791. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  41792. ** assertion that the transaction counter was modified.
  41793. */
  41794. #ifdef SQLITE_DEBUG
  41795. if( pPager->fd->pMethods ){
  41796. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  41797. }
  41798. #endif
  41799. /* If this playback is happening automatically as a result of an IO or
  41800. ** malloc error that occurred after the change-counter was updated but
  41801. ** before the transaction was committed, then the change-counter
  41802. ** modification may just have been reverted. If this happens in exclusive
  41803. ** mode, then subsequent transactions performed by the connection will not
  41804. ** update the change-counter at all. This may lead to cache inconsistency
  41805. ** problems for other processes at some point in the future. So, just
  41806. ** in case this has happened, clear the changeCountDone flag now.
  41807. */
  41808. pPager->changeCountDone = pPager->tempFile;
  41809. if( rc==SQLITE_OK ){
  41810. zMaster = pPager->pTmpSpace;
  41811. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  41812. testcase( rc!=SQLITE_OK );
  41813. }
  41814. if( rc==SQLITE_OK
  41815. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  41816. ){
  41817. rc = sqlite3PagerSync(pPager);
  41818. }
  41819. if( rc==SQLITE_OK ){
  41820. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  41821. testcase( rc!=SQLITE_OK );
  41822. }
  41823. if( rc==SQLITE_OK && zMaster[0] && res ){
  41824. /* If there was a master journal and this routine will return success,
  41825. ** see if it is possible to delete the master journal.
  41826. */
  41827. rc = pager_delmaster(pPager, zMaster);
  41828. testcase( rc!=SQLITE_OK );
  41829. }
  41830. if( isHot && nPlayback ){
  41831. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  41832. nPlayback, pPager->zJournal);
  41833. }
  41834. /* The Pager.sectorSize variable may have been updated while rolling
  41835. ** back a journal created by a process with a different sector size
  41836. ** value. Reset it to the correct value for this process.
  41837. */
  41838. setSectorSize(pPager);
  41839. return rc;
  41840. }
  41841. /*
  41842. ** Read the content for page pPg out of the database file and into
  41843. ** pPg->pData. A shared lock or greater must be held on the database
  41844. ** file before this function is called.
  41845. **
  41846. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  41847. ** the value read from the database file.
  41848. **
  41849. ** If an IO error occurs, then the IO error is returned to the caller.
  41850. ** Otherwise, SQLITE_OK is returned.
  41851. */
  41852. static int readDbPage(PgHdr *pPg, u32 iFrame){
  41853. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  41854. Pgno pgno = pPg->pgno; /* Page number to read */
  41855. int rc = SQLITE_OK; /* Return code */
  41856. int pgsz = pPager->pageSize; /* Number of bytes to read */
  41857. assert( pPager->eState>=PAGER_READER && !MEMDB );
  41858. assert( isOpen(pPager->fd) );
  41859. #ifndef SQLITE_OMIT_WAL
  41860. if( iFrame ){
  41861. /* Try to pull the page from the write-ahead log. */
  41862. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  41863. }else
  41864. #endif
  41865. {
  41866. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  41867. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  41868. if( rc==SQLITE_IOERR_SHORT_READ ){
  41869. rc = SQLITE_OK;
  41870. }
  41871. }
  41872. if( pgno==1 ){
  41873. if( rc ){
  41874. /* If the read is unsuccessful, set the dbFileVers[] to something
  41875. ** that will never be a valid file version. dbFileVers[] is a copy
  41876. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  41877. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  41878. ** should be page numbers which are never 0xffffffff. So filling
  41879. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  41880. **
  41881. ** For an encrypted database, the situation is more complex: bytes
  41882. ** 24..39 of the database are white noise. But the probability of
  41883. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  41884. ** we should still be ok.
  41885. */
  41886. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  41887. }else{
  41888. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  41889. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  41890. }
  41891. }
  41892. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  41893. PAGER_INCR(sqlite3_pager_readdb_count);
  41894. PAGER_INCR(pPager->nRead);
  41895. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  41896. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  41897. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  41898. return rc;
  41899. }
  41900. /*
  41901. ** Update the value of the change-counter at offsets 24 and 92 in
  41902. ** the header and the sqlite version number at offset 96.
  41903. **
  41904. ** This is an unconditional update. See also the pager_incr_changecounter()
  41905. ** routine which only updates the change-counter if the update is actually
  41906. ** needed, as determined by the pPager->changeCountDone state variable.
  41907. */
  41908. static void pager_write_changecounter(PgHdr *pPg){
  41909. u32 change_counter;
  41910. /* Increment the value just read and write it back to byte 24. */
  41911. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  41912. put32bits(((char*)pPg->pData)+24, change_counter);
  41913. /* Also store the SQLite version number in bytes 96..99 and in
  41914. ** bytes 92..95 store the change counter for which the version number
  41915. ** is valid. */
  41916. put32bits(((char*)pPg->pData)+92, change_counter);
  41917. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  41918. }
  41919. #ifndef SQLITE_OMIT_WAL
  41920. /*
  41921. ** This function is invoked once for each page that has already been
  41922. ** written into the log file when a WAL transaction is rolled back.
  41923. ** Parameter iPg is the page number of said page. The pCtx argument
  41924. ** is actually a pointer to the Pager structure.
  41925. **
  41926. ** If page iPg is present in the cache, and has no outstanding references,
  41927. ** it is discarded. Otherwise, if there are one or more outstanding
  41928. ** references, the page content is reloaded from the database. If the
  41929. ** attempt to reload content from the database is required and fails,
  41930. ** return an SQLite error code. Otherwise, SQLITE_OK.
  41931. */
  41932. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  41933. int rc = SQLITE_OK;
  41934. Pager *pPager = (Pager *)pCtx;
  41935. PgHdr *pPg;
  41936. assert( pagerUseWal(pPager) );
  41937. pPg = sqlite3PagerLookup(pPager, iPg);
  41938. if( pPg ){
  41939. if( sqlite3PcachePageRefcount(pPg)==1 ){
  41940. sqlite3PcacheDrop(pPg);
  41941. }else{
  41942. u32 iFrame = 0;
  41943. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  41944. if( rc==SQLITE_OK ){
  41945. rc = readDbPage(pPg, iFrame);
  41946. }
  41947. if( rc==SQLITE_OK ){
  41948. pPager->xReiniter(pPg);
  41949. }
  41950. sqlite3PagerUnref(pPg);
  41951. }
  41952. }
  41953. /* Normally, if a transaction is rolled back, any backup processes are
  41954. ** updated as data is copied out of the rollback journal and into the
  41955. ** database. This is not generally possible with a WAL database, as
  41956. ** rollback involves simply truncating the log file. Therefore, if one
  41957. ** or more frames have already been written to the log (and therefore
  41958. ** also copied into the backup databases) as part of this transaction,
  41959. ** the backups must be restarted.
  41960. */
  41961. sqlite3BackupRestart(pPager->pBackup);
  41962. return rc;
  41963. }
  41964. /*
  41965. ** This function is called to rollback a transaction on a WAL database.
  41966. */
  41967. static int pagerRollbackWal(Pager *pPager){
  41968. int rc; /* Return Code */
  41969. PgHdr *pList; /* List of dirty pages to revert */
  41970. /* For all pages in the cache that are currently dirty or have already
  41971. ** been written (but not committed) to the log file, do one of the
  41972. ** following:
  41973. **
  41974. ** + Discard the cached page (if refcount==0), or
  41975. ** + Reload page content from the database (if refcount>0).
  41976. */
  41977. pPager->dbSize = pPager->dbOrigSize;
  41978. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  41979. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41980. while( pList && rc==SQLITE_OK ){
  41981. PgHdr *pNext = pList->pDirty;
  41982. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  41983. pList = pNext;
  41984. }
  41985. return rc;
  41986. }
  41987. /*
  41988. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  41989. ** the contents of the list of pages headed by pList (connected by pDirty),
  41990. ** this function notifies any active backup processes that the pages have
  41991. ** changed.
  41992. **
  41993. ** The list of pages passed into this routine is always sorted by page number.
  41994. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  41995. */
  41996. static int pagerWalFrames(
  41997. Pager *pPager, /* Pager object */
  41998. PgHdr *pList, /* List of frames to log */
  41999. Pgno nTruncate, /* Database size after this commit */
  42000. int isCommit /* True if this is a commit */
  42001. ){
  42002. int rc; /* Return code */
  42003. int nList; /* Number of pages in pList */
  42004. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  42005. PgHdr *p; /* For looping over pages */
  42006. #endif
  42007. assert( pPager->pWal );
  42008. assert( pList );
  42009. #ifdef SQLITE_DEBUG
  42010. /* Verify that the page list is in accending order */
  42011. for(p=pList; p && p->pDirty; p=p->pDirty){
  42012. assert( p->pgno < p->pDirty->pgno );
  42013. }
  42014. #endif
  42015. assert( pList->pDirty==0 || isCommit );
  42016. if( isCommit ){
  42017. /* If a WAL transaction is being committed, there is no point in writing
  42018. ** any pages with page numbers greater than nTruncate into the WAL file.
  42019. ** They will never be read by any client. So remove them from the pDirty
  42020. ** list here. */
  42021. PgHdr *p;
  42022. PgHdr **ppNext = &pList;
  42023. nList = 0;
  42024. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  42025. if( p->pgno<=nTruncate ){
  42026. ppNext = &p->pDirty;
  42027. nList++;
  42028. }
  42029. }
  42030. assert( pList );
  42031. }else{
  42032. nList = 1;
  42033. }
  42034. pPager->aStat[PAGER_STAT_WRITE] += nList;
  42035. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42036. rc = sqlite3WalFrames(pPager->pWal,
  42037. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  42038. );
  42039. if( rc==SQLITE_OK && pPager->pBackup ){
  42040. PgHdr *p;
  42041. for(p=pList; p; p=p->pDirty){
  42042. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  42043. }
  42044. }
  42045. #ifdef SQLITE_CHECK_PAGES
  42046. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  42047. for(p=pList; p; p=p->pDirty){
  42048. pager_set_pagehash(p);
  42049. }
  42050. #endif
  42051. return rc;
  42052. }
  42053. /*
  42054. ** Begin a read transaction on the WAL.
  42055. **
  42056. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  42057. ** makes a snapshot of the database at the current point in time and preserves
  42058. ** that snapshot for use by the reader in spite of concurrently changes by
  42059. ** other writers or checkpointers.
  42060. */
  42061. static int pagerBeginReadTransaction(Pager *pPager){
  42062. int rc; /* Return code */
  42063. int changed = 0; /* True if cache must be reset */
  42064. assert( pagerUseWal(pPager) );
  42065. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  42066. /* sqlite3WalEndReadTransaction() was not called for the previous
  42067. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  42068. ** are in locking_mode=NORMAL and EndRead() was previously called,
  42069. ** the duplicate call is harmless.
  42070. */
  42071. sqlite3WalEndReadTransaction(pPager->pWal);
  42072. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  42073. if( rc!=SQLITE_OK || changed ){
  42074. pager_reset(pPager);
  42075. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  42076. }
  42077. return rc;
  42078. }
  42079. #endif
  42080. /*
  42081. ** This function is called as part of the transition from PAGER_OPEN
  42082. ** to PAGER_READER state to determine the size of the database file
  42083. ** in pages (assuming the page size currently stored in Pager.pageSize).
  42084. **
  42085. ** If no error occurs, SQLITE_OK is returned and the size of the database
  42086. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  42087. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  42088. */
  42089. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  42090. Pgno nPage; /* Value to return via *pnPage */
  42091. /* Query the WAL sub-system for the database size. The WalDbsize()
  42092. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  42093. ** if the database size is not available. The database size is not
  42094. ** available from the WAL sub-system if the log file is empty or
  42095. ** contains no valid committed transactions.
  42096. */
  42097. assert( pPager->eState==PAGER_OPEN );
  42098. assert( pPager->eLock>=SHARED_LOCK );
  42099. nPage = sqlite3WalDbsize(pPager->pWal);
  42100. /* If the database size was not available from the WAL sub-system,
  42101. ** determine it based on the size of the database file. If the size
  42102. ** of the database file is not an integer multiple of the page-size,
  42103. ** round down to the nearest page. Except, any file larger than 0
  42104. ** bytes in size is considered to contain at least one page.
  42105. */
  42106. if( nPage==0 ){
  42107. i64 n = 0; /* Size of db file in bytes */
  42108. assert( isOpen(pPager->fd) || pPager->tempFile );
  42109. if( isOpen(pPager->fd) ){
  42110. int rc = sqlite3OsFileSize(pPager->fd, &n);
  42111. if( rc!=SQLITE_OK ){
  42112. return rc;
  42113. }
  42114. }
  42115. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  42116. }
  42117. /* If the current number of pages in the file is greater than the
  42118. ** configured maximum pager number, increase the allowed limit so
  42119. ** that the file can be read.
  42120. */
  42121. if( nPage>pPager->mxPgno ){
  42122. pPager->mxPgno = (Pgno)nPage;
  42123. }
  42124. *pnPage = nPage;
  42125. return SQLITE_OK;
  42126. }
  42127. #ifndef SQLITE_OMIT_WAL
  42128. /*
  42129. ** Check if the *-wal file that corresponds to the database opened by pPager
  42130. ** exists if the database is not empy, or verify that the *-wal file does
  42131. ** not exist (by deleting it) if the database file is empty.
  42132. **
  42133. ** If the database is not empty and the *-wal file exists, open the pager
  42134. ** in WAL mode. If the database is empty or if no *-wal file exists and
  42135. ** if no error occurs, make sure Pager.journalMode is not set to
  42136. ** PAGER_JOURNALMODE_WAL.
  42137. **
  42138. ** Return SQLITE_OK or an error code.
  42139. **
  42140. ** The caller must hold a SHARED lock on the database file to call this
  42141. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  42142. ** a WAL on a none-empty database, this ensures there is no race condition
  42143. ** between the xAccess() below and an xDelete() being executed by some
  42144. ** other connection.
  42145. */
  42146. static int pagerOpenWalIfPresent(Pager *pPager){
  42147. int rc = SQLITE_OK;
  42148. assert( pPager->eState==PAGER_OPEN );
  42149. assert( pPager->eLock>=SHARED_LOCK );
  42150. if( !pPager->tempFile ){
  42151. int isWal; /* True if WAL file exists */
  42152. Pgno nPage; /* Size of the database file */
  42153. rc = pagerPagecount(pPager, &nPage);
  42154. if( rc ) return rc;
  42155. if( nPage==0 ){
  42156. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  42157. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  42158. isWal = 0;
  42159. }else{
  42160. rc = sqlite3OsAccess(
  42161. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  42162. );
  42163. }
  42164. if( rc==SQLITE_OK ){
  42165. if( isWal ){
  42166. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  42167. rc = sqlite3PagerOpenWal(pPager, 0);
  42168. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  42169. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  42170. }
  42171. }
  42172. }
  42173. return rc;
  42174. }
  42175. #endif
  42176. /*
  42177. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  42178. ** the entire master journal file. The case pSavepoint==NULL occurs when
  42179. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  42180. ** savepoint.
  42181. **
  42182. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  42183. ** being rolled back), then the rollback consists of up to three stages,
  42184. ** performed in the order specified:
  42185. **
  42186. ** * Pages are played back from the main journal starting at byte
  42187. ** offset PagerSavepoint.iOffset and continuing to
  42188. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  42189. ** file if PagerSavepoint.iHdrOffset is zero.
  42190. **
  42191. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  42192. ** back starting from the journal header immediately following
  42193. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  42194. **
  42195. ** * Pages are then played back from the sub-journal file, starting
  42196. ** with the PagerSavepoint.iSubRec and continuing to the end of
  42197. ** the journal file.
  42198. **
  42199. ** Throughout the rollback process, each time a page is rolled back, the
  42200. ** corresponding bit is set in a bitvec structure (variable pDone in the
  42201. ** implementation below). This is used to ensure that a page is only
  42202. ** rolled back the first time it is encountered in either journal.
  42203. **
  42204. ** If pSavepoint is NULL, then pages are only played back from the main
  42205. ** journal file. There is no need for a bitvec in this case.
  42206. **
  42207. ** In either case, before playback commences the Pager.dbSize variable
  42208. ** is reset to the value that it held at the start of the savepoint
  42209. ** (or transaction). No page with a page-number greater than this value
  42210. ** is played back. If one is encountered it is simply skipped.
  42211. */
  42212. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  42213. i64 szJ; /* Effective size of the main journal */
  42214. i64 iHdrOff; /* End of first segment of main-journal records */
  42215. int rc = SQLITE_OK; /* Return code */
  42216. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  42217. assert( pPager->eState!=PAGER_ERROR );
  42218. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  42219. /* Allocate a bitvec to use to store the set of pages rolled back */
  42220. if( pSavepoint ){
  42221. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  42222. if( !pDone ){
  42223. return SQLITE_NOMEM;
  42224. }
  42225. }
  42226. /* Set the database size back to the value it was before the savepoint
  42227. ** being reverted was opened.
  42228. */
  42229. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  42230. pPager->changeCountDone = pPager->tempFile;
  42231. if( !pSavepoint && pagerUseWal(pPager) ){
  42232. return pagerRollbackWal(pPager);
  42233. }
  42234. /* Use pPager->journalOff as the effective size of the main rollback
  42235. ** journal. The actual file might be larger than this in
  42236. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  42237. ** past pPager->journalOff is off-limits to us.
  42238. */
  42239. szJ = pPager->journalOff;
  42240. assert( pagerUseWal(pPager)==0 || szJ==0 );
  42241. /* Begin by rolling back records from the main journal starting at
  42242. ** PagerSavepoint.iOffset and continuing to the next journal header.
  42243. ** There might be records in the main journal that have a page number
  42244. ** greater than the current database size (pPager->dbSize) but those
  42245. ** will be skipped automatically. Pages are added to pDone as they
  42246. ** are played back.
  42247. */
  42248. if( pSavepoint && !pagerUseWal(pPager) ){
  42249. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  42250. pPager->journalOff = pSavepoint->iOffset;
  42251. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  42252. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42253. }
  42254. assert( rc!=SQLITE_DONE );
  42255. }else{
  42256. pPager->journalOff = 0;
  42257. }
  42258. /* Continue rolling back records out of the main journal starting at
  42259. ** the first journal header seen and continuing until the effective end
  42260. ** of the main journal file. Continue to skip out-of-range pages and
  42261. ** continue adding pages rolled back to pDone.
  42262. */
  42263. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  42264. u32 ii; /* Loop counter */
  42265. u32 nJRec = 0; /* Number of Journal Records */
  42266. u32 dummy;
  42267. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  42268. assert( rc!=SQLITE_DONE );
  42269. /*
  42270. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  42271. ** test is related to ticket #2565. See the discussion in the
  42272. ** pager_playback() function for additional information.
  42273. */
  42274. if( nJRec==0
  42275. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  42276. ){
  42277. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  42278. }
  42279. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  42280. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  42281. }
  42282. assert( rc!=SQLITE_DONE );
  42283. }
  42284. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  42285. /* Finally, rollback pages from the sub-journal. Page that were
  42286. ** previously rolled back out of the main journal (and are hence in pDone)
  42287. ** will be skipped. Out-of-range pages are also skipped.
  42288. */
  42289. if( pSavepoint ){
  42290. u32 ii; /* Loop counter */
  42291. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  42292. if( pagerUseWal(pPager) ){
  42293. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  42294. }
  42295. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  42296. assert( offset==(i64)ii*(4+pPager->pageSize) );
  42297. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  42298. }
  42299. assert( rc!=SQLITE_DONE );
  42300. }
  42301. sqlite3BitvecDestroy(pDone);
  42302. if( rc==SQLITE_OK ){
  42303. pPager->journalOff = szJ;
  42304. }
  42305. return rc;
  42306. }
  42307. /*
  42308. ** Change the maximum number of in-memory pages that are allowed.
  42309. */
  42310. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  42311. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  42312. }
  42313. /*
  42314. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  42315. */
  42316. static void pagerFixMaplimit(Pager *pPager){
  42317. #if SQLITE_MAX_MMAP_SIZE>0
  42318. sqlite3_file *fd = pPager->fd;
  42319. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  42320. sqlite3_int64 sz;
  42321. sz = pPager->szMmap;
  42322. pPager->bUseFetch = (sz>0);
  42323. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  42324. }
  42325. #endif
  42326. }
  42327. /*
  42328. ** Change the maximum size of any memory mapping made of the database file.
  42329. */
  42330. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  42331. pPager->szMmap = szMmap;
  42332. pagerFixMaplimit(pPager);
  42333. }
  42334. /*
  42335. ** Free as much memory as possible from the pager.
  42336. */
  42337. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  42338. sqlite3PcacheShrink(pPager->pPCache);
  42339. }
  42340. /*
  42341. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  42342. **
  42343. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  42344. ** of the database to damage due to OS crashes or power failures by
  42345. ** changing the number of syncs()s when writing the journals.
  42346. ** There are three levels:
  42347. **
  42348. ** OFF sqlite3OsSync() is never called. This is the default
  42349. ** for temporary and transient files.
  42350. **
  42351. ** NORMAL The journal is synced once before writes begin on the
  42352. ** database. This is normally adequate protection, but
  42353. ** it is theoretically possible, though very unlikely,
  42354. ** that an inopertune power failure could leave the journal
  42355. ** in a state which would cause damage to the database
  42356. ** when it is rolled back.
  42357. **
  42358. ** FULL The journal is synced twice before writes begin on the
  42359. ** database (with some additional information - the nRec field
  42360. ** of the journal header - being written in between the two
  42361. ** syncs). If we assume that writing a
  42362. ** single disk sector is atomic, then this mode provides
  42363. ** assurance that the journal will not be corrupted to the
  42364. ** point of causing damage to the database during rollback.
  42365. **
  42366. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  42367. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  42368. ** prior to the start of checkpoint and that the database file is synced
  42369. ** at the conclusion of the checkpoint if the entire content of the WAL
  42370. ** was written back into the database. But no sync operations occur for
  42371. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  42372. ** file is synced following each commit operation, in addition to the
  42373. ** syncs associated with NORMAL.
  42374. **
  42375. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  42376. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  42377. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  42378. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  42379. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  42380. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  42381. ** the xSync primitive is called and is relevant to all platforms.
  42382. **
  42383. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  42384. ** and FULL=3.
  42385. */
  42386. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  42387. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  42388. Pager *pPager, /* The pager to set safety level for */
  42389. unsigned pgFlags /* Various flags */
  42390. ){
  42391. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  42392. assert( level>=1 && level<=3 );
  42393. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  42394. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  42395. if( pPager->noSync ){
  42396. pPager->syncFlags = 0;
  42397. pPager->ckptSyncFlags = 0;
  42398. }else if( pgFlags & PAGER_FULLFSYNC ){
  42399. pPager->syncFlags = SQLITE_SYNC_FULL;
  42400. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42401. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  42402. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42403. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  42404. }else{
  42405. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42406. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42407. }
  42408. pPager->walSyncFlags = pPager->syncFlags;
  42409. if( pPager->fullSync ){
  42410. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  42411. }
  42412. if( pgFlags & PAGER_CACHESPILL ){
  42413. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  42414. }else{
  42415. pPager->doNotSpill |= SPILLFLAG_OFF;
  42416. }
  42417. }
  42418. #endif
  42419. /*
  42420. ** The following global variable is incremented whenever the library
  42421. ** attempts to open a temporary file. This information is used for
  42422. ** testing and analysis only.
  42423. */
  42424. #ifdef SQLITE_TEST
  42425. SQLITE_API int sqlite3_opentemp_count = 0;
  42426. #endif
  42427. /*
  42428. ** Open a temporary file.
  42429. **
  42430. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  42431. ** or some other error code if we fail. The OS will automatically
  42432. ** delete the temporary file when it is closed.
  42433. **
  42434. ** The flags passed to the VFS layer xOpen() call are those specified
  42435. ** by parameter vfsFlags ORed with the following:
  42436. **
  42437. ** SQLITE_OPEN_READWRITE
  42438. ** SQLITE_OPEN_CREATE
  42439. ** SQLITE_OPEN_EXCLUSIVE
  42440. ** SQLITE_OPEN_DELETEONCLOSE
  42441. */
  42442. static int pagerOpentemp(
  42443. Pager *pPager, /* The pager object */
  42444. sqlite3_file *pFile, /* Write the file descriptor here */
  42445. int vfsFlags /* Flags passed through to the VFS */
  42446. ){
  42447. int rc; /* Return code */
  42448. #ifdef SQLITE_TEST
  42449. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  42450. #endif
  42451. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  42452. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  42453. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  42454. assert( rc!=SQLITE_OK || isOpen(pFile) );
  42455. return rc;
  42456. }
  42457. /*
  42458. ** Set the busy handler function.
  42459. **
  42460. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  42461. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  42462. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  42463. ** lock. It does *not* invoke the busy handler when upgrading from
  42464. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  42465. ** (which occurs during hot-journal rollback). Summary:
  42466. **
  42467. ** Transition | Invokes xBusyHandler
  42468. ** --------------------------------------------------------
  42469. ** NO_LOCK -> SHARED_LOCK | Yes
  42470. ** SHARED_LOCK -> RESERVED_LOCK | No
  42471. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  42472. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  42473. **
  42474. ** If the busy-handler callback returns non-zero, the lock is
  42475. ** retried. If it returns zero, then the SQLITE_BUSY error is
  42476. ** returned to the caller of the pager API function.
  42477. */
  42478. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  42479. Pager *pPager, /* Pager object */
  42480. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  42481. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  42482. ){
  42483. pPager->xBusyHandler = xBusyHandler;
  42484. pPager->pBusyHandlerArg = pBusyHandlerArg;
  42485. if( isOpen(pPager->fd) ){
  42486. void **ap = (void **)&pPager->xBusyHandler;
  42487. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  42488. assert( ap[1]==pBusyHandlerArg );
  42489. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  42490. }
  42491. }
  42492. /*
  42493. ** Change the page size used by the Pager object. The new page size
  42494. ** is passed in *pPageSize.
  42495. **
  42496. ** If the pager is in the error state when this function is called, it
  42497. ** is a no-op. The value returned is the error state error code (i.e.
  42498. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  42499. **
  42500. ** Otherwise, if all of the following are true:
  42501. **
  42502. ** * the new page size (value of *pPageSize) is valid (a power
  42503. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  42504. **
  42505. ** * there are no outstanding page references, and
  42506. **
  42507. ** * the database is either not an in-memory database or it is
  42508. ** an in-memory database that currently consists of zero pages.
  42509. **
  42510. ** then the pager object page size is set to *pPageSize.
  42511. **
  42512. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  42513. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  42514. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  42515. ** In all other cases, SQLITE_OK is returned.
  42516. **
  42517. ** If the page size is not changed, either because one of the enumerated
  42518. ** conditions above is not true, the pager was in error state when this
  42519. ** function was called, or because the memory allocation attempt failed,
  42520. ** then *pPageSize is set to the old, retained page size before returning.
  42521. */
  42522. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  42523. int rc = SQLITE_OK;
  42524. /* It is not possible to do a full assert_pager_state() here, as this
  42525. ** function may be called from within PagerOpen(), before the state
  42526. ** of the Pager object is internally consistent.
  42527. **
  42528. ** At one point this function returned an error if the pager was in
  42529. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  42530. ** there is at least one outstanding page reference, this function
  42531. ** is a no-op for that case anyhow.
  42532. */
  42533. u32 pageSize = *pPageSize;
  42534. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  42535. if( (pPager->memDb==0 || pPager->dbSize==0)
  42536. && sqlite3PcacheRefCount(pPager->pPCache)==0
  42537. && pageSize && pageSize!=(u32)pPager->pageSize
  42538. ){
  42539. char *pNew = NULL; /* New temp space */
  42540. i64 nByte = 0;
  42541. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  42542. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  42543. }
  42544. if( rc==SQLITE_OK ){
  42545. pNew = (char *)sqlite3PageMalloc(pageSize);
  42546. if( !pNew ) rc = SQLITE_NOMEM;
  42547. }
  42548. if( rc==SQLITE_OK ){
  42549. pager_reset(pPager);
  42550. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  42551. pPager->pageSize = pageSize;
  42552. sqlite3PageFree(pPager->pTmpSpace);
  42553. pPager->pTmpSpace = pNew;
  42554. sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  42555. }
  42556. }
  42557. *pPageSize = pPager->pageSize;
  42558. if( rc==SQLITE_OK ){
  42559. if( nReserve<0 ) nReserve = pPager->nReserve;
  42560. assert( nReserve>=0 && nReserve<1000 );
  42561. pPager->nReserve = (i16)nReserve;
  42562. pagerReportSize(pPager);
  42563. pagerFixMaplimit(pPager);
  42564. }
  42565. return rc;
  42566. }
  42567. /*
  42568. ** Return a pointer to the "temporary page" buffer held internally
  42569. ** by the pager. This is a buffer that is big enough to hold the
  42570. ** entire content of a database page. This buffer is used internally
  42571. ** during rollback and will be overwritten whenever a rollback
  42572. ** occurs. But other modules are free to use it too, as long as
  42573. ** no rollbacks are happening.
  42574. */
  42575. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  42576. return pPager->pTmpSpace;
  42577. }
  42578. /*
  42579. ** Attempt to set the maximum database page count if mxPage is positive.
  42580. ** Make no changes if mxPage is zero or negative. And never reduce the
  42581. ** maximum page count below the current size of the database.
  42582. **
  42583. ** Regardless of mxPage, return the current maximum page count.
  42584. */
  42585. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  42586. if( mxPage>0 ){
  42587. pPager->mxPgno = mxPage;
  42588. }
  42589. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  42590. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  42591. return pPager->mxPgno;
  42592. }
  42593. /*
  42594. ** The following set of routines are used to disable the simulated
  42595. ** I/O error mechanism. These routines are used to avoid simulated
  42596. ** errors in places where we do not care about errors.
  42597. **
  42598. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  42599. ** and generate no code.
  42600. */
  42601. #ifdef SQLITE_TEST
  42602. SQLITE_API extern int sqlite3_io_error_pending;
  42603. SQLITE_API extern int sqlite3_io_error_hit;
  42604. static int saved_cnt;
  42605. void disable_simulated_io_errors(void){
  42606. saved_cnt = sqlite3_io_error_pending;
  42607. sqlite3_io_error_pending = -1;
  42608. }
  42609. void enable_simulated_io_errors(void){
  42610. sqlite3_io_error_pending = saved_cnt;
  42611. }
  42612. #else
  42613. # define disable_simulated_io_errors()
  42614. # define enable_simulated_io_errors()
  42615. #endif
  42616. /*
  42617. ** Read the first N bytes from the beginning of the file into memory
  42618. ** that pDest points to.
  42619. **
  42620. ** If the pager was opened on a transient file (zFilename==""), or
  42621. ** opened on a file less than N bytes in size, the output buffer is
  42622. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  42623. ** function is used to read database headers, and a new transient or
  42624. ** zero sized database has a header than consists entirely of zeroes.
  42625. **
  42626. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  42627. ** the error code is returned to the caller and the contents of the
  42628. ** output buffer undefined.
  42629. */
  42630. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  42631. int rc = SQLITE_OK;
  42632. memset(pDest, 0, N);
  42633. assert( isOpen(pPager->fd) || pPager->tempFile );
  42634. /* This routine is only called by btree immediately after creating
  42635. ** the Pager object. There has not been an opportunity to transition
  42636. ** to WAL mode yet.
  42637. */
  42638. assert( !pagerUseWal(pPager) );
  42639. if( isOpen(pPager->fd) ){
  42640. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  42641. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  42642. if( rc==SQLITE_IOERR_SHORT_READ ){
  42643. rc = SQLITE_OK;
  42644. }
  42645. }
  42646. return rc;
  42647. }
  42648. /*
  42649. ** This function may only be called when a read-transaction is open on
  42650. ** the pager. It returns the total number of pages in the database.
  42651. **
  42652. ** However, if the file is between 1 and <page-size> bytes in size, then
  42653. ** this is considered a 1 page file.
  42654. */
  42655. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  42656. assert( pPager->eState>=PAGER_READER );
  42657. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  42658. *pnPage = (int)pPager->dbSize;
  42659. }
  42660. /*
  42661. ** Try to obtain a lock of type locktype on the database file. If
  42662. ** a similar or greater lock is already held, this function is a no-op
  42663. ** (returning SQLITE_OK immediately).
  42664. **
  42665. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  42666. ** the busy callback if the lock is currently not available. Repeat
  42667. ** until the busy callback returns false or until the attempt to
  42668. ** obtain the lock succeeds.
  42669. **
  42670. ** Return SQLITE_OK on success and an error code if we cannot obtain
  42671. ** the lock. If the lock is obtained successfully, set the Pager.state
  42672. ** variable to locktype before returning.
  42673. */
  42674. static int pager_wait_on_lock(Pager *pPager, int locktype){
  42675. int rc; /* Return code */
  42676. /* Check that this is either a no-op (because the requested lock is
  42677. ** already held, or one of the transistions that the busy-handler
  42678. ** may be invoked during, according to the comment above
  42679. ** sqlite3PagerSetBusyhandler().
  42680. */
  42681. assert( (pPager->eLock>=locktype)
  42682. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  42683. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  42684. );
  42685. do {
  42686. rc = pagerLockDb(pPager, locktype);
  42687. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  42688. return rc;
  42689. }
  42690. /*
  42691. ** Function assertTruncateConstraint(pPager) checks that one of the
  42692. ** following is true for all dirty pages currently in the page-cache:
  42693. **
  42694. ** a) The page number is less than or equal to the size of the
  42695. ** current database image, in pages, OR
  42696. **
  42697. ** b) if the page content were written at this time, it would not
  42698. ** be necessary to write the current content out to the sub-journal
  42699. ** (as determined by function subjRequiresPage()).
  42700. **
  42701. ** If the condition asserted by this function were not true, and the
  42702. ** dirty page were to be discarded from the cache via the pagerStress()
  42703. ** routine, pagerStress() would not write the current page content to
  42704. ** the database file. If a savepoint transaction were rolled back after
  42705. ** this happened, the correct behavior would be to restore the current
  42706. ** content of the page. However, since this content is not present in either
  42707. ** the database file or the portion of the rollback journal and
  42708. ** sub-journal rolled back the content could not be restored and the
  42709. ** database image would become corrupt. It is therefore fortunate that
  42710. ** this circumstance cannot arise.
  42711. */
  42712. #if defined(SQLITE_DEBUG)
  42713. static void assertTruncateConstraintCb(PgHdr *pPg){
  42714. assert( pPg->flags&PGHDR_DIRTY );
  42715. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  42716. }
  42717. static void assertTruncateConstraint(Pager *pPager){
  42718. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  42719. }
  42720. #else
  42721. # define assertTruncateConstraint(pPager)
  42722. #endif
  42723. /*
  42724. ** Truncate the in-memory database file image to nPage pages. This
  42725. ** function does not actually modify the database file on disk. It
  42726. ** just sets the internal state of the pager object so that the
  42727. ** truncation will be done when the current transaction is committed.
  42728. **
  42729. ** This function is only called right before committing a transaction.
  42730. ** Once this function has been called, the transaction must either be
  42731. ** rolled back or committed. It is not safe to call this function and
  42732. ** then continue writing to the database.
  42733. */
  42734. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  42735. assert( pPager->dbSize>=nPage );
  42736. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  42737. pPager->dbSize = nPage;
  42738. /* At one point the code here called assertTruncateConstraint() to
  42739. ** ensure that all pages being truncated away by this operation are,
  42740. ** if one or more savepoints are open, present in the savepoint
  42741. ** journal so that they can be restored if the savepoint is rolled
  42742. ** back. This is no longer necessary as this function is now only
  42743. ** called right before committing a transaction. So although the
  42744. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  42745. ** they cannot be rolled back. So the assertTruncateConstraint() call
  42746. ** is no longer correct. */
  42747. }
  42748. /*
  42749. ** This function is called before attempting a hot-journal rollback. It
  42750. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  42751. ** size of the journal file so that the pager_playback() routine knows
  42752. ** that the entire journal file has been synced.
  42753. **
  42754. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  42755. ** that if a power-failure occurs during the rollback, the process that
  42756. ** attempts rollback following system recovery sees the same journal
  42757. ** content as this process.
  42758. **
  42759. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  42760. ** an SQLite error code.
  42761. */
  42762. static int pagerSyncHotJournal(Pager *pPager){
  42763. int rc = SQLITE_OK;
  42764. if( !pPager->noSync ){
  42765. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  42766. }
  42767. if( rc==SQLITE_OK ){
  42768. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  42769. }
  42770. return rc;
  42771. }
  42772. /*
  42773. ** Obtain a reference to a memory mapped page object for page number pgno.
  42774. ** The new object will use the pointer pData, obtained from xFetch().
  42775. ** If successful, set *ppPage to point to the new page reference
  42776. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  42777. ** *ppPage to zero.
  42778. **
  42779. ** Page references obtained by calling this function should be released
  42780. ** by calling pagerReleaseMapPage().
  42781. */
  42782. static int pagerAcquireMapPage(
  42783. Pager *pPager, /* Pager object */
  42784. Pgno pgno, /* Page number */
  42785. void *pData, /* xFetch()'d data for this page */
  42786. PgHdr **ppPage /* OUT: Acquired page object */
  42787. ){
  42788. PgHdr *p; /* Memory mapped page to return */
  42789. if( pPager->pMmapFreelist ){
  42790. *ppPage = p = pPager->pMmapFreelist;
  42791. pPager->pMmapFreelist = p->pDirty;
  42792. p->pDirty = 0;
  42793. memset(p->pExtra, 0, pPager->nExtra);
  42794. }else{
  42795. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  42796. if( p==0 ){
  42797. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  42798. return SQLITE_NOMEM;
  42799. }
  42800. p->pExtra = (void *)&p[1];
  42801. p->flags = PGHDR_MMAP;
  42802. p->nRef = 1;
  42803. p->pPager = pPager;
  42804. }
  42805. assert( p->pExtra==(void *)&p[1] );
  42806. assert( p->pPage==0 );
  42807. assert( p->flags==PGHDR_MMAP );
  42808. assert( p->pPager==pPager );
  42809. assert( p->nRef==1 );
  42810. p->pgno = pgno;
  42811. p->pData = pData;
  42812. pPager->nMmapOut++;
  42813. return SQLITE_OK;
  42814. }
  42815. /*
  42816. ** Release a reference to page pPg. pPg must have been returned by an
  42817. ** earlier call to pagerAcquireMapPage().
  42818. */
  42819. static void pagerReleaseMapPage(PgHdr *pPg){
  42820. Pager *pPager = pPg->pPager;
  42821. pPager->nMmapOut--;
  42822. pPg->pDirty = pPager->pMmapFreelist;
  42823. pPager->pMmapFreelist = pPg;
  42824. assert( pPager->fd->pMethods->iVersion>=3 );
  42825. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  42826. }
  42827. /*
  42828. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  42829. */
  42830. static void pagerFreeMapHdrs(Pager *pPager){
  42831. PgHdr *p;
  42832. PgHdr *pNext;
  42833. for(p=pPager->pMmapFreelist; p; p=pNext){
  42834. pNext = p->pDirty;
  42835. sqlite3_free(p);
  42836. }
  42837. }
  42838. /*
  42839. ** Shutdown the page cache. Free all memory and close all files.
  42840. **
  42841. ** If a transaction was in progress when this routine is called, that
  42842. ** transaction is rolled back. All outstanding pages are invalidated
  42843. ** and their memory is freed. Any attempt to use a page associated
  42844. ** with this page cache after this function returns will likely
  42845. ** result in a coredump.
  42846. **
  42847. ** This function always succeeds. If a transaction is active an attempt
  42848. ** is made to roll it back. If an error occurs during the rollback
  42849. ** a hot journal may be left in the filesystem but no error is returned
  42850. ** to the caller.
  42851. */
  42852. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  42853. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  42854. assert( assert_pager_state(pPager) );
  42855. disable_simulated_io_errors();
  42856. sqlite3BeginBenignMalloc();
  42857. pagerFreeMapHdrs(pPager);
  42858. /* pPager->errCode = 0; */
  42859. pPager->exclusiveMode = 0;
  42860. #ifndef SQLITE_OMIT_WAL
  42861. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  42862. pPager->pWal = 0;
  42863. #endif
  42864. pager_reset(pPager);
  42865. if( MEMDB ){
  42866. pager_unlock(pPager);
  42867. }else{
  42868. /* If it is open, sync the journal file before calling UnlockAndRollback.
  42869. ** If this is not done, then an unsynced portion of the open journal
  42870. ** file may be played back into the database. If a power failure occurs
  42871. ** while this is happening, the database could become corrupt.
  42872. **
  42873. ** If an error occurs while trying to sync the journal, shift the pager
  42874. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  42875. ** database and close the journal file without attempting to roll it
  42876. ** back or finalize it. The next database user will have to do hot-journal
  42877. ** rollback before accessing the database file.
  42878. */
  42879. if( isOpen(pPager->jfd) ){
  42880. pager_error(pPager, pagerSyncHotJournal(pPager));
  42881. }
  42882. pagerUnlockAndRollback(pPager);
  42883. }
  42884. sqlite3EndBenignMalloc();
  42885. enable_simulated_io_errors();
  42886. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  42887. IOTRACE(("CLOSE %p\n", pPager))
  42888. sqlite3OsClose(pPager->jfd);
  42889. sqlite3OsClose(pPager->fd);
  42890. sqlite3PageFree(pTmp);
  42891. sqlite3PcacheClose(pPager->pPCache);
  42892. #ifdef SQLITE_HAS_CODEC
  42893. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  42894. #endif
  42895. assert( !pPager->aSavepoint && !pPager->pInJournal );
  42896. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  42897. sqlite3_free(pPager);
  42898. return SQLITE_OK;
  42899. }
  42900. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  42901. /*
  42902. ** Return the page number for page pPg.
  42903. */
  42904. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  42905. return pPg->pgno;
  42906. }
  42907. #endif
  42908. /*
  42909. ** Increment the reference count for page pPg.
  42910. */
  42911. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  42912. sqlite3PcacheRef(pPg);
  42913. }
  42914. /*
  42915. ** Sync the journal. In other words, make sure all the pages that have
  42916. ** been written to the journal have actually reached the surface of the
  42917. ** disk and can be restored in the event of a hot-journal rollback.
  42918. **
  42919. ** If the Pager.noSync flag is set, then this function is a no-op.
  42920. ** Otherwise, the actions required depend on the journal-mode and the
  42921. ** device characteristics of the file-system, as follows:
  42922. **
  42923. ** * If the journal file is an in-memory journal file, no action need
  42924. ** be taken.
  42925. **
  42926. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  42927. ** then the nRec field of the most recently written journal header
  42928. ** is updated to contain the number of journal records that have
  42929. ** been written following it. If the pager is operating in full-sync
  42930. ** mode, then the journal file is synced before this field is updated.
  42931. **
  42932. ** * If the device does not support the SEQUENTIAL property, then
  42933. ** journal file is synced.
  42934. **
  42935. ** Or, in pseudo-code:
  42936. **
  42937. ** if( NOT <in-memory journal> ){
  42938. ** if( NOT SAFE_APPEND ){
  42939. ** if( <full-sync mode> ) xSync(<journal file>);
  42940. ** <update nRec field>
  42941. ** }
  42942. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  42943. ** }
  42944. **
  42945. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  42946. ** page currently held in memory before returning SQLITE_OK. If an IO
  42947. ** error is encountered, then the IO error code is returned to the caller.
  42948. */
  42949. static int syncJournal(Pager *pPager, int newHdr){
  42950. int rc; /* Return code */
  42951. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42952. || pPager->eState==PAGER_WRITER_DBMOD
  42953. );
  42954. assert( assert_pager_state(pPager) );
  42955. assert( !pagerUseWal(pPager) );
  42956. rc = sqlite3PagerExclusiveLock(pPager);
  42957. if( rc!=SQLITE_OK ) return rc;
  42958. if( !pPager->noSync ){
  42959. assert( !pPager->tempFile );
  42960. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  42961. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42962. assert( isOpen(pPager->jfd) );
  42963. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42964. /* This block deals with an obscure problem. If the last connection
  42965. ** that wrote to this database was operating in persistent-journal
  42966. ** mode, then the journal file may at this point actually be larger
  42967. ** than Pager.journalOff bytes. If the next thing in the journal
  42968. ** file happens to be a journal-header (written as part of the
  42969. ** previous connection's transaction), and a crash or power-failure
  42970. ** occurs after nRec is updated but before this connection writes
  42971. ** anything else to the journal file (or commits/rolls back its
  42972. ** transaction), then SQLite may become confused when doing the
  42973. ** hot-journal rollback following recovery. It may roll back all
  42974. ** of this connections data, then proceed to rolling back the old,
  42975. ** out-of-date data that follows it. Database corruption.
  42976. **
  42977. ** To work around this, if the journal file does appear to contain
  42978. ** a valid header following Pager.journalOff, then write a 0x00
  42979. ** byte to the start of it to prevent it from being recognized.
  42980. **
  42981. ** Variable iNextHdrOffset is set to the offset at which this
  42982. ** problematic header will occur, if it exists. aMagic is used
  42983. ** as a temporary buffer to inspect the first couple of bytes of
  42984. ** the potential journal header.
  42985. */
  42986. i64 iNextHdrOffset;
  42987. u8 aMagic[8];
  42988. u8 zHeader[sizeof(aJournalMagic)+4];
  42989. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42990. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  42991. iNextHdrOffset = journalHdrOffset(pPager);
  42992. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  42993. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  42994. static const u8 zerobyte = 0;
  42995. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  42996. }
  42997. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  42998. return rc;
  42999. }
  43000. /* Write the nRec value into the journal file header. If in
  43001. ** full-synchronous mode, sync the journal first. This ensures that
  43002. ** all data has really hit the disk before nRec is updated to mark
  43003. ** it as a candidate for rollback.
  43004. **
  43005. ** This is not required if the persistent media supports the
  43006. ** SAFE_APPEND property. Because in this case it is not possible
  43007. ** for garbage data to be appended to the file, the nRec field
  43008. ** is populated with 0xFFFFFFFF when the journal header is written
  43009. ** and never needs to be updated.
  43010. */
  43011. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43012. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43013. IOTRACE(("JSYNC %p\n", pPager))
  43014. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  43015. if( rc!=SQLITE_OK ) return rc;
  43016. }
  43017. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  43018. rc = sqlite3OsWrite(
  43019. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  43020. );
  43021. if( rc!=SQLITE_OK ) return rc;
  43022. }
  43023. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  43024. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  43025. IOTRACE(("JSYNC %p\n", pPager))
  43026. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  43027. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  43028. );
  43029. if( rc!=SQLITE_OK ) return rc;
  43030. }
  43031. pPager->journalHdr = pPager->journalOff;
  43032. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  43033. pPager->nRec = 0;
  43034. rc = writeJournalHdr(pPager);
  43035. if( rc!=SQLITE_OK ) return rc;
  43036. }
  43037. }else{
  43038. pPager->journalHdr = pPager->journalOff;
  43039. }
  43040. }
  43041. /* Unless the pager is in noSync mode, the journal file was just
  43042. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  43043. ** all pages.
  43044. */
  43045. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  43046. pPager->eState = PAGER_WRITER_DBMOD;
  43047. assert( assert_pager_state(pPager) );
  43048. return SQLITE_OK;
  43049. }
  43050. /*
  43051. ** The argument is the first in a linked list of dirty pages connected
  43052. ** by the PgHdr.pDirty pointer. This function writes each one of the
  43053. ** in-memory pages in the list to the database file. The argument may
  43054. ** be NULL, representing an empty list. In this case this function is
  43055. ** a no-op.
  43056. **
  43057. ** The pager must hold at least a RESERVED lock when this function
  43058. ** is called. Before writing anything to the database file, this lock
  43059. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  43060. ** SQLITE_BUSY is returned and no data is written to the database file.
  43061. **
  43062. ** If the pager is a temp-file pager and the actual file-system file
  43063. ** is not yet open, it is created and opened before any data is
  43064. ** written out.
  43065. **
  43066. ** Once the lock has been upgraded and, if necessary, the file opened,
  43067. ** the pages are written out to the database file in list order. Writing
  43068. ** a page is skipped if it meets either of the following criteria:
  43069. **
  43070. ** * The page number is greater than Pager.dbSize, or
  43071. ** * The PGHDR_DONT_WRITE flag is set on the page.
  43072. **
  43073. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  43074. ** is updated accordingly. If page 1 is written out, then the value cached
  43075. ** in Pager.dbFileVers[] is updated to match the new value stored in
  43076. ** the database file.
  43077. **
  43078. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43079. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  43080. ** be obtained, SQLITE_BUSY is returned.
  43081. */
  43082. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  43083. int rc = SQLITE_OK; /* Return code */
  43084. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  43085. assert( !pagerUseWal(pPager) );
  43086. assert( pPager->eState==PAGER_WRITER_DBMOD );
  43087. assert( pPager->eLock==EXCLUSIVE_LOCK );
  43088. /* If the file is a temp-file has not yet been opened, open it now. It
  43089. ** is not possible for rc to be other than SQLITE_OK if this branch
  43090. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  43091. */
  43092. if( !isOpen(pPager->fd) ){
  43093. assert( pPager->tempFile && rc==SQLITE_OK );
  43094. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  43095. }
  43096. /* Before the first write, give the VFS a hint of what the final
  43097. ** file size will be.
  43098. */
  43099. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  43100. if( rc==SQLITE_OK
  43101. && pPager->dbHintSize<pPager->dbSize
  43102. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  43103. ){
  43104. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  43105. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  43106. pPager->dbHintSize = pPager->dbSize;
  43107. }
  43108. while( rc==SQLITE_OK && pList ){
  43109. Pgno pgno = pList->pgno;
  43110. /* If there are dirty pages in the page cache with page numbers greater
  43111. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  43112. ** make the file smaller (presumably by auto-vacuum code). Do not write
  43113. ** any such pages to the file.
  43114. **
  43115. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  43116. ** set (set by sqlite3PagerDontWrite()).
  43117. */
  43118. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  43119. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  43120. char *pData; /* Data to write */
  43121. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  43122. if( pList->pgno==1 ) pager_write_changecounter(pList);
  43123. /* Encode the database */
  43124. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  43125. /* Write out the page data. */
  43126. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  43127. /* If page 1 was just written, update Pager.dbFileVers to match
  43128. ** the value now stored in the database file. If writing this
  43129. ** page caused the database file to grow, update dbFileSize.
  43130. */
  43131. if( pgno==1 ){
  43132. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  43133. }
  43134. if( pgno>pPager->dbFileSize ){
  43135. pPager->dbFileSize = pgno;
  43136. }
  43137. pPager->aStat[PAGER_STAT_WRITE]++;
  43138. /* Update any backup objects copying the contents of this pager. */
  43139. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  43140. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  43141. PAGERID(pPager), pgno, pager_pagehash(pList)));
  43142. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  43143. PAGER_INCR(sqlite3_pager_writedb_count);
  43144. }else{
  43145. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  43146. }
  43147. pager_set_pagehash(pList);
  43148. pList = pList->pDirty;
  43149. }
  43150. return rc;
  43151. }
  43152. /*
  43153. ** Ensure that the sub-journal file is open. If it is already open, this
  43154. ** function is a no-op.
  43155. **
  43156. ** SQLITE_OK is returned if everything goes according to plan. An
  43157. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  43158. ** fails.
  43159. */
  43160. static int openSubJournal(Pager *pPager){
  43161. int rc = SQLITE_OK;
  43162. if( !isOpen(pPager->sjfd) ){
  43163. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  43164. sqlite3MemJournalOpen(pPager->sjfd);
  43165. }else{
  43166. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  43167. }
  43168. }
  43169. return rc;
  43170. }
  43171. /*
  43172. ** Append a record of the current state of page pPg to the sub-journal.
  43173. ** It is the callers responsibility to use subjRequiresPage() to check
  43174. ** that it is really required before calling this function.
  43175. **
  43176. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  43177. ** for all open savepoints before returning.
  43178. **
  43179. ** This function returns SQLITE_OK if everything is successful, an IO
  43180. ** error code if the attempt to write to the sub-journal fails, or
  43181. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  43182. ** bitvec.
  43183. */
  43184. static int subjournalPage(PgHdr *pPg){
  43185. int rc = SQLITE_OK;
  43186. Pager *pPager = pPg->pPager;
  43187. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  43188. /* Open the sub-journal, if it has not already been opened */
  43189. assert( pPager->useJournal );
  43190. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  43191. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  43192. assert( pagerUseWal(pPager)
  43193. || pageInJournal(pPg)
  43194. || pPg->pgno>pPager->dbOrigSize
  43195. );
  43196. rc = openSubJournal(pPager);
  43197. /* If the sub-journal was opened successfully (or was already open),
  43198. ** write the journal record into the file. */
  43199. if( rc==SQLITE_OK ){
  43200. void *pData = pPg->pData;
  43201. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  43202. char *pData2;
  43203. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  43204. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  43205. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  43206. if( rc==SQLITE_OK ){
  43207. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  43208. }
  43209. }
  43210. }
  43211. if( rc==SQLITE_OK ){
  43212. pPager->nSubRec++;
  43213. assert( pPager->nSavepoint>0 );
  43214. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  43215. }
  43216. return rc;
  43217. }
  43218. /*
  43219. ** This function is called by the pcache layer when it has reached some
  43220. ** soft memory limit. The first argument is a pointer to a Pager object
  43221. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  43222. ** database). The second argument is a reference to a page that is
  43223. ** currently dirty but has no outstanding references. The page
  43224. ** is always associated with the Pager object passed as the first
  43225. ** argument.
  43226. **
  43227. ** The job of this function is to make pPg clean by writing its contents
  43228. ** out to the database file, if possible. This may involve syncing the
  43229. ** journal file.
  43230. **
  43231. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  43232. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  43233. ** page clean, the IO error code is returned. If the page cannot be
  43234. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  43235. ** is returned by sqlite3PcacheMakeClean() is not called.
  43236. */
  43237. static int pagerStress(void *p, PgHdr *pPg){
  43238. Pager *pPager = (Pager *)p;
  43239. int rc = SQLITE_OK;
  43240. assert( pPg->pPager==pPager );
  43241. assert( pPg->flags&PGHDR_DIRTY );
  43242. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  43243. ** journal (and adding a new header) is not allowed. This occurs
  43244. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  43245. ** pages belonging to the same sector.
  43246. **
  43247. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  43248. ** regardless of whether or not a sync is required. This is set during
  43249. ** a rollback or by user request, respectively.
  43250. **
  43251. ** Spilling is also prohibited when in an error state since that could
  43252. ** lead to database corruption. In the current implementaton it
  43253. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==1
  43254. ** while in the error state, hence it is impossible for this routine to
  43255. ** be called in the error state. Nevertheless, we include a NEVER()
  43256. ** test for the error state as a safeguard against future changes.
  43257. */
  43258. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  43259. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  43260. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  43261. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  43262. if( pPager->doNotSpill
  43263. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  43264. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  43265. ){
  43266. return SQLITE_OK;
  43267. }
  43268. pPg->pDirty = 0;
  43269. if( pagerUseWal(pPager) ){
  43270. /* Write a single frame for this page to the log. */
  43271. if( subjRequiresPage(pPg) ){
  43272. rc = subjournalPage(pPg);
  43273. }
  43274. if( rc==SQLITE_OK ){
  43275. rc = pagerWalFrames(pPager, pPg, 0, 0);
  43276. }
  43277. }else{
  43278. /* Sync the journal file if required. */
  43279. if( pPg->flags&PGHDR_NEED_SYNC
  43280. || pPager->eState==PAGER_WRITER_CACHEMOD
  43281. ){
  43282. rc = syncJournal(pPager, 1);
  43283. }
  43284. /* If the page number of this page is larger than the current size of
  43285. ** the database image, it may need to be written to the sub-journal.
  43286. ** This is because the call to pager_write_pagelist() below will not
  43287. ** actually write data to the file in this case.
  43288. **
  43289. ** Consider the following sequence of events:
  43290. **
  43291. ** BEGIN;
  43292. ** <journal page X>
  43293. ** <modify page X>
  43294. ** SAVEPOINT sp;
  43295. ** <shrink database file to Y pages>
  43296. ** pagerStress(page X)
  43297. ** ROLLBACK TO sp;
  43298. **
  43299. ** If (X>Y), then when pagerStress is called page X will not be written
  43300. ** out to the database file, but will be dropped from the cache. Then,
  43301. ** following the "ROLLBACK TO sp" statement, reading page X will read
  43302. ** data from the database file. This will be the copy of page X as it
  43303. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  43304. ** was executed.
  43305. **
  43306. ** The solution is to write the current data for page X into the
  43307. ** sub-journal file now (if it is not already there), so that it will
  43308. ** be restored to its current value when the "ROLLBACK TO sp" is
  43309. ** executed.
  43310. */
  43311. if( NEVER(
  43312. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  43313. ) ){
  43314. rc = subjournalPage(pPg);
  43315. }
  43316. /* Write the contents of the page out to the database file. */
  43317. if( rc==SQLITE_OK ){
  43318. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  43319. rc = pager_write_pagelist(pPager, pPg);
  43320. }
  43321. }
  43322. /* Mark the page as clean. */
  43323. if( rc==SQLITE_OK ){
  43324. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  43325. sqlite3PcacheMakeClean(pPg);
  43326. }
  43327. return pager_error(pPager, rc);
  43328. }
  43329. /*
  43330. ** Allocate and initialize a new Pager object and put a pointer to it
  43331. ** in *ppPager. The pager should eventually be freed by passing it
  43332. ** to sqlite3PagerClose().
  43333. **
  43334. ** The zFilename argument is the path to the database file to open.
  43335. ** If zFilename is NULL then a randomly-named temporary file is created
  43336. ** and used as the file to be cached. Temporary files are be deleted
  43337. ** automatically when they are closed. If zFilename is ":memory:" then
  43338. ** all information is held in cache. It is never written to disk.
  43339. ** This can be used to implement an in-memory database.
  43340. **
  43341. ** The nExtra parameter specifies the number of bytes of space allocated
  43342. ** along with each page reference. This space is available to the user
  43343. ** via the sqlite3PagerGetExtra() API.
  43344. **
  43345. ** The flags argument is used to specify properties that affect the
  43346. ** operation of the pager. It should be passed some bitwise combination
  43347. ** of the PAGER_* flags.
  43348. **
  43349. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  43350. ** of the xOpen() method of the supplied VFS when opening files.
  43351. **
  43352. ** If the pager object is allocated and the specified file opened
  43353. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  43354. ** the new pager object. If an error occurs, *ppPager is set to NULL
  43355. ** and error code returned. This function may return SQLITE_NOMEM
  43356. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  43357. ** various SQLITE_IO_XXX errors.
  43358. */
  43359. SQLITE_PRIVATE int sqlite3PagerOpen(
  43360. sqlite3_vfs *pVfs, /* The virtual file system to use */
  43361. Pager **ppPager, /* OUT: Return the Pager structure here */
  43362. const char *zFilename, /* Name of the database file to open */
  43363. int nExtra, /* Extra bytes append to each in-memory page */
  43364. int flags, /* flags controlling this file */
  43365. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  43366. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  43367. ){
  43368. u8 *pPtr;
  43369. Pager *pPager = 0; /* Pager object to allocate and return */
  43370. int rc = SQLITE_OK; /* Return code */
  43371. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  43372. int memDb = 0; /* True if this is an in-memory file */
  43373. int readOnly = 0; /* True if this is a read-only file */
  43374. int journalFileSize; /* Bytes to allocate for each journal fd */
  43375. char *zPathname = 0; /* Full path to database file */
  43376. int nPathname = 0; /* Number of bytes in zPathname */
  43377. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  43378. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  43379. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  43380. const char *zUri = 0; /* URI args to copy */
  43381. int nUri = 0; /* Number of bytes of URI args at *zUri */
  43382. /* Figure out how much space is required for each journal file-handle
  43383. ** (there are two of them, the main journal and the sub-journal). This
  43384. ** is the maximum space required for an in-memory journal file handle
  43385. ** and a regular journal file-handle. Note that a "regular journal-handle"
  43386. ** may be a wrapper capable of caching the first portion of the journal
  43387. ** file in memory to implement the atomic-write optimization (see
  43388. ** source file journal.c).
  43389. */
  43390. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  43391. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  43392. }else{
  43393. journalFileSize = ROUND8(sqlite3MemJournalSize());
  43394. }
  43395. /* Set the output variable to NULL in case an error occurs. */
  43396. *ppPager = 0;
  43397. #ifndef SQLITE_OMIT_MEMORYDB
  43398. if( flags & PAGER_MEMORY ){
  43399. memDb = 1;
  43400. if( zFilename && zFilename[0] ){
  43401. zPathname = sqlite3DbStrDup(0, zFilename);
  43402. if( zPathname==0 ) return SQLITE_NOMEM;
  43403. nPathname = sqlite3Strlen30(zPathname);
  43404. zFilename = 0;
  43405. }
  43406. }
  43407. #endif
  43408. /* Compute and store the full pathname in an allocated buffer pointed
  43409. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  43410. ** leave both nPathname and zPathname set to 0.
  43411. */
  43412. if( zFilename && zFilename[0] ){
  43413. const char *z;
  43414. nPathname = pVfs->mxPathname+1;
  43415. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  43416. if( zPathname==0 ){
  43417. return SQLITE_NOMEM;
  43418. }
  43419. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  43420. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  43421. nPathname = sqlite3Strlen30(zPathname);
  43422. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  43423. while( *z ){
  43424. z += sqlite3Strlen30(z)+1;
  43425. z += sqlite3Strlen30(z)+1;
  43426. }
  43427. nUri = (int)(&z[1] - zUri);
  43428. assert( nUri>=0 );
  43429. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  43430. /* This branch is taken when the journal path required by
  43431. ** the database being opened will be more than pVfs->mxPathname
  43432. ** bytes in length. This means the database cannot be opened,
  43433. ** as it will not be possible to open the journal file or even
  43434. ** check for a hot-journal before reading.
  43435. */
  43436. rc = SQLITE_CANTOPEN_BKPT;
  43437. }
  43438. if( rc!=SQLITE_OK ){
  43439. sqlite3DbFree(0, zPathname);
  43440. return rc;
  43441. }
  43442. }
  43443. /* Allocate memory for the Pager structure, PCache object, the
  43444. ** three file descriptors, the database file name and the journal
  43445. ** file name. The layout in memory is as follows:
  43446. **
  43447. ** Pager object (sizeof(Pager) bytes)
  43448. ** PCache object (sqlite3PcacheSize() bytes)
  43449. ** Database file handle (pVfs->szOsFile bytes)
  43450. ** Sub-journal file handle (journalFileSize bytes)
  43451. ** Main journal file handle (journalFileSize bytes)
  43452. ** Database file name (nPathname+1 bytes)
  43453. ** Journal file name (nPathname+8+1 bytes)
  43454. */
  43455. pPtr = (u8 *)sqlite3MallocZero(
  43456. ROUND8(sizeof(*pPager)) + /* Pager structure */
  43457. ROUND8(pcacheSize) + /* PCache object */
  43458. ROUND8(pVfs->szOsFile) + /* The main db file */
  43459. journalFileSize * 2 + /* The two journal files */
  43460. nPathname + 1 + nUri + /* zFilename */
  43461. nPathname + 8 + 2 /* zJournal */
  43462. #ifndef SQLITE_OMIT_WAL
  43463. + nPathname + 4 + 2 /* zWal */
  43464. #endif
  43465. );
  43466. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  43467. if( !pPtr ){
  43468. sqlite3DbFree(0, zPathname);
  43469. return SQLITE_NOMEM;
  43470. }
  43471. pPager = (Pager*)(pPtr);
  43472. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  43473. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  43474. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  43475. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  43476. pPager->zFilename = (char*)(pPtr += journalFileSize);
  43477. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  43478. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  43479. if( zPathname ){
  43480. assert( nPathname>0 );
  43481. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  43482. memcpy(pPager->zFilename, zPathname, nPathname);
  43483. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  43484. memcpy(pPager->zJournal, zPathname, nPathname);
  43485. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  43486. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  43487. #ifndef SQLITE_OMIT_WAL
  43488. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  43489. memcpy(pPager->zWal, zPathname, nPathname);
  43490. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  43491. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  43492. #endif
  43493. sqlite3DbFree(0, zPathname);
  43494. }
  43495. pPager->pVfs = pVfs;
  43496. pPager->vfsFlags = vfsFlags;
  43497. /* Open the pager file.
  43498. */
  43499. if( zFilename && zFilename[0] ){
  43500. int fout = 0; /* VFS flags returned by xOpen() */
  43501. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  43502. assert( !memDb );
  43503. readOnly = (fout&SQLITE_OPEN_READONLY);
  43504. /* If the file was successfully opened for read/write access,
  43505. ** choose a default page size in case we have to create the
  43506. ** database file. The default page size is the maximum of:
  43507. **
  43508. ** + SQLITE_DEFAULT_PAGE_SIZE,
  43509. ** + The value returned by sqlite3OsSectorSize()
  43510. ** + The largest page size that can be written atomically.
  43511. */
  43512. if( rc==SQLITE_OK && !readOnly ){
  43513. setSectorSize(pPager);
  43514. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  43515. if( szPageDflt<pPager->sectorSize ){
  43516. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  43517. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  43518. }else{
  43519. szPageDflt = (u32)pPager->sectorSize;
  43520. }
  43521. }
  43522. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43523. {
  43524. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  43525. int ii;
  43526. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  43527. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  43528. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  43529. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  43530. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  43531. szPageDflt = ii;
  43532. }
  43533. }
  43534. }
  43535. #endif
  43536. }
  43537. }else{
  43538. /* If a temporary file is requested, it is not opened immediately.
  43539. ** In this case we accept the default page size and delay actually
  43540. ** opening the file until the first call to OsWrite().
  43541. **
  43542. ** This branch is also run for an in-memory database. An in-memory
  43543. ** database is the same as a temp-file that is never written out to
  43544. ** disk and uses an in-memory rollback journal.
  43545. */
  43546. tempFile = 1;
  43547. pPager->eState = PAGER_READER;
  43548. pPager->eLock = EXCLUSIVE_LOCK;
  43549. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  43550. }
  43551. /* The following call to PagerSetPagesize() serves to set the value of
  43552. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  43553. */
  43554. if( rc==SQLITE_OK ){
  43555. assert( pPager->memDb==0 );
  43556. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  43557. testcase( rc!=SQLITE_OK );
  43558. }
  43559. /* If an error occurred in either of the blocks above, free the
  43560. ** Pager structure and close the file.
  43561. */
  43562. if( rc!=SQLITE_OK ){
  43563. assert( !pPager->pTmpSpace );
  43564. sqlite3OsClose(pPager->fd);
  43565. sqlite3_free(pPager);
  43566. return rc;
  43567. }
  43568. /* Initialize the PCache object. */
  43569. assert( nExtra<1000 );
  43570. nExtra = ROUND8(nExtra);
  43571. sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  43572. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  43573. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  43574. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  43575. pPager->useJournal = (u8)useJournal;
  43576. /* pPager->stmtOpen = 0; */
  43577. /* pPager->stmtInUse = 0; */
  43578. /* pPager->nRef = 0; */
  43579. /* pPager->stmtSize = 0; */
  43580. /* pPager->stmtJSize = 0; */
  43581. /* pPager->nPage = 0; */
  43582. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  43583. /* pPager->state = PAGER_UNLOCK; */
  43584. #if 0
  43585. assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
  43586. #endif
  43587. /* pPager->errMask = 0; */
  43588. pPager->tempFile = (u8)tempFile;
  43589. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  43590. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  43591. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  43592. pPager->exclusiveMode = (u8)tempFile;
  43593. pPager->changeCountDone = pPager->tempFile;
  43594. pPager->memDb = (u8)memDb;
  43595. pPager->readOnly = (u8)readOnly;
  43596. assert( useJournal || pPager->tempFile );
  43597. pPager->noSync = pPager->tempFile;
  43598. if( pPager->noSync ){
  43599. assert( pPager->fullSync==0 );
  43600. assert( pPager->syncFlags==0 );
  43601. assert( pPager->walSyncFlags==0 );
  43602. assert( pPager->ckptSyncFlags==0 );
  43603. }else{
  43604. pPager->fullSync = 1;
  43605. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  43606. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  43607. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  43608. }
  43609. /* pPager->pFirst = 0; */
  43610. /* pPager->pFirstSynced = 0; */
  43611. /* pPager->pLast = 0; */
  43612. pPager->nExtra = (u16)nExtra;
  43613. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  43614. assert( isOpen(pPager->fd) || tempFile );
  43615. setSectorSize(pPager);
  43616. if( !useJournal ){
  43617. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  43618. }else if( memDb ){
  43619. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  43620. }
  43621. /* pPager->xBusyHandler = 0; */
  43622. /* pPager->pBusyHandlerArg = 0; */
  43623. pPager->xReiniter = xReinit;
  43624. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  43625. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  43626. *ppPager = pPager;
  43627. return SQLITE_OK;
  43628. }
  43629. /*
  43630. ** This function is called after transitioning from PAGER_UNLOCK to
  43631. ** PAGER_SHARED state. It tests if there is a hot journal present in
  43632. ** the file-system for the given pager. A hot journal is one that
  43633. ** needs to be played back. According to this function, a hot-journal
  43634. ** file exists if the following criteria are met:
  43635. **
  43636. ** * The journal file exists in the file system, and
  43637. ** * No process holds a RESERVED or greater lock on the database file, and
  43638. ** * The database file itself is greater than 0 bytes in size, and
  43639. ** * The first byte of the journal file exists and is not 0x00.
  43640. **
  43641. ** If the current size of the database file is 0 but a journal file
  43642. ** exists, that is probably an old journal left over from a prior
  43643. ** database with the same name. In this case the journal file is
  43644. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  43645. ** is returned.
  43646. **
  43647. ** This routine does not check if there is a master journal filename
  43648. ** at the end of the file. If there is, and that master journal file
  43649. ** does not exist, then the journal file is not really hot. In this
  43650. ** case this routine will return a false-positive. The pager_playback()
  43651. ** routine will discover that the journal file is not really hot and
  43652. ** will not roll it back.
  43653. **
  43654. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  43655. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  43656. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  43657. ** to determine whether or not a hot-journal file exists, the IO error
  43658. ** code is returned and the value of *pExists is undefined.
  43659. */
  43660. static int hasHotJournal(Pager *pPager, int *pExists){
  43661. sqlite3_vfs * const pVfs = pPager->pVfs;
  43662. int rc = SQLITE_OK; /* Return code */
  43663. int exists = 1; /* True if a journal file is present */
  43664. int jrnlOpen = !!isOpen(pPager->jfd);
  43665. assert( pPager->useJournal );
  43666. assert( isOpen(pPager->fd) );
  43667. assert( pPager->eState==PAGER_OPEN );
  43668. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  43669. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  43670. ));
  43671. *pExists = 0;
  43672. if( !jrnlOpen ){
  43673. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  43674. }
  43675. if( rc==SQLITE_OK && exists ){
  43676. int locked = 0; /* True if some process holds a RESERVED lock */
  43677. /* Race condition here: Another process might have been holding the
  43678. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  43679. ** call above, but then delete the journal and drop the lock before
  43680. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  43681. ** is the case, this routine might think there is a hot journal when
  43682. ** in fact there is none. This results in a false-positive which will
  43683. ** be dealt with by the playback routine. Ticket #3883.
  43684. */
  43685. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  43686. if( rc==SQLITE_OK && !locked ){
  43687. Pgno nPage; /* Number of pages in database file */
  43688. /* Check the size of the database file. If it consists of 0 pages,
  43689. ** then delete the journal file. See the header comment above for
  43690. ** the reasoning here. Delete the obsolete journal file under
  43691. ** a RESERVED lock to avoid race conditions and to avoid violating
  43692. ** [H33020].
  43693. */
  43694. rc = pagerPagecount(pPager, &nPage);
  43695. if( rc==SQLITE_OK ){
  43696. if( nPage==0 ){
  43697. sqlite3BeginBenignMalloc();
  43698. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  43699. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  43700. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  43701. }
  43702. sqlite3EndBenignMalloc();
  43703. }else{
  43704. /* The journal file exists and no other connection has a reserved
  43705. ** or greater lock on the database file. Now check that there is
  43706. ** at least one non-zero bytes at the start of the journal file.
  43707. ** If there is, then we consider this journal to be hot. If not,
  43708. ** it can be ignored.
  43709. */
  43710. if( !jrnlOpen ){
  43711. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  43712. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  43713. }
  43714. if( rc==SQLITE_OK ){
  43715. u8 first = 0;
  43716. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  43717. if( rc==SQLITE_IOERR_SHORT_READ ){
  43718. rc = SQLITE_OK;
  43719. }
  43720. if( !jrnlOpen ){
  43721. sqlite3OsClose(pPager->jfd);
  43722. }
  43723. *pExists = (first!=0);
  43724. }else if( rc==SQLITE_CANTOPEN ){
  43725. /* If we cannot open the rollback journal file in order to see if
  43726. ** its has a zero header, that might be due to an I/O error, or
  43727. ** it might be due to the race condition described above and in
  43728. ** ticket #3883. Either way, assume that the journal is hot.
  43729. ** This might be a false positive. But if it is, then the
  43730. ** automatic journal playback and recovery mechanism will deal
  43731. ** with it under an EXCLUSIVE lock where we do not need to
  43732. ** worry so much with race conditions.
  43733. */
  43734. *pExists = 1;
  43735. rc = SQLITE_OK;
  43736. }
  43737. }
  43738. }
  43739. }
  43740. }
  43741. return rc;
  43742. }
  43743. /*
  43744. ** This function is called to obtain a shared lock on the database file.
  43745. ** It is illegal to call sqlite3PagerAcquire() until after this function
  43746. ** has been successfully called. If a shared-lock is already held when
  43747. ** this function is called, it is a no-op.
  43748. **
  43749. ** The following operations are also performed by this function.
  43750. **
  43751. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  43752. ** on the database file), then an attempt is made to obtain a
  43753. ** SHARED lock on the database file. Immediately after obtaining
  43754. ** the SHARED lock, the file-system is checked for a hot-journal,
  43755. ** which is played back if present. Following any hot-journal
  43756. ** rollback, the contents of the cache are validated by checking
  43757. ** the 'change-counter' field of the database file header and
  43758. ** discarded if they are found to be invalid.
  43759. **
  43760. ** 2) If the pager is running in exclusive-mode, and there are currently
  43761. ** no outstanding references to any pages, and is in the error state,
  43762. ** then an attempt is made to clear the error state by discarding
  43763. ** the contents of the page cache and rolling back any open journal
  43764. ** file.
  43765. **
  43766. ** If everything is successful, SQLITE_OK is returned. If an IO error
  43767. ** occurs while locking the database, checking for a hot-journal file or
  43768. ** rolling back a journal file, the IO error code is returned.
  43769. */
  43770. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  43771. int rc = SQLITE_OK; /* Return code */
  43772. /* This routine is only called from b-tree and only when there are no
  43773. ** outstanding pages. This implies that the pager state should either
  43774. ** be OPEN or READER. READER is only possible if the pager is or was in
  43775. ** exclusive access mode.
  43776. */
  43777. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  43778. assert( assert_pager_state(pPager) );
  43779. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  43780. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  43781. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  43782. int bHotJournal = 1; /* True if there exists a hot journal-file */
  43783. assert( !MEMDB );
  43784. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  43785. if( rc!=SQLITE_OK ){
  43786. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  43787. goto failed;
  43788. }
  43789. /* If a journal file exists, and there is no RESERVED lock on the
  43790. ** database file, then it either needs to be played back or deleted.
  43791. */
  43792. if( pPager->eLock<=SHARED_LOCK ){
  43793. rc = hasHotJournal(pPager, &bHotJournal);
  43794. }
  43795. if( rc!=SQLITE_OK ){
  43796. goto failed;
  43797. }
  43798. if( bHotJournal ){
  43799. if( pPager->readOnly ){
  43800. rc = SQLITE_READONLY_ROLLBACK;
  43801. goto failed;
  43802. }
  43803. /* Get an EXCLUSIVE lock on the database file. At this point it is
  43804. ** important that a RESERVED lock is not obtained on the way to the
  43805. ** EXCLUSIVE lock. If it were, another process might open the
  43806. ** database file, detect the RESERVED lock, and conclude that the
  43807. ** database is safe to read while this process is still rolling the
  43808. ** hot-journal back.
  43809. **
  43810. ** Because the intermediate RESERVED lock is not requested, any
  43811. ** other process attempting to access the database file will get to
  43812. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  43813. ** on the database file.
  43814. **
  43815. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  43816. ** downgraded to SHARED_LOCK before this function returns.
  43817. */
  43818. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  43819. if( rc!=SQLITE_OK ){
  43820. goto failed;
  43821. }
  43822. /* If it is not already open and the file exists on disk, open the
  43823. ** journal for read/write access. Write access is required because
  43824. ** in exclusive-access mode the file descriptor will be kept open
  43825. ** and possibly used for a transaction later on. Also, write-access
  43826. ** is usually required to finalize the journal in journal_mode=persist
  43827. ** mode (and also for journal_mode=truncate on some systems).
  43828. **
  43829. ** If the journal does not exist, it usually means that some
  43830. ** other connection managed to get in and roll it back before
  43831. ** this connection obtained the exclusive lock above. Or, it
  43832. ** may mean that the pager was in the error-state when this
  43833. ** function was called and the journal file does not exist.
  43834. */
  43835. if( !isOpen(pPager->jfd) ){
  43836. sqlite3_vfs * const pVfs = pPager->pVfs;
  43837. int bExists; /* True if journal file exists */
  43838. rc = sqlite3OsAccess(
  43839. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  43840. if( rc==SQLITE_OK && bExists ){
  43841. int fout = 0;
  43842. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  43843. assert( !pPager->tempFile );
  43844. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  43845. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  43846. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  43847. rc = SQLITE_CANTOPEN_BKPT;
  43848. sqlite3OsClose(pPager->jfd);
  43849. }
  43850. }
  43851. }
  43852. /* Playback and delete the journal. Drop the database write
  43853. ** lock and reacquire the read lock. Purge the cache before
  43854. ** playing back the hot-journal so that we don't end up with
  43855. ** an inconsistent cache. Sync the hot journal before playing
  43856. ** it back since the process that crashed and left the hot journal
  43857. ** probably did not sync it and we are required to always sync
  43858. ** the journal before playing it back.
  43859. */
  43860. if( isOpen(pPager->jfd) ){
  43861. assert( rc==SQLITE_OK );
  43862. rc = pagerSyncHotJournal(pPager);
  43863. if( rc==SQLITE_OK ){
  43864. rc = pager_playback(pPager, 1);
  43865. pPager->eState = PAGER_OPEN;
  43866. }
  43867. }else if( !pPager->exclusiveMode ){
  43868. pagerUnlockDb(pPager, SHARED_LOCK);
  43869. }
  43870. if( rc!=SQLITE_OK ){
  43871. /* This branch is taken if an error occurs while trying to open
  43872. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  43873. ** pager_unlock() routine will be called before returning to unlock
  43874. ** the file. If the unlock attempt fails, then Pager.eLock must be
  43875. ** set to UNKNOWN_LOCK (see the comment above the #define for
  43876. ** UNKNOWN_LOCK above for an explanation).
  43877. **
  43878. ** In order to get pager_unlock() to do this, set Pager.eState to
  43879. ** PAGER_ERROR now. This is not actually counted as a transition
  43880. ** to ERROR state in the state diagram at the top of this file,
  43881. ** since we know that the same call to pager_unlock() will very
  43882. ** shortly transition the pager object to the OPEN state. Calling
  43883. ** assert_pager_state() would fail now, as it should not be possible
  43884. ** to be in ERROR state when there are zero outstanding page
  43885. ** references.
  43886. */
  43887. pager_error(pPager, rc);
  43888. goto failed;
  43889. }
  43890. assert( pPager->eState==PAGER_OPEN );
  43891. assert( (pPager->eLock==SHARED_LOCK)
  43892. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  43893. );
  43894. }
  43895. if( !pPager->tempFile && (
  43896. pPager->pBackup
  43897. || sqlite3PcachePagecount(pPager->pPCache)>0
  43898. || USEFETCH(pPager)
  43899. )){
  43900. /* The shared-lock has just been acquired on the database file
  43901. ** and there are already pages in the cache (from a previous
  43902. ** read or write transaction). Check to see if the database
  43903. ** has been modified. If the database has changed, flush the
  43904. ** cache.
  43905. **
  43906. ** Database changes is detected by looking at 15 bytes beginning
  43907. ** at offset 24 into the file. The first 4 of these 16 bytes are
  43908. ** a 32-bit counter that is incremented with each change. The
  43909. ** other bytes change randomly with each file change when
  43910. ** a codec is in use.
  43911. **
  43912. ** There is a vanishingly small chance that a change will not be
  43913. ** detected. The chance of an undetected change is so small that
  43914. ** it can be neglected.
  43915. */
  43916. Pgno nPage = 0;
  43917. char dbFileVers[sizeof(pPager->dbFileVers)];
  43918. rc = pagerPagecount(pPager, &nPage);
  43919. if( rc ) goto failed;
  43920. if( nPage>0 ){
  43921. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  43922. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  43923. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43924. goto failed;
  43925. }
  43926. }else{
  43927. memset(dbFileVers, 0, sizeof(dbFileVers));
  43928. }
  43929. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  43930. pager_reset(pPager);
  43931. /* Unmap the database file. It is possible that external processes
  43932. ** may have truncated the database file and then extended it back
  43933. ** to its original size while this process was not holding a lock.
  43934. ** In this case there may exist a Pager.pMap mapping that appears
  43935. ** to be the right size but is not actually valid. Avoid this
  43936. ** possibility by unmapping the db here. */
  43937. if( USEFETCH(pPager) ){
  43938. sqlite3OsUnfetch(pPager->fd, 0, 0);
  43939. }
  43940. }
  43941. }
  43942. /* If there is a WAL file in the file-system, open this database in WAL
  43943. ** mode. Otherwise, the following function call is a no-op.
  43944. */
  43945. rc = pagerOpenWalIfPresent(pPager);
  43946. #ifndef SQLITE_OMIT_WAL
  43947. assert( pPager->pWal==0 || rc==SQLITE_OK );
  43948. #endif
  43949. }
  43950. if( pagerUseWal(pPager) ){
  43951. assert( rc==SQLITE_OK );
  43952. rc = pagerBeginReadTransaction(pPager);
  43953. }
  43954. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  43955. rc = pagerPagecount(pPager, &pPager->dbSize);
  43956. }
  43957. failed:
  43958. if( rc!=SQLITE_OK ){
  43959. assert( !MEMDB );
  43960. pager_unlock(pPager);
  43961. assert( pPager->eState==PAGER_OPEN );
  43962. }else{
  43963. pPager->eState = PAGER_READER;
  43964. }
  43965. return rc;
  43966. }
  43967. /*
  43968. ** If the reference count has reached zero, rollback any active
  43969. ** transaction and unlock the pager.
  43970. **
  43971. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  43972. ** the rollback journal, the unlock is not performed and there is
  43973. ** nothing to rollback, so this routine is a no-op.
  43974. */
  43975. static void pagerUnlockIfUnused(Pager *pPager){
  43976. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  43977. pagerUnlockAndRollback(pPager);
  43978. }
  43979. }
  43980. /*
  43981. ** Acquire a reference to page number pgno in pager pPager (a page
  43982. ** reference has type DbPage*). If the requested reference is
  43983. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  43984. **
  43985. ** If the requested page is already in the cache, it is returned.
  43986. ** Otherwise, a new page object is allocated and populated with data
  43987. ** read from the database file. In some cases, the pcache module may
  43988. ** choose not to allocate a new page object and may reuse an existing
  43989. ** object with no outstanding references.
  43990. **
  43991. ** The extra data appended to a page is always initialized to zeros the
  43992. ** first time a page is loaded into memory. If the page requested is
  43993. ** already in the cache when this function is called, then the extra
  43994. ** data is left as it was when the page object was last used.
  43995. **
  43996. ** If the database image is smaller than the requested page or if a
  43997. ** non-zero value is passed as the noContent parameter and the
  43998. ** requested page is not already stored in the cache, then no
  43999. ** actual disk read occurs. In this case the memory image of the
  44000. ** page is initialized to all zeros.
  44001. **
  44002. ** If noContent is true, it means that we do not care about the contents
  44003. ** of the page. This occurs in two scenarios:
  44004. **
  44005. ** a) When reading a free-list leaf page from the database, and
  44006. **
  44007. ** b) When a savepoint is being rolled back and we need to load
  44008. ** a new page into the cache to be filled with the data read
  44009. ** from the savepoint journal.
  44010. **
  44011. ** If noContent is true, then the data returned is zeroed instead of
  44012. ** being read from the database. Additionally, the bits corresponding
  44013. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  44014. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  44015. ** savepoints are set. This means if the page is made writable at any
  44016. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  44017. ** will not be journaled. This saves IO.
  44018. **
  44019. ** The acquisition might fail for several reasons. In all cases,
  44020. ** an appropriate error code is returned and *ppPage is set to NULL.
  44021. **
  44022. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  44023. ** to find a page in the in-memory cache first. If the page is not already
  44024. ** in memory, this routine goes to disk to read it in whereas Lookup()
  44025. ** just returns 0. This routine acquires a read-lock the first time it
  44026. ** has to go to disk, and could also playback an old journal if necessary.
  44027. ** Since Lookup() never goes to disk, it never has to deal with locks
  44028. ** or journal files.
  44029. */
  44030. SQLITE_PRIVATE int sqlite3PagerAcquire(
  44031. Pager *pPager, /* The pager open on the database file */
  44032. Pgno pgno, /* Page number to fetch */
  44033. DbPage **ppPage, /* Write a pointer to the page here */
  44034. int flags /* PAGER_GET_XXX flags */
  44035. ){
  44036. int rc = SQLITE_OK;
  44037. PgHdr *pPg = 0;
  44038. u32 iFrame = 0; /* Frame to read from WAL file */
  44039. const int noContent = (flags & PAGER_GET_NOCONTENT);
  44040. /* It is acceptable to use a read-only (mmap) page for any page except
  44041. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  44042. ** flag was specified by the caller. And so long as the db is not a
  44043. ** temporary or in-memory database. */
  44044. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  44045. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  44046. #ifdef SQLITE_HAS_CODEC
  44047. && pPager->xCodec==0
  44048. #endif
  44049. );
  44050. assert( pPager->eState>=PAGER_READER );
  44051. assert( assert_pager_state(pPager) );
  44052. assert( noContent==0 || bMmapOk==0 );
  44053. if( pgno==0 ){
  44054. return SQLITE_CORRUPT_BKPT;
  44055. }
  44056. /* If the pager is in the error state, return an error immediately.
  44057. ** Otherwise, request the page from the PCache layer. */
  44058. if( pPager->errCode!=SQLITE_OK ){
  44059. rc = pPager->errCode;
  44060. }else{
  44061. if( bMmapOk && pagerUseWal(pPager) ){
  44062. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44063. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44064. }
  44065. if( iFrame==0 && bMmapOk ){
  44066. void *pData = 0;
  44067. rc = sqlite3OsFetch(pPager->fd,
  44068. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  44069. );
  44070. if( rc==SQLITE_OK && pData ){
  44071. if( pPager->eState>PAGER_READER ){
  44072. (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  44073. }
  44074. if( pPg==0 ){
  44075. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  44076. }else{
  44077. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  44078. }
  44079. if( pPg ){
  44080. assert( rc==SQLITE_OK );
  44081. *ppPage = pPg;
  44082. return SQLITE_OK;
  44083. }
  44084. }
  44085. if( rc!=SQLITE_OK ){
  44086. goto pager_acquire_err;
  44087. }
  44088. }
  44089. rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
  44090. }
  44091. if( rc!=SQLITE_OK ){
  44092. /* Either the call to sqlite3PcacheFetch() returned an error or the
  44093. ** pager was already in the error-state when this function was called.
  44094. ** Set pPg to 0 and jump to the exception handler. */
  44095. pPg = 0;
  44096. goto pager_acquire_err;
  44097. }
  44098. assert( (*ppPage)->pgno==pgno );
  44099. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  44100. if( (*ppPage)->pPager && !noContent ){
  44101. /* In this case the pcache already contains an initialized copy of
  44102. ** the page. Return without further ado. */
  44103. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  44104. pPager->aStat[PAGER_STAT_HIT]++;
  44105. return SQLITE_OK;
  44106. }else{
  44107. /* The pager cache has created a new page. Its content needs to
  44108. ** be initialized. */
  44109. pPg = *ppPage;
  44110. pPg->pPager = pPager;
  44111. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  44112. ** number greater than this, or the unused locking-page, is requested. */
  44113. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  44114. rc = SQLITE_CORRUPT_BKPT;
  44115. goto pager_acquire_err;
  44116. }
  44117. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  44118. if( pgno>pPager->mxPgno ){
  44119. rc = SQLITE_FULL;
  44120. goto pager_acquire_err;
  44121. }
  44122. if( noContent ){
  44123. /* Failure to set the bits in the InJournal bit-vectors is benign.
  44124. ** It merely means that we might do some extra work to journal a
  44125. ** page that does not need to be journaled. Nevertheless, be sure
  44126. ** to test the case where a malloc error occurs while trying to set
  44127. ** a bit in a bit vector.
  44128. */
  44129. sqlite3BeginBenignMalloc();
  44130. if( pgno<=pPager->dbOrigSize ){
  44131. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  44132. testcase( rc==SQLITE_NOMEM );
  44133. }
  44134. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  44135. testcase( rc==SQLITE_NOMEM );
  44136. sqlite3EndBenignMalloc();
  44137. }
  44138. memset(pPg->pData, 0, pPager->pageSize);
  44139. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  44140. }else{
  44141. if( pagerUseWal(pPager) && bMmapOk==0 ){
  44142. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  44143. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  44144. }
  44145. assert( pPg->pPager==pPager );
  44146. pPager->aStat[PAGER_STAT_MISS]++;
  44147. rc = readDbPage(pPg, iFrame);
  44148. if( rc!=SQLITE_OK ){
  44149. goto pager_acquire_err;
  44150. }
  44151. }
  44152. pager_set_pagehash(pPg);
  44153. }
  44154. return SQLITE_OK;
  44155. pager_acquire_err:
  44156. assert( rc!=SQLITE_OK );
  44157. if( pPg ){
  44158. sqlite3PcacheDrop(pPg);
  44159. }
  44160. pagerUnlockIfUnused(pPager);
  44161. *ppPage = 0;
  44162. return rc;
  44163. }
  44164. /*
  44165. ** Acquire a page if it is already in the in-memory cache. Do
  44166. ** not read the page from disk. Return a pointer to the page,
  44167. ** or 0 if the page is not in cache.
  44168. **
  44169. ** See also sqlite3PagerGet(). The difference between this routine
  44170. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  44171. ** in the page if the page is not already in cache. This routine
  44172. ** returns NULL if the page is not in cache or if a disk I/O error
  44173. ** has ever happened.
  44174. */
  44175. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  44176. PgHdr *pPg = 0;
  44177. assert( pPager!=0 );
  44178. assert( pgno!=0 );
  44179. assert( pPager->pPCache!=0 );
  44180. assert( pPager->eState>=PAGER_READER && pPager->eState!=PAGER_ERROR );
  44181. sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
  44182. return pPg;
  44183. }
  44184. /*
  44185. ** Release a page reference.
  44186. **
  44187. ** If the number of references to the page drop to zero, then the
  44188. ** page is added to the LRU list. When all references to all pages
  44189. ** are released, a rollback occurs and the lock on the database is
  44190. ** removed.
  44191. */
  44192. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  44193. if( pPg ){
  44194. Pager *pPager = pPg->pPager;
  44195. if( pPg->flags & PGHDR_MMAP ){
  44196. pagerReleaseMapPage(pPg);
  44197. }else{
  44198. sqlite3PcacheRelease(pPg);
  44199. }
  44200. pagerUnlockIfUnused(pPager);
  44201. }
  44202. }
  44203. /*
  44204. ** This function is called at the start of every write transaction.
  44205. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  44206. ** file when this routine is called.
  44207. **
  44208. ** Open the journal file for pager pPager and write a journal header
  44209. ** to the start of it. If there are active savepoints, open the sub-journal
  44210. ** as well. This function is only used when the journal file is being
  44211. ** opened to write a rollback log for a transaction. It is not used
  44212. ** when opening a hot journal file to roll it back.
  44213. **
  44214. ** If the journal file is already open (as it may be in exclusive mode),
  44215. ** then this function just writes a journal header to the start of the
  44216. ** already open file.
  44217. **
  44218. ** Whether or not the journal file is opened by this function, the
  44219. ** Pager.pInJournal bitvec structure is allocated.
  44220. **
  44221. ** Return SQLITE_OK if everything is successful. Otherwise, return
  44222. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  44223. ** an IO error code if opening or writing the journal file fails.
  44224. */
  44225. static int pager_open_journal(Pager *pPager){
  44226. int rc = SQLITE_OK; /* Return code */
  44227. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  44228. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44229. assert( assert_pager_state(pPager) );
  44230. assert( pPager->pInJournal==0 );
  44231. /* If already in the error state, this function is a no-op. But on
  44232. ** the other hand, this routine is never called if we are already in
  44233. ** an error state. */
  44234. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44235. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  44236. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  44237. if( pPager->pInJournal==0 ){
  44238. return SQLITE_NOMEM;
  44239. }
  44240. /* Open the journal file if it is not already open. */
  44241. if( !isOpen(pPager->jfd) ){
  44242. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  44243. sqlite3MemJournalOpen(pPager->jfd);
  44244. }else{
  44245. const int flags = /* VFS flags to open journal file */
  44246. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  44247. (pPager->tempFile ?
  44248. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  44249. (SQLITE_OPEN_MAIN_JOURNAL)
  44250. );
  44251. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44252. rc = sqlite3JournalOpen(
  44253. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  44254. );
  44255. #else
  44256. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  44257. #endif
  44258. }
  44259. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  44260. }
  44261. /* Write the first journal header to the journal file and open
  44262. ** the sub-journal if necessary.
  44263. */
  44264. if( rc==SQLITE_OK ){
  44265. /* TODO: Check if all of these are really required. */
  44266. pPager->nRec = 0;
  44267. pPager->journalOff = 0;
  44268. pPager->setMaster = 0;
  44269. pPager->journalHdr = 0;
  44270. rc = writeJournalHdr(pPager);
  44271. }
  44272. }
  44273. if( rc!=SQLITE_OK ){
  44274. sqlite3BitvecDestroy(pPager->pInJournal);
  44275. pPager->pInJournal = 0;
  44276. }else{
  44277. assert( pPager->eState==PAGER_WRITER_LOCKED );
  44278. pPager->eState = PAGER_WRITER_CACHEMOD;
  44279. }
  44280. return rc;
  44281. }
  44282. /*
  44283. ** Begin a write-transaction on the specified pager object. If a
  44284. ** write-transaction has already been opened, this function is a no-op.
  44285. **
  44286. ** If the exFlag argument is false, then acquire at least a RESERVED
  44287. ** lock on the database file. If exFlag is true, then acquire at least
  44288. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  44289. ** functions need be called.
  44290. **
  44291. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  44292. ** within this transaction will be opened as an in-memory file. This
  44293. ** has no effect if the sub-journal is already opened (as it may be when
  44294. ** running in exclusive mode) or if the transaction does not require a
  44295. ** sub-journal. If the subjInMemory argument is zero, then any required
  44296. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  44297. ** or using a temporary file otherwise.
  44298. */
  44299. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  44300. int rc = SQLITE_OK;
  44301. if( pPager->errCode ) return pPager->errCode;
  44302. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  44303. pPager->subjInMemory = (u8)subjInMemory;
  44304. if( ALWAYS(pPager->eState==PAGER_READER) ){
  44305. assert( pPager->pInJournal==0 );
  44306. if( pagerUseWal(pPager) ){
  44307. /* If the pager is configured to use locking_mode=exclusive, and an
  44308. ** exclusive lock on the database is not already held, obtain it now.
  44309. */
  44310. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  44311. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44312. if( rc!=SQLITE_OK ){
  44313. return rc;
  44314. }
  44315. sqlite3WalExclusiveMode(pPager->pWal, 1);
  44316. }
  44317. /* Grab the write lock on the log file. If successful, upgrade to
  44318. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  44319. ** The busy-handler is not invoked if another connection already
  44320. ** holds the write-lock. If possible, the upper layer will call it.
  44321. */
  44322. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  44323. }else{
  44324. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  44325. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  44326. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  44327. ** lock, but not when obtaining the RESERVED lock.
  44328. */
  44329. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44330. if( rc==SQLITE_OK && exFlag ){
  44331. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44332. }
  44333. }
  44334. if( rc==SQLITE_OK ){
  44335. /* Change to WRITER_LOCKED state.
  44336. **
  44337. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  44338. ** when it has an open transaction, but never to DBMOD or FINISHED.
  44339. ** This is because in those states the code to roll back savepoint
  44340. ** transactions may copy data from the sub-journal into the database
  44341. ** file as well as into the page cache. Which would be incorrect in
  44342. ** WAL mode.
  44343. */
  44344. pPager->eState = PAGER_WRITER_LOCKED;
  44345. pPager->dbHintSize = pPager->dbSize;
  44346. pPager->dbFileSize = pPager->dbSize;
  44347. pPager->dbOrigSize = pPager->dbSize;
  44348. pPager->journalOff = 0;
  44349. }
  44350. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  44351. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  44352. assert( assert_pager_state(pPager) );
  44353. }
  44354. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  44355. return rc;
  44356. }
  44357. /*
  44358. ** Mark a single data page as writeable. The page is written into the
  44359. ** main journal or sub-journal as required. If the page is written into
  44360. ** one of the journals, the corresponding bit is set in the
  44361. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  44362. ** of any open savepoints as appropriate.
  44363. */
  44364. static int pager_write(PgHdr *pPg){
  44365. void *pData = pPg->pData;
  44366. Pager *pPager = pPg->pPager;
  44367. int rc = SQLITE_OK;
  44368. /* This routine is not called unless a write-transaction has already
  44369. ** been started. The journal file may or may not be open at this point.
  44370. ** It is never called in the ERROR state.
  44371. */
  44372. assert( pPager->eState==PAGER_WRITER_LOCKED
  44373. || pPager->eState==PAGER_WRITER_CACHEMOD
  44374. || pPager->eState==PAGER_WRITER_DBMOD
  44375. );
  44376. assert( assert_pager_state(pPager) );
  44377. /* If an error has been previously detected, report the same error
  44378. ** again. This should not happen, but the check provides robustness. */
  44379. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44380. /* Higher-level routines never call this function if database is not
  44381. ** writable. But check anyway, just for robustness. */
  44382. if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
  44383. CHECK_PAGE(pPg);
  44384. /* The journal file needs to be opened. Higher level routines have already
  44385. ** obtained the necessary locks to begin the write-transaction, but the
  44386. ** rollback journal might not yet be open. Open it now if this is the case.
  44387. **
  44388. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  44389. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  44390. ** an error might occur and the pager would end up in WRITER_LOCKED state
  44391. ** with pages marked as dirty in the cache.
  44392. */
  44393. if( pPager->eState==PAGER_WRITER_LOCKED ){
  44394. rc = pager_open_journal(pPager);
  44395. if( rc!=SQLITE_OK ) return rc;
  44396. }
  44397. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  44398. assert( assert_pager_state(pPager) );
  44399. /* Mark the page as dirty. If the page has already been written
  44400. ** to the journal then we can return right away.
  44401. */
  44402. sqlite3PcacheMakeDirty(pPg);
  44403. if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
  44404. assert( !pagerUseWal(pPager) );
  44405. }else{
  44406. /* The transaction journal now exists and we have a RESERVED or an
  44407. ** EXCLUSIVE lock on the main database file. Write the current page to
  44408. ** the transaction journal if it is not there already.
  44409. */
  44410. if( !pageInJournal(pPg) && !pagerUseWal(pPager) ){
  44411. assert( pagerUseWal(pPager)==0 );
  44412. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  44413. u32 cksum;
  44414. char *pData2;
  44415. i64 iOff = pPager->journalOff;
  44416. /* We should never write to the journal file the page that
  44417. ** contains the database locks. The following assert verifies
  44418. ** that we do not. */
  44419. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  44420. assert( pPager->journalHdr<=pPager->journalOff );
  44421. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  44422. cksum = pager_cksum(pPager, (u8*)pData2);
  44423. /* Even if an IO or diskfull error occurs while journalling the
  44424. ** page in the block above, set the need-sync flag for the page.
  44425. ** Otherwise, when the transaction is rolled back, the logic in
  44426. ** playback_one_page() will think that the page needs to be restored
  44427. ** in the database file. And if an IO error occurs while doing so,
  44428. ** then corruption may follow.
  44429. */
  44430. pPg->flags |= PGHDR_NEED_SYNC;
  44431. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  44432. if( rc!=SQLITE_OK ) return rc;
  44433. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  44434. if( rc!=SQLITE_OK ) return rc;
  44435. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  44436. if( rc!=SQLITE_OK ) return rc;
  44437. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  44438. pPager->journalOff, pPager->pageSize));
  44439. PAGER_INCR(sqlite3_pager_writej_count);
  44440. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  44441. PAGERID(pPager), pPg->pgno,
  44442. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  44443. pPager->journalOff += 8 + pPager->pageSize;
  44444. pPager->nRec++;
  44445. assert( pPager->pInJournal!=0 );
  44446. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  44447. testcase( rc==SQLITE_NOMEM );
  44448. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  44449. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  44450. if( rc!=SQLITE_OK ){
  44451. assert( rc==SQLITE_NOMEM );
  44452. return rc;
  44453. }
  44454. }else{
  44455. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  44456. pPg->flags |= PGHDR_NEED_SYNC;
  44457. }
  44458. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  44459. PAGERID(pPager), pPg->pgno,
  44460. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  44461. }
  44462. }
  44463. /* If the statement journal is open and the page is not in it,
  44464. ** then write the current page to the statement journal. Note that
  44465. ** the statement journal format differs from the standard journal format
  44466. ** in that it omits the checksums and the header.
  44467. */
  44468. if( subjRequiresPage(pPg) ){
  44469. rc = subjournalPage(pPg);
  44470. }
  44471. }
  44472. /* Update the database size and return.
  44473. */
  44474. if( pPager->dbSize<pPg->pgno ){
  44475. pPager->dbSize = pPg->pgno;
  44476. }
  44477. return rc;
  44478. }
  44479. /*
  44480. ** Mark a data page as writeable. This routine must be called before
  44481. ** making changes to a page. The caller must check the return value
  44482. ** of this function and be careful not to change any page data unless
  44483. ** this routine returns SQLITE_OK.
  44484. **
  44485. ** The difference between this function and pager_write() is that this
  44486. ** function also deals with the special case where 2 or more pages
  44487. ** fit on a single disk sector. In this case all co-resident pages
  44488. ** must have been written to the journal file before returning.
  44489. **
  44490. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  44491. ** as appropriate. Otherwise, SQLITE_OK.
  44492. */
  44493. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
  44494. int rc = SQLITE_OK;
  44495. PgHdr *pPg = pDbPage;
  44496. Pager *pPager = pPg->pPager;
  44497. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  44498. assert( (pPg->flags & PGHDR_MMAP)==0 );
  44499. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44500. assert( pPager->eState!=PAGER_ERROR );
  44501. assert( assert_pager_state(pPager) );
  44502. if( nPagePerSector>1 ){
  44503. Pgno nPageCount; /* Total number of pages in database file */
  44504. Pgno pg1; /* First page of the sector pPg is located on. */
  44505. int nPage = 0; /* Number of pages starting at pg1 to journal */
  44506. int ii; /* Loop counter */
  44507. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  44508. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  44509. ** a journal header to be written between the pages journaled by
  44510. ** this function.
  44511. */
  44512. assert( !MEMDB );
  44513. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  44514. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  44515. /* This trick assumes that both the page-size and sector-size are
  44516. ** an integer power of 2. It sets variable pg1 to the identifier
  44517. ** of the first page of the sector pPg is located on.
  44518. */
  44519. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  44520. nPageCount = pPager->dbSize;
  44521. if( pPg->pgno>nPageCount ){
  44522. nPage = (pPg->pgno - pg1)+1;
  44523. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  44524. nPage = nPageCount+1-pg1;
  44525. }else{
  44526. nPage = nPagePerSector;
  44527. }
  44528. assert(nPage>0);
  44529. assert(pg1<=pPg->pgno);
  44530. assert((pg1+nPage)>pPg->pgno);
  44531. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  44532. Pgno pg = pg1+ii;
  44533. PgHdr *pPage;
  44534. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  44535. if( pg!=PAGER_MJ_PGNO(pPager) ){
  44536. rc = sqlite3PagerGet(pPager, pg, &pPage);
  44537. if( rc==SQLITE_OK ){
  44538. rc = pager_write(pPage);
  44539. if( pPage->flags&PGHDR_NEED_SYNC ){
  44540. needSync = 1;
  44541. }
  44542. sqlite3PagerUnref(pPage);
  44543. }
  44544. }
  44545. }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
  44546. if( pPage->flags&PGHDR_NEED_SYNC ){
  44547. needSync = 1;
  44548. }
  44549. sqlite3PagerUnref(pPage);
  44550. }
  44551. }
  44552. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  44553. ** starting at pg1, then it needs to be set for all of them. Because
  44554. ** writing to any of these nPage pages may damage the others, the
  44555. ** journal file must contain sync()ed copies of all of them
  44556. ** before any of them can be written out to the database file.
  44557. */
  44558. if( rc==SQLITE_OK && needSync ){
  44559. assert( !MEMDB );
  44560. for(ii=0; ii<nPage; ii++){
  44561. PgHdr *pPage = pager_lookup(pPager, pg1+ii);
  44562. if( pPage ){
  44563. pPage->flags |= PGHDR_NEED_SYNC;
  44564. sqlite3PagerUnref(pPage);
  44565. }
  44566. }
  44567. }
  44568. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  44569. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  44570. }else{
  44571. rc = pager_write(pDbPage);
  44572. }
  44573. return rc;
  44574. }
  44575. /*
  44576. ** Return TRUE if the page given in the argument was previously passed
  44577. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  44578. ** to change the content of the page.
  44579. */
  44580. #ifndef NDEBUG
  44581. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  44582. return pPg->flags&PGHDR_DIRTY;
  44583. }
  44584. #endif
  44585. /*
  44586. ** A call to this routine tells the pager that it is not necessary to
  44587. ** write the information on page pPg back to the disk, even though
  44588. ** that page might be marked as dirty. This happens, for example, when
  44589. ** the page has been added as a leaf of the freelist and so its
  44590. ** content no longer matters.
  44591. **
  44592. ** The overlying software layer calls this routine when all of the data
  44593. ** on the given page is unused. The pager marks the page as clean so
  44594. ** that it does not get written to disk.
  44595. **
  44596. ** Tests show that this optimization can quadruple the speed of large
  44597. ** DELETE operations.
  44598. */
  44599. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  44600. Pager *pPager = pPg->pPager;
  44601. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  44602. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  44603. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  44604. pPg->flags |= PGHDR_DONT_WRITE;
  44605. pager_set_pagehash(pPg);
  44606. }
  44607. }
  44608. /*
  44609. ** This routine is called to increment the value of the database file
  44610. ** change-counter, stored as a 4-byte big-endian integer starting at
  44611. ** byte offset 24 of the pager file. The secondary change counter at
  44612. ** 92 is also updated, as is the SQLite version number at offset 96.
  44613. **
  44614. ** But this only happens if the pPager->changeCountDone flag is false.
  44615. ** To avoid excess churning of page 1, the update only happens once.
  44616. ** See also the pager_write_changecounter() routine that does an
  44617. ** unconditional update of the change counters.
  44618. **
  44619. ** If the isDirectMode flag is zero, then this is done by calling
  44620. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  44621. ** page data. In this case the file will be updated when the current
  44622. ** transaction is committed.
  44623. **
  44624. ** The isDirectMode flag may only be non-zero if the library was compiled
  44625. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  44626. ** if isDirect is non-zero, then the database file is updated directly
  44627. ** by writing an updated version of page 1 using a call to the
  44628. ** sqlite3OsWrite() function.
  44629. */
  44630. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  44631. int rc = SQLITE_OK;
  44632. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44633. || pPager->eState==PAGER_WRITER_DBMOD
  44634. );
  44635. assert( assert_pager_state(pPager) );
  44636. /* Declare and initialize constant integer 'isDirect'. If the
  44637. ** atomic-write optimization is enabled in this build, then isDirect
  44638. ** is initialized to the value passed as the isDirectMode parameter
  44639. ** to this function. Otherwise, it is always set to zero.
  44640. **
  44641. ** The idea is that if the atomic-write optimization is not
  44642. ** enabled at compile time, the compiler can omit the tests of
  44643. ** 'isDirect' below, as well as the block enclosed in the
  44644. ** "if( isDirect )" condition.
  44645. */
  44646. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  44647. # define DIRECT_MODE 0
  44648. assert( isDirectMode==0 );
  44649. UNUSED_PARAMETER(isDirectMode);
  44650. #else
  44651. # define DIRECT_MODE isDirectMode
  44652. #endif
  44653. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  44654. PgHdr *pPgHdr; /* Reference to page 1 */
  44655. assert( !pPager->tempFile && isOpen(pPager->fd) );
  44656. /* Open page 1 of the file for writing. */
  44657. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  44658. assert( pPgHdr==0 || rc==SQLITE_OK );
  44659. /* If page one was fetched successfully, and this function is not
  44660. ** operating in direct-mode, make page 1 writable. When not in
  44661. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  44662. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  44663. */
  44664. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  44665. rc = sqlite3PagerWrite(pPgHdr);
  44666. }
  44667. if( rc==SQLITE_OK ){
  44668. /* Actually do the update of the change counter */
  44669. pager_write_changecounter(pPgHdr);
  44670. /* If running in direct mode, write the contents of page 1 to the file. */
  44671. if( DIRECT_MODE ){
  44672. const void *zBuf;
  44673. assert( pPager->dbFileSize>0 );
  44674. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  44675. if( rc==SQLITE_OK ){
  44676. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  44677. pPager->aStat[PAGER_STAT_WRITE]++;
  44678. }
  44679. if( rc==SQLITE_OK ){
  44680. /* Update the pager's copy of the change-counter. Otherwise, the
  44681. ** next time a read transaction is opened the cache will be
  44682. ** flushed (as the change-counter values will not match). */
  44683. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  44684. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  44685. pPager->changeCountDone = 1;
  44686. }
  44687. }else{
  44688. pPager->changeCountDone = 1;
  44689. }
  44690. }
  44691. /* Release the page reference. */
  44692. sqlite3PagerUnref(pPgHdr);
  44693. }
  44694. return rc;
  44695. }
  44696. /*
  44697. ** Sync the database file to disk. This is a no-op for in-memory databases
  44698. ** or pages with the Pager.noSync flag set.
  44699. **
  44700. ** If successful, or if called on a pager for which it is a no-op, this
  44701. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  44702. */
  44703. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
  44704. int rc = SQLITE_OK;
  44705. if( !pPager->noSync ){
  44706. assert( !MEMDB );
  44707. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  44708. }else if( isOpen(pPager->fd) ){
  44709. assert( !MEMDB );
  44710. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC_OMITTED, 0);
  44711. if( rc==SQLITE_NOTFOUND ){
  44712. rc = SQLITE_OK;
  44713. }
  44714. }
  44715. return rc;
  44716. }
  44717. /*
  44718. ** This function may only be called while a write-transaction is active in
  44719. ** rollback. If the connection is in WAL mode, this call is a no-op.
  44720. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  44721. ** the database file, an attempt is made to obtain one.
  44722. **
  44723. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  44724. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  44725. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  44726. ** returned.
  44727. */
  44728. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  44729. int rc = SQLITE_OK;
  44730. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44731. || pPager->eState==PAGER_WRITER_DBMOD
  44732. || pPager->eState==PAGER_WRITER_LOCKED
  44733. );
  44734. assert( assert_pager_state(pPager) );
  44735. if( 0==pagerUseWal(pPager) ){
  44736. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  44737. }
  44738. return rc;
  44739. }
  44740. /*
  44741. ** Sync the database file for the pager pPager. zMaster points to the name
  44742. ** of a master journal file that should be written into the individual
  44743. ** journal file. zMaster may be NULL, which is interpreted as no master
  44744. ** journal (a single database transaction).
  44745. **
  44746. ** This routine ensures that:
  44747. **
  44748. ** * The database file change-counter is updated,
  44749. ** * the journal is synced (unless the atomic-write optimization is used),
  44750. ** * all dirty pages are written to the database file,
  44751. ** * the database file is truncated (if required), and
  44752. ** * the database file synced.
  44753. **
  44754. ** The only thing that remains to commit the transaction is to finalize
  44755. ** (delete, truncate or zero the first part of) the journal file (or
  44756. ** delete the master journal file if specified).
  44757. **
  44758. ** Note that if zMaster==NULL, this does not overwrite a previous value
  44759. ** passed to an sqlite3PagerCommitPhaseOne() call.
  44760. **
  44761. ** If the final parameter - noSync - is true, then the database file itself
  44762. ** is not synced. The caller must call sqlite3PagerSync() directly to
  44763. ** sync the database file before calling CommitPhaseTwo() to delete the
  44764. ** journal file in this case.
  44765. */
  44766. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  44767. Pager *pPager, /* Pager object */
  44768. const char *zMaster, /* If not NULL, the master journal name */
  44769. int noSync /* True to omit the xSync on the db file */
  44770. ){
  44771. int rc = SQLITE_OK; /* Return code */
  44772. assert( pPager->eState==PAGER_WRITER_LOCKED
  44773. || pPager->eState==PAGER_WRITER_CACHEMOD
  44774. || pPager->eState==PAGER_WRITER_DBMOD
  44775. || pPager->eState==PAGER_ERROR
  44776. );
  44777. assert( assert_pager_state(pPager) );
  44778. /* If a prior error occurred, report that error again. */
  44779. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44780. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  44781. pPager->zFilename, zMaster, pPager->dbSize));
  44782. /* If no database changes have been made, return early. */
  44783. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  44784. if( MEMDB ){
  44785. /* If this is an in-memory db, or no pages have been written to, or this
  44786. ** function has already been called, it is mostly a no-op. However, any
  44787. ** backup in progress needs to be restarted.
  44788. */
  44789. sqlite3BackupRestart(pPager->pBackup);
  44790. }else{
  44791. if( pagerUseWal(pPager) ){
  44792. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  44793. PgHdr *pPageOne = 0;
  44794. if( pList==0 ){
  44795. /* Must have at least one page for the WAL commit flag.
  44796. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  44797. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  44798. pList = pPageOne;
  44799. pList->pDirty = 0;
  44800. }
  44801. assert( rc==SQLITE_OK );
  44802. if( ALWAYS(pList) ){
  44803. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  44804. }
  44805. sqlite3PagerUnref(pPageOne);
  44806. if( rc==SQLITE_OK ){
  44807. sqlite3PcacheCleanAll(pPager->pPCache);
  44808. }
  44809. }else{
  44810. /* The following block updates the change-counter. Exactly how it
  44811. ** does this depends on whether or not the atomic-update optimization
  44812. ** was enabled at compile time, and if this transaction meets the
  44813. ** runtime criteria to use the operation:
  44814. **
  44815. ** * The file-system supports the atomic-write property for
  44816. ** blocks of size page-size, and
  44817. ** * This commit is not part of a multi-file transaction, and
  44818. ** * Exactly one page has been modified and store in the journal file.
  44819. **
  44820. ** If the optimization was not enabled at compile time, then the
  44821. ** pager_incr_changecounter() function is called to update the change
  44822. ** counter in 'indirect-mode'. If the optimization is compiled in but
  44823. ** is not applicable to this transaction, call sqlite3JournalCreate()
  44824. ** to make sure the journal file has actually been created, then call
  44825. ** pager_incr_changecounter() to update the change-counter in indirect
  44826. ** mode.
  44827. **
  44828. ** Otherwise, if the optimization is both enabled and applicable,
  44829. ** then call pager_incr_changecounter() to update the change-counter
  44830. ** in 'direct' mode. In this case the journal file will never be
  44831. ** created for this transaction.
  44832. */
  44833. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  44834. PgHdr *pPg;
  44835. assert( isOpen(pPager->jfd)
  44836. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  44837. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  44838. );
  44839. if( !zMaster && isOpen(pPager->jfd)
  44840. && pPager->journalOff==jrnlBufferSize(pPager)
  44841. && pPager->dbSize>=pPager->dbOrigSize
  44842. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  44843. ){
  44844. /* Update the db file change counter via the direct-write method. The
  44845. ** following call will modify the in-memory representation of page 1
  44846. ** to include the updated change counter and then write page 1
  44847. ** directly to the database file. Because of the atomic-write
  44848. ** property of the host file-system, this is safe.
  44849. */
  44850. rc = pager_incr_changecounter(pPager, 1);
  44851. }else{
  44852. rc = sqlite3JournalCreate(pPager->jfd);
  44853. if( rc==SQLITE_OK ){
  44854. rc = pager_incr_changecounter(pPager, 0);
  44855. }
  44856. }
  44857. #else
  44858. rc = pager_incr_changecounter(pPager, 0);
  44859. #endif
  44860. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44861. /* Write the master journal name into the journal file. If a master
  44862. ** journal file name has already been written to the journal file,
  44863. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  44864. */
  44865. rc = writeMasterJournal(pPager, zMaster);
  44866. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44867. /* Sync the journal file and write all dirty pages to the database.
  44868. ** If the atomic-update optimization is being used, this sync will not
  44869. ** create the journal file or perform any real IO.
  44870. **
  44871. ** Because the change-counter page was just modified, unless the
  44872. ** atomic-update optimization is used it is almost certain that the
  44873. ** journal requires a sync here. However, in locking_mode=exclusive
  44874. ** on a system under memory pressure it is just possible that this is
  44875. ** not the case. In this case it is likely enough that the redundant
  44876. ** xSync() call will be changed to a no-op by the OS anyhow.
  44877. */
  44878. rc = syncJournal(pPager, 0);
  44879. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44880. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  44881. if( rc!=SQLITE_OK ){
  44882. assert( rc!=SQLITE_IOERR_BLOCKED );
  44883. goto commit_phase_one_exit;
  44884. }
  44885. sqlite3PcacheCleanAll(pPager->pPCache);
  44886. /* If the file on disk is smaller than the database image, use
  44887. ** pager_truncate to grow the file here. This can happen if the database
  44888. ** image was extended as part of the current transaction and then the
  44889. ** last page in the db image moved to the free-list. In this case the
  44890. ** last page is never written out to disk, leaving the database file
  44891. ** undersized. Fix this now if it is the case. */
  44892. if( pPager->dbSize>pPager->dbFileSize ){
  44893. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  44894. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44895. rc = pager_truncate(pPager, nNew);
  44896. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44897. }
  44898. /* Finally, sync the database file. */
  44899. if( !noSync ){
  44900. rc = sqlite3PagerSync(pPager);
  44901. }
  44902. IOTRACE(("DBSYNC %p\n", pPager))
  44903. }
  44904. }
  44905. commit_phase_one_exit:
  44906. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  44907. pPager->eState = PAGER_WRITER_FINISHED;
  44908. }
  44909. return rc;
  44910. }
  44911. /*
  44912. ** When this function is called, the database file has been completely
  44913. ** updated to reflect the changes made by the current transaction and
  44914. ** synced to disk. The journal file still exists in the file-system
  44915. ** though, and if a failure occurs at this point it will eventually
  44916. ** be used as a hot-journal and the current transaction rolled back.
  44917. **
  44918. ** This function finalizes the journal file, either by deleting,
  44919. ** truncating or partially zeroing it, so that it cannot be used
  44920. ** for hot-journal rollback. Once this is done the transaction is
  44921. ** irrevocably committed.
  44922. **
  44923. ** If an error occurs, an IO error code is returned and the pager
  44924. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  44925. */
  44926. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  44927. int rc = SQLITE_OK; /* Return code */
  44928. /* This routine should not be called if a prior error has occurred.
  44929. ** But if (due to a coding error elsewhere in the system) it does get
  44930. ** called, just return the same error code without doing anything. */
  44931. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44932. assert( pPager->eState==PAGER_WRITER_LOCKED
  44933. || pPager->eState==PAGER_WRITER_FINISHED
  44934. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  44935. );
  44936. assert( assert_pager_state(pPager) );
  44937. /* An optimization. If the database was not actually modified during
  44938. ** this transaction, the pager is running in exclusive-mode and is
  44939. ** using persistent journals, then this function is a no-op.
  44940. **
  44941. ** The start of the journal file currently contains a single journal
  44942. ** header with the nRec field set to 0. If such a journal is used as
  44943. ** a hot-journal during hot-journal rollback, 0 changes will be made
  44944. ** to the database file. So there is no need to zero the journal
  44945. ** header. Since the pager is in exclusive mode, there is no need
  44946. ** to drop any locks either.
  44947. */
  44948. if( pPager->eState==PAGER_WRITER_LOCKED
  44949. && pPager->exclusiveMode
  44950. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  44951. ){
  44952. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  44953. pPager->eState = PAGER_READER;
  44954. return SQLITE_OK;
  44955. }
  44956. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  44957. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  44958. return pager_error(pPager, rc);
  44959. }
  44960. /*
  44961. ** If a write transaction is open, then all changes made within the
  44962. ** transaction are reverted and the current write-transaction is closed.
  44963. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  44964. ** state if an error occurs.
  44965. **
  44966. ** If the pager is already in PAGER_ERROR state when this function is called,
  44967. ** it returns Pager.errCode immediately. No work is performed in this case.
  44968. **
  44969. ** Otherwise, in rollback mode, this function performs two functions:
  44970. **
  44971. ** 1) It rolls back the journal file, restoring all database file and
  44972. ** in-memory cache pages to the state they were in when the transaction
  44973. ** was opened, and
  44974. **
  44975. ** 2) It finalizes the journal file, so that it is not used for hot
  44976. ** rollback at any point in the future.
  44977. **
  44978. ** Finalization of the journal file (task 2) is only performed if the
  44979. ** rollback is successful.
  44980. **
  44981. ** In WAL mode, all cache-entries containing data modified within the
  44982. ** current transaction are either expelled from the cache or reverted to
  44983. ** their pre-transaction state by re-reading data from the database or
  44984. ** WAL files. The WAL transaction is then closed.
  44985. */
  44986. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  44987. int rc = SQLITE_OK; /* Return code */
  44988. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  44989. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  44990. ** the pager is already in the ERROR state, the rollback is not
  44991. ** attempted here. Instead, the error code is returned to the caller.
  44992. */
  44993. assert( assert_pager_state(pPager) );
  44994. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  44995. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  44996. if( pagerUseWal(pPager) ){
  44997. int rc2;
  44998. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  44999. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  45000. if( rc==SQLITE_OK ) rc = rc2;
  45001. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  45002. int eState = pPager->eState;
  45003. rc = pager_end_transaction(pPager, 0, 0);
  45004. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  45005. /* This can happen using journal_mode=off. Move the pager to the error
  45006. ** state to indicate that the contents of the cache may not be trusted.
  45007. ** Any active readers will get SQLITE_ABORT.
  45008. */
  45009. pPager->errCode = SQLITE_ABORT;
  45010. pPager->eState = PAGER_ERROR;
  45011. return rc;
  45012. }
  45013. }else{
  45014. rc = pager_playback(pPager, 0);
  45015. }
  45016. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  45017. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  45018. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR );
  45019. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  45020. ** cache. So call pager_error() on the way out to make any error persistent.
  45021. */
  45022. return pager_error(pPager, rc);
  45023. }
  45024. /*
  45025. ** Return TRUE if the database file is opened read-only. Return FALSE
  45026. ** if the database is (in theory) writable.
  45027. */
  45028. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  45029. return pPager->readOnly;
  45030. }
  45031. /*
  45032. ** Return the number of references to the pager.
  45033. */
  45034. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  45035. return sqlite3PcacheRefCount(pPager->pPCache);
  45036. }
  45037. /*
  45038. ** Return the approximate number of bytes of memory currently
  45039. ** used by the pager and its associated cache.
  45040. */
  45041. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  45042. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  45043. + 5*sizeof(void*);
  45044. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  45045. + sqlite3MallocSize(pPager)
  45046. + pPager->pageSize;
  45047. }
  45048. /*
  45049. ** Return the number of references to the specified page.
  45050. */
  45051. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  45052. return sqlite3PcachePageRefcount(pPage);
  45053. }
  45054. #ifdef SQLITE_TEST
  45055. /*
  45056. ** This routine is used for testing and analysis only.
  45057. */
  45058. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  45059. static int a[11];
  45060. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  45061. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  45062. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  45063. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  45064. a[4] = pPager->eState;
  45065. a[5] = pPager->errCode;
  45066. a[6] = pPager->aStat[PAGER_STAT_HIT];
  45067. a[7] = pPager->aStat[PAGER_STAT_MISS];
  45068. a[8] = 0; /* Used to be pPager->nOvfl */
  45069. a[9] = pPager->nRead;
  45070. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  45071. return a;
  45072. }
  45073. #endif
  45074. /*
  45075. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  45076. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  45077. ** current cache hit or miss count, according to the value of eStat. If the
  45078. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  45079. ** returning.
  45080. */
  45081. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  45082. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  45083. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  45084. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  45085. );
  45086. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  45087. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  45088. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  45089. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  45090. if( reset ){
  45091. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  45092. }
  45093. }
  45094. /*
  45095. ** Return true if this is an in-memory pager.
  45096. */
  45097. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  45098. return MEMDB;
  45099. }
  45100. /*
  45101. ** Check that there are at least nSavepoint savepoints open. If there are
  45102. ** currently less than nSavepoints open, then open one or more savepoints
  45103. ** to make up the difference. If the number of savepoints is already
  45104. ** equal to nSavepoint, then this function is a no-op.
  45105. **
  45106. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  45107. ** occurs while opening the sub-journal file, then an IO error code is
  45108. ** returned. Otherwise, SQLITE_OK.
  45109. */
  45110. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  45111. int rc = SQLITE_OK; /* Return code */
  45112. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  45113. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  45114. assert( assert_pager_state(pPager) );
  45115. if( nSavepoint>nCurrent && pPager->useJournal ){
  45116. int ii; /* Iterator variable */
  45117. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  45118. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  45119. ** if the allocation fails. Otherwise, zero the new portion in case a
  45120. ** malloc failure occurs while populating it in the for(...) loop below.
  45121. */
  45122. aNew = (PagerSavepoint *)sqlite3Realloc(
  45123. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  45124. );
  45125. if( !aNew ){
  45126. return SQLITE_NOMEM;
  45127. }
  45128. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  45129. pPager->aSavepoint = aNew;
  45130. /* Populate the PagerSavepoint structures just allocated. */
  45131. for(ii=nCurrent; ii<nSavepoint; ii++){
  45132. aNew[ii].nOrig = pPager->dbSize;
  45133. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  45134. aNew[ii].iOffset = pPager->journalOff;
  45135. }else{
  45136. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  45137. }
  45138. aNew[ii].iSubRec = pPager->nSubRec;
  45139. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  45140. if( !aNew[ii].pInSavepoint ){
  45141. return SQLITE_NOMEM;
  45142. }
  45143. if( pagerUseWal(pPager) ){
  45144. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  45145. }
  45146. pPager->nSavepoint = ii+1;
  45147. }
  45148. assert( pPager->nSavepoint==nSavepoint );
  45149. assertTruncateConstraint(pPager);
  45150. }
  45151. return rc;
  45152. }
  45153. /*
  45154. ** This function is called to rollback or release (commit) a savepoint.
  45155. ** The savepoint to release or rollback need not be the most recently
  45156. ** created savepoint.
  45157. **
  45158. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  45159. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  45160. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  45161. ** that have occurred since the specified savepoint was created.
  45162. **
  45163. ** The savepoint to rollback or release is identified by parameter
  45164. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  45165. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  45166. ** on the most recently created savepoint. If iSavepoint is greater than
  45167. ** (Pager.nSavepoint-1), then this function is a no-op.
  45168. **
  45169. ** If a negative value is passed to this function, then the current
  45170. ** transaction is rolled back. This is different to calling
  45171. ** sqlite3PagerRollback() because this function does not terminate
  45172. ** the transaction or unlock the database, it just restores the
  45173. ** contents of the database to its original state.
  45174. **
  45175. ** In any case, all savepoints with an index greater than iSavepoint
  45176. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  45177. ** then savepoint iSavepoint is also destroyed.
  45178. **
  45179. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  45180. ** or an IO error code if an IO error occurs while rolling back a
  45181. ** savepoint. If no errors occur, SQLITE_OK is returned.
  45182. */
  45183. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  45184. int rc = pPager->errCode; /* Return code */
  45185. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  45186. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  45187. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  45188. int ii; /* Iterator variable */
  45189. int nNew; /* Number of remaining savepoints after this op. */
  45190. /* Figure out how many savepoints will still be active after this
  45191. ** operation. Store this value in nNew. Then free resources associated
  45192. ** with any savepoints that are destroyed by this operation.
  45193. */
  45194. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  45195. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  45196. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  45197. }
  45198. pPager->nSavepoint = nNew;
  45199. /* If this is a release of the outermost savepoint, truncate
  45200. ** the sub-journal to zero bytes in size. */
  45201. if( op==SAVEPOINT_RELEASE ){
  45202. if( nNew==0 && isOpen(pPager->sjfd) ){
  45203. /* Only truncate if it is an in-memory sub-journal. */
  45204. if( sqlite3IsMemJournal(pPager->sjfd) ){
  45205. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  45206. assert( rc==SQLITE_OK );
  45207. }
  45208. pPager->nSubRec = 0;
  45209. }
  45210. }
  45211. /* Else this is a rollback operation, playback the specified savepoint.
  45212. ** If this is a temp-file, it is possible that the journal file has
  45213. ** not yet been opened. In this case there have been no changes to
  45214. ** the database file, so the playback operation can be skipped.
  45215. */
  45216. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  45217. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  45218. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  45219. assert(rc!=SQLITE_DONE);
  45220. }
  45221. }
  45222. return rc;
  45223. }
  45224. /*
  45225. ** Return the full pathname of the database file.
  45226. **
  45227. ** Except, if the pager is in-memory only, then return an empty string if
  45228. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  45229. ** used to report the filename to the user, for compatibility with legacy
  45230. ** behavior. But when the Btree needs to know the filename for matching to
  45231. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  45232. ** participate in shared-cache.
  45233. */
  45234. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  45235. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  45236. }
  45237. /*
  45238. ** Return the VFS structure for the pager.
  45239. */
  45240. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  45241. return pPager->pVfs;
  45242. }
  45243. /*
  45244. ** Return the file handle for the database file associated
  45245. ** with the pager. This might return NULL if the file has
  45246. ** not yet been opened.
  45247. */
  45248. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  45249. return pPager->fd;
  45250. }
  45251. /*
  45252. ** Return the full pathname of the journal file.
  45253. */
  45254. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  45255. return pPager->zJournal;
  45256. }
  45257. /*
  45258. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  45259. ** if fsync()s are executed normally.
  45260. */
  45261. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  45262. return pPager->noSync;
  45263. }
  45264. #ifdef SQLITE_HAS_CODEC
  45265. /*
  45266. ** Set or retrieve the codec for this pager
  45267. */
  45268. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  45269. Pager *pPager,
  45270. void *(*xCodec)(void*,void*,Pgno,int),
  45271. void (*xCodecSizeChng)(void*,int,int),
  45272. void (*xCodecFree)(void*),
  45273. void *pCodec
  45274. ){
  45275. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  45276. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  45277. pPager->xCodecSizeChng = xCodecSizeChng;
  45278. pPager->xCodecFree = xCodecFree;
  45279. pPager->pCodec = pCodec;
  45280. pagerReportSize(pPager);
  45281. }
  45282. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  45283. return pPager->pCodec;
  45284. }
  45285. /*
  45286. ** This function is called by the wal module when writing page content
  45287. ** into the log file.
  45288. **
  45289. ** This function returns a pointer to a buffer containing the encrypted
  45290. ** page content. If a malloc fails, this function may return NULL.
  45291. */
  45292. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  45293. void *aData = 0;
  45294. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  45295. return aData;
  45296. }
  45297. /*
  45298. ** Return the current pager state
  45299. */
  45300. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  45301. return pPager->eState;
  45302. }
  45303. #endif /* SQLITE_HAS_CODEC */
  45304. #ifndef SQLITE_OMIT_AUTOVACUUM
  45305. /*
  45306. ** Move the page pPg to location pgno in the file.
  45307. **
  45308. ** There must be no references to the page previously located at
  45309. ** pgno (which we call pPgOld) though that page is allowed to be
  45310. ** in cache. If the page previously located at pgno is not already
  45311. ** in the rollback journal, it is not put there by by this routine.
  45312. **
  45313. ** References to the page pPg remain valid. Updating any
  45314. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  45315. ** allocated along with the page) is the responsibility of the caller.
  45316. **
  45317. ** A transaction must be active when this routine is called. It used to be
  45318. ** required that a statement transaction was not active, but this restriction
  45319. ** has been removed (CREATE INDEX needs to move a page when a statement
  45320. ** transaction is active).
  45321. **
  45322. ** If the fourth argument, isCommit, is non-zero, then this page is being
  45323. ** moved as part of a database reorganization just before the transaction
  45324. ** is being committed. In this case, it is guaranteed that the database page
  45325. ** pPg refers to will not be written to again within this transaction.
  45326. **
  45327. ** This function may return SQLITE_NOMEM or an IO error code if an error
  45328. ** occurs. Otherwise, it returns SQLITE_OK.
  45329. */
  45330. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  45331. PgHdr *pPgOld; /* The page being overwritten. */
  45332. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  45333. int rc; /* Return code */
  45334. Pgno origPgno; /* The original page number */
  45335. assert( pPg->nRef>0 );
  45336. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  45337. || pPager->eState==PAGER_WRITER_DBMOD
  45338. );
  45339. assert( assert_pager_state(pPager) );
  45340. /* In order to be able to rollback, an in-memory database must journal
  45341. ** the page we are moving from.
  45342. */
  45343. if( MEMDB ){
  45344. rc = sqlite3PagerWrite(pPg);
  45345. if( rc ) return rc;
  45346. }
  45347. /* If the page being moved is dirty and has not been saved by the latest
  45348. ** savepoint, then save the current contents of the page into the
  45349. ** sub-journal now. This is required to handle the following scenario:
  45350. **
  45351. ** BEGIN;
  45352. ** <journal page X, then modify it in memory>
  45353. ** SAVEPOINT one;
  45354. ** <Move page X to location Y>
  45355. ** ROLLBACK TO one;
  45356. **
  45357. ** If page X were not written to the sub-journal here, it would not
  45358. ** be possible to restore its contents when the "ROLLBACK TO one"
  45359. ** statement were is processed.
  45360. **
  45361. ** subjournalPage() may need to allocate space to store pPg->pgno into
  45362. ** one or more savepoint bitvecs. This is the reason this function
  45363. ** may return SQLITE_NOMEM.
  45364. */
  45365. if( pPg->flags&PGHDR_DIRTY
  45366. && subjRequiresPage(pPg)
  45367. && SQLITE_OK!=(rc = subjournalPage(pPg))
  45368. ){
  45369. return rc;
  45370. }
  45371. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  45372. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  45373. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  45374. /* If the journal needs to be sync()ed before page pPg->pgno can
  45375. ** be written to, store pPg->pgno in local variable needSyncPgno.
  45376. **
  45377. ** If the isCommit flag is set, there is no need to remember that
  45378. ** the journal needs to be sync()ed before database page pPg->pgno
  45379. ** can be written to. The caller has already promised not to write to it.
  45380. */
  45381. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  45382. needSyncPgno = pPg->pgno;
  45383. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  45384. pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
  45385. assert( pPg->flags&PGHDR_DIRTY );
  45386. }
  45387. /* If the cache contains a page with page-number pgno, remove it
  45388. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  45389. ** page pgno before the 'move' operation, it needs to be retained
  45390. ** for the page moved there.
  45391. */
  45392. pPg->flags &= ~PGHDR_NEED_SYNC;
  45393. pPgOld = pager_lookup(pPager, pgno);
  45394. assert( !pPgOld || pPgOld->nRef==1 );
  45395. if( pPgOld ){
  45396. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  45397. if( MEMDB ){
  45398. /* Do not discard pages from an in-memory database since we might
  45399. ** need to rollback later. Just move the page out of the way. */
  45400. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  45401. }else{
  45402. sqlite3PcacheDrop(pPgOld);
  45403. }
  45404. }
  45405. origPgno = pPg->pgno;
  45406. sqlite3PcacheMove(pPg, pgno);
  45407. sqlite3PcacheMakeDirty(pPg);
  45408. /* For an in-memory database, make sure the original page continues
  45409. ** to exist, in case the transaction needs to roll back. Use pPgOld
  45410. ** as the original page since it has already been allocated.
  45411. */
  45412. if( MEMDB ){
  45413. assert( pPgOld );
  45414. sqlite3PcacheMove(pPgOld, origPgno);
  45415. sqlite3PagerUnref(pPgOld);
  45416. }
  45417. if( needSyncPgno ){
  45418. /* If needSyncPgno is non-zero, then the journal file needs to be
  45419. ** sync()ed before any data is written to database file page needSyncPgno.
  45420. ** Currently, no such page exists in the page-cache and the
  45421. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  45422. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  45423. ** flag.
  45424. **
  45425. ** If the attempt to load the page into the page-cache fails, (due
  45426. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  45427. ** array. Otherwise, if the page is loaded and written again in
  45428. ** this transaction, it may be written to the database file before
  45429. ** it is synced into the journal file. This way, it may end up in
  45430. ** the journal file twice, but that is not a problem.
  45431. */
  45432. PgHdr *pPgHdr;
  45433. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  45434. if( rc!=SQLITE_OK ){
  45435. if( needSyncPgno<=pPager->dbOrigSize ){
  45436. assert( pPager->pTmpSpace!=0 );
  45437. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  45438. }
  45439. return rc;
  45440. }
  45441. pPgHdr->flags |= PGHDR_NEED_SYNC;
  45442. sqlite3PcacheMakeDirty(pPgHdr);
  45443. sqlite3PagerUnref(pPgHdr);
  45444. }
  45445. return SQLITE_OK;
  45446. }
  45447. #endif
  45448. /*
  45449. ** Return a pointer to the data for the specified page.
  45450. */
  45451. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  45452. assert( pPg->nRef>0 || pPg->pPager->memDb );
  45453. return pPg->pData;
  45454. }
  45455. /*
  45456. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  45457. ** allocated along with the specified page.
  45458. */
  45459. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  45460. return pPg->pExtra;
  45461. }
  45462. /*
  45463. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  45464. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  45465. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  45466. ** the locking-mode is set to the value specified.
  45467. **
  45468. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  45469. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  45470. ** locking-mode.
  45471. */
  45472. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  45473. assert( eMode==PAGER_LOCKINGMODE_QUERY
  45474. || eMode==PAGER_LOCKINGMODE_NORMAL
  45475. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  45476. assert( PAGER_LOCKINGMODE_QUERY<0 );
  45477. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  45478. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  45479. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  45480. pPager->exclusiveMode = (u8)eMode;
  45481. }
  45482. return (int)pPager->exclusiveMode;
  45483. }
  45484. /*
  45485. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  45486. **
  45487. ** PAGER_JOURNALMODE_DELETE
  45488. ** PAGER_JOURNALMODE_TRUNCATE
  45489. ** PAGER_JOURNALMODE_PERSIST
  45490. ** PAGER_JOURNALMODE_OFF
  45491. ** PAGER_JOURNALMODE_MEMORY
  45492. ** PAGER_JOURNALMODE_WAL
  45493. **
  45494. ** The journalmode is set to the value specified if the change is allowed.
  45495. ** The change may be disallowed for the following reasons:
  45496. **
  45497. ** * An in-memory database can only have its journal_mode set to _OFF
  45498. ** or _MEMORY.
  45499. **
  45500. ** * Temporary databases cannot have _WAL journalmode.
  45501. **
  45502. ** The returned indicate the current (possibly updated) journal-mode.
  45503. */
  45504. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  45505. u8 eOld = pPager->journalMode; /* Prior journalmode */
  45506. #ifdef SQLITE_DEBUG
  45507. /* The print_pager_state() routine is intended to be used by the debugger
  45508. ** only. We invoke it once here to suppress a compiler warning. */
  45509. print_pager_state(pPager);
  45510. #endif
  45511. /* The eMode parameter is always valid */
  45512. assert( eMode==PAGER_JOURNALMODE_DELETE
  45513. || eMode==PAGER_JOURNALMODE_TRUNCATE
  45514. || eMode==PAGER_JOURNALMODE_PERSIST
  45515. || eMode==PAGER_JOURNALMODE_OFF
  45516. || eMode==PAGER_JOURNALMODE_WAL
  45517. || eMode==PAGER_JOURNALMODE_MEMORY );
  45518. /* This routine is only called from the OP_JournalMode opcode, and
  45519. ** the logic there will never allow a temporary file to be changed
  45520. ** to WAL mode.
  45521. */
  45522. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  45523. /* Do allow the journalmode of an in-memory database to be set to
  45524. ** anything other than MEMORY or OFF
  45525. */
  45526. if( MEMDB ){
  45527. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  45528. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  45529. eMode = eOld;
  45530. }
  45531. }
  45532. if( eMode!=eOld ){
  45533. /* Change the journal mode. */
  45534. assert( pPager->eState!=PAGER_ERROR );
  45535. pPager->journalMode = (u8)eMode;
  45536. /* When transistioning from TRUNCATE or PERSIST to any other journal
  45537. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  45538. ** delete the journal file.
  45539. */
  45540. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  45541. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  45542. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  45543. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  45544. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  45545. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  45546. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  45547. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  45548. /* In this case we would like to delete the journal file. If it is
  45549. ** not possible, then that is not a problem. Deleting the journal file
  45550. ** here is an optimization only.
  45551. **
  45552. ** Before deleting the journal file, obtain a RESERVED lock on the
  45553. ** database file. This ensures that the journal file is not deleted
  45554. ** while it is in use by some other client.
  45555. */
  45556. sqlite3OsClose(pPager->jfd);
  45557. if( pPager->eLock>=RESERVED_LOCK ){
  45558. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45559. }else{
  45560. int rc = SQLITE_OK;
  45561. int state = pPager->eState;
  45562. assert( state==PAGER_OPEN || state==PAGER_READER );
  45563. if( state==PAGER_OPEN ){
  45564. rc = sqlite3PagerSharedLock(pPager);
  45565. }
  45566. if( pPager->eState==PAGER_READER ){
  45567. assert( rc==SQLITE_OK );
  45568. rc = pagerLockDb(pPager, RESERVED_LOCK);
  45569. }
  45570. if( rc==SQLITE_OK ){
  45571. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  45572. }
  45573. if( rc==SQLITE_OK && state==PAGER_READER ){
  45574. pagerUnlockDb(pPager, SHARED_LOCK);
  45575. }else if( state==PAGER_OPEN ){
  45576. pager_unlock(pPager);
  45577. }
  45578. assert( state==pPager->eState );
  45579. }
  45580. }
  45581. }
  45582. /* Return the new journal mode */
  45583. return (int)pPager->journalMode;
  45584. }
  45585. /*
  45586. ** Return the current journal mode.
  45587. */
  45588. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  45589. return (int)pPager->journalMode;
  45590. }
  45591. /*
  45592. ** Return TRUE if the pager is in a state where it is OK to change the
  45593. ** journalmode. Journalmode changes can only happen when the database
  45594. ** is unmodified.
  45595. */
  45596. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  45597. assert( assert_pager_state(pPager) );
  45598. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  45599. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  45600. return 1;
  45601. }
  45602. /*
  45603. ** Get/set the size-limit used for persistent journal files.
  45604. **
  45605. ** Setting the size limit to -1 means no limit is enforced.
  45606. ** An attempt to set a limit smaller than -1 is a no-op.
  45607. */
  45608. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  45609. if( iLimit>=-1 ){
  45610. pPager->journalSizeLimit = iLimit;
  45611. sqlite3WalLimit(pPager->pWal, iLimit);
  45612. }
  45613. return pPager->journalSizeLimit;
  45614. }
  45615. /*
  45616. ** Return a pointer to the pPager->pBackup variable. The backup module
  45617. ** in backup.c maintains the content of this variable. This module
  45618. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  45619. ** sqlite3BackupUpdate() only.
  45620. */
  45621. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  45622. return &pPager->pBackup;
  45623. }
  45624. #ifndef SQLITE_OMIT_VACUUM
  45625. /*
  45626. ** Unless this is an in-memory or temporary database, clear the pager cache.
  45627. */
  45628. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  45629. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  45630. }
  45631. #endif
  45632. #ifndef SQLITE_OMIT_WAL
  45633. /*
  45634. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  45635. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  45636. ** or wal_blocking_checkpoint() API functions.
  45637. **
  45638. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  45639. */
  45640. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  45641. int rc = SQLITE_OK;
  45642. if( pPager->pWal ){
  45643. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  45644. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  45645. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  45646. pnLog, pnCkpt
  45647. );
  45648. }
  45649. return rc;
  45650. }
  45651. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  45652. return sqlite3WalCallback(pPager->pWal);
  45653. }
  45654. /*
  45655. ** Return true if the underlying VFS for the given pager supports the
  45656. ** primitives necessary for write-ahead logging.
  45657. */
  45658. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  45659. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  45660. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  45661. }
  45662. /*
  45663. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  45664. ** is obtained instead, immediately release it.
  45665. */
  45666. static int pagerExclusiveLock(Pager *pPager){
  45667. int rc; /* Return code */
  45668. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45669. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  45670. if( rc!=SQLITE_OK ){
  45671. /* If the attempt to grab the exclusive lock failed, release the
  45672. ** pending lock that may have been obtained instead. */
  45673. pagerUnlockDb(pPager, SHARED_LOCK);
  45674. }
  45675. return rc;
  45676. }
  45677. /*
  45678. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  45679. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  45680. ** lock on the database file and use heap-memory to store the wal-index
  45681. ** in. Otherwise, use the normal shared-memory.
  45682. */
  45683. static int pagerOpenWal(Pager *pPager){
  45684. int rc = SQLITE_OK;
  45685. assert( pPager->pWal==0 && pPager->tempFile==0 );
  45686. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  45687. /* If the pager is already in exclusive-mode, the WAL module will use
  45688. ** heap-memory for the wal-index instead of the VFS shared-memory
  45689. ** implementation. Take the exclusive lock now, before opening the WAL
  45690. ** file, to make sure this is safe.
  45691. */
  45692. if( pPager->exclusiveMode ){
  45693. rc = pagerExclusiveLock(pPager);
  45694. }
  45695. /* Open the connection to the log file. If this operation fails,
  45696. ** (e.g. due to malloc() failure), return an error code.
  45697. */
  45698. if( rc==SQLITE_OK ){
  45699. rc = sqlite3WalOpen(pPager->pVfs,
  45700. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  45701. pPager->journalSizeLimit, &pPager->pWal
  45702. );
  45703. }
  45704. pagerFixMaplimit(pPager);
  45705. return rc;
  45706. }
  45707. /*
  45708. ** The caller must be holding a SHARED lock on the database file to call
  45709. ** this function.
  45710. **
  45711. ** If the pager passed as the first argument is open on a real database
  45712. ** file (not a temp file or an in-memory database), and the WAL file
  45713. ** is not already open, make an attempt to open it now. If successful,
  45714. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  45715. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  45716. ** not modified in either case.
  45717. **
  45718. ** If the pager is open on a temp-file (or in-memory database), or if
  45719. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  45720. ** without doing anything.
  45721. */
  45722. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  45723. Pager *pPager, /* Pager object */
  45724. int *pbOpen /* OUT: Set to true if call is a no-op */
  45725. ){
  45726. int rc = SQLITE_OK; /* Return code */
  45727. assert( assert_pager_state(pPager) );
  45728. assert( pPager->eState==PAGER_OPEN || pbOpen );
  45729. assert( pPager->eState==PAGER_READER || !pbOpen );
  45730. assert( pbOpen==0 || *pbOpen==0 );
  45731. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  45732. if( !pPager->tempFile && !pPager->pWal ){
  45733. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  45734. /* Close any rollback journal previously open */
  45735. sqlite3OsClose(pPager->jfd);
  45736. rc = pagerOpenWal(pPager);
  45737. if( rc==SQLITE_OK ){
  45738. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  45739. pPager->eState = PAGER_OPEN;
  45740. }
  45741. }else{
  45742. *pbOpen = 1;
  45743. }
  45744. return rc;
  45745. }
  45746. /*
  45747. ** This function is called to close the connection to the log file prior
  45748. ** to switching from WAL to rollback mode.
  45749. **
  45750. ** Before closing the log file, this function attempts to take an
  45751. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  45752. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  45753. ** If successful, the EXCLUSIVE lock is not released before returning.
  45754. */
  45755. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  45756. int rc = SQLITE_OK;
  45757. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  45758. /* If the log file is not already open, but does exist in the file-system,
  45759. ** it may need to be checkpointed before the connection can switch to
  45760. ** rollback mode. Open it now so this can happen.
  45761. */
  45762. if( !pPager->pWal ){
  45763. int logexists = 0;
  45764. rc = pagerLockDb(pPager, SHARED_LOCK);
  45765. if( rc==SQLITE_OK ){
  45766. rc = sqlite3OsAccess(
  45767. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  45768. );
  45769. }
  45770. if( rc==SQLITE_OK && logexists ){
  45771. rc = pagerOpenWal(pPager);
  45772. }
  45773. }
  45774. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  45775. ** the database file, the log and log-summary files will be deleted.
  45776. */
  45777. if( rc==SQLITE_OK && pPager->pWal ){
  45778. rc = pagerExclusiveLock(pPager);
  45779. if( rc==SQLITE_OK ){
  45780. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  45781. pPager->pageSize, (u8*)pPager->pTmpSpace);
  45782. pPager->pWal = 0;
  45783. pagerFixMaplimit(pPager);
  45784. }
  45785. }
  45786. return rc;
  45787. }
  45788. #endif /* !SQLITE_OMIT_WAL */
  45789. #ifdef SQLITE_ENABLE_ZIPVFS
  45790. /*
  45791. ** A read-lock must be held on the pager when this function is called. If
  45792. ** the pager is in WAL mode and the WAL file currently contains one or more
  45793. ** frames, return the size in bytes of the page images stored within the
  45794. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  45795. ** is empty, return 0.
  45796. */
  45797. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  45798. assert( pPager->eState==PAGER_READER );
  45799. return sqlite3WalFramesize(pPager->pWal);
  45800. }
  45801. #endif
  45802. #endif /* SQLITE_OMIT_DISKIO */
  45803. /************** End of pager.c ***********************************************/
  45804. /************** Begin file wal.c *********************************************/
  45805. /*
  45806. ** 2010 February 1
  45807. **
  45808. ** The author disclaims copyright to this source code. In place of
  45809. ** a legal notice, here is a blessing:
  45810. **
  45811. ** May you do good and not evil.
  45812. ** May you find forgiveness for yourself and forgive others.
  45813. ** May you share freely, never taking more than you give.
  45814. **
  45815. *************************************************************************
  45816. **
  45817. ** This file contains the implementation of a write-ahead log (WAL) used in
  45818. ** "journal_mode=WAL" mode.
  45819. **
  45820. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  45821. **
  45822. ** A WAL file consists of a header followed by zero or more "frames".
  45823. ** Each frame records the revised content of a single page from the
  45824. ** database file. All changes to the database are recorded by writing
  45825. ** frames into the WAL. Transactions commit when a frame is written that
  45826. ** contains a commit marker. A single WAL can and usually does record
  45827. ** multiple transactions. Periodically, the content of the WAL is
  45828. ** transferred back into the database file in an operation called a
  45829. ** "checkpoint".
  45830. **
  45831. ** A single WAL file can be used multiple times. In other words, the
  45832. ** WAL can fill up with frames and then be checkpointed and then new
  45833. ** frames can overwrite the old ones. A WAL always grows from beginning
  45834. ** toward the end. Checksums and counters attached to each frame are
  45835. ** used to determine which frames within the WAL are valid and which
  45836. ** are leftovers from prior checkpoints.
  45837. **
  45838. ** The WAL header is 32 bytes in size and consists of the following eight
  45839. ** big-endian 32-bit unsigned integer values:
  45840. **
  45841. ** 0: Magic number. 0x377f0682 or 0x377f0683
  45842. ** 4: File format version. Currently 3007000
  45843. ** 8: Database page size. Example: 1024
  45844. ** 12: Checkpoint sequence number
  45845. ** 16: Salt-1, random integer incremented with each checkpoint
  45846. ** 20: Salt-2, a different random integer changing with each ckpt
  45847. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  45848. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  45849. **
  45850. ** Immediately following the wal-header are zero or more frames. Each
  45851. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  45852. ** of page data. The frame-header is six big-endian 32-bit unsigned
  45853. ** integer values, as follows:
  45854. **
  45855. ** 0: Page number.
  45856. ** 4: For commit records, the size of the database image in pages
  45857. ** after the commit. For all other records, zero.
  45858. ** 8: Salt-1 (copied from the header)
  45859. ** 12: Salt-2 (copied from the header)
  45860. ** 16: Checksum-1.
  45861. ** 20: Checksum-2.
  45862. **
  45863. ** A frame is considered valid if and only if the following conditions are
  45864. ** true:
  45865. **
  45866. ** (1) The salt-1 and salt-2 values in the frame-header match
  45867. ** salt values in the wal-header
  45868. **
  45869. ** (2) The checksum values in the final 8 bytes of the frame-header
  45870. ** exactly match the checksum computed consecutively on the
  45871. ** WAL header and the first 8 bytes and the content of all frames
  45872. ** up to and including the current frame.
  45873. **
  45874. ** The checksum is computed using 32-bit big-endian integers if the
  45875. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  45876. ** is computed using little-endian if the magic number is 0x377f0682.
  45877. ** The checksum values are always stored in the frame header in a
  45878. ** big-endian format regardless of which byte order is used to compute
  45879. ** the checksum. The checksum is computed by interpreting the input as
  45880. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  45881. ** algorithm used for the checksum is as follows:
  45882. **
  45883. ** for i from 0 to n-1 step 2:
  45884. ** s0 += x[i] + s1;
  45885. ** s1 += x[i+1] + s0;
  45886. ** endfor
  45887. **
  45888. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  45889. ** in reverse order (the largest fibonacci weight occurs on the first element
  45890. ** of the sequence being summed.) The s1 value spans all 32-bit
  45891. ** terms of the sequence whereas s0 omits the final term.
  45892. **
  45893. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  45894. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  45895. ** The VFS.xSync operations serve as write barriers - all writes launched
  45896. ** before the xSync must complete before any write that launches after the
  45897. ** xSync begins.
  45898. **
  45899. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  45900. ** value is randomized. This prevents old and new frames in the WAL from
  45901. ** being considered valid at the same time and being checkpointing together
  45902. ** following a crash.
  45903. **
  45904. ** READER ALGORITHM
  45905. **
  45906. ** To read a page from the database (call it page number P), a reader
  45907. ** first checks the WAL to see if it contains page P. If so, then the
  45908. ** last valid instance of page P that is a followed by a commit frame
  45909. ** or is a commit frame itself becomes the value read. If the WAL
  45910. ** contains no copies of page P that are valid and which are a commit
  45911. ** frame or are followed by a commit frame, then page P is read from
  45912. ** the database file.
  45913. **
  45914. ** To start a read transaction, the reader records the index of the last
  45915. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  45916. ** for all subsequent read operations. New transactions can be appended
  45917. ** to the WAL, but as long as the reader uses its original mxFrame value
  45918. ** and ignores the newly appended content, it will see a consistent snapshot
  45919. ** of the database from a single point in time. This technique allows
  45920. ** multiple concurrent readers to view different versions of the database
  45921. ** content simultaneously.
  45922. **
  45923. ** The reader algorithm in the previous paragraphs works correctly, but
  45924. ** because frames for page P can appear anywhere within the WAL, the
  45925. ** reader has to scan the entire WAL looking for page P frames. If the
  45926. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  45927. ** and read performance suffers. To overcome this problem, a separate
  45928. ** data structure called the wal-index is maintained to expedite the
  45929. ** search for frames of a particular page.
  45930. **
  45931. ** WAL-INDEX FORMAT
  45932. **
  45933. ** Conceptually, the wal-index is shared memory, though VFS implementations
  45934. ** might choose to implement the wal-index using a mmapped file. Because
  45935. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  45936. ** on a network filesystem. All users of the database must be able to
  45937. ** share memory.
  45938. **
  45939. ** The wal-index is transient. After a crash, the wal-index can (and should
  45940. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  45941. ** to either truncate or zero the header of the wal-index when the last
  45942. ** connection to it closes. Because the wal-index is transient, it can
  45943. ** use an architecture-specific format; it does not have to be cross-platform.
  45944. ** Hence, unlike the database and WAL file formats which store all values
  45945. ** as big endian, the wal-index can store multi-byte values in the native
  45946. ** byte order of the host computer.
  45947. **
  45948. ** The purpose of the wal-index is to answer this question quickly: Given
  45949. ** a page number P and a maximum frame index M, return the index of the
  45950. ** last frame in the wal before frame M for page P in the WAL, or return
  45951. ** NULL if there are no frames for page P in the WAL prior to M.
  45952. **
  45953. ** The wal-index consists of a header region, followed by an one or
  45954. ** more index blocks.
  45955. **
  45956. ** The wal-index header contains the total number of frames within the WAL
  45957. ** in the mxFrame field.
  45958. **
  45959. ** Each index block except for the first contains information on
  45960. ** HASHTABLE_NPAGE frames. The first index block contains information on
  45961. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  45962. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  45963. ** first index block are the same size as all other index blocks in the
  45964. ** wal-index.
  45965. **
  45966. ** Each index block contains two sections, a page-mapping that contains the
  45967. ** database page number associated with each wal frame, and a hash-table
  45968. ** that allows readers to query an index block for a specific page number.
  45969. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  45970. ** for the first index block) 32-bit page numbers. The first entry in the
  45971. ** first index-block contains the database page number corresponding to the
  45972. ** first frame in the WAL file. The first entry in the second index block
  45973. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  45974. ** the log, and so on.
  45975. **
  45976. ** The last index block in a wal-index usually contains less than the full
  45977. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  45978. ** depending on the contents of the WAL file. This does not change the
  45979. ** allocated size of the page-mapping array - the page-mapping array merely
  45980. ** contains unused entries.
  45981. **
  45982. ** Even without using the hash table, the last frame for page P
  45983. ** can be found by scanning the page-mapping sections of each index block
  45984. ** starting with the last index block and moving toward the first, and
  45985. ** within each index block, starting at the end and moving toward the
  45986. ** beginning. The first entry that equals P corresponds to the frame
  45987. ** holding the content for that page.
  45988. **
  45989. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  45990. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  45991. ** hash table for each page number in the mapping section, so the hash
  45992. ** table is never more than half full. The expected number of collisions
  45993. ** prior to finding a match is 1. Each entry of the hash table is an
  45994. ** 1-based index of an entry in the mapping section of the same
  45995. ** index block. Let K be the 1-based index of the largest entry in
  45996. ** the mapping section. (For index blocks other than the last, K will
  45997. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  45998. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  45999. ** contain a value of 0.
  46000. **
  46001. ** To look for page P in the hash table, first compute a hash iKey on
  46002. ** P as follows:
  46003. **
  46004. ** iKey = (P * 383) % HASHTABLE_NSLOT
  46005. **
  46006. ** Then start scanning entries of the hash table, starting with iKey
  46007. ** (wrapping around to the beginning when the end of the hash table is
  46008. ** reached) until an unused hash slot is found. Let the first unused slot
  46009. ** be at index iUnused. (iUnused might be less than iKey if there was
  46010. ** wrap-around.) Because the hash table is never more than half full,
  46011. ** the search is guaranteed to eventually hit an unused entry. Let
  46012. ** iMax be the value between iKey and iUnused, closest to iUnused,
  46013. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  46014. ** no hash slot such that aHash[i]==p) then page P is not in the
  46015. ** current index block. Otherwise the iMax-th mapping entry of the
  46016. ** current index block corresponds to the last entry that references
  46017. ** page P.
  46018. **
  46019. ** A hash search begins with the last index block and moves toward the
  46020. ** first index block, looking for entries corresponding to page P. On
  46021. ** average, only two or three slots in each index block need to be
  46022. ** examined in order to either find the last entry for page P, or to
  46023. ** establish that no such entry exists in the block. Each index block
  46024. ** holds over 4000 entries. So two or three index blocks are sufficient
  46025. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  46026. ** comparisons (on average) suffice to either locate a frame in the
  46027. ** WAL or to establish that the frame does not exist in the WAL. This
  46028. ** is much faster than scanning the entire 10MB WAL.
  46029. **
  46030. ** Note that entries are added in order of increasing K. Hence, one
  46031. ** reader might be using some value K0 and a second reader that started
  46032. ** at a later time (after additional transactions were added to the WAL
  46033. ** and to the wal-index) might be using a different value K1, where K1>K0.
  46034. ** Both readers can use the same hash table and mapping section to get
  46035. ** the correct result. There may be entries in the hash table with
  46036. ** K>K0 but to the first reader, those entries will appear to be unused
  46037. ** slots in the hash table and so the first reader will get an answer as
  46038. ** if no values greater than K0 had ever been inserted into the hash table
  46039. ** in the first place - which is what reader one wants. Meanwhile, the
  46040. ** second reader using K1 will see additional values that were inserted
  46041. ** later, which is exactly what reader two wants.
  46042. **
  46043. ** When a rollback occurs, the value of K is decreased. Hash table entries
  46044. ** that correspond to frames greater than the new K value are removed
  46045. ** from the hash table at this point.
  46046. */
  46047. #ifndef SQLITE_OMIT_WAL
  46048. /*
  46049. ** Trace output macros
  46050. */
  46051. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46052. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  46053. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  46054. #else
  46055. # define WALTRACE(X)
  46056. #endif
  46057. /*
  46058. ** The maximum (and only) versions of the wal and wal-index formats
  46059. ** that may be interpreted by this version of SQLite.
  46060. **
  46061. ** If a client begins recovering a WAL file and finds that (a) the checksum
  46062. ** values in the wal-header are correct and (b) the version field is not
  46063. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  46064. **
  46065. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  46066. ** checksum test is successful) and finds that the version field is not
  46067. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  46068. ** returns SQLITE_CANTOPEN.
  46069. */
  46070. #define WAL_MAX_VERSION 3007000
  46071. #define WALINDEX_MAX_VERSION 3007000
  46072. /*
  46073. ** Indices of various locking bytes. WAL_NREADER is the number
  46074. ** of available reader locks and should be at least 3.
  46075. */
  46076. #define WAL_WRITE_LOCK 0
  46077. #define WAL_ALL_BUT_WRITE 1
  46078. #define WAL_CKPT_LOCK 1
  46079. #define WAL_RECOVER_LOCK 2
  46080. #define WAL_READ_LOCK(I) (3+(I))
  46081. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  46082. /* Object declarations */
  46083. typedef struct WalIndexHdr WalIndexHdr;
  46084. typedef struct WalIterator WalIterator;
  46085. typedef struct WalCkptInfo WalCkptInfo;
  46086. /*
  46087. ** The following object holds a copy of the wal-index header content.
  46088. **
  46089. ** The actual header in the wal-index consists of two copies of this
  46090. ** object.
  46091. **
  46092. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  46093. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  46094. ** added in 3.7.1 when support for 64K pages was added.
  46095. */
  46096. struct WalIndexHdr {
  46097. u32 iVersion; /* Wal-index version */
  46098. u32 unused; /* Unused (padding) field */
  46099. u32 iChange; /* Counter incremented each transaction */
  46100. u8 isInit; /* 1 when initialized */
  46101. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  46102. u16 szPage; /* Database page size in bytes. 1==64K */
  46103. u32 mxFrame; /* Index of last valid frame in the WAL */
  46104. u32 nPage; /* Size of database in pages */
  46105. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  46106. u32 aSalt[2]; /* Two salt values copied from WAL header */
  46107. u32 aCksum[2]; /* Checksum over all prior fields */
  46108. };
  46109. /*
  46110. ** A copy of the following object occurs in the wal-index immediately
  46111. ** following the second copy of the WalIndexHdr. This object stores
  46112. ** information used by checkpoint.
  46113. **
  46114. ** nBackfill is the number of frames in the WAL that have been written
  46115. ** back into the database. (We call the act of moving content from WAL to
  46116. ** database "backfilling".) The nBackfill number is never greater than
  46117. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  46118. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  46119. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  46120. ** mxFrame back to zero when the WAL is reset.
  46121. **
  46122. ** There is one entry in aReadMark[] for each reader lock. If a reader
  46123. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  46124. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  46125. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  46126. ** a special case; its value is never used and it exists as a place-holder
  46127. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  46128. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  46129. ** directly from the database.
  46130. **
  46131. ** The value of aReadMark[K] may only be changed by a thread that
  46132. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  46133. ** aReadMark[K] cannot changed while there is a reader is using that mark
  46134. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  46135. **
  46136. ** The checkpointer may only transfer frames from WAL to database where
  46137. ** the frame numbers are less than or equal to every aReadMark[] that is
  46138. ** in use (that is, every aReadMark[j] for which there is a corresponding
  46139. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  46140. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  46141. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  46142. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  46143. ** in the WAL has been backfilled into the database) then new readers
  46144. ** will choose aReadMark[0] which has value 0 and hence such reader will
  46145. ** get all their all content directly from the database file and ignore
  46146. ** the WAL.
  46147. **
  46148. ** Writers normally append new frames to the end of the WAL. However,
  46149. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  46150. ** written back into the database) and if no readers are using the WAL
  46151. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  46152. ** the writer will first "reset" the WAL back to the beginning and start
  46153. ** writing new content beginning at frame 1.
  46154. **
  46155. ** We assume that 32-bit loads are atomic and so no locks are needed in
  46156. ** order to read from any aReadMark[] entries.
  46157. */
  46158. struct WalCkptInfo {
  46159. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  46160. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  46161. };
  46162. #define READMARK_NOT_USED 0xffffffff
  46163. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  46164. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  46165. ** only support mandatory file-locks, we do not read or write data
  46166. ** from the region of the file on which locks are applied.
  46167. */
  46168. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  46169. #define WALINDEX_LOCK_RESERVED 16
  46170. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  46171. /* Size of header before each frame in wal */
  46172. #define WAL_FRAME_HDRSIZE 24
  46173. /* Size of write ahead log header, including checksum. */
  46174. /* #define WAL_HDRSIZE 24 */
  46175. #define WAL_HDRSIZE 32
  46176. /* WAL magic value. Either this value, or the same value with the least
  46177. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  46178. ** big-endian format in the first 4 bytes of a WAL file.
  46179. **
  46180. ** If the LSB is set, then the checksums for each frame within the WAL
  46181. ** file are calculated by treating all data as an array of 32-bit
  46182. ** big-endian words. Otherwise, they are calculated by interpreting
  46183. ** all data as 32-bit little-endian words.
  46184. */
  46185. #define WAL_MAGIC 0x377f0682
  46186. /*
  46187. ** Return the offset of frame iFrame in the write-ahead log file,
  46188. ** assuming a database page size of szPage bytes. The offset returned
  46189. ** is to the start of the write-ahead log frame-header.
  46190. */
  46191. #define walFrameOffset(iFrame, szPage) ( \
  46192. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  46193. )
  46194. /*
  46195. ** An open write-ahead log file is represented by an instance of the
  46196. ** following object.
  46197. */
  46198. struct Wal {
  46199. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  46200. sqlite3_file *pDbFd; /* File handle for the database file */
  46201. sqlite3_file *pWalFd; /* File handle for WAL file */
  46202. u32 iCallback; /* Value to pass to log callback (or 0) */
  46203. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  46204. int nWiData; /* Size of array apWiData */
  46205. int szFirstBlock; /* Size of first block written to WAL file */
  46206. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  46207. u32 szPage; /* Database page size */
  46208. i16 readLock; /* Which read lock is being held. -1 for none */
  46209. u8 syncFlags; /* Flags to use to sync header writes */
  46210. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  46211. u8 writeLock; /* True if in a write transaction */
  46212. u8 ckptLock; /* True if holding a checkpoint lock */
  46213. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  46214. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  46215. u8 syncHeader; /* Fsync the WAL header if true */
  46216. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  46217. WalIndexHdr hdr; /* Wal-index header for current transaction */
  46218. const char *zWalName; /* Name of WAL file */
  46219. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  46220. #ifdef SQLITE_DEBUG
  46221. u8 lockError; /* True if a locking error has occurred */
  46222. #endif
  46223. };
  46224. /*
  46225. ** Candidate values for Wal.exclusiveMode.
  46226. */
  46227. #define WAL_NORMAL_MODE 0
  46228. #define WAL_EXCLUSIVE_MODE 1
  46229. #define WAL_HEAPMEMORY_MODE 2
  46230. /*
  46231. ** Possible values for WAL.readOnly
  46232. */
  46233. #define WAL_RDWR 0 /* Normal read/write connection */
  46234. #define WAL_RDONLY 1 /* The WAL file is readonly */
  46235. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  46236. /*
  46237. ** Each page of the wal-index mapping contains a hash-table made up of
  46238. ** an array of HASHTABLE_NSLOT elements of the following type.
  46239. */
  46240. typedef u16 ht_slot;
  46241. /*
  46242. ** This structure is used to implement an iterator that loops through
  46243. ** all frames in the WAL in database page order. Where two or more frames
  46244. ** correspond to the same database page, the iterator visits only the
  46245. ** frame most recently written to the WAL (in other words, the frame with
  46246. ** the largest index).
  46247. **
  46248. ** The internals of this structure are only accessed by:
  46249. **
  46250. ** walIteratorInit() - Create a new iterator,
  46251. ** walIteratorNext() - Step an iterator,
  46252. ** walIteratorFree() - Free an iterator.
  46253. **
  46254. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  46255. */
  46256. struct WalIterator {
  46257. int iPrior; /* Last result returned from the iterator */
  46258. int nSegment; /* Number of entries in aSegment[] */
  46259. struct WalSegment {
  46260. int iNext; /* Next slot in aIndex[] not yet returned */
  46261. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  46262. u32 *aPgno; /* Array of page numbers. */
  46263. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  46264. int iZero; /* Frame number associated with aPgno[0] */
  46265. } aSegment[1]; /* One for every 32KB page in the wal-index */
  46266. };
  46267. /*
  46268. ** Define the parameters of the hash tables in the wal-index file. There
  46269. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  46270. ** wal-index.
  46271. **
  46272. ** Changing any of these constants will alter the wal-index format and
  46273. ** create incompatibilities.
  46274. */
  46275. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  46276. #define HASHTABLE_HASH_1 383 /* Should be prime */
  46277. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  46278. /*
  46279. ** The block of page numbers associated with the first hash-table in a
  46280. ** wal-index is smaller than usual. This is so that there is a complete
  46281. ** hash-table on each aligned 32KB page of the wal-index.
  46282. */
  46283. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  46284. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  46285. #define WALINDEX_PGSZ ( \
  46286. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  46287. )
  46288. /*
  46289. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  46290. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  46291. ** numbered from zero.
  46292. **
  46293. ** If this call is successful, *ppPage is set to point to the wal-index
  46294. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  46295. ** then an SQLite error code is returned and *ppPage is set to 0.
  46296. */
  46297. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  46298. int rc = SQLITE_OK;
  46299. /* Enlarge the pWal->apWiData[] array if required */
  46300. if( pWal->nWiData<=iPage ){
  46301. int nByte = sizeof(u32*)*(iPage+1);
  46302. volatile u32 **apNew;
  46303. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  46304. if( !apNew ){
  46305. *ppPage = 0;
  46306. return SQLITE_NOMEM;
  46307. }
  46308. memset((void*)&apNew[pWal->nWiData], 0,
  46309. sizeof(u32*)*(iPage+1-pWal->nWiData));
  46310. pWal->apWiData = apNew;
  46311. pWal->nWiData = iPage+1;
  46312. }
  46313. /* Request a pointer to the required page from the VFS */
  46314. if( pWal->apWiData[iPage]==0 ){
  46315. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46316. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  46317. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  46318. }else{
  46319. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  46320. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  46321. );
  46322. if( rc==SQLITE_READONLY ){
  46323. pWal->readOnly |= WAL_SHM_RDONLY;
  46324. rc = SQLITE_OK;
  46325. }
  46326. }
  46327. }
  46328. *ppPage = pWal->apWiData[iPage];
  46329. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  46330. return rc;
  46331. }
  46332. /*
  46333. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  46334. */
  46335. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  46336. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46337. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  46338. }
  46339. /*
  46340. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  46341. */
  46342. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  46343. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46344. return (volatile WalIndexHdr*)pWal->apWiData[0];
  46345. }
  46346. /*
  46347. ** The argument to this macro must be of type u32. On a little-endian
  46348. ** architecture, it returns the u32 value that results from interpreting
  46349. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  46350. ** returns the value that would be produced by intepreting the 4 bytes
  46351. ** of the input value as a little-endian integer.
  46352. */
  46353. #define BYTESWAP32(x) ( \
  46354. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  46355. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  46356. )
  46357. /*
  46358. ** Generate or extend an 8 byte checksum based on the data in
  46359. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  46360. ** initial values of 0 and 0 if aIn==NULL).
  46361. **
  46362. ** The checksum is written back into aOut[] before returning.
  46363. **
  46364. ** nByte must be a positive multiple of 8.
  46365. */
  46366. static void walChecksumBytes(
  46367. int nativeCksum, /* True for native byte-order, false for non-native */
  46368. u8 *a, /* Content to be checksummed */
  46369. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  46370. const u32 *aIn, /* Initial checksum value input */
  46371. u32 *aOut /* OUT: Final checksum value output */
  46372. ){
  46373. u32 s1, s2;
  46374. u32 *aData = (u32 *)a;
  46375. u32 *aEnd = (u32 *)&a[nByte];
  46376. if( aIn ){
  46377. s1 = aIn[0];
  46378. s2 = aIn[1];
  46379. }else{
  46380. s1 = s2 = 0;
  46381. }
  46382. assert( nByte>=8 );
  46383. assert( (nByte&0x00000007)==0 );
  46384. if( nativeCksum ){
  46385. do {
  46386. s1 += *aData++ + s2;
  46387. s2 += *aData++ + s1;
  46388. }while( aData<aEnd );
  46389. }else{
  46390. do {
  46391. s1 += BYTESWAP32(aData[0]) + s2;
  46392. s2 += BYTESWAP32(aData[1]) + s1;
  46393. aData += 2;
  46394. }while( aData<aEnd );
  46395. }
  46396. aOut[0] = s1;
  46397. aOut[1] = s2;
  46398. }
  46399. static void walShmBarrier(Wal *pWal){
  46400. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  46401. sqlite3OsShmBarrier(pWal->pDbFd);
  46402. }
  46403. }
  46404. /*
  46405. ** Write the header information in pWal->hdr into the wal-index.
  46406. **
  46407. ** The checksum on pWal->hdr is updated before it is written.
  46408. */
  46409. static void walIndexWriteHdr(Wal *pWal){
  46410. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  46411. const int nCksum = offsetof(WalIndexHdr, aCksum);
  46412. assert( pWal->writeLock );
  46413. pWal->hdr.isInit = 1;
  46414. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  46415. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  46416. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46417. walShmBarrier(pWal);
  46418. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  46419. }
  46420. /*
  46421. ** This function encodes a single frame header and writes it to a buffer
  46422. ** supplied by the caller. A frame-header is made up of a series of
  46423. ** 4-byte big-endian integers, as follows:
  46424. **
  46425. ** 0: Page number.
  46426. ** 4: For commit records, the size of the database image in pages
  46427. ** after the commit. For all other records, zero.
  46428. ** 8: Salt-1 (copied from the wal-header)
  46429. ** 12: Salt-2 (copied from the wal-header)
  46430. ** 16: Checksum-1.
  46431. ** 20: Checksum-2.
  46432. */
  46433. static void walEncodeFrame(
  46434. Wal *pWal, /* The write-ahead log */
  46435. u32 iPage, /* Database page number for frame */
  46436. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  46437. u8 *aData, /* Pointer to page data */
  46438. u8 *aFrame /* OUT: Write encoded frame here */
  46439. ){
  46440. int nativeCksum; /* True for native byte-order checksums */
  46441. u32 *aCksum = pWal->hdr.aFrameCksum;
  46442. assert( WAL_FRAME_HDRSIZE==24 );
  46443. sqlite3Put4byte(&aFrame[0], iPage);
  46444. sqlite3Put4byte(&aFrame[4], nTruncate);
  46445. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  46446. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46447. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46448. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46449. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  46450. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  46451. }
  46452. /*
  46453. ** Check to see if the frame with header in aFrame[] and content
  46454. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  46455. ** *pnTruncate and return true. Return if the frame is not valid.
  46456. */
  46457. static int walDecodeFrame(
  46458. Wal *pWal, /* The write-ahead log */
  46459. u32 *piPage, /* OUT: Database page number for frame */
  46460. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  46461. u8 *aData, /* Pointer to page data (for checksum) */
  46462. u8 *aFrame /* Frame data */
  46463. ){
  46464. int nativeCksum; /* True for native byte-order checksums */
  46465. u32 *aCksum = pWal->hdr.aFrameCksum;
  46466. u32 pgno; /* Page number of the frame */
  46467. assert( WAL_FRAME_HDRSIZE==24 );
  46468. /* A frame is only valid if the salt values in the frame-header
  46469. ** match the salt values in the wal-header.
  46470. */
  46471. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  46472. return 0;
  46473. }
  46474. /* A frame is only valid if the page number is creater than zero.
  46475. */
  46476. pgno = sqlite3Get4byte(&aFrame[0]);
  46477. if( pgno==0 ){
  46478. return 0;
  46479. }
  46480. /* A frame is only valid if a checksum of the WAL header,
  46481. ** all prior frams, the first 16 bytes of this frame-header,
  46482. ** and the frame-data matches the checksum in the last 8
  46483. ** bytes of this frame-header.
  46484. */
  46485. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  46486. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  46487. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  46488. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  46489. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  46490. ){
  46491. /* Checksum failed. */
  46492. return 0;
  46493. }
  46494. /* If we reach this point, the frame is valid. Return the page number
  46495. ** and the new database size.
  46496. */
  46497. *piPage = pgno;
  46498. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  46499. return 1;
  46500. }
  46501. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  46502. /*
  46503. ** Names of locks. This routine is used to provide debugging output and is not
  46504. ** a part of an ordinary build.
  46505. */
  46506. static const char *walLockName(int lockIdx){
  46507. if( lockIdx==WAL_WRITE_LOCK ){
  46508. return "WRITE-LOCK";
  46509. }else if( lockIdx==WAL_CKPT_LOCK ){
  46510. return "CKPT-LOCK";
  46511. }else if( lockIdx==WAL_RECOVER_LOCK ){
  46512. return "RECOVER-LOCK";
  46513. }else{
  46514. static char zName[15];
  46515. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  46516. lockIdx-WAL_READ_LOCK(0));
  46517. return zName;
  46518. }
  46519. }
  46520. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  46521. /*
  46522. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  46523. ** A lock cannot be moved directly between shared and exclusive - it must go
  46524. ** through the unlocked state first.
  46525. **
  46526. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  46527. */
  46528. static int walLockShared(Wal *pWal, int lockIdx){
  46529. int rc;
  46530. if( pWal->exclusiveMode ) return SQLITE_OK;
  46531. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46532. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  46533. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  46534. walLockName(lockIdx), rc ? "failed" : "ok"));
  46535. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46536. return rc;
  46537. }
  46538. static void walUnlockShared(Wal *pWal, int lockIdx){
  46539. if( pWal->exclusiveMode ) return;
  46540. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  46541. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  46542. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  46543. }
  46544. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  46545. int rc;
  46546. if( pWal->exclusiveMode ) return SQLITE_OK;
  46547. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46548. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  46549. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  46550. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  46551. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  46552. return rc;
  46553. }
  46554. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  46555. if( pWal->exclusiveMode ) return;
  46556. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  46557. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  46558. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  46559. walLockName(lockIdx), n));
  46560. }
  46561. /*
  46562. ** Compute a hash on a page number. The resulting hash value must land
  46563. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  46564. ** the hash to the next value in the event of a collision.
  46565. */
  46566. static int walHash(u32 iPage){
  46567. assert( iPage>0 );
  46568. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  46569. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  46570. }
  46571. static int walNextHash(int iPriorHash){
  46572. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  46573. }
  46574. /*
  46575. ** Return pointers to the hash table and page number array stored on
  46576. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  46577. ** numbered starting from 0.
  46578. **
  46579. ** Set output variable *paHash to point to the start of the hash table
  46580. ** in the wal-index file. Set *piZero to one less than the frame
  46581. ** number of the first frame indexed by this hash table. If a
  46582. ** slot in the hash table is set to N, it refers to frame number
  46583. ** (*piZero+N) in the log.
  46584. **
  46585. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  46586. ** first frame indexed by the hash table, frame (*piZero+1).
  46587. */
  46588. static int walHashGet(
  46589. Wal *pWal, /* WAL handle */
  46590. int iHash, /* Find the iHash'th table */
  46591. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  46592. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  46593. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  46594. ){
  46595. int rc; /* Return code */
  46596. volatile u32 *aPgno;
  46597. rc = walIndexPage(pWal, iHash, &aPgno);
  46598. assert( rc==SQLITE_OK || iHash>0 );
  46599. if( rc==SQLITE_OK ){
  46600. u32 iZero;
  46601. volatile ht_slot *aHash;
  46602. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  46603. if( iHash==0 ){
  46604. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  46605. iZero = 0;
  46606. }else{
  46607. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  46608. }
  46609. *paPgno = &aPgno[-1];
  46610. *paHash = aHash;
  46611. *piZero = iZero;
  46612. }
  46613. return rc;
  46614. }
  46615. /*
  46616. ** Return the number of the wal-index page that contains the hash-table
  46617. ** and page-number array that contain entries corresponding to WAL frame
  46618. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  46619. ** are numbered starting from 0.
  46620. */
  46621. static int walFramePage(u32 iFrame){
  46622. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  46623. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  46624. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  46625. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  46626. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  46627. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  46628. );
  46629. return iHash;
  46630. }
  46631. /*
  46632. ** Return the page number associated with frame iFrame in this WAL.
  46633. */
  46634. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  46635. int iHash = walFramePage(iFrame);
  46636. if( iHash==0 ){
  46637. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  46638. }
  46639. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  46640. }
  46641. /*
  46642. ** Remove entries from the hash table that point to WAL slots greater
  46643. ** than pWal->hdr.mxFrame.
  46644. **
  46645. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  46646. ** to a rollback or savepoint.
  46647. **
  46648. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  46649. ** updated. Any later hash tables will be automatically cleared when
  46650. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  46651. ** actually needed.
  46652. */
  46653. static void walCleanupHash(Wal *pWal){
  46654. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  46655. volatile u32 *aPgno = 0; /* Page number array for hash table */
  46656. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  46657. int iLimit = 0; /* Zero values greater than this */
  46658. int nByte; /* Number of bytes to zero in aPgno[] */
  46659. int i; /* Used to iterate through aHash[] */
  46660. assert( pWal->writeLock );
  46661. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  46662. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  46663. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  46664. if( pWal->hdr.mxFrame==0 ) return;
  46665. /* Obtain pointers to the hash-table and page-number array containing
  46666. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  46667. ** that the page said hash-table and array reside on is already mapped.
  46668. */
  46669. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  46670. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  46671. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  46672. /* Zero all hash-table entries that correspond to frame numbers greater
  46673. ** than pWal->hdr.mxFrame.
  46674. */
  46675. iLimit = pWal->hdr.mxFrame - iZero;
  46676. assert( iLimit>0 );
  46677. for(i=0; i<HASHTABLE_NSLOT; i++){
  46678. if( aHash[i]>iLimit ){
  46679. aHash[i] = 0;
  46680. }
  46681. }
  46682. /* Zero the entries in the aPgno array that correspond to frames with
  46683. ** frame numbers greater than pWal->hdr.mxFrame.
  46684. */
  46685. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  46686. memset((void *)&aPgno[iLimit+1], 0, nByte);
  46687. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46688. /* Verify that the every entry in the mapping region is still reachable
  46689. ** via the hash table even after the cleanup.
  46690. */
  46691. if( iLimit ){
  46692. int i; /* Loop counter */
  46693. int iKey; /* Hash key */
  46694. for(i=1; i<=iLimit; i++){
  46695. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46696. if( aHash[iKey]==i ) break;
  46697. }
  46698. assert( aHash[iKey]==i );
  46699. }
  46700. }
  46701. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46702. }
  46703. /*
  46704. ** Set an entry in the wal-index that will map database page number
  46705. ** pPage into WAL frame iFrame.
  46706. */
  46707. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  46708. int rc; /* Return code */
  46709. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  46710. volatile u32 *aPgno = 0; /* Page number array */
  46711. volatile ht_slot *aHash = 0; /* Hash table */
  46712. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  46713. /* Assuming the wal-index file was successfully mapped, populate the
  46714. ** page number array and hash table entry.
  46715. */
  46716. if( rc==SQLITE_OK ){
  46717. int iKey; /* Hash table key */
  46718. int idx; /* Value to write to hash-table slot */
  46719. int nCollide; /* Number of hash collisions */
  46720. idx = iFrame - iZero;
  46721. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  46722. /* If this is the first entry to be added to this hash-table, zero the
  46723. ** entire hash table and aPgno[] array before proceding.
  46724. */
  46725. if( idx==1 ){
  46726. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  46727. memset((void*)&aPgno[1], 0, nByte);
  46728. }
  46729. /* If the entry in aPgno[] is already set, then the previous writer
  46730. ** must have exited unexpectedly in the middle of a transaction (after
  46731. ** writing one or more dirty pages to the WAL to free up memory).
  46732. ** Remove the remnants of that writers uncommitted transaction from
  46733. ** the hash-table before writing any new entries.
  46734. */
  46735. if( aPgno[idx] ){
  46736. walCleanupHash(pWal);
  46737. assert( !aPgno[idx] );
  46738. }
  46739. /* Write the aPgno[] array entry and the hash-table slot. */
  46740. nCollide = idx;
  46741. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  46742. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  46743. }
  46744. aPgno[idx] = iPage;
  46745. aHash[iKey] = (ht_slot)idx;
  46746. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  46747. /* Verify that the number of entries in the hash table exactly equals
  46748. ** the number of entries in the mapping region.
  46749. */
  46750. {
  46751. int i; /* Loop counter */
  46752. int nEntry = 0; /* Number of entries in the hash table */
  46753. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  46754. assert( nEntry==idx );
  46755. }
  46756. /* Verify that the every entry in the mapping region is reachable
  46757. ** via the hash table. This turns out to be a really, really expensive
  46758. ** thing to check, so only do this occasionally - not on every
  46759. ** iteration.
  46760. */
  46761. if( (idx&0x3ff)==0 ){
  46762. int i; /* Loop counter */
  46763. for(i=1; i<=idx; i++){
  46764. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  46765. if( aHash[iKey]==i ) break;
  46766. }
  46767. assert( aHash[iKey]==i );
  46768. }
  46769. }
  46770. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  46771. }
  46772. return rc;
  46773. }
  46774. /*
  46775. ** Recover the wal-index by reading the write-ahead log file.
  46776. **
  46777. ** This routine first tries to establish an exclusive lock on the
  46778. ** wal-index to prevent other threads/processes from doing anything
  46779. ** with the WAL or wal-index while recovery is running. The
  46780. ** WAL_RECOVER_LOCK is also held so that other threads will know
  46781. ** that this thread is running recovery. If unable to establish
  46782. ** the necessary locks, this routine returns SQLITE_BUSY.
  46783. */
  46784. static int walIndexRecover(Wal *pWal){
  46785. int rc; /* Return Code */
  46786. i64 nSize; /* Size of log file */
  46787. u32 aFrameCksum[2] = {0, 0};
  46788. int iLock; /* Lock offset to lock for checkpoint */
  46789. int nLock; /* Number of locks to hold */
  46790. /* Obtain an exclusive lock on all byte in the locking range not already
  46791. ** locked by the caller. The caller is guaranteed to have locked the
  46792. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  46793. ** If successful, the same bytes that are locked here are unlocked before
  46794. ** this function returns.
  46795. */
  46796. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  46797. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  46798. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  46799. assert( pWal->writeLock );
  46800. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  46801. nLock = SQLITE_SHM_NLOCK - iLock;
  46802. rc = walLockExclusive(pWal, iLock, nLock);
  46803. if( rc ){
  46804. return rc;
  46805. }
  46806. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  46807. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  46808. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  46809. if( rc!=SQLITE_OK ){
  46810. goto recovery_error;
  46811. }
  46812. if( nSize>WAL_HDRSIZE ){
  46813. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  46814. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  46815. int szFrame; /* Number of bytes in buffer aFrame[] */
  46816. u8 *aData; /* Pointer to data part of aFrame buffer */
  46817. int iFrame; /* Index of last frame read */
  46818. i64 iOffset; /* Next offset to read from log file */
  46819. int szPage; /* Page size according to the log */
  46820. u32 magic; /* Magic value read from WAL header */
  46821. u32 version; /* Magic value read from WAL header */
  46822. int isValid; /* True if this frame is valid */
  46823. /* Read in the WAL header. */
  46824. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  46825. if( rc!=SQLITE_OK ){
  46826. goto recovery_error;
  46827. }
  46828. /* If the database page size is not a power of two, or is greater than
  46829. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  46830. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  46831. ** WAL file.
  46832. */
  46833. magic = sqlite3Get4byte(&aBuf[0]);
  46834. szPage = sqlite3Get4byte(&aBuf[8]);
  46835. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  46836. || szPage&(szPage-1)
  46837. || szPage>SQLITE_MAX_PAGE_SIZE
  46838. || szPage<512
  46839. ){
  46840. goto finished;
  46841. }
  46842. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  46843. pWal->szPage = szPage;
  46844. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  46845. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  46846. /* Verify that the WAL header checksum is correct */
  46847. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  46848. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  46849. );
  46850. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  46851. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  46852. ){
  46853. goto finished;
  46854. }
  46855. /* Verify that the version number on the WAL format is one that
  46856. ** are able to understand */
  46857. version = sqlite3Get4byte(&aBuf[4]);
  46858. if( version!=WAL_MAX_VERSION ){
  46859. rc = SQLITE_CANTOPEN_BKPT;
  46860. goto finished;
  46861. }
  46862. /* Malloc a buffer to read frames into. */
  46863. szFrame = szPage + WAL_FRAME_HDRSIZE;
  46864. aFrame = (u8 *)sqlite3_malloc(szFrame);
  46865. if( !aFrame ){
  46866. rc = SQLITE_NOMEM;
  46867. goto recovery_error;
  46868. }
  46869. aData = &aFrame[WAL_FRAME_HDRSIZE];
  46870. /* Read all frames from the log file. */
  46871. iFrame = 0;
  46872. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  46873. u32 pgno; /* Database page number for frame */
  46874. u32 nTruncate; /* dbsize field from frame header */
  46875. /* Read and decode the next log frame. */
  46876. iFrame++;
  46877. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  46878. if( rc!=SQLITE_OK ) break;
  46879. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  46880. if( !isValid ) break;
  46881. rc = walIndexAppend(pWal, iFrame, pgno);
  46882. if( rc!=SQLITE_OK ) break;
  46883. /* If nTruncate is non-zero, this is a commit record. */
  46884. if( nTruncate ){
  46885. pWal->hdr.mxFrame = iFrame;
  46886. pWal->hdr.nPage = nTruncate;
  46887. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  46888. testcase( szPage<=32768 );
  46889. testcase( szPage>=65536 );
  46890. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  46891. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  46892. }
  46893. }
  46894. sqlite3_free(aFrame);
  46895. }
  46896. finished:
  46897. if( rc==SQLITE_OK ){
  46898. volatile WalCkptInfo *pInfo;
  46899. int i;
  46900. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  46901. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  46902. walIndexWriteHdr(pWal);
  46903. /* Reset the checkpoint-header. This is safe because this thread is
  46904. ** currently holding locks that exclude all other readers, writers and
  46905. ** checkpointers.
  46906. */
  46907. pInfo = walCkptInfo(pWal);
  46908. pInfo->nBackfill = 0;
  46909. pInfo->aReadMark[0] = 0;
  46910. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  46911. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  46912. /* If more than one frame was recovered from the log file, report an
  46913. ** event via sqlite3_log(). This is to help with identifying performance
  46914. ** problems caused by applications routinely shutting down without
  46915. ** checkpointing the log file.
  46916. */
  46917. if( pWal->hdr.nPage ){
  46918. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  46919. "recovered %d frames from WAL file %s",
  46920. pWal->hdr.mxFrame, pWal->zWalName
  46921. );
  46922. }
  46923. }
  46924. recovery_error:
  46925. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  46926. walUnlockExclusive(pWal, iLock, nLock);
  46927. return rc;
  46928. }
  46929. /*
  46930. ** Close an open wal-index.
  46931. */
  46932. static void walIndexClose(Wal *pWal, int isDelete){
  46933. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46934. int i;
  46935. for(i=0; i<pWal->nWiData; i++){
  46936. sqlite3_free((void *)pWal->apWiData[i]);
  46937. pWal->apWiData[i] = 0;
  46938. }
  46939. }else{
  46940. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  46941. }
  46942. }
  46943. /*
  46944. ** Open a connection to the WAL file zWalName. The database file must
  46945. ** already be opened on connection pDbFd. The buffer that zWalName points
  46946. ** to must remain valid for the lifetime of the returned Wal* handle.
  46947. **
  46948. ** A SHARED lock should be held on the database file when this function
  46949. ** is called. The purpose of this SHARED lock is to prevent any other
  46950. ** client from unlinking the WAL or wal-index file. If another process
  46951. ** were to do this just after this client opened one of these files, the
  46952. ** system would be badly broken.
  46953. **
  46954. ** If the log file is successfully opened, SQLITE_OK is returned and
  46955. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  46956. ** an SQLite error code is returned and *ppWal is left unmodified.
  46957. */
  46958. SQLITE_PRIVATE int sqlite3WalOpen(
  46959. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  46960. sqlite3_file *pDbFd, /* The open database file */
  46961. const char *zWalName, /* Name of the WAL file */
  46962. int bNoShm, /* True to run in heap-memory mode */
  46963. i64 mxWalSize, /* Truncate WAL to this size on reset */
  46964. Wal **ppWal /* OUT: Allocated Wal handle */
  46965. ){
  46966. int rc; /* Return Code */
  46967. Wal *pRet; /* Object to allocate and return */
  46968. int flags; /* Flags passed to OsOpen() */
  46969. assert( zWalName && zWalName[0] );
  46970. assert( pDbFd );
  46971. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  46972. ** this source file. Verify that the #defines of the locking byte offsets
  46973. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  46974. */
  46975. #ifdef WIN_SHM_BASE
  46976. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46977. #endif
  46978. #ifdef UNIX_SHM_BASE
  46979. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46980. #endif
  46981. /* Allocate an instance of struct Wal to return. */
  46982. *ppWal = 0;
  46983. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  46984. if( !pRet ){
  46985. return SQLITE_NOMEM;
  46986. }
  46987. pRet->pVfs = pVfs;
  46988. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  46989. pRet->pDbFd = pDbFd;
  46990. pRet->readLock = -1;
  46991. pRet->mxWalSize = mxWalSize;
  46992. pRet->zWalName = zWalName;
  46993. pRet->syncHeader = 1;
  46994. pRet->padToSectorBoundary = 1;
  46995. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  46996. /* Open file handle on the write-ahead log file. */
  46997. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  46998. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  46999. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  47000. pRet->readOnly = WAL_RDONLY;
  47001. }
  47002. if( rc!=SQLITE_OK ){
  47003. walIndexClose(pRet, 0);
  47004. sqlite3OsClose(pRet->pWalFd);
  47005. sqlite3_free(pRet);
  47006. }else{
  47007. int iDC = sqlite3OsDeviceCharacteristics(pRet->pWalFd);
  47008. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  47009. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  47010. pRet->padToSectorBoundary = 0;
  47011. }
  47012. *ppWal = pRet;
  47013. WALTRACE(("WAL%d: opened\n", pRet));
  47014. }
  47015. return rc;
  47016. }
  47017. /*
  47018. ** Change the size to which the WAL file is trucated on each reset.
  47019. */
  47020. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  47021. if( pWal ) pWal->mxWalSize = iLimit;
  47022. }
  47023. /*
  47024. ** Find the smallest page number out of all pages held in the WAL that
  47025. ** has not been returned by any prior invocation of this method on the
  47026. ** same WalIterator object. Write into *piFrame the frame index where
  47027. ** that page was last written into the WAL. Write into *piPage the page
  47028. ** number.
  47029. **
  47030. ** Return 0 on success. If there are no pages in the WAL with a page
  47031. ** number larger than *piPage, then return 1.
  47032. */
  47033. static int walIteratorNext(
  47034. WalIterator *p, /* Iterator */
  47035. u32 *piPage, /* OUT: The page number of the next page */
  47036. u32 *piFrame /* OUT: Wal frame index of next page */
  47037. ){
  47038. u32 iMin; /* Result pgno must be greater than iMin */
  47039. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  47040. int i; /* For looping through segments */
  47041. iMin = p->iPrior;
  47042. assert( iMin<0xffffffff );
  47043. for(i=p->nSegment-1; i>=0; i--){
  47044. struct WalSegment *pSegment = &p->aSegment[i];
  47045. while( pSegment->iNext<pSegment->nEntry ){
  47046. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  47047. if( iPg>iMin ){
  47048. if( iPg<iRet ){
  47049. iRet = iPg;
  47050. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  47051. }
  47052. break;
  47053. }
  47054. pSegment->iNext++;
  47055. }
  47056. }
  47057. *piPage = p->iPrior = iRet;
  47058. return (iRet==0xFFFFFFFF);
  47059. }
  47060. /*
  47061. ** This function merges two sorted lists into a single sorted list.
  47062. **
  47063. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  47064. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  47065. ** is guaranteed for all J<K:
  47066. **
  47067. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  47068. ** aContent[aRight[J]] < aContent[aRight[K]]
  47069. **
  47070. ** This routine overwrites aRight[] with a new (probably longer) sequence
  47071. ** of indices such that the aRight[] contains every index that appears in
  47072. ** either aLeft[] or the old aRight[] and such that the second condition
  47073. ** above is still met.
  47074. **
  47075. ** The aContent[aLeft[X]] values will be unique for all X. And the
  47076. ** aContent[aRight[X]] values will be unique too. But there might be
  47077. ** one or more combinations of X and Y such that
  47078. **
  47079. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  47080. **
  47081. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  47082. */
  47083. static void walMerge(
  47084. const u32 *aContent, /* Pages in wal - keys for the sort */
  47085. ht_slot *aLeft, /* IN: Left hand input list */
  47086. int nLeft, /* IN: Elements in array *paLeft */
  47087. ht_slot **paRight, /* IN/OUT: Right hand input list */
  47088. int *pnRight, /* IN/OUT: Elements in *paRight */
  47089. ht_slot *aTmp /* Temporary buffer */
  47090. ){
  47091. int iLeft = 0; /* Current index in aLeft */
  47092. int iRight = 0; /* Current index in aRight */
  47093. int iOut = 0; /* Current index in output buffer */
  47094. int nRight = *pnRight;
  47095. ht_slot *aRight = *paRight;
  47096. assert( nLeft>0 && nRight>0 );
  47097. while( iRight<nRight || iLeft<nLeft ){
  47098. ht_slot logpage;
  47099. Pgno dbpage;
  47100. if( (iLeft<nLeft)
  47101. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  47102. ){
  47103. logpage = aLeft[iLeft++];
  47104. }else{
  47105. logpage = aRight[iRight++];
  47106. }
  47107. dbpage = aContent[logpage];
  47108. aTmp[iOut++] = logpage;
  47109. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  47110. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  47111. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  47112. }
  47113. *paRight = aLeft;
  47114. *pnRight = iOut;
  47115. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  47116. }
  47117. /*
  47118. ** Sort the elements in list aList using aContent[] as the sort key.
  47119. ** Remove elements with duplicate keys, preferring to keep the
  47120. ** larger aList[] values.
  47121. **
  47122. ** The aList[] entries are indices into aContent[]. The values in
  47123. ** aList[] are to be sorted so that for all J<K:
  47124. **
  47125. ** aContent[aList[J]] < aContent[aList[K]]
  47126. **
  47127. ** For any X and Y such that
  47128. **
  47129. ** aContent[aList[X]] == aContent[aList[Y]]
  47130. **
  47131. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  47132. ** the smaller.
  47133. */
  47134. static void walMergesort(
  47135. const u32 *aContent, /* Pages in wal */
  47136. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  47137. ht_slot *aList, /* IN/OUT: List to sort */
  47138. int *pnList /* IN/OUT: Number of elements in aList[] */
  47139. ){
  47140. struct Sublist {
  47141. int nList; /* Number of elements in aList */
  47142. ht_slot *aList; /* Pointer to sub-list content */
  47143. };
  47144. const int nList = *pnList; /* Size of input list */
  47145. int nMerge = 0; /* Number of elements in list aMerge */
  47146. ht_slot *aMerge = 0; /* List to be merged */
  47147. int iList; /* Index into input list */
  47148. int iSub = 0; /* Index into aSub array */
  47149. struct Sublist aSub[13]; /* Array of sub-lists */
  47150. memset(aSub, 0, sizeof(aSub));
  47151. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  47152. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  47153. for(iList=0; iList<nList; iList++){
  47154. nMerge = 1;
  47155. aMerge = &aList[iList];
  47156. for(iSub=0; iList & (1<<iSub); iSub++){
  47157. struct Sublist *p = &aSub[iSub];
  47158. assert( p->aList && p->nList<=(1<<iSub) );
  47159. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  47160. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47161. }
  47162. aSub[iSub].aList = aMerge;
  47163. aSub[iSub].nList = nMerge;
  47164. }
  47165. for(iSub++; iSub<ArraySize(aSub); iSub++){
  47166. if( nList & (1<<iSub) ){
  47167. struct Sublist *p = &aSub[iSub];
  47168. assert( p->nList<=(1<<iSub) );
  47169. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  47170. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  47171. }
  47172. }
  47173. assert( aMerge==aList );
  47174. *pnList = nMerge;
  47175. #ifdef SQLITE_DEBUG
  47176. {
  47177. int i;
  47178. for(i=1; i<*pnList; i++){
  47179. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  47180. }
  47181. }
  47182. #endif
  47183. }
  47184. /*
  47185. ** Free an iterator allocated by walIteratorInit().
  47186. */
  47187. static void walIteratorFree(WalIterator *p){
  47188. sqlite3ScratchFree(p);
  47189. }
  47190. /*
  47191. ** Construct a WalInterator object that can be used to loop over all
  47192. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  47193. ** lock.
  47194. **
  47195. ** On success, make *pp point to the newly allocated WalInterator object
  47196. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  47197. ** returns an error, the value of *pp is undefined.
  47198. **
  47199. ** The calling routine should invoke walIteratorFree() to destroy the
  47200. ** WalIterator object when it has finished with it.
  47201. */
  47202. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  47203. WalIterator *p; /* Return value */
  47204. int nSegment; /* Number of segments to merge */
  47205. u32 iLast; /* Last frame in log */
  47206. int nByte; /* Number of bytes to allocate */
  47207. int i; /* Iterator variable */
  47208. ht_slot *aTmp; /* Temp space used by merge-sort */
  47209. int rc = SQLITE_OK; /* Return Code */
  47210. /* This routine only runs while holding the checkpoint lock. And
  47211. ** it only runs if there is actually content in the log (mxFrame>0).
  47212. */
  47213. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  47214. iLast = pWal->hdr.mxFrame;
  47215. /* Allocate space for the WalIterator object. */
  47216. nSegment = walFramePage(iLast) + 1;
  47217. nByte = sizeof(WalIterator)
  47218. + (nSegment-1)*sizeof(struct WalSegment)
  47219. + iLast*sizeof(ht_slot);
  47220. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  47221. if( !p ){
  47222. return SQLITE_NOMEM;
  47223. }
  47224. memset(p, 0, nByte);
  47225. p->nSegment = nSegment;
  47226. /* Allocate temporary space used by the merge-sort routine. This block
  47227. ** of memory will be freed before this function returns.
  47228. */
  47229. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  47230. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  47231. );
  47232. if( !aTmp ){
  47233. rc = SQLITE_NOMEM;
  47234. }
  47235. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  47236. volatile ht_slot *aHash;
  47237. u32 iZero;
  47238. volatile u32 *aPgno;
  47239. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  47240. if( rc==SQLITE_OK ){
  47241. int j; /* Counter variable */
  47242. int nEntry; /* Number of entries in this segment */
  47243. ht_slot *aIndex; /* Sorted index for this segment */
  47244. aPgno++;
  47245. if( (i+1)==nSegment ){
  47246. nEntry = (int)(iLast - iZero);
  47247. }else{
  47248. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  47249. }
  47250. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  47251. iZero++;
  47252. for(j=0; j<nEntry; j++){
  47253. aIndex[j] = (ht_slot)j;
  47254. }
  47255. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  47256. p->aSegment[i].iZero = iZero;
  47257. p->aSegment[i].nEntry = nEntry;
  47258. p->aSegment[i].aIndex = aIndex;
  47259. p->aSegment[i].aPgno = (u32 *)aPgno;
  47260. }
  47261. }
  47262. sqlite3ScratchFree(aTmp);
  47263. if( rc!=SQLITE_OK ){
  47264. walIteratorFree(p);
  47265. }
  47266. *pp = p;
  47267. return rc;
  47268. }
  47269. /*
  47270. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  47271. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  47272. ** busy-handler function. Invoke it and retry the lock until either the
  47273. ** lock is successfully obtained or the busy-handler returns 0.
  47274. */
  47275. static int walBusyLock(
  47276. Wal *pWal, /* WAL connection */
  47277. int (*xBusy)(void*), /* Function to call when busy */
  47278. void *pBusyArg, /* Context argument for xBusyHandler */
  47279. int lockIdx, /* Offset of first byte to lock */
  47280. int n /* Number of bytes to lock */
  47281. ){
  47282. int rc;
  47283. do {
  47284. rc = walLockExclusive(pWal, lockIdx, n);
  47285. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  47286. return rc;
  47287. }
  47288. /*
  47289. ** The cache of the wal-index header must be valid to call this function.
  47290. ** Return the page-size in bytes used by the database.
  47291. */
  47292. static int walPagesize(Wal *pWal){
  47293. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47294. }
  47295. /*
  47296. ** Copy as much content as we can from the WAL back into the database file
  47297. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  47298. **
  47299. ** The amount of information copies from WAL to database might be limited
  47300. ** by active readers. This routine will never overwrite a database page
  47301. ** that a concurrent reader might be using.
  47302. **
  47303. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  47304. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  47305. ** checkpoints are always run by a background thread or background
  47306. ** process, foreground threads will never block on a lengthy fsync call.
  47307. **
  47308. ** Fsync is called on the WAL before writing content out of the WAL and
  47309. ** into the database. This ensures that if the new content is persistent
  47310. ** in the WAL and can be recovered following a power-loss or hard reset.
  47311. **
  47312. ** Fsync is also called on the database file if (and only if) the entire
  47313. ** WAL content is copied into the database file. This second fsync makes
  47314. ** it safe to delete the WAL since the new content will persist in the
  47315. ** database file.
  47316. **
  47317. ** This routine uses and updates the nBackfill field of the wal-index header.
  47318. ** This is the only routine tha will increase the value of nBackfill.
  47319. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  47320. ** its value.)
  47321. **
  47322. ** The caller must be holding sufficient locks to ensure that no other
  47323. ** checkpoint is running (in any other thread or process) at the same
  47324. ** time.
  47325. */
  47326. static int walCheckpoint(
  47327. Wal *pWal, /* Wal connection */
  47328. int eMode, /* One of PASSIVE, FULL or RESTART */
  47329. int (*xBusyCall)(void*), /* Function to call when busy */
  47330. void *pBusyArg, /* Context argument for xBusyHandler */
  47331. int sync_flags, /* Flags for OsSync() (or 0) */
  47332. u8 *zBuf /* Temporary buffer to use */
  47333. ){
  47334. int rc; /* Return code */
  47335. int szPage; /* Database page-size */
  47336. WalIterator *pIter = 0; /* Wal iterator context */
  47337. u32 iDbpage = 0; /* Next database page to write */
  47338. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  47339. u32 mxSafeFrame; /* Max frame that can be backfilled */
  47340. u32 mxPage; /* Max database page to write */
  47341. int i; /* Loop counter */
  47342. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  47343. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  47344. szPage = walPagesize(pWal);
  47345. testcase( szPage<=32768 );
  47346. testcase( szPage>=65536 );
  47347. pInfo = walCkptInfo(pWal);
  47348. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  47349. /* Allocate the iterator */
  47350. rc = walIteratorInit(pWal, &pIter);
  47351. if( rc!=SQLITE_OK ){
  47352. return rc;
  47353. }
  47354. assert( pIter );
  47355. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  47356. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  47357. ** safe to write into the database. Frames beyond mxSafeFrame might
  47358. ** overwrite database pages that are in use by active readers and thus
  47359. ** cannot be backfilled from the WAL.
  47360. */
  47361. mxSafeFrame = pWal->hdr.mxFrame;
  47362. mxPage = pWal->hdr.nPage;
  47363. for(i=1; i<WAL_NREADER; i++){
  47364. u32 y = pInfo->aReadMark[i];
  47365. if( mxSafeFrame>y ){
  47366. assert( y<=pWal->hdr.mxFrame );
  47367. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  47368. if( rc==SQLITE_OK ){
  47369. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  47370. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47371. }else if( rc==SQLITE_BUSY ){
  47372. mxSafeFrame = y;
  47373. xBusy = 0;
  47374. }else{
  47375. goto walcheckpoint_out;
  47376. }
  47377. }
  47378. }
  47379. if( pInfo->nBackfill<mxSafeFrame
  47380. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  47381. ){
  47382. i64 nSize; /* Current size of database file */
  47383. u32 nBackfill = pInfo->nBackfill;
  47384. /* Sync the WAL to disk */
  47385. if( sync_flags ){
  47386. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  47387. }
  47388. /* If the database may grow as a result of this checkpoint, hint
  47389. ** about the eventual size of the db file to the VFS layer.
  47390. */
  47391. if( rc==SQLITE_OK ){
  47392. i64 nReq = ((i64)mxPage * szPage);
  47393. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  47394. if( rc==SQLITE_OK && nSize<nReq ){
  47395. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  47396. }
  47397. }
  47398. /* Iterate through the contents of the WAL, copying data to the db file. */
  47399. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  47400. i64 iOffset;
  47401. assert( walFramePgno(pWal, iFrame)==iDbpage );
  47402. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  47403. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  47404. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  47405. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  47406. if( rc!=SQLITE_OK ) break;
  47407. iOffset = (iDbpage-1)*(i64)szPage;
  47408. testcase( IS_BIG_INT(iOffset) );
  47409. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  47410. if( rc!=SQLITE_OK ) break;
  47411. }
  47412. /* If work was actually accomplished... */
  47413. if( rc==SQLITE_OK ){
  47414. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  47415. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  47416. testcase( IS_BIG_INT(szDb) );
  47417. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  47418. if( rc==SQLITE_OK && sync_flags ){
  47419. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  47420. }
  47421. }
  47422. if( rc==SQLITE_OK ){
  47423. pInfo->nBackfill = mxSafeFrame;
  47424. }
  47425. }
  47426. /* Release the reader lock held while backfilling */
  47427. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  47428. }
  47429. if( rc==SQLITE_BUSY ){
  47430. /* Reset the return code so as not to report a checkpoint failure
  47431. ** just because there are active readers. */
  47432. rc = SQLITE_OK;
  47433. }
  47434. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  47435. ** file has been copied into the database file, then block until all
  47436. ** readers have finished using the wal file. This ensures that the next
  47437. ** process to write to the database restarts the wal file.
  47438. */
  47439. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  47440. assert( pWal->writeLock );
  47441. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  47442. rc = SQLITE_BUSY;
  47443. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  47444. assert( mxSafeFrame==pWal->hdr.mxFrame );
  47445. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  47446. if( rc==SQLITE_OK ){
  47447. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47448. }
  47449. }
  47450. }
  47451. walcheckpoint_out:
  47452. walIteratorFree(pIter);
  47453. return rc;
  47454. }
  47455. /*
  47456. ** If the WAL file is currently larger than nMax bytes in size, truncate
  47457. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  47458. */
  47459. static void walLimitSize(Wal *pWal, i64 nMax){
  47460. i64 sz;
  47461. int rx;
  47462. sqlite3BeginBenignMalloc();
  47463. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  47464. if( rx==SQLITE_OK && (sz > nMax ) ){
  47465. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  47466. }
  47467. sqlite3EndBenignMalloc();
  47468. if( rx ){
  47469. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  47470. }
  47471. }
  47472. /*
  47473. ** Close a connection to a log file.
  47474. */
  47475. SQLITE_PRIVATE int sqlite3WalClose(
  47476. Wal *pWal, /* Wal to close */
  47477. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  47478. int nBuf,
  47479. u8 *zBuf /* Buffer of at least nBuf bytes */
  47480. ){
  47481. int rc = SQLITE_OK;
  47482. if( pWal ){
  47483. int isDelete = 0; /* True to unlink wal and wal-index files */
  47484. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  47485. ** ordinary, rollback-mode locking methods, this guarantees that the
  47486. ** connection associated with this log file is the only connection to
  47487. ** the database. In this case checkpoint the database and unlink both
  47488. ** the wal and wal-index files.
  47489. **
  47490. ** The EXCLUSIVE lock is not released before returning.
  47491. */
  47492. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  47493. if( rc==SQLITE_OK ){
  47494. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  47495. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  47496. }
  47497. rc = sqlite3WalCheckpoint(
  47498. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  47499. );
  47500. if( rc==SQLITE_OK ){
  47501. int bPersist = -1;
  47502. sqlite3OsFileControlHint(
  47503. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  47504. );
  47505. if( bPersist!=1 ){
  47506. /* Try to delete the WAL file if the checkpoint completed and
  47507. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  47508. ** mode (!bPersist) */
  47509. isDelete = 1;
  47510. }else if( pWal->mxWalSize>=0 ){
  47511. /* Try to truncate the WAL file to zero bytes if the checkpoint
  47512. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  47513. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  47514. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  47515. ** to zero bytes as truncating to the journal_size_limit might
  47516. ** leave a corrupt WAL file on disk. */
  47517. walLimitSize(pWal, 0);
  47518. }
  47519. }
  47520. }
  47521. walIndexClose(pWal, isDelete);
  47522. sqlite3OsClose(pWal->pWalFd);
  47523. if( isDelete ){
  47524. sqlite3BeginBenignMalloc();
  47525. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  47526. sqlite3EndBenignMalloc();
  47527. }
  47528. WALTRACE(("WAL%p: closed\n", pWal));
  47529. sqlite3_free((void *)pWal->apWiData);
  47530. sqlite3_free(pWal);
  47531. }
  47532. return rc;
  47533. }
  47534. /*
  47535. ** Try to read the wal-index header. Return 0 on success and 1 if
  47536. ** there is a problem.
  47537. **
  47538. ** The wal-index is in shared memory. Another thread or process might
  47539. ** be writing the header at the same time this procedure is trying to
  47540. ** read it, which might result in inconsistency. A dirty read is detected
  47541. ** by verifying that both copies of the header are the same and also by
  47542. ** a checksum on the header.
  47543. **
  47544. ** If and only if the read is consistent and the header is different from
  47545. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  47546. ** and *pChanged is set to 1.
  47547. **
  47548. ** If the checksum cannot be verified return non-zero. If the header
  47549. ** is read successfully and the checksum verified, return zero.
  47550. */
  47551. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  47552. u32 aCksum[2]; /* Checksum on the header content */
  47553. WalIndexHdr h1, h2; /* Two copies of the header content */
  47554. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  47555. /* The first page of the wal-index must be mapped at this point. */
  47556. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  47557. /* Read the header. This might happen concurrently with a write to the
  47558. ** same area of shared memory on a different CPU in a SMP,
  47559. ** meaning it is possible that an inconsistent snapshot is read
  47560. ** from the file. If this happens, return non-zero.
  47561. **
  47562. ** There are two copies of the header at the beginning of the wal-index.
  47563. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  47564. ** Memory barriers are used to prevent the compiler or the hardware from
  47565. ** reordering the reads and writes.
  47566. */
  47567. aHdr = walIndexHdr(pWal);
  47568. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  47569. walShmBarrier(pWal);
  47570. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  47571. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  47572. return 1; /* Dirty read */
  47573. }
  47574. if( h1.isInit==0 ){
  47575. return 1; /* Malformed header - probably all zeros */
  47576. }
  47577. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  47578. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  47579. return 1; /* Checksum does not match */
  47580. }
  47581. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  47582. *pChanged = 1;
  47583. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  47584. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  47585. testcase( pWal->szPage<=32768 );
  47586. testcase( pWal->szPage>=65536 );
  47587. }
  47588. /* The header was successfully read. Return zero. */
  47589. return 0;
  47590. }
  47591. /*
  47592. ** Read the wal-index header from the wal-index and into pWal->hdr.
  47593. ** If the wal-header appears to be corrupt, try to reconstruct the
  47594. ** wal-index from the WAL before returning.
  47595. **
  47596. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  47597. ** changed by this opertion. If pWal->hdr is unchanged, set *pChanged
  47598. ** to 0.
  47599. **
  47600. ** If the wal-index header is successfully read, return SQLITE_OK.
  47601. ** Otherwise an SQLite error code.
  47602. */
  47603. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  47604. int rc; /* Return code */
  47605. int badHdr; /* True if a header read failed */
  47606. volatile u32 *page0; /* Chunk of wal-index containing header */
  47607. /* Ensure that page 0 of the wal-index (the page that contains the
  47608. ** wal-index header) is mapped. Return early if an error occurs here.
  47609. */
  47610. assert( pChanged );
  47611. rc = walIndexPage(pWal, 0, &page0);
  47612. if( rc!=SQLITE_OK ){
  47613. return rc;
  47614. };
  47615. assert( page0 || pWal->writeLock==0 );
  47616. /* If the first page of the wal-index has been mapped, try to read the
  47617. ** wal-index header immediately, without holding any lock. This usually
  47618. ** works, but may fail if the wal-index header is corrupt or currently
  47619. ** being modified by another thread or process.
  47620. */
  47621. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  47622. /* If the first attempt failed, it might have been due to a race
  47623. ** with a writer. So get a WRITE lock and try again.
  47624. */
  47625. assert( badHdr==0 || pWal->writeLock==0 );
  47626. if( badHdr ){
  47627. if( pWal->readOnly & WAL_SHM_RDONLY ){
  47628. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  47629. walUnlockShared(pWal, WAL_WRITE_LOCK);
  47630. rc = SQLITE_READONLY_RECOVERY;
  47631. }
  47632. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  47633. pWal->writeLock = 1;
  47634. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  47635. badHdr = walIndexTryHdr(pWal, pChanged);
  47636. if( badHdr ){
  47637. /* If the wal-index header is still malformed even while holding
  47638. ** a WRITE lock, it can only mean that the header is corrupted and
  47639. ** needs to be reconstructed. So run recovery to do exactly that.
  47640. */
  47641. rc = walIndexRecover(pWal);
  47642. *pChanged = 1;
  47643. }
  47644. }
  47645. pWal->writeLock = 0;
  47646. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47647. }
  47648. }
  47649. /* If the header is read successfully, check the version number to make
  47650. ** sure the wal-index was not constructed with some future format that
  47651. ** this version of SQLite cannot understand.
  47652. */
  47653. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  47654. rc = SQLITE_CANTOPEN_BKPT;
  47655. }
  47656. return rc;
  47657. }
  47658. /*
  47659. ** This is the value that walTryBeginRead returns when it needs to
  47660. ** be retried.
  47661. */
  47662. #define WAL_RETRY (-1)
  47663. /*
  47664. ** Attempt to start a read transaction. This might fail due to a race or
  47665. ** other transient condition. When that happens, it returns WAL_RETRY to
  47666. ** indicate to the caller that it is safe to retry immediately.
  47667. **
  47668. ** On success return SQLITE_OK. On a permanent failure (such an
  47669. ** I/O error or an SQLITE_BUSY because another process is running
  47670. ** recovery) return a positive error code.
  47671. **
  47672. ** The useWal parameter is true to force the use of the WAL and disable
  47673. ** the case where the WAL is bypassed because it has been completely
  47674. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  47675. ** to make a copy of the wal-index header into pWal->hdr. If the
  47676. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  47677. ** to the caller that the local paget cache is obsolete and needs to be
  47678. ** flushed.) When useWal==1, the wal-index header is assumed to already
  47679. ** be loaded and the pChanged parameter is unused.
  47680. **
  47681. ** The caller must set the cnt parameter to the number of prior calls to
  47682. ** this routine during the current read attempt that returned WAL_RETRY.
  47683. ** This routine will start taking more aggressive measures to clear the
  47684. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  47685. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  47686. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  47687. ** and is not honoring the locking protocol. There is a vanishingly small
  47688. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  47689. ** bad luck when there is lots of contention for the wal-index, but that
  47690. ** possibility is so small that it can be safely neglected, we believe.
  47691. **
  47692. ** On success, this routine obtains a read lock on
  47693. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  47694. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  47695. ** that means the Wal does not hold any read lock. The reader must not
  47696. ** access any database page that is modified by a WAL frame up to and
  47697. ** including frame number aReadMark[pWal->readLock]. The reader will
  47698. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  47699. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  47700. ** completely and get all content directly from the database file.
  47701. ** If the useWal parameter is 1 then the WAL will never be ignored and
  47702. ** this routine will always set pWal->readLock>0 on success.
  47703. ** When the read transaction is completed, the caller must release the
  47704. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  47705. **
  47706. ** This routine uses the nBackfill and aReadMark[] fields of the header
  47707. ** to select a particular WAL_READ_LOCK() that strives to let the
  47708. ** checkpoint process do as much work as possible. This routine might
  47709. ** update values of the aReadMark[] array in the header, but if it does
  47710. ** so it takes care to hold an exclusive lock on the corresponding
  47711. ** WAL_READ_LOCK() while changing values.
  47712. */
  47713. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  47714. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  47715. u32 mxReadMark; /* Largest aReadMark[] value */
  47716. int mxI; /* Index of largest aReadMark[] value */
  47717. int i; /* Loop counter */
  47718. int rc = SQLITE_OK; /* Return code */
  47719. assert( pWal->readLock<0 ); /* Not currently locked */
  47720. /* Take steps to avoid spinning forever if there is a protocol error.
  47721. **
  47722. ** Circumstances that cause a RETRY should only last for the briefest
  47723. ** instances of time. No I/O or other system calls are done while the
  47724. ** locks are held, so the locks should not be held for very long. But
  47725. ** if we are unlucky, another process that is holding a lock might get
  47726. ** paged out or take a page-fault that is time-consuming to resolve,
  47727. ** during the few nanoseconds that it is holding the lock. In that case,
  47728. ** it might take longer than normal for the lock to free.
  47729. **
  47730. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  47731. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  47732. ** is more of a scheduler yield than an actual delay. But on the 10th
  47733. ** an subsequent retries, the delays start becoming longer and longer,
  47734. ** so that on the 100th (and last) RETRY we delay for 21 milliseconds.
  47735. ** The total delay time before giving up is less than 1 second.
  47736. */
  47737. if( cnt>5 ){
  47738. int nDelay = 1; /* Pause time in microseconds */
  47739. if( cnt>100 ){
  47740. VVA_ONLY( pWal->lockError = 1; )
  47741. return SQLITE_PROTOCOL;
  47742. }
  47743. if( cnt>=10 ) nDelay = (cnt-9)*238; /* Max delay 21ms. Total delay 996ms */
  47744. sqlite3OsSleep(pWal->pVfs, nDelay);
  47745. }
  47746. if( !useWal ){
  47747. rc = walIndexReadHdr(pWal, pChanged);
  47748. if( rc==SQLITE_BUSY ){
  47749. /* If there is not a recovery running in another thread or process
  47750. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  47751. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  47752. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  47753. ** would be technically correct. But the race is benign since with
  47754. ** WAL_RETRY this routine will be called again and will probably be
  47755. ** right on the second iteration.
  47756. */
  47757. if( pWal->apWiData[0]==0 ){
  47758. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  47759. ** We assume this is a transient condition, so return WAL_RETRY. The
  47760. ** xShmMap() implementation used by the default unix and win32 VFS
  47761. ** modules may return SQLITE_BUSY due to a race condition in the
  47762. ** code that determines whether or not the shared-memory region
  47763. ** must be zeroed before the requested page is returned.
  47764. */
  47765. rc = WAL_RETRY;
  47766. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  47767. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  47768. rc = WAL_RETRY;
  47769. }else if( rc==SQLITE_BUSY ){
  47770. rc = SQLITE_BUSY_RECOVERY;
  47771. }
  47772. }
  47773. if( rc!=SQLITE_OK ){
  47774. return rc;
  47775. }
  47776. }
  47777. pInfo = walCkptInfo(pWal);
  47778. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  47779. /* The WAL has been completely backfilled (or it is empty).
  47780. ** and can be safely ignored.
  47781. */
  47782. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  47783. walShmBarrier(pWal);
  47784. if( rc==SQLITE_OK ){
  47785. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  47786. /* It is not safe to allow the reader to continue here if frames
  47787. ** may have been appended to the log before READ_LOCK(0) was obtained.
  47788. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  47789. ** which implies that the database file contains a trustworthy
  47790. ** snapshoT. Since holding READ_LOCK(0) prevents a checkpoint from
  47791. ** happening, this is usually correct.
  47792. **
  47793. ** However, if frames have been appended to the log (or if the log
  47794. ** is wrapped and written for that matter) before the READ_LOCK(0)
  47795. ** is obtained, that is not necessarily true. A checkpointer may
  47796. ** have started to backfill the appended frames but crashed before
  47797. ** it finished. Leaving a corrupt image in the database file.
  47798. */
  47799. walUnlockShared(pWal, WAL_READ_LOCK(0));
  47800. return WAL_RETRY;
  47801. }
  47802. pWal->readLock = 0;
  47803. return SQLITE_OK;
  47804. }else if( rc!=SQLITE_BUSY ){
  47805. return rc;
  47806. }
  47807. }
  47808. /* If we get this far, it means that the reader will want to use
  47809. ** the WAL to get at content from recent commits. The job now is
  47810. ** to select one of the aReadMark[] entries that is closest to
  47811. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  47812. */
  47813. mxReadMark = 0;
  47814. mxI = 0;
  47815. for(i=1; i<WAL_NREADER; i++){
  47816. u32 thisMark = pInfo->aReadMark[i];
  47817. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  47818. assert( thisMark!=READMARK_NOT_USED );
  47819. mxReadMark = thisMark;
  47820. mxI = i;
  47821. }
  47822. }
  47823. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  47824. {
  47825. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  47826. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  47827. ){
  47828. for(i=1; i<WAL_NREADER; i++){
  47829. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47830. if( rc==SQLITE_OK ){
  47831. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  47832. mxI = i;
  47833. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  47834. break;
  47835. }else if( rc!=SQLITE_BUSY ){
  47836. return rc;
  47837. }
  47838. }
  47839. }
  47840. if( mxI==0 ){
  47841. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  47842. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  47843. }
  47844. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  47845. if( rc ){
  47846. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  47847. }
  47848. /* Now that the read-lock has been obtained, check that neither the
  47849. ** value in the aReadMark[] array or the contents of the wal-index
  47850. ** header have changed.
  47851. **
  47852. ** It is necessary to check that the wal-index header did not change
  47853. ** between the time it was read and when the shared-lock was obtained
  47854. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  47855. ** that the log file may have been wrapped by a writer, or that frames
  47856. ** that occur later in the log than pWal->hdr.mxFrame may have been
  47857. ** copied into the database by a checkpointer. If either of these things
  47858. ** happened, then reading the database with the current value of
  47859. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  47860. ** instead.
  47861. **
  47862. ** This does not guarantee that the copy of the wal-index header is up to
  47863. ** date before proceeding. That would not be possible without somehow
  47864. ** blocking writers. It only guarantees that a dangerous checkpoint or
  47865. ** log-wrap (either of which would require an exclusive lock on
  47866. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  47867. */
  47868. walShmBarrier(pWal);
  47869. if( pInfo->aReadMark[mxI]!=mxReadMark
  47870. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  47871. ){
  47872. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  47873. return WAL_RETRY;
  47874. }else{
  47875. assert( mxReadMark<=pWal->hdr.mxFrame );
  47876. pWal->readLock = (i16)mxI;
  47877. }
  47878. }
  47879. return rc;
  47880. }
  47881. /*
  47882. ** Begin a read transaction on the database.
  47883. **
  47884. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  47885. ** it takes a snapshot of the state of the WAL and wal-index for the current
  47886. ** instant in time. The current thread will continue to use this snapshot.
  47887. ** Other threads might append new content to the WAL and wal-index but
  47888. ** that extra content is ignored by the current thread.
  47889. **
  47890. ** If the database contents have changes since the previous read
  47891. ** transaction, then *pChanged is set to 1 before returning. The
  47892. ** Pager layer will use this to know that is cache is stale and
  47893. ** needs to be flushed.
  47894. */
  47895. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  47896. int rc; /* Return code */
  47897. int cnt = 0; /* Number of TryBeginRead attempts */
  47898. do{
  47899. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  47900. }while( rc==WAL_RETRY );
  47901. testcase( (rc&0xff)==SQLITE_BUSY );
  47902. testcase( (rc&0xff)==SQLITE_IOERR );
  47903. testcase( rc==SQLITE_PROTOCOL );
  47904. testcase( rc==SQLITE_OK );
  47905. return rc;
  47906. }
  47907. /*
  47908. ** Finish with a read transaction. All this does is release the
  47909. ** read-lock.
  47910. */
  47911. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  47912. sqlite3WalEndWriteTransaction(pWal);
  47913. if( pWal->readLock>=0 ){
  47914. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47915. pWal->readLock = -1;
  47916. }
  47917. }
  47918. /*
  47919. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  47920. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  47921. ** to zero.
  47922. **
  47923. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  47924. ** error does occur, the final value of *piRead is undefined.
  47925. */
  47926. SQLITE_PRIVATE int sqlite3WalFindFrame(
  47927. Wal *pWal, /* WAL handle */
  47928. Pgno pgno, /* Database page number to read data for */
  47929. u32 *piRead /* OUT: Frame number (or zero) */
  47930. ){
  47931. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  47932. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  47933. int iHash; /* Used to loop through N hash tables */
  47934. /* This routine is only be called from within a read transaction. */
  47935. assert( pWal->readLock>=0 || pWal->lockError );
  47936. /* If the "last page" field of the wal-index header snapshot is 0, then
  47937. ** no data will be read from the wal under any circumstances. Return early
  47938. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  47939. ** then the WAL is ignored by the reader so return early, as if the
  47940. ** WAL were empty.
  47941. */
  47942. if( iLast==0 || pWal->readLock==0 ){
  47943. *piRead = 0;
  47944. return SQLITE_OK;
  47945. }
  47946. /* Search the hash table or tables for an entry matching page number
  47947. ** pgno. Each iteration of the following for() loop searches one
  47948. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  47949. **
  47950. ** This code might run concurrently to the code in walIndexAppend()
  47951. ** that adds entries to the wal-index (and possibly to this hash
  47952. ** table). This means the value just read from the hash
  47953. ** slot (aHash[iKey]) may have been added before or after the
  47954. ** current read transaction was opened. Values added after the
  47955. ** read transaction was opened may have been written incorrectly -
  47956. ** i.e. these slots may contain garbage data. However, we assume
  47957. ** that any slots written before the current read transaction was
  47958. ** opened remain unmodified.
  47959. **
  47960. ** For the reasons above, the if(...) condition featured in the inner
  47961. ** loop of the following block is more stringent that would be required
  47962. ** if we had exclusive access to the hash-table:
  47963. **
  47964. ** (aPgno[iFrame]==pgno):
  47965. ** This condition filters out normal hash-table collisions.
  47966. **
  47967. ** (iFrame<=iLast):
  47968. ** This condition filters out entries that were added to the hash
  47969. ** table after the current read-transaction had started.
  47970. */
  47971. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  47972. volatile ht_slot *aHash; /* Pointer to hash table */
  47973. volatile u32 *aPgno; /* Pointer to array of page numbers */
  47974. u32 iZero; /* Frame number corresponding to aPgno[0] */
  47975. int iKey; /* Hash slot index */
  47976. int nCollide; /* Number of hash collisions remaining */
  47977. int rc; /* Error code */
  47978. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  47979. if( rc!=SQLITE_OK ){
  47980. return rc;
  47981. }
  47982. nCollide = HASHTABLE_NSLOT;
  47983. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  47984. u32 iFrame = aHash[iKey] + iZero;
  47985. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  47986. /* assert( iFrame>iRead ); -- not true if there is corruption */
  47987. iRead = iFrame;
  47988. }
  47989. if( (nCollide--)==0 ){
  47990. return SQLITE_CORRUPT_BKPT;
  47991. }
  47992. }
  47993. }
  47994. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47995. /* If expensive assert() statements are available, do a linear search
  47996. ** of the wal-index file content. Make sure the results agree with the
  47997. ** result obtained using the hash indexes above. */
  47998. {
  47999. u32 iRead2 = 0;
  48000. u32 iTest;
  48001. for(iTest=iLast; iTest>0; iTest--){
  48002. if( walFramePgno(pWal, iTest)==pgno ){
  48003. iRead2 = iTest;
  48004. break;
  48005. }
  48006. }
  48007. assert( iRead==iRead2 );
  48008. }
  48009. #endif
  48010. *piRead = iRead;
  48011. return SQLITE_OK;
  48012. }
  48013. /*
  48014. ** Read the contents of frame iRead from the wal file into buffer pOut
  48015. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  48016. ** error code otherwise.
  48017. */
  48018. SQLITE_PRIVATE int sqlite3WalReadFrame(
  48019. Wal *pWal, /* WAL handle */
  48020. u32 iRead, /* Frame to read */
  48021. int nOut, /* Size of buffer pOut in bytes */
  48022. u8 *pOut /* Buffer to write page data to */
  48023. ){
  48024. int sz;
  48025. i64 iOffset;
  48026. sz = pWal->hdr.szPage;
  48027. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  48028. testcase( sz<=32768 );
  48029. testcase( sz>=65536 );
  48030. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  48031. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  48032. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  48033. }
  48034. /*
  48035. ** Return the size of the database in pages (or zero, if unknown).
  48036. */
  48037. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  48038. if( pWal && ALWAYS(pWal->readLock>=0) ){
  48039. return pWal->hdr.nPage;
  48040. }
  48041. return 0;
  48042. }
  48043. /*
  48044. ** This function starts a write transaction on the WAL.
  48045. **
  48046. ** A read transaction must have already been started by a prior call
  48047. ** to sqlite3WalBeginReadTransaction().
  48048. **
  48049. ** If another thread or process has written into the database since
  48050. ** the read transaction was started, then it is not possible for this
  48051. ** thread to write as doing so would cause a fork. So this routine
  48052. ** returns SQLITE_BUSY in that case and no write transaction is started.
  48053. **
  48054. ** There can only be a single writer active at a time.
  48055. */
  48056. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  48057. int rc;
  48058. /* Cannot start a write transaction without first holding a read
  48059. ** transaction. */
  48060. assert( pWal->readLock>=0 );
  48061. if( pWal->readOnly ){
  48062. return SQLITE_READONLY;
  48063. }
  48064. /* Only one writer allowed at a time. Get the write lock. Return
  48065. ** SQLITE_BUSY if unable.
  48066. */
  48067. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48068. if( rc ){
  48069. return rc;
  48070. }
  48071. pWal->writeLock = 1;
  48072. /* If another connection has written to the database file since the
  48073. ** time the read transaction on this connection was started, then
  48074. ** the write is disallowed.
  48075. */
  48076. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  48077. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48078. pWal->writeLock = 0;
  48079. rc = SQLITE_BUSY_SNAPSHOT;
  48080. }
  48081. return rc;
  48082. }
  48083. /*
  48084. ** End a write transaction. The commit has already been done. This
  48085. ** routine merely releases the lock.
  48086. */
  48087. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  48088. if( pWal->writeLock ){
  48089. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  48090. pWal->writeLock = 0;
  48091. pWal->truncateOnCommit = 0;
  48092. }
  48093. return SQLITE_OK;
  48094. }
  48095. /*
  48096. ** If any data has been written (but not committed) to the log file, this
  48097. ** function moves the write-pointer back to the start of the transaction.
  48098. **
  48099. ** Additionally, the callback function is invoked for each frame written
  48100. ** to the WAL since the start of the transaction. If the callback returns
  48101. ** other than SQLITE_OK, it is not invoked again and the error code is
  48102. ** returned to the caller.
  48103. **
  48104. ** Otherwise, if the callback function does not return an error, this
  48105. ** function returns SQLITE_OK.
  48106. */
  48107. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  48108. int rc = SQLITE_OK;
  48109. if( ALWAYS(pWal->writeLock) ){
  48110. Pgno iMax = pWal->hdr.mxFrame;
  48111. Pgno iFrame;
  48112. /* Restore the clients cache of the wal-index header to the state it
  48113. ** was in before the client began writing to the database.
  48114. */
  48115. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  48116. for(iFrame=pWal->hdr.mxFrame+1;
  48117. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  48118. iFrame++
  48119. ){
  48120. /* This call cannot fail. Unless the page for which the page number
  48121. ** is passed as the second argument is (a) in the cache and
  48122. ** (b) has an outstanding reference, then xUndo is either a no-op
  48123. ** (if (a) is false) or simply expels the page from the cache (if (b)
  48124. ** is false).
  48125. **
  48126. ** If the upper layer is doing a rollback, it is guaranteed that there
  48127. ** are no outstanding references to any page other than page 1. And
  48128. ** page 1 is never written to the log until the transaction is
  48129. ** committed. As a result, the call to xUndo may not fail.
  48130. */
  48131. assert( walFramePgno(pWal, iFrame)!=1 );
  48132. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  48133. }
  48134. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  48135. }
  48136. assert( rc==SQLITE_OK );
  48137. return rc;
  48138. }
  48139. /*
  48140. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  48141. ** values. This function populates the array with values required to
  48142. ** "rollback" the write position of the WAL handle back to the current
  48143. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  48144. */
  48145. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  48146. assert( pWal->writeLock );
  48147. aWalData[0] = pWal->hdr.mxFrame;
  48148. aWalData[1] = pWal->hdr.aFrameCksum[0];
  48149. aWalData[2] = pWal->hdr.aFrameCksum[1];
  48150. aWalData[3] = pWal->nCkpt;
  48151. }
  48152. /*
  48153. ** Move the write position of the WAL back to the point identified by
  48154. ** the values in the aWalData[] array. aWalData must point to an array
  48155. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  48156. ** by a call to WalSavepoint().
  48157. */
  48158. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  48159. int rc = SQLITE_OK;
  48160. assert( pWal->writeLock );
  48161. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  48162. if( aWalData[3]!=pWal->nCkpt ){
  48163. /* This savepoint was opened immediately after the write-transaction
  48164. ** was started. Right after that, the writer decided to wrap around
  48165. ** to the start of the log. Update the savepoint values to match.
  48166. */
  48167. aWalData[0] = 0;
  48168. aWalData[3] = pWal->nCkpt;
  48169. }
  48170. if( aWalData[0]<pWal->hdr.mxFrame ){
  48171. pWal->hdr.mxFrame = aWalData[0];
  48172. pWal->hdr.aFrameCksum[0] = aWalData[1];
  48173. pWal->hdr.aFrameCksum[1] = aWalData[2];
  48174. walCleanupHash(pWal);
  48175. }
  48176. return rc;
  48177. }
  48178. /*
  48179. ** This function is called just before writing a set of frames to the log
  48180. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  48181. ** to the current log file, it is possible to overwrite the start of the
  48182. ** existing log file with the new frames (i.e. "reset" the log). If so,
  48183. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  48184. ** unchanged.
  48185. **
  48186. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  48187. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  48188. ** if an error occurs.
  48189. */
  48190. static int walRestartLog(Wal *pWal){
  48191. int rc = SQLITE_OK;
  48192. int cnt;
  48193. if( pWal->readLock==0 ){
  48194. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  48195. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  48196. if( pInfo->nBackfill>0 ){
  48197. u32 salt1;
  48198. sqlite3_randomness(4, &salt1);
  48199. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48200. if( rc==SQLITE_OK ){
  48201. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  48202. ** readers are currently using the WAL), then the transactions
  48203. ** frames will overwrite the start of the existing log. Update the
  48204. ** wal-index header to reflect this.
  48205. **
  48206. ** In theory it would be Ok to update the cache of the header only
  48207. ** at this point. But updating the actual wal-index header is also
  48208. ** safe and means there is no special case for sqlite3WalUndo()
  48209. ** to handle if this transaction is rolled back.
  48210. */
  48211. int i; /* Loop counter */
  48212. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  48213. pWal->nCkpt++;
  48214. pWal->hdr.mxFrame = 0;
  48215. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  48216. aSalt[1] = salt1;
  48217. walIndexWriteHdr(pWal);
  48218. pInfo->nBackfill = 0;
  48219. pInfo->aReadMark[1] = 0;
  48220. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  48221. assert( pInfo->aReadMark[0]==0 );
  48222. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  48223. }else if( rc!=SQLITE_BUSY ){
  48224. return rc;
  48225. }
  48226. }
  48227. walUnlockShared(pWal, WAL_READ_LOCK(0));
  48228. pWal->readLock = -1;
  48229. cnt = 0;
  48230. do{
  48231. int notUsed;
  48232. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  48233. }while( rc==WAL_RETRY );
  48234. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  48235. testcase( (rc&0xff)==SQLITE_IOERR );
  48236. testcase( rc==SQLITE_PROTOCOL );
  48237. testcase( rc==SQLITE_OK );
  48238. }
  48239. return rc;
  48240. }
  48241. /*
  48242. ** Information about the current state of the WAL file and where
  48243. ** the next fsync should occur - passed from sqlite3WalFrames() into
  48244. ** walWriteToLog().
  48245. */
  48246. typedef struct WalWriter {
  48247. Wal *pWal; /* The complete WAL information */
  48248. sqlite3_file *pFd; /* The WAL file to which we write */
  48249. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  48250. int syncFlags; /* Flags for the fsync */
  48251. int szPage; /* Size of one page */
  48252. } WalWriter;
  48253. /*
  48254. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  48255. ** Do a sync when crossing the p->iSyncPoint boundary.
  48256. **
  48257. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  48258. ** first write the part before iSyncPoint, then sync, then write the
  48259. ** rest.
  48260. */
  48261. static int walWriteToLog(
  48262. WalWriter *p, /* WAL to write to */
  48263. void *pContent, /* Content to be written */
  48264. int iAmt, /* Number of bytes to write */
  48265. sqlite3_int64 iOffset /* Start writing at this offset */
  48266. ){
  48267. int rc;
  48268. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  48269. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  48270. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  48271. if( rc ) return rc;
  48272. iOffset += iFirstAmt;
  48273. iAmt -= iFirstAmt;
  48274. pContent = (void*)(iFirstAmt + (char*)pContent);
  48275. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  48276. rc = sqlite3OsSync(p->pFd, p->syncFlags);
  48277. if( iAmt==0 || rc ) return rc;
  48278. }
  48279. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  48280. return rc;
  48281. }
  48282. /*
  48283. ** Write out a single frame of the WAL
  48284. */
  48285. static int walWriteOneFrame(
  48286. WalWriter *p, /* Where to write the frame */
  48287. PgHdr *pPage, /* The page of the frame to be written */
  48288. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  48289. sqlite3_int64 iOffset /* Byte offset at which to write */
  48290. ){
  48291. int rc; /* Result code from subfunctions */
  48292. void *pData; /* Data actually written */
  48293. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  48294. #if defined(SQLITE_HAS_CODEC)
  48295. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  48296. #else
  48297. pData = pPage->pData;
  48298. #endif
  48299. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  48300. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  48301. if( rc ) return rc;
  48302. /* Write the page data */
  48303. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  48304. return rc;
  48305. }
  48306. /*
  48307. ** Write a set of frames to the log. The caller must hold the write-lock
  48308. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  48309. */
  48310. SQLITE_PRIVATE int sqlite3WalFrames(
  48311. Wal *pWal, /* Wal handle to write to */
  48312. int szPage, /* Database page-size in bytes */
  48313. PgHdr *pList, /* List of dirty pages to write */
  48314. Pgno nTruncate, /* Database size after this commit */
  48315. int isCommit, /* True if this is a commit */
  48316. int sync_flags /* Flags to pass to OsSync() (or 0) */
  48317. ){
  48318. int rc; /* Used to catch return codes */
  48319. u32 iFrame; /* Next frame address */
  48320. PgHdr *p; /* Iterator to run through pList with. */
  48321. PgHdr *pLast = 0; /* Last frame in list */
  48322. int nExtra = 0; /* Number of extra copies of last page */
  48323. int szFrame; /* The size of a single frame */
  48324. i64 iOffset; /* Next byte to write in WAL file */
  48325. WalWriter w; /* The writer */
  48326. assert( pList );
  48327. assert( pWal->writeLock );
  48328. /* If this frame set completes a transaction, then nTruncate>0. If
  48329. ** nTruncate==0 then this frame set does not complete the transaction. */
  48330. assert( (isCommit!=0)==(nTruncate!=0) );
  48331. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  48332. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  48333. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  48334. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  48335. }
  48336. #endif
  48337. /* See if it is possible to write these frames into the start of the
  48338. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  48339. */
  48340. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  48341. return rc;
  48342. }
  48343. /* If this is the first frame written into the log, write the WAL
  48344. ** header to the start of the WAL file. See comments at the top of
  48345. ** this source file for a description of the WAL header format.
  48346. */
  48347. iFrame = pWal->hdr.mxFrame;
  48348. if( iFrame==0 ){
  48349. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  48350. u32 aCksum[2]; /* Checksum for wal-header */
  48351. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  48352. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  48353. sqlite3Put4byte(&aWalHdr[8], szPage);
  48354. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  48355. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  48356. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  48357. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  48358. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  48359. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  48360. pWal->szPage = szPage;
  48361. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  48362. pWal->hdr.aFrameCksum[0] = aCksum[0];
  48363. pWal->hdr.aFrameCksum[1] = aCksum[1];
  48364. pWal->truncateOnCommit = 1;
  48365. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  48366. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  48367. if( rc!=SQLITE_OK ){
  48368. return rc;
  48369. }
  48370. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  48371. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  48372. ** an out-of-order write following a WAL restart could result in
  48373. ** database corruption. See the ticket:
  48374. **
  48375. ** http://localhost:591/sqlite/info/ff5be73dee
  48376. */
  48377. if( pWal->syncHeader && sync_flags ){
  48378. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  48379. if( rc ) return rc;
  48380. }
  48381. }
  48382. assert( (int)pWal->szPage==szPage );
  48383. /* Setup information needed to write frames into the WAL */
  48384. w.pWal = pWal;
  48385. w.pFd = pWal->pWalFd;
  48386. w.iSyncPoint = 0;
  48387. w.syncFlags = sync_flags;
  48388. w.szPage = szPage;
  48389. iOffset = walFrameOffset(iFrame+1, szPage);
  48390. szFrame = szPage + WAL_FRAME_HDRSIZE;
  48391. /* Write all frames into the log file exactly once */
  48392. for(p=pList; p; p=p->pDirty){
  48393. int nDbSize; /* 0 normally. Positive == commit flag */
  48394. iFrame++;
  48395. assert( iOffset==walFrameOffset(iFrame, szPage) );
  48396. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  48397. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  48398. if( rc ) return rc;
  48399. pLast = p;
  48400. iOffset += szFrame;
  48401. }
  48402. /* If this is the end of a transaction, then we might need to pad
  48403. ** the transaction and/or sync the WAL file.
  48404. **
  48405. ** Padding and syncing only occur if this set of frames complete a
  48406. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  48407. ** or synchonous==OFF, then no padding or syncing are needed.
  48408. **
  48409. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  48410. ** needed and only the sync is done. If padding is needed, then the
  48411. ** final frame is repeated (with its commit mark) until the next sector
  48412. ** boundary is crossed. Only the part of the WAL prior to the last
  48413. ** sector boundary is synced; the part of the last frame that extends
  48414. ** past the sector boundary is written after the sync.
  48415. */
  48416. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  48417. if( pWal->padToSectorBoundary ){
  48418. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  48419. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  48420. while( iOffset<w.iSyncPoint ){
  48421. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  48422. if( rc ) return rc;
  48423. iOffset += szFrame;
  48424. nExtra++;
  48425. }
  48426. }else{
  48427. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  48428. }
  48429. }
  48430. /* If this frame set completes the first transaction in the WAL and
  48431. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  48432. ** journal size limit, if possible.
  48433. */
  48434. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  48435. i64 sz = pWal->mxWalSize;
  48436. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  48437. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  48438. }
  48439. walLimitSize(pWal, sz);
  48440. pWal->truncateOnCommit = 0;
  48441. }
  48442. /* Append data to the wal-index. It is not necessary to lock the
  48443. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  48444. ** guarantees that there are no other writers, and no data that may
  48445. ** be in use by existing readers is being overwritten.
  48446. */
  48447. iFrame = pWal->hdr.mxFrame;
  48448. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  48449. iFrame++;
  48450. rc = walIndexAppend(pWal, iFrame, p->pgno);
  48451. }
  48452. while( rc==SQLITE_OK && nExtra>0 ){
  48453. iFrame++;
  48454. nExtra--;
  48455. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  48456. }
  48457. if( rc==SQLITE_OK ){
  48458. /* Update the private copy of the header. */
  48459. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  48460. testcase( szPage<=32768 );
  48461. testcase( szPage>=65536 );
  48462. pWal->hdr.mxFrame = iFrame;
  48463. if( isCommit ){
  48464. pWal->hdr.iChange++;
  48465. pWal->hdr.nPage = nTruncate;
  48466. }
  48467. /* If this is a commit, update the wal-index header too. */
  48468. if( isCommit ){
  48469. walIndexWriteHdr(pWal);
  48470. pWal->iCallback = iFrame;
  48471. }
  48472. }
  48473. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  48474. return rc;
  48475. }
  48476. /*
  48477. ** This routine is called to implement sqlite3_wal_checkpoint() and
  48478. ** related interfaces.
  48479. **
  48480. ** Obtain a CHECKPOINT lock and then backfill as much information as
  48481. ** we can from WAL into the database.
  48482. **
  48483. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  48484. ** callback. In this case this function runs a blocking checkpoint.
  48485. */
  48486. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  48487. Wal *pWal, /* Wal connection */
  48488. int eMode, /* PASSIVE, FULL or RESTART */
  48489. int (*xBusy)(void*), /* Function to call when busy */
  48490. void *pBusyArg, /* Context argument for xBusyHandler */
  48491. int sync_flags, /* Flags to sync db file with (or 0) */
  48492. int nBuf, /* Size of temporary buffer */
  48493. u8 *zBuf, /* Temporary buffer to use */
  48494. int *pnLog, /* OUT: Number of frames in WAL */
  48495. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  48496. ){
  48497. int rc; /* Return code */
  48498. int isChanged = 0; /* True if a new wal-index header is loaded */
  48499. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  48500. assert( pWal->ckptLock==0 );
  48501. assert( pWal->writeLock==0 );
  48502. if( pWal->readOnly ) return SQLITE_READONLY;
  48503. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  48504. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  48505. if( rc ){
  48506. /* Usually this is SQLITE_BUSY meaning that another thread or process
  48507. ** is already running a checkpoint, or maybe a recovery. But it might
  48508. ** also be SQLITE_IOERR. */
  48509. return rc;
  48510. }
  48511. pWal->ckptLock = 1;
  48512. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  48513. ** to prevent any writers from running while the checkpoint is underway.
  48514. ** This has to be done before the call to walIndexReadHdr() below.
  48515. **
  48516. ** If the writer lock cannot be obtained, then a passive checkpoint is
  48517. ** run instead. Since the checkpointer is not holding the writer lock,
  48518. ** there is no point in blocking waiting for any readers. Assuming no
  48519. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  48520. */
  48521. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  48522. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  48523. if( rc==SQLITE_OK ){
  48524. pWal->writeLock = 1;
  48525. }else if( rc==SQLITE_BUSY ){
  48526. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  48527. rc = SQLITE_OK;
  48528. }
  48529. }
  48530. /* Read the wal-index header. */
  48531. if( rc==SQLITE_OK ){
  48532. rc = walIndexReadHdr(pWal, &isChanged);
  48533. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  48534. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  48535. }
  48536. }
  48537. /* Copy data from the log to the database file. */
  48538. if( rc==SQLITE_OK ){
  48539. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  48540. rc = SQLITE_CORRUPT_BKPT;
  48541. }else{
  48542. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  48543. }
  48544. /* If no error occurred, set the output variables. */
  48545. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  48546. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  48547. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  48548. }
  48549. }
  48550. if( isChanged ){
  48551. /* If a new wal-index header was loaded before the checkpoint was
  48552. ** performed, then the pager-cache associated with pWal is now
  48553. ** out of date. So zero the cached wal-index header to ensure that
  48554. ** next time the pager opens a snapshot on this database it knows that
  48555. ** the cache needs to be reset.
  48556. */
  48557. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  48558. }
  48559. /* Release the locks. */
  48560. sqlite3WalEndWriteTransaction(pWal);
  48561. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  48562. pWal->ckptLock = 0;
  48563. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  48564. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  48565. }
  48566. /* Return the value to pass to a sqlite3_wal_hook callback, the
  48567. ** number of frames in the WAL at the point of the last commit since
  48568. ** sqlite3WalCallback() was called. If no commits have occurred since
  48569. ** the last call, then return 0.
  48570. */
  48571. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  48572. u32 ret = 0;
  48573. if( pWal ){
  48574. ret = pWal->iCallback;
  48575. pWal->iCallback = 0;
  48576. }
  48577. return (int)ret;
  48578. }
  48579. /*
  48580. ** This function is called to change the WAL subsystem into or out
  48581. ** of locking_mode=EXCLUSIVE.
  48582. **
  48583. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  48584. ** into locking_mode=NORMAL. This means that we must acquire a lock
  48585. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  48586. ** or if the acquisition of the lock fails, then return 0. If the
  48587. ** transition out of exclusive-mode is successful, return 1. This
  48588. ** operation must occur while the pager is still holding the exclusive
  48589. ** lock on the main database file.
  48590. **
  48591. ** If op is one, then change from locking_mode=NORMAL into
  48592. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  48593. ** be released. Return 1 if the transition is made and 0 if the
  48594. ** WAL is already in exclusive-locking mode - meaning that this
  48595. ** routine is a no-op. The pager must already hold the exclusive lock
  48596. ** on the main database file before invoking this operation.
  48597. **
  48598. ** If op is negative, then do a dry-run of the op==1 case but do
  48599. ** not actually change anything. The pager uses this to see if it
  48600. ** should acquire the database exclusive lock prior to invoking
  48601. ** the op==1 case.
  48602. */
  48603. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  48604. int rc;
  48605. assert( pWal->writeLock==0 );
  48606. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  48607. /* pWal->readLock is usually set, but might be -1 if there was a
  48608. ** prior error while attempting to acquire are read-lock. This cannot
  48609. ** happen if the connection is actually in exclusive mode (as no xShmLock
  48610. ** locks are taken in this case). Nor should the pager attempt to
  48611. ** upgrade to exclusive-mode following such an error.
  48612. */
  48613. assert( pWal->readLock>=0 || pWal->lockError );
  48614. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  48615. if( op==0 ){
  48616. if( pWal->exclusiveMode ){
  48617. pWal->exclusiveMode = 0;
  48618. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  48619. pWal->exclusiveMode = 1;
  48620. }
  48621. rc = pWal->exclusiveMode==0;
  48622. }else{
  48623. /* Already in locking_mode=NORMAL */
  48624. rc = 0;
  48625. }
  48626. }else if( op>0 ){
  48627. assert( pWal->exclusiveMode==0 );
  48628. assert( pWal->readLock>=0 );
  48629. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  48630. pWal->exclusiveMode = 1;
  48631. rc = 1;
  48632. }else{
  48633. rc = pWal->exclusiveMode==0;
  48634. }
  48635. return rc;
  48636. }
  48637. /*
  48638. ** Return true if the argument is non-NULL and the WAL module is using
  48639. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  48640. ** WAL module is using shared-memory, return false.
  48641. */
  48642. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  48643. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  48644. }
  48645. #ifdef SQLITE_ENABLE_ZIPVFS
  48646. /*
  48647. ** If the argument is not NULL, it points to a Wal object that holds a
  48648. ** read-lock. This function returns the database page-size if it is known,
  48649. ** or zero if it is not (or if pWal is NULL).
  48650. */
  48651. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  48652. assert( pWal==0 || pWal->readLock>=0 );
  48653. return (pWal ? pWal->szPage : 0);
  48654. }
  48655. #endif
  48656. #endif /* #ifndef SQLITE_OMIT_WAL */
  48657. /************** End of wal.c *************************************************/
  48658. /************** Begin file btmutex.c *****************************************/
  48659. /*
  48660. ** 2007 August 27
  48661. **
  48662. ** The author disclaims copyright to this source code. In place of
  48663. ** a legal notice, here is a blessing:
  48664. **
  48665. ** May you do good and not evil.
  48666. ** May you find forgiveness for yourself and forgive others.
  48667. ** May you share freely, never taking more than you give.
  48668. **
  48669. *************************************************************************
  48670. **
  48671. ** This file contains code used to implement mutexes on Btree objects.
  48672. ** This code really belongs in btree.c. But btree.c is getting too
  48673. ** big and we want to break it down some. This packaged seemed like
  48674. ** a good breakout.
  48675. */
  48676. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  48677. /************** Begin file btreeInt.h ****************************************/
  48678. /*
  48679. ** 2004 April 6
  48680. **
  48681. ** The author disclaims copyright to this source code. In place of
  48682. ** a legal notice, here is a blessing:
  48683. **
  48684. ** May you do good and not evil.
  48685. ** May you find forgiveness for yourself and forgive others.
  48686. ** May you share freely, never taking more than you give.
  48687. **
  48688. *************************************************************************
  48689. ** This file implements a external (disk-based) database using BTrees.
  48690. ** For a detailed discussion of BTrees, refer to
  48691. **
  48692. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  48693. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  48694. ** Publishing Company, Reading, Massachusetts.
  48695. **
  48696. ** The basic idea is that each page of the file contains N database
  48697. ** entries and N+1 pointers to subpages.
  48698. **
  48699. ** ----------------------------------------------------------------
  48700. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  48701. ** ----------------------------------------------------------------
  48702. **
  48703. ** All of the keys on the page that Ptr(0) points to have values less
  48704. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  48705. ** values greater than Key(0) and less than Key(1). All of the keys
  48706. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  48707. ** so forth.
  48708. **
  48709. ** Finding a particular key requires reading O(log(M)) pages from the
  48710. ** disk where M is the number of entries in the tree.
  48711. **
  48712. ** In this implementation, a single file can hold one or more separate
  48713. ** BTrees. Each BTree is identified by the index of its root page. The
  48714. ** key and data for any entry are combined to form the "payload". A
  48715. ** fixed amount of payload can be carried directly on the database
  48716. ** page. If the payload is larger than the preset amount then surplus
  48717. ** bytes are stored on overflow pages. The payload for an entry
  48718. ** and the preceding pointer are combined to form a "Cell". Each
  48719. ** page has a small header which contains the Ptr(N) pointer and other
  48720. ** information such as the size of key and data.
  48721. **
  48722. ** FORMAT DETAILS
  48723. **
  48724. ** The file is divided into pages. The first page is called page 1,
  48725. ** the second is page 2, and so forth. A page number of zero indicates
  48726. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  48727. ** Each page can be either a btree page, a freelist page, an overflow
  48728. ** page, or a pointer-map page.
  48729. **
  48730. ** The first page is always a btree page. The first 100 bytes of the first
  48731. ** page contain a special header (the "file header") that describes the file.
  48732. ** The format of the file header is as follows:
  48733. **
  48734. ** OFFSET SIZE DESCRIPTION
  48735. ** 0 16 Header string: "SQLite format 3\000"
  48736. ** 16 2 Page size in bytes. (1 means 65536)
  48737. ** 18 1 File format write version
  48738. ** 19 1 File format read version
  48739. ** 20 1 Bytes of unused space at the end of each page
  48740. ** 21 1 Max embedded payload fraction (must be 64)
  48741. ** 22 1 Min embedded payload fraction (must be 32)
  48742. ** 23 1 Min leaf payload fraction (must be 32)
  48743. ** 24 4 File change counter
  48744. ** 28 4 Reserved for future use
  48745. ** 32 4 First freelist page
  48746. ** 36 4 Number of freelist pages in the file
  48747. ** 40 60 15 4-byte meta values passed to higher layers
  48748. **
  48749. ** 40 4 Schema cookie
  48750. ** 44 4 File format of schema layer
  48751. ** 48 4 Size of page cache
  48752. ** 52 4 Largest root-page (auto/incr_vacuum)
  48753. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  48754. ** 60 4 User version
  48755. ** 64 4 Incremental vacuum mode
  48756. ** 68 4 Application-ID
  48757. ** 72 20 unused
  48758. ** 92 4 The version-valid-for number
  48759. ** 96 4 SQLITE_VERSION_NUMBER
  48760. **
  48761. ** All of the integer values are big-endian (most significant byte first).
  48762. **
  48763. ** The file change counter is incremented when the database is changed
  48764. ** This counter allows other processes to know when the file has changed
  48765. ** and thus when they need to flush their cache.
  48766. **
  48767. ** The max embedded payload fraction is the amount of the total usable
  48768. ** space in a page that can be consumed by a single cell for standard
  48769. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  48770. ** is to limit the maximum cell size so that at least 4 cells will fit
  48771. ** on one page. Thus the default max embedded payload fraction is 64.
  48772. **
  48773. ** If the payload for a cell is larger than the max payload, then extra
  48774. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  48775. ** as many bytes as possible are moved into the overflow pages without letting
  48776. ** the cell size drop below the min embedded payload fraction.
  48777. **
  48778. ** The min leaf payload fraction is like the min embedded payload fraction
  48779. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  48780. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  48781. ** not specified in the header.
  48782. **
  48783. ** Each btree pages is divided into three sections: The header, the
  48784. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  48785. ** file header that occurs before the page header.
  48786. **
  48787. ** |----------------|
  48788. ** | file header | 100 bytes. Page 1 only.
  48789. ** |----------------|
  48790. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  48791. ** |----------------|
  48792. ** | cell pointer | | 2 bytes per cell. Sorted order.
  48793. ** | array | | Grows downward
  48794. ** | | v
  48795. ** |----------------|
  48796. ** | unallocated |
  48797. ** | space |
  48798. ** |----------------| ^ Grows upwards
  48799. ** | cell content | | Arbitrary order interspersed with freeblocks.
  48800. ** | area | | and free space fragments.
  48801. ** |----------------|
  48802. **
  48803. ** The page headers looks like this:
  48804. **
  48805. ** OFFSET SIZE DESCRIPTION
  48806. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  48807. ** 1 2 byte offset to the first freeblock
  48808. ** 3 2 number of cells on this page
  48809. ** 5 2 first byte of the cell content area
  48810. ** 7 1 number of fragmented free bytes
  48811. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  48812. **
  48813. ** The flags define the format of this btree page. The leaf flag means that
  48814. ** this page has no children. The zerodata flag means that this page carries
  48815. ** only keys and no data. The intkey flag means that the key is a integer
  48816. ** which is stored in the key size entry of the cell header rather than in
  48817. ** the payload area.
  48818. **
  48819. ** The cell pointer array begins on the first byte after the page header.
  48820. ** The cell pointer array contains zero or more 2-byte numbers which are
  48821. ** offsets from the beginning of the page to the cell content in the cell
  48822. ** content area. The cell pointers occur in sorted order. The system strives
  48823. ** to keep free space after the last cell pointer so that new cells can
  48824. ** be easily added without having to defragment the page.
  48825. **
  48826. ** Cell content is stored at the very end of the page and grows toward the
  48827. ** beginning of the page.
  48828. **
  48829. ** Unused space within the cell content area is collected into a linked list of
  48830. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  48831. ** to the first freeblock is given in the header. Freeblocks occur in
  48832. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  48833. ** any group of 3 or fewer unused bytes in the cell content area cannot
  48834. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  48835. ** a fragment. The total number of bytes in all fragments is recorded.
  48836. ** in the page header at offset 7.
  48837. **
  48838. ** SIZE DESCRIPTION
  48839. ** 2 Byte offset of the next freeblock
  48840. ** 2 Bytes in this freeblock
  48841. **
  48842. ** Cells are of variable length. Cells are stored in the cell content area at
  48843. ** the end of the page. Pointers to the cells are in the cell pointer array
  48844. ** that immediately follows the page header. Cells is not necessarily
  48845. ** contiguous or in order, but cell pointers are contiguous and in order.
  48846. **
  48847. ** Cell content makes use of variable length integers. A variable
  48848. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  48849. ** byte are used. The integer consists of all bytes that have bit 8 set and
  48850. ** the first byte with bit 8 clear. The most significant byte of the integer
  48851. ** appears first. A variable-length integer may not be more than 9 bytes long.
  48852. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  48853. ** allows a 64-bit integer to be encoded in 9 bytes.
  48854. **
  48855. ** 0x00 becomes 0x00000000
  48856. ** 0x7f becomes 0x0000007f
  48857. ** 0x81 0x00 becomes 0x00000080
  48858. ** 0x82 0x00 becomes 0x00000100
  48859. ** 0x80 0x7f becomes 0x0000007f
  48860. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  48861. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  48862. **
  48863. ** Variable length integers are used for rowids and to hold the number of
  48864. ** bytes of key and data in a btree cell.
  48865. **
  48866. ** The content of a cell looks like this:
  48867. **
  48868. ** SIZE DESCRIPTION
  48869. ** 4 Page number of the left child. Omitted if leaf flag is set.
  48870. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  48871. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  48872. ** * Payload
  48873. ** 4 First page of the overflow chain. Omitted if no overflow
  48874. **
  48875. ** Overflow pages form a linked list. Each page except the last is completely
  48876. ** filled with data (pagesize - 4 bytes). The last page can have as little
  48877. ** as 1 byte of data.
  48878. **
  48879. ** SIZE DESCRIPTION
  48880. ** 4 Page number of next overflow page
  48881. ** * Data
  48882. **
  48883. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  48884. ** file header points to the first in a linked list of trunk page. Each trunk
  48885. ** page points to multiple leaf pages. The content of a leaf page is
  48886. ** unspecified. A trunk page looks like this:
  48887. **
  48888. ** SIZE DESCRIPTION
  48889. ** 4 Page number of next trunk page
  48890. ** 4 Number of leaf pointers on this page
  48891. ** * zero or more pages numbers of leaves
  48892. */
  48893. /* The following value is the maximum cell size assuming a maximum page
  48894. ** size give above.
  48895. */
  48896. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  48897. /* The maximum number of cells on a single page of the database. This
  48898. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  48899. ** plus 2 bytes for the index to the cell in the page header). Such
  48900. ** small cells will be rare, but they are possible.
  48901. */
  48902. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  48903. /* Forward declarations */
  48904. typedef struct MemPage MemPage;
  48905. typedef struct BtLock BtLock;
  48906. /*
  48907. ** This is a magic string that appears at the beginning of every
  48908. ** SQLite database in order to identify the file as a real database.
  48909. **
  48910. ** You can change this value at compile-time by specifying a
  48911. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  48912. ** header must be exactly 16 bytes including the zero-terminator so
  48913. ** the string itself should be 15 characters long. If you change
  48914. ** the header, then your custom library will not be able to read
  48915. ** databases generated by the standard tools and the standard tools
  48916. ** will not be able to read databases created by your custom library.
  48917. */
  48918. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  48919. # define SQLITE_FILE_HEADER "SQLite format 3"
  48920. #endif
  48921. /*
  48922. ** Page type flags. An ORed combination of these flags appear as the
  48923. ** first byte of on-disk image of every BTree page.
  48924. */
  48925. #define PTF_INTKEY 0x01
  48926. #define PTF_ZERODATA 0x02
  48927. #define PTF_LEAFDATA 0x04
  48928. #define PTF_LEAF 0x08
  48929. /*
  48930. ** As each page of the file is loaded into memory, an instance of the following
  48931. ** structure is appended and initialized to zero. This structure stores
  48932. ** information about the page that is decoded from the raw file page.
  48933. **
  48934. ** The pParent field points back to the parent page. This allows us to
  48935. ** walk up the BTree from any leaf to the root. Care must be taken to
  48936. ** unref() the parent page pointer when this page is no longer referenced.
  48937. ** The pageDestructor() routine handles that chore.
  48938. **
  48939. ** Access to all fields of this structure is controlled by the mutex
  48940. ** stored in MemPage.pBt->mutex.
  48941. */
  48942. struct MemPage {
  48943. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  48944. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  48945. u8 intKey; /* True if intkey flag is set */
  48946. u8 leaf; /* True if leaf flag is set */
  48947. u8 hasData; /* True if this page stores data */
  48948. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  48949. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  48950. u8 max1bytePayload; /* min(maxLocal,127) */
  48951. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  48952. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  48953. u16 cellOffset; /* Index in aData of first cell pointer */
  48954. u16 nFree; /* Number of free bytes on the page */
  48955. u16 nCell; /* Number of cells on this page, local and ovfl */
  48956. u16 maskPage; /* Mask for page offset */
  48957. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  48958. ** non-overflow cell */
  48959. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  48960. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  48961. u8 *aData; /* Pointer to disk image of the page data */
  48962. u8 *aDataEnd; /* One byte past the end of usable data */
  48963. u8 *aCellIdx; /* The cell index area */
  48964. DbPage *pDbPage; /* Pager page handle */
  48965. Pgno pgno; /* Page number for this page */
  48966. };
  48967. /*
  48968. ** The in-memory image of a disk page has the auxiliary information appended
  48969. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  48970. ** that extra information.
  48971. */
  48972. #define EXTRA_SIZE sizeof(MemPage)
  48973. /*
  48974. ** A linked list of the following structures is stored at BtShared.pLock.
  48975. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  48976. ** is opened on the table with root page BtShared.iTable. Locks are removed
  48977. ** from this list when a transaction is committed or rolled back, or when
  48978. ** a btree handle is closed.
  48979. */
  48980. struct BtLock {
  48981. Btree *pBtree; /* Btree handle holding this lock */
  48982. Pgno iTable; /* Root page of table */
  48983. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  48984. BtLock *pNext; /* Next in BtShared.pLock list */
  48985. };
  48986. /* Candidate values for BtLock.eLock */
  48987. #define READ_LOCK 1
  48988. #define WRITE_LOCK 2
  48989. /* A Btree handle
  48990. **
  48991. ** A database connection contains a pointer to an instance of
  48992. ** this object for every database file that it has open. This structure
  48993. ** is opaque to the database connection. The database connection cannot
  48994. ** see the internals of this structure and only deals with pointers to
  48995. ** this structure.
  48996. **
  48997. ** For some database files, the same underlying database cache might be
  48998. ** shared between multiple connections. In that case, each connection
  48999. ** has it own instance of this object. But each instance of this object
  49000. ** points to the same BtShared object. The database cache and the
  49001. ** schema associated with the database file are all contained within
  49002. ** the BtShared object.
  49003. **
  49004. ** All fields in this structure are accessed under sqlite3.mutex.
  49005. ** The pBt pointer itself may not be changed while there exists cursors
  49006. ** in the referenced BtShared that point back to this Btree since those
  49007. ** cursors have to go through this Btree to find their BtShared and
  49008. ** they often do so without holding sqlite3.mutex.
  49009. */
  49010. struct Btree {
  49011. sqlite3 *db; /* The database connection holding this btree */
  49012. BtShared *pBt; /* Sharable content of this btree */
  49013. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  49014. u8 sharable; /* True if we can share pBt with another db */
  49015. u8 locked; /* True if db currently has pBt locked */
  49016. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  49017. int nBackup; /* Number of backup operations reading this btree */
  49018. Btree *pNext; /* List of other sharable Btrees from the same db */
  49019. Btree *pPrev; /* Back pointer of the same list */
  49020. #ifndef SQLITE_OMIT_SHARED_CACHE
  49021. BtLock lock; /* Object used to lock page 1 */
  49022. #endif
  49023. };
  49024. /*
  49025. ** Btree.inTrans may take one of the following values.
  49026. **
  49027. ** If the shared-data extension is enabled, there may be multiple users
  49028. ** of the Btree structure. At most one of these may open a write transaction,
  49029. ** but any number may have active read transactions.
  49030. */
  49031. #define TRANS_NONE 0
  49032. #define TRANS_READ 1
  49033. #define TRANS_WRITE 2
  49034. /*
  49035. ** An instance of this object represents a single database file.
  49036. **
  49037. ** A single database file can be in use at the same time by two
  49038. ** or more database connections. When two or more connections are
  49039. ** sharing the same database file, each connection has it own
  49040. ** private Btree object for the file and each of those Btrees points
  49041. ** to this one BtShared object. BtShared.nRef is the number of
  49042. ** connections currently sharing this database file.
  49043. **
  49044. ** Fields in this structure are accessed under the BtShared.mutex
  49045. ** mutex, except for nRef and pNext which are accessed under the
  49046. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  49047. ** may not be modified once it is initially set as long as nRef>0.
  49048. ** The pSchema field may be set once under BtShared.mutex and
  49049. ** thereafter is unchanged as long as nRef>0.
  49050. **
  49051. ** isPending:
  49052. **
  49053. ** If a BtShared client fails to obtain a write-lock on a database
  49054. ** table (because there exists one or more read-locks on the table),
  49055. ** the shared-cache enters 'pending-lock' state and isPending is
  49056. ** set to true.
  49057. **
  49058. ** The shared-cache leaves the 'pending lock' state when either of
  49059. ** the following occur:
  49060. **
  49061. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  49062. ** 2) The number of locks held by other connections drops to zero.
  49063. **
  49064. ** while in the 'pending-lock' state, no connection may start a new
  49065. ** transaction.
  49066. **
  49067. ** This feature is included to help prevent writer-starvation.
  49068. */
  49069. struct BtShared {
  49070. Pager *pPager; /* The page cache */
  49071. sqlite3 *db; /* Database connection currently using this Btree */
  49072. BtCursor *pCursor; /* A list of all open cursors */
  49073. MemPage *pPage1; /* First page of the database */
  49074. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  49075. #ifndef SQLITE_OMIT_AUTOVACUUM
  49076. u8 autoVacuum; /* True if auto-vacuum is enabled */
  49077. u8 incrVacuum; /* True if incr-vacuum is enabled */
  49078. u8 bDoTruncate; /* True to truncate db on commit */
  49079. #endif
  49080. u8 inTransaction; /* Transaction state */
  49081. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  49082. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  49083. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  49084. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  49085. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  49086. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  49087. u32 pageSize; /* Total number of bytes on a page */
  49088. u32 usableSize; /* Number of usable bytes on each page */
  49089. int nTransaction; /* Number of open transactions (read + write) */
  49090. u32 nPage; /* Number of pages in the database */
  49091. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  49092. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  49093. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  49094. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  49095. #ifndef SQLITE_OMIT_SHARED_CACHE
  49096. int nRef; /* Number of references to this structure */
  49097. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  49098. BtLock *pLock; /* List of locks held on this shared-btree struct */
  49099. Btree *pWriter; /* Btree with currently open write transaction */
  49100. #endif
  49101. u8 *pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
  49102. };
  49103. /*
  49104. ** Allowed values for BtShared.btsFlags
  49105. */
  49106. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  49107. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  49108. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  49109. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  49110. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  49111. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  49112. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  49113. /*
  49114. ** An instance of the following structure is used to hold information
  49115. ** about a cell. The parseCellPtr() function fills in this structure
  49116. ** based on information extract from the raw disk page.
  49117. */
  49118. typedef struct CellInfo CellInfo;
  49119. struct CellInfo {
  49120. i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
  49121. u8 *pCell; /* Pointer to the start of cell content */
  49122. u32 nData; /* Number of bytes of data */
  49123. u32 nPayload; /* Total amount of payload */
  49124. u16 nHeader; /* Size of the cell content header in bytes */
  49125. u16 nLocal; /* Amount of payload held locally */
  49126. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  49127. u16 nSize; /* Size of the cell content on the main b-tree page */
  49128. };
  49129. /*
  49130. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  49131. ** this will be declared corrupt. This value is calculated based on a
  49132. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  49133. ** root-node and 3 for all other internal nodes.
  49134. **
  49135. ** If a tree that appears to be taller than this is encountered, it is
  49136. ** assumed that the database is corrupt.
  49137. */
  49138. #define BTCURSOR_MAX_DEPTH 20
  49139. /*
  49140. ** A cursor is a pointer to a particular entry within a particular
  49141. ** b-tree within a database file.
  49142. **
  49143. ** The entry is identified by its MemPage and the index in
  49144. ** MemPage.aCell[] of the entry.
  49145. **
  49146. ** A single database file can be shared by two more database connections,
  49147. ** but cursors cannot be shared. Each cursor is associated with a
  49148. ** particular database connection identified BtCursor.pBtree.db.
  49149. **
  49150. ** Fields in this structure are accessed under the BtShared.mutex
  49151. ** found at self->pBt->mutex.
  49152. */
  49153. struct BtCursor {
  49154. Btree *pBtree; /* The Btree to which this cursor belongs */
  49155. BtShared *pBt; /* The BtShared this cursor points to */
  49156. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  49157. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  49158. #ifndef SQLITE_OMIT_INCRBLOB
  49159. Pgno *aOverflow; /* Cache of overflow page locations */
  49160. #endif
  49161. Pgno pgnoRoot; /* The root page of this tree */
  49162. sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
  49163. CellInfo info; /* A parse of the cell we are pointing at */
  49164. i64 nKey; /* Size of pKey, or last integer key */
  49165. void *pKey; /* Saved key that was cursor's last known position */
  49166. int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
  49167. u8 wrFlag; /* True if writable */
  49168. u8 atLast; /* Cursor pointing to the last entry */
  49169. u8 validNKey; /* True if info.nKey is valid */
  49170. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  49171. #ifndef SQLITE_OMIT_INCRBLOB
  49172. u8 isIncrblobHandle; /* True if this cursor is an incr. io handle */
  49173. #endif
  49174. u8 hints; /* As configured by CursorSetHints() */
  49175. i16 iPage; /* Index of current page in apPage */
  49176. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  49177. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  49178. };
  49179. /*
  49180. ** Potential values for BtCursor.eState.
  49181. **
  49182. ** CURSOR_INVALID:
  49183. ** Cursor does not point to a valid entry. This can happen (for example)
  49184. ** because the table is empty or because BtreeCursorFirst() has not been
  49185. ** called.
  49186. **
  49187. ** CURSOR_VALID:
  49188. ** Cursor points to a valid entry. getPayload() etc. may be called.
  49189. **
  49190. ** CURSOR_SKIPNEXT:
  49191. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  49192. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  49193. ** operation should be a no-op.
  49194. **
  49195. ** CURSOR_REQUIRESEEK:
  49196. ** The table that this cursor was opened on still exists, but has been
  49197. ** modified since the cursor was last used. The cursor position is saved
  49198. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  49199. ** this state, restoreCursorPosition() can be called to attempt to
  49200. ** seek the cursor to the saved position.
  49201. **
  49202. ** CURSOR_FAULT:
  49203. ** A unrecoverable error (an I/O error or a malloc failure) has occurred
  49204. ** on a different connection that shares the BtShared cache with this
  49205. ** cursor. The error has left the cache in an inconsistent state.
  49206. ** Do nothing else with this cursor. Any attempt to use the cursor
  49207. ** should return the error code stored in BtCursor.skip
  49208. */
  49209. #define CURSOR_INVALID 0
  49210. #define CURSOR_VALID 1
  49211. #define CURSOR_SKIPNEXT 2
  49212. #define CURSOR_REQUIRESEEK 3
  49213. #define CURSOR_FAULT 4
  49214. /*
  49215. ** The database page the PENDING_BYTE occupies. This page is never used.
  49216. */
  49217. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  49218. /*
  49219. ** These macros define the location of the pointer-map entry for a
  49220. ** database page. The first argument to each is the number of usable
  49221. ** bytes on each page of the database (often 1024). The second is the
  49222. ** page number to look up in the pointer map.
  49223. **
  49224. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  49225. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  49226. ** the offset of the requested map entry.
  49227. **
  49228. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  49229. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  49230. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  49231. ** this test.
  49232. */
  49233. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  49234. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  49235. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  49236. /*
  49237. ** The pointer map is a lookup table that identifies the parent page for
  49238. ** each child page in the database file. The parent page is the page that
  49239. ** contains a pointer to the child. Every page in the database contains
  49240. ** 0 or 1 parent pages. (In this context 'database page' refers
  49241. ** to any page that is not part of the pointer map itself.) Each pointer map
  49242. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  49243. ** The PTRMAP_XXX identifiers below are the valid types.
  49244. **
  49245. ** The purpose of the pointer map is to facility moving pages from one
  49246. ** position in the file to another as part of autovacuum. When a page
  49247. ** is moved, the pointer in its parent must be updated to point to the
  49248. ** new location. The pointer map is used to locate the parent page quickly.
  49249. **
  49250. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  49251. ** used in this case.
  49252. **
  49253. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  49254. ** is not used in this case.
  49255. **
  49256. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  49257. ** overflow pages. The page number identifies the page that
  49258. ** contains the cell with a pointer to this overflow page.
  49259. **
  49260. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  49261. ** overflow pages. The page-number identifies the previous
  49262. ** page in the overflow page list.
  49263. **
  49264. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  49265. ** identifies the parent page in the btree.
  49266. */
  49267. #define PTRMAP_ROOTPAGE 1
  49268. #define PTRMAP_FREEPAGE 2
  49269. #define PTRMAP_OVERFLOW1 3
  49270. #define PTRMAP_OVERFLOW2 4
  49271. #define PTRMAP_BTREE 5
  49272. /* A bunch of assert() statements to check the transaction state variables
  49273. ** of handle p (type Btree*) are internally consistent.
  49274. */
  49275. #define btreeIntegrity(p) \
  49276. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  49277. assert( p->pBt->inTransaction>=p->inTrans );
  49278. /*
  49279. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  49280. ** if the database supports auto-vacuum or not. Because it is used
  49281. ** within an expression that is an argument to another macro
  49282. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  49283. ** So, this macro is defined instead.
  49284. */
  49285. #ifndef SQLITE_OMIT_AUTOVACUUM
  49286. #define ISAUTOVACUUM (pBt->autoVacuum)
  49287. #else
  49288. #define ISAUTOVACUUM 0
  49289. #endif
  49290. /*
  49291. ** This structure is passed around through all the sanity checking routines
  49292. ** in order to keep track of some global state information.
  49293. **
  49294. ** The aRef[] array is allocated so that there is 1 bit for each page in
  49295. ** the database. As the integrity-check proceeds, for each page used in
  49296. ** the database the corresponding bit is set. This allows integrity-check to
  49297. ** detect pages that are used twice and orphaned pages (both of which
  49298. ** indicate corruption).
  49299. */
  49300. typedef struct IntegrityCk IntegrityCk;
  49301. struct IntegrityCk {
  49302. BtShared *pBt; /* The tree being checked out */
  49303. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  49304. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  49305. Pgno nPage; /* Number of pages in the database */
  49306. int mxErr; /* Stop accumulating errors when this reaches zero */
  49307. int nErr; /* Number of messages written to zErrMsg so far */
  49308. int mallocFailed; /* A memory allocation error has occurred */
  49309. StrAccum errMsg; /* Accumulate the error message text here */
  49310. };
  49311. /*
  49312. ** Routines to read or write a two- and four-byte big-endian integer values.
  49313. */
  49314. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  49315. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  49316. #define get4byte sqlite3Get4byte
  49317. #define put4byte sqlite3Put4byte
  49318. /************** End of btreeInt.h ********************************************/
  49319. /************** Continuing where we left off in btmutex.c ********************/
  49320. #ifndef SQLITE_OMIT_SHARED_CACHE
  49321. #if SQLITE_THREADSAFE
  49322. /*
  49323. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  49324. ** set BtShared.db to the database handle associated with p and the
  49325. ** p->locked boolean to true.
  49326. */
  49327. static void lockBtreeMutex(Btree *p){
  49328. assert( p->locked==0 );
  49329. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  49330. assert( sqlite3_mutex_held(p->db->mutex) );
  49331. sqlite3_mutex_enter(p->pBt->mutex);
  49332. p->pBt->db = p->db;
  49333. p->locked = 1;
  49334. }
  49335. /*
  49336. ** Release the BtShared mutex associated with B-Tree handle p and
  49337. ** clear the p->locked boolean.
  49338. */
  49339. static void unlockBtreeMutex(Btree *p){
  49340. BtShared *pBt = p->pBt;
  49341. assert( p->locked==1 );
  49342. assert( sqlite3_mutex_held(pBt->mutex) );
  49343. assert( sqlite3_mutex_held(p->db->mutex) );
  49344. assert( p->db==pBt->db );
  49345. sqlite3_mutex_leave(pBt->mutex);
  49346. p->locked = 0;
  49347. }
  49348. /*
  49349. ** Enter a mutex on the given BTree object.
  49350. **
  49351. ** If the object is not sharable, then no mutex is ever required
  49352. ** and this routine is a no-op. The underlying mutex is non-recursive.
  49353. ** But we keep a reference count in Btree.wantToLock so the behavior
  49354. ** of this interface is recursive.
  49355. **
  49356. ** To avoid deadlocks, multiple Btrees are locked in the same order
  49357. ** by all database connections. The p->pNext is a list of other
  49358. ** Btrees belonging to the same database connection as the p Btree
  49359. ** which need to be locked after p. If we cannot get a lock on
  49360. ** p, then first unlock all of the others on p->pNext, then wait
  49361. ** for the lock to become available on p, then relock all of the
  49362. ** subsequent Btrees that desire a lock.
  49363. */
  49364. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49365. Btree *pLater;
  49366. /* Some basic sanity checking on the Btree. The list of Btrees
  49367. ** connected by pNext and pPrev should be in sorted order by
  49368. ** Btree.pBt value. All elements of the list should belong to
  49369. ** the same connection. Only shared Btrees are on the list. */
  49370. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  49371. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  49372. assert( p->pNext==0 || p->pNext->db==p->db );
  49373. assert( p->pPrev==0 || p->pPrev->db==p->db );
  49374. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  49375. /* Check for locking consistency */
  49376. assert( !p->locked || p->wantToLock>0 );
  49377. assert( p->sharable || p->wantToLock==0 );
  49378. /* We should already hold a lock on the database connection */
  49379. assert( sqlite3_mutex_held(p->db->mutex) );
  49380. /* Unless the database is sharable and unlocked, then BtShared.db
  49381. ** should already be set correctly. */
  49382. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  49383. if( !p->sharable ) return;
  49384. p->wantToLock++;
  49385. if( p->locked ) return;
  49386. /* In most cases, we should be able to acquire the lock we
  49387. ** want without having to go throught the ascending lock
  49388. ** procedure that follows. Just be sure not to block.
  49389. */
  49390. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  49391. p->pBt->db = p->db;
  49392. p->locked = 1;
  49393. return;
  49394. }
  49395. /* To avoid deadlock, first release all locks with a larger
  49396. ** BtShared address. Then acquire our lock. Then reacquire
  49397. ** the other BtShared locks that we used to hold in ascending
  49398. ** order.
  49399. */
  49400. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49401. assert( pLater->sharable );
  49402. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  49403. assert( !pLater->locked || pLater->wantToLock>0 );
  49404. if( pLater->locked ){
  49405. unlockBtreeMutex(pLater);
  49406. }
  49407. }
  49408. lockBtreeMutex(p);
  49409. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  49410. if( pLater->wantToLock ){
  49411. lockBtreeMutex(pLater);
  49412. }
  49413. }
  49414. }
  49415. /*
  49416. ** Exit the recursive mutex on a Btree.
  49417. */
  49418. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  49419. if( p->sharable ){
  49420. assert( p->wantToLock>0 );
  49421. p->wantToLock--;
  49422. if( p->wantToLock==0 ){
  49423. unlockBtreeMutex(p);
  49424. }
  49425. }
  49426. }
  49427. #ifndef NDEBUG
  49428. /*
  49429. ** Return true if the BtShared mutex is held on the btree, or if the
  49430. ** B-Tree is not marked as sharable.
  49431. **
  49432. ** This routine is used only from within assert() statements.
  49433. */
  49434. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  49435. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  49436. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  49437. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  49438. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  49439. return (p->sharable==0 || p->locked);
  49440. }
  49441. #endif
  49442. #ifndef SQLITE_OMIT_INCRBLOB
  49443. /*
  49444. ** Enter and leave a mutex on a Btree given a cursor owned by that
  49445. ** Btree. These entry points are used by incremental I/O and can be
  49446. ** omitted if that module is not used.
  49447. */
  49448. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  49449. sqlite3BtreeEnter(pCur->pBtree);
  49450. }
  49451. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  49452. sqlite3BtreeLeave(pCur->pBtree);
  49453. }
  49454. #endif /* SQLITE_OMIT_INCRBLOB */
  49455. /*
  49456. ** Enter the mutex on every Btree associated with a database
  49457. ** connection. This is needed (for example) prior to parsing
  49458. ** a statement since we will be comparing table and column names
  49459. ** against all schemas and we do not want those schemas being
  49460. ** reset out from under us.
  49461. **
  49462. ** There is a corresponding leave-all procedures.
  49463. **
  49464. ** Enter the mutexes in accending order by BtShared pointer address
  49465. ** to avoid the possibility of deadlock when two threads with
  49466. ** two or more btrees in common both try to lock all their btrees
  49467. ** at the same instant.
  49468. */
  49469. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49470. int i;
  49471. Btree *p;
  49472. assert( sqlite3_mutex_held(db->mutex) );
  49473. for(i=0; i<db->nDb; i++){
  49474. p = db->aDb[i].pBt;
  49475. if( p ) sqlite3BtreeEnter(p);
  49476. }
  49477. }
  49478. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  49479. int i;
  49480. Btree *p;
  49481. assert( sqlite3_mutex_held(db->mutex) );
  49482. for(i=0; i<db->nDb; i++){
  49483. p = db->aDb[i].pBt;
  49484. if( p ) sqlite3BtreeLeave(p);
  49485. }
  49486. }
  49487. /*
  49488. ** Return true if a particular Btree requires a lock. Return FALSE if
  49489. ** no lock is ever required since it is not sharable.
  49490. */
  49491. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  49492. return p->sharable;
  49493. }
  49494. #ifndef NDEBUG
  49495. /*
  49496. ** Return true if the current thread holds the database connection
  49497. ** mutex and all required BtShared mutexes.
  49498. **
  49499. ** This routine is used inside assert() statements only.
  49500. */
  49501. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  49502. int i;
  49503. if( !sqlite3_mutex_held(db->mutex) ){
  49504. return 0;
  49505. }
  49506. for(i=0; i<db->nDb; i++){
  49507. Btree *p;
  49508. p = db->aDb[i].pBt;
  49509. if( p && p->sharable &&
  49510. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  49511. return 0;
  49512. }
  49513. }
  49514. return 1;
  49515. }
  49516. #endif /* NDEBUG */
  49517. #ifndef NDEBUG
  49518. /*
  49519. ** Return true if the correct mutexes are held for accessing the
  49520. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  49521. ** access are:
  49522. **
  49523. ** (1) The mutex on db
  49524. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  49525. **
  49526. ** If pSchema is not NULL, then iDb is computed from pSchema and
  49527. ** db using sqlite3SchemaToIndex().
  49528. */
  49529. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  49530. Btree *p;
  49531. assert( db!=0 );
  49532. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  49533. assert( iDb>=0 && iDb<db->nDb );
  49534. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  49535. if( iDb==1 ) return 1;
  49536. p = db->aDb[iDb].pBt;
  49537. assert( p!=0 );
  49538. return p->sharable==0 || p->locked==1;
  49539. }
  49540. #endif /* NDEBUG */
  49541. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  49542. /*
  49543. ** The following are special cases for mutex enter routines for use
  49544. ** in single threaded applications that use shared cache. Except for
  49545. ** these two routines, all mutex operations are no-ops in that case and
  49546. ** are null #defines in btree.h.
  49547. **
  49548. ** If shared cache is disabled, then all btree mutex routines, including
  49549. ** the ones below, are no-ops and are null #defines in btree.h.
  49550. */
  49551. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  49552. p->pBt->db = p->db;
  49553. }
  49554. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  49555. int i;
  49556. for(i=0; i<db->nDb; i++){
  49557. Btree *p = db->aDb[i].pBt;
  49558. if( p ){
  49559. p->pBt->db = p->db;
  49560. }
  49561. }
  49562. }
  49563. #endif /* if SQLITE_THREADSAFE */
  49564. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  49565. /************** End of btmutex.c *********************************************/
  49566. /************** Begin file btree.c *******************************************/
  49567. /*
  49568. ** 2004 April 6
  49569. **
  49570. ** The author disclaims copyright to this source code. In place of
  49571. ** a legal notice, here is a blessing:
  49572. **
  49573. ** May you do good and not evil.
  49574. ** May you find forgiveness for yourself and forgive others.
  49575. ** May you share freely, never taking more than you give.
  49576. **
  49577. *************************************************************************
  49578. ** This file implements a external (disk-based) database using BTrees.
  49579. ** See the header comment on "btreeInt.h" for additional information.
  49580. ** Including a description of file format and an overview of operation.
  49581. */
  49582. /*
  49583. ** The header string that appears at the beginning of every
  49584. ** SQLite database.
  49585. */
  49586. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  49587. /*
  49588. ** Set this global variable to 1 to enable tracing using the TRACE
  49589. ** macro.
  49590. */
  49591. #if 0
  49592. int sqlite3BtreeTrace=1; /* True to enable tracing */
  49593. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  49594. #else
  49595. # define TRACE(X)
  49596. #endif
  49597. /*
  49598. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  49599. ** But if the value is zero, make it 65536.
  49600. **
  49601. ** This routine is used to extract the "offset to cell content area" value
  49602. ** from the header of a btree page. If the page size is 65536 and the page
  49603. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  49604. ** This routine makes the necessary adjustment to 65536.
  49605. */
  49606. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  49607. /*
  49608. ** Values passed as the 5th argument to allocateBtreePage()
  49609. */
  49610. #define BTALLOC_ANY 0 /* Allocate any page */
  49611. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  49612. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  49613. /*
  49614. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  49615. ** defined, or 0 if it is. For example:
  49616. **
  49617. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  49618. */
  49619. #ifndef SQLITE_OMIT_AUTOVACUUM
  49620. #define IfNotOmitAV(expr) (expr)
  49621. #else
  49622. #define IfNotOmitAV(expr) 0
  49623. #endif
  49624. #ifndef SQLITE_OMIT_SHARED_CACHE
  49625. /*
  49626. ** A list of BtShared objects that are eligible for participation
  49627. ** in shared cache. This variable has file scope during normal builds,
  49628. ** but the test harness needs to access it so we make it global for
  49629. ** test builds.
  49630. **
  49631. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  49632. */
  49633. #ifdef SQLITE_TEST
  49634. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49635. #else
  49636. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  49637. #endif
  49638. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49639. #ifndef SQLITE_OMIT_SHARED_CACHE
  49640. /*
  49641. ** Enable or disable the shared pager and schema features.
  49642. **
  49643. ** This routine has no effect on existing database connections.
  49644. ** The shared cache setting effects only future calls to
  49645. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  49646. */
  49647. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  49648. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  49649. return SQLITE_OK;
  49650. }
  49651. #endif
  49652. #ifdef SQLITE_OMIT_SHARED_CACHE
  49653. /*
  49654. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  49655. ** and clearAllSharedCacheTableLocks()
  49656. ** manipulate entries in the BtShared.pLock linked list used to store
  49657. ** shared-cache table level locks. If the library is compiled with the
  49658. ** shared-cache feature disabled, then there is only ever one user
  49659. ** of each BtShared structure and so this locking is not necessary.
  49660. ** So define the lock related functions as no-ops.
  49661. */
  49662. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  49663. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  49664. #define clearAllSharedCacheTableLocks(a)
  49665. #define downgradeAllSharedCacheTableLocks(a)
  49666. #define hasSharedCacheTableLock(a,b,c,d) 1
  49667. #define hasReadConflicts(a, b) 0
  49668. #endif
  49669. #ifndef SQLITE_OMIT_SHARED_CACHE
  49670. #ifdef SQLITE_DEBUG
  49671. /*
  49672. **** This function is only used as part of an assert() statement. ***
  49673. **
  49674. ** Check to see if pBtree holds the required locks to read or write to the
  49675. ** table with root page iRoot. Return 1 if it does and 0 if not.
  49676. **
  49677. ** For example, when writing to a table with root-page iRoot via
  49678. ** Btree connection pBtree:
  49679. **
  49680. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  49681. **
  49682. ** When writing to an index that resides in a sharable database, the
  49683. ** caller should have first obtained a lock specifying the root page of
  49684. ** the corresponding table. This makes things a bit more complicated,
  49685. ** as this module treats each table as a separate structure. To determine
  49686. ** the table corresponding to the index being written, this
  49687. ** function has to search through the database schema.
  49688. **
  49689. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  49690. ** hold a write-lock on the schema table (root page 1). This is also
  49691. ** acceptable.
  49692. */
  49693. static int hasSharedCacheTableLock(
  49694. Btree *pBtree, /* Handle that must hold lock */
  49695. Pgno iRoot, /* Root page of b-tree */
  49696. int isIndex, /* True if iRoot is the root of an index b-tree */
  49697. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  49698. ){
  49699. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  49700. Pgno iTab = 0;
  49701. BtLock *pLock;
  49702. /* If this database is not shareable, or if the client is reading
  49703. ** and has the read-uncommitted flag set, then no lock is required.
  49704. ** Return true immediately.
  49705. */
  49706. if( (pBtree->sharable==0)
  49707. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  49708. ){
  49709. return 1;
  49710. }
  49711. /* If the client is reading or writing an index and the schema is
  49712. ** not loaded, then it is too difficult to actually check to see if
  49713. ** the correct locks are held. So do not bother - just return true.
  49714. ** This case does not come up very often anyhow.
  49715. */
  49716. if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
  49717. return 1;
  49718. }
  49719. /* Figure out the root-page that the lock should be held on. For table
  49720. ** b-trees, this is just the root page of the b-tree being read or
  49721. ** written. For index b-trees, it is the root page of the associated
  49722. ** table. */
  49723. if( isIndex ){
  49724. HashElem *p;
  49725. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  49726. Index *pIdx = (Index *)sqliteHashData(p);
  49727. if( pIdx->tnum==(int)iRoot ){
  49728. iTab = pIdx->pTable->tnum;
  49729. }
  49730. }
  49731. }else{
  49732. iTab = iRoot;
  49733. }
  49734. /* Search for the required lock. Either a write-lock on root-page iTab, a
  49735. ** write-lock on the schema table, or (if the client is reading) a
  49736. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  49737. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  49738. if( pLock->pBtree==pBtree
  49739. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  49740. && pLock->eLock>=eLockType
  49741. ){
  49742. return 1;
  49743. }
  49744. }
  49745. /* Failed to find the required lock. */
  49746. return 0;
  49747. }
  49748. #endif /* SQLITE_DEBUG */
  49749. #ifdef SQLITE_DEBUG
  49750. /*
  49751. **** This function may be used as part of assert() statements only. ****
  49752. **
  49753. ** Return true if it would be illegal for pBtree to write into the
  49754. ** table or index rooted at iRoot because other shared connections are
  49755. ** simultaneously reading that same table or index.
  49756. **
  49757. ** It is illegal for pBtree to write if some other Btree object that
  49758. ** shares the same BtShared object is currently reading or writing
  49759. ** the iRoot table. Except, if the other Btree object has the
  49760. ** read-uncommitted flag set, then it is OK for the other object to
  49761. ** have a read cursor.
  49762. **
  49763. ** For example, before writing to any part of the table or index
  49764. ** rooted at page iRoot, one should call:
  49765. **
  49766. ** assert( !hasReadConflicts(pBtree, iRoot) );
  49767. */
  49768. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  49769. BtCursor *p;
  49770. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  49771. if( p->pgnoRoot==iRoot
  49772. && p->pBtree!=pBtree
  49773. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  49774. ){
  49775. return 1;
  49776. }
  49777. }
  49778. return 0;
  49779. }
  49780. #endif /* #ifdef SQLITE_DEBUG */
  49781. /*
  49782. ** Query to see if Btree handle p may obtain a lock of type eLock
  49783. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  49784. ** SQLITE_OK if the lock may be obtained (by calling
  49785. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  49786. */
  49787. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  49788. BtShared *pBt = p->pBt;
  49789. BtLock *pIter;
  49790. assert( sqlite3BtreeHoldsMutex(p) );
  49791. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49792. assert( p->db!=0 );
  49793. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  49794. /* If requesting a write-lock, then the Btree must have an open write
  49795. ** transaction on this file. And, obviously, for this to be so there
  49796. ** must be an open write transaction on the file itself.
  49797. */
  49798. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  49799. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  49800. /* This routine is a no-op if the shared-cache is not enabled */
  49801. if( !p->sharable ){
  49802. return SQLITE_OK;
  49803. }
  49804. /* If some other connection is holding an exclusive lock, the
  49805. ** requested lock may not be obtained.
  49806. */
  49807. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  49808. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  49809. return SQLITE_LOCKED_SHAREDCACHE;
  49810. }
  49811. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49812. /* The condition (pIter->eLock!=eLock) in the following if(...)
  49813. ** statement is a simplification of:
  49814. **
  49815. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  49816. **
  49817. ** since we know that if eLock==WRITE_LOCK, then no other connection
  49818. ** may hold a WRITE_LOCK on any table in this file (since there can
  49819. ** only be a single writer).
  49820. */
  49821. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  49822. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  49823. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  49824. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  49825. if( eLock==WRITE_LOCK ){
  49826. assert( p==pBt->pWriter );
  49827. pBt->btsFlags |= BTS_PENDING;
  49828. }
  49829. return SQLITE_LOCKED_SHAREDCACHE;
  49830. }
  49831. }
  49832. return SQLITE_OK;
  49833. }
  49834. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49835. #ifndef SQLITE_OMIT_SHARED_CACHE
  49836. /*
  49837. ** Add a lock on the table with root-page iTable to the shared-btree used
  49838. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  49839. ** WRITE_LOCK.
  49840. **
  49841. ** This function assumes the following:
  49842. **
  49843. ** (a) The specified Btree object p is connected to a sharable
  49844. ** database (one with the BtShared.sharable flag set), and
  49845. **
  49846. ** (b) No other Btree objects hold a lock that conflicts
  49847. ** with the requested lock (i.e. querySharedCacheTableLock() has
  49848. ** already been called and returned SQLITE_OK).
  49849. **
  49850. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  49851. ** is returned if a malloc attempt fails.
  49852. */
  49853. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  49854. BtShared *pBt = p->pBt;
  49855. BtLock *pLock = 0;
  49856. BtLock *pIter;
  49857. assert( sqlite3BtreeHoldsMutex(p) );
  49858. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  49859. assert( p->db!=0 );
  49860. /* A connection with the read-uncommitted flag set will never try to
  49861. ** obtain a read-lock using this function. The only read-lock obtained
  49862. ** by a connection in read-uncommitted mode is on the sqlite_master
  49863. ** table, and that lock is obtained in BtreeBeginTrans(). */
  49864. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  49865. /* This function should only be called on a sharable b-tree after it
  49866. ** has been determined that no other b-tree holds a conflicting lock. */
  49867. assert( p->sharable );
  49868. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  49869. /* First search the list for an existing lock on this table. */
  49870. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49871. if( pIter->iTable==iTable && pIter->pBtree==p ){
  49872. pLock = pIter;
  49873. break;
  49874. }
  49875. }
  49876. /* If the above search did not find a BtLock struct associating Btree p
  49877. ** with table iTable, allocate one and link it into the list.
  49878. */
  49879. if( !pLock ){
  49880. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  49881. if( !pLock ){
  49882. return SQLITE_NOMEM;
  49883. }
  49884. pLock->iTable = iTable;
  49885. pLock->pBtree = p;
  49886. pLock->pNext = pBt->pLock;
  49887. pBt->pLock = pLock;
  49888. }
  49889. /* Set the BtLock.eLock variable to the maximum of the current lock
  49890. ** and the requested lock. This means if a write-lock was already held
  49891. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  49892. */
  49893. assert( WRITE_LOCK>READ_LOCK );
  49894. if( eLock>pLock->eLock ){
  49895. pLock->eLock = eLock;
  49896. }
  49897. return SQLITE_OK;
  49898. }
  49899. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49900. #ifndef SQLITE_OMIT_SHARED_CACHE
  49901. /*
  49902. ** Release all the table locks (locks obtained via calls to
  49903. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  49904. **
  49905. ** This function assumes that Btree p has an open read or write
  49906. ** transaction. If it does not, then the BTS_PENDING flag
  49907. ** may be incorrectly cleared.
  49908. */
  49909. static void clearAllSharedCacheTableLocks(Btree *p){
  49910. BtShared *pBt = p->pBt;
  49911. BtLock **ppIter = &pBt->pLock;
  49912. assert( sqlite3BtreeHoldsMutex(p) );
  49913. assert( p->sharable || 0==*ppIter );
  49914. assert( p->inTrans>0 );
  49915. while( *ppIter ){
  49916. BtLock *pLock = *ppIter;
  49917. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  49918. assert( pLock->pBtree->inTrans>=pLock->eLock );
  49919. if( pLock->pBtree==p ){
  49920. *ppIter = pLock->pNext;
  49921. assert( pLock->iTable!=1 || pLock==&p->lock );
  49922. if( pLock->iTable!=1 ){
  49923. sqlite3_free(pLock);
  49924. }
  49925. }else{
  49926. ppIter = &pLock->pNext;
  49927. }
  49928. }
  49929. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  49930. if( pBt->pWriter==p ){
  49931. pBt->pWriter = 0;
  49932. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49933. }else if( pBt->nTransaction==2 ){
  49934. /* This function is called when Btree p is concluding its
  49935. ** transaction. If there currently exists a writer, and p is not
  49936. ** that writer, then the number of locks held by connections other
  49937. ** than the writer must be about to drop to zero. In this case
  49938. ** set the BTS_PENDING flag to 0.
  49939. **
  49940. ** If there is not currently a writer, then BTS_PENDING must
  49941. ** be zero already. So this next line is harmless in that case.
  49942. */
  49943. pBt->btsFlags &= ~BTS_PENDING;
  49944. }
  49945. }
  49946. /*
  49947. ** This function changes all write-locks held by Btree p into read-locks.
  49948. */
  49949. static void downgradeAllSharedCacheTableLocks(Btree *p){
  49950. BtShared *pBt = p->pBt;
  49951. if( pBt->pWriter==p ){
  49952. BtLock *pLock;
  49953. pBt->pWriter = 0;
  49954. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49955. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  49956. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  49957. pLock->eLock = READ_LOCK;
  49958. }
  49959. }
  49960. }
  49961. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49962. static void releasePage(MemPage *pPage); /* Forward reference */
  49963. /*
  49964. ***** This routine is used inside of assert() only ****
  49965. **
  49966. ** Verify that the cursor holds the mutex on its BtShared
  49967. */
  49968. #ifdef SQLITE_DEBUG
  49969. static int cursorHoldsMutex(BtCursor *p){
  49970. return sqlite3_mutex_held(p->pBt->mutex);
  49971. }
  49972. #endif
  49973. #ifndef SQLITE_OMIT_INCRBLOB
  49974. /*
  49975. ** Invalidate the overflow page-list cache for cursor pCur, if any.
  49976. */
  49977. static void invalidateOverflowCache(BtCursor *pCur){
  49978. assert( cursorHoldsMutex(pCur) );
  49979. sqlite3_free(pCur->aOverflow);
  49980. pCur->aOverflow = 0;
  49981. }
  49982. /*
  49983. ** Invalidate the overflow page-list cache for all cursors opened
  49984. ** on the shared btree structure pBt.
  49985. */
  49986. static void invalidateAllOverflowCache(BtShared *pBt){
  49987. BtCursor *p;
  49988. assert( sqlite3_mutex_held(pBt->mutex) );
  49989. for(p=pBt->pCursor; p; p=p->pNext){
  49990. invalidateOverflowCache(p);
  49991. }
  49992. }
  49993. /*
  49994. ** This function is called before modifying the contents of a table
  49995. ** to invalidate any incrblob cursors that are open on the
  49996. ** row or one of the rows being modified.
  49997. **
  49998. ** If argument isClearTable is true, then the entire contents of the
  49999. ** table is about to be deleted. In this case invalidate all incrblob
  50000. ** cursors open on any row within the table with root-page pgnoRoot.
  50001. **
  50002. ** Otherwise, if argument isClearTable is false, then the row with
  50003. ** rowid iRow is being replaced or deleted. In this case invalidate
  50004. ** only those incrblob cursors open on that specific row.
  50005. */
  50006. static void invalidateIncrblobCursors(
  50007. Btree *pBtree, /* The database file to check */
  50008. i64 iRow, /* The rowid that might be changing */
  50009. int isClearTable /* True if all rows are being deleted */
  50010. ){
  50011. BtCursor *p;
  50012. BtShared *pBt = pBtree->pBt;
  50013. assert( sqlite3BtreeHoldsMutex(pBtree) );
  50014. for(p=pBt->pCursor; p; p=p->pNext){
  50015. if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
  50016. p->eState = CURSOR_INVALID;
  50017. }
  50018. }
  50019. }
  50020. #else
  50021. /* Stub functions when INCRBLOB is omitted */
  50022. #define invalidateOverflowCache(x)
  50023. #define invalidateAllOverflowCache(x)
  50024. #define invalidateIncrblobCursors(x,y,z)
  50025. #endif /* SQLITE_OMIT_INCRBLOB */
  50026. /*
  50027. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  50028. ** when a page that previously contained data becomes a free-list leaf
  50029. ** page.
  50030. **
  50031. ** The BtShared.pHasContent bitvec exists to work around an obscure
  50032. ** bug caused by the interaction of two useful IO optimizations surrounding
  50033. ** free-list leaf pages:
  50034. **
  50035. ** 1) When all data is deleted from a page and the page becomes
  50036. ** a free-list leaf page, the page is not written to the database
  50037. ** (as free-list leaf pages contain no meaningful data). Sometimes
  50038. ** such a page is not even journalled (as it will not be modified,
  50039. ** why bother journalling it?).
  50040. **
  50041. ** 2) When a free-list leaf page is reused, its content is not read
  50042. ** from the database or written to the journal file (why should it
  50043. ** be, if it is not at all meaningful?).
  50044. **
  50045. ** By themselves, these optimizations work fine and provide a handy
  50046. ** performance boost to bulk delete or insert operations. However, if
  50047. ** a page is moved to the free-list and then reused within the same
  50048. ** transaction, a problem comes up. If the page is not journalled when
  50049. ** it is moved to the free-list and it is also not journalled when it
  50050. ** is extracted from the free-list and reused, then the original data
  50051. ** may be lost. In the event of a rollback, it may not be possible
  50052. ** to restore the database to its original configuration.
  50053. **
  50054. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  50055. ** moved to become a free-list leaf page, the corresponding bit is
  50056. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  50057. ** optimization 2 above is omitted if the corresponding bit is already
  50058. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  50059. ** at the end of every transaction.
  50060. */
  50061. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  50062. int rc = SQLITE_OK;
  50063. if( !pBt->pHasContent ){
  50064. assert( pgno<=pBt->nPage );
  50065. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  50066. if( !pBt->pHasContent ){
  50067. rc = SQLITE_NOMEM;
  50068. }
  50069. }
  50070. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  50071. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  50072. }
  50073. return rc;
  50074. }
  50075. /*
  50076. ** Query the BtShared.pHasContent vector.
  50077. **
  50078. ** This function is called when a free-list leaf page is removed from the
  50079. ** free-list for reuse. It returns false if it is safe to retrieve the
  50080. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  50081. */
  50082. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  50083. Bitvec *p = pBt->pHasContent;
  50084. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  50085. }
  50086. /*
  50087. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  50088. ** invoked at the conclusion of each write-transaction.
  50089. */
  50090. static void btreeClearHasContent(BtShared *pBt){
  50091. sqlite3BitvecDestroy(pBt->pHasContent);
  50092. pBt->pHasContent = 0;
  50093. }
  50094. /*
  50095. ** Release all of the apPage[] pages for a cursor.
  50096. */
  50097. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  50098. int i;
  50099. for(i=0; i<=pCur->iPage; i++){
  50100. releasePage(pCur->apPage[i]);
  50101. pCur->apPage[i] = 0;
  50102. }
  50103. pCur->iPage = -1;
  50104. }
  50105. /*
  50106. ** Save the current cursor position in the variables BtCursor.nKey
  50107. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  50108. **
  50109. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  50110. ** prior to calling this routine.
  50111. */
  50112. static int saveCursorPosition(BtCursor *pCur){
  50113. int rc;
  50114. assert( CURSOR_VALID==pCur->eState );
  50115. assert( 0==pCur->pKey );
  50116. assert( cursorHoldsMutex(pCur) );
  50117. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  50118. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  50119. /* If this is an intKey table, then the above call to BtreeKeySize()
  50120. ** stores the integer key in pCur->nKey. In this case this value is
  50121. ** all that is required. Otherwise, if pCur is not open on an intKey
  50122. ** table, then malloc space for and store the pCur->nKey bytes of key
  50123. ** data.
  50124. */
  50125. if( 0==pCur->apPage[0]->intKey ){
  50126. void *pKey = sqlite3Malloc( (int)pCur->nKey );
  50127. if( pKey ){
  50128. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  50129. if( rc==SQLITE_OK ){
  50130. pCur->pKey = pKey;
  50131. }else{
  50132. sqlite3_free(pKey);
  50133. }
  50134. }else{
  50135. rc = SQLITE_NOMEM;
  50136. }
  50137. }
  50138. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  50139. if( rc==SQLITE_OK ){
  50140. btreeReleaseAllCursorPages(pCur);
  50141. pCur->eState = CURSOR_REQUIRESEEK;
  50142. }
  50143. invalidateOverflowCache(pCur);
  50144. return rc;
  50145. }
  50146. /*
  50147. ** Save the positions of all cursors (except pExcept) that are open on
  50148. ** the table with root-page iRoot. Usually, this is called just before cursor
  50149. ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
  50150. */
  50151. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  50152. BtCursor *p;
  50153. assert( sqlite3_mutex_held(pBt->mutex) );
  50154. assert( pExcept==0 || pExcept->pBt==pBt );
  50155. for(p=pBt->pCursor; p; p=p->pNext){
  50156. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  50157. if( p->eState==CURSOR_VALID ){
  50158. int rc = saveCursorPosition(p);
  50159. if( SQLITE_OK!=rc ){
  50160. return rc;
  50161. }
  50162. }else{
  50163. testcase( p->iPage>0 );
  50164. btreeReleaseAllCursorPages(p);
  50165. }
  50166. }
  50167. }
  50168. return SQLITE_OK;
  50169. }
  50170. /*
  50171. ** Clear the current cursor position.
  50172. */
  50173. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  50174. assert( cursorHoldsMutex(pCur) );
  50175. sqlite3_free(pCur->pKey);
  50176. pCur->pKey = 0;
  50177. pCur->eState = CURSOR_INVALID;
  50178. }
  50179. /*
  50180. ** In this version of BtreeMoveto, pKey is a packed index record
  50181. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  50182. ** record and then call BtreeMovetoUnpacked() to do the work.
  50183. */
  50184. static int btreeMoveto(
  50185. BtCursor *pCur, /* Cursor open on the btree to be searched */
  50186. const void *pKey, /* Packed key if the btree is an index */
  50187. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  50188. int bias, /* Bias search to the high end */
  50189. int *pRes /* Write search results here */
  50190. ){
  50191. int rc; /* Status code */
  50192. UnpackedRecord *pIdxKey; /* Unpacked index key */
  50193. char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
  50194. char *pFree = 0;
  50195. if( pKey ){
  50196. assert( nKey==(i64)(int)nKey );
  50197. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  50198. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  50199. );
  50200. if( pIdxKey==0 ) return SQLITE_NOMEM;
  50201. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  50202. }else{
  50203. pIdxKey = 0;
  50204. }
  50205. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  50206. if( pFree ){
  50207. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  50208. }
  50209. return rc;
  50210. }
  50211. /*
  50212. ** Restore the cursor to the position it was in (or as close to as possible)
  50213. ** when saveCursorPosition() was called. Note that this call deletes the
  50214. ** saved position info stored by saveCursorPosition(), so there can be
  50215. ** at most one effective restoreCursorPosition() call after each
  50216. ** saveCursorPosition().
  50217. */
  50218. static int btreeRestoreCursorPosition(BtCursor *pCur){
  50219. int rc;
  50220. assert( cursorHoldsMutex(pCur) );
  50221. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  50222. if( pCur->eState==CURSOR_FAULT ){
  50223. return pCur->skipNext;
  50224. }
  50225. pCur->eState = CURSOR_INVALID;
  50226. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  50227. if( rc==SQLITE_OK ){
  50228. sqlite3_free(pCur->pKey);
  50229. pCur->pKey = 0;
  50230. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  50231. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  50232. pCur->eState = CURSOR_SKIPNEXT;
  50233. }
  50234. }
  50235. return rc;
  50236. }
  50237. #define restoreCursorPosition(p) \
  50238. (p->eState>=CURSOR_REQUIRESEEK ? \
  50239. btreeRestoreCursorPosition(p) : \
  50240. SQLITE_OK)
  50241. /*
  50242. ** Determine whether or not a cursor has moved from the position it
  50243. ** was last placed at. Cursors can move when the row they are pointing
  50244. ** at is deleted out from under them.
  50245. **
  50246. ** This routine returns an error code if something goes wrong. The
  50247. ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
  50248. */
  50249. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
  50250. int rc;
  50251. rc = restoreCursorPosition(pCur);
  50252. if( rc ){
  50253. *pHasMoved = 1;
  50254. return rc;
  50255. }
  50256. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  50257. *pHasMoved = 1;
  50258. }else{
  50259. *pHasMoved = 0;
  50260. }
  50261. return SQLITE_OK;
  50262. }
  50263. #ifndef SQLITE_OMIT_AUTOVACUUM
  50264. /*
  50265. ** Given a page number of a regular database page, return the page
  50266. ** number for the pointer-map page that contains the entry for the
  50267. ** input page number.
  50268. **
  50269. ** Return 0 (not a valid page) for pgno==1 since there is
  50270. ** no pointer map associated with page 1. The integrity_check logic
  50271. ** requires that ptrmapPageno(*,1)!=1.
  50272. */
  50273. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  50274. int nPagesPerMapPage;
  50275. Pgno iPtrMap, ret;
  50276. assert( sqlite3_mutex_held(pBt->mutex) );
  50277. if( pgno<2 ) return 0;
  50278. nPagesPerMapPage = (pBt->usableSize/5)+1;
  50279. iPtrMap = (pgno-2)/nPagesPerMapPage;
  50280. ret = (iPtrMap*nPagesPerMapPage) + 2;
  50281. if( ret==PENDING_BYTE_PAGE(pBt) ){
  50282. ret++;
  50283. }
  50284. return ret;
  50285. }
  50286. /*
  50287. ** Write an entry into the pointer map.
  50288. **
  50289. ** This routine updates the pointer map entry for page number 'key'
  50290. ** so that it maps to type 'eType' and parent page number 'pgno'.
  50291. **
  50292. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  50293. ** a no-op. If an error occurs, the appropriate error code is written
  50294. ** into *pRC.
  50295. */
  50296. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  50297. DbPage *pDbPage; /* The pointer map page */
  50298. u8 *pPtrmap; /* The pointer map data */
  50299. Pgno iPtrmap; /* The pointer map page number */
  50300. int offset; /* Offset in pointer map page */
  50301. int rc; /* Return code from subfunctions */
  50302. if( *pRC ) return;
  50303. assert( sqlite3_mutex_held(pBt->mutex) );
  50304. /* The master-journal page number must never be used as a pointer map page */
  50305. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  50306. assert( pBt->autoVacuum );
  50307. if( key==0 ){
  50308. *pRC = SQLITE_CORRUPT_BKPT;
  50309. return;
  50310. }
  50311. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50312. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50313. if( rc!=SQLITE_OK ){
  50314. *pRC = rc;
  50315. return;
  50316. }
  50317. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50318. if( offset<0 ){
  50319. *pRC = SQLITE_CORRUPT_BKPT;
  50320. goto ptrmap_exit;
  50321. }
  50322. assert( offset <= (int)pBt->usableSize-5 );
  50323. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50324. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  50325. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  50326. *pRC= rc = sqlite3PagerWrite(pDbPage);
  50327. if( rc==SQLITE_OK ){
  50328. pPtrmap[offset] = eType;
  50329. put4byte(&pPtrmap[offset+1], parent);
  50330. }
  50331. }
  50332. ptrmap_exit:
  50333. sqlite3PagerUnref(pDbPage);
  50334. }
  50335. /*
  50336. ** Read an entry from the pointer map.
  50337. **
  50338. ** This routine retrieves the pointer map entry for page 'key', writing
  50339. ** the type and parent page number to *pEType and *pPgno respectively.
  50340. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  50341. */
  50342. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  50343. DbPage *pDbPage; /* The pointer map page */
  50344. int iPtrmap; /* Pointer map page index */
  50345. u8 *pPtrmap; /* Pointer map page data */
  50346. int offset; /* Offset of entry in pointer map */
  50347. int rc;
  50348. assert( sqlite3_mutex_held(pBt->mutex) );
  50349. iPtrmap = PTRMAP_PAGENO(pBt, key);
  50350. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  50351. if( rc!=0 ){
  50352. return rc;
  50353. }
  50354. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  50355. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  50356. if( offset<0 ){
  50357. sqlite3PagerUnref(pDbPage);
  50358. return SQLITE_CORRUPT_BKPT;
  50359. }
  50360. assert( offset <= (int)pBt->usableSize-5 );
  50361. assert( pEType!=0 );
  50362. *pEType = pPtrmap[offset];
  50363. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  50364. sqlite3PagerUnref(pDbPage);
  50365. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  50366. return SQLITE_OK;
  50367. }
  50368. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  50369. #define ptrmapPut(w,x,y,z,rc)
  50370. #define ptrmapGet(w,x,y,z) SQLITE_OK
  50371. #define ptrmapPutOvflPtr(x, y, rc)
  50372. #endif
  50373. /*
  50374. ** Given a btree page and a cell index (0 means the first cell on
  50375. ** the page, 1 means the second cell, and so forth) return a pointer
  50376. ** to the cell content.
  50377. **
  50378. ** This routine works only for pages that do not contain overflow cells.
  50379. */
  50380. #define findCell(P,I) \
  50381. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  50382. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  50383. /*
  50384. ** This a more complex version of findCell() that works for
  50385. ** pages that do contain overflow cells.
  50386. */
  50387. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  50388. int i;
  50389. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50390. for(i=pPage->nOverflow-1; i>=0; i--){
  50391. int k;
  50392. k = pPage->aiOvfl[i];
  50393. if( k<=iCell ){
  50394. if( k==iCell ){
  50395. return pPage->apOvfl[i];
  50396. }
  50397. iCell--;
  50398. }
  50399. }
  50400. return findCell(pPage, iCell);
  50401. }
  50402. /*
  50403. ** Parse a cell content block and fill in the CellInfo structure. There
  50404. ** are two versions of this function. btreeParseCell() takes a
  50405. ** cell index as the second argument and btreeParseCellPtr()
  50406. ** takes a pointer to the body of the cell as its second argument.
  50407. **
  50408. ** Within this file, the parseCell() macro can be called instead of
  50409. ** btreeParseCellPtr(). Using some compilers, this will be faster.
  50410. */
  50411. static void btreeParseCellPtr(
  50412. MemPage *pPage, /* Page containing the cell */
  50413. u8 *pCell, /* Pointer to the cell text. */
  50414. CellInfo *pInfo /* Fill in this structure */
  50415. ){
  50416. u16 n; /* Number bytes in cell content header */
  50417. u32 nPayload; /* Number of bytes of cell payload */
  50418. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50419. pInfo->pCell = pCell;
  50420. assert( pPage->leaf==0 || pPage->leaf==1 );
  50421. n = pPage->childPtrSize;
  50422. assert( n==4-4*pPage->leaf );
  50423. if( pPage->intKey ){
  50424. if( pPage->hasData ){
  50425. assert( n==0 );
  50426. n = getVarint32(pCell, nPayload);
  50427. }else{
  50428. nPayload = 0;
  50429. }
  50430. n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
  50431. pInfo->nData = nPayload;
  50432. }else{
  50433. pInfo->nData = 0;
  50434. n += getVarint32(&pCell[n], nPayload);
  50435. pInfo->nKey = nPayload;
  50436. }
  50437. pInfo->nPayload = nPayload;
  50438. pInfo->nHeader = n;
  50439. testcase( nPayload==pPage->maxLocal );
  50440. testcase( nPayload==pPage->maxLocal+1 );
  50441. if( likely(nPayload<=pPage->maxLocal) ){
  50442. /* This is the (easy) common case where the entire payload fits
  50443. ** on the local page. No overflow is required.
  50444. */
  50445. if( (pInfo->nSize = (u16)(n+nPayload))<4 ) pInfo->nSize = 4;
  50446. pInfo->nLocal = (u16)nPayload;
  50447. pInfo->iOverflow = 0;
  50448. }else{
  50449. /* If the payload will not fit completely on the local page, we have
  50450. ** to decide how much to store locally and how much to spill onto
  50451. ** overflow pages. The strategy is to minimize the amount of unused
  50452. ** space on overflow pages while keeping the amount of local storage
  50453. ** in between minLocal and maxLocal.
  50454. **
  50455. ** Warning: changing the way overflow payload is distributed in any
  50456. ** way will result in an incompatible file format.
  50457. */
  50458. int minLocal; /* Minimum amount of payload held locally */
  50459. int maxLocal; /* Maximum amount of payload held locally */
  50460. int surplus; /* Overflow payload available for local storage */
  50461. minLocal = pPage->minLocal;
  50462. maxLocal = pPage->maxLocal;
  50463. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  50464. testcase( surplus==maxLocal );
  50465. testcase( surplus==maxLocal+1 );
  50466. if( surplus <= maxLocal ){
  50467. pInfo->nLocal = (u16)surplus;
  50468. }else{
  50469. pInfo->nLocal = (u16)minLocal;
  50470. }
  50471. pInfo->iOverflow = (u16)(pInfo->nLocal + n);
  50472. pInfo->nSize = pInfo->iOverflow + 4;
  50473. }
  50474. }
  50475. #define parseCell(pPage, iCell, pInfo) \
  50476. btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
  50477. static void btreeParseCell(
  50478. MemPage *pPage, /* Page containing the cell */
  50479. int iCell, /* The cell index. First cell is 0 */
  50480. CellInfo *pInfo /* Fill in this structure */
  50481. ){
  50482. parseCell(pPage, iCell, pInfo);
  50483. }
  50484. /*
  50485. ** Compute the total number of bytes that a Cell needs in the cell
  50486. ** data area of the btree-page. The return number includes the cell
  50487. ** data header and the local payload, but not any overflow page or
  50488. ** the space used by the cell pointer.
  50489. */
  50490. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  50491. u8 *pIter = &pCell[pPage->childPtrSize];
  50492. u32 nSize;
  50493. #ifdef SQLITE_DEBUG
  50494. /* The value returned by this function should always be the same as
  50495. ** the (CellInfo.nSize) value found by doing a full parse of the
  50496. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  50497. ** this function verifies that this invariant is not violated. */
  50498. CellInfo debuginfo;
  50499. btreeParseCellPtr(pPage, pCell, &debuginfo);
  50500. #endif
  50501. if( pPage->intKey ){
  50502. u8 *pEnd;
  50503. if( pPage->hasData ){
  50504. pIter += getVarint32(pIter, nSize);
  50505. }else{
  50506. nSize = 0;
  50507. }
  50508. /* pIter now points at the 64-bit integer key value, a variable length
  50509. ** integer. The following block moves pIter to point at the first byte
  50510. ** past the end of the key value. */
  50511. pEnd = &pIter[9];
  50512. while( (*pIter++)&0x80 && pIter<pEnd );
  50513. }else{
  50514. pIter += getVarint32(pIter, nSize);
  50515. }
  50516. testcase( nSize==pPage->maxLocal );
  50517. testcase( nSize==pPage->maxLocal+1 );
  50518. if( nSize>pPage->maxLocal ){
  50519. int minLocal = pPage->minLocal;
  50520. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  50521. testcase( nSize==pPage->maxLocal );
  50522. testcase( nSize==pPage->maxLocal+1 );
  50523. if( nSize>pPage->maxLocal ){
  50524. nSize = minLocal;
  50525. }
  50526. nSize += 4;
  50527. }
  50528. nSize += (u32)(pIter - pCell);
  50529. /* The minimum size of any cell is 4 bytes. */
  50530. if( nSize<4 ){
  50531. nSize = 4;
  50532. }
  50533. assert( nSize==debuginfo.nSize );
  50534. return (u16)nSize;
  50535. }
  50536. #ifdef SQLITE_DEBUG
  50537. /* This variation on cellSizePtr() is used inside of assert() statements
  50538. ** only. */
  50539. static u16 cellSize(MemPage *pPage, int iCell){
  50540. return cellSizePtr(pPage, findCell(pPage, iCell));
  50541. }
  50542. #endif
  50543. #ifndef SQLITE_OMIT_AUTOVACUUM
  50544. /*
  50545. ** If the cell pCell, part of page pPage contains a pointer
  50546. ** to an overflow page, insert an entry into the pointer-map
  50547. ** for the overflow page.
  50548. */
  50549. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  50550. CellInfo info;
  50551. if( *pRC ) return;
  50552. assert( pCell!=0 );
  50553. btreeParseCellPtr(pPage, pCell, &info);
  50554. assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
  50555. if( info.iOverflow ){
  50556. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  50557. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  50558. }
  50559. }
  50560. #endif
  50561. /*
  50562. ** Defragment the page given. All Cells are moved to the
  50563. ** end of the page and all free space is collected into one
  50564. ** big FreeBlk that occurs in between the header and cell
  50565. ** pointer array and the cell content area.
  50566. */
  50567. static int defragmentPage(MemPage *pPage){
  50568. int i; /* Loop counter */
  50569. int pc; /* Address of a i-th cell */
  50570. int hdr; /* Offset to the page header */
  50571. int size; /* Size of a cell */
  50572. int usableSize; /* Number of usable bytes on a page */
  50573. int cellOffset; /* Offset to the cell pointer array */
  50574. int cbrk; /* Offset to the cell content area */
  50575. int nCell; /* Number of cells on the page */
  50576. unsigned char *data; /* The page data */
  50577. unsigned char *temp; /* Temp area for cell content */
  50578. int iCellFirst; /* First allowable cell index */
  50579. int iCellLast; /* Last possible cell index */
  50580. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50581. assert( pPage->pBt!=0 );
  50582. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  50583. assert( pPage->nOverflow==0 );
  50584. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50585. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  50586. data = pPage->aData;
  50587. hdr = pPage->hdrOffset;
  50588. cellOffset = pPage->cellOffset;
  50589. nCell = pPage->nCell;
  50590. assert( nCell==get2byte(&data[hdr+3]) );
  50591. usableSize = pPage->pBt->usableSize;
  50592. cbrk = get2byte(&data[hdr+5]);
  50593. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  50594. cbrk = usableSize;
  50595. iCellFirst = cellOffset + 2*nCell;
  50596. iCellLast = usableSize - 4;
  50597. for(i=0; i<nCell; i++){
  50598. u8 *pAddr; /* The i-th cell pointer */
  50599. pAddr = &data[cellOffset + i*2];
  50600. pc = get2byte(pAddr);
  50601. testcase( pc==iCellFirst );
  50602. testcase( pc==iCellLast );
  50603. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50604. /* These conditions have already been verified in btreeInitPage()
  50605. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  50606. */
  50607. if( pc<iCellFirst || pc>iCellLast ){
  50608. return SQLITE_CORRUPT_BKPT;
  50609. }
  50610. #endif
  50611. assert( pc>=iCellFirst && pc<=iCellLast );
  50612. size = cellSizePtr(pPage, &temp[pc]);
  50613. cbrk -= size;
  50614. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50615. if( cbrk<iCellFirst ){
  50616. return SQLITE_CORRUPT_BKPT;
  50617. }
  50618. #else
  50619. if( cbrk<iCellFirst || pc+size>usableSize ){
  50620. return SQLITE_CORRUPT_BKPT;
  50621. }
  50622. #endif
  50623. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  50624. testcase( cbrk+size==usableSize );
  50625. testcase( pc+size==usableSize );
  50626. memcpy(&data[cbrk], &temp[pc], size);
  50627. put2byte(pAddr, cbrk);
  50628. }
  50629. assert( cbrk>=iCellFirst );
  50630. put2byte(&data[hdr+5], cbrk);
  50631. data[hdr+1] = 0;
  50632. data[hdr+2] = 0;
  50633. data[hdr+7] = 0;
  50634. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  50635. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50636. if( cbrk-iCellFirst!=pPage->nFree ){
  50637. return SQLITE_CORRUPT_BKPT;
  50638. }
  50639. return SQLITE_OK;
  50640. }
  50641. /*
  50642. ** Allocate nByte bytes of space from within the B-Tree page passed
  50643. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  50644. ** of the first byte of allocated space. Return either SQLITE_OK or
  50645. ** an error code (usually SQLITE_CORRUPT).
  50646. **
  50647. ** The caller guarantees that there is sufficient space to make the
  50648. ** allocation. This routine might need to defragment in order to bring
  50649. ** all the space together, however. This routine will avoid using
  50650. ** the first two bytes past the cell pointer area since presumably this
  50651. ** allocation is being made in order to insert a new cell, so we will
  50652. ** also end up needing a new cell pointer.
  50653. */
  50654. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  50655. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  50656. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  50657. int nFrag; /* Number of fragmented bytes on pPage */
  50658. int top; /* First byte of cell content area */
  50659. int gap; /* First byte of gap between cell pointers and cell content */
  50660. int rc; /* Integer return code */
  50661. int usableSize; /* Usable size of the page */
  50662. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50663. assert( pPage->pBt );
  50664. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50665. assert( nByte>=0 ); /* Minimum cell size is 4 */
  50666. assert( pPage->nFree>=nByte );
  50667. assert( pPage->nOverflow==0 );
  50668. usableSize = pPage->pBt->usableSize;
  50669. assert( nByte < usableSize-8 );
  50670. nFrag = data[hdr+7];
  50671. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  50672. gap = pPage->cellOffset + 2*pPage->nCell;
  50673. top = get2byteNotZero(&data[hdr+5]);
  50674. if( gap>top ) return SQLITE_CORRUPT_BKPT;
  50675. testcase( gap+2==top );
  50676. testcase( gap+1==top );
  50677. testcase( gap==top );
  50678. if( nFrag>=60 ){
  50679. /* Always defragment highly fragmented pages */
  50680. rc = defragmentPage(pPage);
  50681. if( rc ) return rc;
  50682. top = get2byteNotZero(&data[hdr+5]);
  50683. }else if( gap+2<=top ){
  50684. /* Search the freelist looking for a free slot big enough to satisfy
  50685. ** the request. The allocation is made from the first free slot in
  50686. ** the list that is large enough to accommodate it.
  50687. */
  50688. int pc, addr;
  50689. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  50690. int size; /* Size of the free slot */
  50691. if( pc>usableSize-4 || pc<addr+4 ){
  50692. return SQLITE_CORRUPT_BKPT;
  50693. }
  50694. size = get2byte(&data[pc+2]);
  50695. if( size>=nByte ){
  50696. int x = size - nByte;
  50697. testcase( x==4 );
  50698. testcase( x==3 );
  50699. if( x<4 ){
  50700. /* Remove the slot from the free-list. Update the number of
  50701. ** fragmented bytes within the page. */
  50702. memcpy(&data[addr], &data[pc], 2);
  50703. data[hdr+7] = (u8)(nFrag + x);
  50704. }else if( size+pc > usableSize ){
  50705. return SQLITE_CORRUPT_BKPT;
  50706. }else{
  50707. /* The slot remains on the free-list. Reduce its size to account
  50708. ** for the portion used by the new allocation. */
  50709. put2byte(&data[pc+2], x);
  50710. }
  50711. *pIdx = pc + x;
  50712. return SQLITE_OK;
  50713. }
  50714. }
  50715. }
  50716. /* Check to make sure there is enough space in the gap to satisfy
  50717. ** the allocation. If not, defragment.
  50718. */
  50719. testcase( gap+2+nByte==top );
  50720. if( gap+2+nByte>top ){
  50721. rc = defragmentPage(pPage);
  50722. if( rc ) return rc;
  50723. top = get2byteNotZero(&data[hdr+5]);
  50724. assert( gap+nByte<=top );
  50725. }
  50726. /* Allocate memory from the gap in between the cell pointer array
  50727. ** and the cell content area. The btreeInitPage() call has already
  50728. ** validated the freelist. Given that the freelist is valid, there
  50729. ** is no way that the allocation can extend off the end of the page.
  50730. ** The assert() below verifies the previous sentence.
  50731. */
  50732. top -= nByte;
  50733. put2byte(&data[hdr+5], top);
  50734. assert( top+nByte <= (int)pPage->pBt->usableSize );
  50735. *pIdx = top;
  50736. return SQLITE_OK;
  50737. }
  50738. /*
  50739. ** Return a section of the pPage->aData to the freelist.
  50740. ** The first byte of the new free block is pPage->aDisk[start]
  50741. ** and the size of the block is "size" bytes.
  50742. **
  50743. ** Most of the effort here is involved in coalesing adjacent
  50744. ** free blocks into a single big free block.
  50745. */
  50746. static int freeSpace(MemPage *pPage, int start, int size){
  50747. int addr, pbegin, hdr;
  50748. int iLast; /* Largest possible freeblock offset */
  50749. unsigned char *data = pPage->aData;
  50750. assert( pPage->pBt!=0 );
  50751. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50752. assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
  50753. assert( (start + size) <= (int)pPage->pBt->usableSize );
  50754. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50755. assert( size>=0 ); /* Minimum cell size is 4 */
  50756. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  50757. /* Overwrite deleted information with zeros when the secure_delete
  50758. ** option is enabled */
  50759. memset(&data[start], 0, size);
  50760. }
  50761. /* Add the space back into the linked list of freeblocks. Note that
  50762. ** even though the freeblock list was checked by btreeInitPage(),
  50763. ** btreeInitPage() did not detect overlapping cells or
  50764. ** freeblocks that overlapped cells. Nor does it detect when the
  50765. ** cell content area exceeds the value in the page header. If these
  50766. ** situations arise, then subsequent insert operations might corrupt
  50767. ** the freelist. So we do need to check for corruption while scanning
  50768. ** the freelist.
  50769. */
  50770. hdr = pPage->hdrOffset;
  50771. addr = hdr + 1;
  50772. iLast = pPage->pBt->usableSize - 4;
  50773. assert( start<=iLast );
  50774. while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
  50775. if( pbegin<addr+4 ){
  50776. return SQLITE_CORRUPT_BKPT;
  50777. }
  50778. addr = pbegin;
  50779. }
  50780. if( pbegin>iLast ){
  50781. return SQLITE_CORRUPT_BKPT;
  50782. }
  50783. assert( pbegin>addr || pbegin==0 );
  50784. put2byte(&data[addr], start);
  50785. put2byte(&data[start], pbegin);
  50786. put2byte(&data[start+2], size);
  50787. pPage->nFree = pPage->nFree + (u16)size;
  50788. /* Coalesce adjacent free blocks */
  50789. addr = hdr + 1;
  50790. while( (pbegin = get2byte(&data[addr]))>0 ){
  50791. int pnext, psize, x;
  50792. assert( pbegin>addr );
  50793. assert( pbegin <= (int)pPage->pBt->usableSize-4 );
  50794. pnext = get2byte(&data[pbegin]);
  50795. psize = get2byte(&data[pbegin+2]);
  50796. if( pbegin + psize + 3 >= pnext && pnext>0 ){
  50797. int frag = pnext - (pbegin+psize);
  50798. if( (frag<0) || (frag>(int)data[hdr+7]) ){
  50799. return SQLITE_CORRUPT_BKPT;
  50800. }
  50801. data[hdr+7] -= (u8)frag;
  50802. x = get2byte(&data[pnext]);
  50803. put2byte(&data[pbegin], x);
  50804. x = pnext + get2byte(&data[pnext+2]) - pbegin;
  50805. put2byte(&data[pbegin+2], x);
  50806. }else{
  50807. addr = pbegin;
  50808. }
  50809. }
  50810. /* If the cell content area begins with a freeblock, remove it. */
  50811. if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
  50812. int top;
  50813. pbegin = get2byte(&data[hdr+1]);
  50814. memcpy(&data[hdr+1], &data[pbegin], 2);
  50815. top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
  50816. put2byte(&data[hdr+5], top);
  50817. }
  50818. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50819. return SQLITE_OK;
  50820. }
  50821. /*
  50822. ** Decode the flags byte (the first byte of the header) for a page
  50823. ** and initialize fields of the MemPage structure accordingly.
  50824. **
  50825. ** Only the following combinations are supported. Anything different
  50826. ** indicates a corrupt database files:
  50827. **
  50828. ** PTF_ZERODATA
  50829. ** PTF_ZERODATA | PTF_LEAF
  50830. ** PTF_LEAFDATA | PTF_INTKEY
  50831. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  50832. */
  50833. static int decodeFlags(MemPage *pPage, int flagByte){
  50834. BtShared *pBt; /* A copy of pPage->pBt */
  50835. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  50836. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50837. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  50838. flagByte &= ~PTF_LEAF;
  50839. pPage->childPtrSize = 4-4*pPage->leaf;
  50840. pBt = pPage->pBt;
  50841. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  50842. pPage->intKey = 1;
  50843. pPage->hasData = pPage->leaf;
  50844. pPage->maxLocal = pBt->maxLeaf;
  50845. pPage->minLocal = pBt->minLeaf;
  50846. }else if( flagByte==PTF_ZERODATA ){
  50847. pPage->intKey = 0;
  50848. pPage->hasData = 0;
  50849. pPage->maxLocal = pBt->maxLocal;
  50850. pPage->minLocal = pBt->minLocal;
  50851. }else{
  50852. return SQLITE_CORRUPT_BKPT;
  50853. }
  50854. pPage->max1bytePayload = pBt->max1bytePayload;
  50855. return SQLITE_OK;
  50856. }
  50857. /*
  50858. ** Initialize the auxiliary information for a disk block.
  50859. **
  50860. ** Return SQLITE_OK on success. If we see that the page does
  50861. ** not contain a well-formed database page, then return
  50862. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  50863. ** guarantee that the page is well-formed. It only shows that
  50864. ** we failed to detect any corruption.
  50865. */
  50866. static int btreeInitPage(MemPage *pPage){
  50867. assert( pPage->pBt!=0 );
  50868. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50869. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  50870. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  50871. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  50872. if( !pPage->isInit ){
  50873. u16 pc; /* Address of a freeblock within pPage->aData[] */
  50874. u8 hdr; /* Offset to beginning of page header */
  50875. u8 *data; /* Equal to pPage->aData */
  50876. BtShared *pBt; /* The main btree structure */
  50877. int usableSize; /* Amount of usable space on each page */
  50878. u16 cellOffset; /* Offset from start of page to first cell pointer */
  50879. int nFree; /* Number of unused bytes on the page */
  50880. int top; /* First byte of the cell content area */
  50881. int iCellFirst; /* First allowable cell or freeblock offset */
  50882. int iCellLast; /* Last possible cell or freeblock offset */
  50883. pBt = pPage->pBt;
  50884. hdr = pPage->hdrOffset;
  50885. data = pPage->aData;
  50886. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  50887. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50888. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50889. pPage->nOverflow = 0;
  50890. usableSize = pBt->usableSize;
  50891. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  50892. pPage->aDataEnd = &data[usableSize];
  50893. pPage->aCellIdx = &data[cellOffset];
  50894. top = get2byteNotZero(&data[hdr+5]);
  50895. pPage->nCell = get2byte(&data[hdr+3]);
  50896. if( pPage->nCell>MX_CELL(pBt) ){
  50897. /* To many cells for a single page. The page must be corrupt */
  50898. return SQLITE_CORRUPT_BKPT;
  50899. }
  50900. testcase( pPage->nCell==MX_CELL(pBt) );
  50901. /* A malformed database page might cause us to read past the end
  50902. ** of page when parsing a cell.
  50903. **
  50904. ** The following block of code checks early to see if a cell extends
  50905. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  50906. ** returned if it does.
  50907. */
  50908. iCellFirst = cellOffset + 2*pPage->nCell;
  50909. iCellLast = usableSize - 4;
  50910. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50911. {
  50912. int i; /* Index into the cell pointer array */
  50913. int sz; /* Size of a cell */
  50914. if( !pPage->leaf ) iCellLast--;
  50915. for(i=0; i<pPage->nCell; i++){
  50916. pc = get2byte(&data[cellOffset+i*2]);
  50917. testcase( pc==iCellFirst );
  50918. testcase( pc==iCellLast );
  50919. if( pc<iCellFirst || pc>iCellLast ){
  50920. return SQLITE_CORRUPT_BKPT;
  50921. }
  50922. sz = cellSizePtr(pPage, &data[pc]);
  50923. testcase( pc+sz==usableSize );
  50924. if( pc+sz>usableSize ){
  50925. return SQLITE_CORRUPT_BKPT;
  50926. }
  50927. }
  50928. if( !pPage->leaf ) iCellLast++;
  50929. }
  50930. #endif
  50931. /* Compute the total free space on the page */
  50932. pc = get2byte(&data[hdr+1]);
  50933. nFree = data[hdr+7] + top;
  50934. while( pc>0 ){
  50935. u16 next, size;
  50936. if( pc<iCellFirst || pc>iCellLast ){
  50937. /* Start of free block is off the page */
  50938. return SQLITE_CORRUPT_BKPT;
  50939. }
  50940. next = get2byte(&data[pc]);
  50941. size = get2byte(&data[pc+2]);
  50942. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  50943. /* Free blocks must be in ascending order. And the last byte of
  50944. ** the free-block must lie on the database page. */
  50945. return SQLITE_CORRUPT_BKPT;
  50946. }
  50947. nFree = nFree + size;
  50948. pc = next;
  50949. }
  50950. /* At this point, nFree contains the sum of the offset to the start
  50951. ** of the cell-content area plus the number of free bytes within
  50952. ** the cell-content area. If this is greater than the usable-size
  50953. ** of the page, then the page must be corrupted. This check also
  50954. ** serves to verify that the offset to the start of the cell-content
  50955. ** area, according to the page header, lies within the page.
  50956. */
  50957. if( nFree>usableSize ){
  50958. return SQLITE_CORRUPT_BKPT;
  50959. }
  50960. pPage->nFree = (u16)(nFree - iCellFirst);
  50961. pPage->isInit = 1;
  50962. }
  50963. return SQLITE_OK;
  50964. }
  50965. /*
  50966. ** Set up a raw page so that it looks like a database page holding
  50967. ** no entries.
  50968. */
  50969. static void zeroPage(MemPage *pPage, int flags){
  50970. unsigned char *data = pPage->aData;
  50971. BtShared *pBt = pPage->pBt;
  50972. u8 hdr = pPage->hdrOffset;
  50973. u16 first;
  50974. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  50975. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50976. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  50977. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50978. assert( sqlite3_mutex_held(pBt->mutex) );
  50979. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  50980. memset(&data[hdr], 0, pBt->usableSize - hdr);
  50981. }
  50982. data[hdr] = (char)flags;
  50983. first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
  50984. memset(&data[hdr+1], 0, 4);
  50985. data[hdr+7] = 0;
  50986. put2byte(&data[hdr+5], pBt->usableSize);
  50987. pPage->nFree = (u16)(pBt->usableSize - first);
  50988. decodeFlags(pPage, flags);
  50989. pPage->hdrOffset = hdr;
  50990. pPage->cellOffset = first;
  50991. pPage->aDataEnd = &data[pBt->usableSize];
  50992. pPage->aCellIdx = &data[first];
  50993. pPage->nOverflow = 0;
  50994. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50995. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50996. pPage->nCell = 0;
  50997. pPage->isInit = 1;
  50998. }
  50999. /*
  51000. ** Convert a DbPage obtained from the pager into a MemPage used by
  51001. ** the btree layer.
  51002. */
  51003. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  51004. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  51005. pPage->aData = sqlite3PagerGetData(pDbPage);
  51006. pPage->pDbPage = pDbPage;
  51007. pPage->pBt = pBt;
  51008. pPage->pgno = pgno;
  51009. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  51010. return pPage;
  51011. }
  51012. /*
  51013. ** Get a page from the pager. Initialize the MemPage.pBt and
  51014. ** MemPage.aData elements if needed.
  51015. **
  51016. ** If the noContent flag is set, it means that we do not care about
  51017. ** the content of the page at this time. So do not go to the disk
  51018. ** to fetch the content. Just fill in the content with zeros for now.
  51019. ** If in the future we call sqlite3PagerWrite() on this page, that
  51020. ** means we have started to be concerned about content and the disk
  51021. ** read should occur at that point.
  51022. */
  51023. static int btreeGetPage(
  51024. BtShared *pBt, /* The btree */
  51025. Pgno pgno, /* Number of the page to fetch */
  51026. MemPage **ppPage, /* Return the page in this parameter */
  51027. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  51028. ){
  51029. int rc;
  51030. DbPage *pDbPage;
  51031. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  51032. assert( sqlite3_mutex_held(pBt->mutex) );
  51033. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  51034. if( rc ) return rc;
  51035. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  51036. return SQLITE_OK;
  51037. }
  51038. /*
  51039. ** Retrieve a page from the pager cache. If the requested page is not
  51040. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  51041. ** MemPage.aData elements if needed.
  51042. */
  51043. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  51044. DbPage *pDbPage;
  51045. assert( sqlite3_mutex_held(pBt->mutex) );
  51046. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  51047. if( pDbPage ){
  51048. return btreePageFromDbPage(pDbPage, pgno, pBt);
  51049. }
  51050. return 0;
  51051. }
  51052. /*
  51053. ** Return the size of the database file in pages. If there is any kind of
  51054. ** error, return ((unsigned int)-1).
  51055. */
  51056. static Pgno btreePagecount(BtShared *pBt){
  51057. return pBt->nPage;
  51058. }
  51059. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  51060. assert( sqlite3BtreeHoldsMutex(p) );
  51061. assert( ((p->pBt->nPage)&0x8000000)==0 );
  51062. return (int)btreePagecount(p->pBt);
  51063. }
  51064. /*
  51065. ** Get a page from the pager and initialize it. This routine is just a
  51066. ** convenience wrapper around separate calls to btreeGetPage() and
  51067. ** btreeInitPage().
  51068. **
  51069. ** If an error occurs, then the value *ppPage is set to is undefined. It
  51070. ** may remain unchanged, or it may be set to an invalid value.
  51071. */
  51072. static int getAndInitPage(
  51073. BtShared *pBt, /* The database file */
  51074. Pgno pgno, /* Number of the page to get */
  51075. MemPage **ppPage, /* Write the page pointer here */
  51076. int bReadonly /* PAGER_GET_READONLY or 0 */
  51077. ){
  51078. int rc;
  51079. assert( sqlite3_mutex_held(pBt->mutex) );
  51080. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  51081. if( pgno>btreePagecount(pBt) ){
  51082. rc = SQLITE_CORRUPT_BKPT;
  51083. }else{
  51084. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  51085. if( rc==SQLITE_OK ){
  51086. rc = btreeInitPage(*ppPage);
  51087. if( rc!=SQLITE_OK ){
  51088. releasePage(*ppPage);
  51089. }
  51090. }
  51091. }
  51092. testcase( pgno==0 );
  51093. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  51094. return rc;
  51095. }
  51096. /*
  51097. ** Release a MemPage. This should be called once for each prior
  51098. ** call to btreeGetPage.
  51099. */
  51100. static void releasePage(MemPage *pPage){
  51101. if( pPage ){
  51102. assert( pPage->aData );
  51103. assert( pPage->pBt );
  51104. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  51105. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  51106. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51107. sqlite3PagerUnref(pPage->pDbPage);
  51108. }
  51109. }
  51110. /*
  51111. ** During a rollback, when the pager reloads information into the cache
  51112. ** so that the cache is restored to its original state at the start of
  51113. ** the transaction, for each page restored this routine is called.
  51114. **
  51115. ** This routine needs to reset the extra data section at the end of the
  51116. ** page to agree with the restored data.
  51117. */
  51118. static void pageReinit(DbPage *pData){
  51119. MemPage *pPage;
  51120. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  51121. assert( sqlite3PagerPageRefcount(pData)>0 );
  51122. if( pPage->isInit ){
  51123. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51124. pPage->isInit = 0;
  51125. if( sqlite3PagerPageRefcount(pData)>1 ){
  51126. /* pPage might not be a btree page; it might be an overflow page
  51127. ** or ptrmap page or a free page. In those cases, the following
  51128. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  51129. ** But no harm is done by this. And it is very important that
  51130. ** btreeInitPage() be called on every btree page so we make
  51131. ** the call for every page that comes in for re-initing. */
  51132. btreeInitPage(pPage);
  51133. }
  51134. }
  51135. }
  51136. /*
  51137. ** Invoke the busy handler for a btree.
  51138. */
  51139. static int btreeInvokeBusyHandler(void *pArg){
  51140. BtShared *pBt = (BtShared*)pArg;
  51141. assert( pBt->db );
  51142. assert( sqlite3_mutex_held(pBt->db->mutex) );
  51143. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  51144. }
  51145. /*
  51146. ** Open a database file.
  51147. **
  51148. ** zFilename is the name of the database file. If zFilename is NULL
  51149. ** then an ephemeral database is created. The ephemeral database might
  51150. ** be exclusively in memory, or it might use a disk-based memory cache.
  51151. ** Either way, the ephemeral database will be automatically deleted
  51152. ** when sqlite3BtreeClose() is called.
  51153. **
  51154. ** If zFilename is ":memory:" then an in-memory database is created
  51155. ** that is automatically destroyed when it is closed.
  51156. **
  51157. ** The "flags" parameter is a bitmask that might contain bits like
  51158. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  51159. **
  51160. ** If the database is already opened in the same database connection
  51161. ** and we are in shared cache mode, then the open will fail with an
  51162. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  51163. ** objects in the same database connection since doing so will lead
  51164. ** to problems with locking.
  51165. */
  51166. SQLITE_PRIVATE int sqlite3BtreeOpen(
  51167. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  51168. const char *zFilename, /* Name of the file containing the BTree database */
  51169. sqlite3 *db, /* Associated database handle */
  51170. Btree **ppBtree, /* Pointer to new Btree object written here */
  51171. int flags, /* Options */
  51172. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  51173. ){
  51174. BtShared *pBt = 0; /* Shared part of btree structure */
  51175. Btree *p; /* Handle to return */
  51176. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  51177. int rc = SQLITE_OK; /* Result code from this function */
  51178. u8 nReserve; /* Byte of unused space on each page */
  51179. unsigned char zDbHeader[100]; /* Database header content */
  51180. /* True if opening an ephemeral, temporary database */
  51181. const int isTempDb = zFilename==0 || zFilename[0]==0;
  51182. /* Set the variable isMemdb to true for an in-memory database, or
  51183. ** false for a file-based database.
  51184. */
  51185. #ifdef SQLITE_OMIT_MEMORYDB
  51186. const int isMemdb = 0;
  51187. #else
  51188. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  51189. || (isTempDb && sqlite3TempInMemory(db))
  51190. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  51191. #endif
  51192. assert( db!=0 );
  51193. assert( pVfs!=0 );
  51194. assert( sqlite3_mutex_held(db->mutex) );
  51195. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  51196. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  51197. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  51198. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  51199. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  51200. if( isMemdb ){
  51201. flags |= BTREE_MEMORY;
  51202. }
  51203. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  51204. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  51205. }
  51206. p = sqlite3MallocZero(sizeof(Btree));
  51207. if( !p ){
  51208. return SQLITE_NOMEM;
  51209. }
  51210. p->inTrans = TRANS_NONE;
  51211. p->db = db;
  51212. #ifndef SQLITE_OMIT_SHARED_CACHE
  51213. p->lock.pBtree = p;
  51214. p->lock.iTable = 1;
  51215. #endif
  51216. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51217. /*
  51218. ** If this Btree is a candidate for shared cache, try to find an
  51219. ** existing BtShared object that we can share with
  51220. */
  51221. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  51222. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  51223. int nFullPathname = pVfs->mxPathname+1;
  51224. char *zFullPathname = sqlite3Malloc(nFullPathname);
  51225. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51226. p->sharable = 1;
  51227. if( !zFullPathname ){
  51228. sqlite3_free(p);
  51229. return SQLITE_NOMEM;
  51230. }
  51231. if( isMemdb ){
  51232. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  51233. }else{
  51234. rc = sqlite3OsFullPathname(pVfs, zFilename,
  51235. nFullPathname, zFullPathname);
  51236. if( rc ){
  51237. sqlite3_free(zFullPathname);
  51238. sqlite3_free(p);
  51239. return rc;
  51240. }
  51241. }
  51242. #if SQLITE_THREADSAFE
  51243. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  51244. sqlite3_mutex_enter(mutexOpen);
  51245. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  51246. sqlite3_mutex_enter(mutexShared);
  51247. #endif
  51248. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  51249. assert( pBt->nRef>0 );
  51250. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  51251. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  51252. int iDb;
  51253. for(iDb=db->nDb-1; iDb>=0; iDb--){
  51254. Btree *pExisting = db->aDb[iDb].pBt;
  51255. if( pExisting && pExisting->pBt==pBt ){
  51256. sqlite3_mutex_leave(mutexShared);
  51257. sqlite3_mutex_leave(mutexOpen);
  51258. sqlite3_free(zFullPathname);
  51259. sqlite3_free(p);
  51260. return SQLITE_CONSTRAINT;
  51261. }
  51262. }
  51263. p->pBt = pBt;
  51264. pBt->nRef++;
  51265. break;
  51266. }
  51267. }
  51268. sqlite3_mutex_leave(mutexShared);
  51269. sqlite3_free(zFullPathname);
  51270. }
  51271. #ifdef SQLITE_DEBUG
  51272. else{
  51273. /* In debug mode, we mark all persistent databases as sharable
  51274. ** even when they are not. This exercises the locking code and
  51275. ** gives more opportunity for asserts(sqlite3_mutex_held())
  51276. ** statements to find locking problems.
  51277. */
  51278. p->sharable = 1;
  51279. }
  51280. #endif
  51281. }
  51282. #endif
  51283. if( pBt==0 ){
  51284. /*
  51285. ** The following asserts make sure that structures used by the btree are
  51286. ** the right size. This is to guard against size changes that result
  51287. ** when compiling on a different architecture.
  51288. */
  51289. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  51290. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  51291. assert( sizeof(u32)==4 );
  51292. assert( sizeof(u16)==2 );
  51293. assert( sizeof(Pgno)==4 );
  51294. pBt = sqlite3MallocZero( sizeof(*pBt) );
  51295. if( pBt==0 ){
  51296. rc = SQLITE_NOMEM;
  51297. goto btree_open_out;
  51298. }
  51299. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  51300. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  51301. if( rc==SQLITE_OK ){
  51302. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  51303. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  51304. }
  51305. if( rc!=SQLITE_OK ){
  51306. goto btree_open_out;
  51307. }
  51308. pBt->openFlags = (u8)flags;
  51309. pBt->db = db;
  51310. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  51311. p->pBt = pBt;
  51312. pBt->pCursor = 0;
  51313. pBt->pPage1 = 0;
  51314. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  51315. #ifdef SQLITE_SECURE_DELETE
  51316. pBt->btsFlags |= BTS_SECURE_DELETE;
  51317. #endif
  51318. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  51319. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  51320. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  51321. pBt->pageSize = 0;
  51322. #ifndef SQLITE_OMIT_AUTOVACUUM
  51323. /* If the magic name ":memory:" will create an in-memory database, then
  51324. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  51325. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  51326. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  51327. ** regular file-name. In this case the auto-vacuum applies as per normal.
  51328. */
  51329. if( zFilename && !isMemdb ){
  51330. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  51331. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  51332. }
  51333. #endif
  51334. nReserve = 0;
  51335. }else{
  51336. nReserve = zDbHeader[20];
  51337. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51338. #ifndef SQLITE_OMIT_AUTOVACUUM
  51339. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  51340. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  51341. #endif
  51342. }
  51343. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51344. if( rc ) goto btree_open_out;
  51345. pBt->usableSize = pBt->pageSize - nReserve;
  51346. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  51347. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51348. /* Add the new BtShared object to the linked list sharable BtShareds.
  51349. */
  51350. if( p->sharable ){
  51351. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  51352. pBt->nRef = 1;
  51353. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  51354. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  51355. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  51356. if( pBt->mutex==0 ){
  51357. rc = SQLITE_NOMEM;
  51358. db->mallocFailed = 0;
  51359. goto btree_open_out;
  51360. }
  51361. }
  51362. sqlite3_mutex_enter(mutexShared);
  51363. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51364. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  51365. sqlite3_mutex_leave(mutexShared);
  51366. }
  51367. #endif
  51368. }
  51369. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  51370. /* If the new Btree uses a sharable pBtShared, then link the new
  51371. ** Btree into the list of all sharable Btrees for the same connection.
  51372. ** The list is kept in ascending order by pBt address.
  51373. */
  51374. if( p->sharable ){
  51375. int i;
  51376. Btree *pSib;
  51377. for(i=0; i<db->nDb; i++){
  51378. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  51379. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  51380. if( p->pBt<pSib->pBt ){
  51381. p->pNext = pSib;
  51382. p->pPrev = 0;
  51383. pSib->pPrev = p;
  51384. }else{
  51385. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  51386. pSib = pSib->pNext;
  51387. }
  51388. p->pNext = pSib->pNext;
  51389. p->pPrev = pSib;
  51390. if( p->pNext ){
  51391. p->pNext->pPrev = p;
  51392. }
  51393. pSib->pNext = p;
  51394. }
  51395. break;
  51396. }
  51397. }
  51398. }
  51399. #endif
  51400. *ppBtree = p;
  51401. btree_open_out:
  51402. if( rc!=SQLITE_OK ){
  51403. if( pBt && pBt->pPager ){
  51404. sqlite3PagerClose(pBt->pPager);
  51405. }
  51406. sqlite3_free(pBt);
  51407. sqlite3_free(p);
  51408. *ppBtree = 0;
  51409. }else{
  51410. /* If the B-Tree was successfully opened, set the pager-cache size to the
  51411. ** default value. Except, when opening on an existing shared pager-cache,
  51412. ** do not change the pager-cache size.
  51413. */
  51414. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  51415. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  51416. }
  51417. }
  51418. if( mutexOpen ){
  51419. assert( sqlite3_mutex_held(mutexOpen) );
  51420. sqlite3_mutex_leave(mutexOpen);
  51421. }
  51422. return rc;
  51423. }
  51424. /*
  51425. ** Decrement the BtShared.nRef counter. When it reaches zero,
  51426. ** remove the BtShared structure from the sharing list. Return
  51427. ** true if the BtShared.nRef counter reaches zero and return
  51428. ** false if it is still positive.
  51429. */
  51430. static int removeFromSharingList(BtShared *pBt){
  51431. #ifndef SQLITE_OMIT_SHARED_CACHE
  51432. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  51433. BtShared *pList;
  51434. int removed = 0;
  51435. assert( sqlite3_mutex_notheld(pBt->mutex) );
  51436. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  51437. sqlite3_mutex_enter(pMaster);
  51438. pBt->nRef--;
  51439. if( pBt->nRef<=0 ){
  51440. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  51441. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  51442. }else{
  51443. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  51444. while( ALWAYS(pList) && pList->pNext!=pBt ){
  51445. pList=pList->pNext;
  51446. }
  51447. if( ALWAYS(pList) ){
  51448. pList->pNext = pBt->pNext;
  51449. }
  51450. }
  51451. if( SQLITE_THREADSAFE ){
  51452. sqlite3_mutex_free(pBt->mutex);
  51453. }
  51454. removed = 1;
  51455. }
  51456. sqlite3_mutex_leave(pMaster);
  51457. return removed;
  51458. #else
  51459. return 1;
  51460. #endif
  51461. }
  51462. /*
  51463. ** Make sure pBt->pTmpSpace points to an allocation of
  51464. ** MX_CELL_SIZE(pBt) bytes.
  51465. */
  51466. static void allocateTempSpace(BtShared *pBt){
  51467. if( !pBt->pTmpSpace ){
  51468. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  51469. /* One of the uses of pBt->pTmpSpace is to format cells before
  51470. ** inserting them into a leaf page (function fillInCell()). If
  51471. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  51472. ** by the various routines that manipulate binary cells. Which
  51473. ** can mean that fillInCell() only initializes the first 2 or 3
  51474. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  51475. ** it into a database page. This is not actually a problem, but it
  51476. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  51477. ** data is passed to system call write(). So to avoid this error,
  51478. ** zero the first 4 bytes of temp space here. */
  51479. if( pBt->pTmpSpace ) memset(pBt->pTmpSpace, 0, 4);
  51480. }
  51481. }
  51482. /*
  51483. ** Free the pBt->pTmpSpace allocation
  51484. */
  51485. static void freeTempSpace(BtShared *pBt){
  51486. sqlite3PageFree( pBt->pTmpSpace);
  51487. pBt->pTmpSpace = 0;
  51488. }
  51489. /*
  51490. ** Close an open database and invalidate all cursors.
  51491. */
  51492. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  51493. BtShared *pBt = p->pBt;
  51494. BtCursor *pCur;
  51495. /* Close all cursors opened via this handle. */
  51496. assert( sqlite3_mutex_held(p->db->mutex) );
  51497. sqlite3BtreeEnter(p);
  51498. pCur = pBt->pCursor;
  51499. while( pCur ){
  51500. BtCursor *pTmp = pCur;
  51501. pCur = pCur->pNext;
  51502. if( pTmp->pBtree==p ){
  51503. sqlite3BtreeCloseCursor(pTmp);
  51504. }
  51505. }
  51506. /* Rollback any active transaction and free the handle structure.
  51507. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  51508. ** this handle.
  51509. */
  51510. sqlite3BtreeRollback(p, SQLITE_OK);
  51511. sqlite3BtreeLeave(p);
  51512. /* If there are still other outstanding references to the shared-btree
  51513. ** structure, return now. The remainder of this procedure cleans
  51514. ** up the shared-btree.
  51515. */
  51516. assert( p->wantToLock==0 && p->locked==0 );
  51517. if( !p->sharable || removeFromSharingList(pBt) ){
  51518. /* The pBt is no longer on the sharing list, so we can access
  51519. ** it without having to hold the mutex.
  51520. **
  51521. ** Clean out and delete the BtShared object.
  51522. */
  51523. assert( !pBt->pCursor );
  51524. sqlite3PagerClose(pBt->pPager);
  51525. if( pBt->xFreeSchema && pBt->pSchema ){
  51526. pBt->xFreeSchema(pBt->pSchema);
  51527. }
  51528. sqlite3DbFree(0, pBt->pSchema);
  51529. freeTempSpace(pBt);
  51530. sqlite3_free(pBt);
  51531. }
  51532. #ifndef SQLITE_OMIT_SHARED_CACHE
  51533. assert( p->wantToLock==0 );
  51534. assert( p->locked==0 );
  51535. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  51536. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  51537. #endif
  51538. sqlite3_free(p);
  51539. return SQLITE_OK;
  51540. }
  51541. /*
  51542. ** Change the limit on the number of pages allowed in the cache.
  51543. **
  51544. ** The maximum number of cache pages is set to the absolute
  51545. ** value of mxPage. If mxPage is negative, the pager will
  51546. ** operate asynchronously - it will not stop to do fsync()s
  51547. ** to insure data is written to the disk surface before
  51548. ** continuing. Transactions still work if synchronous is off,
  51549. ** and the database cannot be corrupted if this program
  51550. ** crashes. But if the operating system crashes or there is
  51551. ** an abrupt power failure when synchronous is off, the database
  51552. ** could be left in an inconsistent and unrecoverable state.
  51553. ** Synchronous is on by default so database corruption is not
  51554. ** normally a worry.
  51555. */
  51556. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  51557. BtShared *pBt = p->pBt;
  51558. assert( sqlite3_mutex_held(p->db->mutex) );
  51559. sqlite3BtreeEnter(p);
  51560. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  51561. sqlite3BtreeLeave(p);
  51562. return SQLITE_OK;
  51563. }
  51564. /*
  51565. ** Change the limit on the amount of the database file that may be
  51566. ** memory mapped.
  51567. */
  51568. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  51569. BtShared *pBt = p->pBt;
  51570. assert( sqlite3_mutex_held(p->db->mutex) );
  51571. sqlite3BtreeEnter(p);
  51572. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  51573. sqlite3BtreeLeave(p);
  51574. return SQLITE_OK;
  51575. }
  51576. /*
  51577. ** Change the way data is synced to disk in order to increase or decrease
  51578. ** how well the database resists damage due to OS crashes and power
  51579. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  51580. ** there is a high probability of damage) Level 2 is the default. There
  51581. ** is a very low but non-zero probability of damage. Level 3 reduces the
  51582. ** probability of damage to near zero but with a write performance reduction.
  51583. */
  51584. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  51585. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  51586. Btree *p, /* The btree to set the safety level on */
  51587. unsigned pgFlags /* Various PAGER_* flags */
  51588. ){
  51589. BtShared *pBt = p->pBt;
  51590. assert( sqlite3_mutex_held(p->db->mutex) );
  51591. sqlite3BtreeEnter(p);
  51592. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  51593. sqlite3BtreeLeave(p);
  51594. return SQLITE_OK;
  51595. }
  51596. #endif
  51597. /*
  51598. ** Return TRUE if the given btree is set to safety level 1. In other
  51599. ** words, return TRUE if no sync() occurs on the disk files.
  51600. */
  51601. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  51602. BtShared *pBt = p->pBt;
  51603. int rc;
  51604. assert( sqlite3_mutex_held(p->db->mutex) );
  51605. sqlite3BtreeEnter(p);
  51606. assert( pBt && pBt->pPager );
  51607. rc = sqlite3PagerNosync(pBt->pPager);
  51608. sqlite3BtreeLeave(p);
  51609. return rc;
  51610. }
  51611. /*
  51612. ** Change the default pages size and the number of reserved bytes per page.
  51613. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  51614. ** without changing anything.
  51615. **
  51616. ** The page size must be a power of 2 between 512 and 65536. If the page
  51617. ** size supplied does not meet this constraint then the page size is not
  51618. ** changed.
  51619. **
  51620. ** Page sizes are constrained to be a power of two so that the region
  51621. ** of the database file used for locking (beginning at PENDING_BYTE,
  51622. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  51623. ** at the beginning of a page.
  51624. **
  51625. ** If parameter nReserve is less than zero, then the number of reserved
  51626. ** bytes per page is left unchanged.
  51627. **
  51628. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  51629. ** and autovacuum mode can no longer be changed.
  51630. */
  51631. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  51632. int rc = SQLITE_OK;
  51633. BtShared *pBt = p->pBt;
  51634. assert( nReserve>=-1 && nReserve<=255 );
  51635. sqlite3BtreeEnter(p);
  51636. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  51637. sqlite3BtreeLeave(p);
  51638. return SQLITE_READONLY;
  51639. }
  51640. if( nReserve<0 ){
  51641. nReserve = pBt->pageSize - pBt->usableSize;
  51642. }
  51643. assert( nReserve>=0 && nReserve<=255 );
  51644. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  51645. ((pageSize-1)&pageSize)==0 ){
  51646. assert( (pageSize & 7)==0 );
  51647. assert( !pBt->pPage1 && !pBt->pCursor );
  51648. pBt->pageSize = (u32)pageSize;
  51649. freeTempSpace(pBt);
  51650. }
  51651. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  51652. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  51653. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51654. sqlite3BtreeLeave(p);
  51655. return rc;
  51656. }
  51657. /*
  51658. ** Return the currently defined page size
  51659. */
  51660. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  51661. return p->pBt->pageSize;
  51662. }
  51663. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  51664. /*
  51665. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  51666. ** may only be called if it is guaranteed that the b-tree mutex is already
  51667. ** held.
  51668. **
  51669. ** This is useful in one special case in the backup API code where it is
  51670. ** known that the shared b-tree mutex is held, but the mutex on the
  51671. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  51672. ** were to be called, it might collide with some other operation on the
  51673. ** database handle that owns *p, causing undefined behavior.
  51674. */
  51675. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  51676. assert( sqlite3_mutex_held(p->pBt->mutex) );
  51677. return p->pBt->pageSize - p->pBt->usableSize;
  51678. }
  51679. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  51680. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  51681. /*
  51682. ** Return the number of bytes of space at the end of every page that
  51683. ** are intentually left unused. This is the "reserved" space that is
  51684. ** sometimes used by extensions.
  51685. */
  51686. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  51687. int n;
  51688. sqlite3BtreeEnter(p);
  51689. n = p->pBt->pageSize - p->pBt->usableSize;
  51690. sqlite3BtreeLeave(p);
  51691. return n;
  51692. }
  51693. /*
  51694. ** Set the maximum page count for a database if mxPage is positive.
  51695. ** No changes are made if mxPage is 0 or negative.
  51696. ** Regardless of the value of mxPage, return the maximum page count.
  51697. */
  51698. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  51699. int n;
  51700. sqlite3BtreeEnter(p);
  51701. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  51702. sqlite3BtreeLeave(p);
  51703. return n;
  51704. }
  51705. /*
  51706. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  51707. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  51708. ** setting after the change.
  51709. */
  51710. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  51711. int b;
  51712. if( p==0 ) return 0;
  51713. sqlite3BtreeEnter(p);
  51714. if( newFlag>=0 ){
  51715. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  51716. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  51717. }
  51718. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  51719. sqlite3BtreeLeave(p);
  51720. return b;
  51721. }
  51722. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  51723. /*
  51724. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  51725. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  51726. ** is disabled. The default value for the auto-vacuum property is
  51727. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  51728. */
  51729. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  51730. #ifdef SQLITE_OMIT_AUTOVACUUM
  51731. return SQLITE_READONLY;
  51732. #else
  51733. BtShared *pBt = p->pBt;
  51734. int rc = SQLITE_OK;
  51735. u8 av = (u8)autoVacuum;
  51736. sqlite3BtreeEnter(p);
  51737. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  51738. rc = SQLITE_READONLY;
  51739. }else{
  51740. pBt->autoVacuum = av ?1:0;
  51741. pBt->incrVacuum = av==2 ?1:0;
  51742. }
  51743. sqlite3BtreeLeave(p);
  51744. return rc;
  51745. #endif
  51746. }
  51747. /*
  51748. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  51749. ** enabled 1 is returned. Otherwise 0.
  51750. */
  51751. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  51752. #ifdef SQLITE_OMIT_AUTOVACUUM
  51753. return BTREE_AUTOVACUUM_NONE;
  51754. #else
  51755. int rc;
  51756. sqlite3BtreeEnter(p);
  51757. rc = (
  51758. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  51759. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  51760. BTREE_AUTOVACUUM_INCR
  51761. );
  51762. sqlite3BtreeLeave(p);
  51763. return rc;
  51764. #endif
  51765. }
  51766. /*
  51767. ** Get a reference to pPage1 of the database file. This will
  51768. ** also acquire a readlock on that file.
  51769. **
  51770. ** SQLITE_OK is returned on success. If the file is not a
  51771. ** well-formed database file, then SQLITE_CORRUPT is returned.
  51772. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  51773. ** is returned if we run out of memory.
  51774. */
  51775. static int lockBtree(BtShared *pBt){
  51776. int rc; /* Result code from subfunctions */
  51777. MemPage *pPage1; /* Page 1 of the database file */
  51778. int nPage; /* Number of pages in the database */
  51779. int nPageFile = 0; /* Number of pages in the database file */
  51780. int nPageHeader; /* Number of pages in the database according to hdr */
  51781. assert( sqlite3_mutex_held(pBt->mutex) );
  51782. assert( pBt->pPage1==0 );
  51783. rc = sqlite3PagerSharedLock(pBt->pPager);
  51784. if( rc!=SQLITE_OK ) return rc;
  51785. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  51786. if( rc!=SQLITE_OK ) return rc;
  51787. /* Do some checking to help insure the file we opened really is
  51788. ** a valid database file.
  51789. */
  51790. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  51791. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  51792. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  51793. nPage = nPageFile;
  51794. }
  51795. if( nPage>0 ){
  51796. u32 pageSize;
  51797. u32 usableSize;
  51798. u8 *page1 = pPage1->aData;
  51799. rc = SQLITE_NOTADB;
  51800. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  51801. goto page1_init_failed;
  51802. }
  51803. #ifdef SQLITE_OMIT_WAL
  51804. if( page1[18]>1 ){
  51805. pBt->btsFlags |= BTS_READ_ONLY;
  51806. }
  51807. if( page1[19]>1 ){
  51808. goto page1_init_failed;
  51809. }
  51810. #else
  51811. if( page1[18]>2 ){
  51812. pBt->btsFlags |= BTS_READ_ONLY;
  51813. }
  51814. if( page1[19]>2 ){
  51815. goto page1_init_failed;
  51816. }
  51817. /* If the write version is set to 2, this database should be accessed
  51818. ** in WAL mode. If the log is not already open, open it now. Then
  51819. ** return SQLITE_OK and return without populating BtShared.pPage1.
  51820. ** The caller detects this and calls this function again. This is
  51821. ** required as the version of page 1 currently in the page1 buffer
  51822. ** may not be the latest version - there may be a newer one in the log
  51823. ** file.
  51824. */
  51825. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  51826. int isOpen = 0;
  51827. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  51828. if( rc!=SQLITE_OK ){
  51829. goto page1_init_failed;
  51830. }else if( isOpen==0 ){
  51831. releasePage(pPage1);
  51832. return SQLITE_OK;
  51833. }
  51834. rc = SQLITE_NOTADB;
  51835. }
  51836. #endif
  51837. /* The maximum embedded fraction must be exactly 25%. And the minimum
  51838. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  51839. ** The original design allowed these amounts to vary, but as of
  51840. ** version 3.6.0, we require them to be fixed.
  51841. */
  51842. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  51843. goto page1_init_failed;
  51844. }
  51845. pageSize = (page1[16]<<8) | (page1[17]<<16);
  51846. if( ((pageSize-1)&pageSize)!=0
  51847. || pageSize>SQLITE_MAX_PAGE_SIZE
  51848. || pageSize<=256
  51849. ){
  51850. goto page1_init_failed;
  51851. }
  51852. assert( (pageSize & 7)==0 );
  51853. usableSize = pageSize - page1[20];
  51854. if( (u32)pageSize!=pBt->pageSize ){
  51855. /* After reading the first page of the database assuming a page size
  51856. ** of BtShared.pageSize, we have discovered that the page-size is
  51857. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  51858. ** zero and return SQLITE_OK. The caller will call this function
  51859. ** again with the correct page-size.
  51860. */
  51861. releasePage(pPage1);
  51862. pBt->usableSize = usableSize;
  51863. pBt->pageSize = pageSize;
  51864. freeTempSpace(pBt);
  51865. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  51866. pageSize-usableSize);
  51867. return rc;
  51868. }
  51869. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  51870. rc = SQLITE_CORRUPT_BKPT;
  51871. goto page1_init_failed;
  51872. }
  51873. if( usableSize<480 ){
  51874. goto page1_init_failed;
  51875. }
  51876. pBt->pageSize = pageSize;
  51877. pBt->usableSize = usableSize;
  51878. #ifndef SQLITE_OMIT_AUTOVACUUM
  51879. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  51880. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  51881. #endif
  51882. }
  51883. /* maxLocal is the maximum amount of payload to store locally for
  51884. ** a cell. Make sure it is small enough so that at least minFanout
  51885. ** cells can will fit on one page. We assume a 10-byte page header.
  51886. ** Besides the payload, the cell must store:
  51887. ** 2-byte pointer to the cell
  51888. ** 4-byte child pointer
  51889. ** 9-byte nKey value
  51890. ** 4-byte nData value
  51891. ** 4-byte overflow page pointer
  51892. ** So a cell consists of a 2-byte pointer, a header which is as much as
  51893. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  51894. ** page pointer.
  51895. */
  51896. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  51897. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  51898. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  51899. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  51900. if( pBt->maxLocal>127 ){
  51901. pBt->max1bytePayload = 127;
  51902. }else{
  51903. pBt->max1bytePayload = (u8)pBt->maxLocal;
  51904. }
  51905. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  51906. pBt->pPage1 = pPage1;
  51907. pBt->nPage = nPage;
  51908. return SQLITE_OK;
  51909. page1_init_failed:
  51910. releasePage(pPage1);
  51911. pBt->pPage1 = 0;
  51912. return rc;
  51913. }
  51914. #ifndef NDEBUG
  51915. /*
  51916. ** Return the number of cursors open on pBt. This is for use
  51917. ** in assert() expressions, so it is only compiled if NDEBUG is not
  51918. ** defined.
  51919. **
  51920. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  51921. ** false then all cursors are counted.
  51922. **
  51923. ** For the purposes of this routine, a cursor is any cursor that
  51924. ** is capable of reading or writing to the databse. Cursors that
  51925. ** have been tripped into the CURSOR_FAULT state are not counted.
  51926. */
  51927. static int countValidCursors(BtShared *pBt, int wrOnly){
  51928. BtCursor *pCur;
  51929. int r = 0;
  51930. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  51931. if( (wrOnly==0 || pCur->wrFlag) && pCur->eState!=CURSOR_FAULT ) r++;
  51932. }
  51933. return r;
  51934. }
  51935. #endif
  51936. /*
  51937. ** If there are no outstanding cursors and we are not in the middle
  51938. ** of a transaction but there is a read lock on the database, then
  51939. ** this routine unrefs the first page of the database file which
  51940. ** has the effect of releasing the read lock.
  51941. **
  51942. ** If there is a transaction in progress, this routine is a no-op.
  51943. */
  51944. static void unlockBtreeIfUnused(BtShared *pBt){
  51945. assert( sqlite3_mutex_held(pBt->mutex) );
  51946. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  51947. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  51948. assert( pBt->pPage1->aData );
  51949. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  51950. assert( pBt->pPage1->aData );
  51951. releasePage(pBt->pPage1);
  51952. pBt->pPage1 = 0;
  51953. }
  51954. }
  51955. /*
  51956. ** If pBt points to an empty file then convert that empty file
  51957. ** into a new empty database by initializing the first page of
  51958. ** the database.
  51959. */
  51960. static int newDatabase(BtShared *pBt){
  51961. MemPage *pP1;
  51962. unsigned char *data;
  51963. int rc;
  51964. assert( sqlite3_mutex_held(pBt->mutex) );
  51965. if( pBt->nPage>0 ){
  51966. return SQLITE_OK;
  51967. }
  51968. pP1 = pBt->pPage1;
  51969. assert( pP1!=0 );
  51970. data = pP1->aData;
  51971. rc = sqlite3PagerWrite(pP1->pDbPage);
  51972. if( rc ) return rc;
  51973. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  51974. assert( sizeof(zMagicHeader)==16 );
  51975. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  51976. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  51977. data[18] = 1;
  51978. data[19] = 1;
  51979. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  51980. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  51981. data[21] = 64;
  51982. data[22] = 32;
  51983. data[23] = 32;
  51984. memset(&data[24], 0, 100-24);
  51985. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  51986. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51987. #ifndef SQLITE_OMIT_AUTOVACUUM
  51988. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  51989. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  51990. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  51991. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  51992. #endif
  51993. pBt->nPage = 1;
  51994. data[31] = 1;
  51995. return SQLITE_OK;
  51996. }
  51997. /*
  51998. ** Initialize the first page of the database file (creating a database
  51999. ** consisting of a single page and no schema objects). Return SQLITE_OK
  52000. ** if successful, or an SQLite error code otherwise.
  52001. */
  52002. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  52003. int rc;
  52004. sqlite3BtreeEnter(p);
  52005. p->pBt->nPage = 0;
  52006. rc = newDatabase(p->pBt);
  52007. sqlite3BtreeLeave(p);
  52008. return rc;
  52009. }
  52010. /*
  52011. ** Attempt to start a new transaction. A write-transaction
  52012. ** is started if the second argument is nonzero, otherwise a read-
  52013. ** transaction. If the second argument is 2 or more and exclusive
  52014. ** transaction is started, meaning that no other process is allowed
  52015. ** to access the database. A preexisting transaction may not be
  52016. ** upgraded to exclusive by calling this routine a second time - the
  52017. ** exclusivity flag only works for a new transaction.
  52018. **
  52019. ** A write-transaction must be started before attempting any
  52020. ** changes to the database. None of the following routines
  52021. ** will work unless a transaction is started first:
  52022. **
  52023. ** sqlite3BtreeCreateTable()
  52024. ** sqlite3BtreeCreateIndex()
  52025. ** sqlite3BtreeClearTable()
  52026. ** sqlite3BtreeDropTable()
  52027. ** sqlite3BtreeInsert()
  52028. ** sqlite3BtreeDelete()
  52029. ** sqlite3BtreeUpdateMeta()
  52030. **
  52031. ** If an initial attempt to acquire the lock fails because of lock contention
  52032. ** and the database was previously unlocked, then invoke the busy handler
  52033. ** if there is one. But if there was previously a read-lock, do not
  52034. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  52035. ** returned when there is already a read-lock in order to avoid a deadlock.
  52036. **
  52037. ** Suppose there are two processes A and B. A has a read lock and B has
  52038. ** a reserved lock. B tries to promote to exclusive but is blocked because
  52039. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  52040. ** One or the other of the two processes must give way or there can be
  52041. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  52042. ** when A already has a read lock, we encourage A to give up and let B
  52043. ** proceed.
  52044. */
  52045. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  52046. sqlite3 *pBlock = 0;
  52047. BtShared *pBt = p->pBt;
  52048. int rc = SQLITE_OK;
  52049. sqlite3BtreeEnter(p);
  52050. btreeIntegrity(p);
  52051. /* If the btree is already in a write-transaction, or it
  52052. ** is already in a read-transaction and a read-transaction
  52053. ** is requested, this is a no-op.
  52054. */
  52055. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  52056. goto trans_begun;
  52057. }
  52058. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  52059. /* Write transactions are not possible on a read-only database */
  52060. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  52061. rc = SQLITE_READONLY;
  52062. goto trans_begun;
  52063. }
  52064. #ifndef SQLITE_OMIT_SHARED_CACHE
  52065. /* If another database handle has already opened a write transaction
  52066. ** on this shared-btree structure and a second write transaction is
  52067. ** requested, return SQLITE_LOCKED.
  52068. */
  52069. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  52070. || (pBt->btsFlags & BTS_PENDING)!=0
  52071. ){
  52072. pBlock = pBt->pWriter->db;
  52073. }else if( wrflag>1 ){
  52074. BtLock *pIter;
  52075. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  52076. if( pIter->pBtree!=p ){
  52077. pBlock = pIter->pBtree->db;
  52078. break;
  52079. }
  52080. }
  52081. }
  52082. if( pBlock ){
  52083. sqlite3ConnectionBlocked(p->db, pBlock);
  52084. rc = SQLITE_LOCKED_SHAREDCACHE;
  52085. goto trans_begun;
  52086. }
  52087. #endif
  52088. /* Any read-only or read-write transaction implies a read-lock on
  52089. ** page 1. So if some other shared-cache client already has a write-lock
  52090. ** on page 1, the transaction cannot be opened. */
  52091. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  52092. if( SQLITE_OK!=rc ) goto trans_begun;
  52093. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  52094. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  52095. do {
  52096. /* Call lockBtree() until either pBt->pPage1 is populated or
  52097. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  52098. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  52099. ** reading page 1 it discovers that the page-size of the database
  52100. ** file is not pBt->pageSize. In this case lockBtree() will update
  52101. ** pBt->pageSize to the page-size of the file on disk.
  52102. */
  52103. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  52104. if( rc==SQLITE_OK && wrflag ){
  52105. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  52106. rc = SQLITE_READONLY;
  52107. }else{
  52108. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  52109. if( rc==SQLITE_OK ){
  52110. rc = newDatabase(pBt);
  52111. }
  52112. }
  52113. }
  52114. if( rc!=SQLITE_OK ){
  52115. unlockBtreeIfUnused(pBt);
  52116. }
  52117. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  52118. btreeInvokeBusyHandler(pBt) );
  52119. if( rc==SQLITE_OK ){
  52120. if( p->inTrans==TRANS_NONE ){
  52121. pBt->nTransaction++;
  52122. #ifndef SQLITE_OMIT_SHARED_CACHE
  52123. if( p->sharable ){
  52124. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  52125. p->lock.eLock = READ_LOCK;
  52126. p->lock.pNext = pBt->pLock;
  52127. pBt->pLock = &p->lock;
  52128. }
  52129. #endif
  52130. }
  52131. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  52132. if( p->inTrans>pBt->inTransaction ){
  52133. pBt->inTransaction = p->inTrans;
  52134. }
  52135. if( wrflag ){
  52136. MemPage *pPage1 = pBt->pPage1;
  52137. #ifndef SQLITE_OMIT_SHARED_CACHE
  52138. assert( !pBt->pWriter );
  52139. pBt->pWriter = p;
  52140. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  52141. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  52142. #endif
  52143. /* If the db-size header field is incorrect (as it may be if an old
  52144. ** client has been writing the database file), update it now. Doing
  52145. ** this sooner rather than later means the database size can safely
  52146. ** re-read the database size from page 1 if a savepoint or transaction
  52147. ** rollback occurs within the transaction.
  52148. */
  52149. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  52150. rc = sqlite3PagerWrite(pPage1->pDbPage);
  52151. if( rc==SQLITE_OK ){
  52152. put4byte(&pPage1->aData[28], pBt->nPage);
  52153. }
  52154. }
  52155. }
  52156. }
  52157. trans_begun:
  52158. if( rc==SQLITE_OK && wrflag ){
  52159. /* This call makes sure that the pager has the correct number of
  52160. ** open savepoints. If the second parameter is greater than 0 and
  52161. ** the sub-journal is not already open, then it will be opened here.
  52162. */
  52163. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  52164. }
  52165. btreeIntegrity(p);
  52166. sqlite3BtreeLeave(p);
  52167. return rc;
  52168. }
  52169. #ifndef SQLITE_OMIT_AUTOVACUUM
  52170. /*
  52171. ** Set the pointer-map entries for all children of page pPage. Also, if
  52172. ** pPage contains cells that point to overflow pages, set the pointer
  52173. ** map entries for the overflow pages as well.
  52174. */
  52175. static int setChildPtrmaps(MemPage *pPage){
  52176. int i; /* Counter variable */
  52177. int nCell; /* Number of cells in page pPage */
  52178. int rc; /* Return code */
  52179. BtShared *pBt = pPage->pBt;
  52180. u8 isInitOrig = pPage->isInit;
  52181. Pgno pgno = pPage->pgno;
  52182. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52183. rc = btreeInitPage(pPage);
  52184. if( rc!=SQLITE_OK ){
  52185. goto set_child_ptrmaps_out;
  52186. }
  52187. nCell = pPage->nCell;
  52188. for(i=0; i<nCell; i++){
  52189. u8 *pCell = findCell(pPage, i);
  52190. ptrmapPutOvflPtr(pPage, pCell, &rc);
  52191. if( !pPage->leaf ){
  52192. Pgno childPgno = get4byte(pCell);
  52193. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52194. }
  52195. }
  52196. if( !pPage->leaf ){
  52197. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52198. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  52199. }
  52200. set_child_ptrmaps_out:
  52201. pPage->isInit = isInitOrig;
  52202. return rc;
  52203. }
  52204. /*
  52205. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  52206. ** that it points to iTo. Parameter eType describes the type of pointer to
  52207. ** be modified, as follows:
  52208. **
  52209. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  52210. ** page of pPage.
  52211. **
  52212. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  52213. ** page pointed to by one of the cells on pPage.
  52214. **
  52215. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  52216. ** overflow page in the list.
  52217. */
  52218. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  52219. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  52220. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  52221. if( eType==PTRMAP_OVERFLOW2 ){
  52222. /* The pointer is always the first 4 bytes of the page in this case. */
  52223. if( get4byte(pPage->aData)!=iFrom ){
  52224. return SQLITE_CORRUPT_BKPT;
  52225. }
  52226. put4byte(pPage->aData, iTo);
  52227. }else{
  52228. u8 isInitOrig = pPage->isInit;
  52229. int i;
  52230. int nCell;
  52231. btreeInitPage(pPage);
  52232. nCell = pPage->nCell;
  52233. for(i=0; i<nCell; i++){
  52234. u8 *pCell = findCell(pPage, i);
  52235. if( eType==PTRMAP_OVERFLOW1 ){
  52236. CellInfo info;
  52237. btreeParseCellPtr(pPage, pCell, &info);
  52238. if( info.iOverflow
  52239. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  52240. && iFrom==get4byte(&pCell[info.iOverflow])
  52241. ){
  52242. put4byte(&pCell[info.iOverflow], iTo);
  52243. break;
  52244. }
  52245. }else{
  52246. if( get4byte(pCell)==iFrom ){
  52247. put4byte(pCell, iTo);
  52248. break;
  52249. }
  52250. }
  52251. }
  52252. if( i==nCell ){
  52253. if( eType!=PTRMAP_BTREE ||
  52254. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  52255. return SQLITE_CORRUPT_BKPT;
  52256. }
  52257. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  52258. }
  52259. pPage->isInit = isInitOrig;
  52260. }
  52261. return SQLITE_OK;
  52262. }
  52263. /*
  52264. ** Move the open database page pDbPage to location iFreePage in the
  52265. ** database. The pDbPage reference remains valid.
  52266. **
  52267. ** The isCommit flag indicates that there is no need to remember that
  52268. ** the journal needs to be sync()ed before database page pDbPage->pgno
  52269. ** can be written to. The caller has already promised not to write to that
  52270. ** page.
  52271. */
  52272. static int relocatePage(
  52273. BtShared *pBt, /* Btree */
  52274. MemPage *pDbPage, /* Open page to move */
  52275. u8 eType, /* Pointer map 'type' entry for pDbPage */
  52276. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  52277. Pgno iFreePage, /* The location to move pDbPage to */
  52278. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  52279. ){
  52280. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  52281. Pgno iDbPage = pDbPage->pgno;
  52282. Pager *pPager = pBt->pPager;
  52283. int rc;
  52284. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  52285. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  52286. assert( sqlite3_mutex_held(pBt->mutex) );
  52287. assert( pDbPage->pBt==pBt );
  52288. /* Move page iDbPage from its current location to page number iFreePage */
  52289. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  52290. iDbPage, iFreePage, iPtrPage, eType));
  52291. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  52292. if( rc!=SQLITE_OK ){
  52293. return rc;
  52294. }
  52295. pDbPage->pgno = iFreePage;
  52296. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  52297. ** that point to overflow pages. The pointer map entries for all these
  52298. ** pages need to be changed.
  52299. **
  52300. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  52301. ** pointer to a subsequent overflow page. If this is the case, then
  52302. ** the pointer map needs to be updated for the subsequent overflow page.
  52303. */
  52304. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  52305. rc = setChildPtrmaps(pDbPage);
  52306. if( rc!=SQLITE_OK ){
  52307. return rc;
  52308. }
  52309. }else{
  52310. Pgno nextOvfl = get4byte(pDbPage->aData);
  52311. if( nextOvfl!=0 ){
  52312. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  52313. if( rc!=SQLITE_OK ){
  52314. return rc;
  52315. }
  52316. }
  52317. }
  52318. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  52319. ** that it points at iFreePage. Also fix the pointer map entry for
  52320. ** iPtrPage.
  52321. */
  52322. if( eType!=PTRMAP_ROOTPAGE ){
  52323. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  52324. if( rc!=SQLITE_OK ){
  52325. return rc;
  52326. }
  52327. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  52328. if( rc!=SQLITE_OK ){
  52329. releasePage(pPtrPage);
  52330. return rc;
  52331. }
  52332. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  52333. releasePage(pPtrPage);
  52334. if( rc==SQLITE_OK ){
  52335. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  52336. }
  52337. }
  52338. return rc;
  52339. }
  52340. /* Forward declaration required by incrVacuumStep(). */
  52341. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  52342. /*
  52343. ** Perform a single step of an incremental-vacuum. If successful, return
  52344. ** SQLITE_OK. If there is no work to do (and therefore no point in
  52345. ** calling this function again), return SQLITE_DONE. Or, if an error
  52346. ** occurs, return some other error code.
  52347. **
  52348. ** More specificly, this function attempts to re-organize the database so
  52349. ** that the last page of the file currently in use is no longer in use.
  52350. **
  52351. ** Parameter nFin is the number of pages that this database would contain
  52352. ** were this function called until it returns SQLITE_DONE.
  52353. **
  52354. ** If the bCommit parameter is non-zero, this function assumes that the
  52355. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  52356. ** or an error. bCommit is passed true for an auto-vacuum-on-commmit
  52357. ** operation, or false for an incremental vacuum.
  52358. */
  52359. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  52360. Pgno nFreeList; /* Number of pages still on the free-list */
  52361. int rc;
  52362. assert( sqlite3_mutex_held(pBt->mutex) );
  52363. assert( iLastPg>nFin );
  52364. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  52365. u8 eType;
  52366. Pgno iPtrPage;
  52367. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  52368. if( nFreeList==0 ){
  52369. return SQLITE_DONE;
  52370. }
  52371. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  52372. if( rc!=SQLITE_OK ){
  52373. return rc;
  52374. }
  52375. if( eType==PTRMAP_ROOTPAGE ){
  52376. return SQLITE_CORRUPT_BKPT;
  52377. }
  52378. if( eType==PTRMAP_FREEPAGE ){
  52379. if( bCommit==0 ){
  52380. /* Remove the page from the files free-list. This is not required
  52381. ** if bCommit is non-zero. In that case, the free-list will be
  52382. ** truncated to zero after this function returns, so it doesn't
  52383. ** matter if it still contains some garbage entries.
  52384. */
  52385. Pgno iFreePg;
  52386. MemPage *pFreePg;
  52387. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  52388. if( rc!=SQLITE_OK ){
  52389. return rc;
  52390. }
  52391. assert( iFreePg==iLastPg );
  52392. releasePage(pFreePg);
  52393. }
  52394. } else {
  52395. Pgno iFreePg; /* Index of free page to move pLastPg to */
  52396. MemPage *pLastPg;
  52397. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  52398. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  52399. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  52400. if( rc!=SQLITE_OK ){
  52401. return rc;
  52402. }
  52403. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  52404. ** is swapped with the first free page pulled off the free list.
  52405. **
  52406. ** On the other hand, if bCommit is greater than zero, then keep
  52407. ** looping until a free-page located within the first nFin pages
  52408. ** of the file is found.
  52409. */
  52410. if( bCommit==0 ){
  52411. eMode = BTALLOC_LE;
  52412. iNear = nFin;
  52413. }
  52414. do {
  52415. MemPage *pFreePg;
  52416. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  52417. if( rc!=SQLITE_OK ){
  52418. releasePage(pLastPg);
  52419. return rc;
  52420. }
  52421. releasePage(pFreePg);
  52422. }while( bCommit && iFreePg>nFin );
  52423. assert( iFreePg<iLastPg );
  52424. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  52425. releasePage(pLastPg);
  52426. if( rc!=SQLITE_OK ){
  52427. return rc;
  52428. }
  52429. }
  52430. }
  52431. if( bCommit==0 ){
  52432. do {
  52433. iLastPg--;
  52434. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  52435. pBt->bDoTruncate = 1;
  52436. pBt->nPage = iLastPg;
  52437. }
  52438. return SQLITE_OK;
  52439. }
  52440. /*
  52441. ** The database opened by the first argument is an auto-vacuum database
  52442. ** nOrig pages in size containing nFree free pages. Return the expected
  52443. ** size of the database in pages following an auto-vacuum operation.
  52444. */
  52445. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  52446. int nEntry; /* Number of entries on one ptrmap page */
  52447. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  52448. Pgno nFin; /* Return value */
  52449. nEntry = pBt->usableSize/5;
  52450. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  52451. nFin = nOrig - nFree - nPtrmap;
  52452. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  52453. nFin--;
  52454. }
  52455. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  52456. nFin--;
  52457. }
  52458. return nFin;
  52459. }
  52460. /*
  52461. ** A write-transaction must be opened before calling this function.
  52462. ** It performs a single unit of work towards an incremental vacuum.
  52463. **
  52464. ** If the incremental vacuum is finished after this function has run,
  52465. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  52466. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  52467. */
  52468. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  52469. int rc;
  52470. BtShared *pBt = p->pBt;
  52471. sqlite3BtreeEnter(p);
  52472. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  52473. if( !pBt->autoVacuum ){
  52474. rc = SQLITE_DONE;
  52475. }else{
  52476. Pgno nOrig = btreePagecount(pBt);
  52477. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  52478. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  52479. if( nOrig<nFin ){
  52480. rc = SQLITE_CORRUPT_BKPT;
  52481. }else if( nFree>0 ){
  52482. rc = saveAllCursors(pBt, 0, 0);
  52483. if( rc==SQLITE_OK ){
  52484. invalidateAllOverflowCache(pBt);
  52485. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  52486. }
  52487. if( rc==SQLITE_OK ){
  52488. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52489. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  52490. }
  52491. }else{
  52492. rc = SQLITE_DONE;
  52493. }
  52494. }
  52495. sqlite3BtreeLeave(p);
  52496. return rc;
  52497. }
  52498. /*
  52499. ** This routine is called prior to sqlite3PagerCommit when a transaction
  52500. ** is committed for an auto-vacuum database.
  52501. **
  52502. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  52503. ** the database file should be truncated to during the commit process.
  52504. ** i.e. the database has been reorganized so that only the first *pnTrunc
  52505. ** pages are in use.
  52506. */
  52507. static int autoVacuumCommit(BtShared *pBt){
  52508. int rc = SQLITE_OK;
  52509. Pager *pPager = pBt->pPager;
  52510. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  52511. assert( sqlite3_mutex_held(pBt->mutex) );
  52512. invalidateAllOverflowCache(pBt);
  52513. assert(pBt->autoVacuum);
  52514. if( !pBt->incrVacuum ){
  52515. Pgno nFin; /* Number of pages in database after autovacuuming */
  52516. Pgno nFree; /* Number of pages on the freelist initially */
  52517. Pgno iFree; /* The next page to be freed */
  52518. Pgno nOrig; /* Database size before freeing */
  52519. nOrig = btreePagecount(pBt);
  52520. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  52521. /* It is not possible to create a database for which the final page
  52522. ** is either a pointer-map page or the pending-byte page. If one
  52523. ** is encountered, this indicates corruption.
  52524. */
  52525. return SQLITE_CORRUPT_BKPT;
  52526. }
  52527. nFree = get4byte(&pBt->pPage1->aData[36]);
  52528. nFin = finalDbSize(pBt, nOrig, nFree);
  52529. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  52530. if( nFin<nOrig ){
  52531. rc = saveAllCursors(pBt, 0, 0);
  52532. }
  52533. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  52534. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  52535. }
  52536. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  52537. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  52538. put4byte(&pBt->pPage1->aData[32], 0);
  52539. put4byte(&pBt->pPage1->aData[36], 0);
  52540. put4byte(&pBt->pPage1->aData[28], nFin);
  52541. pBt->bDoTruncate = 1;
  52542. pBt->nPage = nFin;
  52543. }
  52544. if( rc!=SQLITE_OK ){
  52545. sqlite3PagerRollback(pPager);
  52546. }
  52547. }
  52548. assert( nRef>=sqlite3PagerRefcount(pPager) );
  52549. return rc;
  52550. }
  52551. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  52552. # define setChildPtrmaps(x) SQLITE_OK
  52553. #endif
  52554. /*
  52555. ** This routine does the first phase of a two-phase commit. This routine
  52556. ** causes a rollback journal to be created (if it does not already exist)
  52557. ** and populated with enough information so that if a power loss occurs
  52558. ** the database can be restored to its original state by playing back
  52559. ** the journal. Then the contents of the journal are flushed out to
  52560. ** the disk. After the journal is safely on oxide, the changes to the
  52561. ** database are written into the database file and flushed to oxide.
  52562. ** At the end of this call, the rollback journal still exists on the
  52563. ** disk and we are still holding all locks, so the transaction has not
  52564. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  52565. ** commit process.
  52566. **
  52567. ** This call is a no-op if no write-transaction is currently active on pBt.
  52568. **
  52569. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  52570. ** the name of a master journal file that should be written into the
  52571. ** individual journal file, or is NULL, indicating no master journal file
  52572. ** (single database transaction).
  52573. **
  52574. ** When this is called, the master journal should already have been
  52575. ** created, populated with this journal pointer and synced to disk.
  52576. **
  52577. ** Once this is routine has returned, the only thing required to commit
  52578. ** the write-transaction for this database file is to delete the journal.
  52579. */
  52580. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  52581. int rc = SQLITE_OK;
  52582. if( p->inTrans==TRANS_WRITE ){
  52583. BtShared *pBt = p->pBt;
  52584. sqlite3BtreeEnter(p);
  52585. #ifndef SQLITE_OMIT_AUTOVACUUM
  52586. if( pBt->autoVacuum ){
  52587. rc = autoVacuumCommit(pBt);
  52588. if( rc!=SQLITE_OK ){
  52589. sqlite3BtreeLeave(p);
  52590. return rc;
  52591. }
  52592. }
  52593. if( pBt->bDoTruncate ){
  52594. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  52595. }
  52596. #endif
  52597. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  52598. sqlite3BtreeLeave(p);
  52599. }
  52600. return rc;
  52601. }
  52602. /*
  52603. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  52604. ** at the conclusion of a transaction.
  52605. */
  52606. static void btreeEndTransaction(Btree *p){
  52607. BtShared *pBt = p->pBt;
  52608. sqlite3 *db = p->db;
  52609. assert( sqlite3BtreeHoldsMutex(p) );
  52610. #ifndef SQLITE_OMIT_AUTOVACUUM
  52611. pBt->bDoTruncate = 0;
  52612. #endif
  52613. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  52614. /* If there are other active statements that belong to this database
  52615. ** handle, downgrade to a read-only transaction. The other statements
  52616. ** may still be reading from the database. */
  52617. downgradeAllSharedCacheTableLocks(p);
  52618. p->inTrans = TRANS_READ;
  52619. }else{
  52620. /* If the handle had any kind of transaction open, decrement the
  52621. ** transaction count of the shared btree. If the transaction count
  52622. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  52623. ** call below will unlock the pager. */
  52624. if( p->inTrans!=TRANS_NONE ){
  52625. clearAllSharedCacheTableLocks(p);
  52626. pBt->nTransaction--;
  52627. if( 0==pBt->nTransaction ){
  52628. pBt->inTransaction = TRANS_NONE;
  52629. }
  52630. }
  52631. /* Set the current transaction state to TRANS_NONE and unlock the
  52632. ** pager if this call closed the only read or write transaction. */
  52633. p->inTrans = TRANS_NONE;
  52634. unlockBtreeIfUnused(pBt);
  52635. }
  52636. btreeIntegrity(p);
  52637. }
  52638. /*
  52639. ** Commit the transaction currently in progress.
  52640. **
  52641. ** This routine implements the second phase of a 2-phase commit. The
  52642. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  52643. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  52644. ** routine did all the work of writing information out to disk and flushing the
  52645. ** contents so that they are written onto the disk platter. All this
  52646. ** routine has to do is delete or truncate or zero the header in the
  52647. ** the rollback journal (which causes the transaction to commit) and
  52648. ** drop locks.
  52649. **
  52650. ** Normally, if an error occurs while the pager layer is attempting to
  52651. ** finalize the underlying journal file, this function returns an error and
  52652. ** the upper layer will attempt a rollback. However, if the second argument
  52653. ** is non-zero then this b-tree transaction is part of a multi-file
  52654. ** transaction. In this case, the transaction has already been committed
  52655. ** (by deleting a master journal file) and the caller will ignore this
  52656. ** functions return code. So, even if an error occurs in the pager layer,
  52657. ** reset the b-tree objects internal state to indicate that the write
  52658. ** transaction has been closed. This is quite safe, as the pager will have
  52659. ** transitioned to the error state.
  52660. **
  52661. ** This will release the write lock on the database file. If there
  52662. ** are no active cursors, it also releases the read lock.
  52663. */
  52664. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  52665. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  52666. sqlite3BtreeEnter(p);
  52667. btreeIntegrity(p);
  52668. /* If the handle has a write-transaction open, commit the shared-btrees
  52669. ** transaction and set the shared state to TRANS_READ.
  52670. */
  52671. if( p->inTrans==TRANS_WRITE ){
  52672. int rc;
  52673. BtShared *pBt = p->pBt;
  52674. assert( pBt->inTransaction==TRANS_WRITE );
  52675. assert( pBt->nTransaction>0 );
  52676. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  52677. if( rc!=SQLITE_OK && bCleanup==0 ){
  52678. sqlite3BtreeLeave(p);
  52679. return rc;
  52680. }
  52681. pBt->inTransaction = TRANS_READ;
  52682. btreeClearHasContent(pBt);
  52683. }
  52684. btreeEndTransaction(p);
  52685. sqlite3BtreeLeave(p);
  52686. return SQLITE_OK;
  52687. }
  52688. /*
  52689. ** Do both phases of a commit.
  52690. */
  52691. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  52692. int rc;
  52693. sqlite3BtreeEnter(p);
  52694. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  52695. if( rc==SQLITE_OK ){
  52696. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  52697. }
  52698. sqlite3BtreeLeave(p);
  52699. return rc;
  52700. }
  52701. /*
  52702. ** This routine sets the state to CURSOR_FAULT and the error
  52703. ** code to errCode for every cursor on BtShared that pBtree
  52704. ** references.
  52705. **
  52706. ** Every cursor is tripped, including cursors that belong
  52707. ** to other database connections that happen to be sharing
  52708. ** the cache with pBtree.
  52709. **
  52710. ** This routine gets called when a rollback occurs.
  52711. ** All cursors using the same cache must be tripped
  52712. ** to prevent them from trying to use the btree after
  52713. ** the rollback. The rollback may have deleted tables
  52714. ** or moved root pages, so it is not sufficient to
  52715. ** save the state of the cursor. The cursor must be
  52716. ** invalidated.
  52717. */
  52718. SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
  52719. BtCursor *p;
  52720. if( pBtree==0 ) return;
  52721. sqlite3BtreeEnter(pBtree);
  52722. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  52723. int i;
  52724. sqlite3BtreeClearCursor(p);
  52725. p->eState = CURSOR_FAULT;
  52726. p->skipNext = errCode;
  52727. for(i=0; i<=p->iPage; i++){
  52728. releasePage(p->apPage[i]);
  52729. p->apPage[i] = 0;
  52730. }
  52731. }
  52732. sqlite3BtreeLeave(pBtree);
  52733. }
  52734. /*
  52735. ** Rollback the transaction in progress. All cursors will be
  52736. ** invalided by this operation. Any attempt to use a cursor
  52737. ** that was open at the beginning of this operation will result
  52738. ** in an error.
  52739. **
  52740. ** This will release the write lock on the database file. If there
  52741. ** are no active cursors, it also releases the read lock.
  52742. */
  52743. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode){
  52744. int rc;
  52745. BtShared *pBt = p->pBt;
  52746. MemPage *pPage1;
  52747. sqlite3BtreeEnter(p);
  52748. if( tripCode==SQLITE_OK ){
  52749. rc = tripCode = saveAllCursors(pBt, 0, 0);
  52750. }else{
  52751. rc = SQLITE_OK;
  52752. }
  52753. if( tripCode ){
  52754. sqlite3BtreeTripAllCursors(p, tripCode);
  52755. }
  52756. btreeIntegrity(p);
  52757. if( p->inTrans==TRANS_WRITE ){
  52758. int rc2;
  52759. assert( TRANS_WRITE==pBt->inTransaction );
  52760. rc2 = sqlite3PagerRollback(pBt->pPager);
  52761. if( rc2!=SQLITE_OK ){
  52762. rc = rc2;
  52763. }
  52764. /* The rollback may have destroyed the pPage1->aData value. So
  52765. ** call btreeGetPage() on page 1 again to make
  52766. ** sure pPage1->aData is set correctly. */
  52767. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  52768. int nPage = get4byte(28+(u8*)pPage1->aData);
  52769. testcase( nPage==0 );
  52770. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  52771. testcase( pBt->nPage!=nPage );
  52772. pBt->nPage = nPage;
  52773. releasePage(pPage1);
  52774. }
  52775. assert( countValidCursors(pBt, 1)==0 );
  52776. pBt->inTransaction = TRANS_READ;
  52777. btreeClearHasContent(pBt);
  52778. }
  52779. btreeEndTransaction(p);
  52780. sqlite3BtreeLeave(p);
  52781. return rc;
  52782. }
  52783. /*
  52784. ** Start a statement subtransaction. The subtransaction can can be rolled
  52785. ** back independently of the main transaction. You must start a transaction
  52786. ** before starting a subtransaction. The subtransaction is ended automatically
  52787. ** if the main transaction commits or rolls back.
  52788. **
  52789. ** Statement subtransactions are used around individual SQL statements
  52790. ** that are contained within a BEGIN...COMMIT block. If a constraint
  52791. ** error occurs within the statement, the effect of that one statement
  52792. ** can be rolled back without having to rollback the entire transaction.
  52793. **
  52794. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  52795. ** value passed as the second parameter is the total number of savepoints,
  52796. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  52797. ** are no active savepoints and no other statement-transactions open,
  52798. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  52799. ** using the sqlite3BtreeSavepoint() function.
  52800. */
  52801. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  52802. int rc;
  52803. BtShared *pBt = p->pBt;
  52804. sqlite3BtreeEnter(p);
  52805. assert( p->inTrans==TRANS_WRITE );
  52806. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52807. assert( iStatement>0 );
  52808. assert( iStatement>p->db->nSavepoint );
  52809. assert( pBt->inTransaction==TRANS_WRITE );
  52810. /* At the pager level, a statement transaction is a savepoint with
  52811. ** an index greater than all savepoints created explicitly using
  52812. ** SQL statements. It is illegal to open, release or rollback any
  52813. ** such savepoints while the statement transaction savepoint is active.
  52814. */
  52815. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  52816. sqlite3BtreeLeave(p);
  52817. return rc;
  52818. }
  52819. /*
  52820. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  52821. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  52822. ** savepoint identified by parameter iSavepoint, depending on the value
  52823. ** of op.
  52824. **
  52825. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  52826. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  52827. ** contents of the entire transaction are rolled back. This is different
  52828. ** from a normal transaction rollback, as no locks are released and the
  52829. ** transaction remains open.
  52830. */
  52831. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  52832. int rc = SQLITE_OK;
  52833. if( p && p->inTrans==TRANS_WRITE ){
  52834. BtShared *pBt = p->pBt;
  52835. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52836. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  52837. sqlite3BtreeEnter(p);
  52838. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  52839. if( rc==SQLITE_OK ){
  52840. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  52841. pBt->nPage = 0;
  52842. }
  52843. rc = newDatabase(pBt);
  52844. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  52845. /* The database size was written into the offset 28 of the header
  52846. ** when the transaction started, so we know that the value at offset
  52847. ** 28 is nonzero. */
  52848. assert( pBt->nPage>0 );
  52849. }
  52850. sqlite3BtreeLeave(p);
  52851. }
  52852. return rc;
  52853. }
  52854. /*
  52855. ** Create a new cursor for the BTree whose root is on the page
  52856. ** iTable. If a read-only cursor is requested, it is assumed that
  52857. ** the caller already has at least a read-only transaction open
  52858. ** on the database already. If a write-cursor is requested, then
  52859. ** the caller is assumed to have an open write transaction.
  52860. **
  52861. ** If wrFlag==0, then the cursor can only be used for reading.
  52862. ** If wrFlag==1, then the cursor can be used for reading or for
  52863. ** writing if other conditions for writing are also met. These
  52864. ** are the conditions that must be met in order for writing to
  52865. ** be allowed:
  52866. **
  52867. ** 1: The cursor must have been opened with wrFlag==1
  52868. **
  52869. ** 2: Other database connections that share the same pager cache
  52870. ** but which are not in the READ_UNCOMMITTED state may not have
  52871. ** cursors open with wrFlag==0 on the same table. Otherwise
  52872. ** the changes made by this write cursor would be visible to
  52873. ** the read cursors in the other database connection.
  52874. **
  52875. ** 3: The database must be writable (not on read-only media)
  52876. **
  52877. ** 4: There must be an active transaction.
  52878. **
  52879. ** No checking is done to make sure that page iTable really is the
  52880. ** root page of a b-tree. If it is not, then the cursor acquired
  52881. ** will not work correctly.
  52882. **
  52883. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  52884. ** on pCur to initialize the memory space prior to invoking this routine.
  52885. */
  52886. static int btreeCursor(
  52887. Btree *p, /* The btree */
  52888. int iTable, /* Root page of table to open */
  52889. int wrFlag, /* 1 to write. 0 read-only */
  52890. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  52891. BtCursor *pCur /* Space for new cursor */
  52892. ){
  52893. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  52894. assert( sqlite3BtreeHoldsMutex(p) );
  52895. assert( wrFlag==0 || wrFlag==1 );
  52896. /* The following assert statements verify that if this is a sharable
  52897. ** b-tree database, the connection is holding the required table locks,
  52898. ** and that no other connection has any open cursor that conflicts with
  52899. ** this lock. */
  52900. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  52901. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  52902. /* Assert that the caller has opened the required transaction. */
  52903. assert( p->inTrans>TRANS_NONE );
  52904. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  52905. assert( pBt->pPage1 && pBt->pPage1->aData );
  52906. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  52907. return SQLITE_READONLY;
  52908. }
  52909. if( iTable==1 && btreePagecount(pBt)==0 ){
  52910. assert( wrFlag==0 );
  52911. iTable = 0;
  52912. }
  52913. /* Now that no other errors can occur, finish filling in the BtCursor
  52914. ** variables and link the cursor into the BtShared list. */
  52915. pCur->pgnoRoot = (Pgno)iTable;
  52916. pCur->iPage = -1;
  52917. pCur->pKeyInfo = pKeyInfo;
  52918. pCur->pBtree = p;
  52919. pCur->pBt = pBt;
  52920. pCur->wrFlag = (u8)wrFlag;
  52921. pCur->pNext = pBt->pCursor;
  52922. if( pCur->pNext ){
  52923. pCur->pNext->pPrev = pCur;
  52924. }
  52925. pBt->pCursor = pCur;
  52926. pCur->eState = CURSOR_INVALID;
  52927. pCur->cachedRowid = 0;
  52928. return SQLITE_OK;
  52929. }
  52930. SQLITE_PRIVATE int sqlite3BtreeCursor(
  52931. Btree *p, /* The btree */
  52932. int iTable, /* Root page of table to open */
  52933. int wrFlag, /* 1 to write. 0 read-only */
  52934. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  52935. BtCursor *pCur /* Write new cursor here */
  52936. ){
  52937. int rc;
  52938. sqlite3BtreeEnter(p);
  52939. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  52940. sqlite3BtreeLeave(p);
  52941. return rc;
  52942. }
  52943. /*
  52944. ** Return the size of a BtCursor object in bytes.
  52945. **
  52946. ** This interfaces is needed so that users of cursors can preallocate
  52947. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  52948. ** to users so they cannot do the sizeof() themselves - they must call
  52949. ** this routine.
  52950. */
  52951. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  52952. return ROUND8(sizeof(BtCursor));
  52953. }
  52954. /*
  52955. ** Initialize memory that will be converted into a BtCursor object.
  52956. **
  52957. ** The simple approach here would be to memset() the entire object
  52958. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  52959. ** do not need to be zeroed and they are large, so we can save a lot
  52960. ** of run-time by skipping the initialization of those elements.
  52961. */
  52962. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  52963. memset(p, 0, offsetof(BtCursor, iPage));
  52964. }
  52965. /*
  52966. ** Set the cached rowid value of every cursor in the same database file
  52967. ** as pCur and having the same root page number as pCur. The value is
  52968. ** set to iRowid.
  52969. **
  52970. ** Only positive rowid values are considered valid for this cache.
  52971. ** The cache is initialized to zero, indicating an invalid cache.
  52972. ** A btree will work fine with zero or negative rowids. We just cannot
  52973. ** cache zero or negative rowids, which means tables that use zero or
  52974. ** negative rowids might run a little slower. But in practice, zero
  52975. ** or negative rowids are very uncommon so this should not be a problem.
  52976. */
  52977. SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
  52978. BtCursor *p;
  52979. for(p=pCur->pBt->pCursor; p; p=p->pNext){
  52980. if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
  52981. }
  52982. assert( pCur->cachedRowid==iRowid );
  52983. }
  52984. /*
  52985. ** Return the cached rowid for the given cursor. A negative or zero
  52986. ** return value indicates that the rowid cache is invalid and should be
  52987. ** ignored. If the rowid cache has never before been set, then a
  52988. ** zero is returned.
  52989. */
  52990. SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
  52991. return pCur->cachedRowid;
  52992. }
  52993. /*
  52994. ** Close a cursor. The read lock on the database file is released
  52995. ** when the last cursor is closed.
  52996. */
  52997. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  52998. Btree *pBtree = pCur->pBtree;
  52999. if( pBtree ){
  53000. int i;
  53001. BtShared *pBt = pCur->pBt;
  53002. sqlite3BtreeEnter(pBtree);
  53003. sqlite3BtreeClearCursor(pCur);
  53004. if( pCur->pPrev ){
  53005. pCur->pPrev->pNext = pCur->pNext;
  53006. }else{
  53007. pBt->pCursor = pCur->pNext;
  53008. }
  53009. if( pCur->pNext ){
  53010. pCur->pNext->pPrev = pCur->pPrev;
  53011. }
  53012. for(i=0; i<=pCur->iPage; i++){
  53013. releasePage(pCur->apPage[i]);
  53014. }
  53015. unlockBtreeIfUnused(pBt);
  53016. invalidateOverflowCache(pCur);
  53017. /* sqlite3_free(pCur); */
  53018. sqlite3BtreeLeave(pBtree);
  53019. }
  53020. return SQLITE_OK;
  53021. }
  53022. /*
  53023. ** Make sure the BtCursor* given in the argument has a valid
  53024. ** BtCursor.info structure. If it is not already valid, call
  53025. ** btreeParseCell() to fill it in.
  53026. **
  53027. ** BtCursor.info is a cache of the information in the current cell.
  53028. ** Using this cache reduces the number of calls to btreeParseCell().
  53029. **
  53030. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  53031. ** compiler to crash when getCellInfo() is implemented as a macro.
  53032. ** But there is a measureable speed advantage to using the macro on gcc
  53033. ** (when less compiler optimizations like -Os or -O0 are used and the
  53034. ** compiler is not doing agressive inlining.) So we use a real function
  53035. ** for MSVC and a macro for everything else. Ticket #2457.
  53036. */
  53037. #ifndef NDEBUG
  53038. static void assertCellInfo(BtCursor *pCur){
  53039. CellInfo info;
  53040. int iPage = pCur->iPage;
  53041. memset(&info, 0, sizeof(info));
  53042. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  53043. assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
  53044. }
  53045. #else
  53046. #define assertCellInfo(x)
  53047. #endif
  53048. #ifdef _MSC_VER
  53049. /* Use a real function in MSVC to work around bugs in that compiler. */
  53050. static void getCellInfo(BtCursor *pCur){
  53051. if( pCur->info.nSize==0 ){
  53052. int iPage = pCur->iPage;
  53053. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  53054. pCur->validNKey = 1;
  53055. }else{
  53056. assertCellInfo(pCur);
  53057. }
  53058. }
  53059. #else /* if not _MSC_VER */
  53060. /* Use a macro in all other compilers so that the function is inlined */
  53061. #define getCellInfo(pCur) \
  53062. if( pCur->info.nSize==0 ){ \
  53063. int iPage = pCur->iPage; \
  53064. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  53065. pCur->validNKey = 1; \
  53066. }else{ \
  53067. assertCellInfo(pCur); \
  53068. }
  53069. #endif /* _MSC_VER */
  53070. #ifndef NDEBUG /* The next routine used only within assert() statements */
  53071. /*
  53072. ** Return true if the given BtCursor is valid. A valid cursor is one
  53073. ** that is currently pointing to a row in a (non-empty) table.
  53074. ** This is a verification routine is used only within assert() statements.
  53075. */
  53076. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  53077. return pCur && pCur->eState==CURSOR_VALID;
  53078. }
  53079. #endif /* NDEBUG */
  53080. /*
  53081. ** Set *pSize to the size of the buffer needed to hold the value of
  53082. ** the key for the current entry. If the cursor is not pointing
  53083. ** to a valid entry, *pSize is set to 0.
  53084. **
  53085. ** For a table with the INTKEY flag set, this routine returns the key
  53086. ** itself, not the number of bytes in the key.
  53087. **
  53088. ** The caller must position the cursor prior to invoking this routine.
  53089. **
  53090. ** This routine cannot fail. It always returns SQLITE_OK.
  53091. */
  53092. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  53093. assert( cursorHoldsMutex(pCur) );
  53094. assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
  53095. if( pCur->eState!=CURSOR_VALID ){
  53096. *pSize = 0;
  53097. }else{
  53098. getCellInfo(pCur);
  53099. *pSize = pCur->info.nKey;
  53100. }
  53101. return SQLITE_OK;
  53102. }
  53103. /*
  53104. ** Set *pSize to the number of bytes of data in the entry the
  53105. ** cursor currently points to.
  53106. **
  53107. ** The caller must guarantee that the cursor is pointing to a non-NULL
  53108. ** valid entry. In other words, the calling procedure must guarantee
  53109. ** that the cursor has Cursor.eState==CURSOR_VALID.
  53110. **
  53111. ** Failure is not possible. This function always returns SQLITE_OK.
  53112. ** It might just as well be a procedure (returning void) but we continue
  53113. ** to return an integer result code for historical reasons.
  53114. */
  53115. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  53116. assert( cursorHoldsMutex(pCur) );
  53117. assert( pCur->eState==CURSOR_VALID );
  53118. getCellInfo(pCur);
  53119. *pSize = pCur->info.nData;
  53120. return SQLITE_OK;
  53121. }
  53122. /*
  53123. ** Given the page number of an overflow page in the database (parameter
  53124. ** ovfl), this function finds the page number of the next page in the
  53125. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  53126. ** pointer-map data instead of reading the content of page ovfl to do so.
  53127. **
  53128. ** If an error occurs an SQLite error code is returned. Otherwise:
  53129. **
  53130. ** The page number of the next overflow page in the linked list is
  53131. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  53132. ** list, *pPgnoNext is set to zero.
  53133. **
  53134. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  53135. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  53136. ** reference. It is the responsibility of the caller to call releasePage()
  53137. ** on *ppPage to free the reference. In no reference was obtained (because
  53138. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  53139. ** *ppPage is set to zero.
  53140. */
  53141. static int getOverflowPage(
  53142. BtShared *pBt, /* The database file */
  53143. Pgno ovfl, /* Current overflow page number */
  53144. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  53145. Pgno *pPgnoNext /* OUT: Next overflow page number */
  53146. ){
  53147. Pgno next = 0;
  53148. MemPage *pPage = 0;
  53149. int rc = SQLITE_OK;
  53150. assert( sqlite3_mutex_held(pBt->mutex) );
  53151. assert(pPgnoNext);
  53152. #ifndef SQLITE_OMIT_AUTOVACUUM
  53153. /* Try to find the next page in the overflow list using the
  53154. ** autovacuum pointer-map pages. Guess that the next page in
  53155. ** the overflow list is page number (ovfl+1). If that guess turns
  53156. ** out to be wrong, fall back to loading the data of page
  53157. ** number ovfl to determine the next page number.
  53158. */
  53159. if( pBt->autoVacuum ){
  53160. Pgno pgno;
  53161. Pgno iGuess = ovfl+1;
  53162. u8 eType;
  53163. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  53164. iGuess++;
  53165. }
  53166. if( iGuess<=btreePagecount(pBt) ){
  53167. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  53168. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  53169. next = iGuess;
  53170. rc = SQLITE_DONE;
  53171. }
  53172. }
  53173. }
  53174. #endif
  53175. assert( next==0 || rc==SQLITE_DONE );
  53176. if( rc==SQLITE_OK ){
  53177. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  53178. assert( rc==SQLITE_OK || pPage==0 );
  53179. if( rc==SQLITE_OK ){
  53180. next = get4byte(pPage->aData);
  53181. }
  53182. }
  53183. *pPgnoNext = next;
  53184. if( ppPage ){
  53185. *ppPage = pPage;
  53186. }else{
  53187. releasePage(pPage);
  53188. }
  53189. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  53190. }
  53191. /*
  53192. ** Copy data from a buffer to a page, or from a page to a buffer.
  53193. **
  53194. ** pPayload is a pointer to data stored on database page pDbPage.
  53195. ** If argument eOp is false, then nByte bytes of data are copied
  53196. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  53197. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  53198. ** of data are copied from the buffer pBuf to pPayload.
  53199. **
  53200. ** SQLITE_OK is returned on success, otherwise an error code.
  53201. */
  53202. static int copyPayload(
  53203. void *pPayload, /* Pointer to page data */
  53204. void *pBuf, /* Pointer to buffer */
  53205. int nByte, /* Number of bytes to copy */
  53206. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  53207. DbPage *pDbPage /* Page containing pPayload */
  53208. ){
  53209. if( eOp ){
  53210. /* Copy data from buffer to page (a write operation) */
  53211. int rc = sqlite3PagerWrite(pDbPage);
  53212. if( rc!=SQLITE_OK ){
  53213. return rc;
  53214. }
  53215. memcpy(pPayload, pBuf, nByte);
  53216. }else{
  53217. /* Copy data from page to buffer (a read operation) */
  53218. memcpy(pBuf, pPayload, nByte);
  53219. }
  53220. return SQLITE_OK;
  53221. }
  53222. /*
  53223. ** This function is used to read or overwrite payload information
  53224. ** for the entry that the pCur cursor is pointing to. If the eOp
  53225. ** parameter is 0, this is a read operation (data copied into
  53226. ** buffer pBuf). If it is non-zero, a write (data copied from
  53227. ** buffer pBuf).
  53228. **
  53229. ** A total of "amt" bytes are read or written beginning at "offset".
  53230. ** Data is read to or from the buffer pBuf.
  53231. **
  53232. ** The content being read or written might appear on the main page
  53233. ** or be scattered out on multiple overflow pages.
  53234. **
  53235. ** If the BtCursor.isIncrblobHandle flag is set, and the current
  53236. ** cursor entry uses one or more overflow pages, this function
  53237. ** allocates space for and lazily popluates the overflow page-list
  53238. ** cache array (BtCursor.aOverflow). Subsequent calls use this
  53239. ** cache to make seeking to the supplied offset more efficient.
  53240. **
  53241. ** Once an overflow page-list cache has been allocated, it may be
  53242. ** invalidated if some other cursor writes to the same table, or if
  53243. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  53244. ** mode, the following events may invalidate an overflow page-list cache.
  53245. **
  53246. ** * An incremental vacuum,
  53247. ** * A commit in auto_vacuum="full" mode,
  53248. ** * Creating a table (may require moving an overflow page).
  53249. */
  53250. static int accessPayload(
  53251. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53252. u32 offset, /* Begin reading this far into payload */
  53253. u32 amt, /* Read this many bytes */
  53254. unsigned char *pBuf, /* Write the bytes into this buffer */
  53255. int eOp /* zero to read. non-zero to write. */
  53256. ){
  53257. unsigned char *aPayload;
  53258. int rc = SQLITE_OK;
  53259. u32 nKey;
  53260. int iIdx = 0;
  53261. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  53262. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  53263. assert( pPage );
  53264. assert( pCur->eState==CURSOR_VALID );
  53265. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53266. assert( cursorHoldsMutex(pCur) );
  53267. getCellInfo(pCur);
  53268. aPayload = pCur->info.pCell + pCur->info.nHeader;
  53269. nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
  53270. if( NEVER(offset+amt > nKey+pCur->info.nData)
  53271. || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
  53272. ){
  53273. /* Trying to read or write past the end of the data is an error */
  53274. return SQLITE_CORRUPT_BKPT;
  53275. }
  53276. /* Check if data must be read/written to/from the btree page itself. */
  53277. if( offset<pCur->info.nLocal ){
  53278. int a = amt;
  53279. if( a+offset>pCur->info.nLocal ){
  53280. a = pCur->info.nLocal - offset;
  53281. }
  53282. rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
  53283. offset = 0;
  53284. pBuf += a;
  53285. amt -= a;
  53286. }else{
  53287. offset -= pCur->info.nLocal;
  53288. }
  53289. if( rc==SQLITE_OK && amt>0 ){
  53290. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  53291. Pgno nextPage;
  53292. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  53293. #ifndef SQLITE_OMIT_INCRBLOB
  53294. /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
  53295. ** has not been allocated, allocate it now. The array is sized at
  53296. ** one entry for each overflow page in the overflow chain. The
  53297. ** page number of the first overflow page is stored in aOverflow[0],
  53298. ** etc. A value of 0 in the aOverflow[] array means "not yet known"
  53299. ** (the cache is lazily populated).
  53300. */
  53301. if( pCur->isIncrblobHandle && !pCur->aOverflow ){
  53302. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  53303. pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
  53304. /* nOvfl is always positive. If it were zero, fetchPayload would have
  53305. ** been used instead of this routine. */
  53306. if( ALWAYS(nOvfl) && !pCur->aOverflow ){
  53307. rc = SQLITE_NOMEM;
  53308. }
  53309. }
  53310. /* If the overflow page-list cache has been allocated and the
  53311. ** entry for the first required overflow page is valid, skip
  53312. ** directly to it.
  53313. */
  53314. if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
  53315. iIdx = (offset/ovflSize);
  53316. nextPage = pCur->aOverflow[iIdx];
  53317. offset = (offset%ovflSize);
  53318. }
  53319. #endif
  53320. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  53321. #ifndef SQLITE_OMIT_INCRBLOB
  53322. /* If required, populate the overflow page-list cache. */
  53323. if( pCur->aOverflow ){
  53324. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  53325. pCur->aOverflow[iIdx] = nextPage;
  53326. }
  53327. #endif
  53328. if( offset>=ovflSize ){
  53329. /* The only reason to read this page is to obtain the page
  53330. ** number for the next page in the overflow chain. The page
  53331. ** data is not required. So first try to lookup the overflow
  53332. ** page-list cache, if any, then fall back to the getOverflowPage()
  53333. ** function.
  53334. */
  53335. #ifndef SQLITE_OMIT_INCRBLOB
  53336. if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
  53337. nextPage = pCur->aOverflow[iIdx+1];
  53338. } else
  53339. #endif
  53340. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  53341. offset -= ovflSize;
  53342. }else{
  53343. /* Need to read this page properly. It contains some of the
  53344. ** range of data that is being read (eOp==0) or written (eOp!=0).
  53345. */
  53346. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53347. sqlite3_file *fd;
  53348. #endif
  53349. int a = amt;
  53350. if( a + offset > ovflSize ){
  53351. a = ovflSize - offset;
  53352. }
  53353. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  53354. /* If all the following are true:
  53355. **
  53356. ** 1) this is a read operation, and
  53357. ** 2) data is required from the start of this overflow page, and
  53358. ** 3) the database is file-backed, and
  53359. ** 4) there is no open write-transaction, and
  53360. ** 5) the database is not a WAL database,
  53361. **
  53362. ** then data can be read directly from the database file into the
  53363. ** output buffer, bypassing the page-cache altogether. This speeds
  53364. ** up loading large records that span many overflow pages.
  53365. */
  53366. if( eOp==0 /* (1) */
  53367. && offset==0 /* (2) */
  53368. && pBt->inTransaction==TRANS_READ /* (4) */
  53369. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  53370. && pBt->pPage1->aData[19]==0x01 /* (5) */
  53371. ){
  53372. u8 aSave[4];
  53373. u8 *aWrite = &pBuf[-4];
  53374. memcpy(aSave, aWrite, 4);
  53375. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  53376. nextPage = get4byte(aWrite);
  53377. memcpy(aWrite, aSave, 4);
  53378. }else
  53379. #endif
  53380. {
  53381. DbPage *pDbPage;
  53382. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  53383. (eOp==0 ? PAGER_GET_READONLY : 0)
  53384. );
  53385. if( rc==SQLITE_OK ){
  53386. aPayload = sqlite3PagerGetData(pDbPage);
  53387. nextPage = get4byte(aPayload);
  53388. rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
  53389. sqlite3PagerUnref(pDbPage);
  53390. offset = 0;
  53391. }
  53392. }
  53393. amt -= a;
  53394. pBuf += a;
  53395. }
  53396. }
  53397. }
  53398. if( rc==SQLITE_OK && amt>0 ){
  53399. return SQLITE_CORRUPT_BKPT;
  53400. }
  53401. return rc;
  53402. }
  53403. /*
  53404. ** Read part of the key associated with cursor pCur. Exactly
  53405. ** "amt" bytes will be transfered into pBuf[]. The transfer
  53406. ** begins at "offset".
  53407. **
  53408. ** The caller must ensure that pCur is pointing to a valid row
  53409. ** in the table.
  53410. **
  53411. ** Return SQLITE_OK on success or an error code if anything goes
  53412. ** wrong. An error is returned if "offset+amt" is larger than
  53413. ** the available payload.
  53414. */
  53415. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53416. assert( cursorHoldsMutex(pCur) );
  53417. assert( pCur->eState==CURSOR_VALID );
  53418. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53419. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53420. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  53421. }
  53422. /*
  53423. ** Read part of the data associated with cursor pCur. Exactly
  53424. ** "amt" bytes will be transfered into pBuf[]. The transfer
  53425. ** begins at "offset".
  53426. **
  53427. ** Return SQLITE_OK on success or an error code if anything goes
  53428. ** wrong. An error is returned if "offset+amt" is larger than
  53429. ** the available payload.
  53430. */
  53431. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  53432. int rc;
  53433. #ifndef SQLITE_OMIT_INCRBLOB
  53434. if ( pCur->eState==CURSOR_INVALID ){
  53435. return SQLITE_ABORT;
  53436. }
  53437. #endif
  53438. assert( cursorHoldsMutex(pCur) );
  53439. rc = restoreCursorPosition(pCur);
  53440. if( rc==SQLITE_OK ){
  53441. assert( pCur->eState==CURSOR_VALID );
  53442. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  53443. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53444. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  53445. }
  53446. return rc;
  53447. }
  53448. /*
  53449. ** Return a pointer to payload information from the entry that the
  53450. ** pCur cursor is pointing to. The pointer is to the beginning of
  53451. ** the key if skipKey==0 and it points to the beginning of data if
  53452. ** skipKey==1. The number of bytes of available key/data is written
  53453. ** into *pAmt. If *pAmt==0, then the value returned will not be
  53454. ** a valid pointer.
  53455. **
  53456. ** This routine is an optimization. It is common for the entire key
  53457. ** and data to fit on the local page and for there to be no overflow
  53458. ** pages. When that is so, this routine can be used to access the
  53459. ** key and data without making a copy. If the key and/or data spills
  53460. ** onto overflow pages, then accessPayload() must be used to reassemble
  53461. ** the key/data and copy it into a preallocated buffer.
  53462. **
  53463. ** The pointer returned by this routine looks directly into the cached
  53464. ** page of the database. The data might change or move the next time
  53465. ** any btree routine is called.
  53466. */
  53467. static const unsigned char *fetchPayload(
  53468. BtCursor *pCur, /* Cursor pointing to entry to read from */
  53469. int *pAmt, /* Write the number of available bytes here */
  53470. int skipKey /* read beginning at data if this is true */
  53471. ){
  53472. unsigned char *aPayload;
  53473. MemPage *pPage;
  53474. u32 nKey;
  53475. u32 nLocal;
  53476. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  53477. assert( pCur->eState==CURSOR_VALID );
  53478. assert( cursorHoldsMutex(pCur) );
  53479. pPage = pCur->apPage[pCur->iPage];
  53480. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53481. if( NEVER(pCur->info.nSize==0) ){
  53482. btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
  53483. &pCur->info);
  53484. }
  53485. aPayload = pCur->info.pCell;
  53486. aPayload += pCur->info.nHeader;
  53487. if( pPage->intKey ){
  53488. nKey = 0;
  53489. }else{
  53490. nKey = (int)pCur->info.nKey;
  53491. }
  53492. if( skipKey ){
  53493. aPayload += nKey;
  53494. nLocal = pCur->info.nLocal - nKey;
  53495. }else{
  53496. nLocal = pCur->info.nLocal;
  53497. assert( nLocal<=nKey );
  53498. }
  53499. *pAmt = nLocal;
  53500. return aPayload;
  53501. }
  53502. /*
  53503. ** For the entry that cursor pCur is point to, return as
  53504. ** many bytes of the key or data as are available on the local
  53505. ** b-tree page. Write the number of available bytes into *pAmt.
  53506. **
  53507. ** The pointer returned is ephemeral. The key/data may move
  53508. ** or be destroyed on the next call to any Btree routine,
  53509. ** including calls from other threads against the same cache.
  53510. ** Hence, a mutex on the BtShared should be held prior to calling
  53511. ** this routine.
  53512. **
  53513. ** These routines is used to get quick access to key and data
  53514. ** in the common case where no overflow pages are used.
  53515. */
  53516. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
  53517. const void *p = 0;
  53518. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53519. assert( cursorHoldsMutex(pCur) );
  53520. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  53521. p = (const void*)fetchPayload(pCur, pAmt, 0);
  53522. }
  53523. return p;
  53524. }
  53525. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
  53526. const void *p = 0;
  53527. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53528. assert( cursorHoldsMutex(pCur) );
  53529. if( ALWAYS(pCur->eState==CURSOR_VALID) ){
  53530. p = (const void*)fetchPayload(pCur, pAmt, 1);
  53531. }
  53532. return p;
  53533. }
  53534. /*
  53535. ** Move the cursor down to a new child page. The newPgno argument is the
  53536. ** page number of the child page to move to.
  53537. **
  53538. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  53539. ** the new child page does not match the flags field of the parent (i.e.
  53540. ** if an intkey page appears to be the parent of a non-intkey page, or
  53541. ** vice-versa).
  53542. */
  53543. static int moveToChild(BtCursor *pCur, u32 newPgno){
  53544. int rc;
  53545. int i = pCur->iPage;
  53546. MemPage *pNewPage;
  53547. BtShared *pBt = pCur->pBt;
  53548. assert( cursorHoldsMutex(pCur) );
  53549. assert( pCur->eState==CURSOR_VALID );
  53550. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  53551. assert( pCur->iPage>=0 );
  53552. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  53553. return SQLITE_CORRUPT_BKPT;
  53554. }
  53555. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  53556. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  53557. if( rc ) return rc;
  53558. pCur->apPage[i+1] = pNewPage;
  53559. pCur->aiIdx[i+1] = 0;
  53560. pCur->iPage++;
  53561. pCur->info.nSize = 0;
  53562. pCur->validNKey = 0;
  53563. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  53564. return SQLITE_CORRUPT_BKPT;
  53565. }
  53566. return SQLITE_OK;
  53567. }
  53568. #if 0
  53569. /*
  53570. ** Page pParent is an internal (non-leaf) tree page. This function
  53571. ** asserts that page number iChild is the left-child if the iIdx'th
  53572. ** cell in page pParent. Or, if iIdx is equal to the total number of
  53573. ** cells in pParent, that page number iChild is the right-child of
  53574. ** the page.
  53575. */
  53576. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  53577. assert( iIdx<=pParent->nCell );
  53578. if( iIdx==pParent->nCell ){
  53579. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  53580. }else{
  53581. assert( get4byte(findCell(pParent, iIdx))==iChild );
  53582. }
  53583. }
  53584. #else
  53585. # define assertParentIndex(x,y,z)
  53586. #endif
  53587. /*
  53588. ** Move the cursor up to the parent page.
  53589. **
  53590. ** pCur->idx is set to the cell index that contains the pointer
  53591. ** to the page we are coming from. If we are coming from the
  53592. ** right-most child page then pCur->idx is set to one more than
  53593. ** the largest cell index.
  53594. */
  53595. static void moveToParent(BtCursor *pCur){
  53596. assert( cursorHoldsMutex(pCur) );
  53597. assert( pCur->eState==CURSOR_VALID );
  53598. assert( pCur->iPage>0 );
  53599. assert( pCur->apPage[pCur->iPage] );
  53600. /* UPDATE: It is actually possible for the condition tested by the assert
  53601. ** below to be untrue if the database file is corrupt. This can occur if
  53602. ** one cursor has modified page pParent while a reference to it is held
  53603. ** by a second cursor. Which can only happen if a single page is linked
  53604. ** into more than one b-tree structure in a corrupt database. */
  53605. #if 0
  53606. assertParentIndex(
  53607. pCur->apPage[pCur->iPage-1],
  53608. pCur->aiIdx[pCur->iPage-1],
  53609. pCur->apPage[pCur->iPage]->pgno
  53610. );
  53611. #endif
  53612. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  53613. releasePage(pCur->apPage[pCur->iPage]);
  53614. pCur->iPage--;
  53615. pCur->info.nSize = 0;
  53616. pCur->validNKey = 0;
  53617. }
  53618. /*
  53619. ** Move the cursor to point to the root page of its b-tree structure.
  53620. **
  53621. ** If the table has a virtual root page, then the cursor is moved to point
  53622. ** to the virtual root page instead of the actual root page. A table has a
  53623. ** virtual root page when the actual root page contains no cells and a
  53624. ** single child page. This can only happen with the table rooted at page 1.
  53625. **
  53626. ** If the b-tree structure is empty, the cursor state is set to
  53627. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  53628. ** cell located on the root (or virtual root) page and the cursor state
  53629. ** is set to CURSOR_VALID.
  53630. **
  53631. ** If this function returns successfully, it may be assumed that the
  53632. ** page-header flags indicate that the [virtual] root-page is the expected
  53633. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  53634. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  53635. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  53636. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  53637. ** b-tree).
  53638. */
  53639. static int moveToRoot(BtCursor *pCur){
  53640. MemPage *pRoot;
  53641. int rc = SQLITE_OK;
  53642. Btree *p = pCur->pBtree;
  53643. BtShared *pBt = p->pBt;
  53644. assert( cursorHoldsMutex(pCur) );
  53645. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  53646. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  53647. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  53648. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  53649. if( pCur->eState==CURSOR_FAULT ){
  53650. assert( pCur->skipNext!=SQLITE_OK );
  53651. return pCur->skipNext;
  53652. }
  53653. sqlite3BtreeClearCursor(pCur);
  53654. }
  53655. if( pCur->iPage>=0 ){
  53656. int i;
  53657. for(i=1; i<=pCur->iPage; i++){
  53658. releasePage(pCur->apPage[i]);
  53659. }
  53660. pCur->iPage = 0;
  53661. }else if( pCur->pgnoRoot==0 ){
  53662. pCur->eState = CURSOR_INVALID;
  53663. return SQLITE_OK;
  53664. }else{
  53665. rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0],
  53666. pCur->wrFlag==0 ? PAGER_GET_READONLY : 0);
  53667. if( rc!=SQLITE_OK ){
  53668. pCur->eState = CURSOR_INVALID;
  53669. return rc;
  53670. }
  53671. pCur->iPage = 0;
  53672. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  53673. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  53674. ** NULL, the caller expects a table b-tree. If this is not the case,
  53675. ** return an SQLITE_CORRUPT error. */
  53676. assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
  53677. if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
  53678. return SQLITE_CORRUPT_BKPT;
  53679. }
  53680. }
  53681. /* Assert that the root page is of the correct type. This must be the
  53682. ** case as the call to this function that loaded the root-page (either
  53683. ** this call or a previous invocation) would have detected corruption
  53684. ** if the assumption were not true, and it is not possible for the flags
  53685. ** byte to have been modified while this cursor is holding a reference
  53686. ** to the page. */
  53687. pRoot = pCur->apPage[0];
  53688. assert( pRoot->pgno==pCur->pgnoRoot );
  53689. assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
  53690. pCur->aiIdx[0] = 0;
  53691. pCur->info.nSize = 0;
  53692. pCur->atLast = 0;
  53693. pCur->validNKey = 0;
  53694. if( pRoot->nCell==0 && !pRoot->leaf ){
  53695. Pgno subpage;
  53696. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  53697. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  53698. pCur->eState = CURSOR_VALID;
  53699. rc = moveToChild(pCur, subpage);
  53700. }else{
  53701. pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
  53702. }
  53703. return rc;
  53704. }
  53705. /*
  53706. ** Move the cursor down to the left-most leaf entry beneath the
  53707. ** entry to which it is currently pointing.
  53708. **
  53709. ** The left-most leaf is the one with the smallest key - the first
  53710. ** in ascending order.
  53711. */
  53712. static int moveToLeftmost(BtCursor *pCur){
  53713. Pgno pgno;
  53714. int rc = SQLITE_OK;
  53715. MemPage *pPage;
  53716. assert( cursorHoldsMutex(pCur) );
  53717. assert( pCur->eState==CURSOR_VALID );
  53718. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53719. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  53720. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  53721. rc = moveToChild(pCur, pgno);
  53722. }
  53723. return rc;
  53724. }
  53725. /*
  53726. ** Move the cursor down to the right-most leaf entry beneath the
  53727. ** page to which it is currently pointing. Notice the difference
  53728. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  53729. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  53730. ** finds the right-most entry beneath the *page*.
  53731. **
  53732. ** The right-most entry is the one with the largest key - the last
  53733. ** key in ascending order.
  53734. */
  53735. static int moveToRightmost(BtCursor *pCur){
  53736. Pgno pgno;
  53737. int rc = SQLITE_OK;
  53738. MemPage *pPage = 0;
  53739. assert( cursorHoldsMutex(pCur) );
  53740. assert( pCur->eState==CURSOR_VALID );
  53741. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  53742. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53743. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  53744. rc = moveToChild(pCur, pgno);
  53745. }
  53746. if( rc==SQLITE_OK ){
  53747. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  53748. pCur->info.nSize = 0;
  53749. pCur->validNKey = 0;
  53750. }
  53751. return rc;
  53752. }
  53753. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  53754. ** on success. Set *pRes to 0 if the cursor actually points to something
  53755. ** or set *pRes to 1 if the table is empty.
  53756. */
  53757. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  53758. int rc;
  53759. assert( cursorHoldsMutex(pCur) );
  53760. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53761. rc = moveToRoot(pCur);
  53762. if( rc==SQLITE_OK ){
  53763. if( pCur->eState==CURSOR_INVALID ){
  53764. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53765. *pRes = 1;
  53766. }else{
  53767. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  53768. *pRes = 0;
  53769. rc = moveToLeftmost(pCur);
  53770. }
  53771. }
  53772. return rc;
  53773. }
  53774. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  53775. ** on success. Set *pRes to 0 if the cursor actually points to something
  53776. ** or set *pRes to 1 if the table is empty.
  53777. */
  53778. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  53779. int rc;
  53780. assert( cursorHoldsMutex(pCur) );
  53781. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53782. /* If the cursor already points to the last entry, this is a no-op. */
  53783. if( CURSOR_VALID==pCur->eState && pCur->atLast ){
  53784. #ifdef SQLITE_DEBUG
  53785. /* This block serves to assert() that the cursor really does point
  53786. ** to the last entry in the b-tree. */
  53787. int ii;
  53788. for(ii=0; ii<pCur->iPage; ii++){
  53789. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  53790. }
  53791. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  53792. assert( pCur->apPage[pCur->iPage]->leaf );
  53793. #endif
  53794. return SQLITE_OK;
  53795. }
  53796. rc = moveToRoot(pCur);
  53797. if( rc==SQLITE_OK ){
  53798. if( CURSOR_INVALID==pCur->eState ){
  53799. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53800. *pRes = 1;
  53801. }else{
  53802. assert( pCur->eState==CURSOR_VALID );
  53803. *pRes = 0;
  53804. rc = moveToRightmost(pCur);
  53805. pCur->atLast = rc==SQLITE_OK ?1:0;
  53806. }
  53807. }
  53808. return rc;
  53809. }
  53810. /* Move the cursor so that it points to an entry near the key
  53811. ** specified by pIdxKey or intKey. Return a success code.
  53812. **
  53813. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  53814. ** must be NULL. For index tables, pIdxKey is used and intKey
  53815. ** is ignored.
  53816. **
  53817. ** If an exact match is not found, then the cursor is always
  53818. ** left pointing at a leaf page which would hold the entry if it
  53819. ** were present. The cursor might point to an entry that comes
  53820. ** before or after the key.
  53821. **
  53822. ** An integer is written into *pRes which is the result of
  53823. ** comparing the key with the entry to which the cursor is
  53824. ** pointing. The meaning of the integer written into
  53825. ** *pRes is as follows:
  53826. **
  53827. ** *pRes<0 The cursor is left pointing at an entry that
  53828. ** is smaller than intKey/pIdxKey or if the table is empty
  53829. ** and the cursor is therefore left point to nothing.
  53830. **
  53831. ** *pRes==0 The cursor is left pointing at an entry that
  53832. ** exactly matches intKey/pIdxKey.
  53833. **
  53834. ** *pRes>0 The cursor is left pointing at an entry that
  53835. ** is larger than intKey/pIdxKey.
  53836. **
  53837. */
  53838. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  53839. BtCursor *pCur, /* The cursor to be moved */
  53840. UnpackedRecord *pIdxKey, /* Unpacked index key */
  53841. i64 intKey, /* The table key */
  53842. int biasRight, /* If true, bias the search to the high end */
  53843. int *pRes /* Write search results here */
  53844. ){
  53845. int rc;
  53846. assert( cursorHoldsMutex(pCur) );
  53847. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53848. assert( pRes );
  53849. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  53850. /* If the cursor is already positioned at the point we are trying
  53851. ** to move to, then just return without doing any work */
  53852. if( pCur->eState==CURSOR_VALID && pCur->validNKey
  53853. && pCur->apPage[0]->intKey
  53854. ){
  53855. if( pCur->info.nKey==intKey ){
  53856. *pRes = 0;
  53857. return SQLITE_OK;
  53858. }
  53859. if( pCur->atLast && pCur->info.nKey<intKey ){
  53860. *pRes = -1;
  53861. return SQLITE_OK;
  53862. }
  53863. }
  53864. rc = moveToRoot(pCur);
  53865. if( rc ){
  53866. return rc;
  53867. }
  53868. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  53869. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  53870. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  53871. if( pCur->eState==CURSOR_INVALID ){
  53872. *pRes = -1;
  53873. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53874. return SQLITE_OK;
  53875. }
  53876. assert( pCur->apPage[0]->intKey || pIdxKey );
  53877. for(;;){
  53878. int lwr, upr, idx;
  53879. Pgno chldPg;
  53880. MemPage *pPage = pCur->apPage[pCur->iPage];
  53881. int c;
  53882. /* pPage->nCell must be greater than zero. If this is the root-page
  53883. ** the cursor would have been INVALID above and this for(;;) loop
  53884. ** not run. If this is not the root-page, then the moveToChild() routine
  53885. ** would have already detected db corruption. Similarly, pPage must
  53886. ** be the right kind (index or table) of b-tree page. Otherwise
  53887. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  53888. assert( pPage->nCell>0 );
  53889. assert( pPage->intKey==(pIdxKey==0) );
  53890. lwr = 0;
  53891. upr = pPage->nCell-1;
  53892. if( biasRight ){
  53893. pCur->aiIdx[pCur->iPage] = (u16)(idx = upr);
  53894. }else{
  53895. pCur->aiIdx[pCur->iPage] = (u16)(idx = (upr+lwr)/2);
  53896. }
  53897. for(;;){
  53898. u8 *pCell; /* Pointer to current cell in pPage */
  53899. assert( idx==pCur->aiIdx[pCur->iPage] );
  53900. pCur->info.nSize = 0;
  53901. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53902. if( pPage->intKey ){
  53903. i64 nCellKey;
  53904. if( pPage->hasData ){
  53905. u32 dummy;
  53906. pCell += getVarint32(pCell, dummy);
  53907. }
  53908. getVarint(pCell, (u64*)&nCellKey);
  53909. if( nCellKey==intKey ){
  53910. c = 0;
  53911. }else if( nCellKey<intKey ){
  53912. c = -1;
  53913. }else{
  53914. assert( nCellKey>intKey );
  53915. c = +1;
  53916. }
  53917. pCur->validNKey = 1;
  53918. pCur->info.nKey = nCellKey;
  53919. }else{
  53920. /* The maximum supported page-size is 65536 bytes. This means that
  53921. ** the maximum number of record bytes stored on an index B-Tree
  53922. ** page is less than 16384 bytes and may be stored as a 2-byte
  53923. ** varint. This information is used to attempt to avoid parsing
  53924. ** the entire cell by checking for the cases where the record is
  53925. ** stored entirely within the b-tree page by inspecting the first
  53926. ** 2 bytes of the cell.
  53927. */
  53928. int nCell = pCell[0];
  53929. if( nCell<=pPage->max1bytePayload
  53930. /* && (pCell+nCell)<pPage->aDataEnd */
  53931. ){
  53932. /* This branch runs if the record-size field of the cell is a
  53933. ** single byte varint and the record fits entirely on the main
  53934. ** b-tree page. */
  53935. testcase( pCell+nCell+1==pPage->aDataEnd );
  53936. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  53937. }else if( !(pCell[1] & 0x80)
  53938. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  53939. /* && (pCell+nCell+2)<=pPage->aDataEnd */
  53940. ){
  53941. /* The record-size field is a 2 byte varint and the record
  53942. ** fits entirely on the main b-tree page. */
  53943. testcase( pCell+nCell+2==pPage->aDataEnd );
  53944. c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  53945. }else{
  53946. /* The record flows over onto one or more overflow pages. In
  53947. ** this case the whole cell needs to be parsed, a buffer allocated
  53948. ** and accessPayload() used to retrieve the record into the
  53949. ** buffer before VdbeRecordCompare() can be called. */
  53950. void *pCellKey;
  53951. u8 * const pCellBody = pCell - pPage->childPtrSize;
  53952. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  53953. nCell = (int)pCur->info.nKey;
  53954. pCellKey = sqlite3Malloc( nCell );
  53955. if( pCellKey==0 ){
  53956. rc = SQLITE_NOMEM;
  53957. goto moveto_finish;
  53958. }
  53959. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
  53960. if( rc ){
  53961. sqlite3_free(pCellKey);
  53962. goto moveto_finish;
  53963. }
  53964. c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
  53965. sqlite3_free(pCellKey);
  53966. }
  53967. }
  53968. if( c==0 ){
  53969. if( pPage->intKey && !pPage->leaf ){
  53970. lwr = idx;
  53971. break;
  53972. }else{
  53973. *pRes = 0;
  53974. rc = SQLITE_OK;
  53975. goto moveto_finish;
  53976. }
  53977. }
  53978. if( c<0 ){
  53979. lwr = idx+1;
  53980. }else{
  53981. upr = idx-1;
  53982. }
  53983. if( lwr>upr ){
  53984. break;
  53985. }
  53986. pCur->aiIdx[pCur->iPage] = (u16)(idx = (lwr+upr)/2);
  53987. }
  53988. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  53989. assert( pPage->isInit );
  53990. if( pPage->leaf ){
  53991. chldPg = 0;
  53992. }else if( lwr>=pPage->nCell ){
  53993. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53994. }else{
  53995. chldPg = get4byte(findCell(pPage, lwr));
  53996. }
  53997. if( chldPg==0 ){
  53998. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53999. *pRes = c;
  54000. rc = SQLITE_OK;
  54001. goto moveto_finish;
  54002. }
  54003. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  54004. pCur->info.nSize = 0;
  54005. pCur->validNKey = 0;
  54006. rc = moveToChild(pCur, chldPg);
  54007. if( rc ) goto moveto_finish;
  54008. }
  54009. moveto_finish:
  54010. return rc;
  54011. }
  54012. /*
  54013. ** Return TRUE if the cursor is not pointing at an entry of the table.
  54014. **
  54015. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  54016. ** past the last entry in the table or sqlite3BtreePrev() moves past
  54017. ** the first entry. TRUE is also returned if the table is empty.
  54018. */
  54019. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  54020. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  54021. ** have been deleted? This API will need to change to return an error code
  54022. ** as well as the boolean result value.
  54023. */
  54024. return (CURSOR_VALID!=pCur->eState);
  54025. }
  54026. /*
  54027. ** Advance the cursor to the next entry in the database. If
  54028. ** successful then set *pRes=0. If the cursor
  54029. ** was already pointing to the last entry in the database before
  54030. ** this routine was called, then set *pRes=1.
  54031. */
  54032. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  54033. int rc;
  54034. int idx;
  54035. MemPage *pPage;
  54036. assert( cursorHoldsMutex(pCur) );
  54037. assert( pRes!=0 );
  54038. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54039. if( pCur->eState!=CURSOR_VALID ){
  54040. rc = restoreCursorPosition(pCur);
  54041. if( rc!=SQLITE_OK ){
  54042. *pRes = 0;
  54043. return rc;
  54044. }
  54045. if( CURSOR_INVALID==pCur->eState ){
  54046. *pRes = 1;
  54047. return SQLITE_OK;
  54048. }
  54049. if( pCur->skipNext ){
  54050. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54051. pCur->eState = CURSOR_VALID;
  54052. if( pCur->skipNext>0 ){
  54053. pCur->skipNext = 0;
  54054. *pRes = 0;
  54055. return SQLITE_OK;
  54056. }
  54057. pCur->skipNext = 0;
  54058. }
  54059. }
  54060. pPage = pCur->apPage[pCur->iPage];
  54061. idx = ++pCur->aiIdx[pCur->iPage];
  54062. assert( pPage->isInit );
  54063. /* If the database file is corrupt, it is possible for the value of idx
  54064. ** to be invalid here. This can only occur if a second cursor modifies
  54065. ** the page while cursor pCur is holding a reference to it. Which can
  54066. ** only happen if the database is corrupt in such a way as to link the
  54067. ** page into more than one b-tree structure. */
  54068. testcase( idx>pPage->nCell );
  54069. pCur->info.nSize = 0;
  54070. pCur->validNKey = 0;
  54071. if( idx>=pPage->nCell ){
  54072. if( !pPage->leaf ){
  54073. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  54074. if( rc ){
  54075. *pRes = 0;
  54076. return rc;
  54077. }
  54078. rc = moveToLeftmost(pCur);
  54079. *pRes = 0;
  54080. return rc;
  54081. }
  54082. do{
  54083. if( pCur->iPage==0 ){
  54084. *pRes = 1;
  54085. pCur->eState = CURSOR_INVALID;
  54086. return SQLITE_OK;
  54087. }
  54088. moveToParent(pCur);
  54089. pPage = pCur->apPage[pCur->iPage];
  54090. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  54091. *pRes = 0;
  54092. if( pPage->intKey ){
  54093. rc = sqlite3BtreeNext(pCur, pRes);
  54094. }else{
  54095. rc = SQLITE_OK;
  54096. }
  54097. return rc;
  54098. }
  54099. *pRes = 0;
  54100. if( pPage->leaf ){
  54101. return SQLITE_OK;
  54102. }
  54103. rc = moveToLeftmost(pCur);
  54104. return rc;
  54105. }
  54106. /*
  54107. ** Step the cursor to the back to the previous entry in the database. If
  54108. ** successful then set *pRes=0. If the cursor
  54109. ** was already pointing to the first entry in the database before
  54110. ** this routine was called, then set *pRes=1.
  54111. */
  54112. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  54113. int rc;
  54114. MemPage *pPage;
  54115. assert( cursorHoldsMutex(pCur) );
  54116. assert( pRes!=0 );
  54117. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  54118. pCur->atLast = 0;
  54119. if( pCur->eState!=CURSOR_VALID ){
  54120. if( ALWAYS(pCur->eState>=CURSOR_REQUIRESEEK) ){
  54121. rc = btreeRestoreCursorPosition(pCur);
  54122. if( rc!=SQLITE_OK ){
  54123. *pRes = 0;
  54124. return rc;
  54125. }
  54126. }
  54127. if( CURSOR_INVALID==pCur->eState ){
  54128. *pRes = 1;
  54129. return SQLITE_OK;
  54130. }
  54131. if( pCur->skipNext ){
  54132. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  54133. pCur->eState = CURSOR_VALID;
  54134. if( pCur->skipNext<0 ){
  54135. pCur->skipNext = 0;
  54136. *pRes = 0;
  54137. return SQLITE_OK;
  54138. }
  54139. pCur->skipNext = 0;
  54140. }
  54141. }
  54142. pPage = pCur->apPage[pCur->iPage];
  54143. assert( pPage->isInit );
  54144. if( !pPage->leaf ){
  54145. int idx = pCur->aiIdx[pCur->iPage];
  54146. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  54147. if( rc ){
  54148. *pRes = 0;
  54149. return rc;
  54150. }
  54151. rc = moveToRightmost(pCur);
  54152. }else{
  54153. while( pCur->aiIdx[pCur->iPage]==0 ){
  54154. if( pCur->iPage==0 ){
  54155. pCur->eState = CURSOR_INVALID;
  54156. *pRes = 1;
  54157. return SQLITE_OK;
  54158. }
  54159. moveToParent(pCur);
  54160. }
  54161. pCur->info.nSize = 0;
  54162. pCur->validNKey = 0;
  54163. pCur->aiIdx[pCur->iPage]--;
  54164. pPage = pCur->apPage[pCur->iPage];
  54165. if( pPage->intKey && !pPage->leaf ){
  54166. rc = sqlite3BtreePrevious(pCur, pRes);
  54167. }else{
  54168. rc = SQLITE_OK;
  54169. }
  54170. }
  54171. *pRes = 0;
  54172. return rc;
  54173. }
  54174. /*
  54175. ** Allocate a new page from the database file.
  54176. **
  54177. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  54178. ** has already been called on the new page.) The new page has also
  54179. ** been referenced and the calling routine is responsible for calling
  54180. ** sqlite3PagerUnref() on the new page when it is done.
  54181. **
  54182. ** SQLITE_OK is returned on success. Any other return value indicates
  54183. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  54184. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  54185. **
  54186. ** If the "nearby" parameter is not 0, then an effort is made to
  54187. ** locate a page close to the page number "nearby". This can be used in an
  54188. ** attempt to keep related pages close to each other in the database file,
  54189. ** which in turn can make database access faster.
  54190. **
  54191. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  54192. ** anywhere on the free-list, then it is guaranteed to be returned. If
  54193. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  54194. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  54195. ** are no restrictions on which page is returned.
  54196. */
  54197. static int allocateBtreePage(
  54198. BtShared *pBt, /* The btree */
  54199. MemPage **ppPage, /* Store pointer to the allocated page here */
  54200. Pgno *pPgno, /* Store the page number here */
  54201. Pgno nearby, /* Search for a page near this one */
  54202. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  54203. ){
  54204. MemPage *pPage1;
  54205. int rc;
  54206. u32 n; /* Number of pages on the freelist */
  54207. u32 k; /* Number of leaves on the trunk of the freelist */
  54208. MemPage *pTrunk = 0;
  54209. MemPage *pPrevTrunk = 0;
  54210. Pgno mxPage; /* Total size of the database file */
  54211. assert( sqlite3_mutex_held(pBt->mutex) );
  54212. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  54213. pPage1 = pBt->pPage1;
  54214. mxPage = btreePagecount(pBt);
  54215. n = get4byte(&pPage1->aData[36]);
  54216. testcase( n==mxPage-1 );
  54217. if( n>=mxPage ){
  54218. return SQLITE_CORRUPT_BKPT;
  54219. }
  54220. if( n>0 ){
  54221. /* There are pages on the freelist. Reuse one of those pages. */
  54222. Pgno iTrunk;
  54223. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  54224. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  54225. ** shows that the page 'nearby' is somewhere on the free-list, then
  54226. ** the entire-list will be searched for that page.
  54227. */
  54228. #ifndef SQLITE_OMIT_AUTOVACUUM
  54229. if( eMode==BTALLOC_EXACT ){
  54230. if( nearby<=mxPage ){
  54231. u8 eType;
  54232. assert( nearby>0 );
  54233. assert( pBt->autoVacuum );
  54234. rc = ptrmapGet(pBt, nearby, &eType, 0);
  54235. if( rc ) return rc;
  54236. if( eType==PTRMAP_FREEPAGE ){
  54237. searchList = 1;
  54238. }
  54239. }
  54240. }else if( eMode==BTALLOC_LE ){
  54241. searchList = 1;
  54242. }
  54243. #endif
  54244. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  54245. ** first free-list trunk page. iPrevTrunk is initially 1.
  54246. */
  54247. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54248. if( rc ) return rc;
  54249. put4byte(&pPage1->aData[36], n-1);
  54250. /* The code within this loop is run only once if the 'searchList' variable
  54251. ** is not true. Otherwise, it runs once for each trunk-page on the
  54252. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  54253. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  54254. */
  54255. do {
  54256. pPrevTrunk = pTrunk;
  54257. if( pPrevTrunk ){
  54258. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  54259. }else{
  54260. iTrunk = get4byte(&pPage1->aData[32]);
  54261. }
  54262. testcase( iTrunk==mxPage );
  54263. if( iTrunk>mxPage ){
  54264. rc = SQLITE_CORRUPT_BKPT;
  54265. }else{
  54266. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54267. }
  54268. if( rc ){
  54269. pTrunk = 0;
  54270. goto end_allocate_page;
  54271. }
  54272. assert( pTrunk!=0 );
  54273. assert( pTrunk->aData!=0 );
  54274. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  54275. if( k==0 && !searchList ){
  54276. /* The trunk has no leaves and the list is not being searched.
  54277. ** So extract the trunk page itself and use it as the newly
  54278. ** allocated page */
  54279. assert( pPrevTrunk==0 );
  54280. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54281. if( rc ){
  54282. goto end_allocate_page;
  54283. }
  54284. *pPgno = iTrunk;
  54285. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54286. *ppPage = pTrunk;
  54287. pTrunk = 0;
  54288. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54289. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  54290. /* Value of k is out of range. Database corruption */
  54291. rc = SQLITE_CORRUPT_BKPT;
  54292. goto end_allocate_page;
  54293. #ifndef SQLITE_OMIT_AUTOVACUUM
  54294. }else if( searchList
  54295. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  54296. ){
  54297. /* The list is being searched and this trunk page is the page
  54298. ** to allocate, regardless of whether it has leaves.
  54299. */
  54300. *pPgno = iTrunk;
  54301. *ppPage = pTrunk;
  54302. searchList = 0;
  54303. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54304. if( rc ){
  54305. goto end_allocate_page;
  54306. }
  54307. if( k==0 ){
  54308. if( !pPrevTrunk ){
  54309. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  54310. }else{
  54311. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54312. if( rc!=SQLITE_OK ){
  54313. goto end_allocate_page;
  54314. }
  54315. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  54316. }
  54317. }else{
  54318. /* The trunk page is required by the caller but it contains
  54319. ** pointers to free-list leaves. The first leaf becomes a trunk
  54320. ** page in this case.
  54321. */
  54322. MemPage *pNewTrunk;
  54323. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  54324. if( iNewTrunk>mxPage ){
  54325. rc = SQLITE_CORRUPT_BKPT;
  54326. goto end_allocate_page;
  54327. }
  54328. testcase( iNewTrunk==mxPage );
  54329. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  54330. if( rc!=SQLITE_OK ){
  54331. goto end_allocate_page;
  54332. }
  54333. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  54334. if( rc!=SQLITE_OK ){
  54335. releasePage(pNewTrunk);
  54336. goto end_allocate_page;
  54337. }
  54338. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  54339. put4byte(&pNewTrunk->aData[4], k-1);
  54340. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  54341. releasePage(pNewTrunk);
  54342. if( !pPrevTrunk ){
  54343. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  54344. put4byte(&pPage1->aData[32], iNewTrunk);
  54345. }else{
  54346. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  54347. if( rc ){
  54348. goto end_allocate_page;
  54349. }
  54350. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  54351. }
  54352. }
  54353. pTrunk = 0;
  54354. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  54355. #endif
  54356. }else if( k>0 ){
  54357. /* Extract a leaf from the trunk */
  54358. u32 closest;
  54359. Pgno iPage;
  54360. unsigned char *aData = pTrunk->aData;
  54361. if( nearby>0 ){
  54362. u32 i;
  54363. closest = 0;
  54364. if( eMode==BTALLOC_LE ){
  54365. for(i=0; i<k; i++){
  54366. iPage = get4byte(&aData[8+i*4]);
  54367. if( iPage<=nearby ){
  54368. closest = i;
  54369. break;
  54370. }
  54371. }
  54372. }else{
  54373. int dist;
  54374. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  54375. for(i=1; i<k; i++){
  54376. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  54377. if( d2<dist ){
  54378. closest = i;
  54379. dist = d2;
  54380. }
  54381. }
  54382. }
  54383. }else{
  54384. closest = 0;
  54385. }
  54386. iPage = get4byte(&aData[8+closest*4]);
  54387. testcase( iPage==mxPage );
  54388. if( iPage>mxPage ){
  54389. rc = SQLITE_CORRUPT_BKPT;
  54390. goto end_allocate_page;
  54391. }
  54392. testcase( iPage==mxPage );
  54393. if( !searchList
  54394. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  54395. ){
  54396. int noContent;
  54397. *pPgno = iPage;
  54398. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  54399. ": %d more free pages\n",
  54400. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  54401. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54402. if( rc ) goto end_allocate_page;
  54403. if( closest<k-1 ){
  54404. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  54405. }
  54406. put4byte(&aData[4], k-1);
  54407. noContent = !btreeGetHasContent(pBt, *pPgno) ? PAGER_GET_NOCONTENT : 0;
  54408. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  54409. if( rc==SQLITE_OK ){
  54410. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54411. if( rc!=SQLITE_OK ){
  54412. releasePage(*ppPage);
  54413. }
  54414. }
  54415. searchList = 0;
  54416. }
  54417. }
  54418. releasePage(pPrevTrunk);
  54419. pPrevTrunk = 0;
  54420. }while( searchList );
  54421. }else{
  54422. /* There are no pages on the freelist, so append a new page to the
  54423. ** database image.
  54424. **
  54425. ** Normally, new pages allocated by this block can be requested from the
  54426. ** pager layer with the 'no-content' flag set. This prevents the pager
  54427. ** from trying to read the pages content from disk. However, if the
  54428. ** current transaction has already run one or more incremental-vacuum
  54429. ** steps, then the page we are about to allocate may contain content
  54430. ** that is required in the event of a rollback. In this case, do
  54431. ** not set the no-content flag. This causes the pager to load and journal
  54432. ** the current page content before overwriting it.
  54433. **
  54434. ** Note that the pager will not actually attempt to load or journal
  54435. ** content for any page that really does lie past the end of the database
  54436. ** file on disk. So the effects of disabling the no-content optimization
  54437. ** here are confined to those pages that lie between the end of the
  54438. ** database image and the end of the database file.
  54439. */
  54440. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate)) ? PAGER_GET_NOCONTENT : 0;
  54441. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  54442. if( rc ) return rc;
  54443. pBt->nPage++;
  54444. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  54445. #ifndef SQLITE_OMIT_AUTOVACUUM
  54446. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  54447. /* If *pPgno refers to a pointer-map page, allocate two new pages
  54448. ** at the end of the file instead of one. The first allocated page
  54449. ** becomes a new pointer-map page, the second is used by the caller.
  54450. */
  54451. MemPage *pPg = 0;
  54452. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  54453. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  54454. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  54455. if( rc==SQLITE_OK ){
  54456. rc = sqlite3PagerWrite(pPg->pDbPage);
  54457. releasePage(pPg);
  54458. }
  54459. if( rc ) return rc;
  54460. pBt->nPage++;
  54461. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  54462. }
  54463. #endif
  54464. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  54465. *pPgno = pBt->nPage;
  54466. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54467. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  54468. if( rc ) return rc;
  54469. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  54470. if( rc!=SQLITE_OK ){
  54471. releasePage(*ppPage);
  54472. }
  54473. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  54474. }
  54475. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  54476. end_allocate_page:
  54477. releasePage(pTrunk);
  54478. releasePage(pPrevTrunk);
  54479. if( rc==SQLITE_OK ){
  54480. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  54481. releasePage(*ppPage);
  54482. return SQLITE_CORRUPT_BKPT;
  54483. }
  54484. (*ppPage)->isInit = 0;
  54485. }else{
  54486. *ppPage = 0;
  54487. }
  54488. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  54489. return rc;
  54490. }
  54491. /*
  54492. ** This function is used to add page iPage to the database file free-list.
  54493. ** It is assumed that the page is not already a part of the free-list.
  54494. **
  54495. ** The value passed as the second argument to this function is optional.
  54496. ** If the caller happens to have a pointer to the MemPage object
  54497. ** corresponding to page iPage handy, it may pass it as the second value.
  54498. ** Otherwise, it may pass NULL.
  54499. **
  54500. ** If a pointer to a MemPage object is passed as the second argument,
  54501. ** its reference count is not altered by this function.
  54502. */
  54503. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  54504. MemPage *pTrunk = 0; /* Free-list trunk page */
  54505. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  54506. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  54507. MemPage *pPage; /* Page being freed. May be NULL. */
  54508. int rc; /* Return Code */
  54509. int nFree; /* Initial number of pages on free-list */
  54510. assert( sqlite3_mutex_held(pBt->mutex) );
  54511. assert( iPage>1 );
  54512. assert( !pMemPage || pMemPage->pgno==iPage );
  54513. if( pMemPage ){
  54514. pPage = pMemPage;
  54515. sqlite3PagerRef(pPage->pDbPage);
  54516. }else{
  54517. pPage = btreePageLookup(pBt, iPage);
  54518. }
  54519. /* Increment the free page count on pPage1 */
  54520. rc = sqlite3PagerWrite(pPage1->pDbPage);
  54521. if( rc ) goto freepage_out;
  54522. nFree = get4byte(&pPage1->aData[36]);
  54523. put4byte(&pPage1->aData[36], nFree+1);
  54524. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  54525. /* If the secure_delete option is enabled, then
  54526. ** always fully overwrite deleted information with zeros.
  54527. */
  54528. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  54529. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  54530. ){
  54531. goto freepage_out;
  54532. }
  54533. memset(pPage->aData, 0, pPage->pBt->pageSize);
  54534. }
  54535. /* If the database supports auto-vacuum, write an entry in the pointer-map
  54536. ** to indicate that the page is free.
  54537. */
  54538. if( ISAUTOVACUUM ){
  54539. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  54540. if( rc ) goto freepage_out;
  54541. }
  54542. /* Now manipulate the actual database free-list structure. There are two
  54543. ** possibilities. If the free-list is currently empty, or if the first
  54544. ** trunk page in the free-list is full, then this page will become a
  54545. ** new free-list trunk page. Otherwise, it will become a leaf of the
  54546. ** first trunk page in the current free-list. This block tests if it
  54547. ** is possible to add the page as a new free-list leaf.
  54548. */
  54549. if( nFree!=0 ){
  54550. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  54551. iTrunk = get4byte(&pPage1->aData[32]);
  54552. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  54553. if( rc!=SQLITE_OK ){
  54554. goto freepage_out;
  54555. }
  54556. nLeaf = get4byte(&pTrunk->aData[4]);
  54557. assert( pBt->usableSize>32 );
  54558. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  54559. rc = SQLITE_CORRUPT_BKPT;
  54560. goto freepage_out;
  54561. }
  54562. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  54563. /* In this case there is room on the trunk page to insert the page
  54564. ** being freed as a new leaf.
  54565. **
  54566. ** Note that the trunk page is not really full until it contains
  54567. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  54568. ** coded. But due to a coding error in versions of SQLite prior to
  54569. ** 3.6.0, databases with freelist trunk pages holding more than
  54570. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  54571. ** to maintain backwards compatibility with older versions of SQLite,
  54572. ** we will continue to restrict the number of entries to usableSize/4 - 8
  54573. ** for now. At some point in the future (once everyone has upgraded
  54574. ** to 3.6.0 or later) we should consider fixing the conditional above
  54575. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  54576. */
  54577. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  54578. if( rc==SQLITE_OK ){
  54579. put4byte(&pTrunk->aData[4], nLeaf+1);
  54580. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  54581. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  54582. sqlite3PagerDontWrite(pPage->pDbPage);
  54583. }
  54584. rc = btreeSetHasContent(pBt, iPage);
  54585. }
  54586. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  54587. goto freepage_out;
  54588. }
  54589. }
  54590. /* If control flows to this point, then it was not possible to add the
  54591. ** the page being freed as a leaf page of the first trunk in the free-list.
  54592. ** Possibly because the free-list is empty, or possibly because the
  54593. ** first trunk in the free-list is full. Either way, the page being freed
  54594. ** will become the new first trunk page in the free-list.
  54595. */
  54596. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  54597. goto freepage_out;
  54598. }
  54599. rc = sqlite3PagerWrite(pPage->pDbPage);
  54600. if( rc!=SQLITE_OK ){
  54601. goto freepage_out;
  54602. }
  54603. put4byte(pPage->aData, iTrunk);
  54604. put4byte(&pPage->aData[4], 0);
  54605. put4byte(&pPage1->aData[32], iPage);
  54606. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  54607. freepage_out:
  54608. if( pPage ){
  54609. pPage->isInit = 0;
  54610. }
  54611. releasePage(pPage);
  54612. releasePage(pTrunk);
  54613. return rc;
  54614. }
  54615. static void freePage(MemPage *pPage, int *pRC){
  54616. if( (*pRC)==SQLITE_OK ){
  54617. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  54618. }
  54619. }
  54620. /*
  54621. ** Free any overflow pages associated with the given Cell.
  54622. */
  54623. static int clearCell(MemPage *pPage, unsigned char *pCell){
  54624. BtShared *pBt = pPage->pBt;
  54625. CellInfo info;
  54626. Pgno ovflPgno;
  54627. int rc;
  54628. int nOvfl;
  54629. u32 ovflPageSize;
  54630. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54631. btreeParseCellPtr(pPage, pCell, &info);
  54632. if( info.iOverflow==0 ){
  54633. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  54634. }
  54635. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  54636. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  54637. }
  54638. ovflPgno = get4byte(&pCell[info.iOverflow]);
  54639. assert( pBt->usableSize > 4 );
  54640. ovflPageSize = pBt->usableSize - 4;
  54641. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  54642. assert( ovflPgno==0 || nOvfl>0 );
  54643. while( nOvfl-- ){
  54644. Pgno iNext = 0;
  54645. MemPage *pOvfl = 0;
  54646. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  54647. /* 0 is not a legal page number and page 1 cannot be an
  54648. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  54649. ** file the database must be corrupt. */
  54650. return SQLITE_CORRUPT_BKPT;
  54651. }
  54652. if( nOvfl ){
  54653. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  54654. if( rc ) return rc;
  54655. }
  54656. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  54657. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  54658. ){
  54659. /* There is no reason any cursor should have an outstanding reference
  54660. ** to an overflow page belonging to a cell that is being deleted/updated.
  54661. ** So if there exists more than one reference to this page, then it
  54662. ** must not really be an overflow page and the database must be corrupt.
  54663. ** It is helpful to detect this before calling freePage2(), as
  54664. ** freePage2() may zero the page contents if secure-delete mode is
  54665. ** enabled. If this 'overflow' page happens to be a page that the
  54666. ** caller is iterating through or using in some other way, this
  54667. ** can be problematic.
  54668. */
  54669. rc = SQLITE_CORRUPT_BKPT;
  54670. }else{
  54671. rc = freePage2(pBt, pOvfl, ovflPgno);
  54672. }
  54673. if( pOvfl ){
  54674. sqlite3PagerUnref(pOvfl->pDbPage);
  54675. }
  54676. if( rc ) return rc;
  54677. ovflPgno = iNext;
  54678. }
  54679. return SQLITE_OK;
  54680. }
  54681. /*
  54682. ** Create the byte sequence used to represent a cell on page pPage
  54683. ** and write that byte sequence into pCell[]. Overflow pages are
  54684. ** allocated and filled in as necessary. The calling procedure
  54685. ** is responsible for making sure sufficient space has been allocated
  54686. ** for pCell[].
  54687. **
  54688. ** Note that pCell does not necessary need to point to the pPage->aData
  54689. ** area. pCell might point to some temporary storage. The cell will
  54690. ** be constructed in this temporary area then copied into pPage->aData
  54691. ** later.
  54692. */
  54693. static int fillInCell(
  54694. MemPage *pPage, /* The page that contains the cell */
  54695. unsigned char *pCell, /* Complete text of the cell */
  54696. const void *pKey, i64 nKey, /* The key */
  54697. const void *pData,int nData, /* The data */
  54698. int nZero, /* Extra zero bytes to append to pData */
  54699. int *pnSize /* Write cell size here */
  54700. ){
  54701. int nPayload;
  54702. const u8 *pSrc;
  54703. int nSrc, n, rc;
  54704. int spaceLeft;
  54705. MemPage *pOvfl = 0;
  54706. MemPage *pToRelease = 0;
  54707. unsigned char *pPrior;
  54708. unsigned char *pPayload;
  54709. BtShared *pBt = pPage->pBt;
  54710. Pgno pgnoOvfl = 0;
  54711. int nHeader;
  54712. CellInfo info;
  54713. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54714. /* pPage is not necessarily writeable since pCell might be auxiliary
  54715. ** buffer space that is separate from the pPage buffer area */
  54716. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  54717. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54718. /* Fill in the header. */
  54719. nHeader = 0;
  54720. if( !pPage->leaf ){
  54721. nHeader += 4;
  54722. }
  54723. if( pPage->hasData ){
  54724. nHeader += putVarint(&pCell[nHeader], nData+nZero);
  54725. }else{
  54726. nData = nZero = 0;
  54727. }
  54728. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  54729. btreeParseCellPtr(pPage, pCell, &info);
  54730. assert( info.nHeader==nHeader );
  54731. assert( info.nKey==nKey );
  54732. assert( info.nData==(u32)(nData+nZero) );
  54733. /* Fill in the payload */
  54734. nPayload = nData + nZero;
  54735. if( pPage->intKey ){
  54736. pSrc = pData;
  54737. nSrc = nData;
  54738. nData = 0;
  54739. }else{
  54740. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  54741. return SQLITE_CORRUPT_BKPT;
  54742. }
  54743. nPayload += (int)nKey;
  54744. pSrc = pKey;
  54745. nSrc = (int)nKey;
  54746. }
  54747. *pnSize = info.nSize;
  54748. spaceLeft = info.nLocal;
  54749. pPayload = &pCell[nHeader];
  54750. pPrior = &pCell[info.iOverflow];
  54751. while( nPayload>0 ){
  54752. if( spaceLeft==0 ){
  54753. #ifndef SQLITE_OMIT_AUTOVACUUM
  54754. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  54755. if( pBt->autoVacuum ){
  54756. do{
  54757. pgnoOvfl++;
  54758. } while(
  54759. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  54760. );
  54761. }
  54762. #endif
  54763. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  54764. #ifndef SQLITE_OMIT_AUTOVACUUM
  54765. /* If the database supports auto-vacuum, and the second or subsequent
  54766. ** overflow page is being allocated, add an entry to the pointer-map
  54767. ** for that page now.
  54768. **
  54769. ** If this is the first overflow page, then write a partial entry
  54770. ** to the pointer-map. If we write nothing to this pointer-map slot,
  54771. ** then the optimistic overflow chain processing in clearCell()
  54772. ** may misinterpret the uninitialized values and delete the
  54773. ** wrong pages from the database.
  54774. */
  54775. if( pBt->autoVacuum && rc==SQLITE_OK ){
  54776. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  54777. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  54778. if( rc ){
  54779. releasePage(pOvfl);
  54780. }
  54781. }
  54782. #endif
  54783. if( rc ){
  54784. releasePage(pToRelease);
  54785. return rc;
  54786. }
  54787. /* If pToRelease is not zero than pPrior points into the data area
  54788. ** of pToRelease. Make sure pToRelease is still writeable. */
  54789. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54790. /* If pPrior is part of the data area of pPage, then make sure pPage
  54791. ** is still writeable */
  54792. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  54793. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54794. put4byte(pPrior, pgnoOvfl);
  54795. releasePage(pToRelease);
  54796. pToRelease = pOvfl;
  54797. pPrior = pOvfl->aData;
  54798. put4byte(pPrior, 0);
  54799. pPayload = &pOvfl->aData[4];
  54800. spaceLeft = pBt->usableSize - 4;
  54801. }
  54802. n = nPayload;
  54803. if( n>spaceLeft ) n = spaceLeft;
  54804. /* If pToRelease is not zero than pPayload points into the data area
  54805. ** of pToRelease. Make sure pToRelease is still writeable. */
  54806. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54807. /* If pPayload is part of the data area of pPage, then make sure pPage
  54808. ** is still writeable */
  54809. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  54810. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54811. if( nSrc>0 ){
  54812. if( n>nSrc ) n = nSrc;
  54813. assert( pSrc );
  54814. memcpy(pPayload, pSrc, n);
  54815. }else{
  54816. memset(pPayload, 0, n);
  54817. }
  54818. nPayload -= n;
  54819. pPayload += n;
  54820. pSrc += n;
  54821. nSrc -= n;
  54822. spaceLeft -= n;
  54823. if( nSrc==0 ){
  54824. nSrc = nData;
  54825. pSrc = pData;
  54826. }
  54827. }
  54828. releasePage(pToRelease);
  54829. return SQLITE_OK;
  54830. }
  54831. /*
  54832. ** Remove the i-th cell from pPage. This routine effects pPage only.
  54833. ** The cell content is not freed or deallocated. It is assumed that
  54834. ** the cell content has been copied someplace else. This routine just
  54835. ** removes the reference to the cell from pPage.
  54836. **
  54837. ** "sz" must be the number of bytes in the cell.
  54838. */
  54839. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  54840. u32 pc; /* Offset to cell content of cell being deleted */
  54841. u8 *data; /* pPage->aData */
  54842. u8 *ptr; /* Used to move bytes around within data[] */
  54843. u8 *endPtr; /* End of loop */
  54844. int rc; /* The return code */
  54845. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  54846. if( *pRC ) return;
  54847. assert( idx>=0 && idx<pPage->nCell );
  54848. assert( sz==cellSize(pPage, idx) );
  54849. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54850. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54851. data = pPage->aData;
  54852. ptr = &pPage->aCellIdx[2*idx];
  54853. pc = get2byte(ptr);
  54854. hdr = pPage->hdrOffset;
  54855. testcase( pc==get2byte(&data[hdr+5]) );
  54856. testcase( pc+sz==pPage->pBt->usableSize );
  54857. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  54858. *pRC = SQLITE_CORRUPT_BKPT;
  54859. return;
  54860. }
  54861. rc = freeSpace(pPage, pc, sz);
  54862. if( rc ){
  54863. *pRC = rc;
  54864. return;
  54865. }
  54866. endPtr = &pPage->aCellIdx[2*pPage->nCell - 2];
  54867. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  54868. while( ptr<endPtr ){
  54869. *(u16*)ptr = *(u16*)&ptr[2];
  54870. ptr += 2;
  54871. }
  54872. pPage->nCell--;
  54873. put2byte(&data[hdr+3], pPage->nCell);
  54874. pPage->nFree += 2;
  54875. }
  54876. /*
  54877. ** Insert a new cell on pPage at cell index "i". pCell points to the
  54878. ** content of the cell.
  54879. **
  54880. ** If the cell content will fit on the page, then put it there. If it
  54881. ** will not fit, then make a copy of the cell content into pTemp if
  54882. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  54883. ** in pPage->apOvfl[] and make it point to the cell content (either
  54884. ** in pTemp or the original pCell) and also record its index.
  54885. ** Allocating a new entry in pPage->aCell[] implies that
  54886. ** pPage->nOverflow is incremented.
  54887. **
  54888. ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
  54889. ** cell. The caller will overwrite them after this function returns. If
  54890. ** nSkip is non-zero, then pCell may not point to an invalid memory location
  54891. ** (but pCell+nSkip is always valid).
  54892. */
  54893. static void insertCell(
  54894. MemPage *pPage, /* Page into which we are copying */
  54895. int i, /* New cell becomes the i-th cell of the page */
  54896. u8 *pCell, /* Content of the new cell */
  54897. int sz, /* Bytes of content in pCell */
  54898. u8 *pTemp, /* Temp storage space for pCell, if needed */
  54899. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  54900. int *pRC /* Read and write return code from here */
  54901. ){
  54902. int idx = 0; /* Where to write new cell content in data[] */
  54903. int j; /* Loop counter */
  54904. int end; /* First byte past the last cell pointer in data[] */
  54905. int ins; /* Index in data[] where new cell pointer is inserted */
  54906. int cellOffset; /* Address of first cell pointer in data[] */
  54907. u8 *data; /* The content of the whole page */
  54908. u8 *ptr; /* Used for moving information around in data[] */
  54909. u8 *endPtr; /* End of the loop */
  54910. int nSkip = (iChild ? 4 : 0);
  54911. if( *pRC ) return;
  54912. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  54913. assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=10921 );
  54914. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  54915. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  54916. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54917. /* The cell should normally be sized correctly. However, when moving a
  54918. ** malformed cell from a leaf page to an interior page, if the cell size
  54919. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  54920. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  54921. ** the term after the || in the following assert(). */
  54922. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  54923. if( pPage->nOverflow || sz+2>pPage->nFree ){
  54924. if( pTemp ){
  54925. memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
  54926. pCell = pTemp;
  54927. }
  54928. if( iChild ){
  54929. put4byte(pCell, iChild);
  54930. }
  54931. j = pPage->nOverflow++;
  54932. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  54933. pPage->apOvfl[j] = pCell;
  54934. pPage->aiOvfl[j] = (u16)i;
  54935. }else{
  54936. int rc = sqlite3PagerWrite(pPage->pDbPage);
  54937. if( rc!=SQLITE_OK ){
  54938. *pRC = rc;
  54939. return;
  54940. }
  54941. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54942. data = pPage->aData;
  54943. cellOffset = pPage->cellOffset;
  54944. end = cellOffset + 2*pPage->nCell;
  54945. ins = cellOffset + 2*i;
  54946. rc = allocateSpace(pPage, sz, &idx);
  54947. if( rc ){ *pRC = rc; return; }
  54948. /* The allocateSpace() routine guarantees the following two properties
  54949. ** if it returns success */
  54950. assert( idx >= end+2 );
  54951. assert( idx+sz <= (int)pPage->pBt->usableSize );
  54952. pPage->nCell++;
  54953. pPage->nFree -= (u16)(2 + sz);
  54954. memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
  54955. if( iChild ){
  54956. put4byte(&data[idx], iChild);
  54957. }
  54958. ptr = &data[end];
  54959. endPtr = &data[ins];
  54960. assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
  54961. while( ptr>endPtr ){
  54962. *(u16*)ptr = *(u16*)&ptr[-2];
  54963. ptr -= 2;
  54964. }
  54965. put2byte(&data[ins], idx);
  54966. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  54967. #ifndef SQLITE_OMIT_AUTOVACUUM
  54968. if( pPage->pBt->autoVacuum ){
  54969. /* The cell may contain a pointer to an overflow page. If so, write
  54970. ** the entry for the overflow page into the pointer map.
  54971. */
  54972. ptrmapPutOvflPtr(pPage, pCell, pRC);
  54973. }
  54974. #endif
  54975. }
  54976. }
  54977. /*
  54978. ** Add a list of cells to a page. The page should be initially empty.
  54979. ** The cells are guaranteed to fit on the page.
  54980. */
  54981. static void assemblePage(
  54982. MemPage *pPage, /* The page to be assemblied */
  54983. int nCell, /* The number of cells to add to this page */
  54984. u8 **apCell, /* Pointers to cell bodies */
  54985. u16 *aSize /* Sizes of the cells */
  54986. ){
  54987. int i; /* Loop counter */
  54988. u8 *pCellptr; /* Address of next cell pointer */
  54989. int cellbody; /* Address of next cell body */
  54990. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  54991. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  54992. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  54993. assert( pPage->nOverflow==0 );
  54994. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54995. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  54996. && (int)MX_CELL(pPage->pBt)<=10921);
  54997. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54998. /* Check that the page has just been zeroed by zeroPage() */
  54999. assert( pPage->nCell==0 );
  55000. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  55001. pCellptr = &pPage->aCellIdx[nCell*2];
  55002. cellbody = nUsable;
  55003. for(i=nCell-1; i>=0; i--){
  55004. u16 sz = aSize[i];
  55005. pCellptr -= 2;
  55006. cellbody -= sz;
  55007. put2byte(pCellptr, cellbody);
  55008. memcpy(&data[cellbody], apCell[i], sz);
  55009. }
  55010. put2byte(&data[hdr+3], nCell);
  55011. put2byte(&data[hdr+5], cellbody);
  55012. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  55013. pPage->nCell = (u16)nCell;
  55014. }
  55015. /*
  55016. ** The following parameters determine how many adjacent pages get involved
  55017. ** in a balancing operation. NN is the number of neighbors on either side
  55018. ** of the page that participate in the balancing operation. NB is the
  55019. ** total number of pages that participate, including the target page and
  55020. ** NN neighbors on either side.
  55021. **
  55022. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  55023. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  55024. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  55025. ** The value of NN appears to give the best results overall.
  55026. */
  55027. #define NN 1 /* Number of neighbors on either side of pPage */
  55028. #define NB (NN*2+1) /* Total pages involved in the balance */
  55029. #ifndef SQLITE_OMIT_QUICKBALANCE
  55030. /*
  55031. ** This version of balance() handles the common special case where
  55032. ** a new entry is being inserted on the extreme right-end of the
  55033. ** tree, in other words, when the new entry will become the largest
  55034. ** entry in the tree.
  55035. **
  55036. ** Instead of trying to balance the 3 right-most leaf pages, just add
  55037. ** a new page to the right-hand side and put the one new entry in
  55038. ** that page. This leaves the right side of the tree somewhat
  55039. ** unbalanced. But odds are that we will be inserting new entries
  55040. ** at the end soon afterwards so the nearly empty page will quickly
  55041. ** fill up. On average.
  55042. **
  55043. ** pPage is the leaf page which is the right-most page in the tree.
  55044. ** pParent is its parent. pPage must have a single overflow entry
  55045. ** which is also the right-most entry on the page.
  55046. **
  55047. ** The pSpace buffer is used to store a temporary copy of the divider
  55048. ** cell that will be inserted into pParent. Such a cell consists of a 4
  55049. ** byte page number followed by a variable length integer. In other
  55050. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  55051. ** least 13 bytes in size.
  55052. */
  55053. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  55054. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  55055. MemPage *pNew; /* Newly allocated page */
  55056. int rc; /* Return Code */
  55057. Pgno pgnoNew; /* Page number of pNew */
  55058. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  55059. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55060. assert( pPage->nOverflow==1 );
  55061. /* This error condition is now caught prior to reaching this function */
  55062. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  55063. /* Allocate a new page. This page will become the right-sibling of
  55064. ** pPage. Make the parent page writable, so that the new divider cell
  55065. ** may be inserted. If both these operations are successful, proceed.
  55066. */
  55067. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  55068. if( rc==SQLITE_OK ){
  55069. u8 *pOut = &pSpace[4];
  55070. u8 *pCell = pPage->apOvfl[0];
  55071. u16 szCell = cellSizePtr(pPage, pCell);
  55072. u8 *pStop;
  55073. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  55074. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  55075. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  55076. assemblePage(pNew, 1, &pCell, &szCell);
  55077. /* If this is an auto-vacuum database, update the pointer map
  55078. ** with entries for the new page, and any pointer from the
  55079. ** cell on the page to an overflow page. If either of these
  55080. ** operations fails, the return code is set, but the contents
  55081. ** of the parent page are still manipulated by thh code below.
  55082. ** That is Ok, at this point the parent page is guaranteed to
  55083. ** be marked as dirty. Returning an error code will cause a
  55084. ** rollback, undoing any changes made to the parent page.
  55085. */
  55086. if( ISAUTOVACUUM ){
  55087. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  55088. if( szCell>pNew->minLocal ){
  55089. ptrmapPutOvflPtr(pNew, pCell, &rc);
  55090. }
  55091. }
  55092. /* Create a divider cell to insert into pParent. The divider cell
  55093. ** consists of a 4-byte page number (the page number of pPage) and
  55094. ** a variable length key value (which must be the same value as the
  55095. ** largest key on pPage).
  55096. **
  55097. ** To find the largest key value on pPage, first find the right-most
  55098. ** cell on pPage. The first two fields of this cell are the
  55099. ** record-length (a variable length integer at most 32-bits in size)
  55100. ** and the key value (a variable length integer, may have any value).
  55101. ** The first of the while(...) loops below skips over the record-length
  55102. ** field. The second while(...) loop copies the key value from the
  55103. ** cell on pPage into the pSpace buffer.
  55104. */
  55105. pCell = findCell(pPage, pPage->nCell-1);
  55106. pStop = &pCell[9];
  55107. while( (*(pCell++)&0x80) && pCell<pStop );
  55108. pStop = &pCell[9];
  55109. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  55110. /* Insert the new divider cell into pParent. */
  55111. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  55112. 0, pPage->pgno, &rc);
  55113. /* Set the right-child pointer of pParent to point to the new page. */
  55114. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  55115. /* Release the reference to the new page. */
  55116. releasePage(pNew);
  55117. }
  55118. return rc;
  55119. }
  55120. #endif /* SQLITE_OMIT_QUICKBALANCE */
  55121. #if 0
  55122. /*
  55123. ** This function does not contribute anything to the operation of SQLite.
  55124. ** it is sometimes activated temporarily while debugging code responsible
  55125. ** for setting pointer-map entries.
  55126. */
  55127. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  55128. int i, j;
  55129. for(i=0; i<nPage; i++){
  55130. Pgno n;
  55131. u8 e;
  55132. MemPage *pPage = apPage[i];
  55133. BtShared *pBt = pPage->pBt;
  55134. assert( pPage->isInit );
  55135. for(j=0; j<pPage->nCell; j++){
  55136. CellInfo info;
  55137. u8 *z;
  55138. z = findCell(pPage, j);
  55139. btreeParseCellPtr(pPage, z, &info);
  55140. if( info.iOverflow ){
  55141. Pgno ovfl = get4byte(&z[info.iOverflow]);
  55142. ptrmapGet(pBt, ovfl, &e, &n);
  55143. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  55144. }
  55145. if( !pPage->leaf ){
  55146. Pgno child = get4byte(z);
  55147. ptrmapGet(pBt, child, &e, &n);
  55148. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55149. }
  55150. }
  55151. if( !pPage->leaf ){
  55152. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  55153. ptrmapGet(pBt, child, &e, &n);
  55154. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  55155. }
  55156. }
  55157. return 1;
  55158. }
  55159. #endif
  55160. /*
  55161. ** This function is used to copy the contents of the b-tree node stored
  55162. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  55163. ** the pointer-map entries for each child page are updated so that the
  55164. ** parent page stored in the pointer map is page pTo. If pFrom contained
  55165. ** any cells with overflow page pointers, then the corresponding pointer
  55166. ** map entries are also updated so that the parent page is page pTo.
  55167. **
  55168. ** If pFrom is currently carrying any overflow cells (entries in the
  55169. ** MemPage.apOvfl[] array), they are not copied to pTo.
  55170. **
  55171. ** Before returning, page pTo is reinitialized using btreeInitPage().
  55172. **
  55173. ** The performance of this function is not critical. It is only used by
  55174. ** the balance_shallower() and balance_deeper() procedures, neither of
  55175. ** which are called often under normal circumstances.
  55176. */
  55177. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  55178. if( (*pRC)==SQLITE_OK ){
  55179. BtShared * const pBt = pFrom->pBt;
  55180. u8 * const aFrom = pFrom->aData;
  55181. u8 * const aTo = pTo->aData;
  55182. int const iFromHdr = pFrom->hdrOffset;
  55183. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  55184. int rc;
  55185. int iData;
  55186. assert( pFrom->isInit );
  55187. assert( pFrom->nFree>=iToHdr );
  55188. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  55189. /* Copy the b-tree node content from page pFrom to page pTo. */
  55190. iData = get2byte(&aFrom[iFromHdr+5]);
  55191. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  55192. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  55193. /* Reinitialize page pTo so that the contents of the MemPage structure
  55194. ** match the new data. The initialization of pTo can actually fail under
  55195. ** fairly obscure circumstances, even though it is a copy of initialized
  55196. ** page pFrom.
  55197. */
  55198. pTo->isInit = 0;
  55199. rc = btreeInitPage(pTo);
  55200. if( rc!=SQLITE_OK ){
  55201. *pRC = rc;
  55202. return;
  55203. }
  55204. /* If this is an auto-vacuum database, update the pointer-map entries
  55205. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  55206. */
  55207. if( ISAUTOVACUUM ){
  55208. *pRC = setChildPtrmaps(pTo);
  55209. }
  55210. }
  55211. }
  55212. /*
  55213. ** This routine redistributes cells on the iParentIdx'th child of pParent
  55214. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  55215. ** same amount of free space. Usually a single sibling on either side of the
  55216. ** page are used in the balancing, though both siblings might come from one
  55217. ** side if the page is the first or last child of its parent. If the page
  55218. ** has fewer than 2 siblings (something which can only happen if the page
  55219. ** is a root page or a child of a root page) then all available siblings
  55220. ** participate in the balancing.
  55221. **
  55222. ** The number of siblings of the page might be increased or decreased by
  55223. ** one or two in an effort to keep pages nearly full but not over full.
  55224. **
  55225. ** Note that when this routine is called, some of the cells on the page
  55226. ** might not actually be stored in MemPage.aData[]. This can happen
  55227. ** if the page is overfull. This routine ensures that all cells allocated
  55228. ** to the page and its siblings fit into MemPage.aData[] before returning.
  55229. **
  55230. ** In the course of balancing the page and its siblings, cells may be
  55231. ** inserted into or removed from the parent page (pParent). Doing so
  55232. ** may cause the parent page to become overfull or underfull. If this
  55233. ** happens, it is the responsibility of the caller to invoke the correct
  55234. ** balancing routine to fix this problem (see the balance() routine).
  55235. **
  55236. ** If this routine fails for any reason, it might leave the database
  55237. ** in a corrupted state. So if this routine fails, the database should
  55238. ** be rolled back.
  55239. **
  55240. ** The third argument to this function, aOvflSpace, is a pointer to a
  55241. ** buffer big enough to hold one page. If while inserting cells into the parent
  55242. ** page (pParent) the parent page becomes overfull, this buffer is
  55243. ** used to store the parent's overflow cells. Because this function inserts
  55244. ** a maximum of four divider cells into the parent page, and the maximum
  55245. ** size of a cell stored within an internal node is always less than 1/4
  55246. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  55247. ** enough for all overflow cells.
  55248. **
  55249. ** If aOvflSpace is set to a null pointer, this function returns
  55250. ** SQLITE_NOMEM.
  55251. */
  55252. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55253. #pragma optimize("", off)
  55254. #endif
  55255. static int balance_nonroot(
  55256. MemPage *pParent, /* Parent page of siblings being balanced */
  55257. int iParentIdx, /* Index of "the page" in pParent */
  55258. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  55259. int isRoot, /* True if pParent is a root-page */
  55260. int bBulk /* True if this call is part of a bulk load */
  55261. ){
  55262. BtShared *pBt; /* The whole database */
  55263. int nCell = 0; /* Number of cells in apCell[] */
  55264. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  55265. int nNew = 0; /* Number of pages in apNew[] */
  55266. int nOld; /* Number of pages in apOld[] */
  55267. int i, j, k; /* Loop counters */
  55268. int nxDiv; /* Next divider slot in pParent->aCell[] */
  55269. int rc = SQLITE_OK; /* The return code */
  55270. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  55271. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  55272. int usableSpace; /* Bytes in pPage beyond the header */
  55273. int pageFlags; /* Value of pPage->aData[0] */
  55274. int subtotal; /* Subtotal of bytes in cells on one page */
  55275. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  55276. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  55277. int szScratch; /* Size of scratch memory requested */
  55278. MemPage *apOld[NB]; /* pPage and up to two siblings */
  55279. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  55280. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  55281. u8 *pRight; /* Location in parent of right-sibling pointer */
  55282. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  55283. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  55284. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  55285. u8 **apCell = 0; /* All cells begin balanced */
  55286. u16 *szCell; /* Local size of all cells in apCell[] */
  55287. u8 *aSpace1; /* Space for copies of dividers cells */
  55288. Pgno pgno; /* Temp var to store a page number in */
  55289. pBt = pParent->pBt;
  55290. assert( sqlite3_mutex_held(pBt->mutex) );
  55291. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55292. #if 0
  55293. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  55294. #endif
  55295. /* At this point pParent may have at most one overflow cell. And if
  55296. ** this overflow cell is present, it must be the cell with
  55297. ** index iParentIdx. This scenario comes about when this function
  55298. ** is called (indirectly) from sqlite3BtreeDelete().
  55299. */
  55300. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  55301. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  55302. if( !aOvflSpace ){
  55303. return SQLITE_NOMEM;
  55304. }
  55305. /* Find the sibling pages to balance. Also locate the cells in pParent
  55306. ** that divide the siblings. An attempt is made to find NN siblings on
  55307. ** either side of pPage. More siblings are taken from one side, however,
  55308. ** if there are fewer than NN siblings on the other side. If pParent
  55309. ** has NB or fewer children then all children of pParent are taken.
  55310. **
  55311. ** This loop also drops the divider cells from the parent page. This
  55312. ** way, the remainder of the function does not have to deal with any
  55313. ** overflow cells in the parent page, since if any existed they will
  55314. ** have already been removed.
  55315. */
  55316. i = pParent->nOverflow + pParent->nCell;
  55317. if( i<2 ){
  55318. nxDiv = 0;
  55319. }else{
  55320. assert( bBulk==0 || bBulk==1 );
  55321. if( iParentIdx==0 ){
  55322. nxDiv = 0;
  55323. }else if( iParentIdx==i ){
  55324. nxDiv = i-2+bBulk;
  55325. }else{
  55326. assert( bBulk==0 );
  55327. nxDiv = iParentIdx-1;
  55328. }
  55329. i = 2-bBulk;
  55330. }
  55331. nOld = i+1;
  55332. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  55333. pRight = &pParent->aData[pParent->hdrOffset+8];
  55334. }else{
  55335. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55336. }
  55337. pgno = get4byte(pRight);
  55338. while( 1 ){
  55339. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  55340. if( rc ){
  55341. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55342. goto balance_cleanup;
  55343. }
  55344. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  55345. if( (i--)==0 ) break;
  55346. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  55347. apDiv[i] = pParent->apOvfl[0];
  55348. pgno = get4byte(apDiv[i]);
  55349. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55350. pParent->nOverflow = 0;
  55351. }else{
  55352. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  55353. pgno = get4byte(apDiv[i]);
  55354. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  55355. /* Drop the cell from the parent page. apDiv[i] still points to
  55356. ** the cell within the parent, even though it has been dropped.
  55357. ** This is safe because dropping a cell only overwrites the first
  55358. ** four bytes of it, and this function does not need the first
  55359. ** four bytes of the divider cell. So the pointer is safe to use
  55360. ** later on.
  55361. **
  55362. ** But not if we are in secure-delete mode. In secure-delete mode,
  55363. ** the dropCell() routine will overwrite the entire cell with zeroes.
  55364. ** In this case, temporarily copy the cell into the aOvflSpace[]
  55365. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  55366. ** is allocated. */
  55367. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  55368. int iOff;
  55369. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  55370. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  55371. rc = SQLITE_CORRUPT_BKPT;
  55372. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  55373. goto balance_cleanup;
  55374. }else{
  55375. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  55376. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  55377. }
  55378. }
  55379. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  55380. }
  55381. }
  55382. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  55383. ** alignment */
  55384. nMaxCells = (nMaxCells + 3)&~3;
  55385. /*
  55386. ** Allocate space for memory structures
  55387. */
  55388. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  55389. szScratch =
  55390. nMaxCells*sizeof(u8*) /* apCell */
  55391. + nMaxCells*sizeof(u16) /* szCell */
  55392. + pBt->pageSize /* aSpace1 */
  55393. + k*nOld; /* Page copies (apCopy) */
  55394. apCell = sqlite3ScratchMalloc( szScratch );
  55395. if( apCell==0 ){
  55396. rc = SQLITE_NOMEM;
  55397. goto balance_cleanup;
  55398. }
  55399. szCell = (u16*)&apCell[nMaxCells];
  55400. aSpace1 = (u8*)&szCell[nMaxCells];
  55401. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  55402. /*
  55403. ** Load pointers to all cells on sibling pages and the divider cells
  55404. ** into the local apCell[] array. Make copies of the divider cells
  55405. ** into space obtained from aSpace1[] and remove the divider cells
  55406. ** from pParent.
  55407. **
  55408. ** If the siblings are on leaf pages, then the child pointers of the
  55409. ** divider cells are stripped from the cells before they are copied
  55410. ** into aSpace1[]. In this way, all cells in apCell[] are without
  55411. ** child pointers. If siblings are not leaves, then all cell in
  55412. ** apCell[] include child pointers. Either way, all cells in apCell[]
  55413. ** are alike.
  55414. **
  55415. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  55416. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  55417. */
  55418. leafCorrection = apOld[0]->leaf*4;
  55419. leafData = apOld[0]->hasData;
  55420. for(i=0; i<nOld; i++){
  55421. int limit;
  55422. /* Before doing anything else, take a copy of the i'th original sibling
  55423. ** The rest of this function will use data from the copies rather
  55424. ** that the original pages since the original pages will be in the
  55425. ** process of being overwritten. */
  55426. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  55427. memcpy(pOld, apOld[i], sizeof(MemPage));
  55428. pOld->aData = (void*)&pOld[1];
  55429. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  55430. limit = pOld->nCell+pOld->nOverflow;
  55431. if( pOld->nOverflow>0 ){
  55432. for(j=0; j<limit; j++){
  55433. assert( nCell<nMaxCells );
  55434. apCell[nCell] = findOverflowCell(pOld, j);
  55435. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55436. nCell++;
  55437. }
  55438. }else{
  55439. u8 *aData = pOld->aData;
  55440. u16 maskPage = pOld->maskPage;
  55441. u16 cellOffset = pOld->cellOffset;
  55442. for(j=0; j<limit; j++){
  55443. assert( nCell<nMaxCells );
  55444. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  55445. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  55446. nCell++;
  55447. }
  55448. }
  55449. if( i<nOld-1 && !leafData){
  55450. u16 sz = (u16)szNew[i];
  55451. u8 *pTemp;
  55452. assert( nCell<nMaxCells );
  55453. szCell[nCell] = sz;
  55454. pTemp = &aSpace1[iSpace1];
  55455. iSpace1 += sz;
  55456. assert( sz<=pBt->maxLocal+23 );
  55457. assert( iSpace1 <= (int)pBt->pageSize );
  55458. memcpy(pTemp, apDiv[i], sz);
  55459. apCell[nCell] = pTemp+leafCorrection;
  55460. assert( leafCorrection==0 || leafCorrection==4 );
  55461. szCell[nCell] = szCell[nCell] - leafCorrection;
  55462. if( !pOld->leaf ){
  55463. assert( leafCorrection==0 );
  55464. assert( pOld->hdrOffset==0 );
  55465. /* The right pointer of the child page pOld becomes the left
  55466. ** pointer of the divider cell */
  55467. memcpy(apCell[nCell], &pOld->aData[8], 4);
  55468. }else{
  55469. assert( leafCorrection==4 );
  55470. if( szCell[nCell]<4 ){
  55471. /* Do not allow any cells smaller than 4 bytes. */
  55472. szCell[nCell] = 4;
  55473. }
  55474. }
  55475. nCell++;
  55476. }
  55477. }
  55478. /*
  55479. ** Figure out the number of pages needed to hold all nCell cells.
  55480. ** Store this number in "k". Also compute szNew[] which is the total
  55481. ** size of all cells on the i-th page and cntNew[] which is the index
  55482. ** in apCell[] of the cell that divides page i from page i+1.
  55483. ** cntNew[k] should equal nCell.
  55484. **
  55485. ** Values computed by this block:
  55486. **
  55487. ** k: The total number of sibling pages
  55488. ** szNew[i]: Spaced used on the i-th sibling page.
  55489. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  55490. ** the right of the i-th sibling page.
  55491. ** usableSpace: Number of bytes of space available on each sibling.
  55492. **
  55493. */
  55494. usableSpace = pBt->usableSize - 12 + leafCorrection;
  55495. for(subtotal=k=i=0; i<nCell; i++){
  55496. assert( i<nMaxCells );
  55497. subtotal += szCell[i] + 2;
  55498. if( subtotal > usableSpace ){
  55499. szNew[k] = subtotal - szCell[i];
  55500. cntNew[k] = i;
  55501. if( leafData ){ i--; }
  55502. subtotal = 0;
  55503. k++;
  55504. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  55505. }
  55506. }
  55507. szNew[k] = subtotal;
  55508. cntNew[k] = nCell;
  55509. k++;
  55510. /*
  55511. ** The packing computed by the previous block is biased toward the siblings
  55512. ** on the left side. The left siblings are always nearly full, while the
  55513. ** right-most sibling might be nearly empty. This block of code attempts
  55514. ** to adjust the packing of siblings to get a better balance.
  55515. **
  55516. ** This adjustment is more than an optimization. The packing above might
  55517. ** be so out of balance as to be illegal. For example, the right-most
  55518. ** sibling might be completely empty. This adjustment is not optional.
  55519. */
  55520. for(i=k-1; i>0; i--){
  55521. int szRight = szNew[i]; /* Size of sibling on the right */
  55522. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  55523. int r; /* Index of right-most cell in left sibling */
  55524. int d; /* Index of first cell to the left of right sibling */
  55525. r = cntNew[i-1] - 1;
  55526. d = r + 1 - leafData;
  55527. assert( d<nMaxCells );
  55528. assert( r<nMaxCells );
  55529. while( szRight==0
  55530. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  55531. ){
  55532. szRight += szCell[d] + 2;
  55533. szLeft -= szCell[r] + 2;
  55534. cntNew[i-1]--;
  55535. r = cntNew[i-1] - 1;
  55536. d = r + 1 - leafData;
  55537. }
  55538. szNew[i] = szRight;
  55539. szNew[i-1] = szLeft;
  55540. }
  55541. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  55542. ** a virtual root page. A virtual root page is when the real root
  55543. ** page is page 1 and we are the only child of that page.
  55544. **
  55545. ** UPDATE: The assert() below is not necessarily true if the database
  55546. ** file is corrupt. The corruption will be detected and reported later
  55547. ** in this procedure so there is no need to act upon it now.
  55548. */
  55549. #if 0
  55550. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  55551. #endif
  55552. TRACE(("BALANCE: old: %d %d %d ",
  55553. apOld[0]->pgno,
  55554. nOld>=2 ? apOld[1]->pgno : 0,
  55555. nOld>=3 ? apOld[2]->pgno : 0
  55556. ));
  55557. /*
  55558. ** Allocate k new pages. Reuse old pages where possible.
  55559. */
  55560. if( apOld[0]->pgno<=1 ){
  55561. rc = SQLITE_CORRUPT_BKPT;
  55562. goto balance_cleanup;
  55563. }
  55564. pageFlags = apOld[0]->aData[0];
  55565. for(i=0; i<k; i++){
  55566. MemPage *pNew;
  55567. if( i<nOld ){
  55568. pNew = apNew[i] = apOld[i];
  55569. apOld[i] = 0;
  55570. rc = sqlite3PagerWrite(pNew->pDbPage);
  55571. nNew++;
  55572. if( rc ) goto balance_cleanup;
  55573. }else{
  55574. assert( i>0 );
  55575. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  55576. if( rc ) goto balance_cleanup;
  55577. apNew[i] = pNew;
  55578. nNew++;
  55579. /* Set the pointer-map entry for the new sibling page. */
  55580. if( ISAUTOVACUUM ){
  55581. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  55582. if( rc!=SQLITE_OK ){
  55583. goto balance_cleanup;
  55584. }
  55585. }
  55586. }
  55587. }
  55588. /* Free any old pages that were not reused as new pages.
  55589. */
  55590. while( i<nOld ){
  55591. freePage(apOld[i], &rc);
  55592. if( rc ) goto balance_cleanup;
  55593. releasePage(apOld[i]);
  55594. apOld[i] = 0;
  55595. i++;
  55596. }
  55597. /*
  55598. ** Put the new pages in accending order. This helps to
  55599. ** keep entries in the disk file in order so that a scan
  55600. ** of the table is a linear scan through the file. That
  55601. ** in turn helps the operating system to deliver pages
  55602. ** from the disk more rapidly.
  55603. **
  55604. ** An O(n^2) insertion sort algorithm is used, but since
  55605. ** n is never more than NB (a small constant), that should
  55606. ** not be a problem.
  55607. **
  55608. ** When NB==3, this one optimization makes the database
  55609. ** about 25% faster for large insertions and deletions.
  55610. */
  55611. for(i=0; i<k-1; i++){
  55612. int minV = apNew[i]->pgno;
  55613. int minI = i;
  55614. for(j=i+1; j<k; j++){
  55615. if( apNew[j]->pgno<(unsigned)minV ){
  55616. minI = j;
  55617. minV = apNew[j]->pgno;
  55618. }
  55619. }
  55620. if( minI>i ){
  55621. MemPage *pT;
  55622. pT = apNew[i];
  55623. apNew[i] = apNew[minI];
  55624. apNew[minI] = pT;
  55625. }
  55626. }
  55627. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  55628. apNew[0]->pgno, szNew[0],
  55629. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  55630. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  55631. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  55632. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  55633. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55634. put4byte(pRight, apNew[nNew-1]->pgno);
  55635. /*
  55636. ** Evenly distribute the data in apCell[] across the new pages.
  55637. ** Insert divider cells into pParent as necessary.
  55638. */
  55639. j = 0;
  55640. for(i=0; i<nNew; i++){
  55641. /* Assemble the new sibling page. */
  55642. MemPage *pNew = apNew[i];
  55643. assert( j<nMaxCells );
  55644. zeroPage(pNew, pageFlags);
  55645. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  55646. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  55647. assert( pNew->nOverflow==0 );
  55648. j = cntNew[i];
  55649. /* If the sibling page assembled above was not the right-most sibling,
  55650. ** insert a divider cell into the parent page.
  55651. */
  55652. assert( i<nNew-1 || j==nCell );
  55653. if( j<nCell ){
  55654. u8 *pCell;
  55655. u8 *pTemp;
  55656. int sz;
  55657. assert( j<nMaxCells );
  55658. pCell = apCell[j];
  55659. sz = szCell[j] + leafCorrection;
  55660. pTemp = &aOvflSpace[iOvflSpace];
  55661. if( !pNew->leaf ){
  55662. memcpy(&pNew->aData[8], pCell, 4);
  55663. }else if( leafData ){
  55664. /* If the tree is a leaf-data tree, and the siblings are leaves,
  55665. ** then there is no divider cell in apCell[]. Instead, the divider
  55666. ** cell consists of the integer key for the right-most cell of
  55667. ** the sibling-page assembled above only.
  55668. */
  55669. CellInfo info;
  55670. j--;
  55671. btreeParseCellPtr(pNew, apCell[j], &info);
  55672. pCell = pTemp;
  55673. sz = 4 + putVarint(&pCell[4], info.nKey);
  55674. pTemp = 0;
  55675. }else{
  55676. pCell -= 4;
  55677. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  55678. ** previously stored on a leaf node, and its reported size was 4
  55679. ** bytes, then it may actually be smaller than this
  55680. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  55681. ** any cell). But it is important to pass the correct size to
  55682. ** insertCell(), so reparse the cell now.
  55683. **
  55684. ** Note that this can never happen in an SQLite data file, as all
  55685. ** cells are at least 4 bytes. It only happens in b-trees used
  55686. ** to evaluate "IN (SELECT ...)" and similar clauses.
  55687. */
  55688. if( szCell[j]==4 ){
  55689. assert(leafCorrection==4);
  55690. sz = cellSizePtr(pParent, pCell);
  55691. }
  55692. }
  55693. iOvflSpace += sz;
  55694. assert( sz<=pBt->maxLocal+23 );
  55695. assert( iOvflSpace <= (int)pBt->pageSize );
  55696. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  55697. if( rc!=SQLITE_OK ) goto balance_cleanup;
  55698. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  55699. j++;
  55700. nxDiv++;
  55701. }
  55702. }
  55703. assert( j==nCell );
  55704. assert( nOld>0 );
  55705. assert( nNew>0 );
  55706. if( (pageFlags & PTF_LEAF)==0 ){
  55707. u8 *zChild = &apCopy[nOld-1]->aData[8];
  55708. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  55709. }
  55710. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  55711. /* The root page of the b-tree now contains no cells. The only sibling
  55712. ** page is the right-child of the parent. Copy the contents of the
  55713. ** child page into the parent, decreasing the overall height of the
  55714. ** b-tree structure by one. This is described as the "balance-shallower"
  55715. ** sub-algorithm in some documentation.
  55716. **
  55717. ** If this is an auto-vacuum database, the call to copyNodeContent()
  55718. ** sets all pointer-map entries corresponding to database image pages
  55719. ** for which the pointer is stored within the content being copied.
  55720. **
  55721. ** The second assert below verifies that the child page is defragmented
  55722. ** (it must be, as it was just reconstructed using assemblePage()). This
  55723. ** is important if the parent page happens to be page 1 of the database
  55724. ** image. */
  55725. assert( nNew==1 );
  55726. assert( apNew[0]->nFree ==
  55727. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  55728. );
  55729. copyNodeContent(apNew[0], pParent, &rc);
  55730. freePage(apNew[0], &rc);
  55731. }else if( ISAUTOVACUUM ){
  55732. /* Fix the pointer-map entries for all the cells that were shifted around.
  55733. ** There are several different types of pointer-map entries that need to
  55734. ** be dealt with by this routine. Some of these have been set already, but
  55735. ** many have not. The following is a summary:
  55736. **
  55737. ** 1) The entries associated with new sibling pages that were not
  55738. ** siblings when this function was called. These have already
  55739. ** been set. We don't need to worry about old siblings that were
  55740. ** moved to the free-list - the freePage() code has taken care
  55741. ** of those.
  55742. **
  55743. ** 2) The pointer-map entries associated with the first overflow
  55744. ** page in any overflow chains used by new divider cells. These
  55745. ** have also already been taken care of by the insertCell() code.
  55746. **
  55747. ** 3) If the sibling pages are not leaves, then the child pages of
  55748. ** cells stored on the sibling pages may need to be updated.
  55749. **
  55750. ** 4) If the sibling pages are not internal intkey nodes, then any
  55751. ** overflow pages used by these cells may need to be updated
  55752. ** (internal intkey nodes never contain pointers to overflow pages).
  55753. **
  55754. ** 5) If the sibling pages are not leaves, then the pointer-map
  55755. ** entries for the right-child pages of each sibling may need
  55756. ** to be updated.
  55757. **
  55758. ** Cases 1 and 2 are dealt with above by other code. The next
  55759. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  55760. ** setting a pointer map entry is a relatively expensive operation, this
  55761. ** code only sets pointer map entries for child or overflow pages that have
  55762. ** actually moved between pages. */
  55763. MemPage *pNew = apNew[0];
  55764. MemPage *pOld = apCopy[0];
  55765. int nOverflow = pOld->nOverflow;
  55766. int iNextOld = pOld->nCell + nOverflow;
  55767. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  55768. j = 0; /* Current 'old' sibling page */
  55769. k = 0; /* Current 'new' sibling page */
  55770. for(i=0; i<nCell; i++){
  55771. int isDivider = 0;
  55772. while( i==iNextOld ){
  55773. /* Cell i is the cell immediately following the last cell on old
  55774. ** sibling page j. If the siblings are not leaf pages of an
  55775. ** intkey b-tree, then cell i was a divider cell. */
  55776. assert( j+1 < ArraySize(apCopy) );
  55777. assert( j+1 < nOld );
  55778. pOld = apCopy[++j];
  55779. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  55780. if( pOld->nOverflow ){
  55781. nOverflow = pOld->nOverflow;
  55782. iOverflow = i + !leafData + pOld->aiOvfl[0];
  55783. }
  55784. isDivider = !leafData;
  55785. }
  55786. assert(nOverflow>0 || iOverflow<i );
  55787. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  55788. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  55789. if( i==iOverflow ){
  55790. isDivider = 1;
  55791. if( (--nOverflow)>0 ){
  55792. iOverflow++;
  55793. }
  55794. }
  55795. if( i==cntNew[k] ){
  55796. /* Cell i is the cell immediately following the last cell on new
  55797. ** sibling page k. If the siblings are not leaf pages of an
  55798. ** intkey b-tree, then cell i is a divider cell. */
  55799. pNew = apNew[++k];
  55800. if( !leafData ) continue;
  55801. }
  55802. assert( j<nOld );
  55803. assert( k<nNew );
  55804. /* If the cell was originally divider cell (and is not now) or
  55805. ** an overflow cell, or if the cell was located on a different sibling
  55806. ** page before the balancing, then the pointer map entries associated
  55807. ** with any child or overflow pages need to be updated. */
  55808. if( isDivider || pOld->pgno!=pNew->pgno ){
  55809. if( !leafCorrection ){
  55810. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  55811. }
  55812. if( szCell[i]>pNew->minLocal ){
  55813. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  55814. }
  55815. }
  55816. }
  55817. if( !leafCorrection ){
  55818. for(i=0; i<nNew; i++){
  55819. u32 key = get4byte(&apNew[i]->aData[8]);
  55820. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  55821. }
  55822. }
  55823. #if 0
  55824. /* The ptrmapCheckPages() contains assert() statements that verify that
  55825. ** all pointer map pages are set correctly. This is helpful while
  55826. ** debugging. This is usually disabled because a corrupt database may
  55827. ** cause an assert() statement to fail. */
  55828. ptrmapCheckPages(apNew, nNew);
  55829. ptrmapCheckPages(&pParent, 1);
  55830. #endif
  55831. }
  55832. assert( pParent->isInit );
  55833. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  55834. nOld, nNew, nCell));
  55835. /*
  55836. ** Cleanup before returning.
  55837. */
  55838. balance_cleanup:
  55839. sqlite3ScratchFree(apCell);
  55840. for(i=0; i<nOld; i++){
  55841. releasePage(apOld[i]);
  55842. }
  55843. for(i=0; i<nNew; i++){
  55844. releasePage(apNew[i]);
  55845. }
  55846. return rc;
  55847. }
  55848. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55849. #pragma optimize("", on)
  55850. #endif
  55851. /*
  55852. ** This function is called when the root page of a b-tree structure is
  55853. ** overfull (has one or more overflow pages).
  55854. **
  55855. ** A new child page is allocated and the contents of the current root
  55856. ** page, including overflow cells, are copied into the child. The root
  55857. ** page is then overwritten to make it an empty page with the right-child
  55858. ** pointer pointing to the new page.
  55859. **
  55860. ** Before returning, all pointer-map entries corresponding to pages
  55861. ** that the new child-page now contains pointers to are updated. The
  55862. ** entry corresponding to the new right-child pointer of the root
  55863. ** page is also updated.
  55864. **
  55865. ** If successful, *ppChild is set to contain a reference to the child
  55866. ** page and SQLITE_OK is returned. In this case the caller is required
  55867. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  55868. ** an error code is returned and *ppChild is set to 0.
  55869. */
  55870. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  55871. int rc; /* Return value from subprocedures */
  55872. MemPage *pChild = 0; /* Pointer to a new child page */
  55873. Pgno pgnoChild = 0; /* Page number of the new child page */
  55874. BtShared *pBt = pRoot->pBt; /* The BTree */
  55875. assert( pRoot->nOverflow>0 );
  55876. assert( sqlite3_mutex_held(pBt->mutex) );
  55877. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  55878. ** page that will become the new right-child of pPage. Copy the contents
  55879. ** of the node stored on pRoot into the new child page.
  55880. */
  55881. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55882. if( rc==SQLITE_OK ){
  55883. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  55884. copyNodeContent(pRoot, pChild, &rc);
  55885. if( ISAUTOVACUUM ){
  55886. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  55887. }
  55888. }
  55889. if( rc ){
  55890. *ppChild = 0;
  55891. releasePage(pChild);
  55892. return rc;
  55893. }
  55894. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  55895. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55896. assert( pChild->nCell==pRoot->nCell );
  55897. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  55898. /* Copy the overflow cells from pRoot to pChild */
  55899. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  55900. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  55901. memcpy(pChild->apOvfl, pRoot->apOvfl,
  55902. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  55903. pChild->nOverflow = pRoot->nOverflow;
  55904. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  55905. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  55906. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  55907. *ppChild = pChild;
  55908. return SQLITE_OK;
  55909. }
  55910. /*
  55911. ** The page that pCur currently points to has just been modified in
  55912. ** some way. This function figures out if this modification means the
  55913. ** tree needs to be balanced, and if so calls the appropriate balancing
  55914. ** routine. Balancing routines are:
  55915. **
  55916. ** balance_quick()
  55917. ** balance_deeper()
  55918. ** balance_nonroot()
  55919. */
  55920. static int balance(BtCursor *pCur){
  55921. int rc = SQLITE_OK;
  55922. const int nMin = pCur->pBt->usableSize * 2 / 3;
  55923. u8 aBalanceQuickSpace[13];
  55924. u8 *pFree = 0;
  55925. TESTONLY( int balance_quick_called = 0 );
  55926. TESTONLY( int balance_deeper_called = 0 );
  55927. do {
  55928. int iPage = pCur->iPage;
  55929. MemPage *pPage = pCur->apPage[iPage];
  55930. if( iPage==0 ){
  55931. if( pPage->nOverflow ){
  55932. /* The root page of the b-tree is overfull. In this case call the
  55933. ** balance_deeper() function to create a new child for the root-page
  55934. ** and copy the current contents of the root-page to it. The
  55935. ** next iteration of the do-loop will balance the child page.
  55936. */
  55937. assert( (balance_deeper_called++)==0 );
  55938. rc = balance_deeper(pPage, &pCur->apPage[1]);
  55939. if( rc==SQLITE_OK ){
  55940. pCur->iPage = 1;
  55941. pCur->aiIdx[0] = 0;
  55942. pCur->aiIdx[1] = 0;
  55943. assert( pCur->apPage[1]->nOverflow );
  55944. }
  55945. }else{
  55946. break;
  55947. }
  55948. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  55949. break;
  55950. }else{
  55951. MemPage * const pParent = pCur->apPage[iPage-1];
  55952. int const iIdx = pCur->aiIdx[iPage-1];
  55953. rc = sqlite3PagerWrite(pParent->pDbPage);
  55954. if( rc==SQLITE_OK ){
  55955. #ifndef SQLITE_OMIT_QUICKBALANCE
  55956. if( pPage->hasData
  55957. && pPage->nOverflow==1
  55958. && pPage->aiOvfl[0]==pPage->nCell
  55959. && pParent->pgno!=1
  55960. && pParent->nCell==iIdx
  55961. ){
  55962. /* Call balance_quick() to create a new sibling of pPage on which
  55963. ** to store the overflow cell. balance_quick() inserts a new cell
  55964. ** into pParent, which may cause pParent overflow. If this
  55965. ** happens, the next interation of the do-loop will balance pParent
  55966. ** use either balance_nonroot() or balance_deeper(). Until this
  55967. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  55968. ** buffer.
  55969. **
  55970. ** The purpose of the following assert() is to check that only a
  55971. ** single call to balance_quick() is made for each call to this
  55972. ** function. If this were not verified, a subtle bug involving reuse
  55973. ** of the aBalanceQuickSpace[] might sneak in.
  55974. */
  55975. assert( (balance_quick_called++)==0 );
  55976. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  55977. }else
  55978. #endif
  55979. {
  55980. /* In this case, call balance_nonroot() to redistribute cells
  55981. ** between pPage and up to 2 of its sibling pages. This involves
  55982. ** modifying the contents of pParent, which may cause pParent to
  55983. ** become overfull or underfull. The next iteration of the do-loop
  55984. ** will balance the parent page to correct this.
  55985. **
  55986. ** If the parent page becomes overfull, the overflow cell or cells
  55987. ** are stored in the pSpace buffer allocated immediately below.
  55988. ** A subsequent iteration of the do-loop will deal with this by
  55989. ** calling balance_nonroot() (balance_deeper() may be called first,
  55990. ** but it doesn't deal with overflow cells - just moves them to a
  55991. ** different page). Once this subsequent call to balance_nonroot()
  55992. ** has completed, it is safe to release the pSpace buffer used by
  55993. ** the previous call, as the overflow cell data will have been
  55994. ** copied either into the body of a database page or into the new
  55995. ** pSpace buffer passed to the latter call to balance_nonroot().
  55996. */
  55997. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  55998. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  55999. if( pFree ){
  56000. /* If pFree is not NULL, it points to the pSpace buffer used
  56001. ** by a previous call to balance_nonroot(). Its contents are
  56002. ** now stored either on real database pages or within the
  56003. ** new pSpace buffer, so it may be safely freed here. */
  56004. sqlite3PageFree(pFree);
  56005. }
  56006. /* The pSpace buffer will be freed after the next call to
  56007. ** balance_nonroot(), or just before this function returns, whichever
  56008. ** comes first. */
  56009. pFree = pSpace;
  56010. }
  56011. }
  56012. pPage->nOverflow = 0;
  56013. /* The next iteration of the do-loop balances the parent page. */
  56014. releasePage(pPage);
  56015. pCur->iPage--;
  56016. }
  56017. }while( rc==SQLITE_OK );
  56018. if( pFree ){
  56019. sqlite3PageFree(pFree);
  56020. }
  56021. return rc;
  56022. }
  56023. /*
  56024. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  56025. ** and the data is given by (pData,nData). The cursor is used only to
  56026. ** define what table the record should be inserted into. The cursor
  56027. ** is left pointing at a random location.
  56028. **
  56029. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  56030. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  56031. **
  56032. ** If the seekResult parameter is non-zero, then a successful call to
  56033. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  56034. ** been performed. seekResult is the search result returned (a negative
  56035. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  56036. ** a positive value if pCur points at an etry that is larger than
  56037. ** (pKey, nKey)).
  56038. **
  56039. ** If the seekResult parameter is non-zero, then the caller guarantees that
  56040. ** cursor pCur is pointing at the existing copy of a row that is to be
  56041. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  56042. ** point to any entry or to no entry at all and so this function has to seek
  56043. ** the cursor before the new key can be inserted.
  56044. */
  56045. SQLITE_PRIVATE int sqlite3BtreeInsert(
  56046. BtCursor *pCur, /* Insert data into the table of this cursor */
  56047. const void *pKey, i64 nKey, /* The key of the new record */
  56048. const void *pData, int nData, /* The data of the new record */
  56049. int nZero, /* Number of extra 0 bytes to append to data */
  56050. int appendBias, /* True if this is likely an append */
  56051. int seekResult /* Result of prior MovetoUnpacked() call */
  56052. ){
  56053. int rc;
  56054. int loc = seekResult; /* -1: before desired location +1: after */
  56055. int szNew = 0;
  56056. int idx;
  56057. MemPage *pPage;
  56058. Btree *p = pCur->pBtree;
  56059. BtShared *pBt = p->pBt;
  56060. unsigned char *oldCell;
  56061. unsigned char *newCell = 0;
  56062. if( pCur->eState==CURSOR_FAULT ){
  56063. assert( pCur->skipNext!=SQLITE_OK );
  56064. return pCur->skipNext;
  56065. }
  56066. assert( cursorHoldsMutex(pCur) );
  56067. assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE
  56068. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56069. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56070. /* Assert that the caller has been consistent. If this cursor was opened
  56071. ** expecting an index b-tree, then the caller should be inserting blob
  56072. ** keys with no associated data. If the cursor was opened expecting an
  56073. ** intkey table, the caller should be inserting integer keys with a
  56074. ** blob of associated data. */
  56075. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  56076. /* Save the positions of any other cursors open on this table.
  56077. **
  56078. ** In some cases, the call to btreeMoveto() below is a no-op. For
  56079. ** example, when inserting data into a table with auto-generated integer
  56080. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  56081. ** integer key to use. It then calls this function to actually insert the
  56082. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  56083. ** that the cursor is already where it needs to be and returns without
  56084. ** doing any work. To avoid thwarting these optimizations, it is important
  56085. ** not to clear the cursor here.
  56086. */
  56087. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56088. if( rc ) return rc;
  56089. /* If this is an insert into a table b-tree, invalidate any incrblob
  56090. ** cursors open on the row being replaced (assuming this is a replace
  56091. ** operation - if it is not, the following is a no-op). */
  56092. if( pCur->pKeyInfo==0 ){
  56093. invalidateIncrblobCursors(p, nKey, 0);
  56094. }
  56095. if( !loc ){
  56096. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  56097. if( rc ) return rc;
  56098. }
  56099. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  56100. pPage = pCur->apPage[pCur->iPage];
  56101. assert( pPage->intKey || nKey>=0 );
  56102. assert( pPage->leaf || !pPage->intKey );
  56103. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  56104. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  56105. loc==0 ? "overwrite" : "new entry"));
  56106. assert( pPage->isInit );
  56107. allocateTempSpace(pBt);
  56108. newCell = pBt->pTmpSpace;
  56109. if( newCell==0 ) return SQLITE_NOMEM;
  56110. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  56111. if( rc ) goto end_insert;
  56112. assert( szNew==cellSizePtr(pPage, newCell) );
  56113. assert( szNew <= MX_CELL_SIZE(pBt) );
  56114. idx = pCur->aiIdx[pCur->iPage];
  56115. if( loc==0 ){
  56116. u16 szOld;
  56117. assert( idx<pPage->nCell );
  56118. rc = sqlite3PagerWrite(pPage->pDbPage);
  56119. if( rc ){
  56120. goto end_insert;
  56121. }
  56122. oldCell = findCell(pPage, idx);
  56123. if( !pPage->leaf ){
  56124. memcpy(newCell, oldCell, 4);
  56125. }
  56126. szOld = cellSizePtr(pPage, oldCell);
  56127. rc = clearCell(pPage, oldCell);
  56128. dropCell(pPage, idx, szOld, &rc);
  56129. if( rc ) goto end_insert;
  56130. }else if( loc<0 && pPage->nCell>0 ){
  56131. assert( pPage->leaf );
  56132. idx = ++pCur->aiIdx[pCur->iPage];
  56133. }else{
  56134. assert( pPage->leaf );
  56135. }
  56136. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  56137. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  56138. /* If no error has occurred and pPage has an overflow cell, call balance()
  56139. ** to redistribute the cells within the tree. Since balance() may move
  56140. ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
  56141. ** variables.
  56142. **
  56143. ** Previous versions of SQLite called moveToRoot() to move the cursor
  56144. ** back to the root page as balance() used to invalidate the contents
  56145. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  56146. ** set the cursor state to "invalid". This makes common insert operations
  56147. ** slightly faster.
  56148. **
  56149. ** There is a subtle but important optimization here too. When inserting
  56150. ** multiple records into an intkey b-tree using a single cursor (as can
  56151. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  56152. ** is advantageous to leave the cursor pointing to the last entry in
  56153. ** the b-tree if possible. If the cursor is left pointing to the last
  56154. ** entry in the table, and the next row inserted has an integer key
  56155. ** larger than the largest existing key, it is possible to insert the
  56156. ** row without seeking the cursor. This can be a big performance boost.
  56157. */
  56158. pCur->info.nSize = 0;
  56159. pCur->validNKey = 0;
  56160. if( rc==SQLITE_OK && pPage->nOverflow ){
  56161. rc = balance(pCur);
  56162. /* Must make sure nOverflow is reset to zero even if the balance()
  56163. ** fails. Internal data structure corruption will result otherwise.
  56164. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  56165. ** from trying to save the current position of the cursor. */
  56166. pCur->apPage[pCur->iPage]->nOverflow = 0;
  56167. pCur->eState = CURSOR_INVALID;
  56168. }
  56169. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  56170. end_insert:
  56171. return rc;
  56172. }
  56173. /*
  56174. ** Delete the entry that the cursor is pointing to. The cursor
  56175. ** is left pointing at a arbitrary location.
  56176. */
  56177. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  56178. Btree *p = pCur->pBtree;
  56179. BtShared *pBt = p->pBt;
  56180. int rc; /* Return code */
  56181. MemPage *pPage; /* Page to delete cell from */
  56182. unsigned char *pCell; /* Pointer to cell to delete */
  56183. int iCellIdx; /* Index of cell to delete */
  56184. int iCellDepth; /* Depth of node containing pCell */
  56185. assert( cursorHoldsMutex(pCur) );
  56186. assert( pBt->inTransaction==TRANS_WRITE );
  56187. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56188. assert( pCur->wrFlag );
  56189. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  56190. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  56191. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  56192. || NEVER(pCur->eState!=CURSOR_VALID)
  56193. ){
  56194. return SQLITE_ERROR; /* Something has gone awry. */
  56195. }
  56196. iCellDepth = pCur->iPage;
  56197. iCellIdx = pCur->aiIdx[iCellDepth];
  56198. pPage = pCur->apPage[iCellDepth];
  56199. pCell = findCell(pPage, iCellIdx);
  56200. /* If the page containing the entry to delete is not a leaf page, move
  56201. ** the cursor to the largest entry in the tree that is smaller than
  56202. ** the entry being deleted. This cell will replace the cell being deleted
  56203. ** from the internal node. The 'previous' entry is used for this instead
  56204. ** of the 'next' entry, as the previous entry is always a part of the
  56205. ** sub-tree headed by the child page of the cell being deleted. This makes
  56206. ** balancing the tree following the delete operation easier. */
  56207. if( !pPage->leaf ){
  56208. int notUsed;
  56209. rc = sqlite3BtreePrevious(pCur, &notUsed);
  56210. if( rc ) return rc;
  56211. }
  56212. /* Save the positions of any other cursors open on this table before
  56213. ** making any modifications. Make the page containing the entry to be
  56214. ** deleted writable. Then free any overflow pages associated with the
  56215. ** entry and finally remove the cell itself from within the page.
  56216. */
  56217. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  56218. if( rc ) return rc;
  56219. /* If this is a delete operation to remove a row from a table b-tree,
  56220. ** invalidate any incrblob cursors open on the row being deleted. */
  56221. if( pCur->pKeyInfo==0 ){
  56222. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  56223. }
  56224. rc = sqlite3PagerWrite(pPage->pDbPage);
  56225. if( rc ) return rc;
  56226. rc = clearCell(pPage, pCell);
  56227. dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
  56228. if( rc ) return rc;
  56229. /* If the cell deleted was not located on a leaf page, then the cursor
  56230. ** is currently pointing to the largest entry in the sub-tree headed
  56231. ** by the child-page of the cell that was just deleted from an internal
  56232. ** node. The cell from the leaf node needs to be moved to the internal
  56233. ** node to replace the deleted cell. */
  56234. if( !pPage->leaf ){
  56235. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  56236. int nCell;
  56237. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  56238. unsigned char *pTmp;
  56239. pCell = findCell(pLeaf, pLeaf->nCell-1);
  56240. nCell = cellSizePtr(pLeaf, pCell);
  56241. assert( MX_CELL_SIZE(pBt) >= nCell );
  56242. allocateTempSpace(pBt);
  56243. pTmp = pBt->pTmpSpace;
  56244. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  56245. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  56246. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  56247. if( rc ) return rc;
  56248. }
  56249. /* Balance the tree. If the entry deleted was located on a leaf page,
  56250. ** then the cursor still points to that page. In this case the first
  56251. ** call to balance() repairs the tree, and the if(...) condition is
  56252. ** never true.
  56253. **
  56254. ** Otherwise, if the entry deleted was on an internal node page, then
  56255. ** pCur is pointing to the leaf page from which a cell was removed to
  56256. ** replace the cell deleted from the internal node. This is slightly
  56257. ** tricky as the leaf node may be underfull, and the internal node may
  56258. ** be either under or overfull. In this case run the balancing algorithm
  56259. ** on the leaf node first. If the balance proceeds far enough up the
  56260. ** tree that we can be sure that any problem in the internal node has
  56261. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  56262. ** walk the cursor up the tree to the internal node and balance it as
  56263. ** well. */
  56264. rc = balance(pCur);
  56265. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  56266. while( pCur->iPage>iCellDepth ){
  56267. releasePage(pCur->apPage[pCur->iPage--]);
  56268. }
  56269. rc = balance(pCur);
  56270. }
  56271. if( rc==SQLITE_OK ){
  56272. moveToRoot(pCur);
  56273. }
  56274. return rc;
  56275. }
  56276. /*
  56277. ** Create a new BTree table. Write into *piTable the page
  56278. ** number for the root page of the new table.
  56279. **
  56280. ** The type of type is determined by the flags parameter. Only the
  56281. ** following values of flags are currently in use. Other values for
  56282. ** flags might not work:
  56283. **
  56284. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  56285. ** BTREE_ZERODATA Used for SQL indices
  56286. */
  56287. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  56288. BtShared *pBt = p->pBt;
  56289. MemPage *pRoot;
  56290. Pgno pgnoRoot;
  56291. int rc;
  56292. int ptfFlags; /* Page-type flage for the root page of new table */
  56293. assert( sqlite3BtreeHoldsMutex(p) );
  56294. assert( pBt->inTransaction==TRANS_WRITE );
  56295. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  56296. #ifdef SQLITE_OMIT_AUTOVACUUM
  56297. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56298. if( rc ){
  56299. return rc;
  56300. }
  56301. #else
  56302. if( pBt->autoVacuum ){
  56303. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  56304. MemPage *pPageMove; /* The page to move to. */
  56305. /* Creating a new table may probably require moving an existing database
  56306. ** to make room for the new tables root page. In case this page turns
  56307. ** out to be an overflow page, delete all overflow page-map caches
  56308. ** held by open cursors.
  56309. */
  56310. invalidateAllOverflowCache(pBt);
  56311. /* Read the value of meta[3] from the database to determine where the
  56312. ** root page of the new table should go. meta[3] is the largest root-page
  56313. ** created so far, so the new root-page is (meta[3]+1).
  56314. */
  56315. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  56316. pgnoRoot++;
  56317. /* The new root-page may not be allocated on a pointer-map page, or the
  56318. ** PENDING_BYTE page.
  56319. */
  56320. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  56321. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  56322. pgnoRoot++;
  56323. }
  56324. assert( pgnoRoot>=3 );
  56325. /* Allocate a page. The page that currently resides at pgnoRoot will
  56326. ** be moved to the allocated page (unless the allocated page happens
  56327. ** to reside at pgnoRoot).
  56328. */
  56329. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  56330. if( rc!=SQLITE_OK ){
  56331. return rc;
  56332. }
  56333. if( pgnoMove!=pgnoRoot ){
  56334. /* pgnoRoot is the page that will be used for the root-page of
  56335. ** the new table (assuming an error did not occur). But we were
  56336. ** allocated pgnoMove. If required (i.e. if it was not allocated
  56337. ** by extending the file), the current page at position pgnoMove
  56338. ** is already journaled.
  56339. */
  56340. u8 eType = 0;
  56341. Pgno iPtrPage = 0;
  56342. /* Save the positions of any open cursors. This is required in
  56343. ** case they are holding a reference to an xFetch reference
  56344. ** corresponding to page pgnoRoot. */
  56345. rc = saveAllCursors(pBt, 0, 0);
  56346. releasePage(pPageMove);
  56347. if( rc!=SQLITE_OK ){
  56348. return rc;
  56349. }
  56350. /* Move the page currently at pgnoRoot to pgnoMove. */
  56351. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56352. if( rc!=SQLITE_OK ){
  56353. return rc;
  56354. }
  56355. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  56356. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  56357. rc = SQLITE_CORRUPT_BKPT;
  56358. }
  56359. if( rc!=SQLITE_OK ){
  56360. releasePage(pRoot);
  56361. return rc;
  56362. }
  56363. assert( eType!=PTRMAP_ROOTPAGE );
  56364. assert( eType!=PTRMAP_FREEPAGE );
  56365. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  56366. releasePage(pRoot);
  56367. /* Obtain the page at pgnoRoot */
  56368. if( rc!=SQLITE_OK ){
  56369. return rc;
  56370. }
  56371. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  56372. if( rc!=SQLITE_OK ){
  56373. return rc;
  56374. }
  56375. rc = sqlite3PagerWrite(pRoot->pDbPage);
  56376. if( rc!=SQLITE_OK ){
  56377. releasePage(pRoot);
  56378. return rc;
  56379. }
  56380. }else{
  56381. pRoot = pPageMove;
  56382. }
  56383. /* Update the pointer-map and meta-data with the new root-page number. */
  56384. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  56385. if( rc ){
  56386. releasePage(pRoot);
  56387. return rc;
  56388. }
  56389. /* When the new root page was allocated, page 1 was made writable in
  56390. ** order either to increase the database filesize, or to decrement the
  56391. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  56392. */
  56393. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  56394. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  56395. if( NEVER(rc) ){
  56396. releasePage(pRoot);
  56397. return rc;
  56398. }
  56399. }else{
  56400. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  56401. if( rc ) return rc;
  56402. }
  56403. #endif
  56404. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  56405. if( createTabFlags & BTREE_INTKEY ){
  56406. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  56407. }else{
  56408. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  56409. }
  56410. zeroPage(pRoot, ptfFlags);
  56411. sqlite3PagerUnref(pRoot->pDbPage);
  56412. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  56413. *piTable = (int)pgnoRoot;
  56414. return SQLITE_OK;
  56415. }
  56416. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  56417. int rc;
  56418. sqlite3BtreeEnter(p);
  56419. rc = btreeCreateTable(p, piTable, flags);
  56420. sqlite3BtreeLeave(p);
  56421. return rc;
  56422. }
  56423. /*
  56424. ** Erase the given database page and all its children. Return
  56425. ** the page to the freelist.
  56426. */
  56427. static int clearDatabasePage(
  56428. BtShared *pBt, /* The BTree that contains the table */
  56429. Pgno pgno, /* Page number to clear */
  56430. int freePageFlag, /* Deallocate page if true */
  56431. int *pnChange /* Add number of Cells freed to this counter */
  56432. ){
  56433. MemPage *pPage;
  56434. int rc;
  56435. unsigned char *pCell;
  56436. int i;
  56437. assert( sqlite3_mutex_held(pBt->mutex) );
  56438. if( pgno>btreePagecount(pBt) ){
  56439. return SQLITE_CORRUPT_BKPT;
  56440. }
  56441. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  56442. if( rc ) return rc;
  56443. for(i=0; i<pPage->nCell; i++){
  56444. pCell = findCell(pPage, i);
  56445. if( !pPage->leaf ){
  56446. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  56447. if( rc ) goto cleardatabasepage_out;
  56448. }
  56449. rc = clearCell(pPage, pCell);
  56450. if( rc ) goto cleardatabasepage_out;
  56451. }
  56452. if( !pPage->leaf ){
  56453. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
  56454. if( rc ) goto cleardatabasepage_out;
  56455. }else if( pnChange ){
  56456. assert( pPage->intKey );
  56457. *pnChange += pPage->nCell;
  56458. }
  56459. if( freePageFlag ){
  56460. freePage(pPage, &rc);
  56461. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  56462. zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
  56463. }
  56464. cleardatabasepage_out:
  56465. releasePage(pPage);
  56466. return rc;
  56467. }
  56468. /*
  56469. ** Delete all information from a single table in the database. iTable is
  56470. ** the page number of the root of the table. After this routine returns,
  56471. ** the root page is empty, but still exists.
  56472. **
  56473. ** This routine will fail with SQLITE_LOCKED if there are any open
  56474. ** read cursors on the table. Open write cursors are moved to the
  56475. ** root of the table.
  56476. **
  56477. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  56478. ** integer value pointed to by pnChange is incremented by the number of
  56479. ** entries in the table.
  56480. */
  56481. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  56482. int rc;
  56483. BtShared *pBt = p->pBt;
  56484. sqlite3BtreeEnter(p);
  56485. assert( p->inTrans==TRANS_WRITE );
  56486. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  56487. if( SQLITE_OK==rc ){
  56488. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  56489. ** is the root of a table b-tree - if it is not, the following call is
  56490. ** a no-op). */
  56491. invalidateIncrblobCursors(p, 0, 1);
  56492. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  56493. }
  56494. sqlite3BtreeLeave(p);
  56495. return rc;
  56496. }
  56497. /*
  56498. ** Erase all information in a table and add the root of the table to
  56499. ** the freelist. Except, the root of the principle table (the one on
  56500. ** page 1) is never added to the freelist.
  56501. **
  56502. ** This routine will fail with SQLITE_LOCKED if there are any open
  56503. ** cursors on the table.
  56504. **
  56505. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  56506. ** root page in the database file, then the last root page
  56507. ** in the database file is moved into the slot formerly occupied by
  56508. ** iTable and that last slot formerly occupied by the last root page
  56509. ** is added to the freelist instead of iTable. In this say, all
  56510. ** root pages are kept at the beginning of the database file, which
  56511. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  56512. ** page number that used to be the last root page in the file before
  56513. ** the move. If no page gets moved, *piMoved is set to 0.
  56514. ** The last root page is recorded in meta[3] and the value of
  56515. ** meta[3] is updated by this procedure.
  56516. */
  56517. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  56518. int rc;
  56519. MemPage *pPage = 0;
  56520. BtShared *pBt = p->pBt;
  56521. assert( sqlite3BtreeHoldsMutex(p) );
  56522. assert( p->inTrans==TRANS_WRITE );
  56523. /* It is illegal to drop a table if any cursors are open on the
  56524. ** database. This is because in auto-vacuum mode the backend may
  56525. ** need to move another root-page to fill a gap left by the deleted
  56526. ** root page. If an open cursor was using this page a problem would
  56527. ** occur.
  56528. **
  56529. ** This error is caught long before control reaches this point.
  56530. */
  56531. if( NEVER(pBt->pCursor) ){
  56532. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  56533. return SQLITE_LOCKED_SHAREDCACHE;
  56534. }
  56535. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  56536. if( rc ) return rc;
  56537. rc = sqlite3BtreeClearTable(p, iTable, 0);
  56538. if( rc ){
  56539. releasePage(pPage);
  56540. return rc;
  56541. }
  56542. *piMoved = 0;
  56543. if( iTable>1 ){
  56544. #ifdef SQLITE_OMIT_AUTOVACUUM
  56545. freePage(pPage, &rc);
  56546. releasePage(pPage);
  56547. #else
  56548. if( pBt->autoVacuum ){
  56549. Pgno maxRootPgno;
  56550. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  56551. if( iTable==maxRootPgno ){
  56552. /* If the table being dropped is the table with the largest root-page
  56553. ** number in the database, put the root page on the free list.
  56554. */
  56555. freePage(pPage, &rc);
  56556. releasePage(pPage);
  56557. if( rc!=SQLITE_OK ){
  56558. return rc;
  56559. }
  56560. }else{
  56561. /* The table being dropped does not have the largest root-page
  56562. ** number in the database. So move the page that does into the
  56563. ** gap left by the deleted root-page.
  56564. */
  56565. MemPage *pMove;
  56566. releasePage(pPage);
  56567. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56568. if( rc!=SQLITE_OK ){
  56569. return rc;
  56570. }
  56571. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  56572. releasePage(pMove);
  56573. if( rc!=SQLITE_OK ){
  56574. return rc;
  56575. }
  56576. pMove = 0;
  56577. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  56578. freePage(pMove, &rc);
  56579. releasePage(pMove);
  56580. if( rc!=SQLITE_OK ){
  56581. return rc;
  56582. }
  56583. *piMoved = maxRootPgno;
  56584. }
  56585. /* Set the new 'max-root-page' value in the database header. This
  56586. ** is the old value less one, less one more if that happens to
  56587. ** be a root-page number, less one again if that is the
  56588. ** PENDING_BYTE_PAGE.
  56589. */
  56590. maxRootPgno--;
  56591. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  56592. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  56593. maxRootPgno--;
  56594. }
  56595. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  56596. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  56597. }else{
  56598. freePage(pPage, &rc);
  56599. releasePage(pPage);
  56600. }
  56601. #endif
  56602. }else{
  56603. /* If sqlite3BtreeDropTable was called on page 1.
  56604. ** This really never should happen except in a corrupt
  56605. ** database.
  56606. */
  56607. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  56608. releasePage(pPage);
  56609. }
  56610. return rc;
  56611. }
  56612. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  56613. int rc;
  56614. sqlite3BtreeEnter(p);
  56615. rc = btreeDropTable(p, iTable, piMoved);
  56616. sqlite3BtreeLeave(p);
  56617. return rc;
  56618. }
  56619. /*
  56620. ** This function may only be called if the b-tree connection already
  56621. ** has a read or write transaction open on the database.
  56622. **
  56623. ** Read the meta-information out of a database file. Meta[0]
  56624. ** is the number of free pages currently in the database. Meta[1]
  56625. ** through meta[15] are available for use by higher layers. Meta[0]
  56626. ** is read-only, the others are read/write.
  56627. **
  56628. ** The schema layer numbers meta values differently. At the schema
  56629. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  56630. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  56631. */
  56632. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  56633. BtShared *pBt = p->pBt;
  56634. sqlite3BtreeEnter(p);
  56635. assert( p->inTrans>TRANS_NONE );
  56636. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  56637. assert( pBt->pPage1 );
  56638. assert( idx>=0 && idx<=15 );
  56639. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  56640. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  56641. ** database, mark the database as read-only. */
  56642. #ifdef SQLITE_OMIT_AUTOVACUUM
  56643. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  56644. pBt->btsFlags |= BTS_READ_ONLY;
  56645. }
  56646. #endif
  56647. sqlite3BtreeLeave(p);
  56648. }
  56649. /*
  56650. ** Write meta-information back into the database. Meta[0] is
  56651. ** read-only and may not be written.
  56652. */
  56653. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  56654. BtShared *pBt = p->pBt;
  56655. unsigned char *pP1;
  56656. int rc;
  56657. assert( idx>=1 && idx<=15 );
  56658. sqlite3BtreeEnter(p);
  56659. assert( p->inTrans==TRANS_WRITE );
  56660. assert( pBt->pPage1!=0 );
  56661. pP1 = pBt->pPage1->aData;
  56662. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56663. if( rc==SQLITE_OK ){
  56664. put4byte(&pP1[36 + idx*4], iMeta);
  56665. #ifndef SQLITE_OMIT_AUTOVACUUM
  56666. if( idx==BTREE_INCR_VACUUM ){
  56667. assert( pBt->autoVacuum || iMeta==0 );
  56668. assert( iMeta==0 || iMeta==1 );
  56669. pBt->incrVacuum = (u8)iMeta;
  56670. }
  56671. #endif
  56672. }
  56673. sqlite3BtreeLeave(p);
  56674. return rc;
  56675. }
  56676. #ifndef SQLITE_OMIT_BTREECOUNT
  56677. /*
  56678. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  56679. ** number of entries in the b-tree and write the result to *pnEntry.
  56680. **
  56681. ** SQLITE_OK is returned if the operation is successfully executed.
  56682. ** Otherwise, if an error is encountered (i.e. an IO error or database
  56683. ** corruption) an SQLite error code is returned.
  56684. */
  56685. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  56686. i64 nEntry = 0; /* Value to return in *pnEntry */
  56687. int rc; /* Return code */
  56688. if( pCur->pgnoRoot==0 ){
  56689. *pnEntry = 0;
  56690. return SQLITE_OK;
  56691. }
  56692. rc = moveToRoot(pCur);
  56693. /* Unless an error occurs, the following loop runs one iteration for each
  56694. ** page in the B-Tree structure (not including overflow pages).
  56695. */
  56696. while( rc==SQLITE_OK ){
  56697. int iIdx; /* Index of child node in parent */
  56698. MemPage *pPage; /* Current page of the b-tree */
  56699. /* If this is a leaf page or the tree is not an int-key tree, then
  56700. ** this page contains countable entries. Increment the entry counter
  56701. ** accordingly.
  56702. */
  56703. pPage = pCur->apPage[pCur->iPage];
  56704. if( pPage->leaf || !pPage->intKey ){
  56705. nEntry += pPage->nCell;
  56706. }
  56707. /* pPage is a leaf node. This loop navigates the cursor so that it
  56708. ** points to the first interior cell that it points to the parent of
  56709. ** the next page in the tree that has not yet been visited. The
  56710. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  56711. ** of the page, or to the number of cells in the page if the next page
  56712. ** to visit is the right-child of its parent.
  56713. **
  56714. ** If all pages in the tree have been visited, return SQLITE_OK to the
  56715. ** caller.
  56716. */
  56717. if( pPage->leaf ){
  56718. do {
  56719. if( pCur->iPage==0 ){
  56720. /* All pages of the b-tree have been visited. Return successfully. */
  56721. *pnEntry = nEntry;
  56722. return SQLITE_OK;
  56723. }
  56724. moveToParent(pCur);
  56725. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  56726. pCur->aiIdx[pCur->iPage]++;
  56727. pPage = pCur->apPage[pCur->iPage];
  56728. }
  56729. /* Descend to the child node of the cell that the cursor currently
  56730. ** points at. This is the right-child if (iIdx==pPage->nCell).
  56731. */
  56732. iIdx = pCur->aiIdx[pCur->iPage];
  56733. if( iIdx==pPage->nCell ){
  56734. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  56735. }else{
  56736. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  56737. }
  56738. }
  56739. /* An error has occurred. Return an error code. */
  56740. return rc;
  56741. }
  56742. #endif
  56743. /*
  56744. ** Return the pager associated with a BTree. This routine is used for
  56745. ** testing and debugging only.
  56746. */
  56747. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  56748. return p->pBt->pPager;
  56749. }
  56750. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56751. /*
  56752. ** Append a message to the error message string.
  56753. */
  56754. static void checkAppendMsg(
  56755. IntegrityCk *pCheck,
  56756. char *zMsg1,
  56757. const char *zFormat,
  56758. ...
  56759. ){
  56760. va_list ap;
  56761. if( !pCheck->mxErr ) return;
  56762. pCheck->mxErr--;
  56763. pCheck->nErr++;
  56764. va_start(ap, zFormat);
  56765. if( pCheck->errMsg.nChar ){
  56766. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  56767. }
  56768. if( zMsg1 ){
  56769. sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
  56770. }
  56771. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  56772. va_end(ap);
  56773. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  56774. pCheck->mallocFailed = 1;
  56775. }
  56776. }
  56777. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56778. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56779. /*
  56780. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  56781. ** corresponds to page iPg is already set.
  56782. */
  56783. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56784. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56785. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  56786. }
  56787. /*
  56788. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  56789. */
  56790. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56791. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56792. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  56793. }
  56794. /*
  56795. ** Add 1 to the reference count for page iPage. If this is the second
  56796. ** reference to the page, add an error message to pCheck->zErrMsg.
  56797. ** Return 1 if there are 2 ore more references to the page and 0 if
  56798. ** if this is the first reference to the page.
  56799. **
  56800. ** Also check that the page number is in bounds.
  56801. */
  56802. static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
  56803. if( iPage==0 ) return 1;
  56804. if( iPage>pCheck->nPage ){
  56805. checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
  56806. return 1;
  56807. }
  56808. if( getPageReferenced(pCheck, iPage) ){
  56809. checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
  56810. return 1;
  56811. }
  56812. setPageReferenced(pCheck, iPage);
  56813. return 0;
  56814. }
  56815. #ifndef SQLITE_OMIT_AUTOVACUUM
  56816. /*
  56817. ** Check that the entry in the pointer-map for page iChild maps to
  56818. ** page iParent, pointer type ptrType. If not, append an error message
  56819. ** to pCheck.
  56820. */
  56821. static void checkPtrmap(
  56822. IntegrityCk *pCheck, /* Integrity check context */
  56823. Pgno iChild, /* Child page number */
  56824. u8 eType, /* Expected pointer map type */
  56825. Pgno iParent, /* Expected pointer map parent page number */
  56826. char *zContext /* Context description (used for error msg) */
  56827. ){
  56828. int rc;
  56829. u8 ePtrmapType;
  56830. Pgno iPtrmapParent;
  56831. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  56832. if( rc!=SQLITE_OK ){
  56833. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  56834. checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
  56835. return;
  56836. }
  56837. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  56838. checkAppendMsg(pCheck, zContext,
  56839. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  56840. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  56841. }
  56842. }
  56843. #endif
  56844. /*
  56845. ** Check the integrity of the freelist or of an overflow page list.
  56846. ** Verify that the number of pages on the list is N.
  56847. */
  56848. static void checkList(
  56849. IntegrityCk *pCheck, /* Integrity checking context */
  56850. int isFreeList, /* True for a freelist. False for overflow page list */
  56851. int iPage, /* Page number for first page in the list */
  56852. int N, /* Expected number of pages in the list */
  56853. char *zContext /* Context for error messages */
  56854. ){
  56855. int i;
  56856. int expected = N;
  56857. int iFirst = iPage;
  56858. while( N-- > 0 && pCheck->mxErr ){
  56859. DbPage *pOvflPage;
  56860. unsigned char *pOvflData;
  56861. if( iPage<1 ){
  56862. checkAppendMsg(pCheck, zContext,
  56863. "%d of %d pages missing from overflow list starting at %d",
  56864. N+1, expected, iFirst);
  56865. break;
  56866. }
  56867. if( checkRef(pCheck, iPage, zContext) ) break;
  56868. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  56869. checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
  56870. break;
  56871. }
  56872. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  56873. if( isFreeList ){
  56874. int n = get4byte(&pOvflData[4]);
  56875. #ifndef SQLITE_OMIT_AUTOVACUUM
  56876. if( pCheck->pBt->autoVacuum ){
  56877. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
  56878. }
  56879. #endif
  56880. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  56881. checkAppendMsg(pCheck, zContext,
  56882. "freelist leaf count too big on page %d", iPage);
  56883. N--;
  56884. }else{
  56885. for(i=0; i<n; i++){
  56886. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  56887. #ifndef SQLITE_OMIT_AUTOVACUUM
  56888. if( pCheck->pBt->autoVacuum ){
  56889. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
  56890. }
  56891. #endif
  56892. checkRef(pCheck, iFreePage, zContext);
  56893. }
  56894. N -= n;
  56895. }
  56896. }
  56897. #ifndef SQLITE_OMIT_AUTOVACUUM
  56898. else{
  56899. /* If this database supports auto-vacuum and iPage is not the last
  56900. ** page in this overflow list, check that the pointer-map entry for
  56901. ** the following page matches iPage.
  56902. */
  56903. if( pCheck->pBt->autoVacuum && N>0 ){
  56904. i = get4byte(pOvflData);
  56905. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
  56906. }
  56907. }
  56908. #endif
  56909. iPage = get4byte(pOvflData);
  56910. sqlite3PagerUnref(pOvflPage);
  56911. }
  56912. }
  56913. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56914. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56915. /*
  56916. ** Do various sanity checks on a single page of a tree. Return
  56917. ** the tree depth. Root pages return 0. Parents of root pages
  56918. ** return 1, and so forth.
  56919. **
  56920. ** These checks are done:
  56921. **
  56922. ** 1. Make sure that cells and freeblocks do not overlap
  56923. ** but combine to completely cover the page.
  56924. ** NO 2. Make sure cell keys are in order.
  56925. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  56926. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  56927. ** 5. Check the integrity of overflow pages.
  56928. ** 6. Recursively call checkTreePage on all children.
  56929. ** 7. Verify that the depth of all children is the same.
  56930. ** 8. Make sure this page is at least 33% full or else it is
  56931. ** the root of the tree.
  56932. */
  56933. static int checkTreePage(
  56934. IntegrityCk *pCheck, /* Context for the sanity check */
  56935. int iPage, /* Page number of the page to check */
  56936. char *zParentContext, /* Parent context */
  56937. i64 *pnParentMinKey,
  56938. i64 *pnParentMaxKey
  56939. ){
  56940. MemPage *pPage;
  56941. int i, rc, depth, d2, pgno, cnt;
  56942. int hdr, cellStart;
  56943. int nCell;
  56944. u8 *data;
  56945. BtShared *pBt;
  56946. int usableSize;
  56947. char zContext[100];
  56948. char *hit = 0;
  56949. i64 nMinKey = 0;
  56950. i64 nMaxKey = 0;
  56951. sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
  56952. /* Check that the page exists
  56953. */
  56954. pBt = pCheck->pBt;
  56955. usableSize = pBt->usableSize;
  56956. if( iPage==0 ) return 0;
  56957. if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  56958. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  56959. checkAppendMsg(pCheck, zContext,
  56960. "unable to get the page. error code=%d", rc);
  56961. return 0;
  56962. }
  56963. /* Clear MemPage.isInit to make sure the corruption detection code in
  56964. ** btreeInitPage() is executed. */
  56965. pPage->isInit = 0;
  56966. if( (rc = btreeInitPage(pPage))!=0 ){
  56967. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  56968. checkAppendMsg(pCheck, zContext,
  56969. "btreeInitPage() returns error code %d", rc);
  56970. releasePage(pPage);
  56971. return 0;
  56972. }
  56973. /* Check out all the cells.
  56974. */
  56975. depth = 0;
  56976. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  56977. u8 *pCell;
  56978. u32 sz;
  56979. CellInfo info;
  56980. /* Check payload overflow pages
  56981. */
  56982. sqlite3_snprintf(sizeof(zContext), zContext,
  56983. "On tree page %d cell %d: ", iPage, i);
  56984. pCell = findCell(pPage,i);
  56985. btreeParseCellPtr(pPage, pCell, &info);
  56986. sz = info.nData;
  56987. if( !pPage->intKey ) sz += (int)info.nKey;
  56988. /* For intKey pages, check that the keys are in order.
  56989. */
  56990. else if( i==0 ) nMinKey = nMaxKey = info.nKey;
  56991. else{
  56992. if( info.nKey <= nMaxKey ){
  56993. checkAppendMsg(pCheck, zContext,
  56994. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  56995. }
  56996. nMaxKey = info.nKey;
  56997. }
  56998. assert( sz==info.nPayload );
  56999. if( (sz>info.nLocal)
  57000. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  57001. ){
  57002. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  57003. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  57004. #ifndef SQLITE_OMIT_AUTOVACUUM
  57005. if( pBt->autoVacuum ){
  57006. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
  57007. }
  57008. #endif
  57009. checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
  57010. }
  57011. /* Check sanity of left child page.
  57012. */
  57013. if( !pPage->leaf ){
  57014. pgno = get4byte(pCell);
  57015. #ifndef SQLITE_OMIT_AUTOVACUUM
  57016. if( pBt->autoVacuum ){
  57017. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  57018. }
  57019. #endif
  57020. d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
  57021. if( i>0 && d2!=depth ){
  57022. checkAppendMsg(pCheck, zContext, "Child page depth differs");
  57023. }
  57024. depth = d2;
  57025. }
  57026. }
  57027. if( !pPage->leaf ){
  57028. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  57029. sqlite3_snprintf(sizeof(zContext), zContext,
  57030. "On page %d at right child: ", iPage);
  57031. #ifndef SQLITE_OMIT_AUTOVACUUM
  57032. if( pBt->autoVacuum ){
  57033. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
  57034. }
  57035. #endif
  57036. checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
  57037. }
  57038. /* For intKey leaf pages, check that the min/max keys are in order
  57039. ** with any left/parent/right pages.
  57040. */
  57041. if( pPage->leaf && pPage->intKey ){
  57042. /* if we are a left child page */
  57043. if( pnParentMinKey ){
  57044. /* if we are the left most child page */
  57045. if( !pnParentMaxKey ){
  57046. if( nMaxKey > *pnParentMinKey ){
  57047. checkAppendMsg(pCheck, zContext,
  57048. "Rowid %lld out of order (max larger than parent min of %lld)",
  57049. nMaxKey, *pnParentMinKey);
  57050. }
  57051. }else{
  57052. if( nMinKey <= *pnParentMinKey ){
  57053. checkAppendMsg(pCheck, zContext,
  57054. "Rowid %lld out of order (min less than parent min of %lld)",
  57055. nMinKey, *pnParentMinKey);
  57056. }
  57057. if( nMaxKey > *pnParentMaxKey ){
  57058. checkAppendMsg(pCheck, zContext,
  57059. "Rowid %lld out of order (max larger than parent max of %lld)",
  57060. nMaxKey, *pnParentMaxKey);
  57061. }
  57062. *pnParentMinKey = nMaxKey;
  57063. }
  57064. /* else if we're a right child page */
  57065. } else if( pnParentMaxKey ){
  57066. if( nMinKey <= *pnParentMaxKey ){
  57067. checkAppendMsg(pCheck, zContext,
  57068. "Rowid %lld out of order (min less than parent max of %lld)",
  57069. nMinKey, *pnParentMaxKey);
  57070. }
  57071. }
  57072. }
  57073. /* Check for complete coverage of the page
  57074. */
  57075. data = pPage->aData;
  57076. hdr = pPage->hdrOffset;
  57077. hit = sqlite3PageMalloc( pBt->pageSize );
  57078. if( hit==0 ){
  57079. pCheck->mallocFailed = 1;
  57080. }else{
  57081. int contentOffset = get2byteNotZero(&data[hdr+5]);
  57082. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  57083. memset(hit+contentOffset, 0, usableSize-contentOffset);
  57084. memset(hit, 1, contentOffset);
  57085. nCell = get2byte(&data[hdr+3]);
  57086. cellStart = hdr + 12 - 4*pPage->leaf;
  57087. for(i=0; i<nCell; i++){
  57088. int pc = get2byte(&data[cellStart+i*2]);
  57089. u32 size = 65536;
  57090. int j;
  57091. if( pc<=usableSize-4 ){
  57092. size = cellSizePtr(pPage, &data[pc]);
  57093. }
  57094. if( (int)(pc+size-1)>=usableSize ){
  57095. checkAppendMsg(pCheck, 0,
  57096. "Corruption detected in cell %d on page %d",i,iPage);
  57097. }else{
  57098. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  57099. }
  57100. }
  57101. i = get2byte(&data[hdr+1]);
  57102. while( i>0 ){
  57103. int size, j;
  57104. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57105. size = get2byte(&data[i+2]);
  57106. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  57107. for(j=i+size-1; j>=i; j--) hit[j]++;
  57108. j = get2byte(&data[i]);
  57109. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  57110. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  57111. i = j;
  57112. }
  57113. for(i=cnt=0; i<usableSize; i++){
  57114. if( hit[i]==0 ){
  57115. cnt++;
  57116. }else if( hit[i]>1 ){
  57117. checkAppendMsg(pCheck, 0,
  57118. "Multiple uses for byte %d of page %d", i, iPage);
  57119. break;
  57120. }
  57121. }
  57122. if( cnt!=data[hdr+7] ){
  57123. checkAppendMsg(pCheck, 0,
  57124. "Fragmentation of %d bytes reported as %d on page %d",
  57125. cnt, data[hdr+7], iPage);
  57126. }
  57127. }
  57128. sqlite3PageFree(hit);
  57129. releasePage(pPage);
  57130. return depth+1;
  57131. }
  57132. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57133. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  57134. /*
  57135. ** This routine does a complete check of the given BTree file. aRoot[] is
  57136. ** an array of pages numbers were each page number is the root page of
  57137. ** a table. nRoot is the number of entries in aRoot.
  57138. **
  57139. ** A read-only or read-write transaction must be opened before calling
  57140. ** this function.
  57141. **
  57142. ** Write the number of error seen in *pnErr. Except for some memory
  57143. ** allocation errors, an error message held in memory obtained from
  57144. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  57145. ** returned. If a memory allocation error occurs, NULL is returned.
  57146. */
  57147. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  57148. Btree *p, /* The btree to be checked */
  57149. int *aRoot, /* An array of root pages numbers for individual trees */
  57150. int nRoot, /* Number of entries in aRoot[] */
  57151. int mxErr, /* Stop reporting errors after this many */
  57152. int *pnErr /* Write number of errors seen to this variable */
  57153. ){
  57154. Pgno i;
  57155. int nRef;
  57156. IntegrityCk sCheck;
  57157. BtShared *pBt = p->pBt;
  57158. char zErr[100];
  57159. sqlite3BtreeEnter(p);
  57160. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  57161. nRef = sqlite3PagerRefcount(pBt->pPager);
  57162. sCheck.pBt = pBt;
  57163. sCheck.pPager = pBt->pPager;
  57164. sCheck.nPage = btreePagecount(sCheck.pBt);
  57165. sCheck.mxErr = mxErr;
  57166. sCheck.nErr = 0;
  57167. sCheck.mallocFailed = 0;
  57168. *pnErr = 0;
  57169. if( sCheck.nPage==0 ){
  57170. sqlite3BtreeLeave(p);
  57171. return 0;
  57172. }
  57173. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  57174. if( !sCheck.aPgRef ){
  57175. *pnErr = 1;
  57176. sqlite3BtreeLeave(p);
  57177. return 0;
  57178. }
  57179. i = PENDING_BYTE_PAGE(pBt);
  57180. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  57181. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  57182. sCheck.errMsg.useMalloc = 2;
  57183. /* Check the integrity of the freelist
  57184. */
  57185. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  57186. get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
  57187. /* Check all the tables.
  57188. */
  57189. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  57190. if( aRoot[i]==0 ) continue;
  57191. #ifndef SQLITE_OMIT_AUTOVACUUM
  57192. if( pBt->autoVacuum && aRoot[i]>1 ){
  57193. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
  57194. }
  57195. #endif
  57196. checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
  57197. }
  57198. /* Make sure every page in the file is referenced
  57199. */
  57200. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  57201. #ifdef SQLITE_OMIT_AUTOVACUUM
  57202. if( getPageReferenced(&sCheck, i)==0 ){
  57203. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  57204. }
  57205. #else
  57206. /* If the database supports auto-vacuum, make sure no tables contain
  57207. ** references to pointer-map pages.
  57208. */
  57209. if( getPageReferenced(&sCheck, i)==0 &&
  57210. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  57211. checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
  57212. }
  57213. if( getPageReferenced(&sCheck, i)!=0 &&
  57214. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  57215. checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
  57216. }
  57217. #endif
  57218. }
  57219. /* Make sure this analysis did not leave any unref() pages.
  57220. ** This is an internal consistency check; an integrity check
  57221. ** of the integrity check.
  57222. */
  57223. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  57224. checkAppendMsg(&sCheck, 0,
  57225. "Outstanding page count goes from %d to %d during this analysis",
  57226. nRef, sqlite3PagerRefcount(pBt->pPager)
  57227. );
  57228. }
  57229. /* Clean up and report errors.
  57230. */
  57231. sqlite3BtreeLeave(p);
  57232. sqlite3_free(sCheck.aPgRef);
  57233. if( sCheck.mallocFailed ){
  57234. sqlite3StrAccumReset(&sCheck.errMsg);
  57235. *pnErr = sCheck.nErr+1;
  57236. return 0;
  57237. }
  57238. *pnErr = sCheck.nErr;
  57239. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  57240. return sqlite3StrAccumFinish(&sCheck.errMsg);
  57241. }
  57242. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  57243. /*
  57244. ** Return the full pathname of the underlying database file. Return
  57245. ** an empty string if the database is in-memory or a TEMP database.
  57246. **
  57247. ** The pager filename is invariant as long as the pager is
  57248. ** open so it is safe to access without the BtShared mutex.
  57249. */
  57250. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  57251. assert( p->pBt->pPager!=0 );
  57252. return sqlite3PagerFilename(p->pBt->pPager, 1);
  57253. }
  57254. /*
  57255. ** Return the pathname of the journal file for this database. The return
  57256. ** value of this routine is the same regardless of whether the journal file
  57257. ** has been created or not.
  57258. **
  57259. ** The pager journal filename is invariant as long as the pager is
  57260. ** open so it is safe to access without the BtShared mutex.
  57261. */
  57262. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  57263. assert( p->pBt->pPager!=0 );
  57264. return sqlite3PagerJournalname(p->pBt->pPager);
  57265. }
  57266. /*
  57267. ** Return non-zero if a transaction is active.
  57268. */
  57269. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  57270. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  57271. return (p && (p->inTrans==TRANS_WRITE));
  57272. }
  57273. #ifndef SQLITE_OMIT_WAL
  57274. /*
  57275. ** Run a checkpoint on the Btree passed as the first argument.
  57276. **
  57277. ** Return SQLITE_LOCKED if this or any other connection has an open
  57278. ** transaction on the shared-cache the argument Btree is connected to.
  57279. **
  57280. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  57281. */
  57282. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  57283. int rc = SQLITE_OK;
  57284. if( p ){
  57285. BtShared *pBt = p->pBt;
  57286. sqlite3BtreeEnter(p);
  57287. if( pBt->inTransaction!=TRANS_NONE ){
  57288. rc = SQLITE_LOCKED;
  57289. }else{
  57290. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  57291. }
  57292. sqlite3BtreeLeave(p);
  57293. }
  57294. return rc;
  57295. }
  57296. #endif
  57297. /*
  57298. ** Return non-zero if a read (or write) transaction is active.
  57299. */
  57300. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  57301. assert( p );
  57302. assert( sqlite3_mutex_held(p->db->mutex) );
  57303. return p->inTrans!=TRANS_NONE;
  57304. }
  57305. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  57306. assert( p );
  57307. assert( sqlite3_mutex_held(p->db->mutex) );
  57308. return p->nBackup!=0;
  57309. }
  57310. /*
  57311. ** This function returns a pointer to a blob of memory associated with
  57312. ** a single shared-btree. The memory is used by client code for its own
  57313. ** purposes (for example, to store a high-level schema associated with
  57314. ** the shared-btree). The btree layer manages reference counting issues.
  57315. **
  57316. ** The first time this is called on a shared-btree, nBytes bytes of memory
  57317. ** are allocated, zeroed, and returned to the caller. For each subsequent
  57318. ** call the nBytes parameter is ignored and a pointer to the same blob
  57319. ** of memory returned.
  57320. **
  57321. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  57322. ** allocated, a null pointer is returned. If the blob has already been
  57323. ** allocated, it is returned as normal.
  57324. **
  57325. ** Just before the shared-btree is closed, the function passed as the
  57326. ** xFree argument when the memory allocation was made is invoked on the
  57327. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  57328. ** on the memory, the btree layer does that.
  57329. */
  57330. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  57331. BtShared *pBt = p->pBt;
  57332. sqlite3BtreeEnter(p);
  57333. if( !pBt->pSchema && nBytes ){
  57334. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  57335. pBt->xFreeSchema = xFree;
  57336. }
  57337. sqlite3BtreeLeave(p);
  57338. return pBt->pSchema;
  57339. }
  57340. /*
  57341. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  57342. ** btree as the argument handle holds an exclusive lock on the
  57343. ** sqlite_master table. Otherwise SQLITE_OK.
  57344. */
  57345. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  57346. int rc;
  57347. assert( sqlite3_mutex_held(p->db->mutex) );
  57348. sqlite3BtreeEnter(p);
  57349. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  57350. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  57351. sqlite3BtreeLeave(p);
  57352. return rc;
  57353. }
  57354. #ifndef SQLITE_OMIT_SHARED_CACHE
  57355. /*
  57356. ** Obtain a lock on the table whose root page is iTab. The
  57357. ** lock is a write lock if isWritelock is true or a read lock
  57358. ** if it is false.
  57359. */
  57360. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  57361. int rc = SQLITE_OK;
  57362. assert( p->inTrans!=TRANS_NONE );
  57363. if( p->sharable ){
  57364. u8 lockType = READ_LOCK + isWriteLock;
  57365. assert( READ_LOCK+1==WRITE_LOCK );
  57366. assert( isWriteLock==0 || isWriteLock==1 );
  57367. sqlite3BtreeEnter(p);
  57368. rc = querySharedCacheTableLock(p, iTab, lockType);
  57369. if( rc==SQLITE_OK ){
  57370. rc = setSharedCacheTableLock(p, iTab, lockType);
  57371. }
  57372. sqlite3BtreeLeave(p);
  57373. }
  57374. return rc;
  57375. }
  57376. #endif
  57377. #ifndef SQLITE_OMIT_INCRBLOB
  57378. /*
  57379. ** Argument pCsr must be a cursor opened for writing on an
  57380. ** INTKEY table currently pointing at a valid table entry.
  57381. ** This function modifies the data stored as part of that entry.
  57382. **
  57383. ** Only the data content may only be modified, it is not possible to
  57384. ** change the length of the data stored. If this function is called with
  57385. ** parameters that attempt to write past the end of the existing data,
  57386. ** no modifications are made and SQLITE_CORRUPT is returned.
  57387. */
  57388. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  57389. int rc;
  57390. assert( cursorHoldsMutex(pCsr) );
  57391. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  57392. assert( pCsr->isIncrblobHandle );
  57393. rc = restoreCursorPosition(pCsr);
  57394. if( rc!=SQLITE_OK ){
  57395. return rc;
  57396. }
  57397. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  57398. if( pCsr->eState!=CURSOR_VALID ){
  57399. return SQLITE_ABORT;
  57400. }
  57401. /* Save the positions of all other cursors open on this table. This is
  57402. ** required in case any of them are holding references to an xFetch
  57403. ** version of the b-tree page modified by the accessPayload call below.
  57404. **
  57405. ** Note that pCsr must be open on a BTREE_INTKEY table and saveCursorPosition()
  57406. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  57407. ** saveAllCursors can only return SQLITE_OK.
  57408. */
  57409. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  57410. assert( rc==SQLITE_OK );
  57411. /* Check some assumptions:
  57412. ** (a) the cursor is open for writing,
  57413. ** (b) there is a read/write transaction open,
  57414. ** (c) the connection holds a write-lock on the table (if required),
  57415. ** (d) there are no conflicting read-locks, and
  57416. ** (e) the cursor points at a valid row of an intKey table.
  57417. */
  57418. if( !pCsr->wrFlag ){
  57419. return SQLITE_READONLY;
  57420. }
  57421. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  57422. && pCsr->pBt->inTransaction==TRANS_WRITE );
  57423. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  57424. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  57425. assert( pCsr->apPage[pCsr->iPage]->intKey );
  57426. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  57427. }
  57428. /*
  57429. ** Set a flag on this cursor to cache the locations of pages from the
  57430. ** overflow list for the current row. This is used by cursors opened
  57431. ** for incremental blob IO only.
  57432. **
  57433. ** This function sets a flag only. The actual page location cache
  57434. ** (stored in BtCursor.aOverflow[]) is allocated and used by function
  57435. ** accessPayload() (the worker function for sqlite3BtreeData() and
  57436. ** sqlite3BtreePutData()).
  57437. */
  57438. SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
  57439. assert( cursorHoldsMutex(pCur) );
  57440. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  57441. invalidateOverflowCache(pCur);
  57442. pCur->isIncrblobHandle = 1;
  57443. }
  57444. #endif
  57445. /*
  57446. ** Set both the "read version" (single byte at byte offset 18) and
  57447. ** "write version" (single byte at byte offset 19) fields in the database
  57448. ** header to iVersion.
  57449. */
  57450. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  57451. BtShared *pBt = pBtree->pBt;
  57452. int rc; /* Return code */
  57453. assert( iVersion==1 || iVersion==2 );
  57454. /* If setting the version fields to 1, do not automatically open the
  57455. ** WAL connection, even if the version fields are currently set to 2.
  57456. */
  57457. pBt->btsFlags &= ~BTS_NO_WAL;
  57458. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  57459. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  57460. if( rc==SQLITE_OK ){
  57461. u8 *aData = pBt->pPage1->aData;
  57462. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  57463. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  57464. if( rc==SQLITE_OK ){
  57465. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  57466. if( rc==SQLITE_OK ){
  57467. aData[18] = (u8)iVersion;
  57468. aData[19] = (u8)iVersion;
  57469. }
  57470. }
  57471. }
  57472. }
  57473. pBt->btsFlags &= ~BTS_NO_WAL;
  57474. return rc;
  57475. }
  57476. /*
  57477. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  57478. ** values are 0 and BTREE_BULKLOAD.
  57479. */
  57480. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  57481. assert( mask==BTREE_BULKLOAD || mask==0 );
  57482. pCsr->hints = mask;
  57483. }
  57484. /************** End of btree.c ***********************************************/
  57485. /************** Begin file backup.c ******************************************/
  57486. /*
  57487. ** 2009 January 28
  57488. **
  57489. ** The author disclaims copyright to this source code. In place of
  57490. ** a legal notice, here is a blessing:
  57491. **
  57492. ** May you do good and not evil.
  57493. ** May you find forgiveness for yourself and forgive others.
  57494. ** May you share freely, never taking more than you give.
  57495. **
  57496. *************************************************************************
  57497. ** This file contains the implementation of the sqlite3_backup_XXX()
  57498. ** API functions and the related features.
  57499. */
  57500. /*
  57501. ** Structure allocated for each backup operation.
  57502. */
  57503. struct sqlite3_backup {
  57504. sqlite3* pDestDb; /* Destination database handle */
  57505. Btree *pDest; /* Destination b-tree file */
  57506. u32 iDestSchema; /* Original schema cookie in destination */
  57507. int bDestLocked; /* True once a write-transaction is open on pDest */
  57508. Pgno iNext; /* Page number of the next source page to copy */
  57509. sqlite3* pSrcDb; /* Source database handle */
  57510. Btree *pSrc; /* Source b-tree file */
  57511. int rc; /* Backup process error code */
  57512. /* These two variables are set by every call to backup_step(). They are
  57513. ** read by calls to backup_remaining() and backup_pagecount().
  57514. */
  57515. Pgno nRemaining; /* Number of pages left to copy */
  57516. Pgno nPagecount; /* Total number of pages to copy */
  57517. int isAttached; /* True once backup has been registered with pager */
  57518. sqlite3_backup *pNext; /* Next backup associated with source pager */
  57519. };
  57520. /*
  57521. ** THREAD SAFETY NOTES:
  57522. **
  57523. ** Once it has been created using backup_init(), a single sqlite3_backup
  57524. ** structure may be accessed via two groups of thread-safe entry points:
  57525. **
  57526. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  57527. ** backup_finish(). Both these functions obtain the source database
  57528. ** handle mutex and the mutex associated with the source BtShared
  57529. ** structure, in that order.
  57530. **
  57531. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  57532. ** invoked by the pager layer to report various state changes in
  57533. ** the page cache associated with the source database. The mutex
  57534. ** associated with the source database BtShared structure will always
  57535. ** be held when either of these functions are invoked.
  57536. **
  57537. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  57538. ** backup_pagecount() are not thread-safe functions. If they are called
  57539. ** while some other thread is calling backup_step() or backup_finish(),
  57540. ** the values returned may be invalid. There is no way for a call to
  57541. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  57542. ** or backup_pagecount().
  57543. **
  57544. ** Depending on the SQLite configuration, the database handles and/or
  57545. ** the Btree objects may have their own mutexes that require locking.
  57546. ** Non-sharable Btrees (in-memory databases for example), do not have
  57547. ** associated mutexes.
  57548. */
  57549. /*
  57550. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  57551. ** in connection handle pDb. If such a database cannot be found, return
  57552. ** a NULL pointer and write an error message to pErrorDb.
  57553. **
  57554. ** If the "temp" database is requested, it may need to be opened by this
  57555. ** function. If an error occurs while doing so, return 0 and write an
  57556. ** error message to pErrorDb.
  57557. */
  57558. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  57559. int i = sqlite3FindDbName(pDb, zDb);
  57560. if( i==1 ){
  57561. Parse *pParse;
  57562. int rc = 0;
  57563. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  57564. if( pParse==0 ){
  57565. sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
  57566. rc = SQLITE_NOMEM;
  57567. }else{
  57568. pParse->db = pDb;
  57569. if( sqlite3OpenTempDatabase(pParse) ){
  57570. sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  57571. rc = SQLITE_ERROR;
  57572. }
  57573. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  57574. sqlite3StackFree(pErrorDb, pParse);
  57575. }
  57576. if( rc ){
  57577. return 0;
  57578. }
  57579. }
  57580. if( i<0 ){
  57581. sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  57582. return 0;
  57583. }
  57584. return pDb->aDb[i].pBt;
  57585. }
  57586. /*
  57587. ** Attempt to set the page size of the destination to match the page size
  57588. ** of the source.
  57589. */
  57590. static int setDestPgsz(sqlite3_backup *p){
  57591. int rc;
  57592. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  57593. return rc;
  57594. }
  57595. /*
  57596. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  57597. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  57598. ** a pointer to the new sqlite3_backup object.
  57599. **
  57600. ** If an error occurs, NULL is returned and an error code and error message
  57601. ** stored in database handle pDestDb.
  57602. */
  57603. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  57604. sqlite3* pDestDb, /* Database to write to */
  57605. const char *zDestDb, /* Name of database within pDestDb */
  57606. sqlite3* pSrcDb, /* Database connection to read from */
  57607. const char *zSrcDb /* Name of database within pSrcDb */
  57608. ){
  57609. sqlite3_backup *p; /* Value to return */
  57610. /* Lock the source database handle. The destination database
  57611. ** handle is not locked in this routine, but it is locked in
  57612. ** sqlite3_backup_step(). The user is required to ensure that no
  57613. ** other thread accesses the destination handle for the duration
  57614. ** of the backup operation. Any attempt to use the destination
  57615. ** database connection while a backup is in progress may cause
  57616. ** a malfunction or a deadlock.
  57617. */
  57618. sqlite3_mutex_enter(pSrcDb->mutex);
  57619. sqlite3_mutex_enter(pDestDb->mutex);
  57620. if( pSrcDb==pDestDb ){
  57621. sqlite3Error(
  57622. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  57623. );
  57624. p = 0;
  57625. }else {
  57626. /* Allocate space for a new sqlite3_backup object...
  57627. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  57628. ** call to sqlite3_backup_init() and is destroyed by a call to
  57629. ** sqlite3_backup_finish(). */
  57630. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  57631. if( !p ){
  57632. sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
  57633. }
  57634. }
  57635. /* If the allocation succeeded, populate the new object. */
  57636. if( p ){
  57637. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  57638. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  57639. p->pDestDb = pDestDb;
  57640. p->pSrcDb = pSrcDb;
  57641. p->iNext = 1;
  57642. p->isAttached = 0;
  57643. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  57644. /* One (or both) of the named databases did not exist or an OOM
  57645. ** error was hit. The error has already been written into the
  57646. ** pDestDb handle. All that is left to do here is free the
  57647. ** sqlite3_backup structure.
  57648. */
  57649. sqlite3_free(p);
  57650. p = 0;
  57651. }
  57652. }
  57653. if( p ){
  57654. p->pSrc->nBackup++;
  57655. }
  57656. sqlite3_mutex_leave(pDestDb->mutex);
  57657. sqlite3_mutex_leave(pSrcDb->mutex);
  57658. return p;
  57659. }
  57660. /*
  57661. ** Argument rc is an SQLite error code. Return true if this error is
  57662. ** considered fatal if encountered during a backup operation. All errors
  57663. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  57664. */
  57665. static int isFatalError(int rc){
  57666. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  57667. }
  57668. /*
  57669. ** Parameter zSrcData points to a buffer containing the data for
  57670. ** page iSrcPg from the source database. Copy this data into the
  57671. ** destination database.
  57672. */
  57673. static int backupOnePage(
  57674. sqlite3_backup *p, /* Backup handle */
  57675. Pgno iSrcPg, /* Source database page to backup */
  57676. const u8 *zSrcData, /* Source database page data */
  57677. int bUpdate /* True for an update, false otherwise */
  57678. ){
  57679. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  57680. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  57681. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  57682. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  57683. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  57684. #ifdef SQLITE_HAS_CODEC
  57685. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  57686. ** guaranteed that the shared-mutex is held by this thread, handle
  57687. ** p->pSrc may not actually be the owner. */
  57688. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  57689. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  57690. #endif
  57691. int rc = SQLITE_OK;
  57692. i64 iOff;
  57693. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  57694. assert( p->bDestLocked );
  57695. assert( !isFatalError(p->rc) );
  57696. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  57697. assert( zSrcData );
  57698. /* Catch the case where the destination is an in-memory database and the
  57699. ** page sizes of the source and destination differ.
  57700. */
  57701. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  57702. rc = SQLITE_READONLY;
  57703. }
  57704. #ifdef SQLITE_HAS_CODEC
  57705. /* Backup is not possible if the page size of the destination is changing
  57706. ** and a codec is in use.
  57707. */
  57708. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  57709. rc = SQLITE_READONLY;
  57710. }
  57711. /* Backup is not possible if the number of bytes of reserve space differ
  57712. ** between source and destination. If there is a difference, try to
  57713. ** fix the destination to agree with the source. If that is not possible,
  57714. ** then the backup cannot proceed.
  57715. */
  57716. if( nSrcReserve!=nDestReserve ){
  57717. u32 newPgsz = nSrcPgsz;
  57718. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  57719. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  57720. }
  57721. #endif
  57722. /* This loop runs once for each destination page spanned by the source
  57723. ** page. For each iteration, variable iOff is set to the byte offset
  57724. ** of the destination page.
  57725. */
  57726. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  57727. DbPage *pDestPg = 0;
  57728. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  57729. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  57730. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  57731. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  57732. ){
  57733. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  57734. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  57735. u8 *zOut = &zDestData[iOff%nDestPgsz];
  57736. /* Copy the data from the source page into the destination page.
  57737. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  57738. ** and the pager code use this trick (clearing the first byte
  57739. ** of the page 'extra' space to invalidate the Btree layers
  57740. ** cached parse of the page). MemPage.isInit is marked
  57741. ** "MUST BE FIRST" for this purpose.
  57742. */
  57743. memcpy(zOut, zIn, nCopy);
  57744. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  57745. if( iOff==0 && bUpdate==0 ){
  57746. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  57747. }
  57748. }
  57749. sqlite3PagerUnref(pDestPg);
  57750. }
  57751. return rc;
  57752. }
  57753. /*
  57754. ** If pFile is currently larger than iSize bytes, then truncate it to
  57755. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  57756. ** this function is a no-op.
  57757. **
  57758. ** Return SQLITE_OK if everything is successful, or an SQLite error
  57759. ** code if an error occurs.
  57760. */
  57761. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  57762. i64 iCurrent;
  57763. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  57764. if( rc==SQLITE_OK && iCurrent>iSize ){
  57765. rc = sqlite3OsTruncate(pFile, iSize);
  57766. }
  57767. return rc;
  57768. }
  57769. /*
  57770. ** Register this backup object with the associated source pager for
  57771. ** callbacks when pages are changed or the cache invalidated.
  57772. */
  57773. static void attachBackupObject(sqlite3_backup *p){
  57774. sqlite3_backup **pp;
  57775. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  57776. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57777. p->pNext = *pp;
  57778. *pp = p;
  57779. p->isAttached = 1;
  57780. }
  57781. /*
  57782. ** Copy nPage pages from the source b-tree to the destination.
  57783. */
  57784. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  57785. int rc;
  57786. int destMode; /* Destination journal mode */
  57787. int pgszSrc = 0; /* Source page size */
  57788. int pgszDest = 0; /* Destination page size */
  57789. sqlite3_mutex_enter(p->pSrcDb->mutex);
  57790. sqlite3BtreeEnter(p->pSrc);
  57791. if( p->pDestDb ){
  57792. sqlite3_mutex_enter(p->pDestDb->mutex);
  57793. }
  57794. rc = p->rc;
  57795. if( !isFatalError(rc) ){
  57796. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  57797. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  57798. int ii; /* Iterator variable */
  57799. int nSrcPage = -1; /* Size of source db in pages */
  57800. int bCloseTrans = 0; /* True if src db requires unlocking */
  57801. /* If the source pager is currently in a write-transaction, return
  57802. ** SQLITE_BUSY immediately.
  57803. */
  57804. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  57805. rc = SQLITE_BUSY;
  57806. }else{
  57807. rc = SQLITE_OK;
  57808. }
  57809. /* Lock the destination database, if it is not locked already. */
  57810. if( SQLITE_OK==rc && p->bDestLocked==0
  57811. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  57812. ){
  57813. p->bDestLocked = 1;
  57814. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  57815. }
  57816. /* If there is no open read-transaction on the source database, open
  57817. ** one now. If a transaction is opened here, then it will be closed
  57818. ** before this function exits.
  57819. */
  57820. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  57821. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  57822. bCloseTrans = 1;
  57823. }
  57824. /* Do not allow backup if the destination database is in WAL mode
  57825. ** and the page sizes are different between source and destination */
  57826. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  57827. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  57828. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  57829. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  57830. rc = SQLITE_READONLY;
  57831. }
  57832. /* Now that there is a read-lock on the source database, query the
  57833. ** source pager for the number of pages in the database.
  57834. */
  57835. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  57836. assert( nSrcPage>=0 );
  57837. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  57838. const Pgno iSrcPg = p->iNext; /* Source page number */
  57839. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  57840. DbPage *pSrcPg; /* Source page object */
  57841. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  57842. PAGER_GET_READONLY);
  57843. if( rc==SQLITE_OK ){
  57844. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  57845. sqlite3PagerUnref(pSrcPg);
  57846. }
  57847. }
  57848. p->iNext++;
  57849. }
  57850. if( rc==SQLITE_OK ){
  57851. p->nPagecount = nSrcPage;
  57852. p->nRemaining = nSrcPage+1-p->iNext;
  57853. if( p->iNext>(Pgno)nSrcPage ){
  57854. rc = SQLITE_DONE;
  57855. }else if( !p->isAttached ){
  57856. attachBackupObject(p);
  57857. }
  57858. }
  57859. /* Update the schema version field in the destination database. This
  57860. ** is to make sure that the schema-version really does change in
  57861. ** the case where the source and destination databases have the
  57862. ** same schema version.
  57863. */
  57864. if( rc==SQLITE_DONE ){
  57865. if( nSrcPage==0 ){
  57866. rc = sqlite3BtreeNewDb(p->pDest);
  57867. nSrcPage = 1;
  57868. }
  57869. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  57870. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  57871. }
  57872. if( rc==SQLITE_OK ){
  57873. if( p->pDestDb ){
  57874. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  57875. }
  57876. if( destMode==PAGER_JOURNALMODE_WAL ){
  57877. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  57878. }
  57879. }
  57880. if( rc==SQLITE_OK ){
  57881. int nDestTruncate;
  57882. /* Set nDestTruncate to the final number of pages in the destination
  57883. ** database. The complication here is that the destination page
  57884. ** size may be different to the source page size.
  57885. **
  57886. ** If the source page size is smaller than the destination page size,
  57887. ** round up. In this case the call to sqlite3OsTruncate() below will
  57888. ** fix the size of the file. However it is important to call
  57889. ** sqlite3PagerTruncateImage() here so that any pages in the
  57890. ** destination file that lie beyond the nDestTruncate page mark are
  57891. ** journalled by PagerCommitPhaseOne() before they are destroyed
  57892. ** by the file truncation.
  57893. */
  57894. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  57895. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  57896. if( pgszSrc<pgszDest ){
  57897. int ratio = pgszDest/pgszSrc;
  57898. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  57899. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57900. nDestTruncate--;
  57901. }
  57902. }else{
  57903. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  57904. }
  57905. assert( nDestTruncate>0 );
  57906. if( pgszSrc<pgszDest ){
  57907. /* If the source page-size is smaller than the destination page-size,
  57908. ** two extra things may need to happen:
  57909. **
  57910. ** * The destination may need to be truncated, and
  57911. **
  57912. ** * Data stored on the pages immediately following the
  57913. ** pending-byte page in the source database may need to be
  57914. ** copied into the destination database.
  57915. */
  57916. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  57917. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  57918. Pgno iPg;
  57919. int nDstPage;
  57920. i64 iOff;
  57921. i64 iEnd;
  57922. assert( pFile );
  57923. assert( nDestTruncate==0
  57924. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  57925. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  57926. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  57927. ));
  57928. /* This block ensures that all data required to recreate the original
  57929. ** database has been stored in the journal for pDestPager and the
  57930. ** journal synced to disk. So at this point we may safely modify
  57931. ** the database file in any way, knowing that if a power failure
  57932. ** occurs, the original database will be reconstructed from the
  57933. ** journal file. */
  57934. sqlite3PagerPagecount(pDestPager, &nDstPage);
  57935. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  57936. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57937. DbPage *pPg;
  57938. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  57939. if( rc==SQLITE_OK ){
  57940. rc = sqlite3PagerWrite(pPg);
  57941. sqlite3PagerUnref(pPg);
  57942. }
  57943. }
  57944. }
  57945. if( rc==SQLITE_OK ){
  57946. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  57947. }
  57948. /* Write the extra pages and truncate the database file as required */
  57949. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  57950. for(
  57951. iOff=PENDING_BYTE+pgszSrc;
  57952. rc==SQLITE_OK && iOff<iEnd;
  57953. iOff+=pgszSrc
  57954. ){
  57955. PgHdr *pSrcPg = 0;
  57956. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  57957. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  57958. if( rc==SQLITE_OK ){
  57959. u8 *zData = sqlite3PagerGetData(pSrcPg);
  57960. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  57961. }
  57962. sqlite3PagerUnref(pSrcPg);
  57963. }
  57964. if( rc==SQLITE_OK ){
  57965. rc = backupTruncateFile(pFile, iSize);
  57966. }
  57967. /* Sync the database file to disk. */
  57968. if( rc==SQLITE_OK ){
  57969. rc = sqlite3PagerSync(pDestPager);
  57970. }
  57971. }else{
  57972. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  57973. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  57974. }
  57975. /* Finish committing the transaction to the destination database. */
  57976. if( SQLITE_OK==rc
  57977. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  57978. ){
  57979. rc = SQLITE_DONE;
  57980. }
  57981. }
  57982. }
  57983. /* If bCloseTrans is true, then this function opened a read transaction
  57984. ** on the source database. Close the read transaction here. There is
  57985. ** no need to check the return values of the btree methods here, as
  57986. ** "committing" a read-only transaction cannot fail.
  57987. */
  57988. if( bCloseTrans ){
  57989. TESTONLY( int rc2 );
  57990. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  57991. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  57992. assert( rc2==SQLITE_OK );
  57993. }
  57994. if( rc==SQLITE_IOERR_NOMEM ){
  57995. rc = SQLITE_NOMEM;
  57996. }
  57997. p->rc = rc;
  57998. }
  57999. if( p->pDestDb ){
  58000. sqlite3_mutex_leave(p->pDestDb->mutex);
  58001. }
  58002. sqlite3BtreeLeave(p->pSrc);
  58003. sqlite3_mutex_leave(p->pSrcDb->mutex);
  58004. return rc;
  58005. }
  58006. /*
  58007. ** Release all resources associated with an sqlite3_backup* handle.
  58008. */
  58009. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  58010. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  58011. sqlite3 *pSrcDb; /* Source database connection */
  58012. int rc; /* Value to return */
  58013. /* Enter the mutexes */
  58014. if( p==0 ) return SQLITE_OK;
  58015. pSrcDb = p->pSrcDb;
  58016. sqlite3_mutex_enter(pSrcDb->mutex);
  58017. sqlite3BtreeEnter(p->pSrc);
  58018. if( p->pDestDb ){
  58019. sqlite3_mutex_enter(p->pDestDb->mutex);
  58020. }
  58021. /* Detach this backup from the source pager. */
  58022. if( p->pDestDb ){
  58023. p->pSrc->nBackup--;
  58024. }
  58025. if( p->isAttached ){
  58026. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  58027. while( *pp!=p ){
  58028. pp = &(*pp)->pNext;
  58029. }
  58030. *pp = p->pNext;
  58031. }
  58032. /* If a transaction is still open on the Btree, roll it back. */
  58033. sqlite3BtreeRollback(p->pDest, SQLITE_OK);
  58034. /* Set the error code of the destination database handle. */
  58035. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  58036. sqlite3Error(p->pDestDb, rc, 0);
  58037. /* Exit the mutexes and free the backup context structure. */
  58038. if( p->pDestDb ){
  58039. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  58040. }
  58041. sqlite3BtreeLeave(p->pSrc);
  58042. if( p->pDestDb ){
  58043. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  58044. ** call to sqlite3_backup_init() and is destroyed by a call to
  58045. ** sqlite3_backup_finish(). */
  58046. sqlite3_free(p);
  58047. }
  58048. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  58049. return rc;
  58050. }
  58051. /*
  58052. ** Return the number of pages still to be backed up as of the most recent
  58053. ** call to sqlite3_backup_step().
  58054. */
  58055. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  58056. return p->nRemaining;
  58057. }
  58058. /*
  58059. ** Return the total number of pages in the source database as of the most
  58060. ** recent call to sqlite3_backup_step().
  58061. */
  58062. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  58063. return p->nPagecount;
  58064. }
  58065. /*
  58066. ** This function is called after the contents of page iPage of the
  58067. ** source database have been modified. If page iPage has already been
  58068. ** copied into the destination database, then the data written to the
  58069. ** destination is now invalidated. The destination copy of iPage needs
  58070. ** to be updated with the new data before the backup operation is
  58071. ** complete.
  58072. **
  58073. ** It is assumed that the mutex associated with the BtShared object
  58074. ** corresponding to the source database is held when this function is
  58075. ** called.
  58076. */
  58077. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  58078. sqlite3_backup *p; /* Iterator variable */
  58079. for(p=pBackup; p; p=p->pNext){
  58080. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58081. if( !isFatalError(p->rc) && iPage<p->iNext ){
  58082. /* The backup process p has already copied page iPage. But now it
  58083. ** has been modified by a transaction on the source pager. Copy
  58084. ** the new data into the backup.
  58085. */
  58086. int rc;
  58087. assert( p->pDestDb );
  58088. sqlite3_mutex_enter(p->pDestDb->mutex);
  58089. rc = backupOnePage(p, iPage, aData, 1);
  58090. sqlite3_mutex_leave(p->pDestDb->mutex);
  58091. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  58092. if( rc!=SQLITE_OK ){
  58093. p->rc = rc;
  58094. }
  58095. }
  58096. }
  58097. }
  58098. /*
  58099. ** Restart the backup process. This is called when the pager layer
  58100. ** detects that the database has been modified by an external database
  58101. ** connection. In this case there is no way of knowing which of the
  58102. ** pages that have been copied into the destination database are still
  58103. ** valid and which are not, so the entire process needs to be restarted.
  58104. **
  58105. ** It is assumed that the mutex associated with the BtShared object
  58106. ** corresponding to the source database is held when this function is
  58107. ** called.
  58108. */
  58109. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  58110. sqlite3_backup *p; /* Iterator variable */
  58111. for(p=pBackup; p; p=p->pNext){
  58112. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  58113. p->iNext = 1;
  58114. }
  58115. }
  58116. #ifndef SQLITE_OMIT_VACUUM
  58117. /*
  58118. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  58119. ** must be active for both files.
  58120. **
  58121. ** The size of file pTo may be reduced by this operation. If anything
  58122. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  58123. ** transaction is committed before returning.
  58124. */
  58125. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  58126. int rc;
  58127. sqlite3_file *pFd; /* File descriptor for database pTo */
  58128. sqlite3_backup b;
  58129. sqlite3BtreeEnter(pTo);
  58130. sqlite3BtreeEnter(pFrom);
  58131. assert( sqlite3BtreeIsInTrans(pTo) );
  58132. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  58133. if( pFd->pMethods ){
  58134. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  58135. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  58136. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  58137. if( rc ) goto copy_finished;
  58138. }
  58139. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  58140. ** to 0. This is used by the implementations of sqlite3_backup_step()
  58141. ** and sqlite3_backup_finish() to detect that they are being called
  58142. ** from this function, not directly by the user.
  58143. */
  58144. memset(&b, 0, sizeof(b));
  58145. b.pSrcDb = pFrom->db;
  58146. b.pSrc = pFrom;
  58147. b.pDest = pTo;
  58148. b.iNext = 1;
  58149. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  58150. ** file. By passing this as the number of pages to copy to
  58151. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  58152. ** within a single call (unless an error occurs). The assert() statement
  58153. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  58154. ** or an error code.
  58155. */
  58156. sqlite3_backup_step(&b, 0x7FFFFFFF);
  58157. assert( b.rc!=SQLITE_OK );
  58158. rc = sqlite3_backup_finish(&b);
  58159. if( rc==SQLITE_OK ){
  58160. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  58161. }else{
  58162. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  58163. }
  58164. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  58165. copy_finished:
  58166. sqlite3BtreeLeave(pFrom);
  58167. sqlite3BtreeLeave(pTo);
  58168. return rc;
  58169. }
  58170. #endif /* SQLITE_OMIT_VACUUM */
  58171. /************** End of backup.c **********************************************/
  58172. /************** Begin file vdbemem.c *****************************************/
  58173. /*
  58174. ** 2004 May 26
  58175. **
  58176. ** The author disclaims copyright to this source code. In place of
  58177. ** a legal notice, here is a blessing:
  58178. **
  58179. ** May you do good and not evil.
  58180. ** May you find forgiveness for yourself and forgive others.
  58181. ** May you share freely, never taking more than you give.
  58182. **
  58183. *************************************************************************
  58184. **
  58185. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  58186. ** stores a single value in the VDBE. Mem is an opaque structure visible
  58187. ** only within the VDBE. Interface routines refer to a Mem using the
  58188. ** name sqlite_value
  58189. */
  58190. /*
  58191. ** If pMem is an object with a valid string representation, this routine
  58192. ** ensures the internal encoding for the string representation is
  58193. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  58194. **
  58195. ** If pMem is not a string object, or the encoding of the string
  58196. ** representation is already stored using the requested encoding, then this
  58197. ** routine is a no-op.
  58198. **
  58199. ** SQLITE_OK is returned if the conversion is successful (or not required).
  58200. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  58201. ** between formats.
  58202. */
  58203. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  58204. #ifndef SQLITE_OMIT_UTF16
  58205. int rc;
  58206. #endif
  58207. assert( (pMem->flags&MEM_RowSet)==0 );
  58208. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  58209. || desiredEnc==SQLITE_UTF16BE );
  58210. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  58211. return SQLITE_OK;
  58212. }
  58213. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58214. #ifdef SQLITE_OMIT_UTF16
  58215. return SQLITE_ERROR;
  58216. #else
  58217. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  58218. ** then the encoding of the value may not have changed.
  58219. */
  58220. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  58221. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  58222. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  58223. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  58224. return rc;
  58225. #endif
  58226. }
  58227. /*
  58228. ** Make sure pMem->z points to a writable allocation of at least
  58229. ** n bytes.
  58230. **
  58231. ** If the third argument passed to this function is true, then memory
  58232. ** cell pMem must contain a string or blob. In this case the content is
  58233. ** preserved. Otherwise, if the third parameter to this function is false,
  58234. ** any current string or blob value may be discarded.
  58235. **
  58236. ** This function sets the MEM_Dyn flag and clears any xDel callback.
  58237. ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is
  58238. ** not set, Mem.n is zeroed.
  58239. */
  58240. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
  58241. assert( 1 >=
  58242. ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
  58243. (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) +
  58244. ((pMem->flags&MEM_Ephem) ? 1 : 0) +
  58245. ((pMem->flags&MEM_Static) ? 1 : 0)
  58246. );
  58247. assert( (pMem->flags&MEM_RowSet)==0 );
  58248. /* If the preserve flag is set to true, then the memory cell must already
  58249. ** contain a valid string or blob value. */
  58250. assert( preserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  58251. if( n<32 ) n = 32;
  58252. if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
  58253. if( preserve && pMem->z==pMem->zMalloc ){
  58254. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  58255. preserve = 0;
  58256. }else{
  58257. sqlite3DbFree(pMem->db, pMem->zMalloc);
  58258. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  58259. }
  58260. }
  58261. if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
  58262. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  58263. }
  58264. if( pMem->flags&MEM_Dyn && pMem->xDel ){
  58265. assert( pMem->xDel!=SQLITE_DYNAMIC );
  58266. pMem->xDel((void *)(pMem->z));
  58267. }
  58268. pMem->z = pMem->zMalloc;
  58269. if( pMem->z==0 ){
  58270. pMem->flags = MEM_Null;
  58271. }else{
  58272. pMem->flags &= ~(MEM_Ephem|MEM_Static);
  58273. }
  58274. pMem->xDel = 0;
  58275. return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
  58276. }
  58277. /*
  58278. ** Make the given Mem object MEM_Dyn. In other words, make it so
  58279. ** that any TEXT or BLOB content is stored in memory obtained from
  58280. ** malloc(). In this way, we know that the memory is safe to be
  58281. ** overwritten or altered.
  58282. **
  58283. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  58284. */
  58285. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  58286. int f;
  58287. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58288. assert( (pMem->flags&MEM_RowSet)==0 );
  58289. ExpandBlob(pMem);
  58290. f = pMem->flags;
  58291. if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
  58292. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  58293. return SQLITE_NOMEM;
  58294. }
  58295. pMem->z[pMem->n] = 0;
  58296. pMem->z[pMem->n+1] = 0;
  58297. pMem->flags |= MEM_Term;
  58298. #ifdef SQLITE_DEBUG
  58299. pMem->pScopyFrom = 0;
  58300. #endif
  58301. }
  58302. return SQLITE_OK;
  58303. }
  58304. /*
  58305. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  58306. ** blob stored in dynamically allocated space.
  58307. */
  58308. #ifndef SQLITE_OMIT_INCRBLOB
  58309. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  58310. if( pMem->flags & MEM_Zero ){
  58311. int nByte;
  58312. assert( pMem->flags&MEM_Blob );
  58313. assert( (pMem->flags&MEM_RowSet)==0 );
  58314. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58315. /* Set nByte to the number of bytes required to store the expanded blob. */
  58316. nByte = pMem->n + pMem->u.nZero;
  58317. if( nByte<=0 ){
  58318. nByte = 1;
  58319. }
  58320. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  58321. return SQLITE_NOMEM;
  58322. }
  58323. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  58324. pMem->n += pMem->u.nZero;
  58325. pMem->flags &= ~(MEM_Zero|MEM_Term);
  58326. }
  58327. return SQLITE_OK;
  58328. }
  58329. #endif
  58330. /*
  58331. ** Make sure the given Mem is \u0000 terminated.
  58332. */
  58333. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  58334. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58335. if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
  58336. return SQLITE_OK; /* Nothing to do */
  58337. }
  58338. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  58339. return SQLITE_NOMEM;
  58340. }
  58341. pMem->z[pMem->n] = 0;
  58342. pMem->z[pMem->n+1] = 0;
  58343. pMem->flags |= MEM_Term;
  58344. return SQLITE_OK;
  58345. }
  58346. /*
  58347. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  58348. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  58349. ** is a no-op.
  58350. **
  58351. ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
  58352. **
  58353. ** A MEM_Null value will never be passed to this function. This function is
  58354. ** used for converting values to text for returning to the user (i.e. via
  58355. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  58356. ** keys are strings. In the former case a NULL pointer is returned the
  58357. ** user and the later is an internal programming error.
  58358. */
  58359. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
  58360. int rc = SQLITE_OK;
  58361. int fg = pMem->flags;
  58362. const int nByte = 32;
  58363. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58364. assert( !(fg&MEM_Zero) );
  58365. assert( !(fg&(MEM_Str|MEM_Blob)) );
  58366. assert( fg&(MEM_Int|MEM_Real) );
  58367. assert( (pMem->flags&MEM_RowSet)==0 );
  58368. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58369. if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  58370. return SQLITE_NOMEM;
  58371. }
  58372. /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
  58373. ** string representation of the value. Then, if the required encoding
  58374. ** is UTF-16le or UTF-16be do a translation.
  58375. **
  58376. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  58377. */
  58378. if( fg & MEM_Int ){
  58379. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  58380. }else{
  58381. assert( fg & MEM_Real );
  58382. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
  58383. }
  58384. pMem->n = sqlite3Strlen30(pMem->z);
  58385. pMem->enc = SQLITE_UTF8;
  58386. pMem->flags |= MEM_Str|MEM_Term;
  58387. sqlite3VdbeChangeEncoding(pMem, enc);
  58388. return rc;
  58389. }
  58390. /*
  58391. ** Memory cell pMem contains the context of an aggregate function.
  58392. ** This routine calls the finalize method for that function. The
  58393. ** result of the aggregate is stored back into pMem.
  58394. **
  58395. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  58396. ** otherwise.
  58397. */
  58398. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  58399. int rc = SQLITE_OK;
  58400. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  58401. sqlite3_context ctx;
  58402. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  58403. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58404. memset(&ctx, 0, sizeof(ctx));
  58405. ctx.s.flags = MEM_Null;
  58406. ctx.s.db = pMem->db;
  58407. ctx.pMem = pMem;
  58408. ctx.pFunc = pFunc;
  58409. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  58410. assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
  58411. sqlite3DbFree(pMem->db, pMem->zMalloc);
  58412. memcpy(pMem, &ctx.s, sizeof(ctx.s));
  58413. rc = ctx.isError;
  58414. }
  58415. return rc;
  58416. }
  58417. /*
  58418. ** If the memory cell contains a string value that must be freed by
  58419. ** invoking an external callback, free it now. Calling this function
  58420. ** does not free any Mem.zMalloc buffer.
  58421. */
  58422. SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
  58423. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  58424. if( p->flags&MEM_Agg ){
  58425. sqlite3VdbeMemFinalize(p, p->u.pDef);
  58426. assert( (p->flags & MEM_Agg)==0 );
  58427. sqlite3VdbeMemRelease(p);
  58428. }else if( p->flags&MEM_Dyn && p->xDel ){
  58429. assert( (p->flags&MEM_RowSet)==0 );
  58430. assert( p->xDel!=SQLITE_DYNAMIC );
  58431. p->xDel((void *)p->z);
  58432. p->xDel = 0;
  58433. }else if( p->flags&MEM_RowSet ){
  58434. sqlite3RowSetClear(p->u.pRowSet);
  58435. }else if( p->flags&MEM_Frame ){
  58436. sqlite3VdbeMemSetNull(p);
  58437. }
  58438. }
  58439. /*
  58440. ** Release any memory held by the Mem. This may leave the Mem in an
  58441. ** inconsistent state, for example with (Mem.z==0) and
  58442. ** (Mem.type==SQLITE_TEXT).
  58443. */
  58444. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  58445. VdbeMemRelease(p);
  58446. sqlite3DbFree(p->db, p->zMalloc);
  58447. p->z = 0;
  58448. p->zMalloc = 0;
  58449. p->xDel = 0;
  58450. }
  58451. /*
  58452. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  58453. ** If the double is too large, return 0x8000000000000000.
  58454. **
  58455. ** Most systems appear to do this simply by assigning
  58456. ** variables and without the extra range tests. But
  58457. ** there are reports that windows throws an expection
  58458. ** if the floating point value is out of range. (See ticket #2880.)
  58459. ** Because we do not completely understand the problem, we will
  58460. ** take the conservative approach and always do range tests
  58461. ** before attempting the conversion.
  58462. */
  58463. static i64 doubleToInt64(double r){
  58464. #ifdef SQLITE_OMIT_FLOATING_POINT
  58465. /* When floating-point is omitted, double and int64 are the same thing */
  58466. return r;
  58467. #else
  58468. /*
  58469. ** Many compilers we encounter do not define constants for the
  58470. ** minimum and maximum 64-bit integers, or they define them
  58471. ** inconsistently. And many do not understand the "LL" notation.
  58472. ** So we define our own static constants here using nothing
  58473. ** larger than a 32-bit integer constant.
  58474. */
  58475. static const i64 maxInt = LARGEST_INT64;
  58476. static const i64 minInt = SMALLEST_INT64;
  58477. if( r<(double)minInt ){
  58478. return minInt;
  58479. }else if( r>(double)maxInt ){
  58480. /* minInt is correct here - not maxInt. It turns out that assigning
  58481. ** a very large positive number to an integer results in a very large
  58482. ** negative integer. This makes no sense, but it is what x86 hardware
  58483. ** does so for compatibility we will do the same in software. */
  58484. return minInt;
  58485. }else{
  58486. return (i64)r;
  58487. }
  58488. #endif
  58489. }
  58490. /*
  58491. ** Return some kind of integer value which is the best we can do
  58492. ** at representing the value that *pMem describes as an integer.
  58493. ** If pMem is an integer, then the value is exact. If pMem is
  58494. ** a floating-point then the value returned is the integer part.
  58495. ** If pMem is a string or blob, then we make an attempt to convert
  58496. ** it into a integer and return that. If pMem represents an
  58497. ** an SQL-NULL value, return 0.
  58498. **
  58499. ** If pMem represents a string value, its encoding might be changed.
  58500. */
  58501. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  58502. int flags;
  58503. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58504. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58505. flags = pMem->flags;
  58506. if( flags & MEM_Int ){
  58507. return pMem->u.i;
  58508. }else if( flags & MEM_Real ){
  58509. return doubleToInt64(pMem->r);
  58510. }else if( flags & (MEM_Str|MEM_Blob) ){
  58511. i64 value = 0;
  58512. assert( pMem->z || pMem->n==0 );
  58513. testcase( pMem->z==0 );
  58514. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  58515. return value;
  58516. }else{
  58517. return 0;
  58518. }
  58519. }
  58520. /*
  58521. ** Return the best representation of pMem that we can get into a
  58522. ** double. If pMem is already a double or an integer, return its
  58523. ** value. If it is a string or blob, try to convert it to a double.
  58524. ** If it is a NULL, return 0.0.
  58525. */
  58526. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  58527. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58528. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58529. if( pMem->flags & MEM_Real ){
  58530. return pMem->r;
  58531. }else if( pMem->flags & MEM_Int ){
  58532. return (double)pMem->u.i;
  58533. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  58534. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58535. double val = (double)0;
  58536. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  58537. return val;
  58538. }else{
  58539. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  58540. return (double)0;
  58541. }
  58542. }
  58543. /*
  58544. ** The MEM structure is already a MEM_Real. Try to also make it a
  58545. ** MEM_Int if we can.
  58546. */
  58547. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  58548. assert( pMem->flags & MEM_Real );
  58549. assert( (pMem->flags & MEM_RowSet)==0 );
  58550. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58551. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58552. pMem->u.i = doubleToInt64(pMem->r);
  58553. /* Only mark the value as an integer if
  58554. **
  58555. ** (1) the round-trip conversion real->int->real is a no-op, and
  58556. ** (2) The integer is neither the largest nor the smallest
  58557. ** possible integer (ticket #3922)
  58558. **
  58559. ** The second and third terms in the following conditional enforces
  58560. ** the second condition under the assumption that addition overflow causes
  58561. ** values to wrap around. On x86 hardware, the third term is always
  58562. ** true and could be omitted. But we leave it in because other
  58563. ** architectures might behave differently.
  58564. */
  58565. if( pMem->r==(double)pMem->u.i
  58566. && pMem->u.i>SMALLEST_INT64
  58567. #if defined(__i486__) || defined(__x86_64__)
  58568. && ALWAYS(pMem->u.i<LARGEST_INT64)
  58569. #else
  58570. && pMem->u.i<LARGEST_INT64
  58571. #endif
  58572. ){
  58573. pMem->flags |= MEM_Int;
  58574. }
  58575. }
  58576. /*
  58577. ** Convert pMem to type integer. Invalidate any prior representations.
  58578. */
  58579. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  58580. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58581. assert( (pMem->flags & MEM_RowSet)==0 );
  58582. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58583. pMem->u.i = sqlite3VdbeIntValue(pMem);
  58584. MemSetTypeFlag(pMem, MEM_Int);
  58585. return SQLITE_OK;
  58586. }
  58587. /*
  58588. ** Convert pMem so that it is of type MEM_Real.
  58589. ** Invalidate any prior representations.
  58590. */
  58591. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  58592. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58593. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58594. pMem->r = sqlite3VdbeRealValue(pMem);
  58595. MemSetTypeFlag(pMem, MEM_Real);
  58596. return SQLITE_OK;
  58597. }
  58598. /*
  58599. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  58600. ** Invalidate any prior representations.
  58601. **
  58602. ** Every effort is made to force the conversion, even if the input
  58603. ** is a string that does not look completely like a number. Convert
  58604. ** as much of the string as we can and ignore the rest.
  58605. */
  58606. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  58607. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  58608. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  58609. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58610. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  58611. MemSetTypeFlag(pMem, MEM_Int);
  58612. }else{
  58613. pMem->r = sqlite3VdbeRealValue(pMem);
  58614. MemSetTypeFlag(pMem, MEM_Real);
  58615. sqlite3VdbeIntegerAffinity(pMem);
  58616. }
  58617. }
  58618. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  58619. pMem->flags &= ~(MEM_Str|MEM_Blob);
  58620. return SQLITE_OK;
  58621. }
  58622. /*
  58623. ** Delete any previous value and set the value stored in *pMem to NULL.
  58624. */
  58625. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  58626. if( pMem->flags & MEM_Frame ){
  58627. VdbeFrame *pFrame = pMem->u.pFrame;
  58628. pFrame->pParent = pFrame->v->pDelFrame;
  58629. pFrame->v->pDelFrame = pFrame;
  58630. }
  58631. if( pMem->flags & MEM_RowSet ){
  58632. sqlite3RowSetClear(pMem->u.pRowSet);
  58633. }
  58634. MemSetTypeFlag(pMem, MEM_Null);
  58635. pMem->type = SQLITE_NULL;
  58636. }
  58637. /*
  58638. ** Delete any previous value and set the value to be a BLOB of length
  58639. ** n containing all zeros.
  58640. */
  58641. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  58642. sqlite3VdbeMemRelease(pMem);
  58643. pMem->flags = MEM_Blob|MEM_Zero;
  58644. pMem->type = SQLITE_BLOB;
  58645. pMem->n = 0;
  58646. if( n<0 ) n = 0;
  58647. pMem->u.nZero = n;
  58648. pMem->enc = SQLITE_UTF8;
  58649. #ifdef SQLITE_OMIT_INCRBLOB
  58650. sqlite3VdbeMemGrow(pMem, n, 0);
  58651. if( pMem->z ){
  58652. pMem->n = n;
  58653. memset(pMem->z, 0, n);
  58654. }
  58655. #endif
  58656. }
  58657. /*
  58658. ** Delete any previous value and set the value stored in *pMem to val,
  58659. ** manifest type INTEGER.
  58660. */
  58661. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  58662. sqlite3VdbeMemRelease(pMem);
  58663. pMem->u.i = val;
  58664. pMem->flags = MEM_Int;
  58665. pMem->type = SQLITE_INTEGER;
  58666. }
  58667. #ifndef SQLITE_OMIT_FLOATING_POINT
  58668. /*
  58669. ** Delete any previous value and set the value stored in *pMem to val,
  58670. ** manifest type REAL.
  58671. */
  58672. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  58673. if( sqlite3IsNaN(val) ){
  58674. sqlite3VdbeMemSetNull(pMem);
  58675. }else{
  58676. sqlite3VdbeMemRelease(pMem);
  58677. pMem->r = val;
  58678. pMem->flags = MEM_Real;
  58679. pMem->type = SQLITE_FLOAT;
  58680. }
  58681. }
  58682. #endif
  58683. /*
  58684. ** Delete any previous value and set the value of pMem to be an
  58685. ** empty boolean index.
  58686. */
  58687. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  58688. sqlite3 *db = pMem->db;
  58689. assert( db!=0 );
  58690. assert( (pMem->flags & MEM_RowSet)==0 );
  58691. sqlite3VdbeMemRelease(pMem);
  58692. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  58693. if( db->mallocFailed ){
  58694. pMem->flags = MEM_Null;
  58695. }else{
  58696. assert( pMem->zMalloc );
  58697. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc,
  58698. sqlite3DbMallocSize(db, pMem->zMalloc));
  58699. assert( pMem->u.pRowSet!=0 );
  58700. pMem->flags = MEM_RowSet;
  58701. }
  58702. }
  58703. /*
  58704. ** Return true if the Mem object contains a TEXT or BLOB that is
  58705. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  58706. */
  58707. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  58708. assert( p->db!=0 );
  58709. if( p->flags & (MEM_Str|MEM_Blob) ){
  58710. int n = p->n;
  58711. if( p->flags & MEM_Zero ){
  58712. n += p->u.nZero;
  58713. }
  58714. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  58715. }
  58716. return 0;
  58717. }
  58718. #ifdef SQLITE_DEBUG
  58719. /*
  58720. ** This routine prepares a memory cell for modication by breaking
  58721. ** its link to a shallow copy and by marking any current shallow
  58722. ** copies of this cell as invalid.
  58723. **
  58724. ** This is used for testing and debugging only - to make sure shallow
  58725. ** copies are not misused.
  58726. */
  58727. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  58728. int i;
  58729. Mem *pX;
  58730. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  58731. if( pX->pScopyFrom==pMem ){
  58732. pX->flags |= MEM_Invalid;
  58733. pX->pScopyFrom = 0;
  58734. }
  58735. }
  58736. pMem->pScopyFrom = 0;
  58737. }
  58738. #endif /* SQLITE_DEBUG */
  58739. /*
  58740. ** Size of struct Mem not including the Mem.zMalloc member.
  58741. */
  58742. #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
  58743. /*
  58744. ** Make an shallow copy of pFrom into pTo. Prior contents of
  58745. ** pTo are freed. The pFrom->z field is not duplicated. If
  58746. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  58747. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  58748. */
  58749. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  58750. assert( (pFrom->flags & MEM_RowSet)==0 );
  58751. VdbeMemRelease(pTo);
  58752. memcpy(pTo, pFrom, MEMCELLSIZE);
  58753. pTo->xDel = 0;
  58754. if( (pFrom->flags&MEM_Static)==0 ){
  58755. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  58756. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  58757. pTo->flags |= srcType;
  58758. }
  58759. }
  58760. /*
  58761. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  58762. ** freed before the copy is made.
  58763. */
  58764. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  58765. int rc = SQLITE_OK;
  58766. assert( (pFrom->flags & MEM_RowSet)==0 );
  58767. VdbeMemRelease(pTo);
  58768. memcpy(pTo, pFrom, MEMCELLSIZE);
  58769. pTo->flags &= ~MEM_Dyn;
  58770. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  58771. if( 0==(pFrom->flags&MEM_Static) ){
  58772. pTo->flags |= MEM_Ephem;
  58773. rc = sqlite3VdbeMemMakeWriteable(pTo);
  58774. }
  58775. }
  58776. return rc;
  58777. }
  58778. /*
  58779. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  58780. ** freed. If pFrom contains ephemeral data, a copy is made.
  58781. **
  58782. ** pFrom contains an SQL NULL when this routine returns.
  58783. */
  58784. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  58785. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  58786. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  58787. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  58788. sqlite3VdbeMemRelease(pTo);
  58789. memcpy(pTo, pFrom, sizeof(Mem));
  58790. pFrom->flags = MEM_Null;
  58791. pFrom->xDel = 0;
  58792. pFrom->zMalloc = 0;
  58793. }
  58794. /*
  58795. ** Change the value of a Mem to be a string or a BLOB.
  58796. **
  58797. ** The memory management strategy depends on the value of the xDel
  58798. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  58799. ** string is copied into a (possibly existing) buffer managed by the
  58800. ** Mem structure. Otherwise, any existing buffer is freed and the
  58801. ** pointer copied.
  58802. **
  58803. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  58804. ** size limit) then no memory allocation occurs. If the string can be
  58805. ** stored without allocating memory, then it is. If a memory allocation
  58806. ** is required to store the string, then value of pMem is unchanged. In
  58807. ** either case, SQLITE_TOOBIG is returned.
  58808. */
  58809. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  58810. Mem *pMem, /* Memory cell to set to string value */
  58811. const char *z, /* String pointer */
  58812. int n, /* Bytes in string, or negative */
  58813. u8 enc, /* Encoding of z. 0 for BLOBs */
  58814. void (*xDel)(void*) /* Destructor function */
  58815. ){
  58816. int nByte = n; /* New value for pMem->n */
  58817. int iLimit; /* Maximum allowed string or blob size */
  58818. u16 flags = 0; /* New value for pMem->flags */
  58819. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58820. assert( (pMem->flags & MEM_RowSet)==0 );
  58821. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  58822. if( !z ){
  58823. sqlite3VdbeMemSetNull(pMem);
  58824. return SQLITE_OK;
  58825. }
  58826. if( pMem->db ){
  58827. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  58828. }else{
  58829. iLimit = SQLITE_MAX_LENGTH;
  58830. }
  58831. flags = (enc==0?MEM_Blob:MEM_Str);
  58832. if( nByte<0 ){
  58833. assert( enc!=0 );
  58834. if( enc==SQLITE_UTF8 ){
  58835. for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
  58836. }else{
  58837. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  58838. }
  58839. flags |= MEM_Term;
  58840. }
  58841. /* The following block sets the new values of Mem.z and Mem.xDel. It
  58842. ** also sets a flag in local variable "flags" to indicate the memory
  58843. ** management (one of MEM_Dyn or MEM_Static).
  58844. */
  58845. if( xDel==SQLITE_TRANSIENT ){
  58846. int nAlloc = nByte;
  58847. if( flags&MEM_Term ){
  58848. nAlloc += (enc==SQLITE_UTF8?1:2);
  58849. }
  58850. if( nByte>iLimit ){
  58851. return SQLITE_TOOBIG;
  58852. }
  58853. if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
  58854. return SQLITE_NOMEM;
  58855. }
  58856. memcpy(pMem->z, z, nAlloc);
  58857. }else if( xDel==SQLITE_DYNAMIC ){
  58858. sqlite3VdbeMemRelease(pMem);
  58859. pMem->zMalloc = pMem->z = (char *)z;
  58860. pMem->xDel = 0;
  58861. }else{
  58862. sqlite3VdbeMemRelease(pMem);
  58863. pMem->z = (char *)z;
  58864. pMem->xDel = xDel;
  58865. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  58866. }
  58867. pMem->n = nByte;
  58868. pMem->flags = flags;
  58869. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  58870. pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
  58871. #ifndef SQLITE_OMIT_UTF16
  58872. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  58873. return SQLITE_NOMEM;
  58874. }
  58875. #endif
  58876. if( nByte>iLimit ){
  58877. return SQLITE_TOOBIG;
  58878. }
  58879. return SQLITE_OK;
  58880. }
  58881. /*
  58882. ** Compare the values contained by the two memory cells, returning
  58883. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  58884. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  58885. ** and reals) sorted numerically, followed by text ordered by the collating
  58886. ** sequence pColl and finally blob's ordered by memcmp().
  58887. **
  58888. ** Two NULL values are considered equal by this function.
  58889. */
  58890. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  58891. int rc;
  58892. int f1, f2;
  58893. int combined_flags;
  58894. f1 = pMem1->flags;
  58895. f2 = pMem2->flags;
  58896. combined_flags = f1|f2;
  58897. assert( (combined_flags & MEM_RowSet)==0 );
  58898. /* If one value is NULL, it is less than the other. If both values
  58899. ** are NULL, return 0.
  58900. */
  58901. if( combined_flags&MEM_Null ){
  58902. return (f2&MEM_Null) - (f1&MEM_Null);
  58903. }
  58904. /* If one value is a number and the other is not, the number is less.
  58905. ** If both are numbers, compare as reals if one is a real, or as integers
  58906. ** if both values are integers.
  58907. */
  58908. if( combined_flags&(MEM_Int|MEM_Real) ){
  58909. double r1, r2;
  58910. if( (f1 & f2 & MEM_Int)!=0 ){
  58911. if( pMem1->u.i < pMem2->u.i ) return -1;
  58912. if( pMem1->u.i > pMem2->u.i ) return 1;
  58913. return 0;
  58914. }
  58915. if( (f1&MEM_Real)!=0 ){
  58916. r1 = pMem1->r;
  58917. }else if( (f1&MEM_Int)!=0 ){
  58918. r1 = (double)pMem1->u.i;
  58919. }else{
  58920. return 1;
  58921. }
  58922. if( (f2&MEM_Real)!=0 ){
  58923. r2 = pMem2->r;
  58924. }else if( (f2&MEM_Int)!=0 ){
  58925. r2 = (double)pMem2->u.i;
  58926. }else{
  58927. return -1;
  58928. }
  58929. if( r1<r2 ) return -1;
  58930. if( r1>r2 ) return 1;
  58931. return 0;
  58932. }
  58933. /* If one value is a string and the other is a blob, the string is less.
  58934. ** If both are strings, compare using the collating functions.
  58935. */
  58936. if( combined_flags&MEM_Str ){
  58937. if( (f1 & MEM_Str)==0 ){
  58938. return 1;
  58939. }
  58940. if( (f2 & MEM_Str)==0 ){
  58941. return -1;
  58942. }
  58943. assert( pMem1->enc==pMem2->enc );
  58944. assert( pMem1->enc==SQLITE_UTF8 ||
  58945. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  58946. /* The collation sequence must be defined at this point, even if
  58947. ** the user deletes the collation sequence after the vdbe program is
  58948. ** compiled (this was not always the case).
  58949. */
  58950. assert( !pColl || pColl->xCmp );
  58951. if( pColl ){
  58952. if( pMem1->enc==pColl->enc ){
  58953. /* The strings are already in the correct encoding. Call the
  58954. ** comparison function directly */
  58955. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  58956. }else{
  58957. const void *v1, *v2;
  58958. int n1, n2;
  58959. Mem c1;
  58960. Mem c2;
  58961. memset(&c1, 0, sizeof(c1));
  58962. memset(&c2, 0, sizeof(c2));
  58963. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  58964. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  58965. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  58966. n1 = v1==0 ? 0 : c1.n;
  58967. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  58968. n2 = v2==0 ? 0 : c2.n;
  58969. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  58970. sqlite3VdbeMemRelease(&c1);
  58971. sqlite3VdbeMemRelease(&c2);
  58972. return rc;
  58973. }
  58974. }
  58975. /* If a NULL pointer was passed as the collate function, fall through
  58976. ** to the blob case and use memcmp(). */
  58977. }
  58978. /* Both values must be blobs. Compare using memcmp(). */
  58979. rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
  58980. if( rc==0 ){
  58981. rc = pMem1->n - pMem2->n;
  58982. }
  58983. return rc;
  58984. }
  58985. /*
  58986. ** Move data out of a btree key or data field and into a Mem structure.
  58987. ** The data or key is taken from the entry that pCur is currently pointing
  58988. ** to. offset and amt determine what portion of the data or key to retrieve.
  58989. ** key is true to get the key or false to get data. The result is written
  58990. ** into the pMem element.
  58991. **
  58992. ** The pMem structure is assumed to be uninitialized. Any prior content
  58993. ** is overwritten without being freed.
  58994. **
  58995. ** If this routine fails for any reason (malloc returns NULL or unable
  58996. ** to read from the disk) then the pMem is left in an inconsistent state.
  58997. */
  58998. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  58999. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  59000. int offset, /* Offset from the start of data to return bytes from. */
  59001. int amt, /* Number of bytes to return. */
  59002. int key, /* If true, retrieve from the btree key, not data. */
  59003. Mem *pMem /* OUT: Return data in this Mem structure. */
  59004. ){
  59005. char *zData; /* Data from the btree layer */
  59006. int available = 0; /* Number of bytes available on the local btree page */
  59007. int rc = SQLITE_OK; /* Return code */
  59008. assert( sqlite3BtreeCursorIsValid(pCur) );
  59009. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  59010. ** that both the BtShared and database handle mutexes are held. */
  59011. assert( (pMem->flags & MEM_RowSet)==0 );
  59012. if( key ){
  59013. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  59014. }else{
  59015. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  59016. }
  59017. assert( zData!=0 );
  59018. if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
  59019. sqlite3VdbeMemRelease(pMem);
  59020. pMem->z = &zData[offset];
  59021. pMem->flags = MEM_Blob|MEM_Ephem;
  59022. }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
  59023. pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
  59024. pMem->enc = 0;
  59025. pMem->type = SQLITE_BLOB;
  59026. if( key ){
  59027. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  59028. }else{
  59029. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  59030. }
  59031. pMem->z[amt] = 0;
  59032. pMem->z[amt+1] = 0;
  59033. if( rc!=SQLITE_OK ){
  59034. sqlite3VdbeMemRelease(pMem);
  59035. }
  59036. }
  59037. pMem->n = amt;
  59038. return rc;
  59039. }
  59040. /* This function is only available internally, it is not part of the
  59041. ** external API. It works in a similar way to sqlite3_value_text(),
  59042. ** except the data returned is in the encoding specified by the second
  59043. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  59044. ** SQLITE_UTF8.
  59045. **
  59046. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  59047. ** If that is the case, then the result must be aligned on an even byte
  59048. ** boundary.
  59049. */
  59050. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  59051. if( !pVal ) return 0;
  59052. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  59053. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  59054. assert( (pVal->flags & MEM_RowSet)==0 );
  59055. if( pVal->flags&MEM_Null ){
  59056. return 0;
  59057. }
  59058. assert( (MEM_Blob>>3) == MEM_Str );
  59059. pVal->flags |= (pVal->flags & MEM_Blob)>>3;
  59060. ExpandBlob(pVal);
  59061. if( pVal->flags&MEM_Str ){
  59062. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  59063. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  59064. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  59065. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  59066. return 0;
  59067. }
  59068. }
  59069. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  59070. }else{
  59071. assert( (pVal->flags&MEM_Blob)==0 );
  59072. sqlite3VdbeMemStringify(pVal, enc);
  59073. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  59074. }
  59075. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  59076. || pVal->db->mallocFailed );
  59077. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  59078. return pVal->z;
  59079. }else{
  59080. return 0;
  59081. }
  59082. }
  59083. /*
  59084. ** Create a new sqlite3_value object.
  59085. */
  59086. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  59087. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  59088. if( p ){
  59089. p->flags = MEM_Null;
  59090. p->type = SQLITE_NULL;
  59091. p->db = db;
  59092. }
  59093. return p;
  59094. }
  59095. /*
  59096. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  59097. ** valueNew(). See comments above valueNew() for details.
  59098. */
  59099. struct ValueNewStat4Ctx {
  59100. Parse *pParse;
  59101. Index *pIdx;
  59102. UnpackedRecord **ppRec;
  59103. int iVal;
  59104. };
  59105. /*
  59106. ** Allocate and return a pointer to a new sqlite3_value object. If
  59107. ** the second argument to this function is NULL, the object is allocated
  59108. ** by calling sqlite3ValueNew().
  59109. **
  59110. ** Otherwise, if the second argument is non-zero, then this function is
  59111. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  59112. ** already been allocated, allocate the UnpackedRecord structure that
  59113. ** that function will return to its caller here. Then return a pointer
  59114. ** an sqlite3_value within the UnpackedRecord.a[] array.
  59115. */
  59116. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  59117. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59118. if( p ){
  59119. UnpackedRecord *pRec = p->ppRec[0];
  59120. if( pRec==0 ){
  59121. Index *pIdx = p->pIdx; /* Index being probed */
  59122. int nByte; /* Bytes of space to allocate */
  59123. int i; /* Counter variable */
  59124. int nCol = pIdx->nColumn+1; /* Number of index columns including rowid */
  59125. nByte = sizeof(Mem) * nCol + sizeof(UnpackedRecord);
  59126. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  59127. if( pRec ){
  59128. pRec->pKeyInfo = sqlite3IndexKeyinfo(p->pParse, pIdx);
  59129. if( pRec->pKeyInfo ){
  59130. assert( pRec->pKeyInfo->nField+1==nCol );
  59131. pRec->pKeyInfo->enc = ENC(db);
  59132. pRec->flags = UNPACKED_PREFIX_MATCH;
  59133. pRec->aMem = (Mem *)&pRec[1];
  59134. for(i=0; i<nCol; i++){
  59135. pRec->aMem[i].flags = MEM_Null;
  59136. pRec->aMem[i].type = SQLITE_NULL;
  59137. pRec->aMem[i].db = db;
  59138. }
  59139. }else{
  59140. sqlite3DbFree(db, pRec);
  59141. pRec = 0;
  59142. }
  59143. }
  59144. if( pRec==0 ) return 0;
  59145. p->ppRec[0] = pRec;
  59146. }
  59147. pRec->nField = p->iVal+1;
  59148. return &pRec->aMem[p->iVal];
  59149. }
  59150. #else
  59151. UNUSED_PARAMETER(p);
  59152. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  59153. return sqlite3ValueNew(db);
  59154. }
  59155. /*
  59156. ** Extract a value from the supplied expression in the manner described
  59157. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  59158. ** using valueNew().
  59159. **
  59160. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  59161. ** has been allocated, it is freed before returning. Or, if pCtx is not
  59162. ** NULL, it is assumed that the caller will free any allocated object
  59163. ** in all cases.
  59164. */
  59165. static int valueFromExpr(
  59166. sqlite3 *db, /* The database connection */
  59167. Expr *pExpr, /* The expression to evaluate */
  59168. u8 enc, /* Encoding to use */
  59169. u8 affinity, /* Affinity to use */
  59170. sqlite3_value **ppVal, /* Write the new value here */
  59171. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  59172. ){
  59173. int op;
  59174. char *zVal = 0;
  59175. sqlite3_value *pVal = 0;
  59176. int negInt = 1;
  59177. const char *zNeg = "";
  59178. int rc = SQLITE_OK;
  59179. if( !pExpr ){
  59180. *ppVal = 0;
  59181. return SQLITE_OK;
  59182. }
  59183. op = pExpr->op;
  59184. /* op can only be TK_REGISTER if we have compiled with SQLITE_ENABLE_STAT4.
  59185. ** The ifdef here is to enable us to achieve 100% branch test coverage even
  59186. ** when SQLITE_ENABLE_STAT4 is omitted.
  59187. */
  59188. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59189. if( op==TK_REGISTER ) op = pExpr->op2;
  59190. #else
  59191. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  59192. #endif
  59193. /* Handle negative integers in a single step. This is needed in the
  59194. ** case when the value is -9223372036854775808.
  59195. */
  59196. if( op==TK_UMINUS
  59197. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  59198. pExpr = pExpr->pLeft;
  59199. op = pExpr->op;
  59200. negInt = -1;
  59201. zNeg = "-";
  59202. }
  59203. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  59204. pVal = valueNew(db, pCtx);
  59205. if( pVal==0 ) goto no_mem;
  59206. if( ExprHasProperty(pExpr, EP_IntValue) ){
  59207. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  59208. }else{
  59209. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  59210. if( zVal==0 ) goto no_mem;
  59211. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  59212. if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
  59213. }
  59214. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  59215. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  59216. }else{
  59217. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  59218. }
  59219. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  59220. if( enc!=SQLITE_UTF8 ){
  59221. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  59222. }
  59223. }else if( op==TK_UMINUS ) {
  59224. /* This branch happens for multiple negative signs. Ex: -(-5) */
  59225. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  59226. && pVal!=0
  59227. ){
  59228. sqlite3VdbeMemNumerify(pVal);
  59229. if( pVal->u.i==SMALLEST_INT64 ){
  59230. pVal->flags &= MEM_Int;
  59231. pVal->flags |= MEM_Real;
  59232. pVal->r = (double)LARGEST_INT64;
  59233. }else{
  59234. pVal->u.i = -pVal->u.i;
  59235. }
  59236. pVal->r = -pVal->r;
  59237. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  59238. }
  59239. }else if( op==TK_NULL ){
  59240. pVal = valueNew(db, pCtx);
  59241. if( pVal==0 ) goto no_mem;
  59242. }
  59243. #ifndef SQLITE_OMIT_BLOB_LITERAL
  59244. else if( op==TK_BLOB ){
  59245. int nVal;
  59246. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  59247. assert( pExpr->u.zToken[1]=='\'' );
  59248. pVal = valueNew(db, pCtx);
  59249. if( !pVal ) goto no_mem;
  59250. zVal = &pExpr->u.zToken[2];
  59251. nVal = sqlite3Strlen30(zVal)-1;
  59252. assert( zVal[nVal]=='\'' );
  59253. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  59254. 0, SQLITE_DYNAMIC);
  59255. }
  59256. #endif
  59257. if( pVal ){
  59258. sqlite3VdbeMemStoreType(pVal);
  59259. }
  59260. *ppVal = pVal;
  59261. return rc;
  59262. no_mem:
  59263. db->mallocFailed = 1;
  59264. sqlite3DbFree(db, zVal);
  59265. assert( *ppVal==0 );
  59266. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59267. if( pCtx==0 ) sqlite3ValueFree(pVal);
  59268. #else
  59269. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  59270. #endif
  59271. return SQLITE_NOMEM;
  59272. }
  59273. /*
  59274. ** Create a new sqlite3_value object, containing the value of pExpr.
  59275. **
  59276. ** This only works for very simple expressions that consist of one constant
  59277. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  59278. ** be converted directly into a value, then the value is allocated and
  59279. ** a pointer written to *ppVal. The caller is responsible for deallocating
  59280. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  59281. ** cannot be converted to a value, then *ppVal is set to NULL.
  59282. */
  59283. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  59284. sqlite3 *db, /* The database connection */
  59285. Expr *pExpr, /* The expression to evaluate */
  59286. u8 enc, /* Encoding to use */
  59287. u8 affinity, /* Affinity to use */
  59288. sqlite3_value **ppVal /* Write the new value here */
  59289. ){
  59290. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  59291. }
  59292. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  59293. /*
  59294. ** The implementation of the sqlite_record() function. This function accepts
  59295. ** a single argument of any type. The return value is a formatted database
  59296. ** record (a blob) containing the argument value.
  59297. **
  59298. ** This is used to convert the value stored in the 'sample' column of the
  59299. ** sqlite_stat3 table to the record format SQLite uses internally.
  59300. */
  59301. static void recordFunc(
  59302. sqlite3_context *context,
  59303. int argc,
  59304. sqlite3_value **argv
  59305. ){
  59306. const int file_format = 1;
  59307. int iSerial; /* Serial type */
  59308. int nSerial; /* Bytes of space for iSerial as varint */
  59309. int nVal; /* Bytes of space required for argv[0] */
  59310. int nRet;
  59311. sqlite3 *db;
  59312. u8 *aRet;
  59313. UNUSED_PARAMETER( argc );
  59314. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  59315. nSerial = sqlite3VarintLen(iSerial);
  59316. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  59317. db = sqlite3_context_db_handle(context);
  59318. nRet = 1 + nSerial + nVal;
  59319. aRet = sqlite3DbMallocRaw(db, nRet);
  59320. if( aRet==0 ){
  59321. sqlite3_result_error_nomem(context);
  59322. }else{
  59323. aRet[0] = nSerial+1;
  59324. sqlite3PutVarint(&aRet[1], iSerial);
  59325. sqlite3VdbeSerialPut(&aRet[1+nSerial], nVal, argv[0], file_format);
  59326. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  59327. sqlite3DbFree(db, aRet);
  59328. }
  59329. }
  59330. /*
  59331. ** Register built-in functions used to help read ANALYZE data.
  59332. */
  59333. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  59334. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  59335. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  59336. };
  59337. int i;
  59338. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  59339. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  59340. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  59341. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  59342. }
  59343. }
  59344. /*
  59345. ** This function is used to allocate and populate UnpackedRecord
  59346. ** structures intended to be compared against sample index keys stored
  59347. ** in the sqlite_stat4 table.
  59348. **
  59349. ** A single call to this function attempts to populates field iVal (leftmost
  59350. ** is 0 etc.) of the unpacked record with a value extracted from expression
  59351. ** pExpr. Extraction of values is possible if:
  59352. **
  59353. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  59354. **
  59355. ** * The expression is a bound variable, and this is a reprepare, or
  59356. **
  59357. ** * The sqlite3ValueFromExpr() function is able to extract a value
  59358. ** from the expression (i.e. the expression is a literal value).
  59359. **
  59360. ** If a value can be extracted, the affinity passed as the 5th argument
  59361. ** is applied to it before it is copied into the UnpackedRecord. Output
  59362. ** parameter *pbOk is set to true if a value is extracted, or false
  59363. ** otherwise.
  59364. **
  59365. ** When this function is called, *ppRec must either point to an object
  59366. ** allocated by an earlier call to this function, or must be NULL. If it
  59367. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  59368. ** is allocated (and *ppRec set to point to it) before returning.
  59369. **
  59370. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  59371. ** error if a value cannot be extracted from pExpr. If an error does
  59372. ** occur, an SQLite error code is returned.
  59373. */
  59374. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  59375. Parse *pParse, /* Parse context */
  59376. Index *pIdx, /* Index being probed */
  59377. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  59378. Expr *pExpr, /* The expression to extract a value from */
  59379. u8 affinity, /* Affinity to use */
  59380. int iVal, /* Array element to populate */
  59381. int *pbOk /* OUT: True if value was extracted */
  59382. ){
  59383. int rc = SQLITE_OK;
  59384. sqlite3_value *pVal = 0;
  59385. sqlite3 *db = pParse->db;
  59386. struct ValueNewStat4Ctx alloc;
  59387. alloc.pParse = pParse;
  59388. alloc.pIdx = pIdx;
  59389. alloc.ppRec = ppRec;
  59390. alloc.iVal = iVal;
  59391. /* Skip over any TK_COLLATE nodes */
  59392. pExpr = sqlite3ExprSkipCollate(pExpr);
  59393. if( !pExpr ){
  59394. pVal = valueNew(db, &alloc);
  59395. if( pVal ){
  59396. sqlite3VdbeMemSetNull((Mem*)pVal);
  59397. *pbOk = 1;
  59398. }
  59399. }else if( pExpr->op==TK_VARIABLE
  59400. || (pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  59401. ){
  59402. Vdbe *v;
  59403. int iBindVar = pExpr->iColumn;
  59404. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  59405. if( (v = pParse->pReprepare)!=0 ){
  59406. pVal = valueNew(db, &alloc);
  59407. if( pVal ){
  59408. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  59409. if( rc==SQLITE_OK ){
  59410. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  59411. }
  59412. pVal->db = pParse->db;
  59413. *pbOk = 1;
  59414. sqlite3VdbeMemStoreType((Mem*)pVal);
  59415. }
  59416. }else{
  59417. *pbOk = 0;
  59418. }
  59419. }else{
  59420. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, &alloc);
  59421. *pbOk = (pVal!=0);
  59422. }
  59423. assert( pVal==0 || pVal->db==db );
  59424. return rc;
  59425. }
  59426. /*
  59427. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  59428. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  59429. ** the object.
  59430. */
  59431. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  59432. if( pRec ){
  59433. int i;
  59434. int nCol = pRec->pKeyInfo->nField+1;
  59435. Mem *aMem = pRec->aMem;
  59436. sqlite3 *db = aMem[0].db;
  59437. for(i=0; i<nCol; i++){
  59438. sqlite3DbFree(db, aMem[i].zMalloc);
  59439. }
  59440. sqlite3DbFree(db, pRec->pKeyInfo);
  59441. sqlite3DbFree(db, pRec);
  59442. }
  59443. }
  59444. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  59445. /*
  59446. ** Change the string value of an sqlite3_value object
  59447. */
  59448. SQLITE_PRIVATE void sqlite3ValueSetStr(
  59449. sqlite3_value *v, /* Value to be set */
  59450. int n, /* Length of string z */
  59451. const void *z, /* Text of the new string */
  59452. u8 enc, /* Encoding to use */
  59453. void (*xDel)(void*) /* Destructor for the string */
  59454. ){
  59455. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  59456. }
  59457. /*
  59458. ** Free an sqlite3_value object
  59459. */
  59460. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  59461. if( !v ) return;
  59462. sqlite3VdbeMemRelease((Mem *)v);
  59463. sqlite3DbFree(((Mem*)v)->db, v);
  59464. }
  59465. /*
  59466. ** Return the number of bytes in the sqlite3_value object assuming
  59467. ** that it uses the encoding "enc"
  59468. */
  59469. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  59470. Mem *p = (Mem*)pVal;
  59471. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  59472. if( p->flags & MEM_Zero ){
  59473. return p->n + p->u.nZero;
  59474. }else{
  59475. return p->n;
  59476. }
  59477. }
  59478. return 0;
  59479. }
  59480. /************** End of vdbemem.c *********************************************/
  59481. /************** Begin file vdbeaux.c *****************************************/
  59482. /*
  59483. ** 2003 September 6
  59484. **
  59485. ** The author disclaims copyright to this source code. In place of
  59486. ** a legal notice, here is a blessing:
  59487. **
  59488. ** May you do good and not evil.
  59489. ** May you find forgiveness for yourself and forgive others.
  59490. ** May you share freely, never taking more than you give.
  59491. **
  59492. *************************************************************************
  59493. ** This file contains code used for creating, destroying, and populating
  59494. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) Prior
  59495. ** to version 2.8.7, all this code was combined into the vdbe.c source file.
  59496. ** But that file was getting too big so this subroutines were split out.
  59497. */
  59498. /*
  59499. ** Create a new virtual database engine.
  59500. */
  59501. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
  59502. Vdbe *p;
  59503. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  59504. if( p==0 ) return 0;
  59505. p->db = db;
  59506. if( db->pVdbe ){
  59507. db->pVdbe->pPrev = p;
  59508. }
  59509. p->pNext = db->pVdbe;
  59510. p->pPrev = 0;
  59511. db->pVdbe = p;
  59512. p->magic = VDBE_MAGIC_INIT;
  59513. return p;
  59514. }
  59515. /*
  59516. ** Remember the SQL string for a prepared statement.
  59517. */
  59518. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  59519. assert( isPrepareV2==1 || isPrepareV2==0 );
  59520. if( p==0 ) return;
  59521. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  59522. if( !isPrepareV2 ) return;
  59523. #endif
  59524. assert( p->zSql==0 );
  59525. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  59526. p->isPrepareV2 = (u8)isPrepareV2;
  59527. }
  59528. /*
  59529. ** Return the SQL associated with a prepared statement
  59530. */
  59531. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  59532. Vdbe *p = (Vdbe *)pStmt;
  59533. return (p && p->isPrepareV2) ? p->zSql : 0;
  59534. }
  59535. /*
  59536. ** Swap all content between two VDBE structures.
  59537. */
  59538. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  59539. Vdbe tmp, *pTmp;
  59540. char *zTmp;
  59541. tmp = *pA;
  59542. *pA = *pB;
  59543. *pB = tmp;
  59544. pTmp = pA->pNext;
  59545. pA->pNext = pB->pNext;
  59546. pB->pNext = pTmp;
  59547. pTmp = pA->pPrev;
  59548. pA->pPrev = pB->pPrev;
  59549. pB->pPrev = pTmp;
  59550. zTmp = pA->zSql;
  59551. pA->zSql = pB->zSql;
  59552. pB->zSql = zTmp;
  59553. pB->isPrepareV2 = pA->isPrepareV2;
  59554. }
  59555. #ifdef SQLITE_DEBUG
  59556. /*
  59557. ** Turn tracing on or off
  59558. */
  59559. SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
  59560. p->trace = trace;
  59561. }
  59562. #endif
  59563. /*
  59564. ** Resize the Vdbe.aOp array so that it is at least one op larger than
  59565. ** it was.
  59566. **
  59567. ** If an out-of-memory error occurs while resizing the array, return
  59568. ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain
  59569. ** unchanged (this is so that any opcodes already allocated can be
  59570. ** correctly deallocated along with the rest of the Vdbe).
  59571. */
  59572. static int growOpArray(Vdbe *p){
  59573. VdbeOp *pNew;
  59574. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  59575. pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
  59576. if( pNew ){
  59577. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  59578. p->aOp = pNew;
  59579. }
  59580. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  59581. }
  59582. /*
  59583. ** Add a new instruction to the list of instructions current in the
  59584. ** VDBE. Return the address of the new instruction.
  59585. **
  59586. ** Parameters:
  59587. **
  59588. ** p Pointer to the VDBE
  59589. **
  59590. ** op The opcode for this instruction
  59591. **
  59592. ** p1, p2, p3 Operands
  59593. **
  59594. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  59595. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  59596. ** operand.
  59597. */
  59598. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  59599. int i;
  59600. VdbeOp *pOp;
  59601. i = p->nOp;
  59602. assert( p->magic==VDBE_MAGIC_INIT );
  59603. assert( op>0 && op<0xff );
  59604. if( p->nOpAlloc<=i ){
  59605. if( growOpArray(p) ){
  59606. return 1;
  59607. }
  59608. }
  59609. p->nOp++;
  59610. pOp = &p->aOp[i];
  59611. pOp->opcode = (u8)op;
  59612. pOp->p5 = 0;
  59613. pOp->p1 = p1;
  59614. pOp->p2 = p2;
  59615. pOp->p3 = p3;
  59616. pOp->p4.p = 0;
  59617. pOp->p4type = P4_NOTUSED;
  59618. #ifdef SQLITE_DEBUG
  59619. pOp->zComment = 0;
  59620. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59621. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  59622. }
  59623. #endif
  59624. #ifdef VDBE_PROFILE
  59625. pOp->cycles = 0;
  59626. pOp->cnt = 0;
  59627. #endif
  59628. return i;
  59629. }
  59630. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  59631. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  59632. }
  59633. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  59634. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  59635. }
  59636. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  59637. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  59638. }
  59639. /*
  59640. ** Add an opcode that includes the p4 value as a pointer.
  59641. */
  59642. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  59643. Vdbe *p, /* Add the opcode to this VM */
  59644. int op, /* The new opcode */
  59645. int p1, /* The P1 operand */
  59646. int p2, /* The P2 operand */
  59647. int p3, /* The P3 operand */
  59648. const char *zP4, /* The P4 operand */
  59649. int p4type /* P4 operand type */
  59650. ){
  59651. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59652. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  59653. return addr;
  59654. }
  59655. /*
  59656. ** Add an OP_ParseSchema opcode. This routine is broken out from
  59657. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  59658. ** as having been used.
  59659. **
  59660. ** The zWhere string must have been obtained from sqlite3_malloc().
  59661. ** This routine will take ownership of the allocated memory.
  59662. */
  59663. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  59664. int j;
  59665. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  59666. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  59667. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  59668. }
  59669. /*
  59670. ** Add an opcode that includes the p4 value as an integer.
  59671. */
  59672. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  59673. Vdbe *p, /* Add the opcode to this VM */
  59674. int op, /* The new opcode */
  59675. int p1, /* The P1 operand */
  59676. int p2, /* The P2 operand */
  59677. int p3, /* The P3 operand */
  59678. int p4 /* The P4 operand as an integer */
  59679. ){
  59680. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59681. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  59682. return addr;
  59683. }
  59684. /*
  59685. ** Create a new symbolic label for an instruction that has yet to be
  59686. ** coded. The symbolic label is really just a negative number. The
  59687. ** label can be used as the P2 value of an operation. Later, when
  59688. ** the label is resolved to a specific address, the VDBE will scan
  59689. ** through its operation list and change all values of P2 which match
  59690. ** the label into the resolved address.
  59691. **
  59692. ** The VDBE knows that a P2 value is a label because labels are
  59693. ** always negative and P2 values are suppose to be non-negative.
  59694. ** Hence, a negative P2 value is a label that has yet to be resolved.
  59695. **
  59696. ** Zero is returned if a malloc() fails.
  59697. */
  59698. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
  59699. int i = p->nLabel++;
  59700. assert( p->magic==VDBE_MAGIC_INIT );
  59701. if( (i & (i-1))==0 ){
  59702. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  59703. (i*2+1)*sizeof(p->aLabel[0]));
  59704. }
  59705. if( p->aLabel ){
  59706. p->aLabel[i] = -1;
  59707. }
  59708. return -1-i;
  59709. }
  59710. /*
  59711. ** Resolve label "x" to be the address of the next instruction to
  59712. ** be inserted. The parameter "x" must have been obtained from
  59713. ** a prior call to sqlite3VdbeMakeLabel().
  59714. */
  59715. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
  59716. int j = -1-x;
  59717. assert( p->magic==VDBE_MAGIC_INIT );
  59718. assert( j<p->nLabel );
  59719. if( j>=0 && p->aLabel ){
  59720. p->aLabel[j] = p->nOp;
  59721. }
  59722. }
  59723. /*
  59724. ** Mark the VDBE as one that can only be run one time.
  59725. */
  59726. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  59727. p->runOnlyOnce = 1;
  59728. }
  59729. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  59730. /*
  59731. ** The following type and function are used to iterate through all opcodes
  59732. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  59733. ** invoke directly or indirectly. It should be used as follows:
  59734. **
  59735. ** Op *pOp;
  59736. ** VdbeOpIter sIter;
  59737. **
  59738. ** memset(&sIter, 0, sizeof(sIter));
  59739. ** sIter.v = v; // v is of type Vdbe*
  59740. ** while( (pOp = opIterNext(&sIter)) ){
  59741. ** // Do something with pOp
  59742. ** }
  59743. ** sqlite3DbFree(v->db, sIter.apSub);
  59744. **
  59745. */
  59746. typedef struct VdbeOpIter VdbeOpIter;
  59747. struct VdbeOpIter {
  59748. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  59749. SubProgram **apSub; /* Array of subprograms */
  59750. int nSub; /* Number of entries in apSub */
  59751. int iAddr; /* Address of next instruction to return */
  59752. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  59753. };
  59754. static Op *opIterNext(VdbeOpIter *p){
  59755. Vdbe *v = p->v;
  59756. Op *pRet = 0;
  59757. Op *aOp;
  59758. int nOp;
  59759. if( p->iSub<=p->nSub ){
  59760. if( p->iSub==0 ){
  59761. aOp = v->aOp;
  59762. nOp = v->nOp;
  59763. }else{
  59764. aOp = p->apSub[p->iSub-1]->aOp;
  59765. nOp = p->apSub[p->iSub-1]->nOp;
  59766. }
  59767. assert( p->iAddr<nOp );
  59768. pRet = &aOp[p->iAddr];
  59769. p->iAddr++;
  59770. if( p->iAddr==nOp ){
  59771. p->iSub++;
  59772. p->iAddr = 0;
  59773. }
  59774. if( pRet->p4type==P4_SUBPROGRAM ){
  59775. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  59776. int j;
  59777. for(j=0; j<p->nSub; j++){
  59778. if( p->apSub[j]==pRet->p4.pProgram ) break;
  59779. }
  59780. if( j==p->nSub ){
  59781. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  59782. if( !p->apSub ){
  59783. pRet = 0;
  59784. }else{
  59785. p->apSub[p->nSub++] = pRet->p4.pProgram;
  59786. }
  59787. }
  59788. }
  59789. }
  59790. return pRet;
  59791. }
  59792. /*
  59793. ** Check if the program stored in the VM associated with pParse may
  59794. ** throw an ABORT exception (causing the statement, but not entire transaction
  59795. ** to be rolled back). This condition is true if the main program or any
  59796. ** sub-programs contains any of the following:
  59797. **
  59798. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59799. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59800. ** * OP_Destroy
  59801. ** * OP_VUpdate
  59802. ** * OP_VRename
  59803. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  59804. **
  59805. ** Then check that the value of Parse.mayAbort is true if an
  59806. ** ABORT may be thrown, or false otherwise. Return true if it does
  59807. ** match, or false otherwise. This function is intended to be used as
  59808. ** part of an assert statement in the compiler. Similar to:
  59809. **
  59810. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  59811. */
  59812. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  59813. int hasAbort = 0;
  59814. Op *pOp;
  59815. VdbeOpIter sIter;
  59816. memset(&sIter, 0, sizeof(sIter));
  59817. sIter.v = v;
  59818. while( (pOp = opIterNext(&sIter))!=0 ){
  59819. int opcode = pOp->opcode;
  59820. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  59821. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59822. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  59823. #endif
  59824. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  59825. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  59826. ){
  59827. hasAbort = 1;
  59828. break;
  59829. }
  59830. }
  59831. sqlite3DbFree(v->db, sIter.apSub);
  59832. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  59833. ** If malloc failed, then the while() loop above may not have iterated
  59834. ** through all opcodes and hasAbort may be set incorrectly. Return
  59835. ** true for this case to prevent the assert() in the callers frame
  59836. ** from failing. */
  59837. return ( v->db->mallocFailed || hasAbort==mayAbort );
  59838. }
  59839. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  59840. /*
  59841. ** Loop through the program looking for P2 values that are negative
  59842. ** on jump instructions. Each such value is a label. Resolve the
  59843. ** label by setting the P2 value to its correct non-zero value.
  59844. **
  59845. ** This routine is called once after all opcodes have been inserted.
  59846. **
  59847. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  59848. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  59849. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  59850. **
  59851. ** The Op.opflags field is set on all opcodes.
  59852. */
  59853. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  59854. int i;
  59855. int nMaxArgs = *pMaxFuncArgs;
  59856. Op *pOp;
  59857. int *aLabel = p->aLabel;
  59858. p->readOnly = 1;
  59859. p->bIsReader = 0;
  59860. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  59861. u8 opcode = pOp->opcode;
  59862. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  59863. ** cases from this switch! */
  59864. switch( opcode ){
  59865. case OP_Function:
  59866. case OP_AggStep: {
  59867. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  59868. break;
  59869. }
  59870. case OP_Transaction: {
  59871. if( pOp->p2!=0 ) p->readOnly = 0;
  59872. /* fall thru */
  59873. }
  59874. case OP_AutoCommit:
  59875. case OP_Savepoint: {
  59876. p->bIsReader = 1;
  59877. break;
  59878. }
  59879. #ifndef SQLITE_OMIT_WAL
  59880. case OP_Checkpoint:
  59881. #endif
  59882. case OP_Vacuum:
  59883. case OP_JournalMode: {
  59884. p->readOnly = 0;
  59885. p->bIsReader = 1;
  59886. break;
  59887. }
  59888. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59889. case OP_VUpdate: {
  59890. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  59891. break;
  59892. }
  59893. case OP_VFilter: {
  59894. int n;
  59895. assert( p->nOp - i >= 3 );
  59896. assert( pOp[-1].opcode==OP_Integer );
  59897. n = pOp[-1].p1;
  59898. if( n>nMaxArgs ) nMaxArgs = n;
  59899. break;
  59900. }
  59901. #endif
  59902. case OP_Next:
  59903. case OP_SorterNext: {
  59904. pOp->p4.xAdvance = sqlite3BtreeNext;
  59905. pOp->p4type = P4_ADVANCE;
  59906. break;
  59907. }
  59908. case OP_Prev: {
  59909. pOp->p4.xAdvance = sqlite3BtreePrevious;
  59910. pOp->p4type = P4_ADVANCE;
  59911. break;
  59912. }
  59913. }
  59914. pOp->opflags = sqlite3OpcodeProperty[opcode];
  59915. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  59916. assert( -1-pOp->p2<p->nLabel );
  59917. pOp->p2 = aLabel[-1-pOp->p2];
  59918. }
  59919. }
  59920. sqlite3DbFree(p->db, p->aLabel);
  59921. p->aLabel = 0;
  59922. *pMaxFuncArgs = nMaxArgs;
  59923. assert( p->bIsReader!=0 || p->btreeMask==0 );
  59924. }
  59925. /*
  59926. ** Return the address of the next instruction to be inserted.
  59927. */
  59928. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  59929. assert( p->magic==VDBE_MAGIC_INIT );
  59930. return p->nOp;
  59931. }
  59932. /*
  59933. ** This function returns a pointer to the array of opcodes associated with
  59934. ** the Vdbe passed as the first argument. It is the callers responsibility
  59935. ** to arrange for the returned array to be eventually freed using the
  59936. ** vdbeFreeOpArray() function.
  59937. **
  59938. ** Before returning, *pnOp is set to the number of entries in the returned
  59939. ** array. Also, *pnMaxArg is set to the larger of its current value and
  59940. ** the number of entries in the Vdbe.apArg[] array required to execute the
  59941. ** returned program.
  59942. */
  59943. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  59944. VdbeOp *aOp = p->aOp;
  59945. assert( aOp && !p->db->mallocFailed );
  59946. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  59947. assert( p->btreeMask==0 );
  59948. resolveP2Values(p, pnMaxArg);
  59949. *pnOp = p->nOp;
  59950. p->aOp = 0;
  59951. return aOp;
  59952. }
  59953. /*
  59954. ** Add a whole list of operations to the operation stack. Return the
  59955. ** address of the first operation added.
  59956. */
  59957. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  59958. int addr;
  59959. assert( p->magic==VDBE_MAGIC_INIT );
  59960. if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
  59961. return 0;
  59962. }
  59963. addr = p->nOp;
  59964. if( ALWAYS(nOp>0) ){
  59965. int i;
  59966. VdbeOpList const *pIn = aOp;
  59967. for(i=0; i<nOp; i++, pIn++){
  59968. int p2 = pIn->p2;
  59969. VdbeOp *pOut = &p->aOp[i+addr];
  59970. pOut->opcode = pIn->opcode;
  59971. pOut->p1 = pIn->p1;
  59972. if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
  59973. pOut->p2 = addr + ADDR(p2);
  59974. }else{
  59975. pOut->p2 = p2;
  59976. }
  59977. pOut->p3 = pIn->p3;
  59978. pOut->p4type = P4_NOTUSED;
  59979. pOut->p4.p = 0;
  59980. pOut->p5 = 0;
  59981. #ifdef SQLITE_DEBUG
  59982. pOut->zComment = 0;
  59983. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59984. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  59985. }
  59986. #endif
  59987. }
  59988. p->nOp += nOp;
  59989. }
  59990. return addr;
  59991. }
  59992. /*
  59993. ** Change the value of the P1 operand for a specific instruction.
  59994. ** This routine is useful when a large program is loaded from a
  59995. ** static array using sqlite3VdbeAddOpList but we want to make a
  59996. ** few minor changes to the program.
  59997. */
  59998. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  59999. assert( p!=0 );
  60000. if( ((u32)p->nOp)>addr ){
  60001. p->aOp[addr].p1 = val;
  60002. }
  60003. }
  60004. /*
  60005. ** Change the value of the P2 operand for a specific instruction.
  60006. ** This routine is useful for setting a jump destination.
  60007. */
  60008. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  60009. assert( p!=0 );
  60010. if( ((u32)p->nOp)>addr ){
  60011. p->aOp[addr].p2 = val;
  60012. }
  60013. }
  60014. /*
  60015. ** Change the value of the P3 operand for a specific instruction.
  60016. */
  60017. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  60018. assert( p!=0 );
  60019. if( ((u32)p->nOp)>addr ){
  60020. p->aOp[addr].p3 = val;
  60021. }
  60022. }
  60023. /*
  60024. ** Change the value of the P5 operand for the most recently
  60025. ** added operation.
  60026. */
  60027. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  60028. assert( p!=0 );
  60029. if( p->aOp ){
  60030. assert( p->nOp>0 );
  60031. p->aOp[p->nOp-1].p5 = val;
  60032. }
  60033. }
  60034. /*
  60035. ** Change the P2 operand of instruction addr so that it points to
  60036. ** the address of the next instruction to be coded.
  60037. */
  60038. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  60039. if( ALWAYS(addr>=0) ) sqlite3VdbeChangeP2(p, addr, p->nOp);
  60040. }
  60041. /*
  60042. ** If the input FuncDef structure is ephemeral, then free it. If
  60043. ** the FuncDef is not ephermal, then do nothing.
  60044. */
  60045. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  60046. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  60047. sqlite3DbFree(db, pDef);
  60048. }
  60049. }
  60050. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  60051. /*
  60052. ** Delete a P4 value if necessary.
  60053. */
  60054. static void freeP4(sqlite3 *db, int p4type, void *p4){
  60055. if( p4 ){
  60056. assert( db );
  60057. switch( p4type ){
  60058. case P4_REAL:
  60059. case P4_INT64:
  60060. case P4_DYNAMIC:
  60061. case P4_KEYINFO:
  60062. case P4_INTARRAY:
  60063. case P4_KEYINFO_HANDOFF: {
  60064. sqlite3DbFree(db, p4);
  60065. break;
  60066. }
  60067. case P4_MPRINTF: {
  60068. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  60069. break;
  60070. }
  60071. case P4_FUNCDEF: {
  60072. freeEphemeralFunction(db, (FuncDef*)p4);
  60073. break;
  60074. }
  60075. case P4_MEM: {
  60076. if( db->pnBytesFreed==0 ){
  60077. sqlite3ValueFree((sqlite3_value*)p4);
  60078. }else{
  60079. Mem *p = (Mem*)p4;
  60080. sqlite3DbFree(db, p->zMalloc);
  60081. sqlite3DbFree(db, p);
  60082. }
  60083. break;
  60084. }
  60085. case P4_VTAB : {
  60086. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  60087. break;
  60088. }
  60089. }
  60090. }
  60091. }
  60092. /*
  60093. ** Free the space allocated for aOp and any p4 values allocated for the
  60094. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  60095. ** nOp entries.
  60096. */
  60097. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  60098. if( aOp ){
  60099. Op *pOp;
  60100. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  60101. freeP4(db, pOp->p4type, pOp->p4.p);
  60102. #ifdef SQLITE_DEBUG
  60103. sqlite3DbFree(db, pOp->zComment);
  60104. #endif
  60105. }
  60106. }
  60107. sqlite3DbFree(db, aOp);
  60108. }
  60109. /*
  60110. ** Link the SubProgram object passed as the second argument into the linked
  60111. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  60112. ** objects when the VM is no longer required.
  60113. */
  60114. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  60115. p->pNext = pVdbe->pProgram;
  60116. pVdbe->pProgram = p;
  60117. }
  60118. /*
  60119. ** Change the opcode at addr into OP_Noop
  60120. */
  60121. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  60122. if( p->aOp ){
  60123. VdbeOp *pOp = &p->aOp[addr];
  60124. sqlite3 *db = p->db;
  60125. freeP4(db, pOp->p4type, pOp->p4.p);
  60126. memset(pOp, 0, sizeof(pOp[0]));
  60127. pOp->opcode = OP_Noop;
  60128. }
  60129. }
  60130. /*
  60131. ** Change the value of the P4 operand for a specific instruction.
  60132. ** This routine is useful when a large program is loaded from a
  60133. ** static array using sqlite3VdbeAddOpList but we want to make a
  60134. ** few minor changes to the program.
  60135. **
  60136. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  60137. ** the string is made into memory obtained from sqlite3_malloc().
  60138. ** A value of n==0 means copy bytes of zP4 up to and including the
  60139. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  60140. **
  60141. ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
  60142. ** A copy is made of the KeyInfo structure into memory obtained from
  60143. ** sqlite3_malloc, to be freed when the Vdbe is finalized.
  60144. ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
  60145. ** stored in memory that the caller has obtained from sqlite3_malloc. The
  60146. ** caller should not free the allocation, it will be freed when the Vdbe is
  60147. ** finalized.
  60148. **
  60149. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  60150. ** to a string or structure that is guaranteed to exist for the lifetime of
  60151. ** the Vdbe. In these cases we can just copy the pointer.
  60152. **
  60153. ** If addr<0 then change P4 on the most recently inserted instruction.
  60154. */
  60155. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  60156. Op *pOp;
  60157. sqlite3 *db;
  60158. assert( p!=0 );
  60159. db = p->db;
  60160. assert( p->magic==VDBE_MAGIC_INIT );
  60161. if( p->aOp==0 || db->mallocFailed ){
  60162. if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
  60163. freeP4(db, n, (void*)*(char**)&zP4);
  60164. }
  60165. return;
  60166. }
  60167. assert( p->nOp>0 );
  60168. assert( addr<p->nOp );
  60169. if( addr<0 ){
  60170. addr = p->nOp - 1;
  60171. }
  60172. pOp = &p->aOp[addr];
  60173. assert( pOp->p4type==P4_NOTUSED || pOp->p4type==P4_INT32 );
  60174. freeP4(db, pOp->p4type, pOp->p4.p);
  60175. pOp->p4.p = 0;
  60176. if( n==P4_INT32 ){
  60177. /* Note: this cast is safe, because the origin data point was an int
  60178. ** that was cast to a (const char *). */
  60179. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  60180. pOp->p4type = P4_INT32;
  60181. }else if( zP4==0 ){
  60182. pOp->p4.p = 0;
  60183. pOp->p4type = P4_NOTUSED;
  60184. }else if( n==P4_KEYINFO ){
  60185. KeyInfo *pOrig, *pNew;
  60186. pOrig = (KeyInfo*)zP4;
  60187. pOp->p4.pKeyInfo = pNew = sqlite3KeyInfoAlloc(db, pOrig->nField);
  60188. if( pNew ){
  60189. memcpy(pNew->aColl, pOrig->aColl, pOrig->nField*sizeof(pNew->aColl[0]));
  60190. memcpy(pNew->aSortOrder, pOrig->aSortOrder, pOrig->nField);
  60191. pOp->p4type = P4_KEYINFO;
  60192. }else{
  60193. p->db->mallocFailed = 1;
  60194. pOp->p4type = P4_NOTUSED;
  60195. }
  60196. }else if( n==P4_KEYINFO_HANDOFF ){
  60197. pOp->p4.p = (void*)zP4;
  60198. pOp->p4type = P4_KEYINFO;
  60199. }else if( n==P4_VTAB ){
  60200. pOp->p4.p = (void*)zP4;
  60201. pOp->p4type = P4_VTAB;
  60202. sqlite3VtabLock((VTable *)zP4);
  60203. assert( ((VTable *)zP4)->db==p->db );
  60204. }else if( n<0 ){
  60205. pOp->p4.p = (void*)zP4;
  60206. pOp->p4type = (signed char)n;
  60207. }else{
  60208. if( n==0 ) n = sqlite3Strlen30(zP4);
  60209. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  60210. pOp->p4type = P4_DYNAMIC;
  60211. }
  60212. }
  60213. #ifndef NDEBUG
  60214. /*
  60215. ** Change the comment on the most recently coded instruction. Or
  60216. ** insert a No-op and add the comment to that new instruction. This
  60217. ** makes the code easier to read during debugging. None of this happens
  60218. ** in a production build.
  60219. */
  60220. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  60221. assert( p->nOp>0 || p->aOp==0 );
  60222. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  60223. if( p->nOp ){
  60224. assert( p->aOp );
  60225. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  60226. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  60227. }
  60228. }
  60229. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  60230. va_list ap;
  60231. if( p ){
  60232. va_start(ap, zFormat);
  60233. vdbeVComment(p, zFormat, ap);
  60234. va_end(ap);
  60235. }
  60236. }
  60237. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  60238. va_list ap;
  60239. if( p ){
  60240. sqlite3VdbeAddOp0(p, OP_Noop);
  60241. va_start(ap, zFormat);
  60242. vdbeVComment(p, zFormat, ap);
  60243. va_end(ap);
  60244. }
  60245. }
  60246. #endif /* NDEBUG */
  60247. /*
  60248. ** Return the opcode for a given address. If the address is -1, then
  60249. ** return the most recently inserted opcode.
  60250. **
  60251. ** If a memory allocation error has occurred prior to the calling of this
  60252. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  60253. ** is readable but not writable, though it is cast to a writable value.
  60254. ** The return of a dummy opcode allows the call to continue functioning
  60255. ** after a OOM fault without having to check to see if the return from
  60256. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  60257. ** dummy will never be written to. This is verified by code inspection and
  60258. ** by running with Valgrind.
  60259. **
  60260. ** About the #ifdef SQLITE_OMIT_TRACE: Normally, this routine is never called
  60261. ** unless p->nOp>0. This is because in the absense of SQLITE_OMIT_TRACE,
  60262. ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
  60263. ** a new VDBE is created. So we are free to set addr to p->nOp-1 without
  60264. ** having to double-check to make sure that the result is non-negative. But
  60265. ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
  60266. ** check the value of p->nOp-1 before continuing.
  60267. */
  60268. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  60269. /* C89 specifies that the constant "dummy" will be initialized to all
  60270. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  60271. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  60272. assert( p->magic==VDBE_MAGIC_INIT );
  60273. if( addr<0 ){
  60274. #ifdef SQLITE_OMIT_TRACE
  60275. if( p->nOp==0 ) return (VdbeOp*)&dummy;
  60276. #endif
  60277. addr = p->nOp - 1;
  60278. }
  60279. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  60280. if( p->db->mallocFailed ){
  60281. return (VdbeOp*)&dummy;
  60282. }else{
  60283. return &p->aOp[addr];
  60284. }
  60285. }
  60286. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  60287. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60288. /*
  60289. ** Compute a string that describes the P4 parameter for an opcode.
  60290. ** Use zTemp for any required temporary buffer space.
  60291. */
  60292. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  60293. char *zP4 = zTemp;
  60294. assert( nTemp>=20 );
  60295. switch( pOp->p4type ){
  60296. case P4_KEYINFO_STATIC:
  60297. case P4_KEYINFO: {
  60298. int i, j;
  60299. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  60300. assert( pKeyInfo->aSortOrder!=0 );
  60301. sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
  60302. i = sqlite3Strlen30(zTemp);
  60303. for(j=0; j<pKeyInfo->nField; j++){
  60304. CollSeq *pColl = pKeyInfo->aColl[j];
  60305. const char *zColl = pColl ? pColl->zName : "nil";
  60306. int n = sqlite3Strlen30(zColl);
  60307. if( i+n>nTemp-6 ){
  60308. memcpy(&zTemp[i],",...",4);
  60309. break;
  60310. }
  60311. zTemp[i++] = ',';
  60312. if( pKeyInfo->aSortOrder[j] ){
  60313. zTemp[i++] = '-';
  60314. }
  60315. memcpy(&zTemp[i], zColl, n+1);
  60316. i += n;
  60317. }
  60318. zTemp[i++] = ')';
  60319. zTemp[i] = 0;
  60320. assert( i<nTemp );
  60321. break;
  60322. }
  60323. case P4_COLLSEQ: {
  60324. CollSeq *pColl = pOp->p4.pColl;
  60325. sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
  60326. break;
  60327. }
  60328. case P4_FUNCDEF: {
  60329. FuncDef *pDef = pOp->p4.pFunc;
  60330. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  60331. break;
  60332. }
  60333. case P4_INT64: {
  60334. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  60335. break;
  60336. }
  60337. case P4_INT32: {
  60338. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  60339. break;
  60340. }
  60341. case P4_REAL: {
  60342. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  60343. break;
  60344. }
  60345. case P4_MEM: {
  60346. Mem *pMem = pOp->p4.pMem;
  60347. if( pMem->flags & MEM_Str ){
  60348. zP4 = pMem->z;
  60349. }else if( pMem->flags & MEM_Int ){
  60350. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  60351. }else if( pMem->flags & MEM_Real ){
  60352. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
  60353. }else if( pMem->flags & MEM_Null ){
  60354. sqlite3_snprintf(nTemp, zTemp, "NULL");
  60355. }else{
  60356. assert( pMem->flags & MEM_Blob );
  60357. zP4 = "(blob)";
  60358. }
  60359. break;
  60360. }
  60361. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60362. case P4_VTAB: {
  60363. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  60364. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  60365. break;
  60366. }
  60367. #endif
  60368. case P4_INTARRAY: {
  60369. sqlite3_snprintf(nTemp, zTemp, "intarray");
  60370. break;
  60371. }
  60372. case P4_SUBPROGRAM: {
  60373. sqlite3_snprintf(nTemp, zTemp, "program");
  60374. break;
  60375. }
  60376. case P4_ADVANCE: {
  60377. zTemp[0] = 0;
  60378. break;
  60379. }
  60380. default: {
  60381. zP4 = pOp->p4.z;
  60382. if( zP4==0 ){
  60383. zP4 = zTemp;
  60384. zTemp[0] = 0;
  60385. }
  60386. }
  60387. }
  60388. assert( zP4!=0 );
  60389. return zP4;
  60390. }
  60391. #endif
  60392. /*
  60393. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  60394. **
  60395. ** The prepared statements need to know in advance the complete set of
  60396. ** attached databases that will be use. A mask of these databases
  60397. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  60398. ** p->btreeMask of databases that will require a lock.
  60399. */
  60400. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  60401. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  60402. assert( i<(int)sizeof(p->btreeMask)*8 );
  60403. p->btreeMask |= ((yDbMask)1)<<i;
  60404. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  60405. p->lockMask |= ((yDbMask)1)<<i;
  60406. }
  60407. }
  60408. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60409. /*
  60410. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  60411. ** this routine obtains the mutex associated with each BtShared structure
  60412. ** that may be accessed by the VM passed as an argument. In doing so it also
  60413. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  60414. ** that the correct busy-handler callback is invoked if required.
  60415. **
  60416. ** If SQLite is not threadsafe but does support shared-cache mode, then
  60417. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  60418. ** of all of BtShared structures accessible via the database handle
  60419. ** associated with the VM.
  60420. **
  60421. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  60422. ** function is a no-op.
  60423. **
  60424. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  60425. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  60426. ** corresponding to btrees that use shared cache. Then the runtime of
  60427. ** this routine is N*N. But as N is rarely more than 1, this should not
  60428. ** be a problem.
  60429. */
  60430. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  60431. int i;
  60432. yDbMask mask;
  60433. sqlite3 *db;
  60434. Db *aDb;
  60435. int nDb;
  60436. if( p->lockMask==0 ) return; /* The common case */
  60437. db = p->db;
  60438. aDb = db->aDb;
  60439. nDb = db->nDb;
  60440. for(i=0, mask=1; i<nDb; i++, mask += mask){
  60441. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  60442. sqlite3BtreeEnter(aDb[i].pBt);
  60443. }
  60444. }
  60445. }
  60446. #endif
  60447. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60448. /*
  60449. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  60450. */
  60451. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  60452. int i;
  60453. yDbMask mask;
  60454. sqlite3 *db;
  60455. Db *aDb;
  60456. int nDb;
  60457. if( p->lockMask==0 ) return; /* The common case */
  60458. db = p->db;
  60459. aDb = db->aDb;
  60460. nDb = db->nDb;
  60461. for(i=0, mask=1; i<nDb; i++, mask += mask){
  60462. if( i!=1 && (mask & p->lockMask)!=0 && ALWAYS(aDb[i].pBt!=0) ){
  60463. sqlite3BtreeLeave(aDb[i].pBt);
  60464. }
  60465. }
  60466. }
  60467. #endif
  60468. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60469. /*
  60470. ** Print a single opcode. This routine is used for debugging only.
  60471. */
  60472. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  60473. char *zP4;
  60474. char zPtr[50];
  60475. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
  60476. if( pOut==0 ) pOut = stdout;
  60477. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  60478. fprintf(pOut, zFormat1, pc,
  60479. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  60480. #ifdef SQLITE_DEBUG
  60481. pOp->zComment ? pOp->zComment : ""
  60482. #else
  60483. ""
  60484. #endif
  60485. );
  60486. fflush(pOut);
  60487. }
  60488. #endif
  60489. /*
  60490. ** Release an array of N Mem elements
  60491. */
  60492. static void releaseMemArray(Mem *p, int N){
  60493. if( p && N ){
  60494. Mem *pEnd;
  60495. sqlite3 *db = p->db;
  60496. u8 malloc_failed = db->mallocFailed;
  60497. if( db->pnBytesFreed ){
  60498. for(pEnd=&p[N]; p<pEnd; p++){
  60499. sqlite3DbFree(db, p->zMalloc);
  60500. }
  60501. return;
  60502. }
  60503. for(pEnd=&p[N]; p<pEnd; p++){
  60504. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  60505. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  60506. ** that takes advantage of the fact that the memory cell value is
  60507. ** being set to NULL after releasing any dynamic resources.
  60508. **
  60509. ** The justification for duplicating code is that according to
  60510. ** callgrind, this causes a certain test case to hit the CPU 4.7
  60511. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  60512. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  60513. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  60514. ** with no indexes using a single prepared INSERT statement, bind()
  60515. ** and reset(). Inserts are grouped into a transaction.
  60516. */
  60517. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  60518. sqlite3VdbeMemRelease(p);
  60519. }else if( p->zMalloc ){
  60520. sqlite3DbFree(db, p->zMalloc);
  60521. p->zMalloc = 0;
  60522. }
  60523. p->flags = MEM_Invalid;
  60524. }
  60525. db->mallocFailed = malloc_failed;
  60526. }
  60527. }
  60528. /*
  60529. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  60530. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  60531. */
  60532. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  60533. int i;
  60534. Mem *aMem = VdbeFrameMem(p);
  60535. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  60536. for(i=0; i<p->nChildCsr; i++){
  60537. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  60538. }
  60539. releaseMemArray(aMem, p->nChildMem);
  60540. sqlite3DbFree(p->v->db, p);
  60541. }
  60542. #ifndef SQLITE_OMIT_EXPLAIN
  60543. /*
  60544. ** Give a listing of the program in the virtual machine.
  60545. **
  60546. ** The interface is the same as sqlite3VdbeExec(). But instead of
  60547. ** running the code, it invokes the callback once for each instruction.
  60548. ** This feature is used to implement "EXPLAIN".
  60549. **
  60550. ** When p->explain==1, each instruction is listed. When
  60551. ** p->explain==2, only OP_Explain instructions are listed and these
  60552. ** are shown in a different format. p->explain==2 is used to implement
  60553. ** EXPLAIN QUERY PLAN.
  60554. **
  60555. ** When p->explain==1, first the main program is listed, then each of
  60556. ** the trigger subprograms are listed one by one.
  60557. */
  60558. SQLITE_PRIVATE int sqlite3VdbeList(
  60559. Vdbe *p /* The VDBE */
  60560. ){
  60561. int nRow; /* Stop when row count reaches this */
  60562. int nSub = 0; /* Number of sub-vdbes seen so far */
  60563. SubProgram **apSub = 0; /* Array of sub-vdbes */
  60564. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  60565. sqlite3 *db = p->db; /* The database connection */
  60566. int i; /* Loop counter */
  60567. int rc = SQLITE_OK; /* Return code */
  60568. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  60569. assert( p->explain );
  60570. assert( p->magic==VDBE_MAGIC_RUN );
  60571. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  60572. /* Even though this opcode does not use dynamic strings for
  60573. ** the result, result columns may become dynamic if the user calls
  60574. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  60575. */
  60576. releaseMemArray(pMem, 8);
  60577. p->pResultSet = 0;
  60578. if( p->rc==SQLITE_NOMEM ){
  60579. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  60580. ** sqlite3_column_text16() failed. */
  60581. db->mallocFailed = 1;
  60582. return SQLITE_ERROR;
  60583. }
  60584. /* When the number of output rows reaches nRow, that means the
  60585. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  60586. ** nRow is the sum of the number of rows in the main program, plus
  60587. ** the sum of the number of rows in all trigger subprograms encountered
  60588. ** so far. The nRow value will increase as new trigger subprograms are
  60589. ** encountered, but p->pc will eventually catch up to nRow.
  60590. */
  60591. nRow = p->nOp;
  60592. if( p->explain==1 ){
  60593. /* The first 8 memory cells are used for the result set. So we will
  60594. ** commandeer the 9th cell to use as storage for an array of pointers
  60595. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  60596. ** cells. */
  60597. assert( p->nMem>9 );
  60598. pSub = &p->aMem[9];
  60599. if( pSub->flags&MEM_Blob ){
  60600. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  60601. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  60602. nSub = pSub->n/sizeof(Vdbe*);
  60603. apSub = (SubProgram **)pSub->z;
  60604. }
  60605. for(i=0; i<nSub; i++){
  60606. nRow += apSub[i]->nOp;
  60607. }
  60608. }
  60609. do{
  60610. i = p->pc++;
  60611. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  60612. if( i>=nRow ){
  60613. p->rc = SQLITE_OK;
  60614. rc = SQLITE_DONE;
  60615. }else if( db->u1.isInterrupted ){
  60616. p->rc = SQLITE_INTERRUPT;
  60617. rc = SQLITE_ERROR;
  60618. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  60619. }else{
  60620. char *z;
  60621. Op *pOp;
  60622. if( i<p->nOp ){
  60623. /* The output line number is small enough that we are still in the
  60624. ** main program. */
  60625. pOp = &p->aOp[i];
  60626. }else{
  60627. /* We are currently listing subprograms. Figure out which one and
  60628. ** pick up the appropriate opcode. */
  60629. int j;
  60630. i -= p->nOp;
  60631. for(j=0; i>=apSub[j]->nOp; j++){
  60632. i -= apSub[j]->nOp;
  60633. }
  60634. pOp = &apSub[j]->aOp[i];
  60635. }
  60636. if( p->explain==1 ){
  60637. pMem->flags = MEM_Int;
  60638. pMem->type = SQLITE_INTEGER;
  60639. pMem->u.i = i; /* Program counter */
  60640. pMem++;
  60641. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  60642. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  60643. assert( pMem->z!=0 );
  60644. pMem->n = sqlite3Strlen30(pMem->z);
  60645. pMem->type = SQLITE_TEXT;
  60646. pMem->enc = SQLITE_UTF8;
  60647. pMem++;
  60648. /* When an OP_Program opcode is encounter (the only opcode that has
  60649. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  60650. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  60651. ** has not already been seen.
  60652. */
  60653. if( pOp->p4type==P4_SUBPROGRAM ){
  60654. int nByte = (nSub+1)*sizeof(SubProgram*);
  60655. int j;
  60656. for(j=0; j<nSub; j++){
  60657. if( apSub[j]==pOp->p4.pProgram ) break;
  60658. }
  60659. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  60660. apSub = (SubProgram **)pSub->z;
  60661. apSub[nSub++] = pOp->p4.pProgram;
  60662. pSub->flags |= MEM_Blob;
  60663. pSub->n = nSub*sizeof(SubProgram*);
  60664. }
  60665. }
  60666. }
  60667. pMem->flags = MEM_Int;
  60668. pMem->u.i = pOp->p1; /* P1 */
  60669. pMem->type = SQLITE_INTEGER;
  60670. pMem++;
  60671. pMem->flags = MEM_Int;
  60672. pMem->u.i = pOp->p2; /* P2 */
  60673. pMem->type = SQLITE_INTEGER;
  60674. pMem++;
  60675. pMem->flags = MEM_Int;
  60676. pMem->u.i = pOp->p3; /* P3 */
  60677. pMem->type = SQLITE_INTEGER;
  60678. pMem++;
  60679. if( sqlite3VdbeMemGrow(pMem, 32, 0) ){ /* P4 */
  60680. assert( p->db->mallocFailed );
  60681. return SQLITE_ERROR;
  60682. }
  60683. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  60684. z = displayP4(pOp, pMem->z, 32);
  60685. if( z!=pMem->z ){
  60686. sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
  60687. }else{
  60688. assert( pMem->z!=0 );
  60689. pMem->n = sqlite3Strlen30(pMem->z);
  60690. pMem->enc = SQLITE_UTF8;
  60691. }
  60692. pMem->type = SQLITE_TEXT;
  60693. pMem++;
  60694. if( p->explain==1 ){
  60695. if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
  60696. assert( p->db->mallocFailed );
  60697. return SQLITE_ERROR;
  60698. }
  60699. pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
  60700. pMem->n = 2;
  60701. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  60702. pMem->type = SQLITE_TEXT;
  60703. pMem->enc = SQLITE_UTF8;
  60704. pMem++;
  60705. #ifdef SQLITE_DEBUG
  60706. if( pOp->zComment ){
  60707. pMem->flags = MEM_Str|MEM_Term;
  60708. pMem->z = pOp->zComment;
  60709. pMem->n = sqlite3Strlen30(pMem->z);
  60710. pMem->enc = SQLITE_UTF8;
  60711. pMem->type = SQLITE_TEXT;
  60712. }else
  60713. #endif
  60714. {
  60715. pMem->flags = MEM_Null; /* Comment */
  60716. pMem->type = SQLITE_NULL;
  60717. }
  60718. }
  60719. p->nResColumn = 8 - 4*(p->explain-1);
  60720. p->pResultSet = &p->aMem[1];
  60721. p->rc = SQLITE_OK;
  60722. rc = SQLITE_ROW;
  60723. }
  60724. return rc;
  60725. }
  60726. #endif /* SQLITE_OMIT_EXPLAIN */
  60727. #ifdef SQLITE_DEBUG
  60728. /*
  60729. ** Print the SQL that was used to generate a VDBE program.
  60730. */
  60731. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  60732. int nOp = p->nOp;
  60733. VdbeOp *pOp;
  60734. if( nOp<1 ) return;
  60735. pOp = &p->aOp[0];
  60736. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  60737. const char *z = pOp->p4.z;
  60738. while( sqlite3Isspace(*z) ) z++;
  60739. printf("SQL: [%s]\n", z);
  60740. }
  60741. }
  60742. #endif
  60743. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  60744. /*
  60745. ** Print an IOTRACE message showing SQL content.
  60746. */
  60747. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  60748. int nOp = p->nOp;
  60749. VdbeOp *pOp;
  60750. if( sqlite3IoTrace==0 ) return;
  60751. if( nOp<1 ) return;
  60752. pOp = &p->aOp[0];
  60753. if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
  60754. int i, j;
  60755. char z[1000];
  60756. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  60757. for(i=0; sqlite3Isspace(z[i]); i++){}
  60758. for(j=0; z[i]; i++){
  60759. if( sqlite3Isspace(z[i]) ){
  60760. if( z[i-1]!=' ' ){
  60761. z[j++] = ' ';
  60762. }
  60763. }else{
  60764. z[j++] = z[i];
  60765. }
  60766. }
  60767. z[j] = 0;
  60768. sqlite3IoTrace("SQL %s\n", z);
  60769. }
  60770. }
  60771. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  60772. /*
  60773. ** Allocate space from a fixed size buffer and return a pointer to
  60774. ** that space. If insufficient space is available, return NULL.
  60775. **
  60776. ** The pBuf parameter is the initial value of a pointer which will
  60777. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  60778. ** NULL, it means that memory space has already been allocated and that
  60779. ** this routine should not allocate any new memory. When pBuf is not
  60780. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  60781. ** is NULL.
  60782. **
  60783. ** nByte is the number of bytes of space needed.
  60784. **
  60785. ** *ppFrom points to available space and pEnd points to the end of the
  60786. ** available space. When space is allocated, *ppFrom is advanced past
  60787. ** the end of the allocated space.
  60788. **
  60789. ** *pnByte is a counter of the number of bytes of space that have failed
  60790. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  60791. ** request, then increment *pnByte by the amount of the request.
  60792. */
  60793. static void *allocSpace(
  60794. void *pBuf, /* Where return pointer will be stored */
  60795. int nByte, /* Number of bytes to allocate */
  60796. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  60797. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  60798. int *pnByte /* If allocation cannot be made, increment *pnByte */
  60799. ){
  60800. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  60801. if( pBuf ) return pBuf;
  60802. nByte = ROUND8(nByte);
  60803. if( &(*ppFrom)[nByte] <= pEnd ){
  60804. pBuf = (void*)*ppFrom;
  60805. *ppFrom += nByte;
  60806. }else{
  60807. *pnByte += nByte;
  60808. }
  60809. return pBuf;
  60810. }
  60811. /*
  60812. ** Rewind the VDBE back to the beginning in preparation for
  60813. ** running it.
  60814. */
  60815. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  60816. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  60817. int i;
  60818. #endif
  60819. assert( p!=0 );
  60820. assert( p->magic==VDBE_MAGIC_INIT );
  60821. /* There should be at least one opcode.
  60822. */
  60823. assert( p->nOp>0 );
  60824. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  60825. p->magic = VDBE_MAGIC_RUN;
  60826. #ifdef SQLITE_DEBUG
  60827. for(i=1; i<p->nMem; i++){
  60828. assert( p->aMem[i].db==p->db );
  60829. }
  60830. #endif
  60831. p->pc = -1;
  60832. p->rc = SQLITE_OK;
  60833. p->errorAction = OE_Abort;
  60834. p->magic = VDBE_MAGIC_RUN;
  60835. p->nChange = 0;
  60836. p->cacheCtr = 1;
  60837. p->minWriteFileFormat = 255;
  60838. p->iStatement = 0;
  60839. p->nFkConstraint = 0;
  60840. #ifdef VDBE_PROFILE
  60841. for(i=0; i<p->nOp; i++){
  60842. p->aOp[i].cnt = 0;
  60843. p->aOp[i].cycles = 0;
  60844. }
  60845. #endif
  60846. }
  60847. /*
  60848. ** Prepare a virtual machine for execution for the first time after
  60849. ** creating the virtual machine. This involves things such
  60850. ** as allocating stack space and initializing the program counter.
  60851. ** After the VDBE has be prepped, it can be executed by one or more
  60852. ** calls to sqlite3VdbeExec().
  60853. **
  60854. ** This function may be called exact once on a each virtual machine.
  60855. ** After this routine is called the VM has been "packaged" and is ready
  60856. ** to run. After this routine is called, futher calls to
  60857. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  60858. ** the Vdbe from the Parse object that helped generate it so that the
  60859. ** the Vdbe becomes an independent entity and the Parse object can be
  60860. ** destroyed.
  60861. **
  60862. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  60863. ** to its initial state after it has been run.
  60864. */
  60865. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  60866. Vdbe *p, /* The VDBE */
  60867. Parse *pParse /* Parsing context */
  60868. ){
  60869. sqlite3 *db; /* The database connection */
  60870. int nVar; /* Number of parameters */
  60871. int nMem; /* Number of VM memory registers */
  60872. int nCursor; /* Number of cursors required */
  60873. int nArg; /* Number of arguments in subprograms */
  60874. int nOnce; /* Number of OP_Once instructions */
  60875. int n; /* Loop counter */
  60876. u8 *zCsr; /* Memory available for allocation */
  60877. u8 *zEnd; /* First byte past allocated memory */
  60878. int nByte; /* How much extra memory is needed */
  60879. assert( p!=0 );
  60880. assert( p->nOp>0 );
  60881. assert( pParse!=0 );
  60882. assert( p->magic==VDBE_MAGIC_INIT );
  60883. db = p->db;
  60884. assert( db->mallocFailed==0 );
  60885. nVar = pParse->nVar;
  60886. nMem = pParse->nMem;
  60887. nCursor = pParse->nTab;
  60888. nArg = pParse->nMaxArg;
  60889. nOnce = pParse->nOnce;
  60890. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  60891. /* For each cursor required, also allocate a memory cell. Memory
  60892. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  60893. ** the vdbe program. Instead they are used to allocate space for
  60894. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  60895. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  60896. ** stores the blob of memory associated with cursor 1, etc.
  60897. **
  60898. ** See also: allocateCursor().
  60899. */
  60900. nMem += nCursor;
  60901. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  60902. ** an array to marshal SQL function arguments in.
  60903. */
  60904. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  60905. zEnd = (u8*)&p->aOp[p->nOpAlloc]; /* First byte past end of zCsr[] */
  60906. resolveP2Values(p, &nArg);
  60907. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  60908. if( pParse->explain && nMem<10 ){
  60909. nMem = 10;
  60910. }
  60911. memset(zCsr, 0, zEnd-zCsr);
  60912. zCsr += (zCsr - (u8*)0)&7;
  60913. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  60914. p->expired = 0;
  60915. /* Memory for registers, parameters, cursor, etc, is allocated in two
  60916. ** passes. On the first pass, we try to reuse unused space at the
  60917. ** end of the opcode array. If we are unable to satisfy all memory
  60918. ** requirements by reusing the opcode array tail, then the second
  60919. ** pass will fill in the rest using a fresh allocation.
  60920. **
  60921. ** This two-pass approach that reuses as much memory as possible from
  60922. ** the leftover space at the end of the opcode array can significantly
  60923. ** reduce the amount of memory held by a prepared statement.
  60924. */
  60925. do {
  60926. nByte = 0;
  60927. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  60928. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  60929. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  60930. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  60931. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  60932. &zCsr, zEnd, &nByte);
  60933. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  60934. if( nByte ){
  60935. p->pFree = sqlite3DbMallocZero(db, nByte);
  60936. }
  60937. zCsr = p->pFree;
  60938. zEnd = &zCsr[nByte];
  60939. }while( nByte && !db->mallocFailed );
  60940. p->nCursor = nCursor;
  60941. p->nOnceFlag = nOnce;
  60942. if( p->aVar ){
  60943. p->nVar = (ynVar)nVar;
  60944. for(n=0; n<nVar; n++){
  60945. p->aVar[n].flags = MEM_Null;
  60946. p->aVar[n].db = db;
  60947. }
  60948. }
  60949. if( p->azVar ){
  60950. p->nzVar = pParse->nzVar;
  60951. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  60952. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  60953. }
  60954. if( p->aMem ){
  60955. p->aMem--; /* aMem[] goes from 1..nMem */
  60956. p->nMem = nMem; /* not from 0..nMem-1 */
  60957. for(n=1; n<=nMem; n++){
  60958. p->aMem[n].flags = MEM_Invalid;
  60959. p->aMem[n].db = db;
  60960. }
  60961. }
  60962. p->explain = pParse->explain;
  60963. sqlite3VdbeRewind(p);
  60964. }
  60965. /*
  60966. ** Close a VDBE cursor and release all the resources that cursor
  60967. ** happens to hold.
  60968. */
  60969. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  60970. if( pCx==0 ){
  60971. return;
  60972. }
  60973. sqlite3VdbeSorterClose(p->db, pCx);
  60974. if( pCx->pBt ){
  60975. sqlite3BtreeClose(pCx->pBt);
  60976. /* The pCx->pCursor will be close automatically, if it exists, by
  60977. ** the call above. */
  60978. }else if( pCx->pCursor ){
  60979. sqlite3BtreeCloseCursor(pCx->pCursor);
  60980. }
  60981. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60982. if( pCx->pVtabCursor ){
  60983. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  60984. const sqlite3_module *pModule = pCx->pModule;
  60985. p->inVtabMethod = 1;
  60986. pModule->xClose(pVtabCursor);
  60987. p->inVtabMethod = 0;
  60988. }
  60989. #endif
  60990. }
  60991. /*
  60992. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  60993. ** is used, for example, when a trigger sub-program is halted to restore
  60994. ** control to the main program.
  60995. */
  60996. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  60997. Vdbe *v = pFrame->v;
  60998. v->aOnceFlag = pFrame->aOnceFlag;
  60999. v->nOnceFlag = pFrame->nOnceFlag;
  61000. v->aOp = pFrame->aOp;
  61001. v->nOp = pFrame->nOp;
  61002. v->aMem = pFrame->aMem;
  61003. v->nMem = pFrame->nMem;
  61004. v->apCsr = pFrame->apCsr;
  61005. v->nCursor = pFrame->nCursor;
  61006. v->db->lastRowid = pFrame->lastRowid;
  61007. v->nChange = pFrame->nChange;
  61008. return pFrame->pc;
  61009. }
  61010. /*
  61011. ** Close all cursors.
  61012. **
  61013. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  61014. ** cell array. This is necessary as the memory cell array may contain
  61015. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  61016. ** open cursors.
  61017. */
  61018. static void closeAllCursors(Vdbe *p){
  61019. if( p->pFrame ){
  61020. VdbeFrame *pFrame;
  61021. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  61022. sqlite3VdbeFrameRestore(pFrame);
  61023. }
  61024. p->pFrame = 0;
  61025. p->nFrame = 0;
  61026. if( p->apCsr ){
  61027. int i;
  61028. for(i=0; i<p->nCursor; i++){
  61029. VdbeCursor *pC = p->apCsr[i];
  61030. if( pC ){
  61031. sqlite3VdbeFreeCursor(p, pC);
  61032. p->apCsr[i] = 0;
  61033. }
  61034. }
  61035. }
  61036. if( p->aMem ){
  61037. releaseMemArray(&p->aMem[1], p->nMem);
  61038. }
  61039. while( p->pDelFrame ){
  61040. VdbeFrame *pDel = p->pDelFrame;
  61041. p->pDelFrame = pDel->pParent;
  61042. sqlite3VdbeFrameDelete(pDel);
  61043. }
  61044. /* Delete any auxdata allocations made by the VM */
  61045. sqlite3VdbeDeleteAuxData(p, -1, 0);
  61046. assert( p->pAuxData==0 );
  61047. }
  61048. /*
  61049. ** Clean up the VM after execution.
  61050. **
  61051. ** This routine will automatically close any cursors, lists, and/or
  61052. ** sorters that were left open. It also deletes the values of
  61053. ** variables in the aVar[] array.
  61054. */
  61055. static void Cleanup(Vdbe *p){
  61056. sqlite3 *db = p->db;
  61057. #ifdef SQLITE_DEBUG
  61058. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  61059. ** Vdbe.aMem[] arrays have already been cleaned up. */
  61060. int i;
  61061. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  61062. if( p->aMem ){
  61063. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Invalid );
  61064. }
  61065. #endif
  61066. sqlite3DbFree(db, p->zErrMsg);
  61067. p->zErrMsg = 0;
  61068. p->pResultSet = 0;
  61069. }
  61070. /*
  61071. ** Set the number of result columns that will be returned by this SQL
  61072. ** statement. This is now set at compile time, rather than during
  61073. ** execution of the vdbe program so that sqlite3_column_count() can
  61074. ** be called on an SQL statement before sqlite3_step().
  61075. */
  61076. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  61077. Mem *pColName;
  61078. int n;
  61079. sqlite3 *db = p->db;
  61080. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61081. sqlite3DbFree(db, p->aColName);
  61082. n = nResColumn*COLNAME_N;
  61083. p->nResColumn = (u16)nResColumn;
  61084. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  61085. if( p->aColName==0 ) return;
  61086. while( n-- > 0 ){
  61087. pColName->flags = MEM_Null;
  61088. pColName->db = p->db;
  61089. pColName++;
  61090. }
  61091. }
  61092. /*
  61093. ** Set the name of the idx'th column to be returned by the SQL statement.
  61094. ** zName must be a pointer to a nul terminated string.
  61095. **
  61096. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  61097. **
  61098. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  61099. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  61100. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  61101. */
  61102. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  61103. Vdbe *p, /* Vdbe being configured */
  61104. int idx, /* Index of column zName applies to */
  61105. int var, /* One of the COLNAME_* constants */
  61106. const char *zName, /* Pointer to buffer containing name */
  61107. void (*xDel)(void*) /* Memory management strategy for zName */
  61108. ){
  61109. int rc;
  61110. Mem *pColName;
  61111. assert( idx<p->nResColumn );
  61112. assert( var<COLNAME_N );
  61113. if( p->db->mallocFailed ){
  61114. assert( !zName || xDel!=SQLITE_DYNAMIC );
  61115. return SQLITE_NOMEM;
  61116. }
  61117. assert( p->aColName!=0 );
  61118. pColName = &(p->aColName[idx+var*p->nResColumn]);
  61119. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  61120. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  61121. return rc;
  61122. }
  61123. /*
  61124. ** A read or write transaction may or may not be active on database handle
  61125. ** db. If a transaction is active, commit it. If there is a
  61126. ** write-transaction spanning more than one database file, this routine
  61127. ** takes care of the master journal trickery.
  61128. */
  61129. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  61130. int i;
  61131. int nTrans = 0; /* Number of databases with an active write-transaction */
  61132. int rc = SQLITE_OK;
  61133. int needXcommit = 0;
  61134. #ifdef SQLITE_OMIT_VIRTUALTABLE
  61135. /* With this option, sqlite3VtabSync() is defined to be simply
  61136. ** SQLITE_OK so p is not used.
  61137. */
  61138. UNUSED_PARAMETER(p);
  61139. #endif
  61140. /* Before doing anything else, call the xSync() callback for any
  61141. ** virtual module tables written in this transaction. This has to
  61142. ** be done before determining whether a master journal file is
  61143. ** required, as an xSync() callback may add an attached database
  61144. ** to the transaction.
  61145. */
  61146. rc = sqlite3VtabSync(db, p);
  61147. /* This loop determines (a) if the commit hook should be invoked and
  61148. ** (b) how many database files have open write transactions, not
  61149. ** including the temp database. (b) is important because if more than
  61150. ** one database file has an open write transaction, a master journal
  61151. ** file is required for an atomic commit.
  61152. */
  61153. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61154. Btree *pBt = db->aDb[i].pBt;
  61155. if( sqlite3BtreeIsInTrans(pBt) ){
  61156. needXcommit = 1;
  61157. if( i!=1 ) nTrans++;
  61158. sqlite3BtreeEnter(pBt);
  61159. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  61160. sqlite3BtreeLeave(pBt);
  61161. }
  61162. }
  61163. if( rc!=SQLITE_OK ){
  61164. return rc;
  61165. }
  61166. /* If there are any write-transactions at all, invoke the commit hook */
  61167. if( needXcommit && db->xCommitCallback ){
  61168. rc = db->xCommitCallback(db->pCommitArg);
  61169. if( rc ){
  61170. return SQLITE_CONSTRAINT_COMMITHOOK;
  61171. }
  61172. }
  61173. /* The simple case - no more than one database file (not counting the
  61174. ** TEMP database) has a transaction active. There is no need for the
  61175. ** master-journal.
  61176. **
  61177. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  61178. ** string, it means the main database is :memory: or a temp file. In
  61179. ** that case we do not support atomic multi-file commits, so use the
  61180. ** simple case then too.
  61181. */
  61182. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  61183. || nTrans<=1
  61184. ){
  61185. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61186. Btree *pBt = db->aDb[i].pBt;
  61187. if( pBt ){
  61188. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  61189. }
  61190. }
  61191. /* Do the commit only if all databases successfully complete phase 1.
  61192. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  61193. ** IO error while deleting or truncating a journal file. It is unlikely,
  61194. ** but could happen. In this case abandon processing and return the error.
  61195. */
  61196. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61197. Btree *pBt = db->aDb[i].pBt;
  61198. if( pBt ){
  61199. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  61200. }
  61201. }
  61202. if( rc==SQLITE_OK ){
  61203. sqlite3VtabCommit(db);
  61204. }
  61205. }
  61206. /* The complex case - There is a multi-file write-transaction active.
  61207. ** This requires a master journal file to ensure the transaction is
  61208. ** committed atomicly.
  61209. */
  61210. #ifndef SQLITE_OMIT_DISKIO
  61211. else{
  61212. sqlite3_vfs *pVfs = db->pVfs;
  61213. int needSync = 0;
  61214. char *zMaster = 0; /* File-name for the master journal */
  61215. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  61216. sqlite3_file *pMaster = 0;
  61217. i64 offset = 0;
  61218. int res;
  61219. int retryCount = 0;
  61220. int nMainFile;
  61221. /* Select a master journal file name */
  61222. nMainFile = sqlite3Strlen30(zMainFile);
  61223. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  61224. if( zMaster==0 ) return SQLITE_NOMEM;
  61225. do {
  61226. u32 iRandom;
  61227. if( retryCount ){
  61228. if( retryCount>100 ){
  61229. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  61230. sqlite3OsDelete(pVfs, zMaster, 0);
  61231. break;
  61232. }else if( retryCount==1 ){
  61233. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  61234. }
  61235. }
  61236. retryCount++;
  61237. sqlite3_randomness(sizeof(iRandom), &iRandom);
  61238. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  61239. (iRandom>>8)&0xffffff, iRandom&0xff);
  61240. /* The antipenultimate character of the master journal name must
  61241. ** be "9" to avoid name collisions when using 8+3 filenames. */
  61242. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  61243. sqlite3FileSuffix3(zMainFile, zMaster);
  61244. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  61245. }while( rc==SQLITE_OK && res );
  61246. if( rc==SQLITE_OK ){
  61247. /* Open the master journal. */
  61248. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  61249. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  61250. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  61251. );
  61252. }
  61253. if( rc!=SQLITE_OK ){
  61254. sqlite3DbFree(db, zMaster);
  61255. return rc;
  61256. }
  61257. /* Write the name of each database file in the transaction into the new
  61258. ** master journal file. If an error occurs at this point close
  61259. ** and delete the master journal file. All the individual journal files
  61260. ** still have 'null' as the master journal pointer, so they will roll
  61261. ** back independently if a failure occurs.
  61262. */
  61263. for(i=0; i<db->nDb; i++){
  61264. Btree *pBt = db->aDb[i].pBt;
  61265. if( sqlite3BtreeIsInTrans(pBt) ){
  61266. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  61267. if( zFile==0 ){
  61268. continue; /* Ignore TEMP and :memory: databases */
  61269. }
  61270. assert( zFile[0]!=0 );
  61271. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  61272. needSync = 1;
  61273. }
  61274. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  61275. offset += sqlite3Strlen30(zFile)+1;
  61276. if( rc!=SQLITE_OK ){
  61277. sqlite3OsCloseFree(pMaster);
  61278. sqlite3OsDelete(pVfs, zMaster, 0);
  61279. sqlite3DbFree(db, zMaster);
  61280. return rc;
  61281. }
  61282. }
  61283. }
  61284. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  61285. ** flag is set this is not required.
  61286. */
  61287. if( needSync
  61288. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  61289. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  61290. ){
  61291. sqlite3OsCloseFree(pMaster);
  61292. sqlite3OsDelete(pVfs, zMaster, 0);
  61293. sqlite3DbFree(db, zMaster);
  61294. return rc;
  61295. }
  61296. /* Sync all the db files involved in the transaction. The same call
  61297. ** sets the master journal pointer in each individual journal. If
  61298. ** an error occurs here, do not delete the master journal file.
  61299. **
  61300. ** If the error occurs during the first call to
  61301. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  61302. ** master journal file will be orphaned. But we cannot delete it,
  61303. ** in case the master journal file name was written into the journal
  61304. ** file before the failure occurred.
  61305. */
  61306. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  61307. Btree *pBt = db->aDb[i].pBt;
  61308. if( pBt ){
  61309. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  61310. }
  61311. }
  61312. sqlite3OsCloseFree(pMaster);
  61313. assert( rc!=SQLITE_BUSY );
  61314. if( rc!=SQLITE_OK ){
  61315. sqlite3DbFree(db, zMaster);
  61316. return rc;
  61317. }
  61318. /* Delete the master journal file. This commits the transaction. After
  61319. ** doing this the directory is synced again before any individual
  61320. ** transaction files are deleted.
  61321. */
  61322. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  61323. sqlite3DbFree(db, zMaster);
  61324. zMaster = 0;
  61325. if( rc ){
  61326. return rc;
  61327. }
  61328. /* All files and directories have already been synced, so the following
  61329. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  61330. ** deleting or truncating journals. If something goes wrong while
  61331. ** this is happening we don't really care. The integrity of the
  61332. ** transaction is already guaranteed, but some stray 'cold' journals
  61333. ** may be lying around. Returning an error code won't help matters.
  61334. */
  61335. disable_simulated_io_errors();
  61336. sqlite3BeginBenignMalloc();
  61337. for(i=0; i<db->nDb; i++){
  61338. Btree *pBt = db->aDb[i].pBt;
  61339. if( pBt ){
  61340. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  61341. }
  61342. }
  61343. sqlite3EndBenignMalloc();
  61344. enable_simulated_io_errors();
  61345. sqlite3VtabCommit(db);
  61346. }
  61347. #endif
  61348. return rc;
  61349. }
  61350. /*
  61351. ** This routine checks that the sqlite3.nVdbeActive count variable
  61352. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  61353. ** currently active. An assertion fails if the two counts do not match.
  61354. ** This is an internal self-check only - it is not an essential processing
  61355. ** step.
  61356. **
  61357. ** This is a no-op if NDEBUG is defined.
  61358. */
  61359. #ifndef NDEBUG
  61360. static void checkActiveVdbeCnt(sqlite3 *db){
  61361. Vdbe *p;
  61362. int cnt = 0;
  61363. int nWrite = 0;
  61364. int nRead = 0;
  61365. p = db->pVdbe;
  61366. while( p ){
  61367. if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
  61368. cnt++;
  61369. if( p->readOnly==0 ) nWrite++;
  61370. if( p->bIsReader ) nRead++;
  61371. }
  61372. p = p->pNext;
  61373. }
  61374. assert( cnt==db->nVdbeActive );
  61375. assert( nWrite==db->nVdbeWrite );
  61376. assert( nRead==db->nVdbeRead );
  61377. }
  61378. #else
  61379. #define checkActiveVdbeCnt(x)
  61380. #endif
  61381. /*
  61382. ** If the Vdbe passed as the first argument opened a statement-transaction,
  61383. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  61384. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  61385. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  61386. ** statement transaction is committed.
  61387. **
  61388. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  61389. ** Otherwise SQLITE_OK.
  61390. */
  61391. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  61392. sqlite3 *const db = p->db;
  61393. int rc = SQLITE_OK;
  61394. /* If p->iStatement is greater than zero, then this Vdbe opened a
  61395. ** statement transaction that should be closed here. The only exception
  61396. ** is that an IO error may have occurred, causing an emergency rollback.
  61397. ** In this case (db->nStatement==0), and there is nothing to do.
  61398. */
  61399. if( db->nStatement && p->iStatement ){
  61400. int i;
  61401. const int iSavepoint = p->iStatement-1;
  61402. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  61403. assert( db->nStatement>0 );
  61404. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  61405. for(i=0; i<db->nDb; i++){
  61406. int rc2 = SQLITE_OK;
  61407. Btree *pBt = db->aDb[i].pBt;
  61408. if( pBt ){
  61409. if( eOp==SAVEPOINT_ROLLBACK ){
  61410. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  61411. }
  61412. if( rc2==SQLITE_OK ){
  61413. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  61414. }
  61415. if( rc==SQLITE_OK ){
  61416. rc = rc2;
  61417. }
  61418. }
  61419. }
  61420. db->nStatement--;
  61421. p->iStatement = 0;
  61422. if( rc==SQLITE_OK ){
  61423. if( eOp==SAVEPOINT_ROLLBACK ){
  61424. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  61425. }
  61426. if( rc==SQLITE_OK ){
  61427. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  61428. }
  61429. }
  61430. /* If the statement transaction is being rolled back, also restore the
  61431. ** database handles deferred constraint counter to the value it had when
  61432. ** the statement transaction was opened. */
  61433. if( eOp==SAVEPOINT_ROLLBACK ){
  61434. db->nDeferredCons = p->nStmtDefCons;
  61435. db->nDeferredImmCons = p->nStmtDefImmCons;
  61436. }
  61437. }
  61438. return rc;
  61439. }
  61440. /*
  61441. ** This function is called when a transaction opened by the database
  61442. ** handle associated with the VM passed as an argument is about to be
  61443. ** committed. If there are outstanding deferred foreign key constraint
  61444. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  61445. **
  61446. ** If there are outstanding FK violations and this function returns
  61447. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  61448. ** and write an error message to it. Then return SQLITE_ERROR.
  61449. */
  61450. #ifndef SQLITE_OMIT_FOREIGN_KEY
  61451. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  61452. sqlite3 *db = p->db;
  61453. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  61454. || (!deferred && p->nFkConstraint>0)
  61455. ){
  61456. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61457. p->errorAction = OE_Abort;
  61458. sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
  61459. return SQLITE_ERROR;
  61460. }
  61461. return SQLITE_OK;
  61462. }
  61463. #endif
  61464. /*
  61465. ** This routine is called the when a VDBE tries to halt. If the VDBE
  61466. ** has made changes and is in autocommit mode, then commit those
  61467. ** changes. If a rollback is needed, then do the rollback.
  61468. **
  61469. ** This routine is the only way to move the state of a VM from
  61470. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  61471. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  61472. **
  61473. ** Return an error code. If the commit could not complete because of
  61474. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  61475. ** means the close did not happen and needs to be repeated.
  61476. */
  61477. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  61478. int rc; /* Used to store transient return codes */
  61479. sqlite3 *db = p->db;
  61480. /* This function contains the logic that determines if a statement or
  61481. ** transaction will be committed or rolled back as a result of the
  61482. ** execution of this virtual machine.
  61483. **
  61484. ** If any of the following errors occur:
  61485. **
  61486. ** SQLITE_NOMEM
  61487. ** SQLITE_IOERR
  61488. ** SQLITE_FULL
  61489. ** SQLITE_INTERRUPT
  61490. **
  61491. ** Then the internal cache might have been left in an inconsistent
  61492. ** state. We need to rollback the statement transaction, if there is
  61493. ** one, or the complete transaction if there is no statement transaction.
  61494. */
  61495. if( p->db->mallocFailed ){
  61496. p->rc = SQLITE_NOMEM;
  61497. }
  61498. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  61499. closeAllCursors(p);
  61500. if( p->magic!=VDBE_MAGIC_RUN ){
  61501. return SQLITE_OK;
  61502. }
  61503. checkActiveVdbeCnt(db);
  61504. /* No commit or rollback needed if the program never started or if the
  61505. ** SQL statement does not read or write a database file. */
  61506. if( p->pc>=0 && p->bIsReader ){
  61507. int mrc; /* Primary error code from p->rc */
  61508. int eStatementOp = 0;
  61509. int isSpecialError; /* Set to true if a 'special' error */
  61510. /* Lock all btrees used by the statement */
  61511. sqlite3VdbeEnter(p);
  61512. /* Check for one of the special errors */
  61513. mrc = p->rc & 0xff;
  61514. assert( p->rc!=SQLITE_IOERR_BLOCKED ); /* This error no longer exists */
  61515. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  61516. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  61517. if( isSpecialError ){
  61518. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  61519. ** no rollback is necessary. Otherwise, at least a savepoint
  61520. ** transaction must be rolled back to restore the database to a
  61521. ** consistent state.
  61522. **
  61523. ** Even if the statement is read-only, it is important to perform
  61524. ** a statement or transaction rollback operation. If the error
  61525. ** occurred while writing to the journal, sub-journal or database
  61526. ** file as part of an effort to free up cache space (see function
  61527. ** pagerStress() in pager.c), the rollback is required to restore
  61528. ** the pager to a consistent state.
  61529. */
  61530. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  61531. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  61532. eStatementOp = SAVEPOINT_ROLLBACK;
  61533. }else{
  61534. /* We are forced to roll back the active transaction. Before doing
  61535. ** so, abort any other statements this handle currently has active.
  61536. */
  61537. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61538. sqlite3CloseSavepoints(db);
  61539. db->autoCommit = 1;
  61540. }
  61541. }
  61542. }
  61543. /* Check for immediate foreign key violations. */
  61544. if( p->rc==SQLITE_OK ){
  61545. sqlite3VdbeCheckFk(p, 0);
  61546. }
  61547. /* If the auto-commit flag is set and this is the only active writer
  61548. ** VM, then we do either a commit or rollback of the current transaction.
  61549. **
  61550. ** Note: This block also runs if one of the special errors handled
  61551. ** above has occurred.
  61552. */
  61553. if( !sqlite3VtabInSync(db)
  61554. && db->autoCommit
  61555. && db->nVdbeWrite==(p->readOnly==0)
  61556. ){
  61557. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  61558. rc = sqlite3VdbeCheckFk(p, 1);
  61559. if( rc!=SQLITE_OK ){
  61560. if( NEVER(p->readOnly) ){
  61561. sqlite3VdbeLeave(p);
  61562. return SQLITE_ERROR;
  61563. }
  61564. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61565. }else{
  61566. /* The auto-commit flag is true, the vdbe program was successful
  61567. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  61568. ** key constraints to hold up the transaction. This means a commit
  61569. ** is required. */
  61570. rc = vdbeCommit(db, p);
  61571. }
  61572. if( rc==SQLITE_BUSY && p->readOnly ){
  61573. sqlite3VdbeLeave(p);
  61574. return SQLITE_BUSY;
  61575. }else if( rc!=SQLITE_OK ){
  61576. p->rc = rc;
  61577. sqlite3RollbackAll(db, SQLITE_OK);
  61578. }else{
  61579. db->nDeferredCons = 0;
  61580. db->nDeferredImmCons = 0;
  61581. db->flags &= ~SQLITE_DeferFKs;
  61582. sqlite3CommitInternalChanges(db);
  61583. }
  61584. }else{
  61585. sqlite3RollbackAll(db, SQLITE_OK);
  61586. }
  61587. db->nStatement = 0;
  61588. }else if( eStatementOp==0 ){
  61589. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  61590. eStatementOp = SAVEPOINT_RELEASE;
  61591. }else if( p->errorAction==OE_Abort ){
  61592. eStatementOp = SAVEPOINT_ROLLBACK;
  61593. }else{
  61594. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61595. sqlite3CloseSavepoints(db);
  61596. db->autoCommit = 1;
  61597. }
  61598. }
  61599. /* If eStatementOp is non-zero, then a statement transaction needs to
  61600. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  61601. ** do so. If this operation returns an error, and the current statement
  61602. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  61603. ** current statement error code.
  61604. */
  61605. if( eStatementOp ){
  61606. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  61607. if( rc ){
  61608. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  61609. p->rc = rc;
  61610. sqlite3DbFree(db, p->zErrMsg);
  61611. p->zErrMsg = 0;
  61612. }
  61613. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61614. sqlite3CloseSavepoints(db);
  61615. db->autoCommit = 1;
  61616. }
  61617. }
  61618. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  61619. ** has been rolled back, update the database connection change-counter.
  61620. */
  61621. if( p->changeCntOn ){
  61622. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  61623. sqlite3VdbeSetChanges(db, p->nChange);
  61624. }else{
  61625. sqlite3VdbeSetChanges(db, 0);
  61626. }
  61627. p->nChange = 0;
  61628. }
  61629. /* Release the locks */
  61630. sqlite3VdbeLeave(p);
  61631. }
  61632. /* We have successfully halted and closed the VM. Record this fact. */
  61633. if( p->pc>=0 ){
  61634. db->nVdbeActive--;
  61635. if( !p->readOnly ) db->nVdbeWrite--;
  61636. if( p->bIsReader ) db->nVdbeRead--;
  61637. assert( db->nVdbeActive>=db->nVdbeRead );
  61638. assert( db->nVdbeRead>=db->nVdbeWrite );
  61639. assert( db->nVdbeWrite>=0 );
  61640. }
  61641. p->magic = VDBE_MAGIC_HALT;
  61642. checkActiveVdbeCnt(db);
  61643. if( p->db->mallocFailed ){
  61644. p->rc = SQLITE_NOMEM;
  61645. }
  61646. /* If the auto-commit flag is set to true, then any locks that were held
  61647. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  61648. ** to invoke any required unlock-notify callbacks.
  61649. */
  61650. if( db->autoCommit ){
  61651. sqlite3ConnectionUnlocked(db);
  61652. }
  61653. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  61654. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  61655. }
  61656. /*
  61657. ** Each VDBE holds the result of the most recent sqlite3_step() call
  61658. ** in p->rc. This routine sets that result back to SQLITE_OK.
  61659. */
  61660. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  61661. p->rc = SQLITE_OK;
  61662. }
  61663. /*
  61664. ** Copy the error code and error message belonging to the VDBE passed
  61665. ** as the first argument to its database handle (so that they will be
  61666. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  61667. **
  61668. ** This function does not clear the VDBE error code or message, just
  61669. ** copies them to the database handle.
  61670. */
  61671. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  61672. sqlite3 *db = p->db;
  61673. int rc = p->rc;
  61674. if( p->zErrMsg ){
  61675. u8 mallocFailed = db->mallocFailed;
  61676. sqlite3BeginBenignMalloc();
  61677. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61678. sqlite3EndBenignMalloc();
  61679. db->mallocFailed = mallocFailed;
  61680. db->errCode = rc;
  61681. }else{
  61682. sqlite3Error(db, rc, 0);
  61683. }
  61684. return rc;
  61685. }
  61686. #ifdef SQLITE_ENABLE_SQLLOG
  61687. /*
  61688. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  61689. ** invoke it.
  61690. */
  61691. static void vdbeInvokeSqllog(Vdbe *v){
  61692. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  61693. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  61694. assert( v->db->init.busy==0 );
  61695. if( zExpanded ){
  61696. sqlite3GlobalConfig.xSqllog(
  61697. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  61698. );
  61699. sqlite3DbFree(v->db, zExpanded);
  61700. }
  61701. }
  61702. }
  61703. #else
  61704. # define vdbeInvokeSqllog(x)
  61705. #endif
  61706. /*
  61707. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  61708. ** Write any error messages into *pzErrMsg. Return the result code.
  61709. **
  61710. ** After this routine is run, the VDBE should be ready to be executed
  61711. ** again.
  61712. **
  61713. ** To look at it another way, this routine resets the state of the
  61714. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  61715. ** VDBE_MAGIC_INIT.
  61716. */
  61717. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  61718. sqlite3 *db;
  61719. db = p->db;
  61720. /* If the VM did not run to completion or if it encountered an
  61721. ** error, then it might not have been halted properly. So halt
  61722. ** it now.
  61723. */
  61724. sqlite3VdbeHalt(p);
  61725. /* If the VDBE has be run even partially, then transfer the error code
  61726. ** and error message from the VDBE into the main database structure. But
  61727. ** if the VDBE has just been set to run but has not actually executed any
  61728. ** instructions yet, leave the main database error information unchanged.
  61729. */
  61730. if( p->pc>=0 ){
  61731. vdbeInvokeSqllog(p);
  61732. sqlite3VdbeTransferError(p);
  61733. sqlite3DbFree(db, p->zErrMsg);
  61734. p->zErrMsg = 0;
  61735. if( p->runOnlyOnce ) p->expired = 1;
  61736. }else if( p->rc && p->expired ){
  61737. /* The expired flag was set on the VDBE before the first call
  61738. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  61739. ** called), set the database error in this case as well.
  61740. */
  61741. sqlite3Error(db, p->rc, 0);
  61742. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61743. sqlite3DbFree(db, p->zErrMsg);
  61744. p->zErrMsg = 0;
  61745. }
  61746. /* Reclaim all memory used by the VDBE
  61747. */
  61748. Cleanup(p);
  61749. /* Save profiling information from this VDBE run.
  61750. */
  61751. #ifdef VDBE_PROFILE
  61752. {
  61753. FILE *out = fopen("vdbe_profile.out", "a");
  61754. if( out ){
  61755. int i;
  61756. fprintf(out, "---- ");
  61757. for(i=0; i<p->nOp; i++){
  61758. fprintf(out, "%02x", p->aOp[i].opcode);
  61759. }
  61760. fprintf(out, "\n");
  61761. for(i=0; i<p->nOp; i++){
  61762. fprintf(out, "%6d %10lld %8lld ",
  61763. p->aOp[i].cnt,
  61764. p->aOp[i].cycles,
  61765. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  61766. );
  61767. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  61768. }
  61769. fclose(out);
  61770. }
  61771. }
  61772. #endif
  61773. p->iCurrentTime = 0;
  61774. p->magic = VDBE_MAGIC_INIT;
  61775. return p->rc & db->errMask;
  61776. }
  61777. /*
  61778. ** Clean up and delete a VDBE after execution. Return an integer which is
  61779. ** the result code. Write any error message text into *pzErrMsg.
  61780. */
  61781. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  61782. int rc = SQLITE_OK;
  61783. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  61784. rc = sqlite3VdbeReset(p);
  61785. assert( (rc & p->db->errMask)==rc );
  61786. }
  61787. sqlite3VdbeDelete(p);
  61788. return rc;
  61789. }
  61790. /*
  61791. ** If parameter iOp is less than zero, then invoke the destructor for
  61792. ** all auxiliary data pointers currently cached by the VM passed as
  61793. ** the first argument.
  61794. **
  61795. ** Or, if iOp is greater than or equal to zero, then the destructor is
  61796. ** only invoked for those auxiliary data pointers created by the user
  61797. ** function invoked by the OP_Function opcode at instruction iOp of
  61798. ** VM pVdbe, and only then if:
  61799. **
  61800. ** * the associated function parameter is the 32nd or later (counting
  61801. ** from left to right), or
  61802. **
  61803. ** * the corresponding bit in argument mask is clear (where the first
  61804. ** function parameter corrsponds to bit 0 etc.).
  61805. */
  61806. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  61807. AuxData **pp = &pVdbe->pAuxData;
  61808. while( *pp ){
  61809. AuxData *pAux = *pp;
  61810. if( (iOp<0)
  61811. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & ((u32)1<<pAux->iArg))))
  61812. ){
  61813. if( pAux->xDelete ){
  61814. pAux->xDelete(pAux->pAux);
  61815. }
  61816. *pp = pAux->pNext;
  61817. sqlite3DbFree(pVdbe->db, pAux);
  61818. }else{
  61819. pp= &pAux->pNext;
  61820. }
  61821. }
  61822. }
  61823. /*
  61824. ** Free all memory associated with the Vdbe passed as the second argument,
  61825. ** except for object itself, which is preserved.
  61826. **
  61827. ** The difference between this function and sqlite3VdbeDelete() is that
  61828. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  61829. ** the database connection and frees the object itself.
  61830. */
  61831. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  61832. SubProgram *pSub, *pNext;
  61833. int i;
  61834. assert( p->db==0 || p->db==db );
  61835. releaseMemArray(p->aVar, p->nVar);
  61836. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61837. for(pSub=p->pProgram; pSub; pSub=pNext){
  61838. pNext = pSub->pNext;
  61839. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  61840. sqlite3DbFree(db, pSub);
  61841. }
  61842. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  61843. vdbeFreeOpArray(db, p->aOp, p->nOp);
  61844. sqlite3DbFree(db, p->aLabel);
  61845. sqlite3DbFree(db, p->aColName);
  61846. sqlite3DbFree(db, p->zSql);
  61847. sqlite3DbFree(db, p->pFree);
  61848. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  61849. sqlite3DbFree(db, p->zExplain);
  61850. sqlite3DbFree(db, p->pExplain);
  61851. #endif
  61852. }
  61853. /*
  61854. ** Delete an entire VDBE.
  61855. */
  61856. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  61857. sqlite3 *db;
  61858. if( NEVER(p==0) ) return;
  61859. db = p->db;
  61860. assert( sqlite3_mutex_held(db->mutex) );
  61861. sqlite3VdbeClearObject(db, p);
  61862. if( p->pPrev ){
  61863. p->pPrev->pNext = p->pNext;
  61864. }else{
  61865. assert( db->pVdbe==p );
  61866. db->pVdbe = p->pNext;
  61867. }
  61868. if( p->pNext ){
  61869. p->pNext->pPrev = p->pPrev;
  61870. }
  61871. p->magic = VDBE_MAGIC_DEAD;
  61872. p->db = 0;
  61873. sqlite3DbFree(db, p);
  61874. }
  61875. /*
  61876. ** Make sure the cursor p is ready to read or write the row to which it
  61877. ** was last positioned. Return an error code if an OOM fault or I/O error
  61878. ** prevents us from positioning the cursor to its correct position.
  61879. **
  61880. ** If a MoveTo operation is pending on the given cursor, then do that
  61881. ** MoveTo now. If no move is pending, check to see if the row has been
  61882. ** deleted out from under the cursor and if it has, mark the row as
  61883. ** a NULL row.
  61884. **
  61885. ** If the cursor is already pointing to the correct row and that row has
  61886. ** not been deleted out from under the cursor, then this routine is a no-op.
  61887. */
  61888. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  61889. if( p->deferredMoveto ){
  61890. int res, rc;
  61891. #ifdef SQLITE_TEST
  61892. extern int sqlite3_search_count;
  61893. #endif
  61894. assert( p->isTable );
  61895. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  61896. if( rc ) return rc;
  61897. p->lastRowid = p->movetoTarget;
  61898. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  61899. p->rowidIsValid = 1;
  61900. #ifdef SQLITE_TEST
  61901. sqlite3_search_count++;
  61902. #endif
  61903. p->deferredMoveto = 0;
  61904. p->cacheStatus = CACHE_STALE;
  61905. }else if( ALWAYS(p->pCursor) ){
  61906. int hasMoved;
  61907. int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
  61908. if( rc ) return rc;
  61909. if( hasMoved ){
  61910. p->cacheStatus = CACHE_STALE;
  61911. p->nullRow = 1;
  61912. }
  61913. }
  61914. return SQLITE_OK;
  61915. }
  61916. /*
  61917. ** The following functions:
  61918. **
  61919. ** sqlite3VdbeSerialType()
  61920. ** sqlite3VdbeSerialTypeLen()
  61921. ** sqlite3VdbeSerialLen()
  61922. ** sqlite3VdbeSerialPut()
  61923. ** sqlite3VdbeSerialGet()
  61924. **
  61925. ** encapsulate the code that serializes values for storage in SQLite
  61926. ** data and index records. Each serialized value consists of a
  61927. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  61928. ** integer, stored as a varint.
  61929. **
  61930. ** In an SQLite index record, the serial type is stored directly before
  61931. ** the blob of data that it corresponds to. In a table record, all serial
  61932. ** types are stored at the start of the record, and the blobs of data at
  61933. ** the end. Hence these functions allow the caller to handle the
  61934. ** serial-type and data blob separately.
  61935. **
  61936. ** The following table describes the various storage classes for data:
  61937. **
  61938. ** serial type bytes of data type
  61939. ** -------------- --------------- ---------------
  61940. ** 0 0 NULL
  61941. ** 1 1 signed integer
  61942. ** 2 2 signed integer
  61943. ** 3 3 signed integer
  61944. ** 4 4 signed integer
  61945. ** 5 6 signed integer
  61946. ** 6 8 signed integer
  61947. ** 7 8 IEEE float
  61948. ** 8 0 Integer constant 0
  61949. ** 9 0 Integer constant 1
  61950. ** 10,11 reserved for expansion
  61951. ** N>=12 and even (N-12)/2 BLOB
  61952. ** N>=13 and odd (N-13)/2 text
  61953. **
  61954. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  61955. ** of SQLite will not understand those serial types.
  61956. */
  61957. /*
  61958. ** Return the serial-type for the value stored in pMem.
  61959. */
  61960. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  61961. int flags = pMem->flags;
  61962. int n;
  61963. if( flags&MEM_Null ){
  61964. return 0;
  61965. }
  61966. if( flags&MEM_Int ){
  61967. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  61968. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  61969. i64 i = pMem->u.i;
  61970. u64 u;
  61971. if( i<0 ){
  61972. if( i<(-MAX_6BYTE) ) return 6;
  61973. /* Previous test prevents: u = -(-9223372036854775808) */
  61974. u = -i;
  61975. }else{
  61976. u = i;
  61977. }
  61978. if( u<=127 ){
  61979. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  61980. }
  61981. if( u<=32767 ) return 2;
  61982. if( u<=8388607 ) return 3;
  61983. if( u<=2147483647 ) return 4;
  61984. if( u<=MAX_6BYTE ) return 5;
  61985. return 6;
  61986. }
  61987. if( flags&MEM_Real ){
  61988. return 7;
  61989. }
  61990. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  61991. n = pMem->n;
  61992. if( flags & MEM_Zero ){
  61993. n += pMem->u.nZero;
  61994. }
  61995. assert( n>=0 );
  61996. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  61997. }
  61998. /*
  61999. ** Return the length of the data corresponding to the supplied serial-type.
  62000. */
  62001. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  62002. if( serial_type>=12 ){
  62003. return (serial_type-12)/2;
  62004. }else{
  62005. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  62006. return aSize[serial_type];
  62007. }
  62008. }
  62009. /*
  62010. ** If we are on an architecture with mixed-endian floating
  62011. ** points (ex: ARM7) then swap the lower 4 bytes with the
  62012. ** upper 4 bytes. Return the result.
  62013. **
  62014. ** For most architectures, this is a no-op.
  62015. **
  62016. ** (later): It is reported to me that the mixed-endian problem
  62017. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  62018. ** that early versions of GCC stored the two words of a 64-bit
  62019. ** float in the wrong order. And that error has been propagated
  62020. ** ever since. The blame is not necessarily with GCC, though.
  62021. ** GCC might have just copying the problem from a prior compiler.
  62022. ** I am also told that newer versions of GCC that follow a different
  62023. ** ABI get the byte order right.
  62024. **
  62025. ** Developers using SQLite on an ARM7 should compile and run their
  62026. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  62027. ** enabled, some asserts below will ensure that the byte order of
  62028. ** floating point values is correct.
  62029. **
  62030. ** (2007-08-30) Frank van Vugt has studied this problem closely
  62031. ** and has send his findings to the SQLite developers. Frank
  62032. ** writes that some Linux kernels offer floating point hardware
  62033. ** emulation that uses only 32-bit mantissas instead of a full
  62034. ** 48-bits as required by the IEEE standard. (This is the
  62035. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  62036. ** byte swapping becomes very complicated. To avoid problems,
  62037. ** the necessary byte swapping is carried out using a 64-bit integer
  62038. ** rather than a 64-bit float. Frank assures us that the code here
  62039. ** works for him. We, the developers, have no way to independently
  62040. ** verify this, but Frank seems to know what he is talking about
  62041. ** so we trust him.
  62042. */
  62043. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  62044. static u64 floatSwap(u64 in){
  62045. union {
  62046. u64 r;
  62047. u32 i[2];
  62048. } u;
  62049. u32 t;
  62050. u.r = in;
  62051. t = u.i[0];
  62052. u.i[0] = u.i[1];
  62053. u.i[1] = t;
  62054. return u.r;
  62055. }
  62056. # define swapMixedEndianFloat(X) X = floatSwap(X)
  62057. #else
  62058. # define swapMixedEndianFloat(X)
  62059. #endif
  62060. /*
  62061. ** Write the serialized data blob for the value stored in pMem into
  62062. ** buf. It is assumed that the caller has allocated sufficient space.
  62063. ** Return the number of bytes written.
  62064. **
  62065. ** nBuf is the amount of space left in buf[]. nBuf must always be
  62066. ** large enough to hold the entire field. Except, if the field is
  62067. ** a blob with a zero-filled tail, then buf[] might be just the right
  62068. ** size to hold everything except for the zero-filled tail. If buf[]
  62069. ** is only big enough to hold the non-zero prefix, then only write that
  62070. ** prefix into buf[]. But if buf[] is large enough to hold both the
  62071. ** prefix and the tail then write the prefix and set the tail to all
  62072. ** zeros.
  62073. **
  62074. ** Return the number of bytes actually written into buf[]. The number
  62075. ** of bytes in the zero-filled tail is included in the return value only
  62076. ** if those bytes were zeroed in buf[].
  62077. */
  62078. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
  62079. u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
  62080. u32 len;
  62081. /* Integer and Real */
  62082. if( serial_type<=7 && serial_type>0 ){
  62083. u64 v;
  62084. u32 i;
  62085. if( serial_type==7 ){
  62086. assert( sizeof(v)==sizeof(pMem->r) );
  62087. memcpy(&v, &pMem->r, sizeof(v));
  62088. swapMixedEndianFloat(v);
  62089. }else{
  62090. v = pMem->u.i;
  62091. }
  62092. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  62093. assert( len<=(u32)nBuf );
  62094. while( i-- ){
  62095. buf[i] = (u8)(v&0xFF);
  62096. v >>= 8;
  62097. }
  62098. return len;
  62099. }
  62100. /* String or blob */
  62101. if( serial_type>=12 ){
  62102. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  62103. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  62104. assert( pMem->n<=nBuf );
  62105. len = pMem->n;
  62106. memcpy(buf, pMem->z, len);
  62107. if( pMem->flags & MEM_Zero ){
  62108. len += pMem->u.nZero;
  62109. assert( nBuf>=0 );
  62110. if( len > (u32)nBuf ){
  62111. len = (u32)nBuf;
  62112. }
  62113. memset(&buf[pMem->n], 0, len-pMem->n);
  62114. }
  62115. return len;
  62116. }
  62117. /* NULL or constants 0 or 1 */
  62118. return 0;
  62119. }
  62120. /*
  62121. ** Deserialize the data blob pointed to by buf as serial type serial_type
  62122. ** and store the result in pMem. Return the number of bytes read.
  62123. */
  62124. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  62125. const unsigned char *buf, /* Buffer to deserialize from */
  62126. u32 serial_type, /* Serial type to deserialize */
  62127. Mem *pMem /* Memory cell to write value into */
  62128. ){
  62129. switch( serial_type ){
  62130. case 10: /* Reserved for future use */
  62131. case 11: /* Reserved for future use */
  62132. case 0: { /* NULL */
  62133. pMem->flags = MEM_Null;
  62134. break;
  62135. }
  62136. case 1: { /* 1-byte signed integer */
  62137. pMem->u.i = (signed char)buf[0];
  62138. pMem->flags = MEM_Int;
  62139. return 1;
  62140. }
  62141. case 2: { /* 2-byte signed integer */
  62142. pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
  62143. pMem->flags = MEM_Int;
  62144. return 2;
  62145. }
  62146. case 3: { /* 3-byte signed integer */
  62147. pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
  62148. pMem->flags = MEM_Int;
  62149. return 3;
  62150. }
  62151. case 4: { /* 4-byte signed integer */
  62152. pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  62153. pMem->flags = MEM_Int;
  62154. return 4;
  62155. }
  62156. case 5: { /* 6-byte signed integer */
  62157. u64 x = (((signed char)buf[0])<<8) | buf[1];
  62158. u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
  62159. x = (x<<32) | y;
  62160. pMem->u.i = *(i64*)&x;
  62161. pMem->flags = MEM_Int;
  62162. return 6;
  62163. }
  62164. case 6: /* 8-byte signed integer */
  62165. case 7: { /* IEEE floating point */
  62166. u64 x;
  62167. u32 y;
  62168. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  62169. /* Verify that integers and floating point values use the same
  62170. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  62171. ** defined that 64-bit floating point values really are mixed
  62172. ** endian.
  62173. */
  62174. static const u64 t1 = ((u64)0x3ff00000)<<32;
  62175. static const double r1 = 1.0;
  62176. u64 t2 = t1;
  62177. swapMixedEndianFloat(t2);
  62178. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  62179. #endif
  62180. x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
  62181. y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
  62182. x = (x<<32) | y;
  62183. if( serial_type==6 ){
  62184. pMem->u.i = *(i64*)&x;
  62185. pMem->flags = MEM_Int;
  62186. }else{
  62187. assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
  62188. swapMixedEndianFloat(x);
  62189. memcpy(&pMem->r, &x, sizeof(x));
  62190. pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
  62191. }
  62192. return 8;
  62193. }
  62194. case 8: /* Integer 0 */
  62195. case 9: { /* Integer 1 */
  62196. pMem->u.i = serial_type-8;
  62197. pMem->flags = MEM_Int;
  62198. return 0;
  62199. }
  62200. default: {
  62201. u32 len = (serial_type-12)/2;
  62202. pMem->z = (char *)buf;
  62203. pMem->n = len;
  62204. pMem->xDel = 0;
  62205. if( serial_type&0x01 ){
  62206. pMem->flags = MEM_Str | MEM_Ephem;
  62207. }else{
  62208. pMem->flags = MEM_Blob | MEM_Ephem;
  62209. }
  62210. return len;
  62211. }
  62212. }
  62213. return 0;
  62214. }
  62215. /*
  62216. ** This routine is used to allocate sufficient space for an UnpackedRecord
  62217. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  62218. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  62219. **
  62220. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  62221. ** the unaligned buffer passed via the second and third arguments (presumably
  62222. ** stack space). If the former, then *ppFree is set to a pointer that should
  62223. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  62224. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  62225. ** before returning.
  62226. **
  62227. ** If an OOM error occurs, NULL is returned.
  62228. */
  62229. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  62230. KeyInfo *pKeyInfo, /* Description of the record */
  62231. char *pSpace, /* Unaligned space available */
  62232. int szSpace, /* Size of pSpace[] in bytes */
  62233. char **ppFree /* OUT: Caller should free this pointer */
  62234. ){
  62235. UnpackedRecord *p; /* Unpacked record to return */
  62236. int nOff; /* Increment pSpace by nOff to align it */
  62237. int nByte; /* Number of bytes required for *p */
  62238. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  62239. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  62240. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  62241. */
  62242. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  62243. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  62244. if( nByte>szSpace+nOff ){
  62245. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  62246. *ppFree = (char *)p;
  62247. if( !p ) return 0;
  62248. }else{
  62249. p = (UnpackedRecord*)&pSpace[nOff];
  62250. *ppFree = 0;
  62251. }
  62252. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  62253. assert( pKeyInfo->aSortOrder!=0 );
  62254. p->pKeyInfo = pKeyInfo;
  62255. p->nField = pKeyInfo->nField + 1;
  62256. return p;
  62257. }
  62258. /*
  62259. ** Given the nKey-byte encoding of a record in pKey[], populate the
  62260. ** UnpackedRecord structure indicated by the fourth argument with the
  62261. ** contents of the decoded record.
  62262. */
  62263. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  62264. KeyInfo *pKeyInfo, /* Information about the record format */
  62265. int nKey, /* Size of the binary record */
  62266. const void *pKey, /* The binary record */
  62267. UnpackedRecord *p /* Populate this structure before returning. */
  62268. ){
  62269. const unsigned char *aKey = (const unsigned char *)pKey;
  62270. int d;
  62271. u32 idx; /* Offset in aKey[] to read from */
  62272. u16 u; /* Unsigned loop counter */
  62273. u32 szHdr;
  62274. Mem *pMem = p->aMem;
  62275. p->flags = 0;
  62276. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  62277. idx = getVarint32(aKey, szHdr);
  62278. d = szHdr;
  62279. u = 0;
  62280. while( idx<szHdr && u<p->nField && d<=nKey ){
  62281. u32 serial_type;
  62282. idx += getVarint32(&aKey[idx], serial_type);
  62283. pMem->enc = pKeyInfo->enc;
  62284. pMem->db = pKeyInfo->db;
  62285. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  62286. pMem->zMalloc = 0;
  62287. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  62288. pMem++;
  62289. u++;
  62290. }
  62291. assert( u<=pKeyInfo->nField + 1 );
  62292. p->nField = u;
  62293. }
  62294. /*
  62295. ** This function compares the two table rows or index records
  62296. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  62297. ** or positive integer if key1 is less than, equal to or
  62298. ** greater than key2. The {nKey1, pKey1} key must be a blob
  62299. ** created by th OP_MakeRecord opcode of the VDBE. The pPKey2
  62300. ** key must be a parsed key such as obtained from
  62301. ** sqlite3VdbeParseRecord.
  62302. **
  62303. ** Key1 and Key2 do not have to contain the same number of fields.
  62304. ** The key with fewer fields is usually compares less than the
  62305. ** longer key. However if the UNPACKED_INCRKEY flags in pPKey2 is set
  62306. ** and the common prefixes are equal, then key1 is less than key2.
  62307. ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
  62308. ** equal, then the keys are considered to be equal and
  62309. ** the parts beyond the common prefix are ignored.
  62310. */
  62311. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  62312. int nKey1, const void *pKey1, /* Left key */
  62313. UnpackedRecord *pPKey2 /* Right key */
  62314. ){
  62315. u32 d1; /* Offset into aKey[] of next data element */
  62316. u32 idx1; /* Offset into aKey[] of next header element */
  62317. u32 szHdr1; /* Number of bytes in header */
  62318. int i = 0;
  62319. int rc = 0;
  62320. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  62321. KeyInfo *pKeyInfo;
  62322. Mem mem1;
  62323. pKeyInfo = pPKey2->pKeyInfo;
  62324. mem1.enc = pKeyInfo->enc;
  62325. mem1.db = pKeyInfo->db;
  62326. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  62327. VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
  62328. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  62329. ** We could initialize it, as shown here, to silence those complaints.
  62330. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  62331. ** the unnecessary initialization has a measurable negative performance
  62332. ** impact, since this routine is a very high runner. And so, we choose
  62333. ** to ignore the compiler warnings and leave this variable uninitialized.
  62334. */
  62335. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  62336. idx1 = getVarint32(aKey1, szHdr1);
  62337. d1 = szHdr1;
  62338. assert( pKeyInfo->nField+1>=pPKey2->nField );
  62339. assert( pKeyInfo->aSortOrder!=0 );
  62340. while( idx1<szHdr1 && i<pPKey2->nField ){
  62341. u32 serial_type1;
  62342. /* Read the serial types for the next element in each key. */
  62343. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  62344. /* Verify that there is enough key space remaining to avoid
  62345. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  62346. ** always be greater than or equal to the amount of required key space.
  62347. ** Use that approximation to avoid the more expensive call to
  62348. ** sqlite3VdbeSerialTypeLen() in the common case.
  62349. */
  62350. if( d1+serial_type1+2>(u32)nKey1
  62351. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  62352. ){
  62353. break;
  62354. }
  62355. /* Extract the values to be compared.
  62356. */
  62357. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  62358. /* Do the comparison
  62359. */
  62360. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  62361. if( rc!=0 ){
  62362. assert( mem1.zMalloc==0 ); /* See comment below */
  62363. /* Invert the result if we are using DESC sort order. */
  62364. if( pKeyInfo->aSortOrder[i] ){
  62365. rc = -rc;
  62366. }
  62367. /* If the PREFIX_SEARCH flag is set and all fields except the final
  62368. ** rowid field were equal, then clear the PREFIX_SEARCH flag and set
  62369. ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
  62370. ** This is used by the OP_IsUnique opcode.
  62371. */
  62372. if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
  62373. assert( idx1==szHdr1 && rc );
  62374. assert( mem1.flags & MEM_Int );
  62375. pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
  62376. pPKey2->rowid = mem1.u.i;
  62377. }
  62378. return rc;
  62379. }
  62380. i++;
  62381. }
  62382. /* No memory allocation is ever used on mem1. Prove this using
  62383. ** the following assert(). If the assert() fails, it indicates a
  62384. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  62385. */
  62386. assert( mem1.zMalloc==0 );
  62387. /* rc==0 here means that one of the keys ran out of fields and
  62388. ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
  62389. ** flag is set, then break the tie by treating key2 as larger.
  62390. ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
  62391. ** are considered to be equal. Otherwise, the longer key is the
  62392. ** larger. As it happens, the pPKey2 will always be the longer
  62393. ** if there is a difference.
  62394. */
  62395. assert( rc==0 );
  62396. if( pPKey2->flags & UNPACKED_INCRKEY ){
  62397. rc = -1;
  62398. }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
  62399. /* Leave rc==0 */
  62400. }else if( idx1<szHdr1 ){
  62401. rc = 1;
  62402. }
  62403. return rc;
  62404. }
  62405. /*
  62406. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  62407. ** Read the rowid (the last field in the record) and store it in *rowid.
  62408. ** Return SQLITE_OK if everything works, or an error code otherwise.
  62409. **
  62410. ** pCur might be pointing to text obtained from a corrupt database file.
  62411. ** So the content cannot be trusted. Do appropriate checks on the content.
  62412. */
  62413. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  62414. i64 nCellKey = 0;
  62415. int rc;
  62416. u32 szHdr; /* Size of the header */
  62417. u32 typeRowid; /* Serial type of the rowid */
  62418. u32 lenRowid; /* Size of the rowid */
  62419. Mem m, v;
  62420. UNUSED_PARAMETER(db);
  62421. /* Get the size of the index entry. Only indices entries of less
  62422. ** than 2GiB are support - anything large must be database corruption.
  62423. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  62424. ** this code can safely assume that nCellKey is 32-bits
  62425. */
  62426. assert( sqlite3BtreeCursorIsValid(pCur) );
  62427. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62428. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62429. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  62430. /* Read in the complete content of the index entry */
  62431. memset(&m, 0, sizeof(m));
  62432. rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
  62433. if( rc ){
  62434. return rc;
  62435. }
  62436. /* The index entry must begin with a header size */
  62437. (void)getVarint32((u8*)m.z, szHdr);
  62438. testcase( szHdr==3 );
  62439. testcase( szHdr==m.n );
  62440. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  62441. goto idx_rowid_corruption;
  62442. }
  62443. /* The last field of the index should be an integer - the ROWID.
  62444. ** Verify that the last entry really is an integer. */
  62445. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  62446. testcase( typeRowid==1 );
  62447. testcase( typeRowid==2 );
  62448. testcase( typeRowid==3 );
  62449. testcase( typeRowid==4 );
  62450. testcase( typeRowid==5 );
  62451. testcase( typeRowid==6 );
  62452. testcase( typeRowid==8 );
  62453. testcase( typeRowid==9 );
  62454. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  62455. goto idx_rowid_corruption;
  62456. }
  62457. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  62458. testcase( (u32)m.n==szHdr+lenRowid );
  62459. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  62460. goto idx_rowid_corruption;
  62461. }
  62462. /* Fetch the integer off the end of the index record */
  62463. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  62464. *rowid = v.u.i;
  62465. sqlite3VdbeMemRelease(&m);
  62466. return SQLITE_OK;
  62467. /* Jump here if database corruption is detected after m has been
  62468. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  62469. idx_rowid_corruption:
  62470. testcase( m.zMalloc!=0 );
  62471. sqlite3VdbeMemRelease(&m);
  62472. return SQLITE_CORRUPT_BKPT;
  62473. }
  62474. /*
  62475. ** Compare the key of the index entry that cursor pC is pointing to against
  62476. ** the key string in pUnpacked. Write into *pRes a number
  62477. ** that is negative, zero, or positive if pC is less than, equal to,
  62478. ** or greater than pUnpacked. Return SQLITE_OK on success.
  62479. **
  62480. ** pUnpacked is either created without a rowid or is truncated so that it
  62481. ** omits the rowid at the end. The rowid at the end of the index entry
  62482. ** is ignored as well. Hence, this routine only compares the prefixes
  62483. ** of the keys prior to the final rowid, not the entire key.
  62484. */
  62485. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  62486. VdbeCursor *pC, /* The cursor to compare against */
  62487. UnpackedRecord *pUnpacked, /* Unpacked version of key to compare against */
  62488. int *res /* Write the comparison result here */
  62489. ){
  62490. i64 nCellKey = 0;
  62491. int rc;
  62492. BtCursor *pCur = pC->pCursor;
  62493. Mem m;
  62494. assert( sqlite3BtreeCursorIsValid(pCur) );
  62495. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62496. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62497. /* nCellKey will always be between 0 and 0xffffffff because of the say
  62498. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  62499. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  62500. *res = 0;
  62501. return SQLITE_CORRUPT_BKPT;
  62502. }
  62503. memset(&m, 0, sizeof(m));
  62504. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
  62505. if( rc ){
  62506. return rc;
  62507. }
  62508. assert( pUnpacked->flags & UNPACKED_PREFIX_MATCH );
  62509. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  62510. sqlite3VdbeMemRelease(&m);
  62511. return SQLITE_OK;
  62512. }
  62513. /*
  62514. ** This routine sets the value to be returned by subsequent calls to
  62515. ** sqlite3_changes() on the database handle 'db'.
  62516. */
  62517. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  62518. assert( sqlite3_mutex_held(db->mutex) );
  62519. db->nChange = nChange;
  62520. db->nTotalChange += nChange;
  62521. }
  62522. /*
  62523. ** Set a flag in the vdbe to update the change counter when it is finalised
  62524. ** or reset.
  62525. */
  62526. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  62527. v->changeCntOn = 1;
  62528. }
  62529. /*
  62530. ** Mark every prepared statement associated with a database connection
  62531. ** as expired.
  62532. **
  62533. ** An expired statement means that recompilation of the statement is
  62534. ** recommend. Statements expire when things happen that make their
  62535. ** programs obsolete. Removing user-defined functions or collating
  62536. ** sequences, or changing an authorization function are the types of
  62537. ** things that make prepared statements obsolete.
  62538. */
  62539. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  62540. Vdbe *p;
  62541. for(p = db->pVdbe; p; p=p->pNext){
  62542. p->expired = 1;
  62543. }
  62544. }
  62545. /*
  62546. ** Return the database associated with the Vdbe.
  62547. */
  62548. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  62549. return v->db;
  62550. }
  62551. /*
  62552. ** Return a pointer to an sqlite3_value structure containing the value bound
  62553. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  62554. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  62555. ** constants) to the value before returning it.
  62556. **
  62557. ** The returned value must be freed by the caller using sqlite3ValueFree().
  62558. */
  62559. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  62560. assert( iVar>0 );
  62561. if( v ){
  62562. Mem *pMem = &v->aVar[iVar-1];
  62563. if( 0==(pMem->flags & MEM_Null) ){
  62564. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  62565. if( pRet ){
  62566. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  62567. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  62568. sqlite3VdbeMemStoreType((Mem *)pRet);
  62569. }
  62570. return pRet;
  62571. }
  62572. }
  62573. return 0;
  62574. }
  62575. /*
  62576. ** Configure SQL variable iVar so that binding a new value to it signals
  62577. ** to sqlite3_reoptimize() that re-preparing the statement may result
  62578. ** in a better query plan.
  62579. */
  62580. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  62581. assert( iVar>0 );
  62582. if( iVar>32 ){
  62583. v->expmask = 0xffffffff;
  62584. }else{
  62585. v->expmask |= ((u32)1 << (iVar-1));
  62586. }
  62587. }
  62588. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62589. /*
  62590. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  62591. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  62592. ** in memory obtained from sqlite3DbMalloc).
  62593. */
  62594. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  62595. sqlite3 *db = p->db;
  62596. sqlite3DbFree(db, p->zErrMsg);
  62597. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  62598. sqlite3_free(pVtab->zErrMsg);
  62599. pVtab->zErrMsg = 0;
  62600. }
  62601. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  62602. /************** End of vdbeaux.c *********************************************/
  62603. /************** Begin file vdbeapi.c *****************************************/
  62604. /*
  62605. ** 2004 May 26
  62606. **
  62607. ** The author disclaims copyright to this source code. In place of
  62608. ** a legal notice, here is a blessing:
  62609. **
  62610. ** May you do good and not evil.
  62611. ** May you find forgiveness for yourself and forgive others.
  62612. ** May you share freely, never taking more than you give.
  62613. **
  62614. *************************************************************************
  62615. **
  62616. ** This file contains code use to implement APIs that are part of the
  62617. ** VDBE.
  62618. */
  62619. #ifndef SQLITE_OMIT_DEPRECATED
  62620. /*
  62621. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  62622. ** to be recompiled. A statement needs to be recompiled whenever the
  62623. ** execution environment changes in a way that would alter the program
  62624. ** that sqlite3_prepare() generates. For example, if new functions or
  62625. ** collating sequences are registered or if an authorizer function is
  62626. ** added or changed.
  62627. */
  62628. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  62629. Vdbe *p = (Vdbe*)pStmt;
  62630. return p==0 || p->expired;
  62631. }
  62632. #endif
  62633. /*
  62634. ** Check on a Vdbe to make sure it has not been finalized. Log
  62635. ** an error and return true if it has been finalized (or is otherwise
  62636. ** invalid). Return false if it is ok.
  62637. */
  62638. static int vdbeSafety(Vdbe *p){
  62639. if( p->db==0 ){
  62640. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  62641. return 1;
  62642. }else{
  62643. return 0;
  62644. }
  62645. }
  62646. static int vdbeSafetyNotNull(Vdbe *p){
  62647. if( p==0 ){
  62648. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  62649. return 1;
  62650. }else{
  62651. return vdbeSafety(p);
  62652. }
  62653. }
  62654. /*
  62655. ** The following routine destroys a virtual machine that is created by
  62656. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  62657. ** success/failure code that describes the result of executing the virtual
  62658. ** machine.
  62659. **
  62660. ** This routine sets the error code and string returned by
  62661. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62662. */
  62663. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  62664. int rc;
  62665. if( pStmt==0 ){
  62666. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  62667. ** pointer is a harmless no-op. */
  62668. rc = SQLITE_OK;
  62669. }else{
  62670. Vdbe *v = (Vdbe*)pStmt;
  62671. sqlite3 *db = v->db;
  62672. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  62673. sqlite3_mutex_enter(db->mutex);
  62674. rc = sqlite3VdbeFinalize(v);
  62675. rc = sqlite3ApiExit(db, rc);
  62676. sqlite3LeaveMutexAndCloseZombie(db);
  62677. }
  62678. return rc;
  62679. }
  62680. /*
  62681. ** Terminate the current execution of an SQL statement and reset it
  62682. ** back to its starting state so that it can be reused. A success code from
  62683. ** the prior execution is returned.
  62684. **
  62685. ** This routine sets the error code and string returned by
  62686. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62687. */
  62688. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  62689. int rc;
  62690. if( pStmt==0 ){
  62691. rc = SQLITE_OK;
  62692. }else{
  62693. Vdbe *v = (Vdbe*)pStmt;
  62694. sqlite3_mutex_enter(v->db->mutex);
  62695. rc = sqlite3VdbeReset(v);
  62696. sqlite3VdbeRewind(v);
  62697. assert( (rc & (v->db->errMask))==rc );
  62698. rc = sqlite3ApiExit(v->db, rc);
  62699. sqlite3_mutex_leave(v->db->mutex);
  62700. }
  62701. return rc;
  62702. }
  62703. /*
  62704. ** Set all the parameters in the compiled SQL statement to NULL.
  62705. */
  62706. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  62707. int i;
  62708. int rc = SQLITE_OK;
  62709. Vdbe *p = (Vdbe*)pStmt;
  62710. #if SQLITE_THREADSAFE
  62711. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  62712. #endif
  62713. sqlite3_mutex_enter(mutex);
  62714. for(i=0; i<p->nVar; i++){
  62715. sqlite3VdbeMemRelease(&p->aVar[i]);
  62716. p->aVar[i].flags = MEM_Null;
  62717. }
  62718. if( p->isPrepareV2 && p->expmask ){
  62719. p->expired = 1;
  62720. }
  62721. sqlite3_mutex_leave(mutex);
  62722. return rc;
  62723. }
  62724. /**************************** sqlite3_value_ *******************************
  62725. ** The following routines extract information from a Mem or sqlite3_value
  62726. ** structure.
  62727. */
  62728. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  62729. Mem *p = (Mem*)pVal;
  62730. if( p->flags & (MEM_Blob|MEM_Str) ){
  62731. sqlite3VdbeMemExpandBlob(p);
  62732. p->flags &= ~MEM_Str;
  62733. p->flags |= MEM_Blob;
  62734. return p->n ? p->z : 0;
  62735. }else{
  62736. return sqlite3_value_text(pVal);
  62737. }
  62738. }
  62739. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  62740. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  62741. }
  62742. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  62743. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  62744. }
  62745. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  62746. return sqlite3VdbeRealValue((Mem*)pVal);
  62747. }
  62748. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  62749. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  62750. }
  62751. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  62752. return sqlite3VdbeIntValue((Mem*)pVal);
  62753. }
  62754. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  62755. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  62756. }
  62757. #ifndef SQLITE_OMIT_UTF16
  62758. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  62759. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  62760. }
  62761. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  62762. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  62763. }
  62764. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  62765. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  62766. }
  62767. #endif /* SQLITE_OMIT_UTF16 */
  62768. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  62769. return pVal->type;
  62770. }
  62771. /**************************** sqlite3_result_ *******************************
  62772. ** The following routines are used by user-defined functions to specify
  62773. ** the function result.
  62774. **
  62775. ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
  62776. ** result as a string or blob but if the string or blob is too large, it
  62777. ** then sets the error code to SQLITE_TOOBIG
  62778. */
  62779. static void setResultStrOrError(
  62780. sqlite3_context *pCtx, /* Function context */
  62781. const char *z, /* String pointer */
  62782. int n, /* Bytes in string, or negative */
  62783. u8 enc, /* Encoding of z. 0 for BLOBs */
  62784. void (*xDel)(void*) /* Destructor function */
  62785. ){
  62786. if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
  62787. sqlite3_result_error_toobig(pCtx);
  62788. }
  62789. }
  62790. SQLITE_API void sqlite3_result_blob(
  62791. sqlite3_context *pCtx,
  62792. const void *z,
  62793. int n,
  62794. void (*xDel)(void *)
  62795. ){
  62796. assert( n>=0 );
  62797. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62798. setResultStrOrError(pCtx, z, n, 0, xDel);
  62799. }
  62800. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  62801. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62802. sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
  62803. }
  62804. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  62805. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62806. pCtx->isError = SQLITE_ERROR;
  62807. pCtx->fErrorOrAux = 1;
  62808. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  62809. }
  62810. #ifndef SQLITE_OMIT_UTF16
  62811. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  62812. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62813. pCtx->isError = SQLITE_ERROR;
  62814. pCtx->fErrorOrAux = 1;
  62815. sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  62816. }
  62817. #endif
  62818. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  62819. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62820. sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
  62821. }
  62822. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  62823. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62824. sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
  62825. }
  62826. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  62827. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62828. sqlite3VdbeMemSetNull(&pCtx->s);
  62829. }
  62830. SQLITE_API void sqlite3_result_text(
  62831. sqlite3_context *pCtx,
  62832. const char *z,
  62833. int n,
  62834. void (*xDel)(void *)
  62835. ){
  62836. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62837. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  62838. }
  62839. #ifndef SQLITE_OMIT_UTF16
  62840. SQLITE_API void sqlite3_result_text16(
  62841. sqlite3_context *pCtx,
  62842. const void *z,
  62843. int n,
  62844. void (*xDel)(void *)
  62845. ){
  62846. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62847. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  62848. }
  62849. SQLITE_API void sqlite3_result_text16be(
  62850. sqlite3_context *pCtx,
  62851. const void *z,
  62852. int n,
  62853. void (*xDel)(void *)
  62854. ){
  62855. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62856. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  62857. }
  62858. SQLITE_API void sqlite3_result_text16le(
  62859. sqlite3_context *pCtx,
  62860. const void *z,
  62861. int n,
  62862. void (*xDel)(void *)
  62863. ){
  62864. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62865. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  62866. }
  62867. #endif /* SQLITE_OMIT_UTF16 */
  62868. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  62869. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62870. sqlite3VdbeMemCopy(&pCtx->s, pValue);
  62871. }
  62872. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  62873. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62874. sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
  62875. }
  62876. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  62877. pCtx->isError = errCode;
  62878. pCtx->fErrorOrAux = 1;
  62879. if( pCtx->s.flags & MEM_Null ){
  62880. sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1,
  62881. SQLITE_UTF8, SQLITE_STATIC);
  62882. }
  62883. }
  62884. /* Force an SQLITE_TOOBIG error. */
  62885. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  62886. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62887. pCtx->isError = SQLITE_TOOBIG;
  62888. pCtx->fErrorOrAux = 1;
  62889. sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1,
  62890. SQLITE_UTF8, SQLITE_STATIC);
  62891. }
  62892. /* An SQLITE_NOMEM error. */
  62893. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  62894. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  62895. sqlite3VdbeMemSetNull(&pCtx->s);
  62896. pCtx->isError = SQLITE_NOMEM;
  62897. pCtx->fErrorOrAux = 1;
  62898. pCtx->s.db->mallocFailed = 1;
  62899. }
  62900. /*
  62901. ** This function is called after a transaction has been committed. It
  62902. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  62903. */
  62904. static int doWalCallbacks(sqlite3 *db){
  62905. int rc = SQLITE_OK;
  62906. #ifndef SQLITE_OMIT_WAL
  62907. int i;
  62908. for(i=0; i<db->nDb; i++){
  62909. Btree *pBt = db->aDb[i].pBt;
  62910. if( pBt ){
  62911. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  62912. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  62913. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  62914. }
  62915. }
  62916. }
  62917. #endif
  62918. return rc;
  62919. }
  62920. /*
  62921. ** Execute the statement pStmt, either until a row of data is ready, the
  62922. ** statement is completely executed or an error occurs.
  62923. **
  62924. ** This routine implements the bulk of the logic behind the sqlite_step()
  62925. ** API. The only thing omitted is the automatic recompile if a
  62926. ** schema change has occurred. That detail is handled by the
  62927. ** outer sqlite3_step() wrapper procedure.
  62928. */
  62929. static int sqlite3Step(Vdbe *p){
  62930. sqlite3 *db;
  62931. int rc;
  62932. assert(p);
  62933. if( p->magic!=VDBE_MAGIC_RUN ){
  62934. /* We used to require that sqlite3_reset() be called before retrying
  62935. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  62936. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  62937. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  62938. ** This "automatic-reset" change is not technically an incompatibility,
  62939. ** since any application that receives an SQLITE_MISUSE is broken by
  62940. ** definition.
  62941. **
  62942. ** Nevertheless, some published applications that were originally written
  62943. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  62944. ** returns, and those were broken by the automatic-reset change. As a
  62945. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  62946. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  62947. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  62948. ** or SQLITE_BUSY error.
  62949. */
  62950. #ifdef SQLITE_OMIT_AUTORESET
  62951. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  62952. sqlite3_reset((sqlite3_stmt*)p);
  62953. }else{
  62954. return SQLITE_MISUSE_BKPT;
  62955. }
  62956. #else
  62957. sqlite3_reset((sqlite3_stmt*)p);
  62958. #endif
  62959. }
  62960. /* Check that malloc() has not failed. If it has, return early. */
  62961. db = p->db;
  62962. if( db->mallocFailed ){
  62963. p->rc = SQLITE_NOMEM;
  62964. return SQLITE_NOMEM;
  62965. }
  62966. if( p->pc<=0 && p->expired ){
  62967. p->rc = SQLITE_SCHEMA;
  62968. rc = SQLITE_ERROR;
  62969. goto end_of_step;
  62970. }
  62971. if( p->pc<0 ){
  62972. /* If there are no other statements currently running, then
  62973. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  62974. ** from interrupting a statement that has not yet started.
  62975. */
  62976. if( db->nVdbeActive==0 ){
  62977. db->u1.isInterrupted = 0;
  62978. }
  62979. assert( db->nVdbeWrite>0 || db->autoCommit==0
  62980. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  62981. );
  62982. #ifndef SQLITE_OMIT_TRACE
  62983. if( db->xProfile && !db->init.busy ){
  62984. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  62985. }
  62986. #endif
  62987. db->nVdbeActive++;
  62988. if( p->readOnly==0 ) db->nVdbeWrite++;
  62989. if( p->bIsReader ) db->nVdbeRead++;
  62990. p->pc = 0;
  62991. }
  62992. #ifndef SQLITE_OMIT_EXPLAIN
  62993. if( p->explain ){
  62994. rc = sqlite3VdbeList(p);
  62995. }else
  62996. #endif /* SQLITE_OMIT_EXPLAIN */
  62997. {
  62998. db->nVdbeExec++;
  62999. rc = sqlite3VdbeExec(p);
  63000. db->nVdbeExec--;
  63001. }
  63002. #ifndef SQLITE_OMIT_TRACE
  63003. /* Invoke the profile callback if there is one
  63004. */
  63005. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  63006. sqlite3_int64 iNow;
  63007. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  63008. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  63009. }
  63010. #endif
  63011. if( rc==SQLITE_DONE ){
  63012. assert( p->rc==SQLITE_OK );
  63013. p->rc = doWalCallbacks(db);
  63014. if( p->rc!=SQLITE_OK ){
  63015. rc = SQLITE_ERROR;
  63016. }
  63017. }
  63018. db->errCode = rc;
  63019. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  63020. p->rc = SQLITE_NOMEM;
  63021. }
  63022. end_of_step:
  63023. /* At this point local variable rc holds the value that should be
  63024. ** returned if this statement was compiled using the legacy
  63025. ** sqlite3_prepare() interface. According to the docs, this can only
  63026. ** be one of the values in the first assert() below. Variable p->rc
  63027. ** contains the value that would be returned if sqlite3_finalize()
  63028. ** were called on statement p.
  63029. */
  63030. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  63031. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  63032. );
  63033. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  63034. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  63035. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  63036. ** error has occurred, then return the error code in p->rc to the
  63037. ** caller. Set the error code in the database handle to the same value.
  63038. */
  63039. rc = sqlite3VdbeTransferError(p);
  63040. }
  63041. return (rc&db->errMask);
  63042. }
  63043. /*
  63044. ** This is the top-level implementation of sqlite3_step(). Call
  63045. ** sqlite3Step() to do most of the work. If a schema error occurs,
  63046. ** call sqlite3Reprepare() and try again.
  63047. */
  63048. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  63049. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  63050. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  63051. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  63052. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  63053. sqlite3 *db; /* The database connection */
  63054. if( vdbeSafetyNotNull(v) ){
  63055. return SQLITE_MISUSE_BKPT;
  63056. }
  63057. db = v->db;
  63058. sqlite3_mutex_enter(db->mutex);
  63059. v->doingRerun = 0;
  63060. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  63061. && cnt++ < SQLITE_MAX_SCHEMA_RETRY
  63062. && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
  63063. sqlite3_reset(pStmt);
  63064. v->doingRerun = 1;
  63065. assert( v->expired==0 );
  63066. }
  63067. if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
  63068. /* This case occurs after failing to recompile an sql statement.
  63069. ** The error message from the SQL compiler has already been loaded
  63070. ** into the database handle. This block copies the error message
  63071. ** from the database handle into the statement and sets the statement
  63072. ** program counter to 0 to ensure that when the statement is
  63073. ** finalized or reset the parser error message is available via
  63074. ** sqlite3_errmsg() and sqlite3_errcode().
  63075. */
  63076. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  63077. sqlite3DbFree(db, v->zErrMsg);
  63078. if( !db->mallocFailed ){
  63079. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  63080. v->rc = rc2;
  63081. } else {
  63082. v->zErrMsg = 0;
  63083. v->rc = rc = SQLITE_NOMEM;
  63084. }
  63085. }
  63086. rc = sqlite3ApiExit(db, rc);
  63087. sqlite3_mutex_leave(db->mutex);
  63088. return rc;
  63089. }
  63090. /*
  63091. ** Extract the user data from a sqlite3_context structure and return a
  63092. ** pointer to it.
  63093. */
  63094. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  63095. assert( p && p->pFunc );
  63096. return p->pFunc->pUserData;
  63097. }
  63098. /*
  63099. ** Extract the user data from a sqlite3_context structure and return a
  63100. ** pointer to it.
  63101. **
  63102. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  63103. ** returns a copy of the pointer to the database connection (the 1st
  63104. ** parameter) of the sqlite3_create_function() and
  63105. ** sqlite3_create_function16() routines that originally registered the
  63106. ** application defined function.
  63107. */
  63108. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  63109. assert( p && p->pFunc );
  63110. return p->s.db;
  63111. }
  63112. /*
  63113. ** Return the current time for a statement
  63114. */
  63115. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  63116. Vdbe *v = p->pVdbe;
  63117. int rc;
  63118. if( v->iCurrentTime==0 ){
  63119. rc = sqlite3OsCurrentTimeInt64(p->s.db->pVfs, &v->iCurrentTime);
  63120. if( rc ) v->iCurrentTime = 0;
  63121. }
  63122. return v->iCurrentTime;
  63123. }
  63124. /*
  63125. ** The following is the implementation of an SQL function that always
  63126. ** fails with an error message stating that the function is used in the
  63127. ** wrong context. The sqlite3_overload_function() API might construct
  63128. ** SQL function that use this routine so that the functions will exist
  63129. ** for name resolution but are actually overloaded by the xFindFunction
  63130. ** method of virtual tables.
  63131. */
  63132. SQLITE_PRIVATE void sqlite3InvalidFunction(
  63133. sqlite3_context *context, /* The function calling context */
  63134. int NotUsed, /* Number of arguments to the function */
  63135. sqlite3_value **NotUsed2 /* Value of each argument */
  63136. ){
  63137. const char *zName = context->pFunc->zName;
  63138. char *zErr;
  63139. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63140. zErr = sqlite3_mprintf(
  63141. "unable to use function %s in the requested context", zName);
  63142. sqlite3_result_error(context, zErr, -1);
  63143. sqlite3_free(zErr);
  63144. }
  63145. /*
  63146. ** Allocate or return the aggregate context for a user function. A new
  63147. ** context is allocated on the first call. Subsequent calls return the
  63148. ** same context that was returned on prior calls.
  63149. */
  63150. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  63151. Mem *pMem;
  63152. assert( p && p->pFunc && p->pFunc->xStep );
  63153. assert( sqlite3_mutex_held(p->s.db->mutex) );
  63154. pMem = p->pMem;
  63155. testcase( nByte<0 );
  63156. if( (pMem->flags & MEM_Agg)==0 ){
  63157. if( nByte<=0 ){
  63158. sqlite3VdbeMemReleaseExternal(pMem);
  63159. pMem->flags = MEM_Null;
  63160. pMem->z = 0;
  63161. }else{
  63162. sqlite3VdbeMemGrow(pMem, nByte, 0);
  63163. pMem->flags = MEM_Agg;
  63164. pMem->u.pDef = p->pFunc;
  63165. if( pMem->z ){
  63166. memset(pMem->z, 0, nByte);
  63167. }
  63168. }
  63169. }
  63170. return (void*)pMem->z;
  63171. }
  63172. /*
  63173. ** Return the auxilary data pointer, if any, for the iArg'th argument to
  63174. ** the user-function defined by pCtx.
  63175. */
  63176. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  63177. AuxData *pAuxData;
  63178. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  63179. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63180. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63181. }
  63182. return (pAuxData ? pAuxData->pAux : 0);
  63183. }
  63184. /*
  63185. ** Set the auxilary data pointer and delete function, for the iArg'th
  63186. ** argument to the user-function defined by pCtx. Any previous value is
  63187. ** deleted by calling the delete function specified when it was set.
  63188. */
  63189. SQLITE_API void sqlite3_set_auxdata(
  63190. sqlite3_context *pCtx,
  63191. int iArg,
  63192. void *pAux,
  63193. void (*xDelete)(void*)
  63194. ){
  63195. AuxData *pAuxData;
  63196. Vdbe *pVdbe = pCtx->pVdbe;
  63197. assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
  63198. if( iArg<0 ) goto failed;
  63199. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63200. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63201. }
  63202. if( pAuxData==0 ){
  63203. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  63204. if( !pAuxData ) goto failed;
  63205. pAuxData->iOp = pCtx->iOp;
  63206. pAuxData->iArg = iArg;
  63207. pAuxData->pNext = pVdbe->pAuxData;
  63208. pVdbe->pAuxData = pAuxData;
  63209. if( pCtx->fErrorOrAux==0 ){
  63210. pCtx->isError = 0;
  63211. pCtx->fErrorOrAux = 1;
  63212. }
  63213. }else if( pAuxData->xDelete ){
  63214. pAuxData->xDelete(pAuxData->pAux);
  63215. }
  63216. pAuxData->pAux = pAux;
  63217. pAuxData->xDelete = xDelete;
  63218. return;
  63219. failed:
  63220. if( xDelete ){
  63221. xDelete(pAux);
  63222. }
  63223. }
  63224. #ifndef SQLITE_OMIT_DEPRECATED
  63225. /*
  63226. ** Return the number of times the Step function of a aggregate has been
  63227. ** called.
  63228. **
  63229. ** This function is deprecated. Do not use it for new code. It is
  63230. ** provide only to avoid breaking legacy code. New aggregate function
  63231. ** implementations should keep their own counts within their aggregate
  63232. ** context.
  63233. */
  63234. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  63235. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  63236. return p->pMem->n;
  63237. }
  63238. #endif
  63239. /*
  63240. ** Return the number of columns in the result set for the statement pStmt.
  63241. */
  63242. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  63243. Vdbe *pVm = (Vdbe *)pStmt;
  63244. return pVm ? pVm->nResColumn : 0;
  63245. }
  63246. /*
  63247. ** Return the number of values available from the current row of the
  63248. ** currently executing statement pStmt.
  63249. */
  63250. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  63251. Vdbe *pVm = (Vdbe *)pStmt;
  63252. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  63253. return pVm->nResColumn;
  63254. }
  63255. /*
  63256. ** Check to see if column iCol of the given statement is valid. If
  63257. ** it is, return a pointer to the Mem for the value of that column.
  63258. ** If iCol is not valid, return a pointer to a Mem which has a value
  63259. ** of NULL.
  63260. */
  63261. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  63262. Vdbe *pVm;
  63263. Mem *pOut;
  63264. pVm = (Vdbe *)pStmt;
  63265. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  63266. sqlite3_mutex_enter(pVm->db->mutex);
  63267. pOut = &pVm->pResultSet[i];
  63268. }else{
  63269. /* If the value passed as the second argument is out of range, return
  63270. ** a pointer to the following static Mem object which contains the
  63271. ** value SQL NULL. Even though the Mem structure contains an element
  63272. ** of type i64, on certain architectures (x86) with certain compiler
  63273. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  63274. ** instead of an 8-byte one. This all works fine, except that when
  63275. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  63276. ** that a Mem structure is located on an 8-byte boundary. To prevent
  63277. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  63278. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  63279. ** __attribute__((aligned(8))) macro. */
  63280. static const Mem nullMem
  63281. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  63282. __attribute__((aligned(8)))
  63283. #endif
  63284. = {0, "", (double)0, {0}, 0, MEM_Null, SQLITE_NULL, 0,
  63285. #ifdef SQLITE_DEBUG
  63286. 0, 0, /* pScopyFrom, pFiller */
  63287. #endif
  63288. 0, 0 };
  63289. if( pVm && ALWAYS(pVm->db) ){
  63290. sqlite3_mutex_enter(pVm->db->mutex);
  63291. sqlite3Error(pVm->db, SQLITE_RANGE, 0);
  63292. }
  63293. pOut = (Mem*)&nullMem;
  63294. }
  63295. return pOut;
  63296. }
  63297. /*
  63298. ** This function is called after invoking an sqlite3_value_XXX function on a
  63299. ** column value (i.e. a value returned by evaluating an SQL expression in the
  63300. ** select list of a SELECT statement) that may cause a malloc() failure. If
  63301. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  63302. ** code of statement pStmt set to SQLITE_NOMEM.
  63303. **
  63304. ** Specifically, this is called from within:
  63305. **
  63306. ** sqlite3_column_int()
  63307. ** sqlite3_column_int64()
  63308. ** sqlite3_column_text()
  63309. ** sqlite3_column_text16()
  63310. ** sqlite3_column_real()
  63311. ** sqlite3_column_bytes()
  63312. ** sqlite3_column_bytes16()
  63313. ** sqiite3_column_blob()
  63314. */
  63315. static void columnMallocFailure(sqlite3_stmt *pStmt)
  63316. {
  63317. /* If malloc() failed during an encoding conversion within an
  63318. ** sqlite3_column_XXX API, then set the return code of the statement to
  63319. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  63320. ** and _finalize() will return NOMEM.
  63321. */
  63322. Vdbe *p = (Vdbe *)pStmt;
  63323. if( p ){
  63324. p->rc = sqlite3ApiExit(p->db, p->rc);
  63325. sqlite3_mutex_leave(p->db->mutex);
  63326. }
  63327. }
  63328. /**************************** sqlite3_column_ *******************************
  63329. ** The following routines are used to access elements of the current row
  63330. ** in the result set.
  63331. */
  63332. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  63333. const void *val;
  63334. val = sqlite3_value_blob( columnMem(pStmt,i) );
  63335. /* Even though there is no encoding conversion, value_blob() might
  63336. ** need to call malloc() to expand the result of a zeroblob()
  63337. ** expression.
  63338. */
  63339. columnMallocFailure(pStmt);
  63340. return val;
  63341. }
  63342. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  63343. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  63344. columnMallocFailure(pStmt);
  63345. return val;
  63346. }
  63347. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  63348. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  63349. columnMallocFailure(pStmt);
  63350. return val;
  63351. }
  63352. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  63353. double val = sqlite3_value_double( columnMem(pStmt,i) );
  63354. columnMallocFailure(pStmt);
  63355. return val;
  63356. }
  63357. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  63358. int val = sqlite3_value_int( columnMem(pStmt,i) );
  63359. columnMallocFailure(pStmt);
  63360. return val;
  63361. }
  63362. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  63363. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  63364. columnMallocFailure(pStmt);
  63365. return val;
  63366. }
  63367. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  63368. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  63369. columnMallocFailure(pStmt);
  63370. return val;
  63371. }
  63372. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  63373. Mem *pOut = columnMem(pStmt, i);
  63374. if( pOut->flags&MEM_Static ){
  63375. pOut->flags &= ~MEM_Static;
  63376. pOut->flags |= MEM_Ephem;
  63377. }
  63378. columnMallocFailure(pStmt);
  63379. return (sqlite3_value *)pOut;
  63380. }
  63381. #ifndef SQLITE_OMIT_UTF16
  63382. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  63383. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  63384. columnMallocFailure(pStmt);
  63385. return val;
  63386. }
  63387. #endif /* SQLITE_OMIT_UTF16 */
  63388. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  63389. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  63390. columnMallocFailure(pStmt);
  63391. return iType;
  63392. }
  63393. /*
  63394. ** Convert the N-th element of pStmt->pColName[] into a string using
  63395. ** xFunc() then return that string. If N is out of range, return 0.
  63396. **
  63397. ** There are up to 5 names for each column. useType determines which
  63398. ** name is returned. Here are the names:
  63399. **
  63400. ** 0 The column name as it should be displayed for output
  63401. ** 1 The datatype name for the column
  63402. ** 2 The name of the database that the column derives from
  63403. ** 3 The name of the table that the column derives from
  63404. ** 4 The name of the table column that the result column derives from
  63405. **
  63406. ** If the result is not a simple column reference (if it is an expression
  63407. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  63408. */
  63409. static const void *columnName(
  63410. sqlite3_stmt *pStmt,
  63411. int N,
  63412. const void *(*xFunc)(Mem*),
  63413. int useType
  63414. ){
  63415. const void *ret = 0;
  63416. Vdbe *p = (Vdbe *)pStmt;
  63417. int n;
  63418. sqlite3 *db = p->db;
  63419. assert( db!=0 );
  63420. n = sqlite3_column_count(pStmt);
  63421. if( N<n && N>=0 ){
  63422. N += useType*n;
  63423. sqlite3_mutex_enter(db->mutex);
  63424. assert( db->mallocFailed==0 );
  63425. ret = xFunc(&p->aColName[N]);
  63426. /* A malloc may have failed inside of the xFunc() call. If this
  63427. ** is the case, clear the mallocFailed flag and return NULL.
  63428. */
  63429. if( db->mallocFailed ){
  63430. db->mallocFailed = 0;
  63431. ret = 0;
  63432. }
  63433. sqlite3_mutex_leave(db->mutex);
  63434. }
  63435. return ret;
  63436. }
  63437. /*
  63438. ** Return the name of the Nth column of the result set returned by SQL
  63439. ** statement pStmt.
  63440. */
  63441. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  63442. return columnName(
  63443. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  63444. }
  63445. #ifndef SQLITE_OMIT_UTF16
  63446. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  63447. return columnName(
  63448. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  63449. }
  63450. #endif
  63451. /*
  63452. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  63453. ** not define OMIT_DECLTYPE.
  63454. */
  63455. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  63456. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  63457. and SQLITE_ENABLE_COLUMN_METADATA"
  63458. #endif
  63459. #ifndef SQLITE_OMIT_DECLTYPE
  63460. /*
  63461. ** Return the column declaration type (if applicable) of the 'i'th column
  63462. ** of the result set of SQL statement pStmt.
  63463. */
  63464. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  63465. return columnName(
  63466. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  63467. }
  63468. #ifndef SQLITE_OMIT_UTF16
  63469. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  63470. return columnName(
  63471. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  63472. }
  63473. #endif /* SQLITE_OMIT_UTF16 */
  63474. #endif /* SQLITE_OMIT_DECLTYPE */
  63475. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  63476. /*
  63477. ** Return the name of the database from which a result column derives.
  63478. ** NULL is returned if the result column is an expression or constant or
  63479. ** anything else which is not an unabiguous reference to a database column.
  63480. */
  63481. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  63482. return columnName(
  63483. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  63484. }
  63485. #ifndef SQLITE_OMIT_UTF16
  63486. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  63487. return columnName(
  63488. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  63489. }
  63490. #endif /* SQLITE_OMIT_UTF16 */
  63491. /*
  63492. ** Return the name of the table from which a result column derives.
  63493. ** NULL is returned if the result column is an expression or constant or
  63494. ** anything else which is not an unabiguous reference to a database column.
  63495. */
  63496. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  63497. return columnName(
  63498. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  63499. }
  63500. #ifndef SQLITE_OMIT_UTF16
  63501. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  63502. return columnName(
  63503. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  63504. }
  63505. #endif /* SQLITE_OMIT_UTF16 */
  63506. /*
  63507. ** Return the name of the table column from which a result column derives.
  63508. ** NULL is returned if the result column is an expression or constant or
  63509. ** anything else which is not an unabiguous reference to a database column.
  63510. */
  63511. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  63512. return columnName(
  63513. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  63514. }
  63515. #ifndef SQLITE_OMIT_UTF16
  63516. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  63517. return columnName(
  63518. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  63519. }
  63520. #endif /* SQLITE_OMIT_UTF16 */
  63521. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  63522. /******************************* sqlite3_bind_ ***************************
  63523. **
  63524. ** Routines used to attach values to wildcards in a compiled SQL statement.
  63525. */
  63526. /*
  63527. ** Unbind the value bound to variable i in virtual machine p. This is the
  63528. ** the same as binding a NULL value to the column. If the "i" parameter is
  63529. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  63530. **
  63531. ** A successful evaluation of this routine acquires the mutex on p.
  63532. ** the mutex is released if any kind of error occurs.
  63533. **
  63534. ** The error code stored in database p->db is overwritten with the return
  63535. ** value in any case.
  63536. */
  63537. static int vdbeUnbind(Vdbe *p, int i){
  63538. Mem *pVar;
  63539. if( vdbeSafetyNotNull(p) ){
  63540. return SQLITE_MISUSE_BKPT;
  63541. }
  63542. sqlite3_mutex_enter(p->db->mutex);
  63543. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  63544. sqlite3Error(p->db, SQLITE_MISUSE, 0);
  63545. sqlite3_mutex_leave(p->db->mutex);
  63546. sqlite3_log(SQLITE_MISUSE,
  63547. "bind on a busy prepared statement: [%s]", p->zSql);
  63548. return SQLITE_MISUSE_BKPT;
  63549. }
  63550. if( i<1 || i>p->nVar ){
  63551. sqlite3Error(p->db, SQLITE_RANGE, 0);
  63552. sqlite3_mutex_leave(p->db->mutex);
  63553. return SQLITE_RANGE;
  63554. }
  63555. i--;
  63556. pVar = &p->aVar[i];
  63557. sqlite3VdbeMemRelease(pVar);
  63558. pVar->flags = MEM_Null;
  63559. sqlite3Error(p->db, SQLITE_OK, 0);
  63560. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  63561. ** binding a new value to this variable invalidates the current query plan.
  63562. **
  63563. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  63564. ** parameter in the WHERE clause might influence the choice of query plan
  63565. ** for a statement, then the statement will be automatically recompiled,
  63566. ** as if there had been a schema change, on the first sqlite3_step() call
  63567. ** following any change to the bindings of that parameter.
  63568. */
  63569. if( p->isPrepareV2 &&
  63570. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  63571. ){
  63572. p->expired = 1;
  63573. }
  63574. return SQLITE_OK;
  63575. }
  63576. /*
  63577. ** Bind a text or BLOB value.
  63578. */
  63579. static int bindText(
  63580. sqlite3_stmt *pStmt, /* The statement to bind against */
  63581. int i, /* Index of the parameter to bind */
  63582. const void *zData, /* Pointer to the data to be bound */
  63583. int nData, /* Number of bytes of data to be bound */
  63584. void (*xDel)(void*), /* Destructor for the data */
  63585. u8 encoding /* Encoding for the data */
  63586. ){
  63587. Vdbe *p = (Vdbe *)pStmt;
  63588. Mem *pVar;
  63589. int rc;
  63590. rc = vdbeUnbind(p, i);
  63591. if( rc==SQLITE_OK ){
  63592. if( zData!=0 ){
  63593. pVar = &p->aVar[i-1];
  63594. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  63595. if( rc==SQLITE_OK && encoding!=0 ){
  63596. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  63597. }
  63598. sqlite3Error(p->db, rc, 0);
  63599. rc = sqlite3ApiExit(p->db, rc);
  63600. }
  63601. sqlite3_mutex_leave(p->db->mutex);
  63602. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  63603. xDel((void*)zData);
  63604. }
  63605. return rc;
  63606. }
  63607. /*
  63608. ** Bind a blob value to an SQL statement variable.
  63609. */
  63610. SQLITE_API int sqlite3_bind_blob(
  63611. sqlite3_stmt *pStmt,
  63612. int i,
  63613. const void *zData,
  63614. int nData,
  63615. void (*xDel)(void*)
  63616. ){
  63617. return bindText(pStmt, i, zData, nData, xDel, 0);
  63618. }
  63619. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  63620. int rc;
  63621. Vdbe *p = (Vdbe *)pStmt;
  63622. rc = vdbeUnbind(p, i);
  63623. if( rc==SQLITE_OK ){
  63624. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  63625. sqlite3_mutex_leave(p->db->mutex);
  63626. }
  63627. return rc;
  63628. }
  63629. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  63630. return sqlite3_bind_int64(p, i, (i64)iValue);
  63631. }
  63632. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  63633. int rc;
  63634. Vdbe *p = (Vdbe *)pStmt;
  63635. rc = vdbeUnbind(p, i);
  63636. if( rc==SQLITE_OK ){
  63637. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  63638. sqlite3_mutex_leave(p->db->mutex);
  63639. }
  63640. return rc;
  63641. }
  63642. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  63643. int rc;
  63644. Vdbe *p = (Vdbe*)pStmt;
  63645. rc = vdbeUnbind(p, i);
  63646. if( rc==SQLITE_OK ){
  63647. sqlite3_mutex_leave(p->db->mutex);
  63648. }
  63649. return rc;
  63650. }
  63651. SQLITE_API int sqlite3_bind_text(
  63652. sqlite3_stmt *pStmt,
  63653. int i,
  63654. const char *zData,
  63655. int nData,
  63656. void (*xDel)(void*)
  63657. ){
  63658. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  63659. }
  63660. #ifndef SQLITE_OMIT_UTF16
  63661. SQLITE_API int sqlite3_bind_text16(
  63662. sqlite3_stmt *pStmt,
  63663. int i,
  63664. const void *zData,
  63665. int nData,
  63666. void (*xDel)(void*)
  63667. ){
  63668. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  63669. }
  63670. #endif /* SQLITE_OMIT_UTF16 */
  63671. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  63672. int rc;
  63673. switch( pValue->type ){
  63674. case SQLITE_INTEGER: {
  63675. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  63676. break;
  63677. }
  63678. case SQLITE_FLOAT: {
  63679. rc = sqlite3_bind_double(pStmt, i, pValue->r);
  63680. break;
  63681. }
  63682. case SQLITE_BLOB: {
  63683. if( pValue->flags & MEM_Zero ){
  63684. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  63685. }else{
  63686. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  63687. }
  63688. break;
  63689. }
  63690. case SQLITE_TEXT: {
  63691. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  63692. pValue->enc);
  63693. break;
  63694. }
  63695. default: {
  63696. rc = sqlite3_bind_null(pStmt, i);
  63697. break;
  63698. }
  63699. }
  63700. return rc;
  63701. }
  63702. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  63703. int rc;
  63704. Vdbe *p = (Vdbe *)pStmt;
  63705. rc = vdbeUnbind(p, i);
  63706. if( rc==SQLITE_OK ){
  63707. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  63708. sqlite3_mutex_leave(p->db->mutex);
  63709. }
  63710. return rc;
  63711. }
  63712. /*
  63713. ** Return the number of wildcards that can be potentially bound to.
  63714. ** This routine is added to support DBD::SQLite.
  63715. */
  63716. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  63717. Vdbe *p = (Vdbe*)pStmt;
  63718. return p ? p->nVar : 0;
  63719. }
  63720. /*
  63721. ** Return the name of a wildcard parameter. Return NULL if the index
  63722. ** is out of range or if the wildcard is unnamed.
  63723. **
  63724. ** The result is always UTF-8.
  63725. */
  63726. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  63727. Vdbe *p = (Vdbe*)pStmt;
  63728. if( p==0 || i<1 || i>p->nzVar ){
  63729. return 0;
  63730. }
  63731. return p->azVar[i-1];
  63732. }
  63733. /*
  63734. ** Given a wildcard parameter name, return the index of the variable
  63735. ** with that name. If there is no variable with the given name,
  63736. ** return 0.
  63737. */
  63738. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  63739. int i;
  63740. if( p==0 ){
  63741. return 0;
  63742. }
  63743. if( zName ){
  63744. for(i=0; i<p->nzVar; i++){
  63745. const char *z = p->azVar[i];
  63746. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  63747. return i+1;
  63748. }
  63749. }
  63750. }
  63751. return 0;
  63752. }
  63753. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  63754. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  63755. }
  63756. /*
  63757. ** Transfer all bindings from the first statement over to the second.
  63758. */
  63759. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  63760. Vdbe *pFrom = (Vdbe*)pFromStmt;
  63761. Vdbe *pTo = (Vdbe*)pToStmt;
  63762. int i;
  63763. assert( pTo->db==pFrom->db );
  63764. assert( pTo->nVar==pFrom->nVar );
  63765. sqlite3_mutex_enter(pTo->db->mutex);
  63766. for(i=0; i<pFrom->nVar; i++){
  63767. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  63768. }
  63769. sqlite3_mutex_leave(pTo->db->mutex);
  63770. return SQLITE_OK;
  63771. }
  63772. #ifndef SQLITE_OMIT_DEPRECATED
  63773. /*
  63774. ** Deprecated external interface. Internal/core SQLite code
  63775. ** should call sqlite3TransferBindings.
  63776. **
  63777. ** Is is misuse to call this routine with statements from different
  63778. ** database connections. But as this is a deprecated interface, we
  63779. ** will not bother to check for that condition.
  63780. **
  63781. ** If the two statements contain a different number of bindings, then
  63782. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  63783. ** SQLITE_OK is returned.
  63784. */
  63785. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  63786. Vdbe *pFrom = (Vdbe*)pFromStmt;
  63787. Vdbe *pTo = (Vdbe*)pToStmt;
  63788. if( pFrom->nVar!=pTo->nVar ){
  63789. return SQLITE_ERROR;
  63790. }
  63791. if( pTo->isPrepareV2 && pTo->expmask ){
  63792. pTo->expired = 1;
  63793. }
  63794. if( pFrom->isPrepareV2 && pFrom->expmask ){
  63795. pFrom->expired = 1;
  63796. }
  63797. return sqlite3TransferBindings(pFromStmt, pToStmt);
  63798. }
  63799. #endif
  63800. /*
  63801. ** Return the sqlite3* database handle to which the prepared statement given
  63802. ** in the argument belongs. This is the same database handle that was
  63803. ** the first argument to the sqlite3_prepare() that was used to create
  63804. ** the statement in the first place.
  63805. */
  63806. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  63807. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  63808. }
  63809. /*
  63810. ** Return true if the prepared statement is guaranteed to not modify the
  63811. ** database.
  63812. */
  63813. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  63814. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  63815. }
  63816. /*
  63817. ** Return true if the prepared statement is in need of being reset.
  63818. */
  63819. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  63820. Vdbe *v = (Vdbe*)pStmt;
  63821. return v!=0 && v->pc>0 && v->magic==VDBE_MAGIC_RUN;
  63822. }
  63823. /*
  63824. ** Return a pointer to the next prepared statement after pStmt associated
  63825. ** with database connection pDb. If pStmt is NULL, return the first
  63826. ** prepared statement for the database connection. Return NULL if there
  63827. ** are no more.
  63828. */
  63829. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  63830. sqlite3_stmt *pNext;
  63831. sqlite3_mutex_enter(pDb->mutex);
  63832. if( pStmt==0 ){
  63833. pNext = (sqlite3_stmt*)pDb->pVdbe;
  63834. }else{
  63835. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  63836. }
  63837. sqlite3_mutex_leave(pDb->mutex);
  63838. return pNext;
  63839. }
  63840. /*
  63841. ** Return the value of a status counter for a prepared statement
  63842. */
  63843. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  63844. Vdbe *pVdbe = (Vdbe*)pStmt;
  63845. u32 v = pVdbe->aCounter[op];
  63846. if( resetFlag ) pVdbe->aCounter[op] = 0;
  63847. return (int)v;
  63848. }
  63849. /************** End of vdbeapi.c *********************************************/
  63850. /************** Begin file vdbetrace.c ***************************************/
  63851. /*
  63852. ** 2009 November 25
  63853. **
  63854. ** The author disclaims copyright to this source code. In place of
  63855. ** a legal notice, here is a blessing:
  63856. **
  63857. ** May you do good and not evil.
  63858. ** May you find forgiveness for yourself and forgive others.
  63859. ** May you share freely, never taking more than you give.
  63860. **
  63861. *************************************************************************
  63862. **
  63863. ** This file contains code used to insert the values of host parameters
  63864. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  63865. **
  63866. ** The Vdbe parse-tree explainer is also found here.
  63867. */
  63868. #ifndef SQLITE_OMIT_TRACE
  63869. /*
  63870. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  63871. ** bytes in this text up to but excluding the first character in
  63872. ** a host parameter. If the text contains no host parameters, return
  63873. ** the total number of bytes in the text.
  63874. */
  63875. static int findNextHostParameter(const char *zSql, int *pnToken){
  63876. int tokenType;
  63877. int nTotal = 0;
  63878. int n;
  63879. *pnToken = 0;
  63880. while( zSql[0] ){
  63881. n = sqlite3GetToken((u8*)zSql, &tokenType);
  63882. assert( n>0 && tokenType!=TK_ILLEGAL );
  63883. if( tokenType==TK_VARIABLE ){
  63884. *pnToken = n;
  63885. break;
  63886. }
  63887. nTotal += n;
  63888. zSql += n;
  63889. }
  63890. return nTotal;
  63891. }
  63892. /*
  63893. ** This function returns a pointer to a nul-terminated string in memory
  63894. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  63895. ** string contains a copy of zRawSql but with host parameters expanded to
  63896. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  63897. ** then the returned string holds a copy of zRawSql with "-- " prepended
  63898. ** to each line of text.
  63899. **
  63900. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  63901. ** then long strings and blobs are truncated to that many bytes. This
  63902. ** can be used to prevent unreasonably large trace strings when dealing
  63903. ** with large (multi-megabyte) strings and blobs.
  63904. **
  63905. ** The calling function is responsible for making sure the memory returned
  63906. ** is eventually freed.
  63907. **
  63908. ** ALGORITHM: Scan the input string looking for host parameters in any of
  63909. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  63910. ** string literals, quoted identifier names, and comments. For text forms,
  63911. ** the host parameter index is found by scanning the perpared
  63912. ** statement for the corresponding OP_Variable opcode. Once the host
  63913. ** parameter index is known, locate the value in p->aVar[]. Then render
  63914. ** the value as a literal in place of the host parameter name.
  63915. */
  63916. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  63917. Vdbe *p, /* The prepared statement being evaluated */
  63918. const char *zRawSql /* Raw text of the SQL statement */
  63919. ){
  63920. sqlite3 *db; /* The database connection */
  63921. int idx = 0; /* Index of a host parameter */
  63922. int nextIndex = 1; /* Index of next ? host parameter */
  63923. int n; /* Length of a token prefix */
  63924. int nToken; /* Length of the parameter token */
  63925. int i; /* Loop counter */
  63926. Mem *pVar; /* Value of a host parameter */
  63927. StrAccum out; /* Accumulate the output here */
  63928. char zBase[100]; /* Initial working space */
  63929. db = p->db;
  63930. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  63931. db->aLimit[SQLITE_LIMIT_LENGTH]);
  63932. out.db = db;
  63933. if( db->nVdbeExec>1 ){
  63934. while( *zRawSql ){
  63935. const char *zStart = zRawSql;
  63936. while( *(zRawSql++)!='\n' && *zRawSql );
  63937. sqlite3StrAccumAppend(&out, "-- ", 3);
  63938. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  63939. }
  63940. }else{
  63941. while( zRawSql[0] ){
  63942. n = findNextHostParameter(zRawSql, &nToken);
  63943. assert( n>0 );
  63944. sqlite3StrAccumAppend(&out, zRawSql, n);
  63945. zRawSql += n;
  63946. assert( zRawSql[0] || nToken==0 );
  63947. if( nToken==0 ) break;
  63948. if( zRawSql[0]=='?' ){
  63949. if( nToken>1 ){
  63950. assert( sqlite3Isdigit(zRawSql[1]) );
  63951. sqlite3GetInt32(&zRawSql[1], &idx);
  63952. }else{
  63953. idx = nextIndex;
  63954. }
  63955. }else{
  63956. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  63957. testcase( zRawSql[0]==':' );
  63958. testcase( zRawSql[0]=='$' );
  63959. testcase( zRawSql[0]=='@' );
  63960. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  63961. assert( idx>0 );
  63962. }
  63963. zRawSql += nToken;
  63964. nextIndex = idx + 1;
  63965. assert( idx>0 && idx<=p->nVar );
  63966. pVar = &p->aVar[idx-1];
  63967. if( pVar->flags & MEM_Null ){
  63968. sqlite3StrAccumAppend(&out, "NULL", 4);
  63969. }else if( pVar->flags & MEM_Int ){
  63970. sqlite3XPrintf(&out, "%lld", pVar->u.i);
  63971. }else if( pVar->flags & MEM_Real ){
  63972. sqlite3XPrintf(&out, "%!.15g", pVar->r);
  63973. }else if( pVar->flags & MEM_Str ){
  63974. int nOut; /* Number of bytes of the string text to include in output */
  63975. #ifndef SQLITE_OMIT_UTF16
  63976. u8 enc = ENC(db);
  63977. Mem utf8;
  63978. if( enc!=SQLITE_UTF8 ){
  63979. memset(&utf8, 0, sizeof(utf8));
  63980. utf8.db = db;
  63981. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  63982. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  63983. pVar = &utf8;
  63984. }
  63985. #endif
  63986. nOut = pVar->n;
  63987. #ifdef SQLITE_TRACE_SIZE_LIMIT
  63988. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  63989. nOut = SQLITE_TRACE_SIZE_LIMIT;
  63990. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  63991. }
  63992. #endif
  63993. sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
  63994. #ifdef SQLITE_TRACE_SIZE_LIMIT
  63995. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  63996. #endif
  63997. #ifndef SQLITE_OMIT_UTF16
  63998. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  63999. #endif
  64000. }else if( pVar->flags & MEM_Zero ){
  64001. sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
  64002. }else{
  64003. int nOut; /* Number of bytes of the blob to include in output */
  64004. assert( pVar->flags & MEM_Blob );
  64005. sqlite3StrAccumAppend(&out, "x'", 2);
  64006. nOut = pVar->n;
  64007. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64008. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  64009. #endif
  64010. for(i=0; i<nOut; i++){
  64011. sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
  64012. }
  64013. sqlite3StrAccumAppend(&out, "'", 1);
  64014. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64015. if( nOut<pVar->n ) sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
  64016. #endif
  64017. }
  64018. }
  64019. }
  64020. return sqlite3StrAccumFinish(&out);
  64021. }
  64022. #endif /* #ifndef SQLITE_OMIT_TRACE */
  64023. /*****************************************************************************
  64024. ** The following code implements the data-structure explaining logic
  64025. ** for the Vdbe.
  64026. */
  64027. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  64028. /*
  64029. ** Allocate a new Explain object
  64030. */
  64031. SQLITE_PRIVATE void sqlite3ExplainBegin(Vdbe *pVdbe){
  64032. if( pVdbe ){
  64033. Explain *p;
  64034. sqlite3BeginBenignMalloc();
  64035. p = (Explain *)sqlite3MallocZero( sizeof(Explain) );
  64036. if( p ){
  64037. p->pVdbe = pVdbe;
  64038. sqlite3_free(pVdbe->pExplain);
  64039. pVdbe->pExplain = p;
  64040. sqlite3StrAccumInit(&p->str, p->zBase, sizeof(p->zBase),
  64041. SQLITE_MAX_LENGTH);
  64042. p->str.useMalloc = 2;
  64043. }else{
  64044. sqlite3EndBenignMalloc();
  64045. }
  64046. }
  64047. }
  64048. /*
  64049. ** Return true if the Explain ends with a new-line.
  64050. */
  64051. static int endsWithNL(Explain *p){
  64052. return p && p->str.zText && p->str.nChar
  64053. && p->str.zText[p->str.nChar-1]=='\n';
  64054. }
  64055. /*
  64056. ** Append text to the indentation
  64057. */
  64058. SQLITE_PRIVATE void sqlite3ExplainPrintf(Vdbe *pVdbe, const char *zFormat, ...){
  64059. Explain *p;
  64060. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  64061. va_list ap;
  64062. if( p->nIndent && endsWithNL(p) ){
  64063. int n = p->nIndent;
  64064. if( n>ArraySize(p->aIndent) ) n = ArraySize(p->aIndent);
  64065. sqlite3AppendSpace(&p->str, p->aIndent[n-1]);
  64066. }
  64067. va_start(ap, zFormat);
  64068. sqlite3VXPrintf(&p->str, 1, zFormat, ap);
  64069. va_end(ap);
  64070. }
  64071. }
  64072. /*
  64073. ** Append a '\n' if there is not already one.
  64074. */
  64075. SQLITE_PRIVATE void sqlite3ExplainNL(Vdbe *pVdbe){
  64076. Explain *p;
  64077. if( pVdbe && (p = pVdbe->pExplain)!=0 && !endsWithNL(p) ){
  64078. sqlite3StrAccumAppend(&p->str, "\n", 1);
  64079. }
  64080. }
  64081. /*
  64082. ** Push a new indentation level. Subsequent lines will be indented
  64083. ** so that they begin at the current cursor position.
  64084. */
  64085. SQLITE_PRIVATE void sqlite3ExplainPush(Vdbe *pVdbe){
  64086. Explain *p;
  64087. if( pVdbe && (p = pVdbe->pExplain)!=0 ){
  64088. if( p->str.zText && p->nIndent<ArraySize(p->aIndent) ){
  64089. const char *z = p->str.zText;
  64090. int i = p->str.nChar-1;
  64091. int x;
  64092. while( i>=0 && z[i]!='\n' ){ i--; }
  64093. x = (p->str.nChar - 1) - i;
  64094. if( p->nIndent && x<p->aIndent[p->nIndent-1] ){
  64095. x = p->aIndent[p->nIndent-1];
  64096. }
  64097. p->aIndent[p->nIndent] = x;
  64098. }
  64099. p->nIndent++;
  64100. }
  64101. }
  64102. /*
  64103. ** Pop the indentation stack by one level.
  64104. */
  64105. SQLITE_PRIVATE void sqlite3ExplainPop(Vdbe *p){
  64106. if( p && p->pExplain ) p->pExplain->nIndent--;
  64107. }
  64108. /*
  64109. ** Free the indentation structure
  64110. */
  64111. SQLITE_PRIVATE void sqlite3ExplainFinish(Vdbe *pVdbe){
  64112. if( pVdbe && pVdbe->pExplain ){
  64113. sqlite3_free(pVdbe->zExplain);
  64114. sqlite3ExplainNL(pVdbe);
  64115. pVdbe->zExplain = sqlite3StrAccumFinish(&pVdbe->pExplain->str);
  64116. sqlite3_free(pVdbe->pExplain);
  64117. pVdbe->pExplain = 0;
  64118. sqlite3EndBenignMalloc();
  64119. }
  64120. }
  64121. /*
  64122. ** Return the explanation of a virtual machine.
  64123. */
  64124. SQLITE_PRIVATE const char *sqlite3VdbeExplanation(Vdbe *pVdbe){
  64125. return (pVdbe && pVdbe->zExplain) ? pVdbe->zExplain : 0;
  64126. }
  64127. #endif /* defined(SQLITE_DEBUG) */
  64128. /************** End of vdbetrace.c *******************************************/
  64129. /************** Begin file vdbe.c ********************************************/
  64130. /*
  64131. ** 2001 September 15
  64132. **
  64133. ** The author disclaims copyright to this source code. In place of
  64134. ** a legal notice, here is a blessing:
  64135. **
  64136. ** May you do good and not evil.
  64137. ** May you find forgiveness for yourself and forgive others.
  64138. ** May you share freely, never taking more than you give.
  64139. **
  64140. *************************************************************************
  64141. ** The code in this file implements execution method of the
  64142. ** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  64143. ** handles housekeeping details such as creating and deleting
  64144. ** VDBE instances. This file is solely interested in executing
  64145. ** the VDBE program.
  64146. **
  64147. ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
  64148. ** to a VDBE.
  64149. **
  64150. ** The SQL parser generates a program which is then executed by
  64151. ** the VDBE to do the work of the SQL statement. VDBE programs are
  64152. ** similar in form to assembly language. The program consists of
  64153. ** a linear sequence of operations. Each operation has an opcode
  64154. ** and 5 operands. Operands P1, P2, and P3 are integers. Operand P4
  64155. ** is a null-terminated string. Operand P5 is an unsigned character.
  64156. ** Few opcodes use all 5 operands.
  64157. **
  64158. ** Computation results are stored on a set of registers numbered beginning
  64159. ** with 1 and going up to Vdbe.nMem. Each register can store
  64160. ** either an integer, a null-terminated string, a floating point
  64161. ** number, or the SQL "NULL" value. An implicit conversion from one
  64162. ** type to the other occurs as necessary.
  64163. **
  64164. ** Most of the code in this file is taken up by the sqlite3VdbeExec()
  64165. ** function which does the work of interpreting a VDBE program.
  64166. ** But other routines are also provided to help in building up
  64167. ** a program instruction by instruction.
  64168. **
  64169. ** Various scripts scan this source file in order to generate HTML
  64170. ** documentation, headers files, or other derived files. The formatting
  64171. ** of the code in this file is, therefore, important. See other comments
  64172. ** in this file for details. If in doubt, do not deviate from existing
  64173. ** commenting and indentation practices when changing or adding code.
  64174. */
  64175. /*
  64176. ** Invoke this macro on memory cells just prior to changing the
  64177. ** value of the cell. This macro verifies that shallow copies are
  64178. ** not misused.
  64179. */
  64180. #ifdef SQLITE_DEBUG
  64181. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  64182. #else
  64183. # define memAboutToChange(P,M)
  64184. #endif
  64185. /*
  64186. ** The following global variable is incremented every time a cursor
  64187. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  64188. ** procedures use this information to make sure that indices are
  64189. ** working correctly. This variable has no function other than to
  64190. ** help verify the correct operation of the library.
  64191. */
  64192. #ifdef SQLITE_TEST
  64193. SQLITE_API int sqlite3_search_count = 0;
  64194. #endif
  64195. /*
  64196. ** When this global variable is positive, it gets decremented once before
  64197. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  64198. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  64199. **
  64200. ** This facility is used for testing purposes only. It does not function
  64201. ** in an ordinary build.
  64202. */
  64203. #ifdef SQLITE_TEST
  64204. SQLITE_API int sqlite3_interrupt_count = 0;
  64205. #endif
  64206. /*
  64207. ** The next global variable is incremented each type the OP_Sort opcode
  64208. ** is executed. The test procedures use this information to make sure that
  64209. ** sorting is occurring or not occurring at appropriate times. This variable
  64210. ** has no function other than to help verify the correct operation of the
  64211. ** library.
  64212. */
  64213. #ifdef SQLITE_TEST
  64214. SQLITE_API int sqlite3_sort_count = 0;
  64215. #endif
  64216. /*
  64217. ** The next global variable records the size of the largest MEM_Blob
  64218. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  64219. ** use this information to make sure that the zero-blob functionality
  64220. ** is working correctly. This variable has no function other than to
  64221. ** help verify the correct operation of the library.
  64222. */
  64223. #ifdef SQLITE_TEST
  64224. SQLITE_API int sqlite3_max_blobsize = 0;
  64225. static void updateMaxBlobsize(Mem *p){
  64226. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  64227. sqlite3_max_blobsize = p->n;
  64228. }
  64229. }
  64230. #endif
  64231. /*
  64232. ** The next global variable is incremented each type the OP_Found opcode
  64233. ** is executed. This is used to test whether or not the foreign key
  64234. ** operation implemented using OP_FkIsZero is working. This variable
  64235. ** has no function other than to help verify the correct operation of the
  64236. ** library.
  64237. */
  64238. #ifdef SQLITE_TEST
  64239. SQLITE_API int sqlite3_found_count = 0;
  64240. #endif
  64241. /*
  64242. ** Test a register to see if it exceeds the current maximum blob size.
  64243. ** If it does, record the new maximum blob size.
  64244. */
  64245. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  64246. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  64247. #else
  64248. # define UPDATE_MAX_BLOBSIZE(P)
  64249. #endif
  64250. /*
  64251. ** Convert the given register into a string if it isn't one
  64252. ** already. Return non-zero if a malloc() fails.
  64253. */
  64254. #define Stringify(P, enc) \
  64255. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
  64256. { goto no_mem; }
  64257. /*
  64258. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  64259. ** a pointer to a dynamically allocated string where some other entity
  64260. ** is responsible for deallocating that string. Because the register
  64261. ** does not control the string, it might be deleted without the register
  64262. ** knowing it.
  64263. **
  64264. ** This routine converts an ephemeral string into a dynamically allocated
  64265. ** string that the register itself controls. In other words, it
  64266. ** converts an MEM_Ephem string into an MEM_Dyn string.
  64267. */
  64268. #define Deephemeralize(P) \
  64269. if( ((P)->flags&MEM_Ephem)!=0 \
  64270. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  64271. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  64272. # define isSorter(x) ((x)->pSorter!=0)
  64273. /*
  64274. ** Argument pMem points at a register that will be passed to a
  64275. ** user-defined function or returned to the user as the result of a query.
  64276. ** This routine sets the pMem->type variable used by the sqlite3_value_*()
  64277. ** routines.
  64278. */
  64279. SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
  64280. int flags = pMem->flags;
  64281. if( flags & MEM_Null ){
  64282. pMem->type = SQLITE_NULL;
  64283. }
  64284. else if( flags & MEM_Int ){
  64285. pMem->type = SQLITE_INTEGER;
  64286. }
  64287. else if( flags & MEM_Real ){
  64288. pMem->type = SQLITE_FLOAT;
  64289. }
  64290. else if( flags & MEM_Str ){
  64291. pMem->type = SQLITE_TEXT;
  64292. }else{
  64293. pMem->type = SQLITE_BLOB;
  64294. }
  64295. }
  64296. /*
  64297. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  64298. ** if we run out of memory.
  64299. */
  64300. static VdbeCursor *allocateCursor(
  64301. Vdbe *p, /* The virtual machine */
  64302. int iCur, /* Index of the new VdbeCursor */
  64303. int nField, /* Number of fields in the table or index */
  64304. int iDb, /* Database the cursor belongs to, or -1 */
  64305. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  64306. ){
  64307. /* Find the memory cell that will be used to store the blob of memory
  64308. ** required for this VdbeCursor structure. It is convenient to use a
  64309. ** vdbe memory cell to manage the memory allocation required for a
  64310. ** VdbeCursor structure for the following reasons:
  64311. **
  64312. ** * Sometimes cursor numbers are used for a couple of different
  64313. ** purposes in a vdbe program. The different uses might require
  64314. ** different sized allocations. Memory cells provide growable
  64315. ** allocations.
  64316. **
  64317. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  64318. ** be freed lazily via the sqlite3_release_memory() API. This
  64319. ** minimizes the number of malloc calls made by the system.
  64320. **
  64321. ** Memory cells for cursors are allocated at the top of the address
  64322. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  64323. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  64324. */
  64325. Mem *pMem = &p->aMem[p->nMem-iCur];
  64326. int nByte;
  64327. VdbeCursor *pCx = 0;
  64328. nByte =
  64329. ROUND8(sizeof(VdbeCursor)) +
  64330. (isBtreeCursor?sqlite3BtreeCursorSize():0) +
  64331. 2*nField*sizeof(u32);
  64332. assert( iCur<p->nCursor );
  64333. if( p->apCsr[iCur] ){
  64334. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  64335. p->apCsr[iCur] = 0;
  64336. }
  64337. if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
  64338. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  64339. memset(pCx, 0, sizeof(VdbeCursor));
  64340. pCx->iDb = iDb;
  64341. pCx->nField = nField;
  64342. if( nField ){
  64343. pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
  64344. }
  64345. if( isBtreeCursor ){
  64346. pCx->pCursor = (BtCursor*)
  64347. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
  64348. sqlite3BtreeCursorZero(pCx->pCursor);
  64349. }
  64350. }
  64351. return pCx;
  64352. }
  64353. /*
  64354. ** Try to convert a value into a numeric representation if we can
  64355. ** do so without loss of information. In other words, if the string
  64356. ** looks like a number, convert it into a number. If it does not
  64357. ** look like a number, leave it alone.
  64358. */
  64359. static void applyNumericAffinity(Mem *pRec){
  64360. if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
  64361. double rValue;
  64362. i64 iValue;
  64363. u8 enc = pRec->enc;
  64364. if( (pRec->flags&MEM_Str)==0 ) return;
  64365. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  64366. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  64367. pRec->u.i = iValue;
  64368. pRec->flags |= MEM_Int;
  64369. }else{
  64370. pRec->r = rValue;
  64371. pRec->flags |= MEM_Real;
  64372. }
  64373. }
  64374. }
  64375. /*
  64376. ** Processing is determine by the affinity parameter:
  64377. **
  64378. ** SQLITE_AFF_INTEGER:
  64379. ** SQLITE_AFF_REAL:
  64380. ** SQLITE_AFF_NUMERIC:
  64381. ** Try to convert pRec to an integer representation or a
  64382. ** floating-point representation if an integer representation
  64383. ** is not possible. Note that the integer representation is
  64384. ** always preferred, even if the affinity is REAL, because
  64385. ** an integer representation is more space efficient on disk.
  64386. **
  64387. ** SQLITE_AFF_TEXT:
  64388. ** Convert pRec to a text representation.
  64389. **
  64390. ** SQLITE_AFF_NONE:
  64391. ** No-op. pRec is unchanged.
  64392. */
  64393. static void applyAffinity(
  64394. Mem *pRec, /* The value to apply affinity to */
  64395. char affinity, /* The affinity to be applied */
  64396. u8 enc /* Use this text encoding */
  64397. ){
  64398. if( affinity==SQLITE_AFF_TEXT ){
  64399. /* Only attempt the conversion to TEXT if there is an integer or real
  64400. ** representation (blob and NULL do not get converted) but no string
  64401. ** representation.
  64402. */
  64403. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  64404. sqlite3VdbeMemStringify(pRec, enc);
  64405. }
  64406. pRec->flags &= ~(MEM_Real|MEM_Int);
  64407. }else if( affinity!=SQLITE_AFF_NONE ){
  64408. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  64409. || affinity==SQLITE_AFF_NUMERIC );
  64410. applyNumericAffinity(pRec);
  64411. if( pRec->flags & MEM_Real ){
  64412. sqlite3VdbeIntegerAffinity(pRec);
  64413. }
  64414. }
  64415. }
  64416. /*
  64417. ** Try to convert the type of a function argument or a result column
  64418. ** into a numeric representation. Use either INTEGER or REAL whichever
  64419. ** is appropriate. But only do the conversion if it is possible without
  64420. ** loss of information and return the revised type of the argument.
  64421. */
  64422. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  64423. Mem *pMem = (Mem*)pVal;
  64424. if( pMem->type==SQLITE_TEXT ){
  64425. applyNumericAffinity(pMem);
  64426. sqlite3VdbeMemStoreType(pMem);
  64427. }
  64428. return pMem->type;
  64429. }
  64430. /*
  64431. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  64432. ** not the internal Mem* type.
  64433. */
  64434. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  64435. sqlite3_value *pVal,
  64436. u8 affinity,
  64437. u8 enc
  64438. ){
  64439. applyAffinity((Mem *)pVal, affinity, enc);
  64440. }
  64441. #ifdef SQLITE_DEBUG
  64442. /*
  64443. ** Write a nice string representation of the contents of cell pMem
  64444. ** into buffer zBuf, length nBuf.
  64445. */
  64446. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  64447. char *zCsr = zBuf;
  64448. int f = pMem->flags;
  64449. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  64450. if( f&MEM_Blob ){
  64451. int i;
  64452. char c;
  64453. if( f & MEM_Dyn ){
  64454. c = 'z';
  64455. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64456. }else if( f & MEM_Static ){
  64457. c = 't';
  64458. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64459. }else if( f & MEM_Ephem ){
  64460. c = 'e';
  64461. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64462. }else{
  64463. c = 's';
  64464. }
  64465. sqlite3_snprintf(100, zCsr, "%c", c);
  64466. zCsr += sqlite3Strlen30(zCsr);
  64467. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  64468. zCsr += sqlite3Strlen30(zCsr);
  64469. for(i=0; i<16 && i<pMem->n; i++){
  64470. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  64471. zCsr += sqlite3Strlen30(zCsr);
  64472. }
  64473. for(i=0; i<16 && i<pMem->n; i++){
  64474. char z = pMem->z[i];
  64475. if( z<32 || z>126 ) *zCsr++ = '.';
  64476. else *zCsr++ = z;
  64477. }
  64478. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  64479. zCsr += sqlite3Strlen30(zCsr);
  64480. if( f & MEM_Zero ){
  64481. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  64482. zCsr += sqlite3Strlen30(zCsr);
  64483. }
  64484. *zCsr = '\0';
  64485. }else if( f & MEM_Str ){
  64486. int j, k;
  64487. zBuf[0] = ' ';
  64488. if( f & MEM_Dyn ){
  64489. zBuf[1] = 'z';
  64490. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64491. }else if( f & MEM_Static ){
  64492. zBuf[1] = 't';
  64493. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64494. }else if( f & MEM_Ephem ){
  64495. zBuf[1] = 'e';
  64496. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64497. }else{
  64498. zBuf[1] = 's';
  64499. }
  64500. k = 2;
  64501. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  64502. k += sqlite3Strlen30(&zBuf[k]);
  64503. zBuf[k++] = '[';
  64504. for(j=0; j<15 && j<pMem->n; j++){
  64505. u8 c = pMem->z[j];
  64506. if( c>=0x20 && c<0x7f ){
  64507. zBuf[k++] = c;
  64508. }else{
  64509. zBuf[k++] = '.';
  64510. }
  64511. }
  64512. zBuf[k++] = ']';
  64513. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  64514. k += sqlite3Strlen30(&zBuf[k]);
  64515. zBuf[k++] = 0;
  64516. }
  64517. }
  64518. #endif
  64519. #ifdef SQLITE_DEBUG
  64520. /*
  64521. ** Print the value of a register for tracing purposes:
  64522. */
  64523. static void memTracePrint(FILE *out, Mem *p){
  64524. if( p->flags & MEM_Invalid ){
  64525. fprintf(out, " undefined");
  64526. }else if( p->flags & MEM_Null ){
  64527. fprintf(out, " NULL");
  64528. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  64529. fprintf(out, " si:%lld", p->u.i);
  64530. }else if( p->flags & MEM_Int ){
  64531. fprintf(out, " i:%lld", p->u.i);
  64532. #ifndef SQLITE_OMIT_FLOATING_POINT
  64533. }else if( p->flags & MEM_Real ){
  64534. fprintf(out, " r:%g", p->r);
  64535. #endif
  64536. }else if( p->flags & MEM_RowSet ){
  64537. fprintf(out, " (rowset)");
  64538. }else{
  64539. char zBuf[200];
  64540. sqlite3VdbeMemPrettyPrint(p, zBuf);
  64541. fprintf(out, " ");
  64542. fprintf(out, "%s", zBuf);
  64543. }
  64544. }
  64545. static void registerTrace(FILE *out, int iReg, Mem *p){
  64546. fprintf(out, "REG[%d] = ", iReg);
  64547. memTracePrint(out, p);
  64548. fprintf(out, "\n");
  64549. }
  64550. #endif
  64551. #ifdef SQLITE_DEBUG
  64552. # define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
  64553. #else
  64554. # define REGISTER_TRACE(R,M)
  64555. #endif
  64556. #ifdef VDBE_PROFILE
  64557. /*
  64558. ** hwtime.h contains inline assembler code for implementing
  64559. ** high-performance timing routines.
  64560. */
  64561. /************** Include hwtime.h in the middle of vdbe.c *********************/
  64562. /************** Begin file hwtime.h ******************************************/
  64563. /*
  64564. ** 2008 May 27
  64565. **
  64566. ** The author disclaims copyright to this source code. In place of
  64567. ** a legal notice, here is a blessing:
  64568. **
  64569. ** May you do good and not evil.
  64570. ** May you find forgiveness for yourself and forgive others.
  64571. ** May you share freely, never taking more than you give.
  64572. **
  64573. ******************************************************************************
  64574. **
  64575. ** This file contains inline asm code for retrieving "high-performance"
  64576. ** counters for x86 class CPUs.
  64577. */
  64578. #ifndef _HWTIME_H_
  64579. #define _HWTIME_H_
  64580. /*
  64581. ** The following routine only works on pentium-class (or newer) processors.
  64582. ** It uses the RDTSC opcode to read the cycle count value out of the
  64583. ** processor and returns that value. This can be used for high-res
  64584. ** profiling.
  64585. */
  64586. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  64587. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  64588. #if defined(__GNUC__)
  64589. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64590. unsigned int lo, hi;
  64591. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  64592. return (sqlite_uint64)hi << 32 | lo;
  64593. }
  64594. #elif defined(_MSC_VER)
  64595. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  64596. __asm {
  64597. rdtsc
  64598. ret ; return value at EDX:EAX
  64599. }
  64600. }
  64601. #endif
  64602. #elif (defined(__GNUC__) && defined(__x86_64__))
  64603. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64604. unsigned long val;
  64605. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  64606. return val;
  64607. }
  64608. #elif (defined(__GNUC__) && defined(__ppc__))
  64609. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64610. unsigned long long retval;
  64611. unsigned long junk;
  64612. __asm__ __volatile__ ("\n\
  64613. 1: mftbu %1\n\
  64614. mftb %L0\n\
  64615. mftbu %0\n\
  64616. cmpw %0,%1\n\
  64617. bne 1b"
  64618. : "=r" (retval), "=r" (junk));
  64619. return retval;
  64620. }
  64621. #else
  64622. #error Need implementation of sqlite3Hwtime() for your platform.
  64623. /*
  64624. ** To compile without implementing sqlite3Hwtime() for your platform,
  64625. ** you can remove the above #error and use the following
  64626. ** stub function. You will lose timing support for many
  64627. ** of the debugging and testing utilities, but it should at
  64628. ** least compile and run.
  64629. */
  64630. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  64631. #endif
  64632. #endif /* !defined(_HWTIME_H_) */
  64633. /************** End of hwtime.h **********************************************/
  64634. /************** Continuing where we left off in vdbe.c ***********************/
  64635. #endif
  64636. /*
  64637. ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  64638. ** sqlite3_interrupt() routine has been called. If it has been, then
  64639. ** processing of the VDBE program is interrupted.
  64640. **
  64641. ** This macro added to every instruction that does a jump in order to
  64642. ** implement a loop. This test used to be on every single instruction,
  64643. ** but that meant we more testing than we needed. By only testing the
  64644. ** flag on jump instructions, we get a (small) speed improvement.
  64645. */
  64646. #define CHECK_FOR_INTERRUPT \
  64647. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  64648. #ifndef NDEBUG
  64649. /*
  64650. ** This function is only called from within an assert() expression. It
  64651. ** checks that the sqlite3.nTransaction variable is correctly set to
  64652. ** the number of non-transaction savepoints currently in the
  64653. ** linked list starting at sqlite3.pSavepoint.
  64654. **
  64655. ** Usage:
  64656. **
  64657. ** assert( checkSavepointCount(db) );
  64658. */
  64659. static int checkSavepointCount(sqlite3 *db){
  64660. int n = 0;
  64661. Savepoint *p;
  64662. for(p=db->pSavepoint; p; p=p->pNext) n++;
  64663. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  64664. return 1;
  64665. }
  64666. #endif
  64667. /*
  64668. ** Execute as much of a VDBE program as we can then return.
  64669. **
  64670. ** sqlite3VdbeMakeReady() must be called before this routine in order to
  64671. ** close the program with a final OP_Halt and to set up the callbacks
  64672. ** and the error message pointer.
  64673. **
  64674. ** Whenever a row or result data is available, this routine will either
  64675. ** invoke the result callback (if there is one) or return with
  64676. ** SQLITE_ROW.
  64677. **
  64678. ** If an attempt is made to open a locked database, then this routine
  64679. ** will either invoke the busy callback (if there is one) or it will
  64680. ** return SQLITE_BUSY.
  64681. **
  64682. ** If an error occurs, an error message is written to memory obtained
  64683. ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
  64684. ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  64685. **
  64686. ** If the callback ever returns non-zero, then the program exits
  64687. ** immediately. There will be no error message but the p->rc field is
  64688. ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  64689. **
  64690. ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  64691. ** routine to return SQLITE_ERROR.
  64692. **
  64693. ** Other fatal errors return SQLITE_ERROR.
  64694. **
  64695. ** After this routine has finished, sqlite3VdbeFinalize() should be
  64696. ** used to clean up the mess that was left behind.
  64697. */
  64698. SQLITE_PRIVATE int sqlite3VdbeExec(
  64699. Vdbe *p /* The VDBE */
  64700. ){
  64701. int pc=0; /* The program counter */
  64702. Op *aOp = p->aOp; /* Copy of p->aOp */
  64703. Op *pOp; /* Current operation */
  64704. int rc = SQLITE_OK; /* Value to return */
  64705. sqlite3 *db = p->db; /* The database */
  64706. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  64707. u8 encoding = ENC(db); /* The database encoding */
  64708. int iCompare = 0; /* Result of last OP_Compare operation */
  64709. unsigned nVmStep = 0; /* Number of virtual machine steps */
  64710. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  64711. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  64712. #endif
  64713. Mem *aMem = p->aMem; /* Copy of p->aMem */
  64714. Mem *pIn1 = 0; /* 1st input operand */
  64715. Mem *pIn2 = 0; /* 2nd input operand */
  64716. Mem *pIn3 = 0; /* 3rd input operand */
  64717. Mem *pOut = 0; /* Output operand */
  64718. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  64719. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  64720. #ifdef VDBE_PROFILE
  64721. u64 start; /* CPU clock count at start of opcode */
  64722. int origPc; /* Program counter at start of opcode */
  64723. #endif
  64724. /********************************************************************
  64725. ** Automatically generated code
  64726. **
  64727. ** The following union is automatically generated by the
  64728. ** vdbe-compress.tcl script. The purpose of this union is to
  64729. ** reduce the amount of stack space required by this function.
  64730. ** See comments in the vdbe-compress.tcl script for details.
  64731. */
  64732. union vdbeExecUnion {
  64733. struct OP_Yield_stack_vars {
  64734. int pcDest;
  64735. } aa;
  64736. struct OP_Null_stack_vars {
  64737. int cnt;
  64738. u16 nullFlag;
  64739. } ab;
  64740. struct OP_Variable_stack_vars {
  64741. Mem *pVar; /* Value being transferred */
  64742. } ac;
  64743. struct OP_Move_stack_vars {
  64744. char *zMalloc; /* Holding variable for allocated memory */
  64745. int n; /* Number of registers left to copy */
  64746. int p1; /* Register to copy from */
  64747. int p2; /* Register to copy to */
  64748. } ad;
  64749. struct OP_Copy_stack_vars {
  64750. int n;
  64751. } ae;
  64752. struct OP_ResultRow_stack_vars {
  64753. Mem *pMem;
  64754. int i;
  64755. } af;
  64756. struct OP_Concat_stack_vars {
  64757. i64 nByte;
  64758. } ag;
  64759. struct OP_Remainder_stack_vars {
  64760. char bIntint; /* Started out as two integer operands */
  64761. int flags; /* Combined MEM_* flags from both inputs */
  64762. i64 iA; /* Integer value of left operand */
  64763. i64 iB; /* Integer value of right operand */
  64764. double rA; /* Real value of left operand */
  64765. double rB; /* Real value of right operand */
  64766. } ah;
  64767. struct OP_Function_stack_vars {
  64768. int i;
  64769. Mem *pArg;
  64770. sqlite3_context ctx;
  64771. sqlite3_value **apVal;
  64772. int n;
  64773. } ai;
  64774. struct OP_ShiftRight_stack_vars {
  64775. i64 iA;
  64776. u64 uA;
  64777. i64 iB;
  64778. u8 op;
  64779. } aj;
  64780. struct OP_Ge_stack_vars {
  64781. int res; /* Result of the comparison of pIn1 against pIn3 */
  64782. char affinity; /* Affinity to use for comparison */
  64783. u16 flags1; /* Copy of initial value of pIn1->flags */
  64784. u16 flags3; /* Copy of initial value of pIn3->flags */
  64785. } ak;
  64786. struct OP_Compare_stack_vars {
  64787. int n;
  64788. int i;
  64789. int p1;
  64790. int p2;
  64791. const KeyInfo *pKeyInfo;
  64792. int idx;
  64793. CollSeq *pColl; /* Collating sequence to use on this term */
  64794. int bRev; /* True for DESCENDING sort order */
  64795. } al;
  64796. struct OP_Or_stack_vars {
  64797. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  64798. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  64799. } am;
  64800. struct OP_IfNot_stack_vars {
  64801. int c;
  64802. } an;
  64803. struct OP_Column_stack_vars {
  64804. u32 payloadSize; /* Number of bytes in the record */
  64805. i64 payloadSize64; /* Number of bytes in the record */
  64806. int p1; /* P1 value of the opcode */
  64807. int p2; /* column number to retrieve */
  64808. VdbeCursor *pC; /* The VDBE cursor */
  64809. char *zRec; /* Pointer to complete record-data */
  64810. BtCursor *pCrsr; /* The BTree cursor */
  64811. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  64812. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  64813. int nField; /* number of fields in the record */
  64814. int len; /* The length of the serialized data for the column */
  64815. int i; /* Loop counter */
  64816. char *zData; /* Part of the record being decoded */
  64817. Mem *pDest; /* Where to write the extracted value */
  64818. Mem sMem; /* For storing the record being decoded */
  64819. u8 *zIdx; /* Index into header */
  64820. u8 *zEndHdr; /* Pointer to first byte after the header */
  64821. u32 offset; /* Offset into the data */
  64822. u32 szField; /* Number of bytes in the content of a field */
  64823. int szHdr; /* Size of the header size field at start of record */
  64824. int avail; /* Number of bytes of available data */
  64825. u32 t; /* A type code from the record header */
  64826. Mem *pReg; /* PseudoTable input register */
  64827. } ao;
  64828. struct OP_Affinity_stack_vars {
  64829. const char *zAffinity; /* The affinity to be applied */
  64830. char cAff; /* A single character of affinity */
  64831. } ap;
  64832. struct OP_MakeRecord_stack_vars {
  64833. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  64834. Mem *pRec; /* The new record */
  64835. u64 nData; /* Number of bytes of data space */
  64836. int nHdr; /* Number of bytes of header space */
  64837. i64 nByte; /* Data space required for this record */
  64838. int nZero; /* Number of zero bytes at the end of the record */
  64839. int nVarint; /* Number of bytes in a varint */
  64840. u32 serial_type; /* Type field */
  64841. Mem *pData0; /* First field to be combined into the record */
  64842. Mem *pLast; /* Last field of the record */
  64843. int nField; /* Number of fields in the record */
  64844. char *zAffinity; /* The affinity string for the record */
  64845. int file_format; /* File format to use for encoding */
  64846. int i; /* Space used in zNewRecord[] */
  64847. int len; /* Length of a field */
  64848. } aq;
  64849. struct OP_Count_stack_vars {
  64850. i64 nEntry;
  64851. BtCursor *pCrsr;
  64852. } ar;
  64853. struct OP_Savepoint_stack_vars {
  64854. int p1; /* Value of P1 operand */
  64855. char *zName; /* Name of savepoint */
  64856. int nName;
  64857. Savepoint *pNew;
  64858. Savepoint *pSavepoint;
  64859. Savepoint *pTmp;
  64860. int iSavepoint;
  64861. int ii;
  64862. } as;
  64863. struct OP_AutoCommit_stack_vars {
  64864. int desiredAutoCommit;
  64865. int iRollback;
  64866. int turnOnAC;
  64867. } at;
  64868. struct OP_Transaction_stack_vars {
  64869. Btree *pBt;
  64870. } au;
  64871. struct OP_ReadCookie_stack_vars {
  64872. int iMeta;
  64873. int iDb;
  64874. int iCookie;
  64875. } av;
  64876. struct OP_SetCookie_stack_vars {
  64877. Db *pDb;
  64878. } aw;
  64879. struct OP_VerifyCookie_stack_vars {
  64880. int iMeta;
  64881. int iGen;
  64882. Btree *pBt;
  64883. } ax;
  64884. struct OP_OpenWrite_stack_vars {
  64885. int nField;
  64886. KeyInfo *pKeyInfo;
  64887. int p2;
  64888. int iDb;
  64889. int wrFlag;
  64890. Btree *pX;
  64891. VdbeCursor *pCur;
  64892. Db *pDb;
  64893. } ay;
  64894. struct OP_OpenEphemeral_stack_vars {
  64895. VdbeCursor *pCx;
  64896. } az;
  64897. struct OP_SorterOpen_stack_vars {
  64898. VdbeCursor *pCx;
  64899. } ba;
  64900. struct OP_OpenPseudo_stack_vars {
  64901. VdbeCursor *pCx;
  64902. } bb;
  64903. struct OP_SeekGt_stack_vars {
  64904. int res;
  64905. int oc;
  64906. VdbeCursor *pC;
  64907. UnpackedRecord r;
  64908. int nField;
  64909. i64 iKey; /* The rowid we are to seek to */
  64910. } bc;
  64911. struct OP_Seek_stack_vars {
  64912. VdbeCursor *pC;
  64913. } bd;
  64914. struct OP_Found_stack_vars {
  64915. int alreadyExists;
  64916. VdbeCursor *pC;
  64917. int res;
  64918. char *pFree;
  64919. UnpackedRecord *pIdxKey;
  64920. UnpackedRecord r;
  64921. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  64922. } be;
  64923. struct OP_IsUnique_stack_vars {
  64924. u16 ii;
  64925. VdbeCursor *pCx;
  64926. BtCursor *pCrsr;
  64927. u16 nField;
  64928. Mem *aMx;
  64929. UnpackedRecord r; /* B-Tree index search key */
  64930. i64 R; /* Rowid stored in register P3 */
  64931. } bf;
  64932. struct OP_NotExists_stack_vars {
  64933. VdbeCursor *pC;
  64934. BtCursor *pCrsr;
  64935. int res;
  64936. u64 iKey;
  64937. } bg;
  64938. struct OP_NewRowid_stack_vars {
  64939. i64 v; /* The new rowid */
  64940. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  64941. int res; /* Result of an sqlite3BtreeLast() */
  64942. int cnt; /* Counter to limit the number of searches */
  64943. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  64944. VdbeFrame *pFrame; /* Root frame of VDBE */
  64945. } bh;
  64946. struct OP_InsertInt_stack_vars {
  64947. Mem *pData; /* MEM cell holding data for the record to be inserted */
  64948. Mem *pKey; /* MEM cell holding key for the record */
  64949. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  64950. VdbeCursor *pC; /* Cursor to table into which insert is written */
  64951. int nZero; /* Number of zero-bytes to append */
  64952. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  64953. const char *zDb; /* database name - used by the update hook */
  64954. const char *zTbl; /* Table name - used by the opdate hook */
  64955. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  64956. } bi;
  64957. struct OP_Delete_stack_vars {
  64958. i64 iKey;
  64959. VdbeCursor *pC;
  64960. } bj;
  64961. struct OP_SorterCompare_stack_vars {
  64962. VdbeCursor *pC;
  64963. int res;
  64964. } bk;
  64965. struct OP_SorterData_stack_vars {
  64966. VdbeCursor *pC;
  64967. } bl;
  64968. struct OP_RowData_stack_vars {
  64969. VdbeCursor *pC;
  64970. BtCursor *pCrsr;
  64971. u32 n;
  64972. i64 n64;
  64973. } bm;
  64974. struct OP_Rowid_stack_vars {
  64975. VdbeCursor *pC;
  64976. i64 v;
  64977. sqlite3_vtab *pVtab;
  64978. const sqlite3_module *pModule;
  64979. } bn;
  64980. struct OP_NullRow_stack_vars {
  64981. VdbeCursor *pC;
  64982. } bo;
  64983. struct OP_Last_stack_vars {
  64984. VdbeCursor *pC;
  64985. BtCursor *pCrsr;
  64986. int res;
  64987. } bp;
  64988. struct OP_Rewind_stack_vars {
  64989. VdbeCursor *pC;
  64990. BtCursor *pCrsr;
  64991. int res;
  64992. } bq;
  64993. struct OP_Next_stack_vars {
  64994. VdbeCursor *pC;
  64995. int res;
  64996. } br;
  64997. struct OP_IdxInsert_stack_vars {
  64998. VdbeCursor *pC;
  64999. BtCursor *pCrsr;
  65000. int nKey;
  65001. const char *zKey;
  65002. } bs;
  65003. struct OP_IdxDelete_stack_vars {
  65004. VdbeCursor *pC;
  65005. BtCursor *pCrsr;
  65006. int res;
  65007. UnpackedRecord r;
  65008. } bt;
  65009. struct OP_IdxRowid_stack_vars {
  65010. BtCursor *pCrsr;
  65011. VdbeCursor *pC;
  65012. i64 rowid;
  65013. } bu;
  65014. struct OP_IdxGE_stack_vars {
  65015. VdbeCursor *pC;
  65016. int res;
  65017. UnpackedRecord r;
  65018. } bv;
  65019. struct OP_Destroy_stack_vars {
  65020. int iMoved;
  65021. int iCnt;
  65022. Vdbe *pVdbe;
  65023. int iDb;
  65024. } bw;
  65025. struct OP_Clear_stack_vars {
  65026. int nChange;
  65027. } bx;
  65028. struct OP_CreateTable_stack_vars {
  65029. int pgno;
  65030. int flags;
  65031. Db *pDb;
  65032. } by;
  65033. struct OP_ParseSchema_stack_vars {
  65034. int iDb;
  65035. const char *zMaster;
  65036. char *zSql;
  65037. InitData initData;
  65038. } bz;
  65039. struct OP_IntegrityCk_stack_vars {
  65040. int nRoot; /* Number of tables to check. (Number of root pages.) */
  65041. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  65042. int j; /* Loop counter */
  65043. int nErr; /* Number of errors reported */
  65044. char *z; /* Text of the error report */
  65045. Mem *pnErr; /* Register keeping track of errors remaining */
  65046. } ca;
  65047. struct OP_RowSetRead_stack_vars {
  65048. i64 val;
  65049. } cb;
  65050. struct OP_RowSetTest_stack_vars {
  65051. int iSet;
  65052. int exists;
  65053. } cc;
  65054. struct OP_Program_stack_vars {
  65055. int nMem; /* Number of memory registers for sub-program */
  65056. int nByte; /* Bytes of runtime space required for sub-program */
  65057. Mem *pRt; /* Register to allocate runtime space */
  65058. Mem *pMem; /* Used to iterate through memory cells */
  65059. Mem *pEnd; /* Last memory cell in new array */
  65060. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  65061. SubProgram *pProgram; /* Sub-program to execute */
  65062. void *t; /* Token identifying trigger */
  65063. } cd;
  65064. struct OP_Param_stack_vars {
  65065. VdbeFrame *pFrame;
  65066. Mem *pIn;
  65067. } ce;
  65068. struct OP_MemMax_stack_vars {
  65069. Mem *pIn1;
  65070. VdbeFrame *pFrame;
  65071. } cf;
  65072. struct OP_AggStep_stack_vars {
  65073. int n;
  65074. int i;
  65075. Mem *pMem;
  65076. Mem *pRec;
  65077. sqlite3_context ctx;
  65078. sqlite3_value **apVal;
  65079. } cg;
  65080. struct OP_AggFinal_stack_vars {
  65081. Mem *pMem;
  65082. } ch;
  65083. struct OP_Checkpoint_stack_vars {
  65084. int i; /* Loop counter */
  65085. int aRes[3]; /* Results */
  65086. Mem *pMem; /* Write results here */
  65087. } ci;
  65088. struct OP_JournalMode_stack_vars {
  65089. Btree *pBt; /* Btree to change journal mode of */
  65090. Pager *pPager; /* Pager associated with pBt */
  65091. int eNew; /* New journal mode */
  65092. int eOld; /* The old journal mode */
  65093. #ifndef SQLITE_OMIT_WAL
  65094. const char *zFilename; /* Name of database file for pPager */
  65095. #endif
  65096. } cj;
  65097. struct OP_IncrVacuum_stack_vars {
  65098. Btree *pBt;
  65099. } ck;
  65100. struct OP_VBegin_stack_vars {
  65101. VTable *pVTab;
  65102. } cl;
  65103. struct OP_VOpen_stack_vars {
  65104. VdbeCursor *pCur;
  65105. sqlite3_vtab_cursor *pVtabCursor;
  65106. sqlite3_vtab *pVtab;
  65107. sqlite3_module *pModule;
  65108. } cm;
  65109. struct OP_VFilter_stack_vars {
  65110. int nArg;
  65111. int iQuery;
  65112. const sqlite3_module *pModule;
  65113. Mem *pQuery;
  65114. Mem *pArgc;
  65115. sqlite3_vtab_cursor *pVtabCursor;
  65116. sqlite3_vtab *pVtab;
  65117. VdbeCursor *pCur;
  65118. int res;
  65119. int i;
  65120. Mem **apArg;
  65121. } cn;
  65122. struct OP_VColumn_stack_vars {
  65123. sqlite3_vtab *pVtab;
  65124. const sqlite3_module *pModule;
  65125. Mem *pDest;
  65126. sqlite3_context sContext;
  65127. } co;
  65128. struct OP_VNext_stack_vars {
  65129. sqlite3_vtab *pVtab;
  65130. const sqlite3_module *pModule;
  65131. int res;
  65132. VdbeCursor *pCur;
  65133. } cp;
  65134. struct OP_VRename_stack_vars {
  65135. sqlite3_vtab *pVtab;
  65136. Mem *pName;
  65137. } cq;
  65138. struct OP_VUpdate_stack_vars {
  65139. sqlite3_vtab *pVtab;
  65140. sqlite3_module *pModule;
  65141. int nArg;
  65142. int i;
  65143. sqlite_int64 rowid;
  65144. Mem **apArg;
  65145. Mem *pX;
  65146. } cr;
  65147. struct OP_Trace_stack_vars {
  65148. char *zTrace;
  65149. char *z;
  65150. } cs;
  65151. } u;
  65152. /* End automatically generated code
  65153. ********************************************************************/
  65154. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  65155. sqlite3VdbeEnter(p);
  65156. if( p->rc==SQLITE_NOMEM ){
  65157. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  65158. ** sqlite3_column_text16() failed. */
  65159. goto no_mem;
  65160. }
  65161. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  65162. assert( p->bIsReader || p->readOnly!=0 );
  65163. p->rc = SQLITE_OK;
  65164. p->iCurrentTime = 0;
  65165. assert( p->explain==0 );
  65166. p->pResultSet = 0;
  65167. db->busyHandler.nBusy = 0;
  65168. CHECK_FOR_INTERRUPT;
  65169. sqlite3VdbeIOTraceSql(p);
  65170. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65171. if( db->xProgress ){
  65172. assert( 0 < db->nProgressOps );
  65173. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  65174. if( nProgressLimit==0 ){
  65175. nProgressLimit = db->nProgressOps;
  65176. }else{
  65177. nProgressLimit %= (unsigned)db->nProgressOps;
  65178. }
  65179. }
  65180. #endif
  65181. #ifdef SQLITE_DEBUG
  65182. sqlite3BeginBenignMalloc();
  65183. if( p->pc==0 && (p->db->flags & SQLITE_VdbeListing)!=0 ){
  65184. int i;
  65185. printf("VDBE Program Listing:\n");
  65186. sqlite3VdbePrintSql(p);
  65187. for(i=0; i<p->nOp; i++){
  65188. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  65189. }
  65190. }
  65191. sqlite3EndBenignMalloc();
  65192. #endif
  65193. for(pc=p->pc; rc==SQLITE_OK; pc++){
  65194. assert( pc>=0 && pc<p->nOp );
  65195. if( db->mallocFailed ) goto no_mem;
  65196. #ifdef VDBE_PROFILE
  65197. origPc = pc;
  65198. start = sqlite3Hwtime();
  65199. #endif
  65200. nVmStep++;
  65201. pOp = &aOp[pc];
  65202. /* Only allow tracing if SQLITE_DEBUG is defined.
  65203. */
  65204. #ifdef SQLITE_DEBUG
  65205. if( p->trace ){
  65206. if( pc==0 ){
  65207. printf("VDBE Execution Trace:\n");
  65208. sqlite3VdbePrintSql(p);
  65209. }
  65210. sqlite3VdbePrintOp(p->trace, pc, pOp);
  65211. }
  65212. #endif
  65213. /* Check to see if we need to simulate an interrupt. This only happens
  65214. ** if we have a special test build.
  65215. */
  65216. #ifdef SQLITE_TEST
  65217. if( sqlite3_interrupt_count>0 ){
  65218. sqlite3_interrupt_count--;
  65219. if( sqlite3_interrupt_count==0 ){
  65220. sqlite3_interrupt(db);
  65221. }
  65222. }
  65223. #endif
  65224. /* On any opcode with the "out2-prerelease" tag, free any
  65225. ** external allocations out of mem[p2] and set mem[p2] to be
  65226. ** an undefined integer. Opcodes will either fill in the integer
  65227. ** value or convert mem[p2] to a different type.
  65228. */
  65229. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  65230. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  65231. assert( pOp->p2>0 );
  65232. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65233. pOut = &aMem[pOp->p2];
  65234. memAboutToChange(p, pOut);
  65235. VdbeMemRelease(pOut);
  65236. pOut->flags = MEM_Int;
  65237. }
  65238. /* Sanity checking on other operands */
  65239. #ifdef SQLITE_DEBUG
  65240. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  65241. assert( pOp->p1>0 );
  65242. assert( pOp->p1<=(p->nMem-p->nCursor) );
  65243. assert( memIsValid(&aMem[pOp->p1]) );
  65244. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  65245. }
  65246. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  65247. assert( pOp->p2>0 );
  65248. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65249. assert( memIsValid(&aMem[pOp->p2]) );
  65250. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  65251. }
  65252. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  65253. assert( pOp->p3>0 );
  65254. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65255. assert( memIsValid(&aMem[pOp->p3]) );
  65256. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  65257. }
  65258. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  65259. assert( pOp->p2>0 );
  65260. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65261. memAboutToChange(p, &aMem[pOp->p2]);
  65262. }
  65263. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  65264. assert( pOp->p3>0 );
  65265. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65266. memAboutToChange(p, &aMem[pOp->p3]);
  65267. }
  65268. #endif
  65269. switch( pOp->opcode ){
  65270. /*****************************************************************************
  65271. ** What follows is a massive switch statement where each case implements a
  65272. ** separate instruction in the virtual machine. If we follow the usual
  65273. ** indentation conventions, each case should be indented by 6 spaces. But
  65274. ** that is a lot of wasted space on the left margin. So the code within
  65275. ** the switch statement will break with convention and be flush-left. Another
  65276. ** big comment (similar to this one) will mark the point in the code where
  65277. ** we transition back to normal indentation.
  65278. **
  65279. ** The formatting of each case is important. The makefile for SQLite
  65280. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  65281. ** file looking for lines that begin with "case OP_". The opcodes.h files
  65282. ** will be filled with #defines that give unique integer values to each
  65283. ** opcode and the opcodes.c file is filled with an array of strings where
  65284. ** each string is the symbolic name for the corresponding opcode. If the
  65285. ** case statement is followed by a comment of the form "/# same as ... #/"
  65286. ** that comment is used to determine the particular value of the opcode.
  65287. **
  65288. ** Other keywords in the comment that follows each case are used to
  65289. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  65290. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  65291. ** the mkopcodeh.awk script for additional information.
  65292. **
  65293. ** Documentation about VDBE opcodes is generated by scanning this file
  65294. ** for lines of that contain "Opcode:". That line and all subsequent
  65295. ** comment lines are used in the generation of the opcode.html documentation
  65296. ** file.
  65297. **
  65298. ** SUMMARY:
  65299. **
  65300. ** Formatting is important to scripts that scan this file.
  65301. ** Do not deviate from the formatting style currently in use.
  65302. **
  65303. *****************************************************************************/
  65304. /* Opcode: Goto * P2 * * *
  65305. **
  65306. ** An unconditional jump to address P2.
  65307. ** The next instruction executed will be
  65308. ** the one at index P2 from the beginning of
  65309. ** the program.
  65310. */
  65311. case OP_Goto: { /* jump */
  65312. pc = pOp->p2 - 1;
  65313. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  65314. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  65315. ** completion. Check to see if sqlite3_interrupt() has been called
  65316. ** or if the progress callback needs to be invoked.
  65317. **
  65318. ** This code uses unstructured "goto" statements and does not look clean.
  65319. ** But that is not due to sloppy coding habits. The code is written this
  65320. ** way for performance, to avoid having to run the interrupt and progress
  65321. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  65322. ** faster according to "valgrind --tool=cachegrind" */
  65323. check_for_interrupt:
  65324. CHECK_FOR_INTERRUPT;
  65325. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65326. /* Call the progress callback if it is configured and the required number
  65327. ** of VDBE ops have been executed (either since this invocation of
  65328. ** sqlite3VdbeExec() or since last time the progress callback was called).
  65329. ** If the progress callback returns non-zero, exit the virtual machine with
  65330. ** a return code SQLITE_ABORT.
  65331. */
  65332. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  65333. int prc;
  65334. prc = db->xProgress(db->pProgressArg);
  65335. if( prc!=0 ){
  65336. rc = SQLITE_INTERRUPT;
  65337. goto vdbe_error_halt;
  65338. }
  65339. if( db->xProgress!=0 ){
  65340. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  65341. }
  65342. }
  65343. #endif
  65344. break;
  65345. }
  65346. /* Opcode: Gosub P1 P2 * * *
  65347. **
  65348. ** Write the current address onto register P1
  65349. ** and then jump to address P2.
  65350. */
  65351. case OP_Gosub: { /* jump */
  65352. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65353. pIn1 = &aMem[pOp->p1];
  65354. assert( (pIn1->flags & MEM_Dyn)==0 );
  65355. memAboutToChange(p, pIn1);
  65356. pIn1->flags = MEM_Int;
  65357. pIn1->u.i = pc;
  65358. REGISTER_TRACE(pOp->p1, pIn1);
  65359. pc = pOp->p2 - 1;
  65360. break;
  65361. }
  65362. /* Opcode: Return P1 * * * *
  65363. **
  65364. ** Jump to the next instruction after the address in register P1.
  65365. */
  65366. case OP_Return: { /* in1 */
  65367. pIn1 = &aMem[pOp->p1];
  65368. assert( pIn1->flags & MEM_Int );
  65369. pc = (int)pIn1->u.i;
  65370. break;
  65371. }
  65372. /* Opcode: Yield P1 * * * *
  65373. **
  65374. ** Swap the program counter with the value in register P1.
  65375. */
  65376. case OP_Yield: { /* in1 */
  65377. #if 0 /* local variables moved into u.aa */
  65378. int pcDest;
  65379. #endif /* local variables moved into u.aa */
  65380. pIn1 = &aMem[pOp->p1];
  65381. assert( (pIn1->flags & MEM_Dyn)==0 );
  65382. pIn1->flags = MEM_Int;
  65383. u.aa.pcDest = (int)pIn1->u.i;
  65384. pIn1->u.i = pc;
  65385. REGISTER_TRACE(pOp->p1, pIn1);
  65386. pc = u.aa.pcDest;
  65387. break;
  65388. }
  65389. /* Opcode: HaltIfNull P1 P2 P3 P4 *
  65390. **
  65391. ** Check the value in register P3. If it is NULL then Halt using
  65392. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  65393. ** value in register P3 is not NULL, then this routine is a no-op.
  65394. */
  65395. case OP_HaltIfNull: { /* in3 */
  65396. pIn3 = &aMem[pOp->p3];
  65397. if( (pIn3->flags & MEM_Null)==0 ) break;
  65398. /* Fall through into OP_Halt */
  65399. }
  65400. /* Opcode: Halt P1 P2 * P4 *
  65401. **
  65402. ** Exit immediately. All open cursors, etc are closed
  65403. ** automatically.
  65404. **
  65405. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  65406. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  65407. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  65408. ** whether or not to rollback the current transaction. Do not rollback
  65409. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  65410. ** then back out all changes that have occurred during this execution of the
  65411. ** VDBE, but do not rollback the transaction.
  65412. **
  65413. ** If P4 is not null then it is an error message string.
  65414. **
  65415. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  65416. ** every program. So a jump past the last instruction of the program
  65417. ** is the same as executing Halt.
  65418. */
  65419. case OP_Halt: {
  65420. if( pOp->p1==SQLITE_OK && p->pFrame ){
  65421. /* Halt the sub-program. Return control to the parent frame. */
  65422. VdbeFrame *pFrame = p->pFrame;
  65423. p->pFrame = pFrame->pParent;
  65424. p->nFrame--;
  65425. sqlite3VdbeSetChanges(db, p->nChange);
  65426. pc = sqlite3VdbeFrameRestore(pFrame);
  65427. lastRowid = db->lastRowid;
  65428. if( pOp->p2==OE_Ignore ){
  65429. /* Instruction pc is the OP_Program that invoked the sub-program
  65430. ** currently being halted. If the p2 instruction of this OP_Halt
  65431. ** instruction is set to OE_Ignore, then the sub-program is throwing
  65432. ** an IGNORE exception. In this case jump to the address specified
  65433. ** as the p2 of the calling OP_Program. */
  65434. pc = p->aOp[pc].p2-1;
  65435. }
  65436. aOp = p->aOp;
  65437. aMem = p->aMem;
  65438. break;
  65439. }
  65440. p->rc = pOp->p1;
  65441. p->errorAction = (u8)pOp->p2;
  65442. p->pc = pc;
  65443. if( pOp->p4.z ){
  65444. assert( p->rc!=SQLITE_OK );
  65445. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  65446. testcase( sqlite3GlobalConfig.xLog!=0 );
  65447. sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
  65448. }else if( p->rc ){
  65449. testcase( sqlite3GlobalConfig.xLog!=0 );
  65450. sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
  65451. }
  65452. rc = sqlite3VdbeHalt(p);
  65453. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  65454. if( rc==SQLITE_BUSY ){
  65455. p->rc = rc = SQLITE_BUSY;
  65456. }else{
  65457. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  65458. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  65459. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  65460. }
  65461. goto vdbe_return;
  65462. }
  65463. /* Opcode: Integer P1 P2 * * *
  65464. **
  65465. ** The 32-bit integer value P1 is written into register P2.
  65466. */
  65467. case OP_Integer: { /* out2-prerelease */
  65468. pOut->u.i = pOp->p1;
  65469. break;
  65470. }
  65471. /* Opcode: Int64 * P2 * P4 *
  65472. **
  65473. ** P4 is a pointer to a 64-bit integer value.
  65474. ** Write that value into register P2.
  65475. */
  65476. case OP_Int64: { /* out2-prerelease */
  65477. assert( pOp->p4.pI64!=0 );
  65478. pOut->u.i = *pOp->p4.pI64;
  65479. break;
  65480. }
  65481. #ifndef SQLITE_OMIT_FLOATING_POINT
  65482. /* Opcode: Real * P2 * P4 *
  65483. **
  65484. ** P4 is a pointer to a 64-bit floating point value.
  65485. ** Write that value into register P2.
  65486. */
  65487. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  65488. pOut->flags = MEM_Real;
  65489. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  65490. pOut->r = *pOp->p4.pReal;
  65491. break;
  65492. }
  65493. #endif
  65494. /* Opcode: String8 * P2 * P4 *
  65495. **
  65496. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  65497. ** into an OP_String before it is executed for the first time.
  65498. */
  65499. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  65500. assert( pOp->p4.z!=0 );
  65501. pOp->opcode = OP_String;
  65502. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  65503. #ifndef SQLITE_OMIT_UTF16
  65504. if( encoding!=SQLITE_UTF8 ){
  65505. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  65506. if( rc==SQLITE_TOOBIG ) goto too_big;
  65507. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  65508. assert( pOut->zMalloc==pOut->z );
  65509. assert( pOut->flags & MEM_Dyn );
  65510. pOut->zMalloc = 0;
  65511. pOut->flags |= MEM_Static;
  65512. pOut->flags &= ~MEM_Dyn;
  65513. if( pOp->p4type==P4_DYNAMIC ){
  65514. sqlite3DbFree(db, pOp->p4.z);
  65515. }
  65516. pOp->p4type = P4_DYNAMIC;
  65517. pOp->p4.z = pOut->z;
  65518. pOp->p1 = pOut->n;
  65519. }
  65520. #endif
  65521. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65522. goto too_big;
  65523. }
  65524. /* Fall through to the next case, OP_String */
  65525. }
  65526. /* Opcode: String P1 P2 * P4 *
  65527. **
  65528. ** The string value P4 of length P1 (bytes) is stored in register P2.
  65529. */
  65530. case OP_String: { /* out2-prerelease */
  65531. assert( pOp->p4.z!=0 );
  65532. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  65533. pOut->z = pOp->p4.z;
  65534. pOut->n = pOp->p1;
  65535. pOut->enc = encoding;
  65536. UPDATE_MAX_BLOBSIZE(pOut);
  65537. break;
  65538. }
  65539. /* Opcode: Null P1 P2 P3 * *
  65540. **
  65541. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  65542. ** NULL into register P3 and every register in between P2 and P3. If P3
  65543. ** is less than P2 (typically P3 is zero) then only register P2 is
  65544. ** set to NULL.
  65545. **
  65546. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  65547. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  65548. ** OP_Ne or OP_Eq.
  65549. */
  65550. case OP_Null: { /* out2-prerelease */
  65551. #if 0 /* local variables moved into u.ab */
  65552. int cnt;
  65553. u16 nullFlag;
  65554. #endif /* local variables moved into u.ab */
  65555. u.ab.cnt = pOp->p3-pOp->p2;
  65556. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65557. pOut->flags = u.ab.nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  65558. while( u.ab.cnt>0 ){
  65559. pOut++;
  65560. memAboutToChange(p, pOut);
  65561. VdbeMemRelease(pOut);
  65562. pOut->flags = u.ab.nullFlag;
  65563. u.ab.cnt--;
  65564. }
  65565. break;
  65566. }
  65567. /* Opcode: Blob P1 P2 * P4
  65568. **
  65569. ** P4 points to a blob of data P1 bytes long. Store this
  65570. ** blob in register P2.
  65571. */
  65572. case OP_Blob: { /* out2-prerelease */
  65573. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  65574. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  65575. pOut->enc = encoding;
  65576. UPDATE_MAX_BLOBSIZE(pOut);
  65577. break;
  65578. }
  65579. /* Opcode: Variable P1 P2 * P4 *
  65580. **
  65581. ** Transfer the values of bound parameter P1 into register P2
  65582. **
  65583. ** If the parameter is named, then its name appears in P4 and P3==1.
  65584. ** The P4 value is used by sqlite3_bind_parameter_name().
  65585. */
  65586. case OP_Variable: { /* out2-prerelease */
  65587. #if 0 /* local variables moved into u.ac */
  65588. Mem *pVar; /* Value being transferred */
  65589. #endif /* local variables moved into u.ac */
  65590. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  65591. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  65592. u.ac.pVar = &p->aVar[pOp->p1 - 1];
  65593. if( sqlite3VdbeMemTooBig(u.ac.pVar) ){
  65594. goto too_big;
  65595. }
  65596. sqlite3VdbeMemShallowCopy(pOut, u.ac.pVar, MEM_Static);
  65597. UPDATE_MAX_BLOBSIZE(pOut);
  65598. break;
  65599. }
  65600. /* Opcode: Move P1 P2 P3 * *
  65601. **
  65602. ** Move the values in register P1..P1+P3 over into
  65603. ** registers P2..P2+P3. Registers P1..P1+P3 are
  65604. ** left holding a NULL. It is an error for register ranges
  65605. ** P1..P1+P3 and P2..P2+P3 to overlap.
  65606. */
  65607. case OP_Move: {
  65608. #if 0 /* local variables moved into u.ad */
  65609. char *zMalloc; /* Holding variable for allocated memory */
  65610. int n; /* Number of registers left to copy */
  65611. int p1; /* Register to copy from */
  65612. int p2; /* Register to copy to */
  65613. #endif /* local variables moved into u.ad */
  65614. u.ad.n = pOp->p3 + 1;
  65615. u.ad.p1 = pOp->p1;
  65616. u.ad.p2 = pOp->p2;
  65617. assert( u.ad.n>0 && u.ad.p1>0 && u.ad.p2>0 );
  65618. assert( u.ad.p1+u.ad.n<=u.ad.p2 || u.ad.p2+u.ad.n<=u.ad.p1 );
  65619. pIn1 = &aMem[u.ad.p1];
  65620. pOut = &aMem[u.ad.p2];
  65621. while( u.ad.n-- ){
  65622. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  65623. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  65624. assert( memIsValid(pIn1) );
  65625. memAboutToChange(p, pOut);
  65626. u.ad.zMalloc = pOut->zMalloc;
  65627. pOut->zMalloc = 0;
  65628. sqlite3VdbeMemMove(pOut, pIn1);
  65629. #ifdef SQLITE_DEBUG
  65630. if( pOut->pScopyFrom>=&aMem[u.ad.p1] && pOut->pScopyFrom<&aMem[u.ad.p1+pOp->p3] ){
  65631. pOut->pScopyFrom += u.ad.p1 - pOp->p2;
  65632. }
  65633. #endif
  65634. pIn1->zMalloc = u.ad.zMalloc;
  65635. REGISTER_TRACE(u.ad.p2++, pOut);
  65636. pIn1++;
  65637. pOut++;
  65638. }
  65639. break;
  65640. }
  65641. /* Opcode: Copy P1 P2 P3 * *
  65642. **
  65643. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  65644. **
  65645. ** This instruction makes a deep copy of the value. A duplicate
  65646. ** is made of any string or blob constant. See also OP_SCopy.
  65647. */
  65648. case OP_Copy: {
  65649. #if 0 /* local variables moved into u.ae */
  65650. int n;
  65651. #endif /* local variables moved into u.ae */
  65652. u.ae.n = pOp->p3;
  65653. pIn1 = &aMem[pOp->p1];
  65654. pOut = &aMem[pOp->p2];
  65655. assert( pOut!=pIn1 );
  65656. while( 1 ){
  65657. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65658. Deephemeralize(pOut);
  65659. #ifdef SQLITE_DEBUG
  65660. pOut->pScopyFrom = 0;
  65661. #endif
  65662. REGISTER_TRACE(pOp->p2+pOp->p3-u.ae.n, pOut);
  65663. if( (u.ae.n--)==0 ) break;
  65664. pOut++;
  65665. pIn1++;
  65666. }
  65667. break;
  65668. }
  65669. /* Opcode: SCopy P1 P2 * * *
  65670. **
  65671. ** Make a shallow copy of register P1 into register P2.
  65672. **
  65673. ** This instruction makes a shallow copy of the value. If the value
  65674. ** is a string or blob, then the copy is only a pointer to the
  65675. ** original and hence if the original changes so will the copy.
  65676. ** Worse, if the original is deallocated, the copy becomes invalid.
  65677. ** Thus the program must guarantee that the original will not change
  65678. ** during the lifetime of the copy. Use OP_Copy to make a complete
  65679. ** copy.
  65680. */
  65681. case OP_SCopy: { /* in1, out2 */
  65682. pIn1 = &aMem[pOp->p1];
  65683. pOut = &aMem[pOp->p2];
  65684. assert( pOut!=pIn1 );
  65685. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65686. #ifdef SQLITE_DEBUG
  65687. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  65688. #endif
  65689. REGISTER_TRACE(pOp->p2, pOut);
  65690. break;
  65691. }
  65692. /* Opcode: ResultRow P1 P2 * * *
  65693. **
  65694. ** The registers P1 through P1+P2-1 contain a single row of
  65695. ** results. This opcode causes the sqlite3_step() call to terminate
  65696. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  65697. ** structure to provide access to the top P1 values as the result
  65698. ** row.
  65699. */
  65700. case OP_ResultRow: {
  65701. #if 0 /* local variables moved into u.af */
  65702. Mem *pMem;
  65703. int i;
  65704. #endif /* local variables moved into u.af */
  65705. assert( p->nResColumn==pOp->p2 );
  65706. assert( pOp->p1>0 );
  65707. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  65708. /* If this statement has violated immediate foreign key constraints, do
  65709. ** not return the number of rows modified. And do not RELEASE the statement
  65710. ** transaction. It needs to be rolled back. */
  65711. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  65712. assert( db->flags&SQLITE_CountRows );
  65713. assert( p->usesStmtJournal );
  65714. break;
  65715. }
  65716. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  65717. ** DML statements invoke this opcode to return the number of rows
  65718. ** modified to the user. This is the only way that a VM that
  65719. ** opens a statement transaction may invoke this opcode.
  65720. **
  65721. ** In case this is such a statement, close any statement transaction
  65722. ** opened by this VM before returning control to the user. This is to
  65723. ** ensure that statement-transactions are always nested, not overlapping.
  65724. ** If the open statement-transaction is not closed here, then the user
  65725. ** may step another VM that opens its own statement transaction. This
  65726. ** may lead to overlapping statement transactions.
  65727. **
  65728. ** The statement transaction is never a top-level transaction. Hence
  65729. ** the RELEASE call below can never fail.
  65730. */
  65731. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  65732. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  65733. if( NEVER(rc!=SQLITE_OK) ){
  65734. break;
  65735. }
  65736. /* Invalidate all ephemeral cursor row caches */
  65737. p->cacheCtr = (p->cacheCtr + 2)|1;
  65738. /* Make sure the results of the current row are \000 terminated
  65739. ** and have an assigned type. The results are de-ephemeralized as
  65740. ** a side effect.
  65741. */
  65742. u.af.pMem = p->pResultSet = &aMem[pOp->p1];
  65743. for(u.af.i=0; u.af.i<pOp->p2; u.af.i++){
  65744. assert( memIsValid(&u.af.pMem[u.af.i]) );
  65745. Deephemeralize(&u.af.pMem[u.af.i]);
  65746. assert( (u.af.pMem[u.af.i].flags & MEM_Ephem)==0
  65747. || (u.af.pMem[u.af.i].flags & (MEM_Str|MEM_Blob))==0 );
  65748. sqlite3VdbeMemNulTerminate(&u.af.pMem[u.af.i]);
  65749. sqlite3VdbeMemStoreType(&u.af.pMem[u.af.i]);
  65750. REGISTER_TRACE(pOp->p1+u.af.i, &u.af.pMem[u.af.i]);
  65751. }
  65752. if( db->mallocFailed ) goto no_mem;
  65753. /* Return SQLITE_ROW
  65754. */
  65755. p->pc = pc + 1;
  65756. rc = SQLITE_ROW;
  65757. goto vdbe_return;
  65758. }
  65759. /* Opcode: Concat P1 P2 P3 * *
  65760. **
  65761. ** Add the text in register P1 onto the end of the text in
  65762. ** register P2 and store the result in register P3.
  65763. ** If either the P1 or P2 text are NULL then store NULL in P3.
  65764. **
  65765. ** P3 = P2 || P1
  65766. **
  65767. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  65768. ** if P3 is the same register as P2, the implementation is able
  65769. ** to avoid a memcpy().
  65770. */
  65771. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  65772. #if 0 /* local variables moved into u.ag */
  65773. i64 nByte;
  65774. #endif /* local variables moved into u.ag */
  65775. pIn1 = &aMem[pOp->p1];
  65776. pIn2 = &aMem[pOp->p2];
  65777. pOut = &aMem[pOp->p3];
  65778. assert( pIn1!=pOut );
  65779. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  65780. sqlite3VdbeMemSetNull(pOut);
  65781. break;
  65782. }
  65783. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  65784. Stringify(pIn1, encoding);
  65785. Stringify(pIn2, encoding);
  65786. u.ag.nByte = pIn1->n + pIn2->n;
  65787. if( u.ag.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65788. goto too_big;
  65789. }
  65790. MemSetTypeFlag(pOut, MEM_Str);
  65791. if( sqlite3VdbeMemGrow(pOut, (int)u.ag.nByte+2, pOut==pIn2) ){
  65792. goto no_mem;
  65793. }
  65794. if( pOut!=pIn2 ){
  65795. memcpy(pOut->z, pIn2->z, pIn2->n);
  65796. }
  65797. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  65798. pOut->z[u.ag.nByte] = 0;
  65799. pOut->z[u.ag.nByte+1] = 0;
  65800. pOut->flags |= MEM_Term;
  65801. pOut->n = (int)u.ag.nByte;
  65802. pOut->enc = encoding;
  65803. UPDATE_MAX_BLOBSIZE(pOut);
  65804. break;
  65805. }
  65806. /* Opcode: Add P1 P2 P3 * *
  65807. **
  65808. ** Add the value in register P1 to the value in register P2
  65809. ** and store the result in register P3.
  65810. ** If either input is NULL, the result is NULL.
  65811. */
  65812. /* Opcode: Multiply P1 P2 P3 * *
  65813. **
  65814. **
  65815. ** Multiply the value in register P1 by the value in register P2
  65816. ** and store the result in register P3.
  65817. ** If either input is NULL, the result is NULL.
  65818. */
  65819. /* Opcode: Subtract P1 P2 P3 * *
  65820. **
  65821. ** Subtract the value in register P1 from the value in register P2
  65822. ** and store the result in register P3.
  65823. ** If either input is NULL, the result is NULL.
  65824. */
  65825. /* Opcode: Divide P1 P2 P3 * *
  65826. **
  65827. ** Divide the value in register P1 by the value in register P2
  65828. ** and store the result in register P3 (P3=P2/P1). If the value in
  65829. ** register P1 is zero, then the result is NULL. If either input is
  65830. ** NULL, the result is NULL.
  65831. */
  65832. /* Opcode: Remainder P1 P2 P3 * *
  65833. **
  65834. ** Compute the remainder after integer division of the value in
  65835. ** register P1 by the value in register P2 and store the result in P3.
  65836. ** If the value in register P2 is zero the result is NULL.
  65837. ** If either operand is NULL, the result is NULL.
  65838. */
  65839. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  65840. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  65841. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  65842. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  65843. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  65844. #if 0 /* local variables moved into u.ah */
  65845. char bIntint; /* Started out as two integer operands */
  65846. int flags; /* Combined MEM_* flags from both inputs */
  65847. i64 iA; /* Integer value of left operand */
  65848. i64 iB; /* Integer value of right operand */
  65849. double rA; /* Real value of left operand */
  65850. double rB; /* Real value of right operand */
  65851. #endif /* local variables moved into u.ah */
  65852. pIn1 = &aMem[pOp->p1];
  65853. applyNumericAffinity(pIn1);
  65854. pIn2 = &aMem[pOp->p2];
  65855. applyNumericAffinity(pIn2);
  65856. pOut = &aMem[pOp->p3];
  65857. u.ah.flags = pIn1->flags | pIn2->flags;
  65858. if( (u.ah.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  65859. if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
  65860. u.ah.iA = pIn1->u.i;
  65861. u.ah.iB = pIn2->u.i;
  65862. u.ah.bIntint = 1;
  65863. switch( pOp->opcode ){
  65864. case OP_Add: if( sqlite3AddInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65865. case OP_Subtract: if( sqlite3SubInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65866. case OP_Multiply: if( sqlite3MulInt64(&u.ah.iB,u.ah.iA) ) goto fp_math; break;
  65867. case OP_Divide: {
  65868. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65869. if( u.ah.iA==-1 && u.ah.iB==SMALLEST_INT64 ) goto fp_math;
  65870. u.ah.iB /= u.ah.iA;
  65871. break;
  65872. }
  65873. default: {
  65874. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65875. if( u.ah.iA==-1 ) u.ah.iA = 1;
  65876. u.ah.iB %= u.ah.iA;
  65877. break;
  65878. }
  65879. }
  65880. pOut->u.i = u.ah.iB;
  65881. MemSetTypeFlag(pOut, MEM_Int);
  65882. }else{
  65883. u.ah.bIntint = 0;
  65884. fp_math:
  65885. u.ah.rA = sqlite3VdbeRealValue(pIn1);
  65886. u.ah.rB = sqlite3VdbeRealValue(pIn2);
  65887. switch( pOp->opcode ){
  65888. case OP_Add: u.ah.rB += u.ah.rA; break;
  65889. case OP_Subtract: u.ah.rB -= u.ah.rA; break;
  65890. case OP_Multiply: u.ah.rB *= u.ah.rA; break;
  65891. case OP_Divide: {
  65892. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65893. if( u.ah.rA==(double)0 ) goto arithmetic_result_is_null;
  65894. u.ah.rB /= u.ah.rA;
  65895. break;
  65896. }
  65897. default: {
  65898. u.ah.iA = (i64)u.ah.rA;
  65899. u.ah.iB = (i64)u.ah.rB;
  65900. if( u.ah.iA==0 ) goto arithmetic_result_is_null;
  65901. if( u.ah.iA==-1 ) u.ah.iA = 1;
  65902. u.ah.rB = (double)(u.ah.iB % u.ah.iA);
  65903. break;
  65904. }
  65905. }
  65906. #ifdef SQLITE_OMIT_FLOATING_POINT
  65907. pOut->u.i = u.ah.rB;
  65908. MemSetTypeFlag(pOut, MEM_Int);
  65909. #else
  65910. if( sqlite3IsNaN(u.ah.rB) ){
  65911. goto arithmetic_result_is_null;
  65912. }
  65913. pOut->r = u.ah.rB;
  65914. MemSetTypeFlag(pOut, MEM_Real);
  65915. if( (u.ah.flags & MEM_Real)==0 && !u.ah.bIntint ){
  65916. sqlite3VdbeIntegerAffinity(pOut);
  65917. }
  65918. #endif
  65919. }
  65920. break;
  65921. arithmetic_result_is_null:
  65922. sqlite3VdbeMemSetNull(pOut);
  65923. break;
  65924. }
  65925. /* Opcode: CollSeq P1 * * P4
  65926. **
  65927. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  65928. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  65929. ** be returned. This is used by the built-in min(), max() and nullif()
  65930. ** functions.
  65931. **
  65932. ** If P1 is not zero, then it is a register that a subsequent min() or
  65933. ** max() aggregate will set to 1 if the current row is not the minimum or
  65934. ** maximum. The P1 register is initialized to 0 by this instruction.
  65935. **
  65936. ** The interface used by the implementation of the aforementioned functions
  65937. ** to retrieve the collation sequence set by this opcode is not available
  65938. ** publicly, only to user functions defined in func.c.
  65939. */
  65940. case OP_CollSeq: {
  65941. assert( pOp->p4type==P4_COLLSEQ );
  65942. if( pOp->p1 ){
  65943. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  65944. }
  65945. break;
  65946. }
  65947. /* Opcode: Function P1 P2 P3 P4 P5
  65948. **
  65949. ** Invoke a user function (P4 is a pointer to a Function structure that
  65950. ** defines the function) with P5 arguments taken from register P2 and
  65951. ** successors. The result of the function is stored in register P3.
  65952. ** Register P3 must not be one of the function inputs.
  65953. **
  65954. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  65955. ** function was determined to be constant at compile time. If the first
  65956. ** argument was constant then bit 0 of P1 is set. This is used to determine
  65957. ** whether meta data associated with a user function argument using the
  65958. ** sqlite3_set_auxdata() API may be safely retained until the next
  65959. ** invocation of this opcode.
  65960. **
  65961. ** See also: AggStep and AggFinal
  65962. */
  65963. case OP_Function: {
  65964. #if 0 /* local variables moved into u.ai */
  65965. int i;
  65966. Mem *pArg;
  65967. sqlite3_context ctx;
  65968. sqlite3_value **apVal;
  65969. int n;
  65970. #endif /* local variables moved into u.ai */
  65971. u.ai.n = pOp->p5;
  65972. u.ai.apVal = p->apArg;
  65973. assert( u.ai.apVal || u.ai.n==0 );
  65974. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  65975. pOut = &aMem[pOp->p3];
  65976. memAboutToChange(p, pOut);
  65977. assert( u.ai.n==0 || (pOp->p2>0 && pOp->p2+u.ai.n<=(p->nMem-p->nCursor)+1) );
  65978. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ai.n );
  65979. u.ai.pArg = &aMem[pOp->p2];
  65980. for(u.ai.i=0; u.ai.i<u.ai.n; u.ai.i++, u.ai.pArg++){
  65981. assert( memIsValid(u.ai.pArg) );
  65982. u.ai.apVal[u.ai.i] = u.ai.pArg;
  65983. Deephemeralize(u.ai.pArg);
  65984. sqlite3VdbeMemStoreType(u.ai.pArg);
  65985. REGISTER_TRACE(pOp->p2+u.ai.i, u.ai.pArg);
  65986. }
  65987. assert( pOp->p4type==P4_FUNCDEF );
  65988. u.ai.ctx.pFunc = pOp->p4.pFunc;
  65989. u.ai.ctx.s.flags = MEM_Null;
  65990. u.ai.ctx.s.db = db;
  65991. u.ai.ctx.s.xDel = 0;
  65992. u.ai.ctx.s.zMalloc = 0;
  65993. u.ai.ctx.iOp = pc;
  65994. u.ai.ctx.pVdbe = p;
  65995. /* The output cell may already have a buffer allocated. Move
  65996. ** the pointer to u.ai.ctx.s so in case the user-function can use
  65997. ** the already allocated buffer instead of allocating a new one.
  65998. */
  65999. sqlite3VdbeMemMove(&u.ai.ctx.s, pOut);
  66000. MemSetTypeFlag(&u.ai.ctx.s, MEM_Null);
  66001. u.ai.ctx.fErrorOrAux = 0;
  66002. if( u.ai.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  66003. assert( pOp>aOp );
  66004. assert( pOp[-1].p4type==P4_COLLSEQ );
  66005. assert( pOp[-1].opcode==OP_CollSeq );
  66006. u.ai.ctx.pColl = pOp[-1].p4.pColl;
  66007. }
  66008. db->lastRowid = lastRowid;
  66009. (*u.ai.ctx.pFunc->xFunc)(&u.ai.ctx, u.ai.n, u.ai.apVal); /* IMP: R-24505-23230 */
  66010. lastRowid = db->lastRowid;
  66011. if( db->mallocFailed ){
  66012. /* Even though a malloc() has failed, the implementation of the
  66013. ** user function may have called an sqlite3_result_XXX() function
  66014. ** to return a value. The following call releases any resources
  66015. ** associated with such a value.
  66016. */
  66017. sqlite3VdbeMemRelease(&u.ai.ctx.s);
  66018. goto no_mem;
  66019. }
  66020. /* If the function returned an error, throw an exception */
  66021. if( u.ai.ctx.fErrorOrAux ){
  66022. if( u.ai.ctx.isError ){
  66023. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ai.ctx.s));
  66024. rc = u.ai.ctx.isError;
  66025. }
  66026. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  66027. }
  66028. /* Copy the result of the function into register P3 */
  66029. sqlite3VdbeChangeEncoding(&u.ai.ctx.s, encoding);
  66030. sqlite3VdbeMemMove(pOut, &u.ai.ctx.s);
  66031. if( sqlite3VdbeMemTooBig(pOut) ){
  66032. goto too_big;
  66033. }
  66034. #if 0
  66035. /* The app-defined function has done something that as caused this
  66036. ** statement to expire. (Perhaps the function called sqlite3_exec()
  66037. ** with a CREATE TABLE statement.)
  66038. */
  66039. if( p->expired ) rc = SQLITE_ABORT;
  66040. #endif
  66041. REGISTER_TRACE(pOp->p3, pOut);
  66042. UPDATE_MAX_BLOBSIZE(pOut);
  66043. break;
  66044. }
  66045. /* Opcode: BitAnd P1 P2 P3 * *
  66046. **
  66047. ** Take the bit-wise AND of the values in register P1 and P2 and
  66048. ** store the result in register P3.
  66049. ** If either input is NULL, the result is NULL.
  66050. */
  66051. /* Opcode: BitOr P1 P2 P3 * *
  66052. **
  66053. ** Take the bit-wise OR of the values in register P1 and P2 and
  66054. ** store the result in register P3.
  66055. ** If either input is NULL, the result is NULL.
  66056. */
  66057. /* Opcode: ShiftLeft P1 P2 P3 * *
  66058. **
  66059. ** Shift the integer value in register P2 to the left by the
  66060. ** number of bits specified by the integer in register P1.
  66061. ** Store the result in register P3.
  66062. ** If either input is NULL, the result is NULL.
  66063. */
  66064. /* Opcode: ShiftRight P1 P2 P3 * *
  66065. **
  66066. ** Shift the integer value in register P2 to the right by the
  66067. ** number of bits specified by the integer in register P1.
  66068. ** Store the result in register P3.
  66069. ** If either input is NULL, the result is NULL.
  66070. */
  66071. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  66072. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  66073. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  66074. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  66075. #if 0 /* local variables moved into u.aj */
  66076. i64 iA;
  66077. u64 uA;
  66078. i64 iB;
  66079. u8 op;
  66080. #endif /* local variables moved into u.aj */
  66081. pIn1 = &aMem[pOp->p1];
  66082. pIn2 = &aMem[pOp->p2];
  66083. pOut = &aMem[pOp->p3];
  66084. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  66085. sqlite3VdbeMemSetNull(pOut);
  66086. break;
  66087. }
  66088. u.aj.iA = sqlite3VdbeIntValue(pIn2);
  66089. u.aj.iB = sqlite3VdbeIntValue(pIn1);
  66090. u.aj.op = pOp->opcode;
  66091. if( u.aj.op==OP_BitAnd ){
  66092. u.aj.iA &= u.aj.iB;
  66093. }else if( u.aj.op==OP_BitOr ){
  66094. u.aj.iA |= u.aj.iB;
  66095. }else if( u.aj.iB!=0 ){
  66096. assert( u.aj.op==OP_ShiftRight || u.aj.op==OP_ShiftLeft );
  66097. /* If shifting by a negative amount, shift in the other direction */
  66098. if( u.aj.iB<0 ){
  66099. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  66100. u.aj.op = 2*OP_ShiftLeft + 1 - u.aj.op;
  66101. u.aj.iB = u.aj.iB>(-64) ? -u.aj.iB : 64;
  66102. }
  66103. if( u.aj.iB>=64 ){
  66104. u.aj.iA = (u.aj.iA>=0 || u.aj.op==OP_ShiftLeft) ? 0 : -1;
  66105. }else{
  66106. memcpy(&u.aj.uA, &u.aj.iA, sizeof(u.aj.uA));
  66107. if( u.aj.op==OP_ShiftLeft ){
  66108. u.aj.uA <<= u.aj.iB;
  66109. }else{
  66110. u.aj.uA >>= u.aj.iB;
  66111. /* Sign-extend on a right shift of a negative number */
  66112. if( u.aj.iA<0 ) u.aj.uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-u.aj.iB);
  66113. }
  66114. memcpy(&u.aj.iA, &u.aj.uA, sizeof(u.aj.iA));
  66115. }
  66116. }
  66117. pOut->u.i = u.aj.iA;
  66118. MemSetTypeFlag(pOut, MEM_Int);
  66119. break;
  66120. }
  66121. /* Opcode: AddImm P1 P2 * * *
  66122. **
  66123. ** Add the constant P2 to the value in register P1.
  66124. ** The result is always an integer.
  66125. **
  66126. ** To force any register to be an integer, just add 0.
  66127. */
  66128. case OP_AddImm: { /* in1 */
  66129. pIn1 = &aMem[pOp->p1];
  66130. memAboutToChange(p, pIn1);
  66131. sqlite3VdbeMemIntegerify(pIn1);
  66132. pIn1->u.i += pOp->p2;
  66133. break;
  66134. }
  66135. /* Opcode: MustBeInt P1 P2 * * *
  66136. **
  66137. ** Force the value in register P1 to be an integer. If the value
  66138. ** in P1 is not an integer and cannot be converted into an integer
  66139. ** without data loss, then jump immediately to P2, or if P2==0
  66140. ** raise an SQLITE_MISMATCH exception.
  66141. */
  66142. case OP_MustBeInt: { /* jump, in1 */
  66143. pIn1 = &aMem[pOp->p1];
  66144. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  66145. if( (pIn1->flags & MEM_Int)==0 ){
  66146. if( pOp->p2==0 ){
  66147. rc = SQLITE_MISMATCH;
  66148. goto abort_due_to_error;
  66149. }else{
  66150. pc = pOp->p2 - 1;
  66151. }
  66152. }else{
  66153. MemSetTypeFlag(pIn1, MEM_Int);
  66154. }
  66155. break;
  66156. }
  66157. #ifndef SQLITE_OMIT_FLOATING_POINT
  66158. /* Opcode: RealAffinity P1 * * * *
  66159. **
  66160. ** If register P1 holds an integer convert it to a real value.
  66161. **
  66162. ** This opcode is used when extracting information from a column that
  66163. ** has REAL affinity. Such column values may still be stored as
  66164. ** integers, for space efficiency, but after extraction we want them
  66165. ** to have only a real value.
  66166. */
  66167. case OP_RealAffinity: { /* in1 */
  66168. pIn1 = &aMem[pOp->p1];
  66169. if( pIn1->flags & MEM_Int ){
  66170. sqlite3VdbeMemRealify(pIn1);
  66171. }
  66172. break;
  66173. }
  66174. #endif
  66175. #ifndef SQLITE_OMIT_CAST
  66176. /* Opcode: ToText P1 * * * *
  66177. **
  66178. ** Force the value in register P1 to be text.
  66179. ** If the value is numeric, convert it to a string using the
  66180. ** equivalent of printf(). Blob values are unchanged and
  66181. ** are afterwards simply interpreted as text.
  66182. **
  66183. ** A NULL value is not changed by this routine. It remains NULL.
  66184. */
  66185. case OP_ToText: { /* same as TK_TO_TEXT, in1 */
  66186. pIn1 = &aMem[pOp->p1];
  66187. memAboutToChange(p, pIn1);
  66188. if( pIn1->flags & MEM_Null ) break;
  66189. assert( MEM_Str==(MEM_Blob>>3) );
  66190. pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
  66191. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  66192. rc = ExpandBlob(pIn1);
  66193. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  66194. pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  66195. UPDATE_MAX_BLOBSIZE(pIn1);
  66196. break;
  66197. }
  66198. /* Opcode: ToBlob P1 * * * *
  66199. **
  66200. ** Force the value in register P1 to be a BLOB.
  66201. ** If the value is numeric, convert it to a string first.
  66202. ** Strings are simply reinterpreted as blobs with no change
  66203. ** to the underlying data.
  66204. **
  66205. ** A NULL value is not changed by this routine. It remains NULL.
  66206. */
  66207. case OP_ToBlob: { /* same as TK_TO_BLOB, in1 */
  66208. pIn1 = &aMem[pOp->p1];
  66209. if( pIn1->flags & MEM_Null ) break;
  66210. if( (pIn1->flags & MEM_Blob)==0 ){
  66211. applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
  66212. assert( pIn1->flags & MEM_Str || db->mallocFailed );
  66213. MemSetTypeFlag(pIn1, MEM_Blob);
  66214. }else{
  66215. pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
  66216. }
  66217. UPDATE_MAX_BLOBSIZE(pIn1);
  66218. break;
  66219. }
  66220. /* Opcode: ToNumeric P1 * * * *
  66221. **
  66222. ** Force the value in register P1 to be numeric (either an
  66223. ** integer or a floating-point number.)
  66224. ** If the value is text or blob, try to convert it to an using the
  66225. ** equivalent of atoi() or atof() and store 0 if no such conversion
  66226. ** is possible.
  66227. **
  66228. ** A NULL value is not changed by this routine. It remains NULL.
  66229. */
  66230. case OP_ToNumeric: { /* same as TK_TO_NUMERIC, in1 */
  66231. pIn1 = &aMem[pOp->p1];
  66232. sqlite3VdbeMemNumerify(pIn1);
  66233. break;
  66234. }
  66235. #endif /* SQLITE_OMIT_CAST */
  66236. /* Opcode: ToInt P1 * * * *
  66237. **
  66238. ** Force the value in register P1 to be an integer. If
  66239. ** The value is currently a real number, drop its fractional part.
  66240. ** If the value is text or blob, try to convert it to an integer using the
  66241. ** equivalent of atoi() and store 0 if no such conversion is possible.
  66242. **
  66243. ** A NULL value is not changed by this routine. It remains NULL.
  66244. */
  66245. case OP_ToInt: { /* same as TK_TO_INT, in1 */
  66246. pIn1 = &aMem[pOp->p1];
  66247. if( (pIn1->flags & MEM_Null)==0 ){
  66248. sqlite3VdbeMemIntegerify(pIn1);
  66249. }
  66250. break;
  66251. }
  66252. #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
  66253. /* Opcode: ToReal P1 * * * *
  66254. **
  66255. ** Force the value in register P1 to be a floating point number.
  66256. ** If The value is currently an integer, convert it.
  66257. ** If the value is text or blob, try to convert it to an integer using the
  66258. ** equivalent of atoi() and store 0.0 if no such conversion is possible.
  66259. **
  66260. ** A NULL value is not changed by this routine. It remains NULL.
  66261. */
  66262. case OP_ToReal: { /* same as TK_TO_REAL, in1 */
  66263. pIn1 = &aMem[pOp->p1];
  66264. memAboutToChange(p, pIn1);
  66265. if( (pIn1->flags & MEM_Null)==0 ){
  66266. sqlite3VdbeMemRealify(pIn1);
  66267. }
  66268. break;
  66269. }
  66270. #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
  66271. /* Opcode: Lt P1 P2 P3 P4 P5
  66272. **
  66273. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  66274. ** jump to address P2.
  66275. **
  66276. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  66277. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  66278. ** bit is clear then fall through if either operand is NULL.
  66279. **
  66280. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  66281. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  66282. ** to coerce both inputs according to this affinity before the
  66283. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  66284. ** affinity is used. Note that the affinity conversions are stored
  66285. ** back into the input registers P1 and P3. So this opcode can cause
  66286. ** persistent changes to registers P1 and P3.
  66287. **
  66288. ** Once any conversions have taken place, and neither value is NULL,
  66289. ** the values are compared. If both values are blobs then memcmp() is
  66290. ** used to determine the results of the comparison. If both values
  66291. ** are text, then the appropriate collating function specified in
  66292. ** P4 is used to do the comparison. If P4 is not specified then
  66293. ** memcmp() is used to compare text string. If both values are
  66294. ** numeric, then a numeric comparison is used. If the two values
  66295. ** are of different types, then numbers are considered less than
  66296. ** strings and strings are considered less than blobs.
  66297. **
  66298. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  66299. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  66300. **
  66301. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  66302. ** equal to one another, provided that they do not have their MEM_Cleared
  66303. ** bit set.
  66304. */
  66305. /* Opcode: Ne P1 P2 P3 P4 P5
  66306. **
  66307. ** This works just like the Lt opcode except that the jump is taken if
  66308. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  66309. ** additional information.
  66310. **
  66311. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66312. ** true or false and is never NULL. If both operands are NULL then the result
  66313. ** of comparison is false. If either operand is NULL then the result is true.
  66314. ** If neither operand is NULL the result is the same as it would be if
  66315. ** the SQLITE_NULLEQ flag were omitted from P5.
  66316. */
  66317. /* Opcode: Eq P1 P2 P3 P4 P5
  66318. **
  66319. ** This works just like the Lt opcode except that the jump is taken if
  66320. ** the operands in registers P1 and P3 are equal.
  66321. ** See the Lt opcode for additional information.
  66322. **
  66323. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66324. ** true or false and is never NULL. If both operands are NULL then the result
  66325. ** of comparison is true. If either operand is NULL then the result is false.
  66326. ** If neither operand is NULL the result is the same as it would be if
  66327. ** the SQLITE_NULLEQ flag were omitted from P5.
  66328. */
  66329. /* Opcode: Le P1 P2 P3 P4 P5
  66330. **
  66331. ** This works just like the Lt opcode except that the jump is taken if
  66332. ** the content of register P3 is less than or equal to the content of
  66333. ** register P1. See the Lt opcode for additional information.
  66334. */
  66335. /* Opcode: Gt P1 P2 P3 P4 P5
  66336. **
  66337. ** This works just like the Lt opcode except that the jump is taken if
  66338. ** the content of register P3 is greater than the content of
  66339. ** register P1. See the Lt opcode for additional information.
  66340. */
  66341. /* Opcode: Ge P1 P2 P3 P4 P5
  66342. **
  66343. ** This works just like the Lt opcode except that the jump is taken if
  66344. ** the content of register P3 is greater than or equal to the content of
  66345. ** register P1. See the Lt opcode for additional information.
  66346. */
  66347. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  66348. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  66349. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  66350. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  66351. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  66352. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  66353. #if 0 /* local variables moved into u.ak */
  66354. int res; /* Result of the comparison of pIn1 against pIn3 */
  66355. char affinity; /* Affinity to use for comparison */
  66356. u16 flags1; /* Copy of initial value of pIn1->flags */
  66357. u16 flags3; /* Copy of initial value of pIn3->flags */
  66358. #endif /* local variables moved into u.ak */
  66359. pIn1 = &aMem[pOp->p1];
  66360. pIn3 = &aMem[pOp->p3];
  66361. u.ak.flags1 = pIn1->flags;
  66362. u.ak.flags3 = pIn3->flags;
  66363. if( (u.ak.flags1 | u.ak.flags3)&MEM_Null ){
  66364. /* One or both operands are NULL */
  66365. if( pOp->p5 & SQLITE_NULLEQ ){
  66366. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  66367. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  66368. ** or not both operands are null.
  66369. */
  66370. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  66371. assert( (u.ak.flags1 & MEM_Cleared)==0 );
  66372. if( (u.ak.flags1&MEM_Null)!=0
  66373. && (u.ak.flags3&MEM_Null)!=0
  66374. && (u.ak.flags3&MEM_Cleared)==0
  66375. ){
  66376. u.ak.res = 0; /* Results are equal */
  66377. }else{
  66378. u.ak.res = 1; /* Results are not equal */
  66379. }
  66380. }else{
  66381. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  66382. ** then the result is always NULL.
  66383. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  66384. */
  66385. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  66386. pc = pOp->p2-1;
  66387. }else if( pOp->p5 & SQLITE_STOREP2 ){
  66388. pOut = &aMem[pOp->p2];
  66389. MemSetTypeFlag(pOut, MEM_Null);
  66390. REGISTER_TRACE(pOp->p2, pOut);
  66391. }
  66392. break;
  66393. }
  66394. }else{
  66395. /* Neither operand is NULL. Do a comparison. */
  66396. u.ak.affinity = pOp->p5 & SQLITE_AFF_MASK;
  66397. if( u.ak.affinity ){
  66398. applyAffinity(pIn1, u.ak.affinity, encoding);
  66399. applyAffinity(pIn3, u.ak.affinity, encoding);
  66400. if( db->mallocFailed ) goto no_mem;
  66401. }
  66402. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  66403. ExpandBlob(pIn1);
  66404. ExpandBlob(pIn3);
  66405. u.ak.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  66406. }
  66407. switch( pOp->opcode ){
  66408. case OP_Eq: u.ak.res = u.ak.res==0; break;
  66409. case OP_Ne: u.ak.res = u.ak.res!=0; break;
  66410. case OP_Lt: u.ak.res = u.ak.res<0; break;
  66411. case OP_Le: u.ak.res = u.ak.res<=0; break;
  66412. case OP_Gt: u.ak.res = u.ak.res>0; break;
  66413. default: u.ak.res = u.ak.res>=0; break;
  66414. }
  66415. if( pOp->p5 & SQLITE_STOREP2 ){
  66416. pOut = &aMem[pOp->p2];
  66417. memAboutToChange(p, pOut);
  66418. MemSetTypeFlag(pOut, MEM_Int);
  66419. pOut->u.i = u.ak.res;
  66420. REGISTER_TRACE(pOp->p2, pOut);
  66421. }else if( u.ak.res ){
  66422. pc = pOp->p2-1;
  66423. }
  66424. /* Undo any changes made by applyAffinity() to the input registers. */
  66425. pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ak.flags1&MEM_TypeMask);
  66426. pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ak.flags3&MEM_TypeMask);
  66427. break;
  66428. }
  66429. /* Opcode: Permutation * * * P4 *
  66430. **
  66431. ** Set the permutation used by the OP_Compare operator to be the array
  66432. ** of integers in P4.
  66433. **
  66434. ** The permutation is only valid until the next OP_Compare that has
  66435. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  66436. ** occur immediately prior to the OP_Compare.
  66437. */
  66438. case OP_Permutation: {
  66439. assert( pOp->p4type==P4_INTARRAY );
  66440. assert( pOp->p4.ai );
  66441. aPermute = pOp->p4.ai;
  66442. break;
  66443. }
  66444. /* Opcode: Compare P1 P2 P3 P4 P5
  66445. **
  66446. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  66447. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  66448. ** the comparison for use by the next OP_Jump instruct.
  66449. **
  66450. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  66451. ** determined by the most recent OP_Permutation operator. If the
  66452. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  66453. ** order.
  66454. **
  66455. ** P4 is a KeyInfo structure that defines collating sequences and sort
  66456. ** orders for the comparison. The permutation applies to registers
  66457. ** only. The KeyInfo elements are used sequentially.
  66458. **
  66459. ** The comparison is a sort comparison, so NULLs compare equal,
  66460. ** NULLs are less than numbers, numbers are less than strings,
  66461. ** and strings are less than blobs.
  66462. */
  66463. case OP_Compare: {
  66464. #if 0 /* local variables moved into u.al */
  66465. int n;
  66466. int i;
  66467. int p1;
  66468. int p2;
  66469. const KeyInfo *pKeyInfo;
  66470. int idx;
  66471. CollSeq *pColl; /* Collating sequence to use on this term */
  66472. int bRev; /* True for DESCENDING sort order */
  66473. #endif /* local variables moved into u.al */
  66474. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  66475. u.al.n = pOp->p3;
  66476. u.al.pKeyInfo = pOp->p4.pKeyInfo;
  66477. assert( u.al.n>0 );
  66478. assert( u.al.pKeyInfo!=0 );
  66479. u.al.p1 = pOp->p1;
  66480. u.al.p2 = pOp->p2;
  66481. #if SQLITE_DEBUG
  66482. if( aPermute ){
  66483. int k, mx = 0;
  66484. for(k=0; k<u.al.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  66485. assert( u.al.p1>0 && u.al.p1+mx<=(p->nMem-p->nCursor)+1 );
  66486. assert( u.al.p2>0 && u.al.p2+mx<=(p->nMem-p->nCursor)+1 );
  66487. }else{
  66488. assert( u.al.p1>0 && u.al.p1+u.al.n<=(p->nMem-p->nCursor)+1 );
  66489. assert( u.al.p2>0 && u.al.p2+u.al.n<=(p->nMem-p->nCursor)+1 );
  66490. }
  66491. #endif /* SQLITE_DEBUG */
  66492. for(u.al.i=0; u.al.i<u.al.n; u.al.i++){
  66493. u.al.idx = aPermute ? aPermute[u.al.i] : u.al.i;
  66494. assert( memIsValid(&aMem[u.al.p1+u.al.idx]) );
  66495. assert( memIsValid(&aMem[u.al.p2+u.al.idx]) );
  66496. REGISTER_TRACE(u.al.p1+u.al.idx, &aMem[u.al.p1+u.al.idx]);
  66497. REGISTER_TRACE(u.al.p2+u.al.idx, &aMem[u.al.p2+u.al.idx]);
  66498. assert( u.al.i<u.al.pKeyInfo->nField );
  66499. u.al.pColl = u.al.pKeyInfo->aColl[u.al.i];
  66500. u.al.bRev = u.al.pKeyInfo->aSortOrder[u.al.i];
  66501. iCompare = sqlite3MemCompare(&aMem[u.al.p1+u.al.idx], &aMem[u.al.p2+u.al.idx], u.al.pColl);
  66502. if( iCompare ){
  66503. if( u.al.bRev ) iCompare = -iCompare;
  66504. break;
  66505. }
  66506. }
  66507. aPermute = 0;
  66508. break;
  66509. }
  66510. /* Opcode: Jump P1 P2 P3 * *
  66511. **
  66512. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  66513. ** in the most recent OP_Compare instruction the P1 vector was less than
  66514. ** equal to, or greater than the P2 vector, respectively.
  66515. */
  66516. case OP_Jump: { /* jump */
  66517. if( iCompare<0 ){
  66518. pc = pOp->p1 - 1;
  66519. }else if( iCompare==0 ){
  66520. pc = pOp->p2 - 1;
  66521. }else{
  66522. pc = pOp->p3 - 1;
  66523. }
  66524. break;
  66525. }
  66526. /* Opcode: And P1 P2 P3 * *
  66527. **
  66528. ** Take the logical AND of the values in registers P1 and P2 and
  66529. ** write the result into register P3.
  66530. **
  66531. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  66532. ** the other input is NULL. A NULL and true or two NULLs give
  66533. ** a NULL output.
  66534. */
  66535. /* Opcode: Or P1 P2 P3 * *
  66536. **
  66537. ** Take the logical OR of the values in register P1 and P2 and
  66538. ** store the answer in register P3.
  66539. **
  66540. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  66541. ** even if the other input is NULL. A NULL and false or two NULLs
  66542. ** give a NULL output.
  66543. */
  66544. case OP_And: /* same as TK_AND, in1, in2, out3 */
  66545. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  66546. #if 0 /* local variables moved into u.am */
  66547. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66548. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66549. #endif /* local variables moved into u.am */
  66550. pIn1 = &aMem[pOp->p1];
  66551. if( pIn1->flags & MEM_Null ){
  66552. u.am.v1 = 2;
  66553. }else{
  66554. u.am.v1 = sqlite3VdbeIntValue(pIn1)!=0;
  66555. }
  66556. pIn2 = &aMem[pOp->p2];
  66557. if( pIn2->flags & MEM_Null ){
  66558. u.am.v2 = 2;
  66559. }else{
  66560. u.am.v2 = sqlite3VdbeIntValue(pIn2)!=0;
  66561. }
  66562. if( pOp->opcode==OP_And ){
  66563. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  66564. u.am.v1 = and_logic[u.am.v1*3+u.am.v2];
  66565. }else{
  66566. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  66567. u.am.v1 = or_logic[u.am.v1*3+u.am.v2];
  66568. }
  66569. pOut = &aMem[pOp->p3];
  66570. if( u.am.v1==2 ){
  66571. MemSetTypeFlag(pOut, MEM_Null);
  66572. }else{
  66573. pOut->u.i = u.am.v1;
  66574. MemSetTypeFlag(pOut, MEM_Int);
  66575. }
  66576. break;
  66577. }
  66578. /* Opcode: Not P1 P2 * * *
  66579. **
  66580. ** Interpret the value in register P1 as a boolean value. Store the
  66581. ** boolean complement in register P2. If the value in register P1 is
  66582. ** NULL, then a NULL is stored in P2.
  66583. */
  66584. case OP_Not: { /* same as TK_NOT, in1, out2 */
  66585. pIn1 = &aMem[pOp->p1];
  66586. pOut = &aMem[pOp->p2];
  66587. if( pIn1->flags & MEM_Null ){
  66588. sqlite3VdbeMemSetNull(pOut);
  66589. }else{
  66590. sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
  66591. }
  66592. break;
  66593. }
  66594. /* Opcode: BitNot P1 P2 * * *
  66595. **
  66596. ** Interpret the content of register P1 as an integer. Store the
  66597. ** ones-complement of the P1 value into register P2. If P1 holds
  66598. ** a NULL then store a NULL in P2.
  66599. */
  66600. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  66601. pIn1 = &aMem[pOp->p1];
  66602. pOut = &aMem[pOp->p2];
  66603. if( pIn1->flags & MEM_Null ){
  66604. sqlite3VdbeMemSetNull(pOut);
  66605. }else{
  66606. sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
  66607. }
  66608. break;
  66609. }
  66610. /* Opcode: Once P1 P2 * * *
  66611. **
  66612. ** Check if OP_Once flag P1 is set. If so, jump to instruction P2. Otherwise,
  66613. ** set the flag and fall through to the next instruction.
  66614. */
  66615. case OP_Once: { /* jump */
  66616. assert( pOp->p1<p->nOnceFlag );
  66617. if( p->aOnceFlag[pOp->p1] ){
  66618. pc = pOp->p2-1;
  66619. }else{
  66620. p->aOnceFlag[pOp->p1] = 1;
  66621. }
  66622. break;
  66623. }
  66624. /* Opcode: If P1 P2 P3 * *
  66625. **
  66626. ** Jump to P2 if the value in register P1 is true. The value
  66627. ** is considered true if it is numeric and non-zero. If the value
  66628. ** in P1 is NULL then take the jump if P3 is non-zero.
  66629. */
  66630. /* Opcode: IfNot P1 P2 P3 * *
  66631. **
  66632. ** Jump to P2 if the value in register P1 is False. The value
  66633. ** is considered false if it has a numeric value of zero. If the value
  66634. ** in P1 is NULL then take the jump if P3 is zero.
  66635. */
  66636. case OP_If: /* jump, in1 */
  66637. case OP_IfNot: { /* jump, in1 */
  66638. #if 0 /* local variables moved into u.an */
  66639. int c;
  66640. #endif /* local variables moved into u.an */
  66641. pIn1 = &aMem[pOp->p1];
  66642. if( pIn1->flags & MEM_Null ){
  66643. u.an.c = pOp->p3;
  66644. }else{
  66645. #ifdef SQLITE_OMIT_FLOATING_POINT
  66646. u.an.c = sqlite3VdbeIntValue(pIn1)!=0;
  66647. #else
  66648. u.an.c = sqlite3VdbeRealValue(pIn1)!=0.0;
  66649. #endif
  66650. if( pOp->opcode==OP_IfNot ) u.an.c = !u.an.c;
  66651. }
  66652. if( u.an.c ){
  66653. pc = pOp->p2-1;
  66654. }
  66655. break;
  66656. }
  66657. /* Opcode: IsNull P1 P2 * * *
  66658. **
  66659. ** Jump to P2 if the value in register P1 is NULL.
  66660. */
  66661. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  66662. pIn1 = &aMem[pOp->p1];
  66663. if( (pIn1->flags & MEM_Null)!=0 ){
  66664. pc = pOp->p2 - 1;
  66665. }
  66666. break;
  66667. }
  66668. /* Opcode: NotNull P1 P2 * * *
  66669. **
  66670. ** Jump to P2 if the value in register P1 is not NULL.
  66671. */
  66672. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  66673. pIn1 = &aMem[pOp->p1];
  66674. if( (pIn1->flags & MEM_Null)==0 ){
  66675. pc = pOp->p2 - 1;
  66676. }
  66677. break;
  66678. }
  66679. /* Opcode: Column P1 P2 P3 P4 P5
  66680. **
  66681. ** Interpret the data that cursor P1 points to as a structure built using
  66682. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  66683. ** information about the format of the data.) Extract the P2-th column
  66684. ** from this record. If there are less that (P2+1)
  66685. ** values in the record, extract a NULL.
  66686. **
  66687. ** The value extracted is stored in register P3.
  66688. **
  66689. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  66690. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  66691. ** the result.
  66692. **
  66693. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  66694. ** then the cache of the cursor is reset prior to extracting the column.
  66695. ** The first OP_Column against a pseudo-table after the value of the content
  66696. ** register has changed should have this bit set.
  66697. **
  66698. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  66699. ** the result is guaranteed to only be used as the argument of a length()
  66700. ** or typeof() function, respectively. The loading of large blobs can be
  66701. ** skipped for length() and all content loading can be skipped for typeof().
  66702. */
  66703. case OP_Column: {
  66704. #if 0 /* local variables moved into u.ao */
  66705. u32 payloadSize; /* Number of bytes in the record */
  66706. i64 payloadSize64; /* Number of bytes in the record */
  66707. int p1; /* P1 value of the opcode */
  66708. int p2; /* column number to retrieve */
  66709. VdbeCursor *pC; /* The VDBE cursor */
  66710. char *zRec; /* Pointer to complete record-data */
  66711. BtCursor *pCrsr; /* The BTree cursor */
  66712. u32 *aType; /* aType[i] holds the numeric type of the i-th column */
  66713. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  66714. int nField; /* number of fields in the record */
  66715. int len; /* The length of the serialized data for the column */
  66716. int i; /* Loop counter */
  66717. char *zData; /* Part of the record being decoded */
  66718. Mem *pDest; /* Where to write the extracted value */
  66719. Mem sMem; /* For storing the record being decoded */
  66720. u8 *zIdx; /* Index into header */
  66721. u8 *zEndHdr; /* Pointer to first byte after the header */
  66722. u32 offset; /* Offset into the data */
  66723. u32 szField; /* Number of bytes in the content of a field */
  66724. int szHdr; /* Size of the header size field at start of record */
  66725. int avail; /* Number of bytes of available data */
  66726. u32 t; /* A type code from the record header */
  66727. Mem *pReg; /* PseudoTable input register */
  66728. #endif /* local variables moved into u.ao */
  66729. u.ao.p1 = pOp->p1;
  66730. u.ao.p2 = pOp->p2;
  66731. u.ao.pC = 0;
  66732. memset(&u.ao.sMem, 0, sizeof(u.ao.sMem));
  66733. assert( u.ao.p1<p->nCursor );
  66734. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66735. u.ao.pDest = &aMem[pOp->p3];
  66736. memAboutToChange(p, u.ao.pDest);
  66737. u.ao.zRec = 0;
  66738. /* This block sets the variable u.ao.payloadSize to be the total number of
  66739. ** bytes in the record.
  66740. **
  66741. ** u.ao.zRec is set to be the complete text of the record if it is available.
  66742. ** The complete record text is always available for pseudo-tables
  66743. ** If the record is stored in a cursor, the complete record text
  66744. ** might be available in the u.ao.pC->aRow cache. Or it might not be.
  66745. ** If the data is unavailable, u.ao.zRec is set to NULL.
  66746. **
  66747. ** We also compute the number of columns in the record. For cursors,
  66748. ** the number of columns is stored in the VdbeCursor.nField element.
  66749. */
  66750. u.ao.pC = p->apCsr[u.ao.p1];
  66751. assert( u.ao.pC!=0 );
  66752. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66753. assert( u.ao.pC->pVtabCursor==0 );
  66754. #endif
  66755. u.ao.pCrsr = u.ao.pC->pCursor;
  66756. if( u.ao.pCrsr!=0 ){
  66757. /* The record is stored in a B-Tree */
  66758. rc = sqlite3VdbeCursorMoveto(u.ao.pC);
  66759. if( rc ) goto abort_due_to_error;
  66760. if( u.ao.pC->nullRow ){
  66761. u.ao.payloadSize = 0;
  66762. }else if( u.ao.pC->cacheStatus==p->cacheCtr ){
  66763. u.ao.payloadSize = u.ao.pC->payloadSize;
  66764. u.ao.zRec = (char*)u.ao.pC->aRow;
  66765. }else if( u.ao.pC->isIndex ){
  66766. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  66767. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.ao.pCrsr, &u.ao.payloadSize64);
  66768. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  66769. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  66770. ** payload size, so it is impossible for u.ao.payloadSize64 to be
  66771. ** larger than 32 bits. */
  66772. assert( (u.ao.payloadSize64 & SQLITE_MAX_U32)==(u64)u.ao.payloadSize64 );
  66773. u.ao.payloadSize = (u32)u.ao.payloadSize64;
  66774. }else{
  66775. assert( sqlite3BtreeCursorIsValid(u.ao.pCrsr) );
  66776. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.ao.pCrsr, &u.ao.payloadSize);
  66777. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  66778. }
  66779. }else if( ALWAYS(u.ao.pC->pseudoTableReg>0) ){
  66780. u.ao.pReg = &aMem[u.ao.pC->pseudoTableReg];
  66781. if( u.ao.pC->multiPseudo ){
  66782. sqlite3VdbeMemShallowCopy(u.ao.pDest, u.ao.pReg+u.ao.p2, MEM_Ephem);
  66783. Deephemeralize(u.ao.pDest);
  66784. goto op_column_out;
  66785. }
  66786. assert( u.ao.pReg->flags & MEM_Blob );
  66787. assert( memIsValid(u.ao.pReg) );
  66788. u.ao.payloadSize = u.ao.pReg->n;
  66789. u.ao.zRec = u.ao.pReg->z;
  66790. u.ao.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
  66791. assert( u.ao.payloadSize==0 || u.ao.zRec!=0 );
  66792. }else{
  66793. /* Consider the row to be NULL */
  66794. u.ao.payloadSize = 0;
  66795. }
  66796. /* If u.ao.payloadSize is 0, then just store a NULL. This can happen because of
  66797. ** nullRow or because of a corrupt database. */
  66798. if( u.ao.payloadSize==0 ){
  66799. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  66800. goto op_column_out;
  66801. }
  66802. assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
  66803. if( u.ao.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66804. goto too_big;
  66805. }
  66806. u.ao.nField = u.ao.pC->nField;
  66807. assert( u.ao.p2<u.ao.nField );
  66808. /* Read and parse the table header. Store the results of the parse
  66809. ** into the record header cache fields of the cursor.
  66810. */
  66811. u.ao.aType = u.ao.pC->aType;
  66812. if( u.ao.pC->cacheStatus==p->cacheCtr ){
  66813. u.ao.aOffset = u.ao.pC->aOffset;
  66814. }else{
  66815. assert(u.ao.aType);
  66816. u.ao.avail = 0;
  66817. u.ao.pC->aOffset = u.ao.aOffset = &u.ao.aType[u.ao.nField];
  66818. u.ao.pC->payloadSize = u.ao.payloadSize;
  66819. u.ao.pC->cacheStatus = p->cacheCtr;
  66820. /* Figure out how many bytes are in the header */
  66821. if( u.ao.zRec ){
  66822. u.ao.zData = u.ao.zRec;
  66823. }else{
  66824. if( u.ao.pC->isIndex ){
  66825. u.ao.zData = (char*)sqlite3BtreeKeyFetch(u.ao.pCrsr, &u.ao.avail);
  66826. }else{
  66827. u.ao.zData = (char*)sqlite3BtreeDataFetch(u.ao.pCrsr, &u.ao.avail);
  66828. }
  66829. /* If KeyFetch()/DataFetch() managed to get the entire payload,
  66830. ** save the payload in the u.ao.pC->aRow cache. That will save us from
  66831. ** having to make additional calls to fetch the content portion of
  66832. ** the record.
  66833. */
  66834. assert( u.ao.avail>=0 );
  66835. if( u.ao.payloadSize <= (u32)u.ao.avail ){
  66836. u.ao.zRec = u.ao.zData;
  66837. u.ao.pC->aRow = (u8*)u.ao.zData;
  66838. }else{
  66839. u.ao.pC->aRow = 0;
  66840. }
  66841. }
  66842. /* The following assert is true in all cases except when
  66843. ** the database file has been corrupted externally.
  66844. ** assert( u.ao.zRec!=0 || u.ao.avail>=u.ao.payloadSize || u.ao.avail>=9 ); */
  66845. u.ao.szHdr = getVarint32((u8*)u.ao.zData, u.ao.offset);
  66846. /* Make sure a corrupt database has not given us an oversize header.
  66847. ** Do this now to avoid an oversize memory allocation.
  66848. **
  66849. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  66850. ** types use so much data space that there can only be 4096 and 32 of
  66851. ** them, respectively. So the maximum header length results from a
  66852. ** 3-byte type for each of the maximum of 32768 columns plus three
  66853. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  66854. */
  66855. if( u.ao.offset > 98307 ){
  66856. rc = SQLITE_CORRUPT_BKPT;
  66857. goto op_column_out;
  66858. }
  66859. /* Compute in u.ao.len the number of bytes of data we need to read in order
  66860. ** to get u.ao.nField type values. u.ao.offset is an upper bound on this. But
  66861. ** u.ao.nField might be significantly less than the true number of columns
  66862. ** in the table, and in that case, 5*u.ao.nField+3 might be smaller than u.ao.offset.
  66863. ** We want to minimize u.ao.len in order to limit the size of the memory
  66864. ** allocation, especially if a corrupt database file has caused u.ao.offset
  66865. ** to be oversized. Offset is limited to 98307 above. But 98307 might
  66866. ** still exceed Robson memory allocation limits on some configurations.
  66867. ** On systems that cannot tolerate large memory allocations, u.ao.nField*5+3
  66868. ** will likely be much smaller since u.ao.nField will likely be less than
  66869. ** 20 or so. This insures that Robson memory allocation limits are
  66870. ** not exceeded even for corrupt database files.
  66871. */
  66872. u.ao.len = u.ao.nField*5 + 3;
  66873. if( u.ao.len > (int)u.ao.offset ) u.ao.len = (int)u.ao.offset;
  66874. /* The KeyFetch() or DataFetch() above are fast and will get the entire
  66875. ** record header in most cases. But they will fail to get the complete
  66876. ** record header if the record header does not fit on a single page
  66877. ** in the B-Tree. When that happens, use sqlite3VdbeMemFromBtree() to
  66878. ** acquire the complete header text.
  66879. */
  66880. if( !u.ao.zRec && u.ao.avail<u.ao.len ){
  66881. u.ao.sMem.flags = 0;
  66882. u.ao.sMem.db = 0;
  66883. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, 0, u.ao.len, u.ao.pC->isIndex, &u.ao.sMem);
  66884. if( rc!=SQLITE_OK ){
  66885. goto op_column_out;
  66886. }
  66887. u.ao.zData = u.ao.sMem.z;
  66888. }
  66889. u.ao.zEndHdr = (u8 *)&u.ao.zData[u.ao.len];
  66890. u.ao.zIdx = (u8 *)&u.ao.zData[u.ao.szHdr];
  66891. /* Scan the header and use it to fill in the u.ao.aType[] and u.ao.aOffset[]
  66892. ** arrays. u.ao.aType[u.ao.i] will contain the type integer for the u.ao.i-th
  66893. ** column and u.ao.aOffset[u.ao.i] will contain the u.ao.offset from the beginning
  66894. ** of the record to the start of the data for the u.ao.i-th column
  66895. */
  66896. for(u.ao.i=0; u.ao.i<u.ao.nField; u.ao.i++){
  66897. if( u.ao.zIdx<u.ao.zEndHdr ){
  66898. u.ao.aOffset[u.ao.i] = u.ao.offset;
  66899. if( u.ao.zIdx[0]<0x80 ){
  66900. u.ao.t = u.ao.zIdx[0];
  66901. u.ao.zIdx++;
  66902. }else{
  66903. u.ao.zIdx += sqlite3GetVarint32(u.ao.zIdx, &u.ao.t);
  66904. }
  66905. u.ao.aType[u.ao.i] = u.ao.t;
  66906. u.ao.szField = sqlite3VdbeSerialTypeLen(u.ao.t);
  66907. u.ao.offset += u.ao.szField;
  66908. if( u.ao.offset<u.ao.szField ){ /* True if u.ao.offset overflows */
  66909. u.ao.zIdx = &u.ao.zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  66910. break;
  66911. }
  66912. }else{
  66913. /* If u.ao.i is less that u.ao.nField, then there are fewer fields in this
  66914. ** record than SetNumColumns indicated there are columns in the
  66915. ** table. Set the u.ao.offset for any extra columns not present in
  66916. ** the record to 0. This tells code below to store the default value
  66917. ** for the column instead of deserializing a value from the record.
  66918. */
  66919. u.ao.aOffset[u.ao.i] = 0;
  66920. }
  66921. }
  66922. sqlite3VdbeMemRelease(&u.ao.sMem);
  66923. u.ao.sMem.flags = MEM_Null;
  66924. /* If we have read more header data than was contained in the header,
  66925. ** or if the end of the last field appears to be past the end of the
  66926. ** record, or if the end of the last field appears to be before the end
  66927. ** of the record (when all fields present), then we must be dealing
  66928. ** with a corrupt database.
  66929. */
  66930. if( (u.ao.zIdx > u.ao.zEndHdr) || (u.ao.offset > u.ao.payloadSize)
  66931. || (u.ao.zIdx==u.ao.zEndHdr && u.ao.offset!=u.ao.payloadSize) ){
  66932. rc = SQLITE_CORRUPT_BKPT;
  66933. goto op_column_out;
  66934. }
  66935. }
  66936. /* Get the column information. If u.ao.aOffset[u.ao.p2] is non-zero, then
  66937. ** deserialize the value from the record. If u.ao.aOffset[u.ao.p2] is zero,
  66938. ** then there are not enough fields in the record to satisfy the
  66939. ** request. In this case, set the value NULL or to P4 if P4 is
  66940. ** a pointer to a Mem object.
  66941. */
  66942. if( u.ao.aOffset[u.ao.p2] ){
  66943. assert( rc==SQLITE_OK );
  66944. if( u.ao.zRec ){
  66945. /* This is the common case where the whole row fits on a single page */
  66946. VdbeMemRelease(u.ao.pDest);
  66947. sqlite3VdbeSerialGet((u8 *)&u.ao.zRec[u.ao.aOffset[u.ao.p2]], u.ao.aType[u.ao.p2], u.ao.pDest);
  66948. }else{
  66949. /* This branch happens only when the row overflows onto multiple pages */
  66950. u.ao.t = u.ao.aType[u.ao.p2];
  66951. if( (pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  66952. && ((u.ao.t>=12 && (u.ao.t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0)
  66953. ){
  66954. /* Content is irrelevant for the typeof() function and for
  66955. ** the length(X) function if X is a blob. So we might as well use
  66956. ** bogus content rather than reading content from disk. NULL works
  66957. ** for text and blob and whatever is in the u.ao.payloadSize64 variable
  66958. ** will work for everything else. */
  66959. u.ao.zData = u.ao.t<12 ? (char*)&u.ao.payloadSize64 : 0;
  66960. }else{
  66961. u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.t);
  66962. sqlite3VdbeMemMove(&u.ao.sMem, u.ao.pDest);
  66963. rc = sqlite3VdbeMemFromBtree(u.ao.pCrsr, u.ao.aOffset[u.ao.p2], u.ao.len, u.ao.pC->isIndex,
  66964. &u.ao.sMem);
  66965. if( rc!=SQLITE_OK ){
  66966. goto op_column_out;
  66967. }
  66968. u.ao.zData = u.ao.sMem.z;
  66969. }
  66970. sqlite3VdbeSerialGet((u8*)u.ao.zData, u.ao.t, u.ao.pDest);
  66971. }
  66972. u.ao.pDest->enc = encoding;
  66973. }else{
  66974. if( pOp->p4type==P4_MEM ){
  66975. sqlite3VdbeMemShallowCopy(u.ao.pDest, pOp->p4.pMem, MEM_Static);
  66976. }else{
  66977. MemSetTypeFlag(u.ao.pDest, MEM_Null);
  66978. }
  66979. }
  66980. /* If we dynamically allocated space to hold the data (in the
  66981. ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
  66982. ** dynamically allocated space over to the u.ao.pDest structure.
  66983. ** This prevents a memory copy.
  66984. */
  66985. if( u.ao.sMem.zMalloc ){
  66986. assert( u.ao.sMem.z==u.ao.sMem.zMalloc );
  66987. assert( !(u.ao.pDest->flags & MEM_Dyn) );
  66988. assert( !(u.ao.pDest->flags & (MEM_Blob|MEM_Str)) || u.ao.pDest->z==u.ao.sMem.z );
  66989. u.ao.pDest->flags &= ~(MEM_Ephem|MEM_Static);
  66990. u.ao.pDest->flags |= MEM_Term;
  66991. u.ao.pDest->z = u.ao.sMem.z;
  66992. u.ao.pDest->zMalloc = u.ao.sMem.zMalloc;
  66993. }
  66994. rc = sqlite3VdbeMemMakeWriteable(u.ao.pDest);
  66995. op_column_out:
  66996. UPDATE_MAX_BLOBSIZE(u.ao.pDest);
  66997. REGISTER_TRACE(pOp->p3, u.ao.pDest);
  66998. break;
  66999. }
  67000. /* Opcode: Affinity P1 P2 * P4 *
  67001. **
  67002. ** Apply affinities to a range of P2 registers starting with P1.
  67003. **
  67004. ** P4 is a string that is P2 characters long. The nth character of the
  67005. ** string indicates the column affinity that should be used for the nth
  67006. ** memory cell in the range.
  67007. */
  67008. case OP_Affinity: {
  67009. #if 0 /* local variables moved into u.ap */
  67010. const char *zAffinity; /* The affinity to be applied */
  67011. char cAff; /* A single character of affinity */
  67012. #endif /* local variables moved into u.ap */
  67013. u.ap.zAffinity = pOp->p4.z;
  67014. assert( u.ap.zAffinity!=0 );
  67015. assert( u.ap.zAffinity[pOp->p2]==0 );
  67016. pIn1 = &aMem[pOp->p1];
  67017. while( (u.ap.cAff = *(u.ap.zAffinity++))!=0 ){
  67018. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  67019. assert( memIsValid(pIn1) );
  67020. ExpandBlob(pIn1);
  67021. applyAffinity(pIn1, u.ap.cAff, encoding);
  67022. pIn1++;
  67023. }
  67024. break;
  67025. }
  67026. /* Opcode: MakeRecord P1 P2 P3 P4 *
  67027. **
  67028. ** Convert P2 registers beginning with P1 into the [record format]
  67029. ** use as a data record in a database table or as a key
  67030. ** in an index. The OP_Column opcode can decode the record later.
  67031. **
  67032. ** P4 may be a string that is P2 characters long. The nth character of the
  67033. ** string indicates the column affinity that should be used for the nth
  67034. ** field of the index key.
  67035. **
  67036. ** The mapping from character to affinity is given by the SQLITE_AFF_
  67037. ** macros defined in sqliteInt.h.
  67038. **
  67039. ** If P4 is NULL then all index fields have the affinity NONE.
  67040. */
  67041. case OP_MakeRecord: {
  67042. #if 0 /* local variables moved into u.aq */
  67043. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  67044. Mem *pRec; /* The new record */
  67045. u64 nData; /* Number of bytes of data space */
  67046. int nHdr; /* Number of bytes of header space */
  67047. i64 nByte; /* Data space required for this record */
  67048. int nZero; /* Number of zero bytes at the end of the record */
  67049. int nVarint; /* Number of bytes in a varint */
  67050. u32 serial_type; /* Type field */
  67051. Mem *pData0; /* First field to be combined into the record */
  67052. Mem *pLast; /* Last field of the record */
  67053. int nField; /* Number of fields in the record */
  67054. char *zAffinity; /* The affinity string for the record */
  67055. int file_format; /* File format to use for encoding */
  67056. int i; /* Space used in zNewRecord[] */
  67057. int len; /* Length of a field */
  67058. #endif /* local variables moved into u.aq */
  67059. /* Assuming the record contains N fields, the record format looks
  67060. ** like this:
  67061. **
  67062. ** ------------------------------------------------------------------------
  67063. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  67064. ** ------------------------------------------------------------------------
  67065. **
  67066. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  67067. ** and so froth.
  67068. **
  67069. ** Each type field is a varint representing the serial type of the
  67070. ** corresponding data element (see sqlite3VdbeSerialType()). The
  67071. ** hdr-size field is also a varint which is the offset from the beginning
  67072. ** of the record to data0.
  67073. */
  67074. u.aq.nData = 0; /* Number of bytes of data space */
  67075. u.aq.nHdr = 0; /* Number of bytes of header space */
  67076. u.aq.nZero = 0; /* Number of zero bytes at the end of the record */
  67077. u.aq.nField = pOp->p1;
  67078. u.aq.zAffinity = pOp->p4.z;
  67079. assert( u.aq.nField>0 && pOp->p2>0 && pOp->p2+u.aq.nField<=(p->nMem-p->nCursor)+1 );
  67080. u.aq.pData0 = &aMem[u.aq.nField];
  67081. u.aq.nField = pOp->p2;
  67082. u.aq.pLast = &u.aq.pData0[u.aq.nField-1];
  67083. u.aq.file_format = p->minWriteFileFormat;
  67084. /* Identify the output register */
  67085. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  67086. pOut = &aMem[pOp->p3];
  67087. memAboutToChange(p, pOut);
  67088. /* Loop through the elements that will make up the record to figure
  67089. ** out how much space is required for the new record.
  67090. */
  67091. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  67092. assert( memIsValid(u.aq.pRec) );
  67093. if( u.aq.zAffinity ){
  67094. applyAffinity(u.aq.pRec, u.aq.zAffinity[u.aq.pRec-u.aq.pData0], encoding);
  67095. }
  67096. if( u.aq.pRec->flags&MEM_Zero && u.aq.pRec->n>0 ){
  67097. sqlite3VdbeMemExpandBlob(u.aq.pRec);
  67098. }
  67099. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  67100. u.aq.len = sqlite3VdbeSerialTypeLen(u.aq.serial_type);
  67101. u.aq.nData += u.aq.len;
  67102. u.aq.nHdr += sqlite3VarintLen(u.aq.serial_type);
  67103. if( u.aq.pRec->flags & MEM_Zero ){
  67104. /* Only pure zero-filled BLOBs can be input to this Opcode.
  67105. ** We do not allow blobs with a prefix and a zero-filled tail. */
  67106. u.aq.nZero += u.aq.pRec->u.nZero;
  67107. }else if( u.aq.len ){
  67108. u.aq.nZero = 0;
  67109. }
  67110. }
  67111. /* Add the initial header varint and total the size */
  67112. u.aq.nHdr += u.aq.nVarint = sqlite3VarintLen(u.aq.nHdr);
  67113. if( u.aq.nVarint<sqlite3VarintLen(u.aq.nHdr) ){
  67114. u.aq.nHdr++;
  67115. }
  67116. u.aq.nByte = u.aq.nHdr+u.aq.nData-u.aq.nZero;
  67117. if( u.aq.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  67118. goto too_big;
  67119. }
  67120. /* Make sure the output register has a buffer large enough to store
  67121. ** the new record. The output register (pOp->p3) is not allowed to
  67122. ** be one of the input registers (because the following call to
  67123. ** sqlite3VdbeMemGrow() could clobber the value before it is used).
  67124. */
  67125. if( sqlite3VdbeMemGrow(pOut, (int)u.aq.nByte, 0) ){
  67126. goto no_mem;
  67127. }
  67128. u.aq.zNewRecord = (u8 *)pOut->z;
  67129. /* Write the record */
  67130. u.aq.i = putVarint32(u.aq.zNewRecord, u.aq.nHdr);
  67131. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){
  67132. u.aq.serial_type = sqlite3VdbeSerialType(u.aq.pRec, u.aq.file_format);
  67133. u.aq.i += putVarint32(&u.aq.zNewRecord[u.aq.i], u.aq.serial_type); /* serial type */
  67134. }
  67135. for(u.aq.pRec=u.aq.pData0; u.aq.pRec<=u.aq.pLast; u.aq.pRec++){ /* serial data */
  67136. u.aq.i += sqlite3VdbeSerialPut(&u.aq.zNewRecord[u.aq.i], (int)(u.aq.nByte-u.aq.i), u.aq.pRec,u.aq.file_format);
  67137. }
  67138. assert( u.aq.i==u.aq.nByte );
  67139. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  67140. pOut->n = (int)u.aq.nByte;
  67141. pOut->flags = MEM_Blob | MEM_Dyn;
  67142. pOut->xDel = 0;
  67143. if( u.aq.nZero ){
  67144. pOut->u.nZero = u.aq.nZero;
  67145. pOut->flags |= MEM_Zero;
  67146. }
  67147. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  67148. REGISTER_TRACE(pOp->p3, pOut);
  67149. UPDATE_MAX_BLOBSIZE(pOut);
  67150. break;
  67151. }
  67152. /* Opcode: Count P1 P2 * * *
  67153. **
  67154. ** Store the number of entries (an integer value) in the table or index
  67155. ** opened by cursor P1 in register P2
  67156. */
  67157. #ifndef SQLITE_OMIT_BTREECOUNT
  67158. case OP_Count: { /* out2-prerelease */
  67159. #if 0 /* local variables moved into u.ar */
  67160. i64 nEntry;
  67161. BtCursor *pCrsr;
  67162. #endif /* local variables moved into u.ar */
  67163. u.ar.pCrsr = p->apCsr[pOp->p1]->pCursor;
  67164. if( ALWAYS(u.ar.pCrsr) ){
  67165. rc = sqlite3BtreeCount(u.ar.pCrsr, &u.ar.nEntry);
  67166. }else{
  67167. u.ar.nEntry = 0;
  67168. }
  67169. pOut->u.i = u.ar.nEntry;
  67170. break;
  67171. }
  67172. #endif
  67173. /* Opcode: Savepoint P1 * * P4 *
  67174. **
  67175. ** Open, release or rollback the savepoint named by parameter P4, depending
  67176. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  67177. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  67178. */
  67179. case OP_Savepoint: {
  67180. #if 0 /* local variables moved into u.as */
  67181. int p1; /* Value of P1 operand */
  67182. char *zName; /* Name of savepoint */
  67183. int nName;
  67184. Savepoint *pNew;
  67185. Savepoint *pSavepoint;
  67186. Savepoint *pTmp;
  67187. int iSavepoint;
  67188. int ii;
  67189. #endif /* local variables moved into u.as */
  67190. u.as.p1 = pOp->p1;
  67191. u.as.zName = pOp->p4.z;
  67192. /* Assert that the u.as.p1 parameter is valid. Also that if there is no open
  67193. ** transaction, then there cannot be any savepoints.
  67194. */
  67195. assert( db->pSavepoint==0 || db->autoCommit==0 );
  67196. assert( u.as.p1==SAVEPOINT_BEGIN||u.as.p1==SAVEPOINT_RELEASE||u.as.p1==SAVEPOINT_ROLLBACK );
  67197. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  67198. assert( checkSavepointCount(db) );
  67199. assert( p->bIsReader );
  67200. if( u.as.p1==SAVEPOINT_BEGIN ){
  67201. if( db->nVdbeWrite>0 ){
  67202. /* A new savepoint cannot be created if there are active write
  67203. ** statements (i.e. open read/write incremental blob handles).
  67204. */
  67205. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  67206. "SQL statements in progress");
  67207. rc = SQLITE_BUSY;
  67208. }else{
  67209. u.as.nName = sqlite3Strlen30(u.as.zName);
  67210. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67211. /* This call is Ok even if this savepoint is actually a transaction
  67212. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  67213. ** If this is a transaction savepoint being opened, it is guaranteed
  67214. ** that the db->aVTrans[] array is empty. */
  67215. assert( db->autoCommit==0 || db->nVTrans==0 );
  67216. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  67217. db->nStatement+db->nSavepoint);
  67218. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67219. #endif
  67220. /* Create a new savepoint structure. */
  67221. u.as.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.as.nName+1);
  67222. if( u.as.pNew ){
  67223. u.as.pNew->zName = (char *)&u.as.pNew[1];
  67224. memcpy(u.as.pNew->zName, u.as.zName, u.as.nName+1);
  67225. /* If there is no open transaction, then mark this as a special
  67226. ** "transaction savepoint". */
  67227. if( db->autoCommit ){
  67228. db->autoCommit = 0;
  67229. db->isTransactionSavepoint = 1;
  67230. }else{
  67231. db->nSavepoint++;
  67232. }
  67233. /* Link the new savepoint into the database handle's list. */
  67234. u.as.pNew->pNext = db->pSavepoint;
  67235. db->pSavepoint = u.as.pNew;
  67236. u.as.pNew->nDeferredCons = db->nDeferredCons;
  67237. u.as.pNew->nDeferredImmCons = db->nDeferredImmCons;
  67238. }
  67239. }
  67240. }else{
  67241. u.as.iSavepoint = 0;
  67242. /* Find the named savepoint. If there is no such savepoint, then an
  67243. ** an error is returned to the user. */
  67244. for(
  67245. u.as.pSavepoint = db->pSavepoint;
  67246. u.as.pSavepoint && sqlite3StrICmp(u.as.pSavepoint->zName, u.as.zName);
  67247. u.as.pSavepoint = u.as.pSavepoint->pNext
  67248. ){
  67249. u.as.iSavepoint++;
  67250. }
  67251. if( !u.as.pSavepoint ){
  67252. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.as.zName);
  67253. rc = SQLITE_ERROR;
  67254. }else if( db->nVdbeWrite>0 && u.as.p1==SAVEPOINT_RELEASE ){
  67255. /* It is not possible to release (commit) a savepoint if there are
  67256. ** active write statements.
  67257. */
  67258. sqlite3SetString(&p->zErrMsg, db,
  67259. "cannot release savepoint - SQL statements in progress"
  67260. );
  67261. rc = SQLITE_BUSY;
  67262. }else{
  67263. /* Determine whether or not this is a transaction savepoint. If so,
  67264. ** and this is a RELEASE command, then the current transaction
  67265. ** is committed.
  67266. */
  67267. int isTransaction = u.as.pSavepoint->pNext==0 && db->isTransactionSavepoint;
  67268. if( isTransaction && u.as.p1==SAVEPOINT_RELEASE ){
  67269. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67270. goto vdbe_return;
  67271. }
  67272. db->autoCommit = 1;
  67273. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67274. p->pc = pc;
  67275. db->autoCommit = 0;
  67276. p->rc = rc = SQLITE_BUSY;
  67277. goto vdbe_return;
  67278. }
  67279. db->isTransactionSavepoint = 0;
  67280. rc = p->rc;
  67281. }else{
  67282. u.as.iSavepoint = db->nSavepoint - u.as.iSavepoint - 1;
  67283. if( u.as.p1==SAVEPOINT_ROLLBACK ){
  67284. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  67285. sqlite3BtreeTripAllCursors(db->aDb[u.as.ii].pBt, SQLITE_ABORT);
  67286. }
  67287. }
  67288. for(u.as.ii=0; u.as.ii<db->nDb; u.as.ii++){
  67289. rc = sqlite3BtreeSavepoint(db->aDb[u.as.ii].pBt, u.as.p1, u.as.iSavepoint);
  67290. if( rc!=SQLITE_OK ){
  67291. goto abort_due_to_error;
  67292. }
  67293. }
  67294. if( u.as.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
  67295. sqlite3ExpirePreparedStatements(db);
  67296. sqlite3ResetAllSchemasOfConnection(db);
  67297. db->flags = (db->flags | SQLITE_InternChanges);
  67298. }
  67299. }
  67300. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  67301. ** savepoints nested inside of the savepoint being operated on. */
  67302. while( db->pSavepoint!=u.as.pSavepoint ){
  67303. u.as.pTmp = db->pSavepoint;
  67304. db->pSavepoint = u.as.pTmp->pNext;
  67305. sqlite3DbFree(db, u.as.pTmp);
  67306. db->nSavepoint--;
  67307. }
  67308. /* If it is a RELEASE, then destroy the savepoint being operated on
  67309. ** too. If it is a ROLLBACK TO, then set the number of deferred
  67310. ** constraint violations present in the database to the value stored
  67311. ** when the savepoint was created. */
  67312. if( u.as.p1==SAVEPOINT_RELEASE ){
  67313. assert( u.as.pSavepoint==db->pSavepoint );
  67314. db->pSavepoint = u.as.pSavepoint->pNext;
  67315. sqlite3DbFree(db, u.as.pSavepoint);
  67316. if( !isTransaction ){
  67317. db->nSavepoint--;
  67318. }
  67319. }else{
  67320. db->nDeferredCons = u.as.pSavepoint->nDeferredCons;
  67321. db->nDeferredImmCons = u.as.pSavepoint->nDeferredImmCons;
  67322. }
  67323. if( !isTransaction ){
  67324. rc = sqlite3VtabSavepoint(db, u.as.p1, u.as.iSavepoint);
  67325. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67326. }
  67327. }
  67328. }
  67329. break;
  67330. }
  67331. /* Opcode: AutoCommit P1 P2 * * *
  67332. **
  67333. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  67334. ** back any currently active btree transactions. If there are any active
  67335. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  67336. ** there are active writing VMs or active VMs that use shared cache.
  67337. **
  67338. ** This instruction causes the VM to halt.
  67339. */
  67340. case OP_AutoCommit: {
  67341. #if 0 /* local variables moved into u.at */
  67342. int desiredAutoCommit;
  67343. int iRollback;
  67344. int turnOnAC;
  67345. #endif /* local variables moved into u.at */
  67346. u.at.desiredAutoCommit = pOp->p1;
  67347. u.at.iRollback = pOp->p2;
  67348. u.at.turnOnAC = u.at.desiredAutoCommit && !db->autoCommit;
  67349. assert( u.at.desiredAutoCommit==1 || u.at.desiredAutoCommit==0 );
  67350. assert( u.at.desiredAutoCommit==1 || u.at.iRollback==0 );
  67351. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  67352. assert( p->bIsReader );
  67353. #if 0
  67354. if( u.at.turnOnAC && u.at.iRollback && db->nVdbeActive>1 ){
  67355. /* If this instruction implements a ROLLBACK and other VMs are
  67356. ** still running, and a transaction is active, return an error indicating
  67357. ** that the other VMs must complete first.
  67358. */
  67359. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  67360. "SQL statements in progress");
  67361. rc = SQLITE_BUSY;
  67362. }else
  67363. #endif
  67364. if( u.at.turnOnAC && !u.at.iRollback && db->nVdbeWrite>0 ){
  67365. /* If this instruction implements a COMMIT and other VMs are writing
  67366. ** return an error indicating that the other VMs must complete first.
  67367. */
  67368. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  67369. "SQL statements in progress");
  67370. rc = SQLITE_BUSY;
  67371. }else if( u.at.desiredAutoCommit!=db->autoCommit ){
  67372. if( u.at.iRollback ){
  67373. assert( u.at.desiredAutoCommit==1 );
  67374. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  67375. db->autoCommit = 1;
  67376. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67377. goto vdbe_return;
  67378. }else{
  67379. db->autoCommit = (u8)u.at.desiredAutoCommit;
  67380. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67381. p->pc = pc;
  67382. db->autoCommit = (u8)(1-u.at.desiredAutoCommit);
  67383. p->rc = rc = SQLITE_BUSY;
  67384. goto vdbe_return;
  67385. }
  67386. }
  67387. assert( db->nStatement==0 );
  67388. sqlite3CloseSavepoints(db);
  67389. if( p->rc==SQLITE_OK ){
  67390. rc = SQLITE_DONE;
  67391. }else{
  67392. rc = SQLITE_ERROR;
  67393. }
  67394. goto vdbe_return;
  67395. }else{
  67396. sqlite3SetString(&p->zErrMsg, db,
  67397. (!u.at.desiredAutoCommit)?"cannot start a transaction within a transaction":(
  67398. (u.at.iRollback)?"cannot rollback - no transaction is active":
  67399. "cannot commit - no transaction is active"));
  67400. rc = SQLITE_ERROR;
  67401. }
  67402. break;
  67403. }
  67404. /* Opcode: Transaction P1 P2 * * *
  67405. **
  67406. ** Begin a transaction. The transaction ends when a Commit or Rollback
  67407. ** opcode is encountered. Depending on the ON CONFLICT setting, the
  67408. ** transaction might also be rolled back if an error is encountered.
  67409. **
  67410. ** P1 is the index of the database file on which the transaction is
  67411. ** started. Index 0 is the main database file and index 1 is the
  67412. ** file used for temporary tables. Indices of 2 or more are used for
  67413. ** attached databases.
  67414. **
  67415. ** If P2 is non-zero, then a write-transaction is started. A RESERVED lock is
  67416. ** obtained on the database file when a write-transaction is started. No
  67417. ** other process can start another write transaction while this transaction is
  67418. ** underway. Starting a write transaction also creates a rollback journal. A
  67419. ** write transaction must be started before any changes can be made to the
  67420. ** database. If P2 is greater than or equal to 2 then an EXCLUSIVE lock is
  67421. ** also obtained on the file.
  67422. **
  67423. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  67424. ** true (this flag is set if the Vdbe may modify more than one row and may
  67425. ** throw an ABORT exception), a statement transaction may also be opened.
  67426. ** More specifically, a statement transaction is opened iff the database
  67427. ** connection is currently not in autocommit mode, or if there are other
  67428. ** active statements. A statement transaction allows the changes made by this
  67429. ** VDBE to be rolled back after an error without having to roll back the
  67430. ** entire transaction. If no error is encountered, the statement transaction
  67431. ** will automatically commit when the VDBE halts.
  67432. **
  67433. ** If P2 is zero, then a read-lock is obtained on the database file.
  67434. */
  67435. case OP_Transaction: {
  67436. #if 0 /* local variables moved into u.au */
  67437. Btree *pBt;
  67438. #endif /* local variables moved into u.au */
  67439. assert( p->bIsReader );
  67440. assert( p->readOnly==0 || pOp->p2==0 );
  67441. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67442. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67443. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  67444. rc = SQLITE_READONLY;
  67445. goto abort_due_to_error;
  67446. }
  67447. u.au.pBt = db->aDb[pOp->p1].pBt;
  67448. if( u.au.pBt ){
  67449. rc = sqlite3BtreeBeginTrans(u.au.pBt, pOp->p2);
  67450. if( rc==SQLITE_BUSY ){
  67451. p->pc = pc;
  67452. p->rc = rc = SQLITE_BUSY;
  67453. goto vdbe_return;
  67454. }
  67455. if( rc!=SQLITE_OK ){
  67456. goto abort_due_to_error;
  67457. }
  67458. if( pOp->p2 && p->usesStmtJournal
  67459. && (db->autoCommit==0 || db->nVdbeRead>1)
  67460. ){
  67461. assert( sqlite3BtreeIsInTrans(u.au.pBt) );
  67462. if( p->iStatement==0 ){
  67463. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  67464. db->nStatement++;
  67465. p->iStatement = db->nSavepoint + db->nStatement;
  67466. }
  67467. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  67468. if( rc==SQLITE_OK ){
  67469. rc = sqlite3BtreeBeginStmt(u.au.pBt, p->iStatement);
  67470. }
  67471. /* Store the current value of the database handles deferred constraint
  67472. ** counter. If the statement transaction needs to be rolled back,
  67473. ** the value of this counter needs to be restored too. */
  67474. p->nStmtDefCons = db->nDeferredCons;
  67475. p->nStmtDefImmCons = db->nDeferredImmCons;
  67476. }
  67477. }
  67478. break;
  67479. }
  67480. /* Opcode: ReadCookie P1 P2 P3 * *
  67481. **
  67482. ** Read cookie number P3 from database P1 and write it into register P2.
  67483. ** P3==1 is the schema version. P3==2 is the database format.
  67484. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  67485. ** the main database file and P1==1 is the database file used to store
  67486. ** temporary tables.
  67487. **
  67488. ** There must be a read-lock on the database (either a transaction
  67489. ** must be started or there must be an open cursor) before
  67490. ** executing this instruction.
  67491. */
  67492. case OP_ReadCookie: { /* out2-prerelease */
  67493. #if 0 /* local variables moved into u.av */
  67494. int iMeta;
  67495. int iDb;
  67496. int iCookie;
  67497. #endif /* local variables moved into u.av */
  67498. assert( p->bIsReader );
  67499. u.av.iDb = pOp->p1;
  67500. u.av.iCookie = pOp->p3;
  67501. assert( pOp->p3<SQLITE_N_BTREE_META );
  67502. assert( u.av.iDb>=0 && u.av.iDb<db->nDb );
  67503. assert( db->aDb[u.av.iDb].pBt!=0 );
  67504. assert( (p->btreeMask & (((yDbMask)1)<<u.av.iDb))!=0 );
  67505. sqlite3BtreeGetMeta(db->aDb[u.av.iDb].pBt, u.av.iCookie, (u32 *)&u.av.iMeta);
  67506. pOut->u.i = u.av.iMeta;
  67507. break;
  67508. }
  67509. /* Opcode: SetCookie P1 P2 P3 * *
  67510. **
  67511. ** Write the content of register P3 (interpreted as an integer)
  67512. ** into cookie number P2 of database P1. P2==1 is the schema version.
  67513. ** P2==2 is the database format. P2==3 is the recommended pager cache
  67514. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  67515. ** database file used to store temporary tables.
  67516. **
  67517. ** A transaction must be started before executing this opcode.
  67518. */
  67519. case OP_SetCookie: { /* in3 */
  67520. #if 0 /* local variables moved into u.aw */
  67521. Db *pDb;
  67522. #endif /* local variables moved into u.aw */
  67523. assert( pOp->p2<SQLITE_N_BTREE_META );
  67524. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67525. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67526. assert( p->readOnly==0 );
  67527. u.aw.pDb = &db->aDb[pOp->p1];
  67528. assert( u.aw.pDb->pBt!=0 );
  67529. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67530. pIn3 = &aMem[pOp->p3];
  67531. sqlite3VdbeMemIntegerify(pIn3);
  67532. /* See note about index shifting on OP_ReadCookie */
  67533. rc = sqlite3BtreeUpdateMeta(u.aw.pDb->pBt, pOp->p2, (int)pIn3->u.i);
  67534. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  67535. /* When the schema cookie changes, record the new cookie internally */
  67536. u.aw.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  67537. db->flags |= SQLITE_InternChanges;
  67538. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  67539. /* Record changes in the file format */
  67540. u.aw.pDb->pSchema->file_format = (u8)pIn3->u.i;
  67541. }
  67542. if( pOp->p1==1 ){
  67543. /* Invalidate all prepared statements whenever the TEMP database
  67544. ** schema is changed. Ticket #1644 */
  67545. sqlite3ExpirePreparedStatements(db);
  67546. p->expired = 0;
  67547. }
  67548. break;
  67549. }
  67550. /* Opcode: VerifyCookie P1 P2 P3 * *
  67551. **
  67552. ** Check the value of global database parameter number 0 (the
  67553. ** schema version) and make sure it is equal to P2 and that the
  67554. ** generation counter on the local schema parse equals P3.
  67555. **
  67556. ** P1 is the database number which is 0 for the main database file
  67557. ** and 1 for the file holding temporary tables and some higher number
  67558. ** for auxiliary databases.
  67559. **
  67560. ** The cookie changes its value whenever the database schema changes.
  67561. ** This operation is used to detect when that the cookie has changed
  67562. ** and that the current process needs to reread the schema.
  67563. **
  67564. ** Either a transaction needs to have been started or an OP_Open needs
  67565. ** to be executed (to establish a read lock) before this opcode is
  67566. ** invoked.
  67567. */
  67568. case OP_VerifyCookie: {
  67569. #if 0 /* local variables moved into u.ax */
  67570. int iMeta;
  67571. int iGen;
  67572. Btree *pBt;
  67573. #endif /* local variables moved into u.ax */
  67574. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67575. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  67576. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67577. assert( p->bIsReader );
  67578. u.ax.pBt = db->aDb[pOp->p1].pBt;
  67579. if( u.ax.pBt ){
  67580. sqlite3BtreeGetMeta(u.ax.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.ax.iMeta);
  67581. u.ax.iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  67582. }else{
  67583. u.ax.iGen = u.ax.iMeta = 0;
  67584. }
  67585. if( u.ax.iMeta!=pOp->p2 || u.ax.iGen!=pOp->p3 ){
  67586. sqlite3DbFree(db, p->zErrMsg);
  67587. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  67588. /* If the schema-cookie from the database file matches the cookie
  67589. ** stored with the in-memory representation of the schema, do
  67590. ** not reload the schema from the database file.
  67591. **
  67592. ** If virtual-tables are in use, this is not just an optimization.
  67593. ** Often, v-tables store their data in other SQLite tables, which
  67594. ** are queried from within xNext() and other v-table methods using
  67595. ** prepared queries. If such a query is out-of-date, we do not want to
  67596. ** discard the database schema, as the user code implementing the
  67597. ** v-table would have to be ready for the sqlite3_vtab structure itself
  67598. ** to be invalidated whenever sqlite3_step() is called from within
  67599. ** a v-table method.
  67600. */
  67601. if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.ax.iMeta ){
  67602. sqlite3ResetOneSchema(db, pOp->p1);
  67603. }
  67604. p->expired = 1;
  67605. rc = SQLITE_SCHEMA;
  67606. }
  67607. break;
  67608. }
  67609. /* Opcode: OpenRead P1 P2 P3 P4 P5
  67610. **
  67611. ** Open a read-only cursor for the database table whose root page is
  67612. ** P2 in a database file. The database file is determined by P3.
  67613. ** P3==0 means the main database, P3==1 means the database used for
  67614. ** temporary tables, and P3>1 means used the corresponding attached
  67615. ** database. Give the new cursor an identifier of P1. The P1
  67616. ** values need not be contiguous but all P1 values should be small integers.
  67617. ** It is an error for P1 to be negative.
  67618. **
  67619. ** If P5!=0 then use the content of register P2 as the root page, not
  67620. ** the value of P2 itself.
  67621. **
  67622. ** There will be a read lock on the database whenever there is an
  67623. ** open cursor. If the database was unlocked prior to this instruction
  67624. ** then a read lock is acquired as part of this instruction. A read
  67625. ** lock allows other processes to read the database but prohibits
  67626. ** any other process from modifying the database. The read lock is
  67627. ** released when all cursors are closed. If this instruction attempts
  67628. ** to get a read lock but fails, the script terminates with an
  67629. ** SQLITE_BUSY error code.
  67630. **
  67631. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67632. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67633. ** structure, then said structure defines the content and collating
  67634. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67635. ** value, it is set to the number of columns in the table.
  67636. **
  67637. ** See also OpenWrite.
  67638. */
  67639. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  67640. **
  67641. ** Open a read/write cursor named P1 on the table or index whose root
  67642. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  67643. ** root page.
  67644. **
  67645. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67646. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67647. ** structure, then said structure defines the content and collating
  67648. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67649. ** value, it is set to the number of columns in the table, or to the
  67650. ** largest index of any column of the table that is actually used.
  67651. **
  67652. ** This instruction works just like OpenRead except that it opens the cursor
  67653. ** in read/write mode. For a given table, there can be one or more read-only
  67654. ** cursors or a single read/write cursor but not both.
  67655. **
  67656. ** See also OpenRead.
  67657. */
  67658. case OP_OpenRead:
  67659. case OP_OpenWrite: {
  67660. #if 0 /* local variables moved into u.ay */
  67661. int nField;
  67662. KeyInfo *pKeyInfo;
  67663. int p2;
  67664. int iDb;
  67665. int wrFlag;
  67666. Btree *pX;
  67667. VdbeCursor *pCur;
  67668. Db *pDb;
  67669. #endif /* local variables moved into u.ay */
  67670. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  67671. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  67672. assert( p->bIsReader );
  67673. assert( pOp->opcode==OP_OpenRead || p->readOnly==0 );
  67674. if( p->expired ){
  67675. rc = SQLITE_ABORT;
  67676. break;
  67677. }
  67678. u.ay.nField = 0;
  67679. u.ay.pKeyInfo = 0;
  67680. u.ay.p2 = pOp->p2;
  67681. u.ay.iDb = pOp->p3;
  67682. assert( u.ay.iDb>=0 && u.ay.iDb<db->nDb );
  67683. assert( (p->btreeMask & (((yDbMask)1)<<u.ay.iDb))!=0 );
  67684. u.ay.pDb = &db->aDb[u.ay.iDb];
  67685. u.ay.pX = u.ay.pDb->pBt;
  67686. assert( u.ay.pX!=0 );
  67687. if( pOp->opcode==OP_OpenWrite ){
  67688. u.ay.wrFlag = 1;
  67689. assert( sqlite3SchemaMutexHeld(db, u.ay.iDb, 0) );
  67690. if( u.ay.pDb->pSchema->file_format < p->minWriteFileFormat ){
  67691. p->minWriteFileFormat = u.ay.pDb->pSchema->file_format;
  67692. }
  67693. }else{
  67694. u.ay.wrFlag = 0;
  67695. }
  67696. if( pOp->p5 & OPFLAG_P2ISREG ){
  67697. assert( u.ay.p2>0 );
  67698. assert( u.ay.p2<=(p->nMem-p->nCursor) );
  67699. pIn2 = &aMem[u.ay.p2];
  67700. assert( memIsValid(pIn2) );
  67701. assert( (pIn2->flags & MEM_Int)!=0 );
  67702. sqlite3VdbeMemIntegerify(pIn2);
  67703. u.ay.p2 = (int)pIn2->u.i;
  67704. /* The u.ay.p2 value always comes from a prior OP_CreateTable opcode and
  67705. ** that opcode will always set the u.ay.p2 value to 2 or more or else fail.
  67706. ** If there were a failure, the prepared statement would have halted
  67707. ** before reaching this instruction. */
  67708. if( NEVER(u.ay.p2<2) ) {
  67709. rc = SQLITE_CORRUPT_BKPT;
  67710. goto abort_due_to_error;
  67711. }
  67712. }
  67713. if( pOp->p4type==P4_KEYINFO ){
  67714. u.ay.pKeyInfo = pOp->p4.pKeyInfo;
  67715. u.ay.pKeyInfo->enc = ENC(p->db);
  67716. u.ay.nField = u.ay.pKeyInfo->nField+1;
  67717. }else if( pOp->p4type==P4_INT32 ){
  67718. u.ay.nField = pOp->p4.i;
  67719. }
  67720. assert( pOp->p1>=0 );
  67721. u.ay.pCur = allocateCursor(p, pOp->p1, u.ay.nField, u.ay.iDb, 1);
  67722. if( u.ay.pCur==0 ) goto no_mem;
  67723. u.ay.pCur->nullRow = 1;
  67724. u.ay.pCur->isOrdered = 1;
  67725. rc = sqlite3BtreeCursor(u.ay.pX, u.ay.p2, u.ay.wrFlag, u.ay.pKeyInfo, u.ay.pCur->pCursor);
  67726. u.ay.pCur->pKeyInfo = u.ay.pKeyInfo;
  67727. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  67728. sqlite3BtreeCursorHints(u.ay.pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  67729. /* Since it performs no memory allocation or IO, the only value that
  67730. ** sqlite3BtreeCursor() may return is SQLITE_OK. */
  67731. assert( rc==SQLITE_OK );
  67732. /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
  67733. ** SQLite used to check if the root-page flags were sane at this point
  67734. ** and report database corruption if they were not, but this check has
  67735. ** since moved into the btree layer. */
  67736. u.ay.pCur->isTable = pOp->p4type!=P4_KEYINFO;
  67737. u.ay.pCur->isIndex = !u.ay.pCur->isTable;
  67738. break;
  67739. }
  67740. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  67741. **
  67742. ** Open a new cursor P1 to a transient table.
  67743. ** The cursor is always opened read/write even if
  67744. ** the main database is read-only. The ephemeral
  67745. ** table is deleted automatically when the cursor is closed.
  67746. **
  67747. ** P2 is the number of columns in the ephemeral table.
  67748. ** The cursor points to a BTree table if P4==0 and to a BTree index
  67749. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  67750. ** that defines the format of keys in the index.
  67751. **
  67752. ** This opcode was once called OpenTemp. But that created
  67753. ** confusion because the term "temp table", might refer either
  67754. ** to a TEMP table at the SQL level, or to a table opened by
  67755. ** this opcode. Then this opcode was call OpenVirtual. But
  67756. ** that created confusion with the whole virtual-table idea.
  67757. **
  67758. ** The P5 parameter can be a mask of the BTREE_* flags defined
  67759. ** in btree.h. These flags control aspects of the operation of
  67760. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  67761. ** added automatically.
  67762. */
  67763. /* Opcode: OpenAutoindex P1 P2 * P4 *
  67764. **
  67765. ** This opcode works the same as OP_OpenEphemeral. It has a
  67766. ** different name to distinguish its use. Tables created using
  67767. ** by this opcode will be used for automatically created transient
  67768. ** indices in joins.
  67769. */
  67770. case OP_OpenAutoindex:
  67771. case OP_OpenEphemeral: {
  67772. #if 0 /* local variables moved into u.az */
  67773. VdbeCursor *pCx;
  67774. #endif /* local variables moved into u.az */
  67775. static const int vfsFlags =
  67776. SQLITE_OPEN_READWRITE |
  67777. SQLITE_OPEN_CREATE |
  67778. SQLITE_OPEN_EXCLUSIVE |
  67779. SQLITE_OPEN_DELETEONCLOSE |
  67780. SQLITE_OPEN_TRANSIENT_DB;
  67781. assert( pOp->p1>=0 );
  67782. u.az.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67783. if( u.az.pCx==0 ) goto no_mem;
  67784. u.az.pCx->nullRow = 1;
  67785. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &u.az.pCx->pBt,
  67786. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  67787. if( rc==SQLITE_OK ){
  67788. rc = sqlite3BtreeBeginTrans(u.az.pCx->pBt, 1);
  67789. }
  67790. if( rc==SQLITE_OK ){
  67791. /* If a transient index is required, create it by calling
  67792. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  67793. ** opening it. If a transient table is required, just use the
  67794. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  67795. */
  67796. if( pOp->p4.pKeyInfo ){
  67797. int pgno;
  67798. assert( pOp->p4type==P4_KEYINFO );
  67799. rc = sqlite3BtreeCreateTable(u.az.pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  67800. if( rc==SQLITE_OK ){
  67801. assert( pgno==MASTER_ROOT+1 );
  67802. rc = sqlite3BtreeCursor(u.az.pCx->pBt, pgno, 1,
  67803. (KeyInfo*)pOp->p4.z, u.az.pCx->pCursor);
  67804. u.az.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67805. u.az.pCx->pKeyInfo->enc = ENC(p->db);
  67806. }
  67807. u.az.pCx->isTable = 0;
  67808. }else{
  67809. rc = sqlite3BtreeCursor(u.az.pCx->pBt, MASTER_ROOT, 1, 0, u.az.pCx->pCursor);
  67810. u.az.pCx->isTable = 1;
  67811. }
  67812. }
  67813. u.az.pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  67814. u.az.pCx->isIndex = !u.az.pCx->isTable;
  67815. break;
  67816. }
  67817. /* Opcode: SorterOpen P1 P2 * P4 *
  67818. **
  67819. ** This opcode works like OP_OpenEphemeral except that it opens
  67820. ** a transient index that is specifically designed to sort large
  67821. ** tables using an external merge-sort algorithm.
  67822. */
  67823. case OP_SorterOpen: {
  67824. #if 0 /* local variables moved into u.ba */
  67825. VdbeCursor *pCx;
  67826. #endif /* local variables moved into u.ba */
  67827. u.ba.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67828. if( u.ba.pCx==0 ) goto no_mem;
  67829. u.ba.pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67830. u.ba.pCx->pKeyInfo->enc = ENC(p->db);
  67831. u.ba.pCx->isSorter = 1;
  67832. rc = sqlite3VdbeSorterInit(db, u.ba.pCx);
  67833. break;
  67834. }
  67835. /* Opcode: OpenPseudo P1 P2 P3 * P5
  67836. **
  67837. ** Open a new cursor that points to a fake table that contains a single
  67838. ** row of data. The content of that one row in the content of memory
  67839. ** register P2 when P5==0. In other words, cursor P1 becomes an alias for the
  67840. ** MEM_Blob content contained in register P2. When P5==1, then the
  67841. ** row is represented by P3 consecutive registers beginning with P2.
  67842. **
  67843. ** A pseudo-table created by this opcode is used to hold a single
  67844. ** row output from the sorter so that the row can be decomposed into
  67845. ** individual columns using the OP_Column opcode. The OP_Column opcode
  67846. ** is the only cursor opcode that works with a pseudo-table.
  67847. **
  67848. ** P3 is the number of fields in the records that will be stored by
  67849. ** the pseudo-table.
  67850. */
  67851. case OP_OpenPseudo: {
  67852. #if 0 /* local variables moved into u.bb */
  67853. VdbeCursor *pCx;
  67854. #endif /* local variables moved into u.bb */
  67855. assert( pOp->p1>=0 );
  67856. u.bb.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  67857. if( u.bb.pCx==0 ) goto no_mem;
  67858. u.bb.pCx->nullRow = 1;
  67859. u.bb.pCx->pseudoTableReg = pOp->p2;
  67860. u.bb.pCx->isTable = 1;
  67861. u.bb.pCx->isIndex = 0;
  67862. u.bb.pCx->multiPseudo = pOp->p5;
  67863. break;
  67864. }
  67865. /* Opcode: Close P1 * * * *
  67866. **
  67867. ** Close a cursor previously opened as P1. If P1 is not
  67868. ** currently open, this instruction is a no-op.
  67869. */
  67870. case OP_Close: {
  67871. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67872. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  67873. p->apCsr[pOp->p1] = 0;
  67874. break;
  67875. }
  67876. /* Opcode: SeekGe P1 P2 P3 P4 *
  67877. **
  67878. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67879. ** use the value in register P3 as the key. If cursor P1 refers
  67880. ** to an SQL index, then P3 is the first in an array of P4 registers
  67881. ** that are used as an unpacked index key.
  67882. **
  67883. ** Reposition cursor P1 so that it points to the smallest entry that
  67884. ** is greater than or equal to the key value. If there are no records
  67885. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  67886. **
  67887. ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
  67888. */
  67889. /* Opcode: SeekGt P1 P2 P3 P4 *
  67890. **
  67891. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67892. ** use the value in register P3 as a key. If cursor P1 refers
  67893. ** to an SQL index, then P3 is the first in an array of P4 registers
  67894. ** that are used as an unpacked index key.
  67895. **
  67896. ** Reposition cursor P1 so that it points to the smallest entry that
  67897. ** is greater than the key value. If there are no records greater than
  67898. ** the key and P2 is not zero, then jump to P2.
  67899. **
  67900. ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
  67901. */
  67902. /* Opcode: SeekLt P1 P2 P3 P4 *
  67903. **
  67904. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67905. ** use the value in register P3 as a key. If cursor P1 refers
  67906. ** to an SQL index, then P3 is the first in an array of P4 registers
  67907. ** that are used as an unpacked index key.
  67908. **
  67909. ** Reposition cursor P1 so that it points to the largest entry that
  67910. ** is less than the key value. If there are no records less than
  67911. ** the key and P2 is not zero, then jump to P2.
  67912. **
  67913. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
  67914. */
  67915. /* Opcode: SeekLe P1 P2 P3 P4 *
  67916. **
  67917. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67918. ** use the value in register P3 as a key. If cursor P1 refers
  67919. ** to an SQL index, then P3 is the first in an array of P4 registers
  67920. ** that are used as an unpacked index key.
  67921. **
  67922. ** Reposition cursor P1 so that it points to the largest entry that
  67923. ** is less than or equal to the key value. If there are no records
  67924. ** less than or equal to the key and P2 is not zero, then jump to P2.
  67925. **
  67926. ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
  67927. */
  67928. case OP_SeekLt: /* jump, in3 */
  67929. case OP_SeekLe: /* jump, in3 */
  67930. case OP_SeekGe: /* jump, in3 */
  67931. case OP_SeekGt: { /* jump, in3 */
  67932. #if 0 /* local variables moved into u.bc */
  67933. int res;
  67934. int oc;
  67935. VdbeCursor *pC;
  67936. UnpackedRecord r;
  67937. int nField;
  67938. i64 iKey; /* The rowid we are to seek to */
  67939. #endif /* local variables moved into u.bc */
  67940. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67941. assert( pOp->p2!=0 );
  67942. u.bc.pC = p->apCsr[pOp->p1];
  67943. assert( u.bc.pC!=0 );
  67944. assert( u.bc.pC->pseudoTableReg==0 );
  67945. assert( OP_SeekLe == OP_SeekLt+1 );
  67946. assert( OP_SeekGe == OP_SeekLt+2 );
  67947. assert( OP_SeekGt == OP_SeekLt+3 );
  67948. assert( u.bc.pC->isOrdered );
  67949. if( ALWAYS(u.bc.pC->pCursor!=0) ){
  67950. u.bc.oc = pOp->opcode;
  67951. u.bc.pC->nullRow = 0;
  67952. if( u.bc.pC->isTable ){
  67953. /* The input value in P3 might be of any type: integer, real, string,
  67954. ** blob, or NULL. But it needs to be an integer before we can do
  67955. ** the seek, so covert it. */
  67956. pIn3 = &aMem[pOp->p3];
  67957. applyNumericAffinity(pIn3);
  67958. u.bc.iKey = sqlite3VdbeIntValue(pIn3);
  67959. u.bc.pC->rowidIsValid = 0;
  67960. /* If the P3 value could not be converted into an integer without
  67961. ** loss of information, then special processing is required... */
  67962. if( (pIn3->flags & MEM_Int)==0 ){
  67963. if( (pIn3->flags & MEM_Real)==0 ){
  67964. /* If the P3 value cannot be converted into any kind of a number,
  67965. ** then the seek is not possible, so jump to P2 */
  67966. pc = pOp->p2 - 1;
  67967. break;
  67968. }
  67969. /* If we reach this point, then the P3 value must be a floating
  67970. ** point number. */
  67971. assert( (pIn3->flags & MEM_Real)!=0 );
  67972. if( u.bc.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.bc.iKey || pIn3->r>0) ){
  67973. /* The P3 value is too large in magnitude to be expressed as an
  67974. ** integer. */
  67975. u.bc.res = 1;
  67976. if( pIn3->r<0 ){
  67977. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  67978. rc = sqlite3BtreeFirst(u.bc.pC->pCursor, &u.bc.res);
  67979. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67980. }
  67981. }else{
  67982. if( u.bc.oc<=OP_SeekLe ){ assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  67983. rc = sqlite3BtreeLast(u.bc.pC->pCursor, &u.bc.res);
  67984. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67985. }
  67986. }
  67987. if( u.bc.res ){
  67988. pc = pOp->p2 - 1;
  67989. }
  67990. break;
  67991. }else if( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekGe ){
  67992. /* Use the ceiling() function to convert real->int */
  67993. if( pIn3->r > (double)u.bc.iKey ) u.bc.iKey++;
  67994. }else{
  67995. /* Use the floor() function to convert real->int */
  67996. assert( u.bc.oc==OP_SeekLe || u.bc.oc==OP_SeekGt );
  67997. if( pIn3->r < (double)u.bc.iKey ) u.bc.iKey--;
  67998. }
  67999. }
  68000. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, 0, (u64)u.bc.iKey, 0, &u.bc.res);
  68001. if( rc!=SQLITE_OK ){
  68002. goto abort_due_to_error;
  68003. }
  68004. if( u.bc.res==0 ){
  68005. u.bc.pC->rowidIsValid = 1;
  68006. u.bc.pC->lastRowid = u.bc.iKey;
  68007. }
  68008. }else{
  68009. u.bc.nField = pOp->p4.i;
  68010. assert( pOp->p4type==P4_INT32 );
  68011. assert( u.bc.nField>0 );
  68012. u.bc.r.pKeyInfo = u.bc.pC->pKeyInfo;
  68013. u.bc.r.nField = (u16)u.bc.nField;
  68014. /* The next line of code computes as follows, only faster:
  68015. ** if( u.bc.oc==OP_SeekGt || u.bc.oc==OP_SeekLe ){
  68016. ** u.bc.r.flags = UNPACKED_INCRKEY;
  68017. ** }else{
  68018. ** u.bc.r.flags = 0;
  68019. ** }
  68020. */
  68021. u.bc.r.flags = (u8)(UNPACKED_INCRKEY * (1 & (u.bc.oc - OP_SeekLt)));
  68022. assert( u.bc.oc!=OP_SeekGt || u.bc.r.flags==UNPACKED_INCRKEY );
  68023. assert( u.bc.oc!=OP_SeekLe || u.bc.r.flags==UNPACKED_INCRKEY );
  68024. assert( u.bc.oc!=OP_SeekGe || u.bc.r.flags==0 );
  68025. assert( u.bc.oc!=OP_SeekLt || u.bc.r.flags==0 );
  68026. u.bc.r.aMem = &aMem[pOp->p3];
  68027. #ifdef SQLITE_DEBUG
  68028. { int i; for(i=0; i<u.bc.r.nField; i++) assert( memIsValid(&u.bc.r.aMem[i]) ); }
  68029. #endif
  68030. ExpandBlob(u.bc.r.aMem);
  68031. rc = sqlite3BtreeMovetoUnpacked(u.bc.pC->pCursor, &u.bc.r, 0, 0, &u.bc.res);
  68032. if( rc!=SQLITE_OK ){
  68033. goto abort_due_to_error;
  68034. }
  68035. u.bc.pC->rowidIsValid = 0;
  68036. }
  68037. u.bc.pC->deferredMoveto = 0;
  68038. u.bc.pC->cacheStatus = CACHE_STALE;
  68039. #ifdef SQLITE_TEST
  68040. sqlite3_search_count++;
  68041. #endif
  68042. if( u.bc.oc>=OP_SeekGe ){ assert( u.bc.oc==OP_SeekGe || u.bc.oc==OP_SeekGt );
  68043. if( u.bc.res<0 || (u.bc.res==0 && u.bc.oc==OP_SeekGt) ){
  68044. rc = sqlite3BtreeNext(u.bc.pC->pCursor, &u.bc.res);
  68045. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68046. u.bc.pC->rowidIsValid = 0;
  68047. }else{
  68048. u.bc.res = 0;
  68049. }
  68050. }else{
  68051. assert( u.bc.oc==OP_SeekLt || u.bc.oc==OP_SeekLe );
  68052. if( u.bc.res>0 || (u.bc.res==0 && u.bc.oc==OP_SeekLt) ){
  68053. rc = sqlite3BtreePrevious(u.bc.pC->pCursor, &u.bc.res);
  68054. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68055. u.bc.pC->rowidIsValid = 0;
  68056. }else{
  68057. /* u.bc.res might be negative because the table is empty. Check to
  68058. ** see if this is the case.
  68059. */
  68060. u.bc.res = sqlite3BtreeEof(u.bc.pC->pCursor);
  68061. }
  68062. }
  68063. assert( pOp->p2>0 );
  68064. if( u.bc.res ){
  68065. pc = pOp->p2 - 1;
  68066. }
  68067. }else{
  68068. /* This happens when attempting to open the sqlite3_master table
  68069. ** for read access returns SQLITE_EMPTY. In this case always
  68070. ** take the jump (since there are no records in the table).
  68071. */
  68072. pc = pOp->p2 - 1;
  68073. }
  68074. break;
  68075. }
  68076. /* Opcode: Seek P1 P2 * * *
  68077. **
  68078. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  68079. ** for P1 to move so that it points to the rowid given by P2.
  68080. **
  68081. ** This is actually a deferred seek. Nothing actually happens until
  68082. ** the cursor is used to read a record. That way, if no reads
  68083. ** occur, no unnecessary I/O happens.
  68084. */
  68085. case OP_Seek: { /* in2 */
  68086. #if 0 /* local variables moved into u.bd */
  68087. VdbeCursor *pC;
  68088. #endif /* local variables moved into u.bd */
  68089. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68090. u.bd.pC = p->apCsr[pOp->p1];
  68091. assert( u.bd.pC!=0 );
  68092. if( ALWAYS(u.bd.pC->pCursor!=0) ){
  68093. assert( u.bd.pC->isTable );
  68094. u.bd.pC->nullRow = 0;
  68095. pIn2 = &aMem[pOp->p2];
  68096. u.bd.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  68097. u.bd.pC->rowidIsValid = 0;
  68098. u.bd.pC->deferredMoveto = 1;
  68099. }
  68100. break;
  68101. }
  68102. /* Opcode: Found P1 P2 P3 P4 *
  68103. **
  68104. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68105. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68106. ** record.
  68107. **
  68108. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68109. ** is a prefix of any entry in P1 then a jump is made to P2 and
  68110. ** P1 is left pointing at the matching entry.
  68111. */
  68112. /* Opcode: NotFound P1 P2 P3 P4 *
  68113. **
  68114. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  68115. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  68116. ** record.
  68117. **
  68118. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  68119. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  68120. ** does contain an entry whose prefix matches the P3/P4 record then control
  68121. ** falls through to the next instruction and P1 is left pointing at the
  68122. ** matching entry.
  68123. **
  68124. ** See also: Found, NotExists, IsUnique
  68125. */
  68126. case OP_NotFound: /* jump, in3 */
  68127. case OP_Found: { /* jump, in3 */
  68128. #if 0 /* local variables moved into u.be */
  68129. int alreadyExists;
  68130. VdbeCursor *pC;
  68131. int res;
  68132. char *pFree;
  68133. UnpackedRecord *pIdxKey;
  68134. UnpackedRecord r;
  68135. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
  68136. #endif /* local variables moved into u.be */
  68137. #ifdef SQLITE_TEST
  68138. sqlite3_found_count++;
  68139. #endif
  68140. u.be.alreadyExists = 0;
  68141. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68142. assert( pOp->p4type==P4_INT32 );
  68143. u.be.pC = p->apCsr[pOp->p1];
  68144. assert( u.be.pC!=0 );
  68145. pIn3 = &aMem[pOp->p3];
  68146. if( ALWAYS(u.be.pC->pCursor!=0) ){
  68147. assert( u.be.pC->isTable==0 );
  68148. if( pOp->p4.i>0 ){
  68149. u.be.r.pKeyInfo = u.be.pC->pKeyInfo;
  68150. u.be.r.nField = (u16)pOp->p4.i;
  68151. u.be.r.aMem = pIn3;
  68152. #ifdef SQLITE_DEBUG
  68153. { int i; for(i=0; i<u.be.r.nField; i++) assert( memIsValid(&u.be.r.aMem[i]) ); }
  68154. #endif
  68155. u.be.r.flags = UNPACKED_PREFIX_MATCH;
  68156. u.be.pIdxKey = &u.be.r;
  68157. }else{
  68158. u.be.pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  68159. u.be.pC->pKeyInfo, u.be.aTempRec, sizeof(u.be.aTempRec), &u.be.pFree
  68160. );
  68161. if( u.be.pIdxKey==0 ) goto no_mem;
  68162. assert( pIn3->flags & MEM_Blob );
  68163. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  68164. sqlite3VdbeRecordUnpack(u.be.pC->pKeyInfo, pIn3->n, pIn3->z, u.be.pIdxKey);
  68165. u.be.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
  68166. }
  68167. rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, u.be.pIdxKey, 0, 0, &u.be.res);
  68168. if( pOp->p4.i==0 ){
  68169. sqlite3DbFree(db, u.be.pFree);
  68170. }
  68171. if( rc!=SQLITE_OK ){
  68172. break;
  68173. }
  68174. u.be.alreadyExists = (u.be.res==0);
  68175. u.be.pC->deferredMoveto = 0;
  68176. u.be.pC->cacheStatus = CACHE_STALE;
  68177. }
  68178. if( pOp->opcode==OP_Found ){
  68179. if( u.be.alreadyExists ) pc = pOp->p2 - 1;
  68180. }else{
  68181. if( !u.be.alreadyExists ) pc = pOp->p2 - 1;
  68182. }
  68183. break;
  68184. }
  68185. /* Opcode: IsUnique P1 P2 P3 P4 *
  68186. **
  68187. ** Cursor P1 is open on an index b-tree - that is to say, a btree which
  68188. ** no data and where the key are records generated by OP_MakeRecord with
  68189. ** the list field being the integer ROWID of the entry that the index
  68190. ** entry refers to.
  68191. **
  68192. ** The P3 register contains an integer record number. Call this record
  68193. ** number R. Register P4 is the first in a set of N contiguous registers
  68194. ** that make up an unpacked index key that can be used with cursor P1.
  68195. ** The value of N can be inferred from the cursor. N includes the rowid
  68196. ** value appended to the end of the index record. This rowid value may
  68197. ** or may not be the same as R.
  68198. **
  68199. ** If any of the N registers beginning with register P4 contains a NULL
  68200. ** value, jump immediately to P2.
  68201. **
  68202. ** Otherwise, this instruction checks if cursor P1 contains an entry
  68203. ** where the first (N-1) fields match but the rowid value at the end
  68204. ** of the index entry is not R. If there is no such entry, control jumps
  68205. ** to instruction P2. Otherwise, the rowid of the conflicting index
  68206. ** entry is copied to register P3 and control falls through to the next
  68207. ** instruction.
  68208. **
  68209. ** See also: NotFound, NotExists, Found
  68210. */
  68211. case OP_IsUnique: { /* jump, in3 */
  68212. #if 0 /* local variables moved into u.bf */
  68213. u16 ii;
  68214. VdbeCursor *pCx;
  68215. BtCursor *pCrsr;
  68216. u16 nField;
  68217. Mem *aMx;
  68218. UnpackedRecord r; /* B-Tree index search key */
  68219. i64 R; /* Rowid stored in register P3 */
  68220. #endif /* local variables moved into u.bf */
  68221. pIn3 = &aMem[pOp->p3];
  68222. u.bf.aMx = &aMem[pOp->p4.i];
  68223. /* Assert that the values of parameters P1 and P4 are in range. */
  68224. assert( pOp->p4type==P4_INT32 );
  68225. assert( pOp->p4.i>0 && pOp->p4.i<=(p->nMem-p->nCursor) );
  68226. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68227. /* Find the index cursor. */
  68228. u.bf.pCx = p->apCsr[pOp->p1];
  68229. assert( u.bf.pCx->deferredMoveto==0 );
  68230. u.bf.pCx->seekResult = 0;
  68231. u.bf.pCx->cacheStatus = CACHE_STALE;
  68232. u.bf.pCrsr = u.bf.pCx->pCursor;
  68233. /* If any of the values are NULL, take the jump. */
  68234. u.bf.nField = u.bf.pCx->pKeyInfo->nField;
  68235. for(u.bf.ii=0; u.bf.ii<u.bf.nField; u.bf.ii++){
  68236. if( u.bf.aMx[u.bf.ii].flags & MEM_Null ){
  68237. pc = pOp->p2 - 1;
  68238. u.bf.pCrsr = 0;
  68239. break;
  68240. }
  68241. }
  68242. assert( (u.bf.aMx[u.bf.nField].flags & MEM_Null)==0 );
  68243. if( u.bf.pCrsr!=0 ){
  68244. /* Populate the index search key. */
  68245. u.bf.r.pKeyInfo = u.bf.pCx->pKeyInfo;
  68246. u.bf.r.nField = u.bf.nField + 1;
  68247. u.bf.r.flags = UNPACKED_PREFIX_SEARCH;
  68248. u.bf.r.aMem = u.bf.aMx;
  68249. #ifdef SQLITE_DEBUG
  68250. { int i; for(i=0; i<u.bf.r.nField; i++) assert( memIsValid(&u.bf.r.aMem[i]) ); }
  68251. #endif
  68252. /* Extract the value of u.bf.R from register P3. */
  68253. sqlite3VdbeMemIntegerify(pIn3);
  68254. u.bf.R = pIn3->u.i;
  68255. /* Search the B-Tree index. If no conflicting record is found, jump
  68256. ** to P2. Otherwise, copy the rowid of the conflicting record to
  68257. ** register P3 and fall through to the next instruction. */
  68258. rc = sqlite3BtreeMovetoUnpacked(u.bf.pCrsr, &u.bf.r, 0, 0, &u.bf.pCx->seekResult);
  68259. if( (u.bf.r.flags & UNPACKED_PREFIX_SEARCH) || u.bf.r.rowid==u.bf.R ){
  68260. pc = pOp->p2 - 1;
  68261. }else{
  68262. pIn3->u.i = u.bf.r.rowid;
  68263. }
  68264. }
  68265. break;
  68266. }
  68267. /* Opcode: NotExists P1 P2 P3 * *
  68268. **
  68269. ** Use the content of register P3 as an integer key. If a record
  68270. ** with that key does not exist in table of P1, then jump to P2.
  68271. ** If the record does exist, then fall through. The cursor is left
  68272. ** pointing to the record if it exists.
  68273. **
  68274. ** The difference between this operation and NotFound is that this
  68275. ** operation assumes the key is an integer and that P1 is a table whereas
  68276. ** NotFound assumes key is a blob constructed from MakeRecord and
  68277. ** P1 is an index.
  68278. **
  68279. ** See also: Found, NotFound, IsUnique
  68280. */
  68281. case OP_NotExists: { /* jump, in3 */
  68282. #if 0 /* local variables moved into u.bg */
  68283. VdbeCursor *pC;
  68284. BtCursor *pCrsr;
  68285. int res;
  68286. u64 iKey;
  68287. #endif /* local variables moved into u.bg */
  68288. pIn3 = &aMem[pOp->p3];
  68289. assert( pIn3->flags & MEM_Int );
  68290. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68291. u.bg.pC = p->apCsr[pOp->p1];
  68292. assert( u.bg.pC!=0 );
  68293. assert( u.bg.pC->isTable );
  68294. assert( u.bg.pC->pseudoTableReg==0 );
  68295. u.bg.pCrsr = u.bg.pC->pCursor;
  68296. if( ALWAYS(u.bg.pCrsr!=0) ){
  68297. u.bg.res = 0;
  68298. u.bg.iKey = pIn3->u.i;
  68299. rc = sqlite3BtreeMovetoUnpacked(u.bg.pCrsr, 0, u.bg.iKey, 0, &u.bg.res);
  68300. u.bg.pC->lastRowid = pIn3->u.i;
  68301. u.bg.pC->rowidIsValid = u.bg.res==0 ?1:0;
  68302. u.bg.pC->nullRow = 0;
  68303. u.bg.pC->cacheStatus = CACHE_STALE;
  68304. u.bg.pC->deferredMoveto = 0;
  68305. if( u.bg.res!=0 ){
  68306. pc = pOp->p2 - 1;
  68307. assert( u.bg.pC->rowidIsValid==0 );
  68308. }
  68309. u.bg.pC->seekResult = u.bg.res;
  68310. }else{
  68311. /* This happens when an attempt to open a read cursor on the
  68312. ** sqlite_master table returns SQLITE_EMPTY.
  68313. */
  68314. pc = pOp->p2 - 1;
  68315. assert( u.bg.pC->rowidIsValid==0 );
  68316. u.bg.pC->seekResult = 0;
  68317. }
  68318. break;
  68319. }
  68320. /* Opcode: Sequence P1 P2 * * *
  68321. **
  68322. ** Find the next available sequence number for cursor P1.
  68323. ** Write the sequence number into register P2.
  68324. ** The sequence number on the cursor is incremented after this
  68325. ** instruction.
  68326. */
  68327. case OP_Sequence: { /* out2-prerelease */
  68328. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68329. assert( p->apCsr[pOp->p1]!=0 );
  68330. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  68331. break;
  68332. }
  68333. /* Opcode: NewRowid P1 P2 P3 * *
  68334. **
  68335. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  68336. ** The record number is not previously used as a key in the database
  68337. ** table that cursor P1 points to. The new record number is written
  68338. ** written to register P2.
  68339. **
  68340. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  68341. ** the largest previously generated record number. No new record numbers are
  68342. ** allowed to be less than this value. When this value reaches its maximum,
  68343. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  68344. ** generated record number. This P3 mechanism is used to help implement the
  68345. ** AUTOINCREMENT feature.
  68346. */
  68347. case OP_NewRowid: { /* out2-prerelease */
  68348. #if 0 /* local variables moved into u.bh */
  68349. i64 v; /* The new rowid */
  68350. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  68351. int res; /* Result of an sqlite3BtreeLast() */
  68352. int cnt; /* Counter to limit the number of searches */
  68353. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  68354. VdbeFrame *pFrame; /* Root frame of VDBE */
  68355. #endif /* local variables moved into u.bh */
  68356. u.bh.v = 0;
  68357. u.bh.res = 0;
  68358. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68359. u.bh.pC = p->apCsr[pOp->p1];
  68360. assert( u.bh.pC!=0 );
  68361. if( NEVER(u.bh.pC->pCursor==0) ){
  68362. /* The zero initialization above is all that is needed */
  68363. }else{
  68364. /* The next rowid or record number (different terms for the same
  68365. ** thing) is obtained in a two-step algorithm.
  68366. **
  68367. ** First we attempt to find the largest existing rowid and add one
  68368. ** to that. But if the largest existing rowid is already the maximum
  68369. ** positive integer, we have to fall through to the second
  68370. ** probabilistic algorithm
  68371. **
  68372. ** The second algorithm is to select a rowid at random and see if
  68373. ** it already exists in the table. If it does not exist, we have
  68374. ** succeeded. If the random rowid does exist, we select a new one
  68375. ** and try again, up to 100 times.
  68376. */
  68377. assert( u.bh.pC->isTable );
  68378. #ifdef SQLITE_32BIT_ROWID
  68379. # define MAX_ROWID 0x7fffffff
  68380. #else
  68381. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  68382. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  68383. ** to provide the constant while making all compilers happy.
  68384. */
  68385. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  68386. #endif
  68387. if( !u.bh.pC->useRandomRowid ){
  68388. u.bh.v = sqlite3BtreeGetCachedRowid(u.bh.pC->pCursor);
  68389. if( u.bh.v==0 ){
  68390. rc = sqlite3BtreeLast(u.bh.pC->pCursor, &u.bh.res);
  68391. if( rc!=SQLITE_OK ){
  68392. goto abort_due_to_error;
  68393. }
  68394. if( u.bh.res ){
  68395. u.bh.v = 1; /* IMP: R-61914-48074 */
  68396. }else{
  68397. assert( sqlite3BtreeCursorIsValid(u.bh.pC->pCursor) );
  68398. rc = sqlite3BtreeKeySize(u.bh.pC->pCursor, &u.bh.v);
  68399. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  68400. if( u.bh.v>=MAX_ROWID ){
  68401. u.bh.pC->useRandomRowid = 1;
  68402. }else{
  68403. u.bh.v++; /* IMP: R-29538-34987 */
  68404. }
  68405. }
  68406. }
  68407. #ifndef SQLITE_OMIT_AUTOINCREMENT
  68408. if( pOp->p3 ){
  68409. /* Assert that P3 is a valid memory cell. */
  68410. assert( pOp->p3>0 );
  68411. if( p->pFrame ){
  68412. for(u.bh.pFrame=p->pFrame; u.bh.pFrame->pParent; u.bh.pFrame=u.bh.pFrame->pParent);
  68413. /* Assert that P3 is a valid memory cell. */
  68414. assert( pOp->p3<=u.bh.pFrame->nMem );
  68415. u.bh.pMem = &u.bh.pFrame->aMem[pOp->p3];
  68416. }else{
  68417. /* Assert that P3 is a valid memory cell. */
  68418. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68419. u.bh.pMem = &aMem[pOp->p3];
  68420. memAboutToChange(p, u.bh.pMem);
  68421. }
  68422. assert( memIsValid(u.bh.pMem) );
  68423. REGISTER_TRACE(pOp->p3, u.bh.pMem);
  68424. sqlite3VdbeMemIntegerify(u.bh.pMem);
  68425. assert( (u.bh.pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  68426. if( u.bh.pMem->u.i==MAX_ROWID || u.bh.pC->useRandomRowid ){
  68427. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  68428. goto abort_due_to_error;
  68429. }
  68430. if( u.bh.v<u.bh.pMem->u.i+1 ){
  68431. u.bh.v = u.bh.pMem->u.i + 1;
  68432. }
  68433. u.bh.pMem->u.i = u.bh.v;
  68434. }
  68435. #endif
  68436. sqlite3BtreeSetCachedRowid(u.bh.pC->pCursor, u.bh.v<MAX_ROWID ? u.bh.v+1 : 0);
  68437. }
  68438. if( u.bh.pC->useRandomRowid ){
  68439. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  68440. ** largest possible integer (9223372036854775807) then the database
  68441. ** engine starts picking positive candidate ROWIDs at random until
  68442. ** it finds one that is not previously used. */
  68443. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  68444. ** an AUTOINCREMENT table. */
  68445. /* on the first attempt, simply do one more than previous */
  68446. u.bh.v = lastRowid;
  68447. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  68448. u.bh.v++; /* ensure non-zero */
  68449. u.bh.cnt = 0;
  68450. while( ((rc = sqlite3BtreeMovetoUnpacked(u.bh.pC->pCursor, 0, (u64)u.bh.v,
  68451. 0, &u.bh.res))==SQLITE_OK)
  68452. && (u.bh.res==0)
  68453. && (++u.bh.cnt<100)){
  68454. /* collision - try another random rowid */
  68455. sqlite3_randomness(sizeof(u.bh.v), &u.bh.v);
  68456. if( u.bh.cnt<5 ){
  68457. /* try "small" random rowids for the initial attempts */
  68458. u.bh.v &= 0xffffff;
  68459. }else{
  68460. u.bh.v &= (MAX_ROWID>>1); /* ensure doesn't go negative */
  68461. }
  68462. u.bh.v++; /* ensure non-zero */
  68463. }
  68464. if( rc==SQLITE_OK && u.bh.res==0 ){
  68465. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  68466. goto abort_due_to_error;
  68467. }
  68468. assert( u.bh.v>0 ); /* EV: R-40812-03570 */
  68469. }
  68470. u.bh.pC->rowidIsValid = 0;
  68471. u.bh.pC->deferredMoveto = 0;
  68472. u.bh.pC->cacheStatus = CACHE_STALE;
  68473. }
  68474. pOut->u.i = u.bh.v;
  68475. break;
  68476. }
  68477. /* Opcode: Insert P1 P2 P3 P4 P5
  68478. **
  68479. ** Write an entry into the table of cursor P1. A new entry is
  68480. ** created if it doesn't already exist or the data for an existing
  68481. ** entry is overwritten. The data is the value MEM_Blob stored in register
  68482. ** number P2. The key is stored in register P3. The key must
  68483. ** be a MEM_Int.
  68484. **
  68485. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  68486. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  68487. ** then rowid is stored for subsequent return by the
  68488. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  68489. **
  68490. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  68491. ** the last seek operation (OP_NotExists) was a success, then this
  68492. ** operation will not attempt to find the appropriate row before doing
  68493. ** the insert but will instead overwrite the row that the cursor is
  68494. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  68495. ** has already positioned the cursor correctly. This is an optimization
  68496. ** that boosts performance by avoiding redundant seeks.
  68497. **
  68498. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  68499. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  68500. ** is part of an INSERT operation. The difference is only important to
  68501. ** the update hook.
  68502. **
  68503. ** Parameter P4 may point to a string containing the table-name, or
  68504. ** may be NULL. If it is not NULL, then the update-hook
  68505. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  68506. **
  68507. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  68508. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  68509. ** and register P2 becomes ephemeral. If the cursor is changed, the
  68510. ** value of register P2 will then change. Make sure this does not
  68511. ** cause any problems.)
  68512. **
  68513. ** This instruction only works on tables. The equivalent instruction
  68514. ** for indices is OP_IdxInsert.
  68515. */
  68516. /* Opcode: InsertInt P1 P2 P3 P4 P5
  68517. **
  68518. ** This works exactly like OP_Insert except that the key is the
  68519. ** integer value P3, not the value of the integer stored in register P3.
  68520. */
  68521. case OP_Insert:
  68522. case OP_InsertInt: {
  68523. #if 0 /* local variables moved into u.bi */
  68524. Mem *pData; /* MEM cell holding data for the record to be inserted */
  68525. Mem *pKey; /* MEM cell holding key for the record */
  68526. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  68527. VdbeCursor *pC; /* Cursor to table into which insert is written */
  68528. int nZero; /* Number of zero-bytes to append */
  68529. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  68530. const char *zDb; /* database name - used by the update hook */
  68531. const char *zTbl; /* Table name - used by the opdate hook */
  68532. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  68533. #endif /* local variables moved into u.bi */
  68534. u.bi.pData = &aMem[pOp->p2];
  68535. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68536. assert( memIsValid(u.bi.pData) );
  68537. u.bi.pC = p->apCsr[pOp->p1];
  68538. assert( u.bi.pC!=0 );
  68539. assert( u.bi.pC->pCursor!=0 );
  68540. assert( u.bi.pC->pseudoTableReg==0 );
  68541. assert( u.bi.pC->isTable );
  68542. REGISTER_TRACE(pOp->p2, u.bi.pData);
  68543. if( pOp->opcode==OP_Insert ){
  68544. u.bi.pKey = &aMem[pOp->p3];
  68545. assert( u.bi.pKey->flags & MEM_Int );
  68546. assert( memIsValid(u.bi.pKey) );
  68547. REGISTER_TRACE(pOp->p3, u.bi.pKey);
  68548. u.bi.iKey = u.bi.pKey->u.i;
  68549. }else{
  68550. assert( pOp->opcode==OP_InsertInt );
  68551. u.bi.iKey = pOp->p3;
  68552. }
  68553. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  68554. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = u.bi.iKey;
  68555. if( u.bi.pData->flags & MEM_Null ){
  68556. u.bi.pData->z = 0;
  68557. u.bi.pData->n = 0;
  68558. }else{
  68559. assert( u.bi.pData->flags & (MEM_Blob|MEM_Str) );
  68560. }
  68561. u.bi.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bi.pC->seekResult : 0);
  68562. if( u.bi.pData->flags & MEM_Zero ){
  68563. u.bi.nZero = u.bi.pData->u.nZero;
  68564. }else{
  68565. u.bi.nZero = 0;
  68566. }
  68567. sqlite3BtreeSetCachedRowid(u.bi.pC->pCursor, 0);
  68568. rc = sqlite3BtreeInsert(u.bi.pC->pCursor, 0, u.bi.iKey,
  68569. u.bi.pData->z, u.bi.pData->n, u.bi.nZero,
  68570. pOp->p5 & OPFLAG_APPEND, u.bi.seekResult
  68571. );
  68572. u.bi.pC->rowidIsValid = 0;
  68573. u.bi.pC->deferredMoveto = 0;
  68574. u.bi.pC->cacheStatus = CACHE_STALE;
  68575. /* Invoke the update-hook if required. */
  68576. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68577. u.bi.zDb = db->aDb[u.bi.pC->iDb].zName;
  68578. u.bi.zTbl = pOp->p4.z;
  68579. u.bi.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  68580. assert( u.bi.pC->isTable );
  68581. db->xUpdateCallback(db->pUpdateArg, u.bi.op, u.bi.zDb, u.bi.zTbl, u.bi.iKey);
  68582. assert( u.bi.pC->iDb>=0 );
  68583. }
  68584. break;
  68585. }
  68586. /* Opcode: Delete P1 P2 * P4 *
  68587. **
  68588. ** Delete the record at which the P1 cursor is currently pointing.
  68589. **
  68590. ** The cursor will be left pointing at either the next or the previous
  68591. ** record in the table. If it is left pointing at the next record, then
  68592. ** the next Next instruction will be a no-op. Hence it is OK to delete
  68593. ** a record from within an Next loop.
  68594. **
  68595. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  68596. ** incremented (otherwise not).
  68597. **
  68598. ** P1 must not be pseudo-table. It has to be a real table with
  68599. ** multiple rows.
  68600. **
  68601. ** If P4 is not NULL, then it is the name of the table that P1 is
  68602. ** pointing to. The update hook will be invoked, if it exists.
  68603. ** If P4 is not NULL then the P1 cursor must have been positioned
  68604. ** using OP_NotFound prior to invoking this opcode.
  68605. */
  68606. case OP_Delete: {
  68607. #if 0 /* local variables moved into u.bj */
  68608. i64 iKey;
  68609. VdbeCursor *pC;
  68610. #endif /* local variables moved into u.bj */
  68611. u.bj.iKey = 0;
  68612. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68613. u.bj.pC = p->apCsr[pOp->p1];
  68614. assert( u.bj.pC!=0 );
  68615. assert( u.bj.pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  68616. /* If the update-hook will be invoked, set u.bj.iKey to the rowid of the
  68617. ** row being deleted.
  68618. */
  68619. if( db->xUpdateCallback && pOp->p4.z ){
  68620. assert( u.bj.pC->isTable );
  68621. assert( u.bj.pC->rowidIsValid ); /* lastRowid set by previous OP_NotFound */
  68622. u.bj.iKey = u.bj.pC->lastRowid;
  68623. }
  68624. /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
  68625. ** OP_Column on the same table without any intervening operations that
  68626. ** might move or invalidate the cursor. Hence cursor u.bj.pC is always pointing
  68627. ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
  68628. ** below is always a no-op and cannot fail. We will run it anyhow, though,
  68629. ** to guard against future changes to the code generator.
  68630. **/
  68631. assert( u.bj.pC->deferredMoveto==0 );
  68632. rc = sqlite3VdbeCursorMoveto(u.bj.pC);
  68633. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  68634. sqlite3BtreeSetCachedRowid(u.bj.pC->pCursor, 0);
  68635. rc = sqlite3BtreeDelete(u.bj.pC->pCursor);
  68636. u.bj.pC->cacheStatus = CACHE_STALE;
  68637. /* Invoke the update-hook if required. */
  68638. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68639. const char *zDb = db->aDb[u.bj.pC->iDb].zName;
  68640. const char *zTbl = pOp->p4.z;
  68641. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bj.iKey);
  68642. assert( u.bj.pC->iDb>=0 );
  68643. }
  68644. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  68645. break;
  68646. }
  68647. /* Opcode: ResetCount * * * * *
  68648. **
  68649. ** The value of the change counter is copied to the database handle
  68650. ** change counter (returned by subsequent calls to sqlite3_changes()).
  68651. ** Then the VMs internal change counter resets to 0.
  68652. ** This is used by trigger programs.
  68653. */
  68654. case OP_ResetCount: {
  68655. sqlite3VdbeSetChanges(db, p->nChange);
  68656. p->nChange = 0;
  68657. break;
  68658. }
  68659. /* Opcode: SorterCompare P1 P2 P3
  68660. **
  68661. ** P1 is a sorter cursor. This instruction compares the record blob in
  68662. ** register P3 with the entry that the sorter cursor currently points to.
  68663. ** If, excluding the rowid fields at the end, the two records are a match,
  68664. ** fall through to the next instruction. Otherwise, jump to instruction P2.
  68665. */
  68666. case OP_SorterCompare: {
  68667. #if 0 /* local variables moved into u.bk */
  68668. VdbeCursor *pC;
  68669. int res;
  68670. #endif /* local variables moved into u.bk */
  68671. u.bk.pC = p->apCsr[pOp->p1];
  68672. assert( isSorter(u.bk.pC) );
  68673. pIn3 = &aMem[pOp->p3];
  68674. rc = sqlite3VdbeSorterCompare(u.bk.pC, pIn3, &u.bk.res);
  68675. if( u.bk.res ){
  68676. pc = pOp->p2-1;
  68677. }
  68678. break;
  68679. };
  68680. /* Opcode: SorterData P1 P2 * * *
  68681. **
  68682. ** Write into register P2 the current sorter data for sorter cursor P1.
  68683. */
  68684. case OP_SorterData: {
  68685. #if 0 /* local variables moved into u.bl */
  68686. VdbeCursor *pC;
  68687. #endif /* local variables moved into u.bl */
  68688. pOut = &aMem[pOp->p2];
  68689. u.bl.pC = p->apCsr[pOp->p1];
  68690. assert( u.bl.pC->isSorter );
  68691. rc = sqlite3VdbeSorterRowkey(u.bl.pC, pOut);
  68692. break;
  68693. }
  68694. /* Opcode: RowData P1 P2 * * *
  68695. **
  68696. ** Write into register P2 the complete row data for cursor P1.
  68697. ** There is no interpretation of the data.
  68698. ** It is just copied onto the P2 register exactly as
  68699. ** it is found in the database file.
  68700. **
  68701. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68702. ** of a real table, not a pseudo-table.
  68703. */
  68704. /* Opcode: RowKey P1 P2 * * *
  68705. **
  68706. ** Write into register P2 the complete row key for cursor P1.
  68707. ** There is no interpretation of the data.
  68708. ** The key is copied onto the P3 register exactly as
  68709. ** it is found in the database file.
  68710. **
  68711. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68712. ** of a real table, not a pseudo-table.
  68713. */
  68714. case OP_RowKey:
  68715. case OP_RowData: {
  68716. #if 0 /* local variables moved into u.bm */
  68717. VdbeCursor *pC;
  68718. BtCursor *pCrsr;
  68719. u32 n;
  68720. i64 n64;
  68721. #endif /* local variables moved into u.bm */
  68722. pOut = &aMem[pOp->p2];
  68723. memAboutToChange(p, pOut);
  68724. /* Note that RowKey and RowData are really exactly the same instruction */
  68725. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68726. u.bm.pC = p->apCsr[pOp->p1];
  68727. assert( u.bm.pC->isSorter==0 );
  68728. assert( u.bm.pC->isTable || pOp->opcode!=OP_RowData );
  68729. assert( u.bm.pC->isIndex || pOp->opcode==OP_RowData );
  68730. assert( u.bm.pC!=0 );
  68731. assert( u.bm.pC->nullRow==0 );
  68732. assert( u.bm.pC->pseudoTableReg==0 );
  68733. assert( u.bm.pC->pCursor!=0 );
  68734. u.bm.pCrsr = u.bm.pC->pCursor;
  68735. assert( sqlite3BtreeCursorIsValid(u.bm.pCrsr) );
  68736. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  68737. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  68738. ** the cursor. Hence the following sqlite3VdbeCursorMoveto() call is always
  68739. ** a no-op and can never fail. But we leave it in place as a safety.
  68740. */
  68741. assert( u.bm.pC->deferredMoveto==0 );
  68742. rc = sqlite3VdbeCursorMoveto(u.bm.pC);
  68743. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  68744. if( u.bm.pC->isIndex ){
  68745. assert( !u.bm.pC->isTable );
  68746. VVA_ONLY(rc =) sqlite3BtreeKeySize(u.bm.pCrsr, &u.bm.n64);
  68747. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  68748. if( u.bm.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68749. goto too_big;
  68750. }
  68751. u.bm.n = (u32)u.bm.n64;
  68752. }else{
  68753. VVA_ONLY(rc =) sqlite3BtreeDataSize(u.bm.pCrsr, &u.bm.n);
  68754. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  68755. if( u.bm.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68756. goto too_big;
  68757. }
  68758. }
  68759. if( sqlite3VdbeMemGrow(pOut, u.bm.n, 0) ){
  68760. goto no_mem;
  68761. }
  68762. pOut->n = u.bm.n;
  68763. MemSetTypeFlag(pOut, MEM_Blob);
  68764. if( u.bm.pC->isIndex ){
  68765. rc = sqlite3BtreeKey(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  68766. }else{
  68767. rc = sqlite3BtreeData(u.bm.pCrsr, 0, u.bm.n, pOut->z);
  68768. }
  68769. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  68770. UPDATE_MAX_BLOBSIZE(pOut);
  68771. break;
  68772. }
  68773. /* Opcode: Rowid P1 P2 * * *
  68774. **
  68775. ** Store in register P2 an integer which is the key of the table entry that
  68776. ** P1 is currently point to.
  68777. **
  68778. ** P1 can be either an ordinary table or a virtual table. There used to
  68779. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  68780. ** one opcode now works for both table types.
  68781. */
  68782. case OP_Rowid: { /* out2-prerelease */
  68783. #if 0 /* local variables moved into u.bn */
  68784. VdbeCursor *pC;
  68785. i64 v;
  68786. sqlite3_vtab *pVtab;
  68787. const sqlite3_module *pModule;
  68788. #endif /* local variables moved into u.bn */
  68789. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68790. u.bn.pC = p->apCsr[pOp->p1];
  68791. assert( u.bn.pC!=0 );
  68792. assert( u.bn.pC->pseudoTableReg==0 || u.bn.pC->nullRow );
  68793. if( u.bn.pC->nullRow ){
  68794. pOut->flags = MEM_Null;
  68795. break;
  68796. }else if( u.bn.pC->deferredMoveto ){
  68797. u.bn.v = u.bn.pC->movetoTarget;
  68798. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68799. }else if( u.bn.pC->pVtabCursor ){
  68800. u.bn.pVtab = u.bn.pC->pVtabCursor->pVtab;
  68801. u.bn.pModule = u.bn.pVtab->pModule;
  68802. assert( u.bn.pModule->xRowid );
  68803. rc = u.bn.pModule->xRowid(u.bn.pC->pVtabCursor, &u.bn.v);
  68804. sqlite3VtabImportErrmsg(p, u.bn.pVtab);
  68805. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  68806. }else{
  68807. assert( u.bn.pC->pCursor!=0 );
  68808. rc = sqlite3VdbeCursorMoveto(u.bn.pC);
  68809. if( rc ) goto abort_due_to_error;
  68810. if( u.bn.pC->rowidIsValid ){
  68811. u.bn.v = u.bn.pC->lastRowid;
  68812. }else{
  68813. rc = sqlite3BtreeKeySize(u.bn.pC->pCursor, &u.bn.v);
  68814. assert( rc==SQLITE_OK ); /* Always so because of CursorMoveto() above */
  68815. }
  68816. }
  68817. pOut->u.i = u.bn.v;
  68818. break;
  68819. }
  68820. /* Opcode: NullRow P1 * * * *
  68821. **
  68822. ** Move the cursor P1 to a null row. Any OP_Column operations
  68823. ** that occur while the cursor is on the null row will always
  68824. ** write a NULL.
  68825. */
  68826. case OP_NullRow: {
  68827. #if 0 /* local variables moved into u.bo */
  68828. VdbeCursor *pC;
  68829. #endif /* local variables moved into u.bo */
  68830. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68831. u.bo.pC = p->apCsr[pOp->p1];
  68832. assert( u.bo.pC!=0 );
  68833. u.bo.pC->nullRow = 1;
  68834. u.bo.pC->rowidIsValid = 0;
  68835. assert( u.bo.pC->pCursor || u.bo.pC->pVtabCursor );
  68836. if( u.bo.pC->pCursor ){
  68837. sqlite3BtreeClearCursor(u.bo.pC->pCursor);
  68838. }
  68839. break;
  68840. }
  68841. /* Opcode: Last P1 P2 * * *
  68842. **
  68843. ** The next use of the Rowid or Column or Next instruction for P1
  68844. ** will refer to the last entry in the database table or index.
  68845. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68846. ** If P2 is 0 or if the table or index is not empty, fall through
  68847. ** to the following instruction.
  68848. */
  68849. case OP_Last: { /* jump */
  68850. #if 0 /* local variables moved into u.bp */
  68851. VdbeCursor *pC;
  68852. BtCursor *pCrsr;
  68853. int res;
  68854. #endif /* local variables moved into u.bp */
  68855. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68856. u.bp.pC = p->apCsr[pOp->p1];
  68857. assert( u.bp.pC!=0 );
  68858. u.bp.pCrsr = u.bp.pC->pCursor;
  68859. u.bp.res = 0;
  68860. if( ALWAYS(u.bp.pCrsr!=0) ){
  68861. rc = sqlite3BtreeLast(u.bp.pCrsr, &u.bp.res);
  68862. }
  68863. u.bp.pC->nullRow = (u8)u.bp.res;
  68864. u.bp.pC->deferredMoveto = 0;
  68865. u.bp.pC->rowidIsValid = 0;
  68866. u.bp.pC->cacheStatus = CACHE_STALE;
  68867. if( pOp->p2>0 && u.bp.res ){
  68868. pc = pOp->p2 - 1;
  68869. }
  68870. break;
  68871. }
  68872. /* Opcode: Sort P1 P2 * * *
  68873. **
  68874. ** This opcode does exactly the same thing as OP_Rewind except that
  68875. ** it increments an undocumented global variable used for testing.
  68876. **
  68877. ** Sorting is accomplished by writing records into a sorting index,
  68878. ** then rewinding that index and playing it back from beginning to
  68879. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  68880. ** rewinding so that the global variable will be incremented and
  68881. ** regression tests can determine whether or not the optimizer is
  68882. ** correctly optimizing out sorts.
  68883. */
  68884. case OP_SorterSort: /* jump */
  68885. case OP_Sort: { /* jump */
  68886. #ifdef SQLITE_TEST
  68887. sqlite3_sort_count++;
  68888. sqlite3_search_count--;
  68889. #endif
  68890. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  68891. /* Fall through into OP_Rewind */
  68892. }
  68893. /* Opcode: Rewind P1 P2 * * *
  68894. **
  68895. ** The next use of the Rowid or Column or Next instruction for P1
  68896. ** will refer to the first entry in the database table or index.
  68897. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68898. ** If P2 is 0 or if the table or index is not empty, fall through
  68899. ** to the following instruction.
  68900. */
  68901. case OP_Rewind: { /* jump */
  68902. #if 0 /* local variables moved into u.bq */
  68903. VdbeCursor *pC;
  68904. BtCursor *pCrsr;
  68905. int res;
  68906. #endif /* local variables moved into u.bq */
  68907. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68908. u.bq.pC = p->apCsr[pOp->p1];
  68909. assert( u.bq.pC!=0 );
  68910. assert( u.bq.pC->isSorter==(pOp->opcode==OP_SorterSort) );
  68911. u.bq.res = 1;
  68912. if( isSorter(u.bq.pC) ){
  68913. rc = sqlite3VdbeSorterRewind(db, u.bq.pC, &u.bq.res);
  68914. }else{
  68915. u.bq.pCrsr = u.bq.pC->pCursor;
  68916. assert( u.bq.pCrsr );
  68917. rc = sqlite3BtreeFirst(u.bq.pCrsr, &u.bq.res);
  68918. u.bq.pC->atFirst = u.bq.res==0 ?1:0;
  68919. u.bq.pC->deferredMoveto = 0;
  68920. u.bq.pC->cacheStatus = CACHE_STALE;
  68921. u.bq.pC->rowidIsValid = 0;
  68922. }
  68923. u.bq.pC->nullRow = (u8)u.bq.res;
  68924. assert( pOp->p2>0 && pOp->p2<p->nOp );
  68925. if( u.bq.res ){
  68926. pc = pOp->p2 - 1;
  68927. }
  68928. break;
  68929. }
  68930. /* Opcode: Next P1 P2 * P4 P5
  68931. **
  68932. ** Advance cursor P1 so that it points to the next key/data pair in its
  68933. ** table or index. If there are no more key/value pairs then fall through
  68934. ** to the following instruction. But if the cursor advance was successful,
  68935. ** jump immediately to P2.
  68936. **
  68937. ** The P1 cursor must be for a real table, not a pseudo-table.
  68938. **
  68939. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68940. ** sqlite3BtreeNext().
  68941. **
  68942. ** If P5 is positive and the jump is taken, then event counter
  68943. ** number P5-1 in the prepared statement is incremented.
  68944. **
  68945. ** See also: Prev
  68946. */
  68947. /* Opcode: Prev P1 P2 * * P5
  68948. **
  68949. ** Back up cursor P1 so that it points to the previous key/data pair in its
  68950. ** table or index. If there is no previous key/value pairs then fall through
  68951. ** to the following instruction. But if the cursor backup was successful,
  68952. ** jump immediately to P2.
  68953. **
  68954. ** The P1 cursor must be for a real table, not a pseudo-table.
  68955. **
  68956. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68957. ** sqlite3BtreePrevious().
  68958. **
  68959. ** If P5 is positive and the jump is taken, then event counter
  68960. ** number P5-1 in the prepared statement is incremented.
  68961. */
  68962. case OP_SorterNext: /* jump */
  68963. case OP_Prev: /* jump */
  68964. case OP_Next: { /* jump */
  68965. #if 0 /* local variables moved into u.br */
  68966. VdbeCursor *pC;
  68967. int res;
  68968. #endif /* local variables moved into u.br */
  68969. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68970. assert( pOp->p5<ArraySize(p->aCounter) );
  68971. u.br.pC = p->apCsr[pOp->p1];
  68972. if( u.br.pC==0 ){
  68973. break; /* See ticket #2273 */
  68974. }
  68975. assert( u.br.pC->isSorter==(pOp->opcode==OP_SorterNext) );
  68976. if( isSorter(u.br.pC) ){
  68977. assert( pOp->opcode==OP_SorterNext );
  68978. rc = sqlite3VdbeSorterNext(db, u.br.pC, &u.br.res);
  68979. }else{
  68980. /* u.br.res = 1; // Always initialized by the xAdvance() call */
  68981. assert( u.br.pC->deferredMoveto==0 );
  68982. assert( u.br.pC->pCursor );
  68983. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  68984. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  68985. rc = pOp->p4.xAdvance(u.br.pC->pCursor, &u.br.res);
  68986. }
  68987. u.br.pC->nullRow = (u8)u.br.res;
  68988. u.br.pC->cacheStatus = CACHE_STALE;
  68989. if( u.br.res==0 ){
  68990. pc = pOp->p2 - 1;
  68991. p->aCounter[pOp->p5]++;
  68992. #ifdef SQLITE_TEST
  68993. sqlite3_search_count++;
  68994. #endif
  68995. }
  68996. u.br.pC->rowidIsValid = 0;
  68997. goto check_for_interrupt;
  68998. }
  68999. /* Opcode: IdxInsert P1 P2 P3 * P5
  69000. **
  69001. ** Register P2 holds an SQL index key made using the
  69002. ** MakeRecord instructions. This opcode writes that key
  69003. ** into the index P1. Data for the entry is nil.
  69004. **
  69005. ** P3 is a flag that provides a hint to the b-tree layer that this
  69006. ** insert is likely to be an append.
  69007. **
  69008. ** This instruction only works for indices. The equivalent instruction
  69009. ** for tables is OP_Insert.
  69010. */
  69011. case OP_SorterInsert: /* in2 */
  69012. case OP_IdxInsert: { /* in2 */
  69013. #if 0 /* local variables moved into u.bs */
  69014. VdbeCursor *pC;
  69015. BtCursor *pCrsr;
  69016. int nKey;
  69017. const char *zKey;
  69018. #endif /* local variables moved into u.bs */
  69019. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69020. u.bs.pC = p->apCsr[pOp->p1];
  69021. assert( u.bs.pC!=0 );
  69022. assert( u.bs.pC->isSorter==(pOp->opcode==OP_SorterInsert) );
  69023. pIn2 = &aMem[pOp->p2];
  69024. assert( pIn2->flags & MEM_Blob );
  69025. u.bs.pCrsr = u.bs.pC->pCursor;
  69026. if( ALWAYS(u.bs.pCrsr!=0) ){
  69027. assert( u.bs.pC->isTable==0 );
  69028. rc = ExpandBlob(pIn2);
  69029. if( rc==SQLITE_OK ){
  69030. if( isSorter(u.bs.pC) ){
  69031. rc = sqlite3VdbeSorterWrite(db, u.bs.pC, pIn2);
  69032. }else{
  69033. u.bs.nKey = pIn2->n;
  69034. u.bs.zKey = pIn2->z;
  69035. rc = sqlite3BtreeInsert(u.bs.pCrsr, u.bs.zKey, u.bs.nKey, "", 0, 0, pOp->p3,
  69036. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bs.pC->seekResult : 0)
  69037. );
  69038. assert( u.bs.pC->deferredMoveto==0 );
  69039. u.bs.pC->cacheStatus = CACHE_STALE;
  69040. }
  69041. }
  69042. }
  69043. break;
  69044. }
  69045. /* Opcode: IdxDelete P1 P2 P3 * *
  69046. **
  69047. ** The content of P3 registers starting at register P2 form
  69048. ** an unpacked index key. This opcode removes that entry from the
  69049. ** index opened by cursor P1.
  69050. */
  69051. case OP_IdxDelete: {
  69052. #if 0 /* local variables moved into u.bt */
  69053. VdbeCursor *pC;
  69054. BtCursor *pCrsr;
  69055. int res;
  69056. UnpackedRecord r;
  69057. #endif /* local variables moved into u.bt */
  69058. assert( pOp->p3>0 );
  69059. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  69060. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69061. u.bt.pC = p->apCsr[pOp->p1];
  69062. assert( u.bt.pC!=0 );
  69063. u.bt.pCrsr = u.bt.pC->pCursor;
  69064. if( ALWAYS(u.bt.pCrsr!=0) ){
  69065. u.bt.r.pKeyInfo = u.bt.pC->pKeyInfo;
  69066. u.bt.r.nField = (u16)pOp->p3;
  69067. u.bt.r.flags = 0;
  69068. u.bt.r.aMem = &aMem[pOp->p2];
  69069. #ifdef SQLITE_DEBUG
  69070. { int i; for(i=0; i<u.bt.r.nField; i++) assert( memIsValid(&u.bt.r.aMem[i]) ); }
  69071. #endif
  69072. rc = sqlite3BtreeMovetoUnpacked(u.bt.pCrsr, &u.bt.r, 0, 0, &u.bt.res);
  69073. if( rc==SQLITE_OK && u.bt.res==0 ){
  69074. rc = sqlite3BtreeDelete(u.bt.pCrsr);
  69075. }
  69076. assert( u.bt.pC->deferredMoveto==0 );
  69077. u.bt.pC->cacheStatus = CACHE_STALE;
  69078. }
  69079. break;
  69080. }
  69081. /* Opcode: IdxRowid P1 P2 * * *
  69082. **
  69083. ** Write into register P2 an integer which is the last entry in the record at
  69084. ** the end of the index key pointed to by cursor P1. This integer should be
  69085. ** the rowid of the table entry to which this index entry points.
  69086. **
  69087. ** See also: Rowid, MakeRecord.
  69088. */
  69089. case OP_IdxRowid: { /* out2-prerelease */
  69090. #if 0 /* local variables moved into u.bu */
  69091. BtCursor *pCrsr;
  69092. VdbeCursor *pC;
  69093. i64 rowid;
  69094. #endif /* local variables moved into u.bu */
  69095. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69096. u.bu.pC = p->apCsr[pOp->p1];
  69097. assert( u.bu.pC!=0 );
  69098. u.bu.pCrsr = u.bu.pC->pCursor;
  69099. pOut->flags = MEM_Null;
  69100. if( ALWAYS(u.bu.pCrsr!=0) ){
  69101. rc = sqlite3VdbeCursorMoveto(u.bu.pC);
  69102. if( NEVER(rc) ) goto abort_due_to_error;
  69103. assert( u.bu.pC->deferredMoveto==0 );
  69104. assert( u.bu.pC->isTable==0 );
  69105. if( !u.bu.pC->nullRow ){
  69106. rc = sqlite3VdbeIdxRowid(db, u.bu.pCrsr, &u.bu.rowid);
  69107. if( rc!=SQLITE_OK ){
  69108. goto abort_due_to_error;
  69109. }
  69110. pOut->u.i = u.bu.rowid;
  69111. pOut->flags = MEM_Int;
  69112. }
  69113. }
  69114. break;
  69115. }
  69116. /* Opcode: IdxGE P1 P2 P3 P4 P5
  69117. **
  69118. ** The P4 register values beginning with P3 form an unpacked index
  69119. ** key that omits the ROWID. Compare this key value against the index
  69120. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  69121. **
  69122. ** If the P1 index entry is greater than or equal to the key value
  69123. ** then jump to P2. Otherwise fall through to the next instruction.
  69124. **
  69125. ** If P5 is non-zero then the key value is increased by an epsilon
  69126. ** prior to the comparison. This make the opcode work like IdxGT except
  69127. ** that if the key from register P3 is a prefix of the key in the cursor,
  69128. ** the result is false whereas it would be true with IdxGT.
  69129. */
  69130. /* Opcode: IdxLT P1 P2 P3 P4 P5
  69131. **
  69132. ** The P4 register values beginning with P3 form an unpacked index
  69133. ** key that omits the ROWID. Compare this key value against the index
  69134. ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
  69135. **
  69136. ** If the P1 index entry is less than the key value then jump to P2.
  69137. ** Otherwise fall through to the next instruction.
  69138. **
  69139. ** If P5 is non-zero then the key value is increased by an epsilon prior
  69140. ** to the comparison. This makes the opcode work like IdxLE.
  69141. */
  69142. case OP_IdxLT: /* jump */
  69143. case OP_IdxGE: { /* jump */
  69144. #if 0 /* local variables moved into u.bv */
  69145. VdbeCursor *pC;
  69146. int res;
  69147. UnpackedRecord r;
  69148. #endif /* local variables moved into u.bv */
  69149. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69150. u.bv.pC = p->apCsr[pOp->p1];
  69151. assert( u.bv.pC!=0 );
  69152. assert( u.bv.pC->isOrdered );
  69153. if( ALWAYS(u.bv.pC->pCursor!=0) ){
  69154. assert( u.bv.pC->deferredMoveto==0 );
  69155. assert( pOp->p5==0 || pOp->p5==1 );
  69156. assert( pOp->p4type==P4_INT32 );
  69157. u.bv.r.pKeyInfo = u.bv.pC->pKeyInfo;
  69158. u.bv.r.nField = (u16)pOp->p4.i;
  69159. if( pOp->p5 ){
  69160. u.bv.r.flags = UNPACKED_INCRKEY | UNPACKED_PREFIX_MATCH;
  69161. }else{
  69162. u.bv.r.flags = UNPACKED_PREFIX_MATCH;
  69163. }
  69164. u.bv.r.aMem = &aMem[pOp->p3];
  69165. #ifdef SQLITE_DEBUG
  69166. { int i; for(i=0; i<u.bv.r.nField; i++) assert( memIsValid(&u.bv.r.aMem[i]) ); }
  69167. #endif
  69168. rc = sqlite3VdbeIdxKeyCompare(u.bv.pC, &u.bv.r, &u.bv.res);
  69169. if( pOp->opcode==OP_IdxLT ){
  69170. u.bv.res = -u.bv.res;
  69171. }else{
  69172. assert( pOp->opcode==OP_IdxGE );
  69173. u.bv.res++;
  69174. }
  69175. if( u.bv.res>0 ){
  69176. pc = pOp->p2 - 1 ;
  69177. }
  69178. }
  69179. break;
  69180. }
  69181. /* Opcode: Destroy P1 P2 P3 * *
  69182. **
  69183. ** Delete an entire database table or index whose root page in the database
  69184. ** file is given by P1.
  69185. **
  69186. ** The table being destroyed is in the main database file if P3==0. If
  69187. ** P3==1 then the table to be clear is in the auxiliary database file
  69188. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69189. **
  69190. ** If AUTOVACUUM is enabled then it is possible that another root page
  69191. ** might be moved into the newly deleted root page in order to keep all
  69192. ** root pages contiguous at the beginning of the database. The former
  69193. ** value of the root page that moved - its value before the move occurred -
  69194. ** is stored in register P2. If no page
  69195. ** movement was required (because the table being dropped was already
  69196. ** the last one in the database) then a zero is stored in register P2.
  69197. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  69198. **
  69199. ** See also: Clear
  69200. */
  69201. case OP_Destroy: { /* out2-prerelease */
  69202. #if 0 /* local variables moved into u.bw */
  69203. int iMoved;
  69204. int iCnt;
  69205. Vdbe *pVdbe;
  69206. int iDb;
  69207. #endif /* local variables moved into u.bw */
  69208. assert( p->readOnly==0 );
  69209. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69210. u.bw.iCnt = 0;
  69211. for(u.bw.pVdbe=db->pVdbe; u.bw.pVdbe; u.bw.pVdbe = u.bw.pVdbe->pNext){
  69212. if( u.bw.pVdbe->magic==VDBE_MAGIC_RUN && u.bw.pVdbe->bIsReader
  69213. && u.bw.pVdbe->inVtabMethod<2 && u.bw.pVdbe->pc>=0
  69214. ){
  69215. u.bw.iCnt++;
  69216. }
  69217. }
  69218. #else
  69219. u.bw.iCnt = db->nVdbeRead;
  69220. #endif
  69221. pOut->flags = MEM_Null;
  69222. if( u.bw.iCnt>1 ){
  69223. rc = SQLITE_LOCKED;
  69224. p->errorAction = OE_Abort;
  69225. }else{
  69226. u.bw.iDb = pOp->p3;
  69227. assert( u.bw.iCnt==1 );
  69228. assert( (p->btreeMask & (((yDbMask)1)<<u.bw.iDb))!=0 );
  69229. rc = sqlite3BtreeDropTable(db->aDb[u.bw.iDb].pBt, pOp->p1, &u.bw.iMoved);
  69230. pOut->flags = MEM_Int;
  69231. pOut->u.i = u.bw.iMoved;
  69232. #ifndef SQLITE_OMIT_AUTOVACUUM
  69233. if( rc==SQLITE_OK && u.bw.iMoved!=0 ){
  69234. sqlite3RootPageMoved(db, u.bw.iDb, u.bw.iMoved, pOp->p1);
  69235. /* All OP_Destroy operations occur on the same btree */
  69236. assert( resetSchemaOnFault==0 || resetSchemaOnFault==u.bw.iDb+1 );
  69237. resetSchemaOnFault = u.bw.iDb+1;
  69238. }
  69239. #endif
  69240. }
  69241. break;
  69242. }
  69243. /* Opcode: Clear P1 P2 P3
  69244. **
  69245. ** Delete all contents of the database table or index whose root page
  69246. ** in the database file is given by P1. But, unlike Destroy, do not
  69247. ** remove the table or index from the database file.
  69248. **
  69249. ** The table being clear is in the main database file if P2==0. If
  69250. ** P2==1 then the table to be clear is in the auxiliary database file
  69251. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69252. **
  69253. ** If the P3 value is non-zero, then the table referred to must be an
  69254. ** intkey table (an SQL table, not an index). In this case the row change
  69255. ** count is incremented by the number of rows in the table being cleared.
  69256. ** If P3 is greater than zero, then the value stored in register P3 is
  69257. ** also incremented by the number of rows in the table being cleared.
  69258. **
  69259. ** See also: Destroy
  69260. */
  69261. case OP_Clear: {
  69262. #if 0 /* local variables moved into u.bx */
  69263. int nChange;
  69264. #endif /* local variables moved into u.bx */
  69265. u.bx.nChange = 0;
  69266. assert( p->readOnly==0 );
  69267. assert( pOp->p1!=1 );
  69268. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p2))!=0 );
  69269. rc = sqlite3BtreeClearTable(
  69270. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bx.nChange : 0)
  69271. );
  69272. if( pOp->p3 ){
  69273. p->nChange += u.bx.nChange;
  69274. if( pOp->p3>0 ){
  69275. assert( memIsValid(&aMem[pOp->p3]) );
  69276. memAboutToChange(p, &aMem[pOp->p3]);
  69277. aMem[pOp->p3].u.i += u.bx.nChange;
  69278. }
  69279. }
  69280. break;
  69281. }
  69282. /* Opcode: CreateTable P1 P2 * * *
  69283. **
  69284. ** Allocate a new table in the main database file if P1==0 or in the
  69285. ** auxiliary database file if P1==1 or in an attached database if
  69286. ** P1>1. Write the root page number of the new table into
  69287. ** register P2
  69288. **
  69289. ** The difference between a table and an index is this: A table must
  69290. ** have a 4-byte integer key and can have arbitrary data. An index
  69291. ** has an arbitrary key but no data.
  69292. **
  69293. ** See also: CreateIndex
  69294. */
  69295. /* Opcode: CreateIndex P1 P2 * * *
  69296. **
  69297. ** Allocate a new index in the main database file if P1==0 or in the
  69298. ** auxiliary database file if P1==1 or in an attached database if
  69299. ** P1>1. Write the root page number of the new table into
  69300. ** register P2.
  69301. **
  69302. ** See documentation on OP_CreateTable for additional information.
  69303. */
  69304. case OP_CreateIndex: /* out2-prerelease */
  69305. case OP_CreateTable: { /* out2-prerelease */
  69306. #if 0 /* local variables moved into u.by */
  69307. int pgno;
  69308. int flags;
  69309. Db *pDb;
  69310. #endif /* local variables moved into u.by */
  69311. u.by.pgno = 0;
  69312. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69313. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  69314. assert( p->readOnly==0 );
  69315. u.by.pDb = &db->aDb[pOp->p1];
  69316. assert( u.by.pDb->pBt!=0 );
  69317. if( pOp->opcode==OP_CreateTable ){
  69318. /* u.by.flags = BTREE_INTKEY; */
  69319. u.by.flags = BTREE_INTKEY;
  69320. }else{
  69321. u.by.flags = BTREE_BLOBKEY;
  69322. }
  69323. rc = sqlite3BtreeCreateTable(u.by.pDb->pBt, &u.by.pgno, u.by.flags);
  69324. pOut->u.i = u.by.pgno;
  69325. break;
  69326. }
  69327. /* Opcode: ParseSchema P1 * * P4 *
  69328. **
  69329. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  69330. ** that match the WHERE clause P4.
  69331. **
  69332. ** This opcode invokes the parser to create a new virtual machine,
  69333. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  69334. */
  69335. case OP_ParseSchema: {
  69336. #if 0 /* local variables moved into u.bz */
  69337. int iDb;
  69338. const char *zMaster;
  69339. char *zSql;
  69340. InitData initData;
  69341. #endif /* local variables moved into u.bz */
  69342. /* Any prepared statement that invokes this opcode will hold mutexes
  69343. ** on every btree. This is a prerequisite for invoking
  69344. ** sqlite3InitCallback().
  69345. */
  69346. #ifdef SQLITE_DEBUG
  69347. for(u.bz.iDb=0; u.bz.iDb<db->nDb; u.bz.iDb++){
  69348. assert( u.bz.iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[u.bz.iDb].pBt) );
  69349. }
  69350. #endif
  69351. u.bz.iDb = pOp->p1;
  69352. assert( u.bz.iDb>=0 && u.bz.iDb<db->nDb );
  69353. assert( DbHasProperty(db, u.bz.iDb, DB_SchemaLoaded) );
  69354. /* Used to be a conditional */ {
  69355. u.bz.zMaster = SCHEMA_TABLE(u.bz.iDb);
  69356. u.bz.initData.db = db;
  69357. u.bz.initData.iDb = pOp->p1;
  69358. u.bz.initData.pzErrMsg = &p->zErrMsg;
  69359. u.bz.zSql = sqlite3MPrintf(db,
  69360. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  69361. db->aDb[u.bz.iDb].zName, u.bz.zMaster, pOp->p4.z);
  69362. if( u.bz.zSql==0 ){
  69363. rc = SQLITE_NOMEM;
  69364. }else{
  69365. assert( db->init.busy==0 );
  69366. db->init.busy = 1;
  69367. u.bz.initData.rc = SQLITE_OK;
  69368. assert( !db->mallocFailed );
  69369. rc = sqlite3_exec(db, u.bz.zSql, sqlite3InitCallback, &u.bz.initData, 0);
  69370. if( rc==SQLITE_OK ) rc = u.bz.initData.rc;
  69371. sqlite3DbFree(db, u.bz.zSql);
  69372. db->init.busy = 0;
  69373. }
  69374. }
  69375. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  69376. if( rc==SQLITE_NOMEM ){
  69377. goto no_mem;
  69378. }
  69379. break;
  69380. }
  69381. #if !defined(SQLITE_OMIT_ANALYZE)
  69382. /* Opcode: LoadAnalysis P1 * * * *
  69383. **
  69384. ** Read the sqlite_stat1 table for database P1 and load the content
  69385. ** of that table into the internal index hash table. This will cause
  69386. ** the analysis to be used when preparing all subsequent queries.
  69387. */
  69388. case OP_LoadAnalysis: {
  69389. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69390. rc = sqlite3AnalysisLoad(db, pOp->p1);
  69391. break;
  69392. }
  69393. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  69394. /* Opcode: DropTable P1 * * P4 *
  69395. **
  69396. ** Remove the internal (in-memory) data structures that describe
  69397. ** the table named P4 in database P1. This is called after a table
  69398. ** is dropped in order to keep the internal representation of the
  69399. ** schema consistent with what is on disk.
  69400. */
  69401. case OP_DropTable: {
  69402. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  69403. break;
  69404. }
  69405. /* Opcode: DropIndex P1 * * P4 *
  69406. **
  69407. ** Remove the internal (in-memory) data structures that describe
  69408. ** the index named P4 in database P1. This is called after an index
  69409. ** is dropped in order to keep the internal representation of the
  69410. ** schema consistent with what is on disk.
  69411. */
  69412. case OP_DropIndex: {
  69413. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  69414. break;
  69415. }
  69416. /* Opcode: DropTrigger P1 * * P4 *
  69417. **
  69418. ** Remove the internal (in-memory) data structures that describe
  69419. ** the trigger named P4 in database P1. This is called after a trigger
  69420. ** is dropped in order to keep the internal representation of the
  69421. ** schema consistent with what is on disk.
  69422. */
  69423. case OP_DropTrigger: {
  69424. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  69425. break;
  69426. }
  69427. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69428. /* Opcode: IntegrityCk P1 P2 P3 * P5
  69429. **
  69430. ** Do an analysis of the currently open database. Store in
  69431. ** register P1 the text of an error message describing any problems.
  69432. ** If no problems are found, store a NULL in register P1.
  69433. **
  69434. ** The register P3 contains the maximum number of allowed errors.
  69435. ** At most reg(P3) errors will be reported.
  69436. ** In other words, the analysis stops as soon as reg(P1) errors are
  69437. ** seen. Reg(P1) is updated with the number of errors remaining.
  69438. **
  69439. ** The root page numbers of all tables in the database are integer
  69440. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  69441. ** total.
  69442. **
  69443. ** If P5 is not zero, the check is done on the auxiliary database
  69444. ** file, not the main database file.
  69445. **
  69446. ** This opcode is used to implement the integrity_check pragma.
  69447. */
  69448. case OP_IntegrityCk: {
  69449. #if 0 /* local variables moved into u.ca */
  69450. int nRoot; /* Number of tables to check. (Number of root pages.) */
  69451. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  69452. int j; /* Loop counter */
  69453. int nErr; /* Number of errors reported */
  69454. char *z; /* Text of the error report */
  69455. Mem *pnErr; /* Register keeping track of errors remaining */
  69456. #endif /* local variables moved into u.ca */
  69457. assert( p->bIsReader );
  69458. u.ca.nRoot = pOp->p2;
  69459. assert( u.ca.nRoot>0 );
  69460. u.ca.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.ca.nRoot+1) );
  69461. if( u.ca.aRoot==0 ) goto no_mem;
  69462. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69463. u.ca.pnErr = &aMem[pOp->p3];
  69464. assert( (u.ca.pnErr->flags & MEM_Int)!=0 );
  69465. assert( (u.ca.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  69466. pIn1 = &aMem[pOp->p1];
  69467. for(u.ca.j=0; u.ca.j<u.ca.nRoot; u.ca.j++){
  69468. u.ca.aRoot[u.ca.j] = (int)sqlite3VdbeIntValue(&pIn1[u.ca.j]);
  69469. }
  69470. u.ca.aRoot[u.ca.j] = 0;
  69471. assert( pOp->p5<db->nDb );
  69472. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p5))!=0 );
  69473. u.ca.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.ca.aRoot, u.ca.nRoot,
  69474. (int)u.ca.pnErr->u.i, &u.ca.nErr);
  69475. sqlite3DbFree(db, u.ca.aRoot);
  69476. u.ca.pnErr->u.i -= u.ca.nErr;
  69477. sqlite3VdbeMemSetNull(pIn1);
  69478. if( u.ca.nErr==0 ){
  69479. assert( u.ca.z==0 );
  69480. }else if( u.ca.z==0 ){
  69481. goto no_mem;
  69482. }else{
  69483. sqlite3VdbeMemSetStr(pIn1, u.ca.z, -1, SQLITE_UTF8, sqlite3_free);
  69484. }
  69485. UPDATE_MAX_BLOBSIZE(pIn1);
  69486. sqlite3VdbeChangeEncoding(pIn1, encoding);
  69487. break;
  69488. }
  69489. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69490. /* Opcode: RowSetAdd P1 P2 * * *
  69491. **
  69492. ** Insert the integer value held by register P2 into a boolean index
  69493. ** held in register P1.
  69494. **
  69495. ** An assertion fails if P2 is not an integer.
  69496. */
  69497. case OP_RowSetAdd: { /* in1, in2 */
  69498. pIn1 = &aMem[pOp->p1];
  69499. pIn2 = &aMem[pOp->p2];
  69500. assert( (pIn2->flags & MEM_Int)!=0 );
  69501. if( (pIn1->flags & MEM_RowSet)==0 ){
  69502. sqlite3VdbeMemSetRowSet(pIn1);
  69503. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69504. }
  69505. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  69506. break;
  69507. }
  69508. /* Opcode: RowSetRead P1 P2 P3 * *
  69509. **
  69510. ** Extract the smallest value from boolean index P1 and put that value into
  69511. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  69512. ** unchanged and jump to instruction P2.
  69513. */
  69514. case OP_RowSetRead: { /* jump, in1, out3 */
  69515. #if 0 /* local variables moved into u.cb */
  69516. i64 val;
  69517. #endif /* local variables moved into u.cb */
  69518. pIn1 = &aMem[pOp->p1];
  69519. if( (pIn1->flags & MEM_RowSet)==0
  69520. || sqlite3RowSetNext(pIn1->u.pRowSet, &u.cb.val)==0
  69521. ){
  69522. /* The boolean index is empty */
  69523. sqlite3VdbeMemSetNull(pIn1);
  69524. pc = pOp->p2 - 1;
  69525. }else{
  69526. /* A value was pulled from the index */
  69527. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.cb.val);
  69528. }
  69529. goto check_for_interrupt;
  69530. }
  69531. /* Opcode: RowSetTest P1 P2 P3 P4
  69532. **
  69533. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  69534. ** contains a RowSet object and that RowSet object contains
  69535. ** the value held in P3, jump to register P2. Otherwise, insert the
  69536. ** integer in P3 into the RowSet and continue on to the
  69537. ** next opcode.
  69538. **
  69539. ** The RowSet object is optimized for the case where successive sets
  69540. ** of integers, where each set contains no duplicates. Each set
  69541. ** of values is identified by a unique P4 value. The first set
  69542. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  69543. ** non-negative. For non-negative values of P4 only the lower 4
  69544. ** bits are significant.
  69545. **
  69546. ** This allows optimizations: (a) when P4==0 there is no need to test
  69547. ** the rowset object for P3, as it is guaranteed not to contain it,
  69548. ** (b) when P4==-1 there is no need to insert the value, as it will
  69549. ** never be tested for, and (c) when a value that is part of set X is
  69550. ** inserted, there is no need to search to see if the same value was
  69551. ** previously inserted as part of set X (only if it was previously
  69552. ** inserted as part of some other set).
  69553. */
  69554. case OP_RowSetTest: { /* jump, in1, in3 */
  69555. #if 0 /* local variables moved into u.cc */
  69556. int iSet;
  69557. int exists;
  69558. #endif /* local variables moved into u.cc */
  69559. pIn1 = &aMem[pOp->p1];
  69560. pIn3 = &aMem[pOp->p3];
  69561. u.cc.iSet = pOp->p4.i;
  69562. assert( pIn3->flags&MEM_Int );
  69563. /* If there is anything other than a rowset object in memory cell P1,
  69564. ** delete it now and initialize P1 with an empty rowset
  69565. */
  69566. if( (pIn1->flags & MEM_RowSet)==0 ){
  69567. sqlite3VdbeMemSetRowSet(pIn1);
  69568. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69569. }
  69570. assert( pOp->p4type==P4_INT32 );
  69571. assert( u.cc.iSet==-1 || u.cc.iSet>=0 );
  69572. if( u.cc.iSet ){
  69573. u.cc.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
  69574. (u8)(u.cc.iSet>=0 ? u.cc.iSet & 0xf : 0xff),
  69575. pIn3->u.i);
  69576. if( u.cc.exists ){
  69577. pc = pOp->p2 - 1;
  69578. break;
  69579. }
  69580. }
  69581. if( u.cc.iSet>=0 ){
  69582. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  69583. }
  69584. break;
  69585. }
  69586. #ifndef SQLITE_OMIT_TRIGGER
  69587. /* Opcode: Program P1 P2 P3 P4 *
  69588. **
  69589. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  69590. **
  69591. ** P1 contains the address of the memory cell that contains the first memory
  69592. ** cell in an array of values used as arguments to the sub-program. P2
  69593. ** contains the address to jump to if the sub-program throws an IGNORE
  69594. ** exception using the RAISE() function. Register P3 contains the address
  69595. ** of a memory cell in this (the parent) VM that is used to allocate the
  69596. ** memory required by the sub-vdbe at runtime.
  69597. **
  69598. ** P4 is a pointer to the VM containing the trigger program.
  69599. */
  69600. case OP_Program: { /* jump */
  69601. #if 0 /* local variables moved into u.cd */
  69602. int nMem; /* Number of memory registers for sub-program */
  69603. int nByte; /* Bytes of runtime space required for sub-program */
  69604. Mem *pRt; /* Register to allocate runtime space */
  69605. Mem *pMem; /* Used to iterate through memory cells */
  69606. Mem *pEnd; /* Last memory cell in new array */
  69607. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  69608. SubProgram *pProgram; /* Sub-program to execute */
  69609. void *t; /* Token identifying trigger */
  69610. #endif /* local variables moved into u.cd */
  69611. u.cd.pProgram = pOp->p4.pProgram;
  69612. u.cd.pRt = &aMem[pOp->p3];
  69613. assert( u.cd.pProgram->nOp>0 );
  69614. /* If the p5 flag is clear, then recursive invocation of triggers is
  69615. ** disabled for backwards compatibility (p5 is set if this sub-program
  69616. ** is really a trigger, not a foreign key action, and the flag set
  69617. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  69618. **
  69619. ** It is recursive invocation of triggers, at the SQL level, that is
  69620. ** disabled. In some cases a single trigger may generate more than one
  69621. ** SubProgram (if the trigger may be executed with more than one different
  69622. ** ON CONFLICT algorithm). SubProgram structures associated with a
  69623. ** single trigger all have the same value for the SubProgram.token
  69624. ** variable. */
  69625. if( pOp->p5 ){
  69626. u.cd.t = u.cd.pProgram->token;
  69627. for(u.cd.pFrame=p->pFrame; u.cd.pFrame && u.cd.pFrame->token!=u.cd.t; u.cd.pFrame=u.cd.pFrame->pParent);
  69628. if( u.cd.pFrame ) break;
  69629. }
  69630. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  69631. rc = SQLITE_ERROR;
  69632. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  69633. break;
  69634. }
  69635. /* Register u.cd.pRt is used to store the memory required to save the state
  69636. ** of the current program, and the memory required at runtime to execute
  69637. ** the trigger program. If this trigger has been fired before, then u.cd.pRt
  69638. ** is already allocated. Otherwise, it must be initialized. */
  69639. if( (u.cd.pRt->flags&MEM_Frame)==0 ){
  69640. /* SubProgram.nMem is set to the number of memory cells used by the
  69641. ** program stored in SubProgram.aOp. As well as these, one memory
  69642. ** cell is required for each cursor used by the program. Set local
  69643. ** variable u.cd.nMem (and later, VdbeFrame.nChildMem) to this value.
  69644. */
  69645. u.cd.nMem = u.cd.pProgram->nMem + u.cd.pProgram->nCsr;
  69646. u.cd.nByte = ROUND8(sizeof(VdbeFrame))
  69647. + u.cd.nMem * sizeof(Mem)
  69648. + u.cd.pProgram->nCsr * sizeof(VdbeCursor *)
  69649. + u.cd.pProgram->nOnce * sizeof(u8);
  69650. u.cd.pFrame = sqlite3DbMallocZero(db, u.cd.nByte);
  69651. if( !u.cd.pFrame ){
  69652. goto no_mem;
  69653. }
  69654. sqlite3VdbeMemRelease(u.cd.pRt);
  69655. u.cd.pRt->flags = MEM_Frame;
  69656. u.cd.pRt->u.pFrame = u.cd.pFrame;
  69657. u.cd.pFrame->v = p;
  69658. u.cd.pFrame->nChildMem = u.cd.nMem;
  69659. u.cd.pFrame->nChildCsr = u.cd.pProgram->nCsr;
  69660. u.cd.pFrame->pc = pc;
  69661. u.cd.pFrame->aMem = p->aMem;
  69662. u.cd.pFrame->nMem = p->nMem;
  69663. u.cd.pFrame->apCsr = p->apCsr;
  69664. u.cd.pFrame->nCursor = p->nCursor;
  69665. u.cd.pFrame->aOp = p->aOp;
  69666. u.cd.pFrame->nOp = p->nOp;
  69667. u.cd.pFrame->token = u.cd.pProgram->token;
  69668. u.cd.pFrame->aOnceFlag = p->aOnceFlag;
  69669. u.cd.pFrame->nOnceFlag = p->nOnceFlag;
  69670. u.cd.pEnd = &VdbeFrameMem(u.cd.pFrame)[u.cd.pFrame->nChildMem];
  69671. for(u.cd.pMem=VdbeFrameMem(u.cd.pFrame); u.cd.pMem!=u.cd.pEnd; u.cd.pMem++){
  69672. u.cd.pMem->flags = MEM_Invalid;
  69673. u.cd.pMem->db = db;
  69674. }
  69675. }else{
  69676. u.cd.pFrame = u.cd.pRt->u.pFrame;
  69677. assert( u.cd.pProgram->nMem+u.cd.pProgram->nCsr==u.cd.pFrame->nChildMem );
  69678. assert( u.cd.pProgram->nCsr==u.cd.pFrame->nChildCsr );
  69679. assert( pc==u.cd.pFrame->pc );
  69680. }
  69681. p->nFrame++;
  69682. u.cd.pFrame->pParent = p->pFrame;
  69683. u.cd.pFrame->lastRowid = lastRowid;
  69684. u.cd.pFrame->nChange = p->nChange;
  69685. p->nChange = 0;
  69686. p->pFrame = u.cd.pFrame;
  69687. p->aMem = aMem = &VdbeFrameMem(u.cd.pFrame)[-1];
  69688. p->nMem = u.cd.pFrame->nChildMem;
  69689. p->nCursor = (u16)u.cd.pFrame->nChildCsr;
  69690. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  69691. p->aOp = aOp = u.cd.pProgram->aOp;
  69692. p->nOp = u.cd.pProgram->nOp;
  69693. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  69694. p->nOnceFlag = u.cd.pProgram->nOnce;
  69695. pc = -1;
  69696. memset(p->aOnceFlag, 0, p->nOnceFlag);
  69697. break;
  69698. }
  69699. /* Opcode: Param P1 P2 * * *
  69700. **
  69701. ** This opcode is only ever present in sub-programs called via the
  69702. ** OP_Program instruction. Copy a value currently stored in a memory
  69703. ** cell of the calling (parent) frame to cell P2 in the current frames
  69704. ** address space. This is used by trigger programs to access the new.*
  69705. ** and old.* values.
  69706. **
  69707. ** The address of the cell in the parent frame is determined by adding
  69708. ** the value of the P1 argument to the value of the P1 argument to the
  69709. ** calling OP_Program instruction.
  69710. */
  69711. case OP_Param: { /* out2-prerelease */
  69712. #if 0 /* local variables moved into u.ce */
  69713. VdbeFrame *pFrame;
  69714. Mem *pIn;
  69715. #endif /* local variables moved into u.ce */
  69716. u.ce.pFrame = p->pFrame;
  69717. u.ce.pIn = &u.ce.pFrame->aMem[pOp->p1 + u.ce.pFrame->aOp[u.ce.pFrame->pc].p1];
  69718. sqlite3VdbeMemShallowCopy(pOut, u.ce.pIn, MEM_Ephem);
  69719. break;
  69720. }
  69721. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  69722. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69723. /* Opcode: FkCounter P1 P2 * * *
  69724. **
  69725. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  69726. ** If P1 is non-zero, the database constraint counter is incremented
  69727. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  69728. ** statement counter is incremented (immediate foreign key constraints).
  69729. */
  69730. case OP_FkCounter: {
  69731. if( db->flags & SQLITE_DeferFKs ){
  69732. db->nDeferredImmCons += pOp->p2;
  69733. }else if( pOp->p1 ){
  69734. db->nDeferredCons += pOp->p2;
  69735. }else{
  69736. p->nFkConstraint += pOp->p2;
  69737. }
  69738. break;
  69739. }
  69740. /* Opcode: FkIfZero P1 P2 * * *
  69741. **
  69742. ** This opcode tests if a foreign key constraint-counter is currently zero.
  69743. ** If so, jump to instruction P2. Otherwise, fall through to the next
  69744. ** instruction.
  69745. **
  69746. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  69747. ** is zero (the one that counts deferred constraint violations). If P1 is
  69748. ** zero, the jump is taken if the statement constraint-counter is zero
  69749. ** (immediate foreign key constraint violations).
  69750. */
  69751. case OP_FkIfZero: { /* jump */
  69752. if( pOp->p1 ){
  69753. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69754. }else{
  69755. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69756. }
  69757. break;
  69758. }
  69759. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  69760. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69761. /* Opcode: MemMax P1 P2 * * *
  69762. **
  69763. ** P1 is a register in the root frame of this VM (the root frame is
  69764. ** different from the current frame if this instruction is being executed
  69765. ** within a sub-program). Set the value of register P1 to the maximum of
  69766. ** its current value and the value in register P2.
  69767. **
  69768. ** This instruction throws an error if the memory cell is not initially
  69769. ** an integer.
  69770. */
  69771. case OP_MemMax: { /* in2 */
  69772. #if 0 /* local variables moved into u.cf */
  69773. Mem *pIn1;
  69774. VdbeFrame *pFrame;
  69775. #endif /* local variables moved into u.cf */
  69776. if( p->pFrame ){
  69777. for(u.cf.pFrame=p->pFrame; u.cf.pFrame->pParent; u.cf.pFrame=u.cf.pFrame->pParent);
  69778. u.cf.pIn1 = &u.cf.pFrame->aMem[pOp->p1];
  69779. }else{
  69780. u.cf.pIn1 = &aMem[pOp->p1];
  69781. }
  69782. assert( memIsValid(u.cf.pIn1) );
  69783. sqlite3VdbeMemIntegerify(u.cf.pIn1);
  69784. pIn2 = &aMem[pOp->p2];
  69785. sqlite3VdbeMemIntegerify(pIn2);
  69786. if( u.cf.pIn1->u.i<pIn2->u.i){
  69787. u.cf.pIn1->u.i = pIn2->u.i;
  69788. }
  69789. break;
  69790. }
  69791. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  69792. /* Opcode: IfPos P1 P2 * * *
  69793. **
  69794. ** If the value of register P1 is 1 or greater, jump to P2.
  69795. **
  69796. ** It is illegal to use this instruction on a register that does
  69797. ** not contain an integer. An assertion fault will result if you try.
  69798. */
  69799. case OP_IfPos: { /* jump, in1 */
  69800. pIn1 = &aMem[pOp->p1];
  69801. assert( pIn1->flags&MEM_Int );
  69802. if( pIn1->u.i>0 ){
  69803. pc = pOp->p2 - 1;
  69804. }
  69805. break;
  69806. }
  69807. /* Opcode: IfNeg P1 P2 * * *
  69808. **
  69809. ** If the value of register P1 is less than zero, jump to P2.
  69810. **
  69811. ** It is illegal to use this instruction on a register that does
  69812. ** not contain an integer. An assertion fault will result if you try.
  69813. */
  69814. case OP_IfNeg: { /* jump, in1 */
  69815. pIn1 = &aMem[pOp->p1];
  69816. assert( pIn1->flags&MEM_Int );
  69817. if( pIn1->u.i<0 ){
  69818. pc = pOp->p2 - 1;
  69819. }
  69820. break;
  69821. }
  69822. /* Opcode: IfZero P1 P2 P3 * *
  69823. **
  69824. ** The register P1 must contain an integer. Add literal P3 to the
  69825. ** value in register P1. If the result is exactly 0, jump to P2.
  69826. **
  69827. ** It is illegal to use this instruction on a register that does
  69828. ** not contain an integer. An assertion fault will result if you try.
  69829. */
  69830. case OP_IfZero: { /* jump, in1 */
  69831. pIn1 = &aMem[pOp->p1];
  69832. assert( pIn1->flags&MEM_Int );
  69833. pIn1->u.i += pOp->p3;
  69834. if( pIn1->u.i==0 ){
  69835. pc = pOp->p2 - 1;
  69836. }
  69837. break;
  69838. }
  69839. /* Opcode: AggStep * P2 P3 P4 P5
  69840. **
  69841. ** Execute the step function for an aggregate. The
  69842. ** function has P5 arguments. P4 is a pointer to the FuncDef
  69843. ** structure that specifies the function. Use register
  69844. ** P3 as the accumulator.
  69845. **
  69846. ** The P5 arguments are taken from register P2 and its
  69847. ** successors.
  69848. */
  69849. case OP_AggStep: {
  69850. #if 0 /* local variables moved into u.cg */
  69851. int n;
  69852. int i;
  69853. Mem *pMem;
  69854. Mem *pRec;
  69855. sqlite3_context ctx;
  69856. sqlite3_value **apVal;
  69857. #endif /* local variables moved into u.cg */
  69858. u.cg.n = pOp->p5;
  69859. assert( u.cg.n>=0 );
  69860. u.cg.pRec = &aMem[pOp->p2];
  69861. u.cg.apVal = p->apArg;
  69862. assert( u.cg.apVal || u.cg.n==0 );
  69863. for(u.cg.i=0; u.cg.i<u.cg.n; u.cg.i++, u.cg.pRec++){
  69864. assert( memIsValid(u.cg.pRec) );
  69865. u.cg.apVal[u.cg.i] = u.cg.pRec;
  69866. memAboutToChange(p, u.cg.pRec);
  69867. sqlite3VdbeMemStoreType(u.cg.pRec);
  69868. }
  69869. u.cg.ctx.pFunc = pOp->p4.pFunc;
  69870. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69871. u.cg.ctx.pMem = u.cg.pMem = &aMem[pOp->p3];
  69872. u.cg.pMem->n++;
  69873. u.cg.ctx.s.flags = MEM_Null;
  69874. u.cg.ctx.s.z = 0;
  69875. u.cg.ctx.s.zMalloc = 0;
  69876. u.cg.ctx.s.xDel = 0;
  69877. u.cg.ctx.s.db = db;
  69878. u.cg.ctx.isError = 0;
  69879. u.cg.ctx.pColl = 0;
  69880. u.cg.ctx.skipFlag = 0;
  69881. if( u.cg.ctx.pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  69882. assert( pOp>p->aOp );
  69883. assert( pOp[-1].p4type==P4_COLLSEQ );
  69884. assert( pOp[-1].opcode==OP_CollSeq );
  69885. u.cg.ctx.pColl = pOp[-1].p4.pColl;
  69886. }
  69887. (u.cg.ctx.pFunc->xStep)(&u.cg.ctx, u.cg.n, u.cg.apVal); /* IMP: R-24505-23230 */
  69888. if( u.cg.ctx.isError ){
  69889. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cg.ctx.s));
  69890. rc = u.cg.ctx.isError;
  69891. }
  69892. if( u.cg.ctx.skipFlag ){
  69893. assert( pOp[-1].opcode==OP_CollSeq );
  69894. u.cg.i = pOp[-1].p1;
  69895. if( u.cg.i ) sqlite3VdbeMemSetInt64(&aMem[u.cg.i], 1);
  69896. }
  69897. sqlite3VdbeMemRelease(&u.cg.ctx.s);
  69898. break;
  69899. }
  69900. /* Opcode: AggFinal P1 P2 * P4 *
  69901. **
  69902. ** Execute the finalizer function for an aggregate. P1 is
  69903. ** the memory location that is the accumulator for the aggregate.
  69904. **
  69905. ** P2 is the number of arguments that the step function takes and
  69906. ** P4 is a pointer to the FuncDef for this function. The P2
  69907. ** argument is not used by this opcode. It is only there to disambiguate
  69908. ** functions that can take varying numbers of arguments. The
  69909. ** P4 argument is only needed for the degenerate case where
  69910. ** the step function was not previously called.
  69911. */
  69912. case OP_AggFinal: {
  69913. #if 0 /* local variables moved into u.ch */
  69914. Mem *pMem;
  69915. #endif /* local variables moved into u.ch */
  69916. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69917. u.ch.pMem = &aMem[pOp->p1];
  69918. assert( (u.ch.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  69919. rc = sqlite3VdbeMemFinalize(u.ch.pMem, pOp->p4.pFunc);
  69920. if( rc ){
  69921. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.ch.pMem));
  69922. }
  69923. sqlite3VdbeChangeEncoding(u.ch.pMem, encoding);
  69924. UPDATE_MAX_BLOBSIZE(u.ch.pMem);
  69925. if( sqlite3VdbeMemTooBig(u.ch.pMem) ){
  69926. goto too_big;
  69927. }
  69928. break;
  69929. }
  69930. #ifndef SQLITE_OMIT_WAL
  69931. /* Opcode: Checkpoint P1 P2 P3 * *
  69932. **
  69933. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  69934. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  69935. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  69936. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  69937. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  69938. ** in the WAL that have been checkpointed after the checkpoint
  69939. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  69940. ** mem[P3+2] are initialized to -1.
  69941. */
  69942. case OP_Checkpoint: {
  69943. #if 0 /* local variables moved into u.ci */
  69944. int i; /* Loop counter */
  69945. int aRes[3]; /* Results */
  69946. Mem *pMem; /* Write results here */
  69947. #endif /* local variables moved into u.ci */
  69948. assert( p->readOnly==0 );
  69949. u.ci.aRes[0] = 0;
  69950. u.ci.aRes[1] = u.ci.aRes[2] = -1;
  69951. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  69952. || pOp->p2==SQLITE_CHECKPOINT_FULL
  69953. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  69954. );
  69955. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &u.ci.aRes[1], &u.ci.aRes[2]);
  69956. if( rc==SQLITE_BUSY ){
  69957. rc = SQLITE_OK;
  69958. u.ci.aRes[0] = 1;
  69959. }
  69960. for(u.ci.i=0, u.ci.pMem = &aMem[pOp->p3]; u.ci.i<3; u.ci.i++, u.ci.pMem++){
  69961. sqlite3VdbeMemSetInt64(u.ci.pMem, (i64)u.ci.aRes[u.ci.i]);
  69962. }
  69963. break;
  69964. };
  69965. #endif
  69966. #ifndef SQLITE_OMIT_PRAGMA
  69967. /* Opcode: JournalMode P1 P2 P3 * P5
  69968. **
  69969. ** Change the journal mode of database P1 to P3. P3 must be one of the
  69970. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  69971. ** modes (delete, truncate, persist, off and memory), this is a simple
  69972. ** operation. No IO is required.
  69973. **
  69974. ** If changing into or out of WAL mode the procedure is more complicated.
  69975. **
  69976. ** Write a string containing the final journal-mode to register P2.
  69977. */
  69978. case OP_JournalMode: { /* out2-prerelease */
  69979. #if 0 /* local variables moved into u.cj */
  69980. Btree *pBt; /* Btree to change journal mode of */
  69981. Pager *pPager; /* Pager associated with pBt */
  69982. int eNew; /* New journal mode */
  69983. int eOld; /* The old journal mode */
  69984. #ifndef SQLITE_OMIT_WAL
  69985. const char *zFilename; /* Name of database file for pPager */
  69986. #endif
  69987. #endif /* local variables moved into u.cj */
  69988. u.cj.eNew = pOp->p3;
  69989. assert( u.cj.eNew==PAGER_JOURNALMODE_DELETE
  69990. || u.cj.eNew==PAGER_JOURNALMODE_TRUNCATE
  69991. || u.cj.eNew==PAGER_JOURNALMODE_PERSIST
  69992. || u.cj.eNew==PAGER_JOURNALMODE_OFF
  69993. || u.cj.eNew==PAGER_JOURNALMODE_MEMORY
  69994. || u.cj.eNew==PAGER_JOURNALMODE_WAL
  69995. || u.cj.eNew==PAGER_JOURNALMODE_QUERY
  69996. );
  69997. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69998. assert( p->readOnly==0 );
  69999. u.cj.pBt = db->aDb[pOp->p1].pBt;
  70000. u.cj.pPager = sqlite3BtreePager(u.cj.pBt);
  70001. u.cj.eOld = sqlite3PagerGetJournalMode(u.cj.pPager);
  70002. if( u.cj.eNew==PAGER_JOURNALMODE_QUERY ) u.cj.eNew = u.cj.eOld;
  70003. if( !sqlite3PagerOkToChangeJournalMode(u.cj.pPager) ) u.cj.eNew = u.cj.eOld;
  70004. #ifndef SQLITE_OMIT_WAL
  70005. u.cj.zFilename = sqlite3PagerFilename(u.cj.pPager, 1);
  70006. /* Do not allow a transition to journal_mode=WAL for a database
  70007. ** in temporary storage or if the VFS does not support shared memory
  70008. */
  70009. if( u.cj.eNew==PAGER_JOURNALMODE_WAL
  70010. && (sqlite3Strlen30(u.cj.zFilename)==0 /* Temp file */
  70011. || !sqlite3PagerWalSupported(u.cj.pPager)) /* No shared-memory support */
  70012. ){
  70013. u.cj.eNew = u.cj.eOld;
  70014. }
  70015. if( (u.cj.eNew!=u.cj.eOld)
  70016. && (u.cj.eOld==PAGER_JOURNALMODE_WAL || u.cj.eNew==PAGER_JOURNALMODE_WAL)
  70017. ){
  70018. if( !db->autoCommit || db->nVdbeRead>1 ){
  70019. rc = SQLITE_ERROR;
  70020. sqlite3SetString(&p->zErrMsg, db,
  70021. "cannot change %s wal mode from within a transaction",
  70022. (u.cj.eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  70023. );
  70024. break;
  70025. }else{
  70026. if( u.cj.eOld==PAGER_JOURNALMODE_WAL ){
  70027. /* If leaving WAL mode, close the log file. If successful, the call
  70028. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  70029. ** file. An EXCLUSIVE lock may still be held on the database file
  70030. ** after a successful return.
  70031. */
  70032. rc = sqlite3PagerCloseWal(u.cj.pPager);
  70033. if( rc==SQLITE_OK ){
  70034. sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  70035. }
  70036. }else if( u.cj.eOld==PAGER_JOURNALMODE_MEMORY ){
  70037. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  70038. ** as an intermediate */
  70039. sqlite3PagerSetJournalMode(u.cj.pPager, PAGER_JOURNALMODE_OFF);
  70040. }
  70041. /* Open a transaction on the database file. Regardless of the journal
  70042. ** mode, this transaction always uses a rollback journal.
  70043. */
  70044. assert( sqlite3BtreeIsInTrans(u.cj.pBt)==0 );
  70045. if( rc==SQLITE_OK ){
  70046. rc = sqlite3BtreeSetVersion(u.cj.pBt, (u.cj.eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  70047. }
  70048. }
  70049. }
  70050. #endif /* ifndef SQLITE_OMIT_WAL */
  70051. if( rc ){
  70052. u.cj.eNew = u.cj.eOld;
  70053. }
  70054. u.cj.eNew = sqlite3PagerSetJournalMode(u.cj.pPager, u.cj.eNew);
  70055. pOut = &aMem[pOp->p2];
  70056. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  70057. pOut->z = (char *)sqlite3JournalModename(u.cj.eNew);
  70058. pOut->n = sqlite3Strlen30(pOut->z);
  70059. pOut->enc = SQLITE_UTF8;
  70060. sqlite3VdbeChangeEncoding(pOut, encoding);
  70061. break;
  70062. };
  70063. #endif /* SQLITE_OMIT_PRAGMA */
  70064. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  70065. /* Opcode: Vacuum * * * * *
  70066. **
  70067. ** Vacuum the entire database. This opcode will cause other virtual
  70068. ** machines to be created and run. It may not be called from within
  70069. ** a transaction.
  70070. */
  70071. case OP_Vacuum: {
  70072. assert( p->readOnly==0 );
  70073. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  70074. break;
  70075. }
  70076. #endif
  70077. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  70078. /* Opcode: IncrVacuum P1 P2 * * *
  70079. **
  70080. ** Perform a single step of the incremental vacuum procedure on
  70081. ** the P1 database. If the vacuum has finished, jump to instruction
  70082. ** P2. Otherwise, fall through to the next instruction.
  70083. */
  70084. case OP_IncrVacuum: { /* jump */
  70085. #if 0 /* local variables moved into u.ck */
  70086. Btree *pBt;
  70087. #endif /* local variables moved into u.ck */
  70088. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  70089. assert( (p->btreeMask & (((yDbMask)1)<<pOp->p1))!=0 );
  70090. assert( p->readOnly==0 );
  70091. u.ck.pBt = db->aDb[pOp->p1].pBt;
  70092. rc = sqlite3BtreeIncrVacuum(u.ck.pBt);
  70093. if( rc==SQLITE_DONE ){
  70094. pc = pOp->p2 - 1;
  70095. rc = SQLITE_OK;
  70096. }
  70097. break;
  70098. }
  70099. #endif
  70100. /* Opcode: Expire P1 * * * *
  70101. **
  70102. ** Cause precompiled statements to become expired. An expired statement
  70103. ** fails with an error code of SQLITE_SCHEMA if it is ever executed
  70104. ** (via sqlite3_step()).
  70105. **
  70106. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  70107. ** then only the currently executing statement is affected.
  70108. */
  70109. case OP_Expire: {
  70110. if( !pOp->p1 ){
  70111. sqlite3ExpirePreparedStatements(db);
  70112. }else{
  70113. p->expired = 1;
  70114. }
  70115. break;
  70116. }
  70117. #ifndef SQLITE_OMIT_SHARED_CACHE
  70118. /* Opcode: TableLock P1 P2 P3 P4 *
  70119. **
  70120. ** Obtain a lock on a particular table. This instruction is only used when
  70121. ** the shared-cache feature is enabled.
  70122. **
  70123. ** P1 is the index of the database in sqlite3.aDb[] of the database
  70124. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  70125. ** a write lock if P3==1.
  70126. **
  70127. ** P2 contains the root-page of the table to lock.
  70128. **
  70129. ** P4 contains a pointer to the name of the table being locked. This is only
  70130. ** used to generate an error message if the lock cannot be obtained.
  70131. */
  70132. case OP_TableLock: {
  70133. u8 isWriteLock = (u8)pOp->p3;
  70134. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  70135. int p1 = pOp->p1;
  70136. assert( p1>=0 && p1<db->nDb );
  70137. assert( (p->btreeMask & (((yDbMask)1)<<p1))!=0 );
  70138. assert( isWriteLock==0 || isWriteLock==1 );
  70139. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  70140. if( (rc&0xFF)==SQLITE_LOCKED ){
  70141. const char *z = pOp->p4.z;
  70142. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  70143. }
  70144. }
  70145. break;
  70146. }
  70147. #endif /* SQLITE_OMIT_SHARED_CACHE */
  70148. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70149. /* Opcode: VBegin * * * P4 *
  70150. **
  70151. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  70152. ** xBegin method for that table.
  70153. **
  70154. ** Also, whether or not P4 is set, check that this is not being called from
  70155. ** within a callback to a virtual table xSync() method. If it is, the error
  70156. ** code will be set to SQLITE_LOCKED.
  70157. */
  70158. case OP_VBegin: {
  70159. #if 0 /* local variables moved into u.cl */
  70160. VTable *pVTab;
  70161. #endif /* local variables moved into u.cl */
  70162. u.cl.pVTab = pOp->p4.pVtab;
  70163. rc = sqlite3VtabBegin(db, u.cl.pVTab);
  70164. if( u.cl.pVTab ) sqlite3VtabImportErrmsg(p, u.cl.pVTab->pVtab);
  70165. break;
  70166. }
  70167. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70168. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70169. /* Opcode: VCreate P1 * * P4 *
  70170. **
  70171. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  70172. ** for that table.
  70173. */
  70174. case OP_VCreate: {
  70175. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  70176. break;
  70177. }
  70178. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70179. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70180. /* Opcode: VDestroy P1 * * P4 *
  70181. **
  70182. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  70183. ** of that table.
  70184. */
  70185. case OP_VDestroy: {
  70186. p->inVtabMethod = 2;
  70187. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  70188. p->inVtabMethod = 0;
  70189. break;
  70190. }
  70191. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70192. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70193. /* Opcode: VOpen P1 * * P4 *
  70194. **
  70195. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70196. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  70197. ** table and stores that cursor in P1.
  70198. */
  70199. case OP_VOpen: {
  70200. #if 0 /* local variables moved into u.cm */
  70201. VdbeCursor *pCur;
  70202. sqlite3_vtab_cursor *pVtabCursor;
  70203. sqlite3_vtab *pVtab;
  70204. sqlite3_module *pModule;
  70205. #endif /* local variables moved into u.cm */
  70206. assert( p->bIsReader );
  70207. u.cm.pCur = 0;
  70208. u.cm.pVtabCursor = 0;
  70209. u.cm.pVtab = pOp->p4.pVtab->pVtab;
  70210. u.cm.pModule = (sqlite3_module *)u.cm.pVtab->pModule;
  70211. assert(u.cm.pVtab && u.cm.pModule);
  70212. rc = u.cm.pModule->xOpen(u.cm.pVtab, &u.cm.pVtabCursor);
  70213. sqlite3VtabImportErrmsg(p, u.cm.pVtab);
  70214. if( SQLITE_OK==rc ){
  70215. /* Initialize sqlite3_vtab_cursor base class */
  70216. u.cm.pVtabCursor->pVtab = u.cm.pVtab;
  70217. /* Initialize vdbe cursor object */
  70218. u.cm.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  70219. if( u.cm.pCur ){
  70220. u.cm.pCur->pVtabCursor = u.cm.pVtabCursor;
  70221. u.cm.pCur->pModule = u.cm.pVtabCursor->pVtab->pModule;
  70222. }else{
  70223. db->mallocFailed = 1;
  70224. u.cm.pModule->xClose(u.cm.pVtabCursor);
  70225. }
  70226. }
  70227. break;
  70228. }
  70229. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70231. /* Opcode: VFilter P1 P2 P3 P4 *
  70232. **
  70233. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  70234. ** the filtered result set is empty.
  70235. **
  70236. ** P4 is either NULL or a string that was generated by the xBestIndex
  70237. ** method of the module. The interpretation of the P4 string is left
  70238. ** to the module implementation.
  70239. **
  70240. ** This opcode invokes the xFilter method on the virtual table specified
  70241. ** by P1. The integer query plan parameter to xFilter is stored in register
  70242. ** P3. Register P3+1 stores the argc parameter to be passed to the
  70243. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  70244. ** additional parameters which are passed to
  70245. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  70246. **
  70247. ** A jump is made to P2 if the result set after filtering would be empty.
  70248. */
  70249. case OP_VFilter: { /* jump */
  70250. #if 0 /* local variables moved into u.cn */
  70251. int nArg;
  70252. int iQuery;
  70253. const sqlite3_module *pModule;
  70254. Mem *pQuery;
  70255. Mem *pArgc;
  70256. sqlite3_vtab_cursor *pVtabCursor;
  70257. sqlite3_vtab *pVtab;
  70258. VdbeCursor *pCur;
  70259. int res;
  70260. int i;
  70261. Mem **apArg;
  70262. #endif /* local variables moved into u.cn */
  70263. u.cn.pQuery = &aMem[pOp->p3];
  70264. u.cn.pArgc = &u.cn.pQuery[1];
  70265. u.cn.pCur = p->apCsr[pOp->p1];
  70266. assert( memIsValid(u.cn.pQuery) );
  70267. REGISTER_TRACE(pOp->p3, u.cn.pQuery);
  70268. assert( u.cn.pCur->pVtabCursor );
  70269. u.cn.pVtabCursor = u.cn.pCur->pVtabCursor;
  70270. u.cn.pVtab = u.cn.pVtabCursor->pVtab;
  70271. u.cn.pModule = u.cn.pVtab->pModule;
  70272. /* Grab the index number and argc parameters */
  70273. assert( (u.cn.pQuery->flags&MEM_Int)!=0 && u.cn.pArgc->flags==MEM_Int );
  70274. u.cn.nArg = (int)u.cn.pArgc->u.i;
  70275. u.cn.iQuery = (int)u.cn.pQuery->u.i;
  70276. /* Invoke the xFilter method */
  70277. {
  70278. u.cn.res = 0;
  70279. u.cn.apArg = p->apArg;
  70280. for(u.cn.i = 0; u.cn.i<u.cn.nArg; u.cn.i++){
  70281. u.cn.apArg[u.cn.i] = &u.cn.pArgc[u.cn.i+1];
  70282. sqlite3VdbeMemStoreType(u.cn.apArg[u.cn.i]);
  70283. }
  70284. p->inVtabMethod = 1;
  70285. rc = u.cn.pModule->xFilter(u.cn.pVtabCursor, u.cn.iQuery, pOp->p4.z, u.cn.nArg, u.cn.apArg);
  70286. p->inVtabMethod = 0;
  70287. sqlite3VtabImportErrmsg(p, u.cn.pVtab);
  70288. if( rc==SQLITE_OK ){
  70289. u.cn.res = u.cn.pModule->xEof(u.cn.pVtabCursor);
  70290. }
  70291. if( u.cn.res ){
  70292. pc = pOp->p2 - 1;
  70293. }
  70294. }
  70295. u.cn.pCur->nullRow = 0;
  70296. break;
  70297. }
  70298. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70299. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70300. /* Opcode: VColumn P1 P2 P3 * *
  70301. **
  70302. ** Store the value of the P2-th column of
  70303. ** the row of the virtual-table that the
  70304. ** P1 cursor is pointing to into register P3.
  70305. */
  70306. case OP_VColumn: {
  70307. #if 0 /* local variables moved into u.co */
  70308. sqlite3_vtab *pVtab;
  70309. const sqlite3_module *pModule;
  70310. Mem *pDest;
  70311. sqlite3_context sContext;
  70312. #endif /* local variables moved into u.co */
  70313. VdbeCursor *pCur = p->apCsr[pOp->p1];
  70314. assert( pCur->pVtabCursor );
  70315. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70316. u.co.pDest = &aMem[pOp->p3];
  70317. memAboutToChange(p, u.co.pDest);
  70318. if( pCur->nullRow ){
  70319. sqlite3VdbeMemSetNull(u.co.pDest);
  70320. break;
  70321. }
  70322. u.co.pVtab = pCur->pVtabCursor->pVtab;
  70323. u.co.pModule = u.co.pVtab->pModule;
  70324. assert( u.co.pModule->xColumn );
  70325. memset(&u.co.sContext, 0, sizeof(u.co.sContext));
  70326. /* The output cell may already have a buffer allocated. Move
  70327. ** the current contents to u.co.sContext.s so in case the user-function
  70328. ** can use the already allocated buffer instead of allocating a
  70329. ** new one.
  70330. */
  70331. sqlite3VdbeMemMove(&u.co.sContext.s, u.co.pDest);
  70332. MemSetTypeFlag(&u.co.sContext.s, MEM_Null);
  70333. rc = u.co.pModule->xColumn(pCur->pVtabCursor, &u.co.sContext, pOp->p2);
  70334. sqlite3VtabImportErrmsg(p, u.co.pVtab);
  70335. if( u.co.sContext.isError ){
  70336. rc = u.co.sContext.isError;
  70337. }
  70338. /* Copy the result of the function to the P3 register. We
  70339. ** do this regardless of whether or not an error occurred to ensure any
  70340. ** dynamic allocation in u.co.sContext.s (a Mem struct) is released.
  70341. */
  70342. sqlite3VdbeChangeEncoding(&u.co.sContext.s, encoding);
  70343. sqlite3VdbeMemMove(u.co.pDest, &u.co.sContext.s);
  70344. REGISTER_TRACE(pOp->p3, u.co.pDest);
  70345. UPDATE_MAX_BLOBSIZE(u.co.pDest);
  70346. if( sqlite3VdbeMemTooBig(u.co.pDest) ){
  70347. goto too_big;
  70348. }
  70349. break;
  70350. }
  70351. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70352. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70353. /* Opcode: VNext P1 P2 * * *
  70354. **
  70355. ** Advance virtual table P1 to the next row in its result set and
  70356. ** jump to instruction P2. Or, if the virtual table has reached
  70357. ** the end of its result set, then fall through to the next instruction.
  70358. */
  70359. case OP_VNext: { /* jump */
  70360. #if 0 /* local variables moved into u.cp */
  70361. sqlite3_vtab *pVtab;
  70362. const sqlite3_module *pModule;
  70363. int res;
  70364. VdbeCursor *pCur;
  70365. #endif /* local variables moved into u.cp */
  70366. u.cp.res = 0;
  70367. u.cp.pCur = p->apCsr[pOp->p1];
  70368. assert( u.cp.pCur->pVtabCursor );
  70369. if( u.cp.pCur->nullRow ){
  70370. break;
  70371. }
  70372. u.cp.pVtab = u.cp.pCur->pVtabCursor->pVtab;
  70373. u.cp.pModule = u.cp.pVtab->pModule;
  70374. assert( u.cp.pModule->xNext );
  70375. /* Invoke the xNext() method of the module. There is no way for the
  70376. ** underlying implementation to return an error if one occurs during
  70377. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  70378. ** data is available) and the error code returned when xColumn or
  70379. ** some other method is next invoked on the save virtual table cursor.
  70380. */
  70381. p->inVtabMethod = 1;
  70382. rc = u.cp.pModule->xNext(u.cp.pCur->pVtabCursor);
  70383. p->inVtabMethod = 0;
  70384. sqlite3VtabImportErrmsg(p, u.cp.pVtab);
  70385. if( rc==SQLITE_OK ){
  70386. u.cp.res = u.cp.pModule->xEof(u.cp.pCur->pVtabCursor);
  70387. }
  70388. if( !u.cp.res ){
  70389. /* If there is data, jump to P2 */
  70390. pc = pOp->p2 - 1;
  70391. }
  70392. goto check_for_interrupt;
  70393. }
  70394. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70395. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70396. /* Opcode: VRename P1 * * P4 *
  70397. **
  70398. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70399. ** This opcode invokes the corresponding xRename method. The value
  70400. ** in register P1 is passed as the zName argument to the xRename method.
  70401. */
  70402. case OP_VRename: {
  70403. #if 0 /* local variables moved into u.cq */
  70404. sqlite3_vtab *pVtab;
  70405. Mem *pName;
  70406. #endif /* local variables moved into u.cq */
  70407. u.cq.pVtab = pOp->p4.pVtab->pVtab;
  70408. u.cq.pName = &aMem[pOp->p1];
  70409. assert( u.cq.pVtab->pModule->xRename );
  70410. assert( memIsValid(u.cq.pName) );
  70411. assert( p->readOnly==0 );
  70412. REGISTER_TRACE(pOp->p1, u.cq.pName);
  70413. assert( u.cq.pName->flags & MEM_Str );
  70414. testcase( u.cq.pName->enc==SQLITE_UTF8 );
  70415. testcase( u.cq.pName->enc==SQLITE_UTF16BE );
  70416. testcase( u.cq.pName->enc==SQLITE_UTF16LE );
  70417. rc = sqlite3VdbeChangeEncoding(u.cq.pName, SQLITE_UTF8);
  70418. if( rc==SQLITE_OK ){
  70419. rc = u.cq.pVtab->pModule->xRename(u.cq.pVtab, u.cq.pName->z);
  70420. sqlite3VtabImportErrmsg(p, u.cq.pVtab);
  70421. p->expired = 0;
  70422. }
  70423. break;
  70424. }
  70425. #endif
  70426. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70427. /* Opcode: VUpdate P1 P2 P3 P4 *
  70428. **
  70429. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70430. ** This opcode invokes the corresponding xUpdate method. P2 values
  70431. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  70432. ** invocation. The value in register (P3+P2-1) corresponds to the
  70433. ** p2th element of the argv array passed to xUpdate.
  70434. **
  70435. ** The xUpdate method will do a DELETE or an INSERT or both.
  70436. ** The argv[0] element (which corresponds to memory cell P3)
  70437. ** is the rowid of a row to delete. If argv[0] is NULL then no
  70438. ** deletion occurs. The argv[1] element is the rowid of the new
  70439. ** row. This can be NULL to have the virtual table select the new
  70440. ** rowid for itself. The subsequent elements in the array are
  70441. ** the values of columns in the new row.
  70442. **
  70443. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  70444. ** a row to delete.
  70445. **
  70446. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  70447. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  70448. ** is set to the value of the rowid for the row just inserted.
  70449. */
  70450. case OP_VUpdate: {
  70451. #if 0 /* local variables moved into u.cr */
  70452. sqlite3_vtab *pVtab;
  70453. sqlite3_module *pModule;
  70454. int nArg;
  70455. int i;
  70456. sqlite_int64 rowid;
  70457. Mem **apArg;
  70458. Mem *pX;
  70459. #endif /* local variables moved into u.cr */
  70460. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  70461. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  70462. );
  70463. assert( p->readOnly==0 );
  70464. u.cr.pVtab = pOp->p4.pVtab->pVtab;
  70465. u.cr.pModule = (sqlite3_module *)u.cr.pVtab->pModule;
  70466. u.cr.nArg = pOp->p2;
  70467. assert( pOp->p4type==P4_VTAB );
  70468. if( ALWAYS(u.cr.pModule->xUpdate) ){
  70469. u8 vtabOnConflict = db->vtabOnConflict;
  70470. u.cr.apArg = p->apArg;
  70471. u.cr.pX = &aMem[pOp->p3];
  70472. for(u.cr.i=0; u.cr.i<u.cr.nArg; u.cr.i++){
  70473. assert( memIsValid(u.cr.pX) );
  70474. memAboutToChange(p, u.cr.pX);
  70475. sqlite3VdbeMemStoreType(u.cr.pX);
  70476. u.cr.apArg[u.cr.i] = u.cr.pX;
  70477. u.cr.pX++;
  70478. }
  70479. db->vtabOnConflict = pOp->p5;
  70480. rc = u.cr.pModule->xUpdate(u.cr.pVtab, u.cr.nArg, u.cr.apArg, &u.cr.rowid);
  70481. db->vtabOnConflict = vtabOnConflict;
  70482. sqlite3VtabImportErrmsg(p, u.cr.pVtab);
  70483. if( rc==SQLITE_OK && pOp->p1 ){
  70484. assert( u.cr.nArg>1 && u.cr.apArg[0] && (u.cr.apArg[0]->flags&MEM_Null) );
  70485. db->lastRowid = lastRowid = u.cr.rowid;
  70486. }
  70487. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  70488. if( pOp->p5==OE_Ignore ){
  70489. rc = SQLITE_OK;
  70490. }else{
  70491. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  70492. }
  70493. }else{
  70494. p->nChange++;
  70495. }
  70496. }
  70497. break;
  70498. }
  70499. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70500. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70501. /* Opcode: Pagecount P1 P2 * * *
  70502. **
  70503. ** Write the current number of pages in database P1 to memory cell P2.
  70504. */
  70505. case OP_Pagecount: { /* out2-prerelease */
  70506. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  70507. break;
  70508. }
  70509. #endif
  70510. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70511. /* Opcode: MaxPgcnt P1 P2 P3 * *
  70512. **
  70513. ** Try to set the maximum page count for database P1 to the value in P3.
  70514. ** Do not let the maximum page count fall below the current page count and
  70515. ** do not change the maximum page count value if P3==0.
  70516. **
  70517. ** Store the maximum page count after the change in register P2.
  70518. */
  70519. case OP_MaxPgcnt: { /* out2-prerelease */
  70520. unsigned int newMax;
  70521. Btree *pBt;
  70522. pBt = db->aDb[pOp->p1].pBt;
  70523. newMax = 0;
  70524. if( pOp->p3 ){
  70525. newMax = sqlite3BtreeLastPage(pBt);
  70526. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  70527. }
  70528. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  70529. break;
  70530. }
  70531. #endif
  70532. #ifndef SQLITE_OMIT_TRACE
  70533. /* Opcode: Trace * * * P4 *
  70534. **
  70535. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  70536. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  70537. */
  70538. case OP_Trace: {
  70539. #if 0 /* local variables moved into u.cs */
  70540. char *zTrace;
  70541. char *z;
  70542. #endif /* local variables moved into u.cs */
  70543. if( db->xTrace
  70544. && !p->doingRerun
  70545. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70546. ){
  70547. u.cs.z = sqlite3VdbeExpandSql(p, u.cs.zTrace);
  70548. db->xTrace(db->pTraceArg, u.cs.z);
  70549. sqlite3DbFree(db, u.cs.z);
  70550. }
  70551. #ifdef SQLITE_DEBUG
  70552. if( (db->flags & SQLITE_SqlTrace)!=0
  70553. && (u.cs.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70554. ){
  70555. sqlite3DebugPrintf("SQL-trace: %s\n", u.cs.zTrace);
  70556. }
  70557. #endif /* SQLITE_DEBUG */
  70558. break;
  70559. }
  70560. #endif
  70561. /* Opcode: Noop * * * * *
  70562. **
  70563. ** Do nothing. This instruction is often useful as a jump
  70564. ** destination.
  70565. */
  70566. /*
  70567. ** The magic Explain opcode are only inserted when explain==2 (which
  70568. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  70569. ** This opcode records information from the optimizer. It is the
  70570. ** the same as a no-op. This opcodesnever appears in a real VM program.
  70571. */
  70572. default: { /* This is really OP_Noop and OP_Explain */
  70573. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  70574. break;
  70575. }
  70576. /*****************************************************************************
  70577. ** The cases of the switch statement above this line should all be indented
  70578. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  70579. ** readability. From this point on down, the normal indentation rules are
  70580. ** restored.
  70581. *****************************************************************************/
  70582. }
  70583. #ifdef VDBE_PROFILE
  70584. {
  70585. u64 elapsed = sqlite3Hwtime() - start;
  70586. pOp->cycles += elapsed;
  70587. pOp->cnt++;
  70588. #if 0
  70589. fprintf(stdout, "%10llu ", elapsed);
  70590. sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
  70591. #endif
  70592. }
  70593. #endif
  70594. /* The following code adds nothing to the actual functionality
  70595. ** of the program. It is only here for testing and debugging.
  70596. ** On the other hand, it does burn CPU cycles every time through
  70597. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  70598. */
  70599. #ifndef NDEBUG
  70600. assert( pc>=-1 && pc<p->nOp );
  70601. #ifdef SQLITE_DEBUG
  70602. if( p->trace ){
  70603. if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
  70604. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  70605. registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
  70606. }
  70607. if( pOp->opflags & OPFLG_OUT3 ){
  70608. registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
  70609. }
  70610. }
  70611. #endif /* SQLITE_DEBUG */
  70612. #endif /* NDEBUG */
  70613. } /* The end of the for(;;) loop the loops through opcodes */
  70614. /* If we reach this point, it means that execution is finished with
  70615. ** an error of some kind.
  70616. */
  70617. vdbe_error_halt:
  70618. assert( rc );
  70619. p->rc = rc;
  70620. testcase( sqlite3GlobalConfig.xLog!=0 );
  70621. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  70622. pc, p->zSql, p->zErrMsg);
  70623. sqlite3VdbeHalt(p);
  70624. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  70625. rc = SQLITE_ERROR;
  70626. if( resetSchemaOnFault>0 ){
  70627. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  70628. }
  70629. /* This is the only way out of this procedure. We have to
  70630. ** release the mutexes on btrees that were acquired at the
  70631. ** top. */
  70632. vdbe_return:
  70633. db->lastRowid = lastRowid;
  70634. testcase( nVmStep>0 );
  70635. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  70636. sqlite3VdbeLeave(p);
  70637. return rc;
  70638. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  70639. ** is encountered.
  70640. */
  70641. too_big:
  70642. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  70643. rc = SQLITE_TOOBIG;
  70644. goto vdbe_error_halt;
  70645. /* Jump to here if a malloc() fails.
  70646. */
  70647. no_mem:
  70648. db->mallocFailed = 1;
  70649. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  70650. rc = SQLITE_NOMEM;
  70651. goto vdbe_error_halt;
  70652. /* Jump to here for any other kind of fatal error. The "rc" variable
  70653. ** should hold the error number.
  70654. */
  70655. abort_due_to_error:
  70656. assert( p->zErrMsg==0 );
  70657. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  70658. if( rc!=SQLITE_IOERR_NOMEM ){
  70659. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70660. }
  70661. goto vdbe_error_halt;
  70662. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  70663. ** flag.
  70664. */
  70665. abort_due_to_interrupt:
  70666. assert( db->u1.isInterrupted );
  70667. rc = SQLITE_INTERRUPT;
  70668. p->rc = rc;
  70669. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70670. goto vdbe_error_halt;
  70671. }
  70672. /************** End of vdbe.c ************************************************/
  70673. /************** Begin file vdbeblob.c ****************************************/
  70674. /*
  70675. ** 2007 May 1
  70676. **
  70677. ** The author disclaims copyright to this source code. In place of
  70678. ** a legal notice, here is a blessing:
  70679. **
  70680. ** May you do good and not evil.
  70681. ** May you find forgiveness for yourself and forgive others.
  70682. ** May you share freely, never taking more than you give.
  70683. **
  70684. *************************************************************************
  70685. **
  70686. ** This file contains code used to implement incremental BLOB I/O.
  70687. */
  70688. #ifndef SQLITE_OMIT_INCRBLOB
  70689. /*
  70690. ** Valid sqlite3_blob* handles point to Incrblob structures.
  70691. */
  70692. typedef struct Incrblob Incrblob;
  70693. struct Incrblob {
  70694. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  70695. int nByte; /* Size of open blob, in bytes */
  70696. int iOffset; /* Byte offset of blob in cursor data */
  70697. int iCol; /* Table column this handle is open on */
  70698. BtCursor *pCsr; /* Cursor pointing at blob row */
  70699. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  70700. sqlite3 *db; /* The associated database */
  70701. };
  70702. /*
  70703. ** This function is used by both blob_open() and blob_reopen(). It seeks
  70704. ** the b-tree cursor associated with blob handle p to point to row iRow.
  70705. ** If successful, SQLITE_OK is returned and subsequent calls to
  70706. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  70707. **
  70708. ** If an error occurs, or if the specified row does not exist or does not
  70709. ** contain a value of type TEXT or BLOB in the column nominated when the
  70710. ** blob handle was opened, then an error code is returned and *pzErr may
  70711. ** be set to point to a buffer containing an error message. It is the
  70712. ** responsibility of the caller to free the error message buffer using
  70713. ** sqlite3DbFree().
  70714. **
  70715. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  70716. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  70717. ** immediately return SQLITE_ABORT.
  70718. */
  70719. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  70720. int rc; /* Error code */
  70721. char *zErr = 0; /* Error message */
  70722. Vdbe *v = (Vdbe *)p->pStmt;
  70723. /* Set the value of the SQL statements only variable to integer iRow.
  70724. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  70725. ** triggering asserts related to mutexes.
  70726. */
  70727. assert( v->aVar[0].flags&MEM_Int );
  70728. v->aVar[0].u.i = iRow;
  70729. rc = sqlite3_step(p->pStmt);
  70730. if( rc==SQLITE_ROW ){
  70731. u32 type = v->apCsr[0]->aType[p->iCol];
  70732. if( type<12 ){
  70733. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  70734. type==0?"null": type==7?"real": "integer"
  70735. );
  70736. rc = SQLITE_ERROR;
  70737. sqlite3_finalize(p->pStmt);
  70738. p->pStmt = 0;
  70739. }else{
  70740. p->iOffset = v->apCsr[0]->aOffset[p->iCol];
  70741. p->nByte = sqlite3VdbeSerialTypeLen(type);
  70742. p->pCsr = v->apCsr[0]->pCursor;
  70743. sqlite3BtreeEnterCursor(p->pCsr);
  70744. sqlite3BtreeCacheOverflow(p->pCsr);
  70745. sqlite3BtreeLeaveCursor(p->pCsr);
  70746. }
  70747. }
  70748. if( rc==SQLITE_ROW ){
  70749. rc = SQLITE_OK;
  70750. }else if( p->pStmt ){
  70751. rc = sqlite3_finalize(p->pStmt);
  70752. p->pStmt = 0;
  70753. if( rc==SQLITE_OK ){
  70754. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  70755. rc = SQLITE_ERROR;
  70756. }else{
  70757. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  70758. }
  70759. }
  70760. assert( rc!=SQLITE_OK || zErr==0 );
  70761. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  70762. *pzErr = zErr;
  70763. return rc;
  70764. }
  70765. /*
  70766. ** Open a blob handle.
  70767. */
  70768. SQLITE_API int sqlite3_blob_open(
  70769. sqlite3* db, /* The database connection */
  70770. const char *zDb, /* The attached database containing the blob */
  70771. const char *zTable, /* The table containing the blob */
  70772. const char *zColumn, /* The column containing the blob */
  70773. sqlite_int64 iRow, /* The row containing the glob */
  70774. int flags, /* True -> read/write access, false -> read-only */
  70775. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  70776. ){
  70777. int nAttempt = 0;
  70778. int iCol; /* Index of zColumn in row-record */
  70779. /* This VDBE program seeks a btree cursor to the identified
  70780. ** db/table/row entry. The reason for using a vdbe program instead
  70781. ** of writing code to use the b-tree layer directly is that the
  70782. ** vdbe program will take advantage of the various transaction,
  70783. ** locking and error handling infrastructure built into the vdbe.
  70784. **
  70785. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  70786. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  70787. ** uses it to implement the blob_read(), blob_write() and
  70788. ** blob_bytes() functions.
  70789. **
  70790. ** The sqlite3_blob_close() function finalizes the vdbe program,
  70791. ** which closes the b-tree cursor and (possibly) commits the
  70792. ** transaction.
  70793. */
  70794. static const VdbeOpList openBlob[] = {
  70795. {OP_Transaction, 0, 0, 0}, /* 0: Start a transaction */
  70796. {OP_VerifyCookie, 0, 0, 0}, /* 1: Check the schema cookie */
  70797. {OP_TableLock, 0, 0, 0}, /* 2: Acquire a read or write lock */
  70798. /* One of the following two instructions is replaced by an OP_Noop. */
  70799. {OP_OpenRead, 0, 0, 0}, /* 3: Open cursor 0 for reading */
  70800. {OP_OpenWrite, 0, 0, 0}, /* 4: Open cursor 0 for read/write */
  70801. {OP_Variable, 1, 1, 1}, /* 5: Push the rowid to the stack */
  70802. {OP_NotExists, 0, 10, 1}, /* 6: Seek the cursor */
  70803. {OP_Column, 0, 0, 1}, /* 7 */
  70804. {OP_ResultRow, 1, 0, 0}, /* 8 */
  70805. {OP_Goto, 0, 5, 0}, /* 9 */
  70806. {OP_Close, 0, 0, 0}, /* 10 */
  70807. {OP_Halt, 0, 0, 0}, /* 11 */
  70808. };
  70809. int rc = SQLITE_OK;
  70810. char *zErr = 0;
  70811. Table *pTab;
  70812. Parse *pParse = 0;
  70813. Incrblob *pBlob = 0;
  70814. flags = !!flags; /* flags = (flags ? 1 : 0); */
  70815. *ppBlob = 0;
  70816. sqlite3_mutex_enter(db->mutex);
  70817. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  70818. if( !pBlob ) goto blob_open_out;
  70819. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  70820. if( !pParse ) goto blob_open_out;
  70821. do {
  70822. memset(pParse, 0, sizeof(Parse));
  70823. pParse->db = db;
  70824. sqlite3DbFree(db, zErr);
  70825. zErr = 0;
  70826. sqlite3BtreeEnterAll(db);
  70827. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  70828. if( pTab && IsVirtual(pTab) ){
  70829. pTab = 0;
  70830. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  70831. }
  70832. #ifndef SQLITE_OMIT_VIEW
  70833. if( pTab && pTab->pSelect ){
  70834. pTab = 0;
  70835. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  70836. }
  70837. #endif
  70838. if( !pTab ){
  70839. if( pParse->zErrMsg ){
  70840. sqlite3DbFree(db, zErr);
  70841. zErr = pParse->zErrMsg;
  70842. pParse->zErrMsg = 0;
  70843. }
  70844. rc = SQLITE_ERROR;
  70845. sqlite3BtreeLeaveAll(db);
  70846. goto blob_open_out;
  70847. }
  70848. /* Now search pTab for the exact column. */
  70849. for(iCol=0; iCol<pTab->nCol; iCol++) {
  70850. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  70851. break;
  70852. }
  70853. }
  70854. if( iCol==pTab->nCol ){
  70855. sqlite3DbFree(db, zErr);
  70856. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  70857. rc = SQLITE_ERROR;
  70858. sqlite3BtreeLeaveAll(db);
  70859. goto blob_open_out;
  70860. }
  70861. /* If the value is being opened for writing, check that the
  70862. ** column is not indexed, and that it is not part of a foreign key.
  70863. ** It is against the rules to open a column to which either of these
  70864. ** descriptions applies for writing. */
  70865. if( flags ){
  70866. const char *zFault = 0;
  70867. Index *pIdx;
  70868. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70869. if( db->flags&SQLITE_ForeignKeys ){
  70870. /* Check that the column is not part of an FK child key definition. It
  70871. ** is not necessary to check if it is part of a parent key, as parent
  70872. ** key columns must be indexed. The check below will pick up this
  70873. ** case. */
  70874. FKey *pFKey;
  70875. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  70876. int j;
  70877. for(j=0; j<pFKey->nCol; j++){
  70878. if( pFKey->aCol[j].iFrom==iCol ){
  70879. zFault = "foreign key";
  70880. }
  70881. }
  70882. }
  70883. }
  70884. #endif
  70885. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70886. int j;
  70887. for(j=0; j<pIdx->nColumn; j++){
  70888. if( pIdx->aiColumn[j]==iCol ){
  70889. zFault = "indexed";
  70890. }
  70891. }
  70892. }
  70893. if( zFault ){
  70894. sqlite3DbFree(db, zErr);
  70895. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  70896. rc = SQLITE_ERROR;
  70897. sqlite3BtreeLeaveAll(db);
  70898. goto blob_open_out;
  70899. }
  70900. }
  70901. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(db);
  70902. assert( pBlob->pStmt || db->mallocFailed );
  70903. if( pBlob->pStmt ){
  70904. Vdbe *v = (Vdbe *)pBlob->pStmt;
  70905. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70906. sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
  70907. /* Configure the OP_Transaction */
  70908. sqlite3VdbeChangeP1(v, 0, iDb);
  70909. sqlite3VdbeChangeP2(v, 0, flags);
  70910. /* Configure the OP_VerifyCookie */
  70911. sqlite3VdbeChangeP1(v, 1, iDb);
  70912. sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
  70913. sqlite3VdbeChangeP3(v, 1, pTab->pSchema->iGeneration);
  70914. /* Make sure a mutex is held on the table to be accessed */
  70915. sqlite3VdbeUsesBtree(v, iDb);
  70916. /* Configure the OP_TableLock instruction */
  70917. #ifdef SQLITE_OMIT_SHARED_CACHE
  70918. sqlite3VdbeChangeToNoop(v, 2);
  70919. #else
  70920. sqlite3VdbeChangeP1(v, 2, iDb);
  70921. sqlite3VdbeChangeP2(v, 2, pTab->tnum);
  70922. sqlite3VdbeChangeP3(v, 2, flags);
  70923. sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
  70924. #endif
  70925. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  70926. ** parameter of the other to pTab->tnum. */
  70927. sqlite3VdbeChangeToNoop(v, 4 - flags);
  70928. sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
  70929. sqlite3VdbeChangeP3(v, 3 + flags, iDb);
  70930. /* Configure the number of columns. Configure the cursor to
  70931. ** think that the table has one more column than it really
  70932. ** does. An OP_Column to retrieve this imaginary column will
  70933. ** always return an SQL NULL. This is useful because it means
  70934. ** we can invoke OP_Column to fill in the vdbe cursors type
  70935. ** and offset cache without causing any IO.
  70936. */
  70937. sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  70938. sqlite3VdbeChangeP2(v, 7, pTab->nCol);
  70939. if( !db->mallocFailed ){
  70940. pParse->nVar = 1;
  70941. pParse->nMem = 1;
  70942. pParse->nTab = 1;
  70943. sqlite3VdbeMakeReady(v, pParse);
  70944. }
  70945. }
  70946. pBlob->flags = flags;
  70947. pBlob->iCol = iCol;
  70948. pBlob->db = db;
  70949. sqlite3BtreeLeaveAll(db);
  70950. if( db->mallocFailed ){
  70951. goto blob_open_out;
  70952. }
  70953. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  70954. rc = blobSeekToRow(pBlob, iRow, &zErr);
  70955. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  70956. blob_open_out:
  70957. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  70958. *ppBlob = (sqlite3_blob *)pBlob;
  70959. }else{
  70960. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  70961. sqlite3DbFree(db, pBlob);
  70962. }
  70963. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  70964. sqlite3DbFree(db, zErr);
  70965. sqlite3StackFree(db, pParse);
  70966. rc = sqlite3ApiExit(db, rc);
  70967. sqlite3_mutex_leave(db->mutex);
  70968. return rc;
  70969. }
  70970. /*
  70971. ** Close a blob handle that was previously created using
  70972. ** sqlite3_blob_open().
  70973. */
  70974. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  70975. Incrblob *p = (Incrblob *)pBlob;
  70976. int rc;
  70977. sqlite3 *db;
  70978. if( p ){
  70979. db = p->db;
  70980. sqlite3_mutex_enter(db->mutex);
  70981. rc = sqlite3_finalize(p->pStmt);
  70982. sqlite3DbFree(db, p);
  70983. sqlite3_mutex_leave(db->mutex);
  70984. }else{
  70985. rc = SQLITE_OK;
  70986. }
  70987. return rc;
  70988. }
  70989. /*
  70990. ** Perform a read or write operation on a blob
  70991. */
  70992. static int blobReadWrite(
  70993. sqlite3_blob *pBlob,
  70994. void *z,
  70995. int n,
  70996. int iOffset,
  70997. int (*xCall)(BtCursor*, u32, u32, void*)
  70998. ){
  70999. int rc;
  71000. Incrblob *p = (Incrblob *)pBlob;
  71001. Vdbe *v;
  71002. sqlite3 *db;
  71003. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71004. db = p->db;
  71005. sqlite3_mutex_enter(db->mutex);
  71006. v = (Vdbe*)p->pStmt;
  71007. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  71008. /* Request is out of range. Return a transient error. */
  71009. rc = SQLITE_ERROR;
  71010. sqlite3Error(db, SQLITE_ERROR, 0);
  71011. }else if( v==0 ){
  71012. /* If there is no statement handle, then the blob-handle has
  71013. ** already been invalidated. Return SQLITE_ABORT in this case.
  71014. */
  71015. rc = SQLITE_ABORT;
  71016. }else{
  71017. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  71018. ** returned, clean-up the statement handle.
  71019. */
  71020. assert( db == v->db );
  71021. sqlite3BtreeEnterCursor(p->pCsr);
  71022. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  71023. sqlite3BtreeLeaveCursor(p->pCsr);
  71024. if( rc==SQLITE_ABORT ){
  71025. sqlite3VdbeFinalize(v);
  71026. p->pStmt = 0;
  71027. }else{
  71028. db->errCode = rc;
  71029. v->rc = rc;
  71030. }
  71031. }
  71032. rc = sqlite3ApiExit(db, rc);
  71033. sqlite3_mutex_leave(db->mutex);
  71034. return rc;
  71035. }
  71036. /*
  71037. ** Read data from a blob handle.
  71038. */
  71039. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  71040. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  71041. }
  71042. /*
  71043. ** Write data to a blob handle.
  71044. */
  71045. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  71046. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  71047. }
  71048. /*
  71049. ** Query a blob handle for the size of the data.
  71050. **
  71051. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  71052. ** so no mutex is required for access.
  71053. */
  71054. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  71055. Incrblob *p = (Incrblob *)pBlob;
  71056. return (p && p->pStmt) ? p->nByte : 0;
  71057. }
  71058. /*
  71059. ** Move an existing blob handle to point to a different row of the same
  71060. ** database table.
  71061. **
  71062. ** If an error occurs, or if the specified row does not exist or does not
  71063. ** contain a blob or text value, then an error code is returned and the
  71064. ** database handle error code and message set. If this happens, then all
  71065. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  71066. ** immediately return SQLITE_ABORT.
  71067. */
  71068. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  71069. int rc;
  71070. Incrblob *p = (Incrblob *)pBlob;
  71071. sqlite3 *db;
  71072. if( p==0 ) return SQLITE_MISUSE_BKPT;
  71073. db = p->db;
  71074. sqlite3_mutex_enter(db->mutex);
  71075. if( p->pStmt==0 ){
  71076. /* If there is no statement handle, then the blob-handle has
  71077. ** already been invalidated. Return SQLITE_ABORT in this case.
  71078. */
  71079. rc = SQLITE_ABORT;
  71080. }else{
  71081. char *zErr;
  71082. rc = blobSeekToRow(p, iRow, &zErr);
  71083. if( rc!=SQLITE_OK ){
  71084. sqlite3Error(db, rc, (zErr ? "%s" : 0), zErr);
  71085. sqlite3DbFree(db, zErr);
  71086. }
  71087. assert( rc!=SQLITE_SCHEMA );
  71088. }
  71089. rc = sqlite3ApiExit(db, rc);
  71090. assert( rc==SQLITE_OK || p->pStmt==0 );
  71091. sqlite3_mutex_leave(db->mutex);
  71092. return rc;
  71093. }
  71094. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  71095. /************** End of vdbeblob.c ********************************************/
  71096. /************** Begin file vdbesort.c ****************************************/
  71097. /*
  71098. ** 2011 July 9
  71099. **
  71100. ** The author disclaims copyright to this source code. In place of
  71101. ** a legal notice, here is a blessing:
  71102. **
  71103. ** May you do good and not evil.
  71104. ** May you find forgiveness for yourself and forgive others.
  71105. ** May you share freely, never taking more than you give.
  71106. **
  71107. *************************************************************************
  71108. ** This file contains code for the VdbeSorter object, used in concert with
  71109. ** a VdbeCursor to sort large numbers of keys (as may be required, for
  71110. ** example, by CREATE INDEX statements on tables too large to fit in main
  71111. ** memory).
  71112. */
  71113. typedef struct VdbeSorterIter VdbeSorterIter;
  71114. typedef struct SorterRecord SorterRecord;
  71115. typedef struct FileWriter FileWriter;
  71116. /*
  71117. ** NOTES ON DATA STRUCTURE USED FOR N-WAY MERGES:
  71118. **
  71119. ** As keys are added to the sorter, they are written to disk in a series
  71120. ** of sorted packed-memory-arrays (PMAs). The size of each PMA is roughly
  71121. ** the same as the cache-size allowed for temporary databases. In order
  71122. ** to allow the caller to extract keys from the sorter in sorted order,
  71123. ** all PMAs currently stored on disk must be merged together. This comment
  71124. ** describes the data structure used to do so. The structure supports
  71125. ** merging any number of arrays in a single pass with no redundant comparison
  71126. ** operations.
  71127. **
  71128. ** The aIter[] array contains an iterator for each of the PMAs being merged.
  71129. ** An aIter[] iterator either points to a valid key or else is at EOF. For
  71130. ** the purposes of the paragraphs below, we assume that the array is actually
  71131. ** N elements in size, where N is the smallest power of 2 greater to or equal
  71132. ** to the number of iterators being merged. The extra aIter[] elements are
  71133. ** treated as if they are empty (always at EOF).
  71134. **
  71135. ** The aTree[] array is also N elements in size. The value of N is stored in
  71136. ** the VdbeSorter.nTree variable.
  71137. **
  71138. ** The final (N/2) elements of aTree[] contain the results of comparing
  71139. ** pairs of iterator keys together. Element i contains the result of
  71140. ** comparing aIter[2*i-N] and aIter[2*i-N+1]. Whichever key is smaller, the
  71141. ** aTree element is set to the index of it.
  71142. **
  71143. ** For the purposes of this comparison, EOF is considered greater than any
  71144. ** other key value. If the keys are equal (only possible with two EOF
  71145. ** values), it doesn't matter which index is stored.
  71146. **
  71147. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  71148. ** above contains the index of the smallest of each block of 4 iterators.
  71149. ** And so on. So that aTree[1] contains the index of the iterator that
  71150. ** currently points to the smallest key value. aTree[0] is unused.
  71151. **
  71152. ** Example:
  71153. **
  71154. ** aIter[0] -> Banana
  71155. ** aIter[1] -> Feijoa
  71156. ** aIter[2] -> Elderberry
  71157. ** aIter[3] -> Currant
  71158. ** aIter[4] -> Grapefruit
  71159. ** aIter[5] -> Apple
  71160. ** aIter[6] -> Durian
  71161. ** aIter[7] -> EOF
  71162. **
  71163. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  71164. **
  71165. ** The current element is "Apple" (the value of the key indicated by
  71166. ** iterator 5). When the Next() operation is invoked, iterator 5 will
  71167. ** be advanced to the next key in its segment. Say the next key is
  71168. ** "Eggplant":
  71169. **
  71170. ** aIter[5] -> Eggplant
  71171. **
  71172. ** The contents of aTree[] are updated first by comparing the new iterator
  71173. ** 5 key to the current key of iterator 4 (still "Grapefruit"). The iterator
  71174. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  71175. ** The value of iterator 6 - "Durian" - is now smaller than that of iterator
  71176. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  71177. ** so the value written into element 1 of the array is 0. As follows:
  71178. **
  71179. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  71180. **
  71181. ** In other words, each time we advance to the next sorter element, log2(N)
  71182. ** key comparison operations are required, where N is the number of segments
  71183. ** being merged (rounded up to the next power of 2).
  71184. */
  71185. struct VdbeSorter {
  71186. i64 iWriteOff; /* Current write offset within file pTemp1 */
  71187. i64 iReadOff; /* Current read offset within file pTemp1 */
  71188. int nInMemory; /* Current size of pRecord list as PMA */
  71189. int nTree; /* Used size of aTree/aIter (power of 2) */
  71190. int nPMA; /* Number of PMAs stored in pTemp1 */
  71191. int mnPmaSize; /* Minimum PMA size, in bytes */
  71192. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  71193. VdbeSorterIter *aIter; /* Array of iterators to merge */
  71194. int *aTree; /* Current state of incremental merge */
  71195. sqlite3_file *pTemp1; /* PMA file 1 */
  71196. SorterRecord *pRecord; /* Head of in-memory record list */
  71197. UnpackedRecord *pUnpacked; /* Used to unpack keys */
  71198. };
  71199. /*
  71200. ** The following type is an iterator for a PMA. It caches the current key in
  71201. ** variables nKey/aKey. If the iterator is at EOF, pFile==0.
  71202. */
  71203. struct VdbeSorterIter {
  71204. i64 iReadOff; /* Current read offset */
  71205. i64 iEof; /* 1 byte past EOF for this iterator */
  71206. int nAlloc; /* Bytes of space at aAlloc */
  71207. int nKey; /* Number of bytes in key */
  71208. sqlite3_file *pFile; /* File iterator is reading from */
  71209. u8 *aAlloc; /* Allocated space */
  71210. u8 *aKey; /* Pointer to current key */
  71211. u8 *aBuffer; /* Current read buffer */
  71212. int nBuffer; /* Size of read buffer in bytes */
  71213. };
  71214. /*
  71215. ** An instance of this structure is used to organize the stream of records
  71216. ** being written to files by the merge-sort code into aligned, page-sized
  71217. ** blocks. Doing all I/O in aligned page-sized blocks helps I/O to go
  71218. ** faster on many operating systems.
  71219. */
  71220. struct FileWriter {
  71221. int eFWErr; /* Non-zero if in an error state */
  71222. u8 *aBuffer; /* Pointer to write buffer */
  71223. int nBuffer; /* Size of write buffer in bytes */
  71224. int iBufStart; /* First byte of buffer to write */
  71225. int iBufEnd; /* Last byte of buffer to write */
  71226. i64 iWriteOff; /* Offset of start of buffer in file */
  71227. sqlite3_file *pFile; /* File to write to */
  71228. };
  71229. /*
  71230. ** A structure to store a single record. All in-memory records are connected
  71231. ** together into a linked list headed at VdbeSorter.pRecord using the
  71232. ** SorterRecord.pNext pointer.
  71233. */
  71234. struct SorterRecord {
  71235. void *pVal;
  71236. int nVal;
  71237. SorterRecord *pNext;
  71238. };
  71239. /* Minimum allowable value for the VdbeSorter.nWorking variable */
  71240. #define SORTER_MIN_WORKING 10
  71241. /* Maximum number of segments to merge in a single pass. */
  71242. #define SORTER_MAX_MERGE_COUNT 16
  71243. /*
  71244. ** Free all memory belonging to the VdbeSorterIter object passed as the second
  71245. ** argument. All structure fields are set to zero before returning.
  71246. */
  71247. static void vdbeSorterIterZero(sqlite3 *db, VdbeSorterIter *pIter){
  71248. sqlite3DbFree(db, pIter->aAlloc);
  71249. sqlite3DbFree(db, pIter->aBuffer);
  71250. memset(pIter, 0, sizeof(VdbeSorterIter));
  71251. }
  71252. /*
  71253. ** Read nByte bytes of data from the stream of data iterated by object p.
  71254. ** If successful, set *ppOut to point to a buffer containing the data
  71255. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  71256. ** error code.
  71257. **
  71258. ** The buffer indicated by *ppOut may only be considered valid until the
  71259. ** next call to this function.
  71260. */
  71261. static int vdbeSorterIterRead(
  71262. sqlite3 *db, /* Database handle (for malloc) */
  71263. VdbeSorterIter *p, /* Iterator */
  71264. int nByte, /* Bytes of data to read */
  71265. u8 **ppOut /* OUT: Pointer to buffer containing data */
  71266. ){
  71267. int iBuf; /* Offset within buffer to read from */
  71268. int nAvail; /* Bytes of data available in buffer */
  71269. assert( p->aBuffer );
  71270. /* If there is no more data to be read from the buffer, read the next
  71271. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  71272. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  71273. iBuf = p->iReadOff % p->nBuffer;
  71274. if( iBuf==0 ){
  71275. int nRead; /* Bytes to read from disk */
  71276. int rc; /* sqlite3OsRead() return code */
  71277. /* Determine how many bytes of data to read. */
  71278. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  71279. nRead = p->nBuffer;
  71280. }else{
  71281. nRead = (int)(p->iEof - p->iReadOff);
  71282. }
  71283. assert( nRead>0 );
  71284. /* Read data from the file. Return early if an error occurs. */
  71285. rc = sqlite3OsRead(p->pFile, p->aBuffer, nRead, p->iReadOff);
  71286. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71287. if( rc!=SQLITE_OK ) return rc;
  71288. }
  71289. nAvail = p->nBuffer - iBuf;
  71290. if( nByte<=nAvail ){
  71291. /* The requested data is available in the in-memory buffer. In this
  71292. ** case there is no need to make a copy of the data, just return a
  71293. ** pointer into the buffer to the caller. */
  71294. *ppOut = &p->aBuffer[iBuf];
  71295. p->iReadOff += nByte;
  71296. }else{
  71297. /* The requested data is not all available in the in-memory buffer.
  71298. ** In this case, allocate space at p->aAlloc[] to copy the requested
  71299. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  71300. int nRem; /* Bytes remaining to copy */
  71301. /* Extend the p->aAlloc[] allocation if required. */
  71302. if( p->nAlloc<nByte ){
  71303. int nNew = p->nAlloc*2;
  71304. while( nByte>nNew ) nNew = nNew*2;
  71305. p->aAlloc = sqlite3DbReallocOrFree(db, p->aAlloc, nNew);
  71306. if( !p->aAlloc ) return SQLITE_NOMEM;
  71307. p->nAlloc = nNew;
  71308. }
  71309. /* Copy as much data as is available in the buffer into the start of
  71310. ** p->aAlloc[]. */
  71311. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  71312. p->iReadOff += nAvail;
  71313. nRem = nByte - nAvail;
  71314. /* The following loop copies up to p->nBuffer bytes per iteration into
  71315. ** the p->aAlloc[] buffer. */
  71316. while( nRem>0 ){
  71317. int rc; /* vdbeSorterIterRead() return code */
  71318. int nCopy; /* Number of bytes to copy */
  71319. u8 *aNext; /* Pointer to buffer to copy data from */
  71320. nCopy = nRem;
  71321. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  71322. rc = vdbeSorterIterRead(db, p, nCopy, &aNext);
  71323. if( rc!=SQLITE_OK ) return rc;
  71324. assert( aNext!=p->aAlloc );
  71325. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  71326. nRem -= nCopy;
  71327. }
  71328. *ppOut = p->aAlloc;
  71329. }
  71330. return SQLITE_OK;
  71331. }
  71332. /*
  71333. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  71334. ** the value read.
  71335. */
  71336. static int vdbeSorterIterVarint(sqlite3 *db, VdbeSorterIter *p, u64 *pnOut){
  71337. int iBuf;
  71338. iBuf = p->iReadOff % p->nBuffer;
  71339. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  71340. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  71341. }else{
  71342. u8 aVarint[16], *a;
  71343. int i = 0, rc;
  71344. do{
  71345. rc = vdbeSorterIterRead(db, p, 1, &a);
  71346. if( rc ) return rc;
  71347. aVarint[(i++)&0xf] = a[0];
  71348. }while( (a[0]&0x80)!=0 );
  71349. sqlite3GetVarint(aVarint, pnOut);
  71350. }
  71351. return SQLITE_OK;
  71352. }
  71353. /*
  71354. ** Advance iterator pIter to the next key in its PMA. Return SQLITE_OK if
  71355. ** no error occurs, or an SQLite error code if one does.
  71356. */
  71357. static int vdbeSorterIterNext(
  71358. sqlite3 *db, /* Database handle (for sqlite3DbMalloc() ) */
  71359. VdbeSorterIter *pIter /* Iterator to advance */
  71360. ){
  71361. int rc; /* Return Code */
  71362. u64 nRec = 0; /* Size of record in bytes */
  71363. if( pIter->iReadOff>=pIter->iEof ){
  71364. /* This is an EOF condition */
  71365. vdbeSorterIterZero(db, pIter);
  71366. return SQLITE_OK;
  71367. }
  71368. rc = vdbeSorterIterVarint(db, pIter, &nRec);
  71369. if( rc==SQLITE_OK ){
  71370. pIter->nKey = (int)nRec;
  71371. rc = vdbeSorterIterRead(db, pIter, (int)nRec, &pIter->aKey);
  71372. }
  71373. return rc;
  71374. }
  71375. /*
  71376. ** Initialize iterator pIter to scan through the PMA stored in file pFile
  71377. ** starting at offset iStart and ending at offset iEof-1. This function
  71378. ** leaves the iterator pointing to the first key in the PMA (or EOF if the
  71379. ** PMA is empty).
  71380. */
  71381. static int vdbeSorterIterInit(
  71382. sqlite3 *db, /* Database handle */
  71383. const VdbeSorter *pSorter, /* Sorter object */
  71384. i64 iStart, /* Start offset in pFile */
  71385. VdbeSorterIter *pIter, /* Iterator to populate */
  71386. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  71387. ){
  71388. int rc = SQLITE_OK;
  71389. int nBuf;
  71390. nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71391. assert( pSorter->iWriteOff>iStart );
  71392. assert( pIter->aAlloc==0 );
  71393. assert( pIter->aBuffer==0 );
  71394. pIter->pFile = pSorter->pTemp1;
  71395. pIter->iReadOff = iStart;
  71396. pIter->nAlloc = 128;
  71397. pIter->aAlloc = (u8 *)sqlite3DbMallocRaw(db, pIter->nAlloc);
  71398. pIter->nBuffer = nBuf;
  71399. pIter->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  71400. if( !pIter->aBuffer ){
  71401. rc = SQLITE_NOMEM;
  71402. }else{
  71403. int iBuf;
  71404. iBuf = iStart % nBuf;
  71405. if( iBuf ){
  71406. int nRead = nBuf - iBuf;
  71407. if( (iStart + nRead) > pSorter->iWriteOff ){
  71408. nRead = (int)(pSorter->iWriteOff - iStart);
  71409. }
  71410. rc = sqlite3OsRead(
  71411. pSorter->pTemp1, &pIter->aBuffer[iBuf], nRead, iStart
  71412. );
  71413. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71414. }
  71415. if( rc==SQLITE_OK ){
  71416. u64 nByte; /* Size of PMA in bytes */
  71417. pIter->iEof = pSorter->iWriteOff;
  71418. rc = vdbeSorterIterVarint(db, pIter, &nByte);
  71419. pIter->iEof = pIter->iReadOff + nByte;
  71420. *pnByte += nByte;
  71421. }
  71422. }
  71423. if( rc==SQLITE_OK ){
  71424. rc = vdbeSorterIterNext(db, pIter);
  71425. }
  71426. return rc;
  71427. }
  71428. /*
  71429. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  71430. ** size nKey2 bytes). Argument pKeyInfo supplies the collation functions
  71431. ** used by the comparison. If an error occurs, return an SQLite error code.
  71432. ** Otherwise, return SQLITE_OK and set *pRes to a negative, zero or positive
  71433. ** value, depending on whether key1 is smaller, equal to or larger than key2.
  71434. **
  71435. ** If the bOmitRowid argument is non-zero, assume both keys end in a rowid
  71436. ** field. For the purposes of the comparison, ignore it. Also, if bOmitRowid
  71437. ** is true and key1 contains even a single NULL value, it is considered to
  71438. ** be less than key2. Even if key2 also contains NULL values.
  71439. **
  71440. ** If pKey2 is passed a NULL pointer, then it is assumed that the pCsr->aSpace
  71441. ** has been allocated and contains an unpacked record that is used as key2.
  71442. */
  71443. static void vdbeSorterCompare(
  71444. const VdbeCursor *pCsr, /* Cursor object (for pKeyInfo) */
  71445. int bOmitRowid, /* Ignore rowid field at end of keys */
  71446. const void *pKey1, int nKey1, /* Left side of comparison */
  71447. const void *pKey2, int nKey2, /* Right side of comparison */
  71448. int *pRes /* OUT: Result of comparison */
  71449. ){
  71450. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  71451. VdbeSorter *pSorter = pCsr->pSorter;
  71452. UnpackedRecord *r2 = pSorter->pUnpacked;
  71453. int i;
  71454. if( pKey2 ){
  71455. sqlite3VdbeRecordUnpack(pKeyInfo, nKey2, pKey2, r2);
  71456. }
  71457. if( bOmitRowid ){
  71458. r2->nField = pKeyInfo->nField;
  71459. assert( r2->nField>0 );
  71460. for(i=0; i<r2->nField; i++){
  71461. if( r2->aMem[i].flags & MEM_Null ){
  71462. *pRes = -1;
  71463. return;
  71464. }
  71465. }
  71466. r2->flags |= UNPACKED_PREFIX_MATCH;
  71467. }
  71468. *pRes = sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  71469. }
  71470. /*
  71471. ** This function is called to compare two iterator keys when merging
  71472. ** multiple b-tree segments. Parameter iOut is the index of the aTree[]
  71473. ** value to recalculate.
  71474. */
  71475. static int vdbeSorterDoCompare(const VdbeCursor *pCsr, int iOut){
  71476. VdbeSorter *pSorter = pCsr->pSorter;
  71477. int i1;
  71478. int i2;
  71479. int iRes;
  71480. VdbeSorterIter *p1;
  71481. VdbeSorterIter *p2;
  71482. assert( iOut<pSorter->nTree && iOut>0 );
  71483. if( iOut>=(pSorter->nTree/2) ){
  71484. i1 = (iOut - pSorter->nTree/2) * 2;
  71485. i2 = i1 + 1;
  71486. }else{
  71487. i1 = pSorter->aTree[iOut*2];
  71488. i2 = pSorter->aTree[iOut*2+1];
  71489. }
  71490. p1 = &pSorter->aIter[i1];
  71491. p2 = &pSorter->aIter[i2];
  71492. if( p1->pFile==0 ){
  71493. iRes = i2;
  71494. }else if( p2->pFile==0 ){
  71495. iRes = i1;
  71496. }else{
  71497. int res;
  71498. assert( pCsr->pSorter->pUnpacked!=0 ); /* allocated in vdbeSorterMerge() */
  71499. vdbeSorterCompare(
  71500. pCsr, 0, p1->aKey, p1->nKey, p2->aKey, p2->nKey, &res
  71501. );
  71502. if( res<=0 ){
  71503. iRes = i1;
  71504. }else{
  71505. iRes = i2;
  71506. }
  71507. }
  71508. pSorter->aTree[iOut] = iRes;
  71509. return SQLITE_OK;
  71510. }
  71511. /*
  71512. ** Initialize the temporary index cursor just opened as a sorter cursor.
  71513. */
  71514. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *db, VdbeCursor *pCsr){
  71515. int pgsz; /* Page size of main database */
  71516. int mxCache; /* Cache size */
  71517. VdbeSorter *pSorter; /* The new sorter */
  71518. char *d; /* Dummy */
  71519. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  71520. pCsr->pSorter = pSorter = sqlite3DbMallocZero(db, sizeof(VdbeSorter));
  71521. if( pSorter==0 ){
  71522. return SQLITE_NOMEM;
  71523. }
  71524. pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pCsr->pKeyInfo, 0, 0, &d);
  71525. if( pSorter->pUnpacked==0 ) return SQLITE_NOMEM;
  71526. assert( pSorter->pUnpacked==(UnpackedRecord *)d );
  71527. if( !sqlite3TempInMemory(db) ){
  71528. pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71529. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  71530. mxCache = db->aDb[0].pSchema->cache_size;
  71531. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  71532. pSorter->mxPmaSize = mxCache * pgsz;
  71533. }
  71534. return SQLITE_OK;
  71535. }
  71536. /*
  71537. ** Free the list of sorted records starting at pRecord.
  71538. */
  71539. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  71540. SorterRecord *p;
  71541. SorterRecord *pNext;
  71542. for(p=pRecord; p; p=pNext){
  71543. pNext = p->pNext;
  71544. sqlite3DbFree(db, p);
  71545. }
  71546. }
  71547. /*
  71548. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  71549. */
  71550. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  71551. VdbeSorter *pSorter = pCsr->pSorter;
  71552. if( pSorter ){
  71553. if( pSorter->aIter ){
  71554. int i;
  71555. for(i=0; i<pSorter->nTree; i++){
  71556. vdbeSorterIterZero(db, &pSorter->aIter[i]);
  71557. }
  71558. sqlite3DbFree(db, pSorter->aIter);
  71559. }
  71560. if( pSorter->pTemp1 ){
  71561. sqlite3OsCloseFree(pSorter->pTemp1);
  71562. }
  71563. vdbeSorterRecordFree(db, pSorter->pRecord);
  71564. sqlite3DbFree(db, pSorter->pUnpacked);
  71565. sqlite3DbFree(db, pSorter);
  71566. pCsr->pSorter = 0;
  71567. }
  71568. }
  71569. /*
  71570. ** Allocate space for a file-handle and open a temporary file. If successful,
  71571. ** set *ppFile to point to the malloc'd file-handle and return SQLITE_OK.
  71572. ** Otherwise, set *ppFile to 0 and return an SQLite error code.
  71573. */
  71574. static int vdbeSorterOpenTempFile(sqlite3 *db, sqlite3_file **ppFile){
  71575. int dummy;
  71576. return sqlite3OsOpenMalloc(db->pVfs, 0, ppFile,
  71577. SQLITE_OPEN_TEMP_JOURNAL |
  71578. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  71579. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &dummy
  71580. );
  71581. }
  71582. /*
  71583. ** Merge the two sorted lists p1 and p2 into a single list.
  71584. ** Set *ppOut to the head of the new list.
  71585. */
  71586. static void vdbeSorterMerge(
  71587. const VdbeCursor *pCsr, /* For pKeyInfo */
  71588. SorterRecord *p1, /* First list to merge */
  71589. SorterRecord *p2, /* Second list to merge */
  71590. SorterRecord **ppOut /* OUT: Head of merged list */
  71591. ){
  71592. SorterRecord *pFinal = 0;
  71593. SorterRecord **pp = &pFinal;
  71594. void *pVal2 = p2 ? p2->pVal : 0;
  71595. while( p1 && p2 ){
  71596. int res;
  71597. vdbeSorterCompare(pCsr, 0, p1->pVal, p1->nVal, pVal2, p2->nVal, &res);
  71598. if( res<=0 ){
  71599. *pp = p1;
  71600. pp = &p1->pNext;
  71601. p1 = p1->pNext;
  71602. pVal2 = 0;
  71603. }else{
  71604. *pp = p2;
  71605. pp = &p2->pNext;
  71606. p2 = p2->pNext;
  71607. if( p2==0 ) break;
  71608. pVal2 = p2->pVal;
  71609. }
  71610. }
  71611. *pp = p1 ? p1 : p2;
  71612. *ppOut = pFinal;
  71613. }
  71614. /*
  71615. ** Sort the linked list of records headed at pCsr->pRecord. Return SQLITE_OK
  71616. ** if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if an error
  71617. ** occurs.
  71618. */
  71619. static int vdbeSorterSort(const VdbeCursor *pCsr){
  71620. int i;
  71621. SorterRecord **aSlot;
  71622. SorterRecord *p;
  71623. VdbeSorter *pSorter = pCsr->pSorter;
  71624. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  71625. if( !aSlot ){
  71626. return SQLITE_NOMEM;
  71627. }
  71628. p = pSorter->pRecord;
  71629. while( p ){
  71630. SorterRecord *pNext = p->pNext;
  71631. p->pNext = 0;
  71632. for(i=0; aSlot[i]; i++){
  71633. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  71634. aSlot[i] = 0;
  71635. }
  71636. aSlot[i] = p;
  71637. p = pNext;
  71638. }
  71639. p = 0;
  71640. for(i=0; i<64; i++){
  71641. vdbeSorterMerge(pCsr, p, aSlot[i], &p);
  71642. }
  71643. pSorter->pRecord = p;
  71644. sqlite3_free(aSlot);
  71645. return SQLITE_OK;
  71646. }
  71647. /*
  71648. ** Initialize a file-writer object.
  71649. */
  71650. static void fileWriterInit(
  71651. sqlite3 *db, /* Database (for malloc) */
  71652. sqlite3_file *pFile, /* File to write to */
  71653. FileWriter *p, /* Object to populate */
  71654. i64 iStart /* Offset of pFile to begin writing at */
  71655. ){
  71656. int nBuf = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71657. memset(p, 0, sizeof(FileWriter));
  71658. p->aBuffer = (u8 *)sqlite3DbMallocRaw(db, nBuf);
  71659. if( !p->aBuffer ){
  71660. p->eFWErr = SQLITE_NOMEM;
  71661. }else{
  71662. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  71663. p->iWriteOff = iStart - p->iBufStart;
  71664. p->nBuffer = nBuf;
  71665. p->pFile = pFile;
  71666. }
  71667. }
  71668. /*
  71669. ** Write nData bytes of data to the file-write object. Return SQLITE_OK
  71670. ** if successful, or an SQLite error code if an error occurs.
  71671. */
  71672. static void fileWriterWrite(FileWriter *p, u8 *pData, int nData){
  71673. int nRem = nData;
  71674. while( nRem>0 && p->eFWErr==0 ){
  71675. int nCopy = nRem;
  71676. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  71677. nCopy = p->nBuffer - p->iBufEnd;
  71678. }
  71679. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  71680. p->iBufEnd += nCopy;
  71681. if( p->iBufEnd==p->nBuffer ){
  71682. p->eFWErr = sqlite3OsWrite(p->pFile,
  71683. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  71684. p->iWriteOff + p->iBufStart
  71685. );
  71686. p->iBufStart = p->iBufEnd = 0;
  71687. p->iWriteOff += p->nBuffer;
  71688. }
  71689. assert( p->iBufEnd<p->nBuffer );
  71690. nRem -= nCopy;
  71691. }
  71692. }
  71693. /*
  71694. ** Flush any buffered data to disk and clean up the file-writer object.
  71695. ** The results of using the file-writer after this call are undefined.
  71696. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  71697. ** required. Otherwise, return an SQLite error code.
  71698. **
  71699. ** Before returning, set *piEof to the offset immediately following the
  71700. ** last byte written to the file.
  71701. */
  71702. static int fileWriterFinish(sqlite3 *db, FileWriter *p, i64 *piEof){
  71703. int rc;
  71704. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  71705. p->eFWErr = sqlite3OsWrite(p->pFile,
  71706. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  71707. p->iWriteOff + p->iBufStart
  71708. );
  71709. }
  71710. *piEof = (p->iWriteOff + p->iBufEnd);
  71711. sqlite3DbFree(db, p->aBuffer);
  71712. rc = p->eFWErr;
  71713. memset(p, 0, sizeof(FileWriter));
  71714. return rc;
  71715. }
  71716. /*
  71717. ** Write value iVal encoded as a varint to the file-write object. Return
  71718. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  71719. */
  71720. static void fileWriterWriteVarint(FileWriter *p, u64 iVal){
  71721. int nByte;
  71722. u8 aByte[10];
  71723. nByte = sqlite3PutVarint(aByte, iVal);
  71724. fileWriterWrite(p, aByte, nByte);
  71725. }
  71726. /*
  71727. ** Write the current contents of the in-memory linked-list to a PMA. Return
  71728. ** SQLITE_OK if successful, or an SQLite error code otherwise.
  71729. **
  71730. ** The format of a PMA is:
  71731. **
  71732. ** * A varint. This varint contains the total number of bytes of content
  71733. ** in the PMA (not including the varint itself).
  71734. **
  71735. ** * One or more records packed end-to-end in order of ascending keys.
  71736. ** Each record consists of a varint followed by a blob of data (the
  71737. ** key). The varint is the number of bytes in the blob of data.
  71738. */
  71739. static int vdbeSorterListToPMA(sqlite3 *db, const VdbeCursor *pCsr){
  71740. int rc = SQLITE_OK; /* Return code */
  71741. VdbeSorter *pSorter = pCsr->pSorter;
  71742. FileWriter writer;
  71743. memset(&writer, 0, sizeof(FileWriter));
  71744. if( pSorter->nInMemory==0 ){
  71745. assert( pSorter->pRecord==0 );
  71746. return rc;
  71747. }
  71748. rc = vdbeSorterSort(pCsr);
  71749. /* If the first temporary PMA file has not been opened, open it now. */
  71750. if( rc==SQLITE_OK && pSorter->pTemp1==0 ){
  71751. rc = vdbeSorterOpenTempFile(db, &pSorter->pTemp1);
  71752. assert( rc!=SQLITE_OK || pSorter->pTemp1 );
  71753. assert( pSorter->iWriteOff==0 );
  71754. assert( pSorter->nPMA==0 );
  71755. }
  71756. if( rc==SQLITE_OK ){
  71757. SorterRecord *p;
  71758. SorterRecord *pNext = 0;
  71759. fileWriterInit(db, pSorter->pTemp1, &writer, pSorter->iWriteOff);
  71760. pSorter->nPMA++;
  71761. fileWriterWriteVarint(&writer, pSorter->nInMemory);
  71762. for(p=pSorter->pRecord; p; p=pNext){
  71763. pNext = p->pNext;
  71764. fileWriterWriteVarint(&writer, p->nVal);
  71765. fileWriterWrite(&writer, p->pVal, p->nVal);
  71766. sqlite3DbFree(db, p);
  71767. }
  71768. pSorter->pRecord = p;
  71769. rc = fileWriterFinish(db, &writer, &pSorter->iWriteOff);
  71770. }
  71771. return rc;
  71772. }
  71773. /*
  71774. ** Add a record to the sorter.
  71775. */
  71776. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  71777. sqlite3 *db, /* Database handle */
  71778. const VdbeCursor *pCsr, /* Sorter cursor */
  71779. Mem *pVal /* Memory cell containing record */
  71780. ){
  71781. VdbeSorter *pSorter = pCsr->pSorter;
  71782. int rc = SQLITE_OK; /* Return Code */
  71783. SorterRecord *pNew; /* New list element */
  71784. assert( pSorter );
  71785. pSorter->nInMemory += sqlite3VarintLen(pVal->n) + pVal->n;
  71786. pNew = (SorterRecord *)sqlite3DbMallocRaw(db, pVal->n + sizeof(SorterRecord));
  71787. if( pNew==0 ){
  71788. rc = SQLITE_NOMEM;
  71789. }else{
  71790. pNew->pVal = (void *)&pNew[1];
  71791. memcpy(pNew->pVal, pVal->z, pVal->n);
  71792. pNew->nVal = pVal->n;
  71793. pNew->pNext = pSorter->pRecord;
  71794. pSorter->pRecord = pNew;
  71795. }
  71796. /* See if the contents of the sorter should now be written out. They
  71797. ** are written out when either of the following are true:
  71798. **
  71799. ** * The total memory allocated for the in-memory list is greater
  71800. ** than (page-size * cache-size), or
  71801. **
  71802. ** * The total memory allocated for the in-memory list is greater
  71803. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  71804. */
  71805. if( rc==SQLITE_OK && pSorter->mxPmaSize>0 && (
  71806. (pSorter->nInMemory>pSorter->mxPmaSize)
  71807. || (pSorter->nInMemory>pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  71808. )){
  71809. #ifdef SQLITE_DEBUG
  71810. i64 nExpect = pSorter->iWriteOff
  71811. + sqlite3VarintLen(pSorter->nInMemory)
  71812. + pSorter->nInMemory;
  71813. #endif
  71814. rc = vdbeSorterListToPMA(db, pCsr);
  71815. pSorter->nInMemory = 0;
  71816. assert( rc!=SQLITE_OK || (nExpect==pSorter->iWriteOff) );
  71817. }
  71818. return rc;
  71819. }
  71820. /*
  71821. ** Helper function for sqlite3VdbeSorterRewind().
  71822. */
  71823. static int vdbeSorterInitMerge(
  71824. sqlite3 *db, /* Database handle */
  71825. const VdbeCursor *pCsr, /* Cursor handle for this sorter */
  71826. i64 *pnByte /* Sum of bytes in all opened PMAs */
  71827. ){
  71828. VdbeSorter *pSorter = pCsr->pSorter;
  71829. int rc = SQLITE_OK; /* Return code */
  71830. int i; /* Used to iterator through aIter[] */
  71831. i64 nByte = 0; /* Total bytes in all opened PMAs */
  71832. /* Initialize the iterators. */
  71833. for(i=0; i<SORTER_MAX_MERGE_COUNT; i++){
  71834. VdbeSorterIter *pIter = &pSorter->aIter[i];
  71835. rc = vdbeSorterIterInit(db, pSorter, pSorter->iReadOff, pIter, &nByte);
  71836. pSorter->iReadOff = pIter->iEof;
  71837. assert( rc!=SQLITE_OK || pSorter->iReadOff<=pSorter->iWriteOff );
  71838. if( rc!=SQLITE_OK || pSorter->iReadOff>=pSorter->iWriteOff ) break;
  71839. }
  71840. /* Initialize the aTree[] array. */
  71841. for(i=pSorter->nTree-1; rc==SQLITE_OK && i>0; i--){
  71842. rc = vdbeSorterDoCompare(pCsr, i);
  71843. }
  71844. *pnByte = nByte;
  71845. return rc;
  71846. }
  71847. /*
  71848. ** Once the sorter has been populated, this function is called to prepare
  71849. ** for iterating through its contents in sorted order.
  71850. */
  71851. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  71852. VdbeSorter *pSorter = pCsr->pSorter;
  71853. int rc; /* Return code */
  71854. sqlite3_file *pTemp2 = 0; /* Second temp file to use */
  71855. i64 iWrite2 = 0; /* Write offset for pTemp2 */
  71856. int nIter; /* Number of iterators used */
  71857. int nByte; /* Bytes of space required for aIter/aTree */
  71858. int N = 2; /* Power of 2 >= nIter */
  71859. assert( pSorter );
  71860. /* If no data has been written to disk, then do not do so now. Instead,
  71861. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  71862. ** from the in-memory list. */
  71863. if( pSorter->nPMA==0 ){
  71864. *pbEof = !pSorter->pRecord;
  71865. assert( pSorter->aTree==0 );
  71866. return vdbeSorterSort(pCsr);
  71867. }
  71868. /* Write the current in-memory list to a PMA. */
  71869. rc = vdbeSorterListToPMA(db, pCsr);
  71870. if( rc!=SQLITE_OK ) return rc;
  71871. /* Allocate space for aIter[] and aTree[]. */
  71872. nIter = pSorter->nPMA;
  71873. if( nIter>SORTER_MAX_MERGE_COUNT ) nIter = SORTER_MAX_MERGE_COUNT;
  71874. assert( nIter>0 );
  71875. while( N<nIter ) N += N;
  71876. nByte = N * (sizeof(int) + sizeof(VdbeSorterIter));
  71877. pSorter->aIter = (VdbeSorterIter *)sqlite3DbMallocZero(db, nByte);
  71878. if( !pSorter->aIter ) return SQLITE_NOMEM;
  71879. pSorter->aTree = (int *)&pSorter->aIter[N];
  71880. pSorter->nTree = N;
  71881. do {
  71882. int iNew; /* Index of new, merged, PMA */
  71883. for(iNew=0;
  71884. rc==SQLITE_OK && iNew*SORTER_MAX_MERGE_COUNT<pSorter->nPMA;
  71885. iNew++
  71886. ){
  71887. int rc2; /* Return code from fileWriterFinish() */
  71888. FileWriter writer; /* Object used to write to disk */
  71889. i64 nWrite; /* Number of bytes in new PMA */
  71890. memset(&writer, 0, sizeof(FileWriter));
  71891. /* If there are SORTER_MAX_MERGE_COUNT or less PMAs in file pTemp1,
  71892. ** initialize an iterator for each of them and break out of the loop.
  71893. ** These iterators will be incrementally merged as the VDBE layer calls
  71894. ** sqlite3VdbeSorterNext().
  71895. **
  71896. ** Otherwise, if pTemp1 contains more than SORTER_MAX_MERGE_COUNT PMAs,
  71897. ** initialize interators for SORTER_MAX_MERGE_COUNT of them. These PMAs
  71898. ** are merged into a single PMA that is written to file pTemp2.
  71899. */
  71900. rc = vdbeSorterInitMerge(db, pCsr, &nWrite);
  71901. assert( rc!=SQLITE_OK || pSorter->aIter[ pSorter->aTree[1] ].pFile );
  71902. if( rc!=SQLITE_OK || pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  71903. break;
  71904. }
  71905. /* Open the second temp file, if it is not already open. */
  71906. if( pTemp2==0 ){
  71907. assert( iWrite2==0 );
  71908. rc = vdbeSorterOpenTempFile(db, &pTemp2);
  71909. }
  71910. if( rc==SQLITE_OK ){
  71911. int bEof = 0;
  71912. fileWriterInit(db, pTemp2, &writer, iWrite2);
  71913. fileWriterWriteVarint(&writer, nWrite);
  71914. while( rc==SQLITE_OK && bEof==0 ){
  71915. VdbeSorterIter *pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  71916. assert( pIter->pFile );
  71917. fileWriterWriteVarint(&writer, pIter->nKey);
  71918. fileWriterWrite(&writer, pIter->aKey, pIter->nKey);
  71919. rc = sqlite3VdbeSorterNext(db, pCsr, &bEof);
  71920. }
  71921. rc2 = fileWriterFinish(db, &writer, &iWrite2);
  71922. if( rc==SQLITE_OK ) rc = rc2;
  71923. }
  71924. }
  71925. if( pSorter->nPMA<=SORTER_MAX_MERGE_COUNT ){
  71926. break;
  71927. }else{
  71928. sqlite3_file *pTmp = pSorter->pTemp1;
  71929. pSorter->nPMA = iNew;
  71930. pSorter->pTemp1 = pTemp2;
  71931. pTemp2 = pTmp;
  71932. pSorter->iWriteOff = iWrite2;
  71933. pSorter->iReadOff = 0;
  71934. iWrite2 = 0;
  71935. }
  71936. }while( rc==SQLITE_OK );
  71937. if( pTemp2 ){
  71938. sqlite3OsCloseFree(pTemp2);
  71939. }
  71940. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  71941. return rc;
  71942. }
  71943. /*
  71944. ** Advance to the next element in the sorter.
  71945. */
  71946. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  71947. VdbeSorter *pSorter = pCsr->pSorter;
  71948. int rc; /* Return code */
  71949. if( pSorter->aTree ){
  71950. int iPrev = pSorter->aTree[1];/* Index of iterator to advance */
  71951. int i; /* Index of aTree[] to recalculate */
  71952. rc = vdbeSorterIterNext(db, &pSorter->aIter[iPrev]);
  71953. for(i=(pSorter->nTree+iPrev)/2; rc==SQLITE_OK && i>0; i=i/2){
  71954. rc = vdbeSorterDoCompare(pCsr, i);
  71955. }
  71956. *pbEof = (pSorter->aIter[pSorter->aTree[1]].pFile==0);
  71957. }else{
  71958. SorterRecord *pFree = pSorter->pRecord;
  71959. pSorter->pRecord = pFree->pNext;
  71960. pFree->pNext = 0;
  71961. vdbeSorterRecordFree(db, pFree);
  71962. *pbEof = !pSorter->pRecord;
  71963. rc = SQLITE_OK;
  71964. }
  71965. return rc;
  71966. }
  71967. /*
  71968. ** Return a pointer to a buffer owned by the sorter that contains the
  71969. ** current key.
  71970. */
  71971. static void *vdbeSorterRowkey(
  71972. const VdbeSorter *pSorter, /* Sorter object */
  71973. int *pnKey /* OUT: Size of current key in bytes */
  71974. ){
  71975. void *pKey;
  71976. if( pSorter->aTree ){
  71977. VdbeSorterIter *pIter;
  71978. pIter = &pSorter->aIter[ pSorter->aTree[1] ];
  71979. *pnKey = pIter->nKey;
  71980. pKey = pIter->aKey;
  71981. }else{
  71982. *pnKey = pSorter->pRecord->nVal;
  71983. pKey = pSorter->pRecord->pVal;
  71984. }
  71985. return pKey;
  71986. }
  71987. /*
  71988. ** Copy the current sorter key into the memory cell pOut.
  71989. */
  71990. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  71991. VdbeSorter *pSorter = pCsr->pSorter;
  71992. void *pKey; int nKey; /* Sorter key to copy into pOut */
  71993. pKey = vdbeSorterRowkey(pSorter, &nKey);
  71994. if( sqlite3VdbeMemGrow(pOut, nKey, 0) ){
  71995. return SQLITE_NOMEM;
  71996. }
  71997. pOut->n = nKey;
  71998. MemSetTypeFlag(pOut, MEM_Blob);
  71999. memcpy(pOut->z, pKey, nKey);
  72000. return SQLITE_OK;
  72001. }
  72002. /*
  72003. ** Compare the key in memory cell pVal with the key that the sorter cursor
  72004. ** passed as the first argument currently points to. For the purposes of
  72005. ** the comparison, ignore the rowid field at the end of each record.
  72006. **
  72007. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  72008. ** Otherwise, set *pRes to a negative, zero or positive value if the
  72009. ** key in pVal is smaller than, equal to or larger than the current sorter
  72010. ** key.
  72011. */
  72012. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  72013. const VdbeCursor *pCsr, /* Sorter cursor */
  72014. Mem *pVal, /* Value to compare to current sorter key */
  72015. int *pRes /* OUT: Result of comparison */
  72016. ){
  72017. VdbeSorter *pSorter = pCsr->pSorter;
  72018. void *pKey; int nKey; /* Sorter key to compare pVal with */
  72019. pKey = vdbeSorterRowkey(pSorter, &nKey);
  72020. vdbeSorterCompare(pCsr, 1, pVal->z, pVal->n, pKey, nKey, pRes);
  72021. return SQLITE_OK;
  72022. }
  72023. /************** End of vdbesort.c ********************************************/
  72024. /************** Begin file journal.c *****************************************/
  72025. /*
  72026. ** 2007 August 22
  72027. **
  72028. ** The author disclaims copyright to this source code. In place of
  72029. ** a legal notice, here is a blessing:
  72030. **
  72031. ** May you do good and not evil.
  72032. ** May you find forgiveness for yourself and forgive others.
  72033. ** May you share freely, never taking more than you give.
  72034. **
  72035. *************************************************************************
  72036. **
  72037. ** This file implements a special kind of sqlite3_file object used
  72038. ** by SQLite to create journal files if the atomic-write optimization
  72039. ** is enabled.
  72040. **
  72041. ** The distinctive characteristic of this sqlite3_file is that the
  72042. ** actual on disk file is created lazily. When the file is created,
  72043. ** the caller specifies a buffer size for an in-memory buffer to
  72044. ** be used to service read() and write() requests. The actual file
  72045. ** on disk is not created or populated until either:
  72046. **
  72047. ** 1) The in-memory representation grows too large for the allocated
  72048. ** buffer, or
  72049. ** 2) The sqlite3JournalCreate() function is called.
  72050. */
  72051. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  72052. /*
  72053. ** A JournalFile object is a subclass of sqlite3_file used by
  72054. ** as an open file handle for journal files.
  72055. */
  72056. struct JournalFile {
  72057. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  72058. int nBuf; /* Size of zBuf[] in bytes */
  72059. char *zBuf; /* Space to buffer journal writes */
  72060. int iSize; /* Amount of zBuf[] currently used */
  72061. int flags; /* xOpen flags */
  72062. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  72063. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  72064. const char *zJournal; /* Name of the journal file */
  72065. };
  72066. typedef struct JournalFile JournalFile;
  72067. /*
  72068. ** If it does not already exists, create and populate the on-disk file
  72069. ** for JournalFile p.
  72070. */
  72071. static int createFile(JournalFile *p){
  72072. int rc = SQLITE_OK;
  72073. if( !p->pReal ){
  72074. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  72075. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  72076. if( rc==SQLITE_OK ){
  72077. p->pReal = pReal;
  72078. if( p->iSize>0 ){
  72079. assert(p->iSize<=p->nBuf);
  72080. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  72081. }
  72082. if( rc!=SQLITE_OK ){
  72083. /* If an error occurred while writing to the file, close it before
  72084. ** returning. This way, SQLite uses the in-memory journal data to
  72085. ** roll back changes made to the internal page-cache before this
  72086. ** function was called. */
  72087. sqlite3OsClose(pReal);
  72088. p->pReal = 0;
  72089. }
  72090. }
  72091. }
  72092. return rc;
  72093. }
  72094. /*
  72095. ** Close the file.
  72096. */
  72097. static int jrnlClose(sqlite3_file *pJfd){
  72098. JournalFile *p = (JournalFile *)pJfd;
  72099. if( p->pReal ){
  72100. sqlite3OsClose(p->pReal);
  72101. }
  72102. sqlite3_free(p->zBuf);
  72103. return SQLITE_OK;
  72104. }
  72105. /*
  72106. ** Read data from the file.
  72107. */
  72108. static int jrnlRead(
  72109. sqlite3_file *pJfd, /* The journal file from which to read */
  72110. void *zBuf, /* Put the results here */
  72111. int iAmt, /* Number of bytes to read */
  72112. sqlite_int64 iOfst /* Begin reading at this offset */
  72113. ){
  72114. int rc = SQLITE_OK;
  72115. JournalFile *p = (JournalFile *)pJfd;
  72116. if( p->pReal ){
  72117. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  72118. }else if( (iAmt+iOfst)>p->iSize ){
  72119. rc = SQLITE_IOERR_SHORT_READ;
  72120. }else{
  72121. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  72122. }
  72123. return rc;
  72124. }
  72125. /*
  72126. ** Write data to the file.
  72127. */
  72128. static int jrnlWrite(
  72129. sqlite3_file *pJfd, /* The journal file into which to write */
  72130. const void *zBuf, /* Take data to be written from here */
  72131. int iAmt, /* Number of bytes to write */
  72132. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  72133. ){
  72134. int rc = SQLITE_OK;
  72135. JournalFile *p = (JournalFile *)pJfd;
  72136. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  72137. rc = createFile(p);
  72138. }
  72139. if( rc==SQLITE_OK ){
  72140. if( p->pReal ){
  72141. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  72142. }else{
  72143. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  72144. if( p->iSize<(iOfst+iAmt) ){
  72145. p->iSize = (iOfst+iAmt);
  72146. }
  72147. }
  72148. }
  72149. return rc;
  72150. }
  72151. /*
  72152. ** Truncate the file.
  72153. */
  72154. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  72155. int rc = SQLITE_OK;
  72156. JournalFile *p = (JournalFile *)pJfd;
  72157. if( p->pReal ){
  72158. rc = sqlite3OsTruncate(p->pReal, size);
  72159. }else if( size<p->iSize ){
  72160. p->iSize = size;
  72161. }
  72162. return rc;
  72163. }
  72164. /*
  72165. ** Sync the file.
  72166. */
  72167. static int jrnlSync(sqlite3_file *pJfd, int flags){
  72168. int rc;
  72169. JournalFile *p = (JournalFile *)pJfd;
  72170. if( p->pReal ){
  72171. rc = sqlite3OsSync(p->pReal, flags);
  72172. }else{
  72173. rc = SQLITE_OK;
  72174. }
  72175. return rc;
  72176. }
  72177. /*
  72178. ** Query the size of the file in bytes.
  72179. */
  72180. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  72181. int rc = SQLITE_OK;
  72182. JournalFile *p = (JournalFile *)pJfd;
  72183. if( p->pReal ){
  72184. rc = sqlite3OsFileSize(p->pReal, pSize);
  72185. }else{
  72186. *pSize = (sqlite_int64) p->iSize;
  72187. }
  72188. return rc;
  72189. }
  72190. /*
  72191. ** Table of methods for JournalFile sqlite3_file object.
  72192. */
  72193. static struct sqlite3_io_methods JournalFileMethods = {
  72194. 1, /* iVersion */
  72195. jrnlClose, /* xClose */
  72196. jrnlRead, /* xRead */
  72197. jrnlWrite, /* xWrite */
  72198. jrnlTruncate, /* xTruncate */
  72199. jrnlSync, /* xSync */
  72200. jrnlFileSize, /* xFileSize */
  72201. 0, /* xLock */
  72202. 0, /* xUnlock */
  72203. 0, /* xCheckReservedLock */
  72204. 0, /* xFileControl */
  72205. 0, /* xSectorSize */
  72206. 0, /* xDeviceCharacteristics */
  72207. 0, /* xShmMap */
  72208. 0, /* xShmLock */
  72209. 0, /* xShmBarrier */
  72210. 0 /* xShmUnmap */
  72211. };
  72212. /*
  72213. ** Open a journal file.
  72214. */
  72215. SQLITE_PRIVATE int sqlite3JournalOpen(
  72216. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  72217. const char *zName, /* Name of the journal file */
  72218. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  72219. int flags, /* Opening flags */
  72220. int nBuf /* Bytes buffered before opening the file */
  72221. ){
  72222. JournalFile *p = (JournalFile *)pJfd;
  72223. memset(p, 0, sqlite3JournalSize(pVfs));
  72224. if( nBuf>0 ){
  72225. p->zBuf = sqlite3MallocZero(nBuf);
  72226. if( !p->zBuf ){
  72227. return SQLITE_NOMEM;
  72228. }
  72229. }else{
  72230. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  72231. }
  72232. p->pMethod = &JournalFileMethods;
  72233. p->nBuf = nBuf;
  72234. p->flags = flags;
  72235. p->zJournal = zName;
  72236. p->pVfs = pVfs;
  72237. return SQLITE_OK;
  72238. }
  72239. /*
  72240. ** If the argument p points to a JournalFile structure, and the underlying
  72241. ** file has not yet been created, create it now.
  72242. */
  72243. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  72244. if( p->pMethods!=&JournalFileMethods ){
  72245. return SQLITE_OK;
  72246. }
  72247. return createFile((JournalFile *)p);
  72248. }
  72249. /*
  72250. ** The file-handle passed as the only argument is guaranteed to be an open
  72251. ** file. It may or may not be of class JournalFile. If the file is a
  72252. ** JournalFile, and the underlying file on disk has not yet been opened,
  72253. ** return 0. Otherwise, return 1.
  72254. */
  72255. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  72256. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  72257. }
  72258. /*
  72259. ** Return the number of bytes required to store a JournalFile that uses vfs
  72260. ** pVfs to create the underlying on-disk files.
  72261. */
  72262. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  72263. return (pVfs->szOsFile+sizeof(JournalFile));
  72264. }
  72265. #endif
  72266. /************** End of journal.c *********************************************/
  72267. /************** Begin file memjournal.c **************************************/
  72268. /*
  72269. ** 2008 October 7
  72270. **
  72271. ** The author disclaims copyright to this source code. In place of
  72272. ** a legal notice, here is a blessing:
  72273. **
  72274. ** May you do good and not evil.
  72275. ** May you find forgiveness for yourself and forgive others.
  72276. ** May you share freely, never taking more than you give.
  72277. **
  72278. *************************************************************************
  72279. **
  72280. ** This file contains code use to implement an in-memory rollback journal.
  72281. ** The in-memory rollback journal is used to journal transactions for
  72282. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  72283. */
  72284. /* Forward references to internal structures */
  72285. typedef struct MemJournal MemJournal;
  72286. typedef struct FilePoint FilePoint;
  72287. typedef struct FileChunk FileChunk;
  72288. /* Space to hold the rollback journal is allocated in increments of
  72289. ** this many bytes.
  72290. **
  72291. ** The size chosen is a little less than a power of two. That way,
  72292. ** the FileChunk object will have a size that almost exactly fills
  72293. ** a power-of-two allocation. This mimimizes wasted space in power-of-two
  72294. ** memory allocators.
  72295. */
  72296. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  72297. /*
  72298. ** The rollback journal is composed of a linked list of these structures.
  72299. */
  72300. struct FileChunk {
  72301. FileChunk *pNext; /* Next chunk in the journal */
  72302. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  72303. };
  72304. /*
  72305. ** An instance of this object serves as a cursor into the rollback journal.
  72306. ** The cursor can be either for reading or writing.
  72307. */
  72308. struct FilePoint {
  72309. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  72310. FileChunk *pChunk; /* Specific chunk into which cursor points */
  72311. };
  72312. /*
  72313. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  72314. ** is an instance of this class.
  72315. */
  72316. struct MemJournal {
  72317. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  72318. FileChunk *pFirst; /* Head of in-memory chunk-list */
  72319. FilePoint endpoint; /* Pointer to the end of the file */
  72320. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  72321. };
  72322. /*
  72323. ** Read data from the in-memory journal file. This is the implementation
  72324. ** of the sqlite3_vfs.xRead method.
  72325. */
  72326. static int memjrnlRead(
  72327. sqlite3_file *pJfd, /* The journal file from which to read */
  72328. void *zBuf, /* Put the results here */
  72329. int iAmt, /* Number of bytes to read */
  72330. sqlite_int64 iOfst /* Begin reading at this offset */
  72331. ){
  72332. MemJournal *p = (MemJournal *)pJfd;
  72333. u8 *zOut = zBuf;
  72334. int nRead = iAmt;
  72335. int iChunkOffset;
  72336. FileChunk *pChunk;
  72337. /* SQLite never tries to read past the end of a rollback journal file */
  72338. assert( iOfst+iAmt<=p->endpoint.iOffset );
  72339. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  72340. sqlite3_int64 iOff = 0;
  72341. for(pChunk=p->pFirst;
  72342. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  72343. pChunk=pChunk->pNext
  72344. ){
  72345. iOff += JOURNAL_CHUNKSIZE;
  72346. }
  72347. }else{
  72348. pChunk = p->readpoint.pChunk;
  72349. }
  72350. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  72351. do {
  72352. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  72353. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  72354. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  72355. zOut += nCopy;
  72356. nRead -= iSpace;
  72357. iChunkOffset = 0;
  72358. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  72359. p->readpoint.iOffset = iOfst+iAmt;
  72360. p->readpoint.pChunk = pChunk;
  72361. return SQLITE_OK;
  72362. }
  72363. /*
  72364. ** Write data to the file.
  72365. */
  72366. static int memjrnlWrite(
  72367. sqlite3_file *pJfd, /* The journal file into which to write */
  72368. const void *zBuf, /* Take data to be written from here */
  72369. int iAmt, /* Number of bytes to write */
  72370. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  72371. ){
  72372. MemJournal *p = (MemJournal *)pJfd;
  72373. int nWrite = iAmt;
  72374. u8 *zWrite = (u8 *)zBuf;
  72375. /* An in-memory journal file should only ever be appended to. Random
  72376. ** access writes are not required by sqlite.
  72377. */
  72378. assert( iOfst==p->endpoint.iOffset );
  72379. UNUSED_PARAMETER(iOfst);
  72380. while( nWrite>0 ){
  72381. FileChunk *pChunk = p->endpoint.pChunk;
  72382. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  72383. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  72384. if( iChunkOffset==0 ){
  72385. /* New chunk is required to extend the file. */
  72386. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  72387. if( !pNew ){
  72388. return SQLITE_IOERR_NOMEM;
  72389. }
  72390. pNew->pNext = 0;
  72391. if( pChunk ){
  72392. assert( p->pFirst );
  72393. pChunk->pNext = pNew;
  72394. }else{
  72395. assert( !p->pFirst );
  72396. p->pFirst = pNew;
  72397. }
  72398. p->endpoint.pChunk = pNew;
  72399. }
  72400. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  72401. zWrite += iSpace;
  72402. nWrite -= iSpace;
  72403. p->endpoint.iOffset += iSpace;
  72404. }
  72405. return SQLITE_OK;
  72406. }
  72407. /*
  72408. ** Truncate the file.
  72409. */
  72410. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  72411. MemJournal *p = (MemJournal *)pJfd;
  72412. FileChunk *pChunk;
  72413. assert(size==0);
  72414. UNUSED_PARAMETER(size);
  72415. pChunk = p->pFirst;
  72416. while( pChunk ){
  72417. FileChunk *pTmp = pChunk;
  72418. pChunk = pChunk->pNext;
  72419. sqlite3_free(pTmp);
  72420. }
  72421. sqlite3MemJournalOpen(pJfd);
  72422. return SQLITE_OK;
  72423. }
  72424. /*
  72425. ** Close the file.
  72426. */
  72427. static int memjrnlClose(sqlite3_file *pJfd){
  72428. memjrnlTruncate(pJfd, 0);
  72429. return SQLITE_OK;
  72430. }
  72431. /*
  72432. ** Sync the file.
  72433. **
  72434. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  72435. ** is never called in a working implementation. This implementation
  72436. ** exists purely as a contingency, in case some malfunction in some other
  72437. ** part of SQLite causes Sync to be called by mistake.
  72438. */
  72439. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  72440. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  72441. return SQLITE_OK;
  72442. }
  72443. /*
  72444. ** Query the size of the file in bytes.
  72445. */
  72446. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  72447. MemJournal *p = (MemJournal *)pJfd;
  72448. *pSize = (sqlite_int64) p->endpoint.iOffset;
  72449. return SQLITE_OK;
  72450. }
  72451. /*
  72452. ** Table of methods for MemJournal sqlite3_file object.
  72453. */
  72454. static const struct sqlite3_io_methods MemJournalMethods = {
  72455. 1, /* iVersion */
  72456. memjrnlClose, /* xClose */
  72457. memjrnlRead, /* xRead */
  72458. memjrnlWrite, /* xWrite */
  72459. memjrnlTruncate, /* xTruncate */
  72460. memjrnlSync, /* xSync */
  72461. memjrnlFileSize, /* xFileSize */
  72462. 0, /* xLock */
  72463. 0, /* xUnlock */
  72464. 0, /* xCheckReservedLock */
  72465. 0, /* xFileControl */
  72466. 0, /* xSectorSize */
  72467. 0, /* xDeviceCharacteristics */
  72468. 0, /* xShmMap */
  72469. 0, /* xShmLock */
  72470. 0, /* xShmBarrier */
  72471. 0, /* xShmUnmap */
  72472. 0, /* xFetch */
  72473. 0 /* xUnfetch */
  72474. };
  72475. /*
  72476. ** Open a journal file.
  72477. */
  72478. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  72479. MemJournal *p = (MemJournal *)pJfd;
  72480. assert( EIGHT_BYTE_ALIGNMENT(p) );
  72481. memset(p, 0, sqlite3MemJournalSize());
  72482. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  72483. }
  72484. /*
  72485. ** Return true if the file-handle passed as an argument is
  72486. ** an in-memory journal
  72487. */
  72488. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  72489. return pJfd->pMethods==&MemJournalMethods;
  72490. }
  72491. /*
  72492. ** Return the number of bytes required to store a MemJournal file descriptor.
  72493. */
  72494. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  72495. return sizeof(MemJournal);
  72496. }
  72497. /************** End of memjournal.c ******************************************/
  72498. /************** Begin file walker.c ******************************************/
  72499. /*
  72500. ** 2008 August 16
  72501. **
  72502. ** The author disclaims copyright to this source code. In place of
  72503. ** a legal notice, here is a blessing:
  72504. **
  72505. ** May you do good and not evil.
  72506. ** May you find forgiveness for yourself and forgive others.
  72507. ** May you share freely, never taking more than you give.
  72508. **
  72509. *************************************************************************
  72510. ** This file contains routines used for walking the parser tree for
  72511. ** an SQL statement.
  72512. */
  72513. /* #include <stdlib.h> */
  72514. /* #include <string.h> */
  72515. /*
  72516. ** Walk an expression tree. Invoke the callback once for each node
  72517. ** of the expression, while decending. (In other words, the callback
  72518. ** is invoked before visiting children.)
  72519. **
  72520. ** The return value from the callback should be one of the WRC_*
  72521. ** constants to specify how to proceed with the walk.
  72522. **
  72523. ** WRC_Continue Continue descending down the tree.
  72524. **
  72525. ** WRC_Prune Do not descend into child nodes. But allow
  72526. ** the walk to continue with sibling nodes.
  72527. **
  72528. ** WRC_Abort Do no more callbacks. Unwind the stack and
  72529. ** return the top-level walk call.
  72530. **
  72531. ** The return value from this routine is WRC_Abort to abandon the tree walk
  72532. ** and WRC_Continue to continue.
  72533. */
  72534. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  72535. int rc;
  72536. if( pExpr==0 ) return WRC_Continue;
  72537. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  72538. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  72539. rc = pWalker->xExprCallback(pWalker, pExpr);
  72540. if( rc==WRC_Continue
  72541. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  72542. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  72543. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  72544. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  72545. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  72546. }else{
  72547. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  72548. }
  72549. }
  72550. return rc & WRC_Abort;
  72551. }
  72552. /*
  72553. ** Call sqlite3WalkExpr() for every expression in list p or until
  72554. ** an abort request is seen.
  72555. */
  72556. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  72557. int i;
  72558. struct ExprList_item *pItem;
  72559. if( p ){
  72560. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  72561. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  72562. }
  72563. }
  72564. return WRC_Continue;
  72565. }
  72566. /*
  72567. ** Walk all expressions associated with SELECT statement p. Do
  72568. ** not invoke the SELECT callback on p, but do (of course) invoke
  72569. ** any expr callbacks and SELECT callbacks that come from subqueries.
  72570. ** Return WRC_Abort or WRC_Continue.
  72571. */
  72572. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  72573. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  72574. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  72575. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  72576. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  72577. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  72578. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  72579. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  72580. return WRC_Continue;
  72581. }
  72582. /*
  72583. ** Walk the parse trees associated with all subqueries in the
  72584. ** FROM clause of SELECT statement p. Do not invoke the select
  72585. ** callback on p, but do invoke it on each FROM clause subquery
  72586. ** and on any subqueries further down in the tree. Return
  72587. ** WRC_Abort or WRC_Continue;
  72588. */
  72589. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  72590. SrcList *pSrc;
  72591. int i;
  72592. struct SrcList_item *pItem;
  72593. pSrc = p->pSrc;
  72594. if( ALWAYS(pSrc) ){
  72595. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  72596. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  72597. return WRC_Abort;
  72598. }
  72599. }
  72600. }
  72601. return WRC_Continue;
  72602. }
  72603. /*
  72604. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  72605. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  72606. ** on the compound select chain, p->pPrior. Invoke the xSelectCallback()
  72607. ** either before or after the walk of expressions and FROM clause, depending
  72608. ** on whether pWalker->bSelectDepthFirst is false or true, respectively.
  72609. **
  72610. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  72611. ** there is an abort request.
  72612. **
  72613. ** If the Walker does not have an xSelectCallback() then this routine
  72614. ** is a no-op returning WRC_Continue.
  72615. */
  72616. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  72617. int rc;
  72618. if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
  72619. rc = WRC_Continue;
  72620. pWalker->walkerDepth++;
  72621. while( p ){
  72622. if( !pWalker->bSelectDepthFirst ){
  72623. rc = pWalker->xSelectCallback(pWalker, p);
  72624. if( rc ) break;
  72625. }
  72626. if( sqlite3WalkSelectExpr(pWalker, p)
  72627. || sqlite3WalkSelectFrom(pWalker, p)
  72628. ){
  72629. pWalker->walkerDepth--;
  72630. return WRC_Abort;
  72631. }
  72632. if( pWalker->bSelectDepthFirst ){
  72633. rc = pWalker->xSelectCallback(pWalker, p);
  72634. /* Depth-first search is currently only used for
  72635. ** selectAddSubqueryTypeInfo() and that routine always returns
  72636. ** WRC_Continue (0). So the following branch is never taken. */
  72637. if( NEVER(rc) ) break;
  72638. }
  72639. p = p->pPrior;
  72640. }
  72641. pWalker->walkerDepth--;
  72642. return rc & WRC_Abort;
  72643. }
  72644. /************** End of walker.c **********************************************/
  72645. /************** Begin file resolve.c *****************************************/
  72646. /*
  72647. ** 2008 August 18
  72648. **
  72649. ** The author disclaims copyright to this source code. In place of
  72650. ** a legal notice, here is a blessing:
  72651. **
  72652. ** May you do good and not evil.
  72653. ** May you find forgiveness for yourself and forgive others.
  72654. ** May you share freely, never taking more than you give.
  72655. **
  72656. *************************************************************************
  72657. **
  72658. ** This file contains routines used for walking the parser tree and
  72659. ** resolve all identifiers by associating them with a particular
  72660. ** table and column.
  72661. */
  72662. /* #include <stdlib.h> */
  72663. /* #include <string.h> */
  72664. /*
  72665. ** Walk the expression tree pExpr and increase the aggregate function
  72666. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  72667. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  72668. ** outer query into an inner subquery.
  72669. **
  72670. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  72671. ** is a helper function - a callback for the tree walker.
  72672. */
  72673. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  72674. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  72675. return WRC_Continue;
  72676. }
  72677. static void incrAggFunctionDepth(Expr *pExpr, int N){
  72678. if( N>0 ){
  72679. Walker w;
  72680. memset(&w, 0, sizeof(w));
  72681. w.xExprCallback = incrAggDepth;
  72682. w.u.i = N;
  72683. sqlite3WalkExpr(&w, pExpr);
  72684. }
  72685. }
  72686. /*
  72687. ** Turn the pExpr expression into an alias for the iCol-th column of the
  72688. ** result set in pEList.
  72689. **
  72690. ** If the result set column is a simple column reference, then this routine
  72691. ** makes an exact copy. But for any other kind of expression, this
  72692. ** routine make a copy of the result set column as the argument to the
  72693. ** TK_AS operator. The TK_AS operator causes the expression to be
  72694. ** evaluated just once and then reused for each alias.
  72695. **
  72696. ** The reason for suppressing the TK_AS term when the expression is a simple
  72697. ** column reference is so that the column reference will be recognized as
  72698. ** usable by indices within the WHERE clause processing logic.
  72699. **
  72700. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  72701. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  72702. **
  72703. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  72704. **
  72705. ** Is equivalent to:
  72706. **
  72707. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  72708. **
  72709. ** The result of random()%5 in the GROUP BY clause is probably different
  72710. ** from the result in the result-set. On the other hand Standard SQL does
  72711. ** not allow the GROUP BY clause to contain references to result-set columns.
  72712. ** So this should never come up in well-formed queries.
  72713. **
  72714. ** If the reference is followed by a COLLATE operator, then make sure
  72715. ** the COLLATE operator is preserved. For example:
  72716. **
  72717. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  72718. **
  72719. ** Should be transformed into:
  72720. **
  72721. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  72722. **
  72723. ** The nSubquery parameter specifies how many levels of subquery the
  72724. ** alias is removed from the original expression. The usually value is
  72725. ** zero but it might be more if the alias is contained within a subquery
  72726. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  72727. ** structures must be increased by the nSubquery amount.
  72728. */
  72729. static void resolveAlias(
  72730. Parse *pParse, /* Parsing context */
  72731. ExprList *pEList, /* A result set */
  72732. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  72733. Expr *pExpr, /* Transform this into an alias to the result set */
  72734. const char *zType, /* "GROUP" or "ORDER" or "" */
  72735. int nSubquery /* Number of subqueries that the label is moving */
  72736. ){
  72737. Expr *pOrig; /* The iCol-th column of the result set */
  72738. Expr *pDup; /* Copy of pOrig */
  72739. sqlite3 *db; /* The database connection */
  72740. assert( iCol>=0 && iCol<pEList->nExpr );
  72741. pOrig = pEList->a[iCol].pExpr;
  72742. assert( pOrig!=0 );
  72743. assert( pOrig->flags & EP_Resolved );
  72744. db = pParse->db;
  72745. pDup = sqlite3ExprDup(db, pOrig, 0);
  72746. if( pDup==0 ) return;
  72747. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  72748. incrAggFunctionDepth(pDup, nSubquery);
  72749. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  72750. if( pDup==0 ) return;
  72751. ExprSetProperty(pDup, EP_Skip);
  72752. if( pEList->a[iCol].iAlias==0 ){
  72753. pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
  72754. }
  72755. pDup->iTable = pEList->a[iCol].iAlias;
  72756. }
  72757. if( pExpr->op==TK_COLLATE ){
  72758. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  72759. }
  72760. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  72761. ** prevents ExprDelete() from deleting the Expr structure itself,
  72762. ** allowing it to be repopulated by the memcpy() on the following line.
  72763. ** The pExpr->u.zToken might point into memory that will be freed by the
  72764. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  72765. ** make a copy of the token before doing the sqlite3DbFree().
  72766. */
  72767. ExprSetProperty(pExpr, EP_Static);
  72768. sqlite3ExprDelete(db, pExpr);
  72769. memcpy(pExpr, pDup, sizeof(*pExpr));
  72770. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  72771. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  72772. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  72773. pExpr->flags |= EP_MemToken;
  72774. }
  72775. sqlite3DbFree(db, pDup);
  72776. }
  72777. /*
  72778. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  72779. **
  72780. ** Return FALSE if the USING clause is NULL or if it does not contain
  72781. ** zCol.
  72782. */
  72783. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  72784. if( pUsing ){
  72785. int k;
  72786. for(k=0; k<pUsing->nId; k++){
  72787. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  72788. }
  72789. }
  72790. return 0;
  72791. }
  72792. /*
  72793. ** Subqueries stores the original database, table and column names for their
  72794. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  72795. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  72796. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  72797. ** match anything.
  72798. */
  72799. SQLITE_PRIVATE int sqlite3MatchSpanName(
  72800. const char *zSpan,
  72801. const char *zCol,
  72802. const char *zTab,
  72803. const char *zDb
  72804. ){
  72805. int n;
  72806. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  72807. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  72808. return 0;
  72809. }
  72810. zSpan += n+1;
  72811. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  72812. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  72813. return 0;
  72814. }
  72815. zSpan += n+1;
  72816. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  72817. return 0;
  72818. }
  72819. return 1;
  72820. }
  72821. /*
  72822. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  72823. ** that name in the set of source tables in pSrcList and make the pExpr
  72824. ** expression node refer back to that source column. The following changes
  72825. ** are made to pExpr:
  72826. **
  72827. ** pExpr->iDb Set the index in db->aDb[] of the database X
  72828. ** (even if X is implied).
  72829. ** pExpr->iTable Set to the cursor number for the table obtained
  72830. ** from pSrcList.
  72831. ** pExpr->pTab Points to the Table structure of X.Y (even if
  72832. ** X and/or Y are implied.)
  72833. ** pExpr->iColumn Set to the column number within the table.
  72834. ** pExpr->op Set to TK_COLUMN.
  72835. ** pExpr->pLeft Any expression this points to is deleted
  72836. ** pExpr->pRight Any expression this points to is deleted.
  72837. **
  72838. ** The zDb variable is the name of the database (the "X"). This value may be
  72839. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  72840. ** can be used. The zTable variable is the name of the table (the "Y"). This
  72841. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  72842. ** means that the form of the name is Z and that columns from any table
  72843. ** can be used.
  72844. **
  72845. ** If the name cannot be resolved unambiguously, leave an error message
  72846. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  72847. */
  72848. static int lookupName(
  72849. Parse *pParse, /* The parsing context */
  72850. const char *zDb, /* Name of the database containing table, or NULL */
  72851. const char *zTab, /* Name of table containing column, or NULL */
  72852. const char *zCol, /* Name of the column. */
  72853. NameContext *pNC, /* The name context used to resolve the name */
  72854. Expr *pExpr /* Make this EXPR node point to the selected column */
  72855. ){
  72856. int i, j; /* Loop counters */
  72857. int cnt = 0; /* Number of matching column names */
  72858. int cntTab = 0; /* Number of matching table names */
  72859. int nSubquery = 0; /* How many levels of subquery */
  72860. sqlite3 *db = pParse->db; /* The database connection */
  72861. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  72862. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  72863. NameContext *pTopNC = pNC; /* First namecontext in the list */
  72864. Schema *pSchema = 0; /* Schema of the expression */
  72865. int isTrigger = 0;
  72866. assert( pNC ); /* the name context cannot be NULL. */
  72867. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  72868. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  72869. /* Initialize the node to no-match */
  72870. pExpr->iTable = -1;
  72871. pExpr->pTab = 0;
  72872. ExprSetVVAProperty(pExpr, EP_NoReduce);
  72873. /* Translate the schema name in zDb into a pointer to the corresponding
  72874. ** schema. If not found, pSchema will remain NULL and nothing will match
  72875. ** resulting in an appropriate error message toward the end of this routine
  72876. */
  72877. if( zDb ){
  72878. testcase( pNC->ncFlags & NC_PartIdx );
  72879. testcase( pNC->ncFlags & NC_IsCheck );
  72880. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  72881. /* Silently ignore database qualifiers inside CHECK constraints and partial
  72882. ** indices. Do not raise errors because that might break legacy and
  72883. ** because it does not hurt anything to just ignore the database name. */
  72884. zDb = 0;
  72885. }else{
  72886. for(i=0; i<db->nDb; i++){
  72887. assert( db->aDb[i].zName );
  72888. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  72889. pSchema = db->aDb[i].pSchema;
  72890. break;
  72891. }
  72892. }
  72893. }
  72894. }
  72895. /* Start at the inner-most context and move outward until a match is found */
  72896. while( pNC && cnt==0 ){
  72897. ExprList *pEList;
  72898. SrcList *pSrcList = pNC->pSrcList;
  72899. if( pSrcList ){
  72900. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  72901. Table *pTab;
  72902. Column *pCol;
  72903. pTab = pItem->pTab;
  72904. assert( pTab!=0 && pTab->zName!=0 );
  72905. assert( pTab->nCol>0 );
  72906. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  72907. int hit = 0;
  72908. pEList = pItem->pSelect->pEList;
  72909. for(j=0; j<pEList->nExpr; j++){
  72910. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  72911. cnt++;
  72912. cntTab = 2;
  72913. pMatch = pItem;
  72914. pExpr->iColumn = j;
  72915. hit = 1;
  72916. }
  72917. }
  72918. if( hit || zTab==0 ) continue;
  72919. }
  72920. if( zDb && pTab->pSchema!=pSchema ){
  72921. continue;
  72922. }
  72923. if( zTab ){
  72924. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  72925. assert( zTabName!=0 );
  72926. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  72927. continue;
  72928. }
  72929. }
  72930. if( 0==(cntTab++) ){
  72931. pMatch = pItem;
  72932. }
  72933. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  72934. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  72935. /* If there has been exactly one prior match and this match
  72936. ** is for the right-hand table of a NATURAL JOIN or is in a
  72937. ** USING clause, then skip this match.
  72938. */
  72939. if( cnt==1 ){
  72940. if( pItem->jointype & JT_NATURAL ) continue;
  72941. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  72942. }
  72943. cnt++;
  72944. pMatch = pItem;
  72945. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  72946. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  72947. break;
  72948. }
  72949. }
  72950. }
  72951. if( pMatch ){
  72952. pExpr->iTable = pMatch->iCursor;
  72953. pExpr->pTab = pMatch->pTab;
  72954. pSchema = pExpr->pTab->pSchema;
  72955. }
  72956. } /* if( pSrcList ) */
  72957. #ifndef SQLITE_OMIT_TRIGGER
  72958. /* If we have not already resolved the name, then maybe
  72959. ** it is a new.* or old.* trigger argument reference
  72960. */
  72961. if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
  72962. int op = pParse->eTriggerOp;
  72963. Table *pTab = 0;
  72964. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  72965. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  72966. pExpr->iTable = 1;
  72967. pTab = pParse->pTriggerTab;
  72968. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  72969. pExpr->iTable = 0;
  72970. pTab = pParse->pTriggerTab;
  72971. }
  72972. if( pTab ){
  72973. int iCol;
  72974. pSchema = pTab->pSchema;
  72975. cntTab++;
  72976. for(iCol=0; iCol<pTab->nCol; iCol++){
  72977. Column *pCol = &pTab->aCol[iCol];
  72978. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  72979. if( iCol==pTab->iPKey ){
  72980. iCol = -1;
  72981. }
  72982. break;
  72983. }
  72984. }
  72985. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
  72986. iCol = -1; /* IMP: R-44911-55124 */
  72987. }
  72988. if( iCol<pTab->nCol ){
  72989. cnt++;
  72990. if( iCol<0 ){
  72991. pExpr->affinity = SQLITE_AFF_INTEGER;
  72992. }else if( pExpr->iTable==0 ){
  72993. testcase( iCol==31 );
  72994. testcase( iCol==32 );
  72995. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  72996. }else{
  72997. testcase( iCol==31 );
  72998. testcase( iCol==32 );
  72999. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  73000. }
  73001. pExpr->iColumn = (i16)iCol;
  73002. pExpr->pTab = pTab;
  73003. isTrigger = 1;
  73004. }
  73005. }
  73006. }
  73007. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  73008. /*
  73009. ** Perhaps the name is a reference to the ROWID
  73010. */
  73011. if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
  73012. cnt = 1;
  73013. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  73014. pExpr->affinity = SQLITE_AFF_INTEGER;
  73015. }
  73016. /*
  73017. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  73018. ** might refer to an result-set alias. This happens, for example, when
  73019. ** we are resolving names in the WHERE clause of the following command:
  73020. **
  73021. ** SELECT a+b AS x FROM table WHERE x<10;
  73022. **
  73023. ** In cases like this, replace pExpr with a copy of the expression that
  73024. ** forms the result set entry ("a+b" in the example) and return immediately.
  73025. ** Note that the expression in the result set should have already been
  73026. ** resolved by the time the WHERE clause is resolved.
  73027. **
  73028. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  73029. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  73030. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  73031. ** is supported for backwards compatibility only. TO DO: Issue a warning
  73032. ** on sqlite3_log() whenever the capability is used.
  73033. */
  73034. if( (pEList = pNC->pEList)!=0
  73035. && zTab==0
  73036. && cnt==0
  73037. ){
  73038. for(j=0; j<pEList->nExpr; j++){
  73039. char *zAs = pEList->a[j].zName;
  73040. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  73041. Expr *pOrig;
  73042. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  73043. assert( pExpr->x.pList==0 );
  73044. assert( pExpr->x.pSelect==0 );
  73045. pOrig = pEList->a[j].pExpr;
  73046. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  73047. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  73048. return WRC_Abort;
  73049. }
  73050. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  73051. cnt = 1;
  73052. pMatch = 0;
  73053. assert( zTab==0 && zDb==0 );
  73054. goto lookupname_end;
  73055. }
  73056. }
  73057. }
  73058. /* Advance to the next name context. The loop will exit when either
  73059. ** we have a match (cnt>0) or when we run out of name contexts.
  73060. */
  73061. if( cnt==0 ){
  73062. pNC = pNC->pNext;
  73063. nSubquery++;
  73064. }
  73065. }
  73066. /*
  73067. ** If X and Y are NULL (in other words if only the column name Z is
  73068. ** supplied) and the value of Z is enclosed in double-quotes, then
  73069. ** Z is a string literal if it doesn't match any column names. In that
  73070. ** case, we need to return right away and not make any changes to
  73071. ** pExpr.
  73072. **
  73073. ** Because no reference was made to outer contexts, the pNC->nRef
  73074. ** fields are not changed in any context.
  73075. */
  73076. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  73077. pExpr->op = TK_STRING;
  73078. pExpr->pTab = 0;
  73079. return WRC_Prune;
  73080. }
  73081. /*
  73082. ** cnt==0 means there was not match. cnt>1 means there were two or
  73083. ** more matches. Either way, we have an error.
  73084. */
  73085. if( cnt!=1 ){
  73086. const char *zErr;
  73087. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  73088. if( zDb ){
  73089. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  73090. }else if( zTab ){
  73091. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  73092. }else{
  73093. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  73094. }
  73095. pParse->checkSchema = 1;
  73096. pTopNC->nErr++;
  73097. }
  73098. /* If a column from a table in pSrcList is referenced, then record
  73099. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  73100. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  73101. ** column number is greater than the number of bits in the bitmask
  73102. ** then set the high-order bit of the bitmask.
  73103. */
  73104. if( pExpr->iColumn>=0 && pMatch!=0 ){
  73105. int n = pExpr->iColumn;
  73106. testcase( n==BMS-1 );
  73107. if( n>=BMS ){
  73108. n = BMS-1;
  73109. }
  73110. assert( pMatch->iCursor==pExpr->iTable );
  73111. pMatch->colUsed |= ((Bitmask)1)<<n;
  73112. }
  73113. /* Clean up and return
  73114. */
  73115. sqlite3ExprDelete(db, pExpr->pLeft);
  73116. pExpr->pLeft = 0;
  73117. sqlite3ExprDelete(db, pExpr->pRight);
  73118. pExpr->pRight = 0;
  73119. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  73120. lookupname_end:
  73121. if( cnt==1 ){
  73122. assert( pNC!=0 );
  73123. if( pExpr->op!=TK_AS ){
  73124. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  73125. }
  73126. /* Increment the nRef value on all name contexts from TopNC up to
  73127. ** the point where the name matched. */
  73128. for(;;){
  73129. assert( pTopNC!=0 );
  73130. pTopNC->nRef++;
  73131. if( pTopNC==pNC ) break;
  73132. pTopNC = pTopNC->pNext;
  73133. }
  73134. return WRC_Prune;
  73135. } else {
  73136. return WRC_Abort;
  73137. }
  73138. }
  73139. /*
  73140. ** Allocate and return a pointer to an expression to load the column iCol
  73141. ** from datasource iSrc in SrcList pSrc.
  73142. */
  73143. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  73144. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  73145. if( p ){
  73146. struct SrcList_item *pItem = &pSrc->a[iSrc];
  73147. p->pTab = pItem->pTab;
  73148. p->iTable = pItem->iCursor;
  73149. if( p->pTab->iPKey==iCol ){
  73150. p->iColumn = -1;
  73151. }else{
  73152. p->iColumn = (ynVar)iCol;
  73153. testcase( iCol==BMS );
  73154. testcase( iCol==BMS-1 );
  73155. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  73156. }
  73157. ExprSetProperty(p, EP_Resolved);
  73158. }
  73159. return p;
  73160. }
  73161. /*
  73162. ** Report an error that an expression is not valid for a partial index WHERE
  73163. ** clause.
  73164. */
  73165. static void notValidPartIdxWhere(
  73166. Parse *pParse, /* Leave error message here */
  73167. NameContext *pNC, /* The name context */
  73168. const char *zMsg /* Type of error */
  73169. ){
  73170. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  73171. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  73172. zMsg);
  73173. }
  73174. }
  73175. #ifndef SQLITE_OMIT_CHECK
  73176. /*
  73177. ** Report an error that an expression is not valid for a CHECK constraint.
  73178. */
  73179. static void notValidCheckConstraint(
  73180. Parse *pParse, /* Leave error message here */
  73181. NameContext *pNC, /* The name context */
  73182. const char *zMsg /* Type of error */
  73183. ){
  73184. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  73185. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  73186. }
  73187. }
  73188. #else
  73189. # define notValidCheckConstraint(P,N,M)
  73190. #endif
  73191. /*
  73192. ** Expression p should encode a floating point value between 1.0 and 0.0.
  73193. ** Return 1024 times this value. Or return -1 if p is not a floating point
  73194. ** value between 1.0 and 0.0.
  73195. */
  73196. static int exprProbability(Expr *p){
  73197. double r = -1.0;
  73198. if( p->op!=TK_FLOAT ) return -1;
  73199. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  73200. assert( r>=0.0 );
  73201. if( r>1.0 ) return -1;
  73202. return (int)(r*1000.0);
  73203. }
  73204. /*
  73205. ** This routine is callback for sqlite3WalkExpr().
  73206. **
  73207. ** Resolve symbolic names into TK_COLUMN operators for the current
  73208. ** node in the expression tree. Return 0 to continue the search down
  73209. ** the tree or 2 to abort the tree walk.
  73210. **
  73211. ** This routine also does error checking and name resolution for
  73212. ** function names. The operator for aggregate functions is changed
  73213. ** to TK_AGG_FUNCTION.
  73214. */
  73215. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  73216. NameContext *pNC;
  73217. Parse *pParse;
  73218. pNC = pWalker->u.pNC;
  73219. assert( pNC!=0 );
  73220. pParse = pNC->pParse;
  73221. assert( pParse==pWalker->pParse );
  73222. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  73223. ExprSetProperty(pExpr, EP_Resolved);
  73224. #ifndef NDEBUG
  73225. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  73226. SrcList *pSrcList = pNC->pSrcList;
  73227. int i;
  73228. for(i=0; i<pNC->pSrcList->nSrc; i++){
  73229. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  73230. }
  73231. }
  73232. #endif
  73233. switch( pExpr->op ){
  73234. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  73235. /* The special operator TK_ROW means use the rowid for the first
  73236. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  73237. ** clause processing on UPDATE and DELETE statements.
  73238. */
  73239. case TK_ROW: {
  73240. SrcList *pSrcList = pNC->pSrcList;
  73241. struct SrcList_item *pItem;
  73242. assert( pSrcList && pSrcList->nSrc==1 );
  73243. pItem = pSrcList->a;
  73244. pExpr->op = TK_COLUMN;
  73245. pExpr->pTab = pItem->pTab;
  73246. pExpr->iTable = pItem->iCursor;
  73247. pExpr->iColumn = -1;
  73248. pExpr->affinity = SQLITE_AFF_INTEGER;
  73249. break;
  73250. }
  73251. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  73252. /* A lone identifier is the name of a column.
  73253. */
  73254. case TK_ID: {
  73255. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  73256. }
  73257. /* A table name and column name: ID.ID
  73258. ** Or a database, table and column: ID.ID.ID
  73259. */
  73260. case TK_DOT: {
  73261. const char *zColumn;
  73262. const char *zTable;
  73263. const char *zDb;
  73264. Expr *pRight;
  73265. /* if( pSrcList==0 ) break; */
  73266. pRight = pExpr->pRight;
  73267. if( pRight->op==TK_ID ){
  73268. zDb = 0;
  73269. zTable = pExpr->pLeft->u.zToken;
  73270. zColumn = pRight->u.zToken;
  73271. }else{
  73272. assert( pRight->op==TK_DOT );
  73273. zDb = pExpr->pLeft->u.zToken;
  73274. zTable = pRight->pLeft->u.zToken;
  73275. zColumn = pRight->pRight->u.zToken;
  73276. }
  73277. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  73278. }
  73279. /* Resolve function names
  73280. */
  73281. case TK_CONST_FUNC:
  73282. case TK_FUNCTION: {
  73283. ExprList *pList = pExpr->x.pList; /* The argument list */
  73284. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  73285. int no_such_func = 0; /* True if no such function exists */
  73286. int wrong_num_args = 0; /* True if wrong number of arguments */
  73287. int is_agg = 0; /* True if is an aggregate function */
  73288. int auth; /* Authorization to use the function */
  73289. int nId; /* Number of characters in function name */
  73290. const char *zId; /* The function name. */
  73291. FuncDef *pDef; /* Information about the function */
  73292. u8 enc = ENC(pParse->db); /* The database encoding */
  73293. testcase( pExpr->op==TK_CONST_FUNC );
  73294. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  73295. notValidPartIdxWhere(pParse, pNC, "functions");
  73296. zId = pExpr->u.zToken;
  73297. nId = sqlite3Strlen30(zId);
  73298. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  73299. if( pDef==0 ){
  73300. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  73301. if( pDef==0 ){
  73302. no_such_func = 1;
  73303. }else{
  73304. wrong_num_args = 1;
  73305. }
  73306. }else{
  73307. is_agg = pDef->xFunc==0;
  73308. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  73309. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  73310. if( n==2 ){
  73311. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  73312. if( pExpr->iTable<0 ){
  73313. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  73314. "constant between 0.0 and 1.0");
  73315. pNC->nErr++;
  73316. }
  73317. }else{
  73318. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  73319. ** likelihood(X, 0.0625).
  73320. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  73321. ** likelihood(X,0.0625). */
  73322. pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
  73323. }
  73324. }
  73325. }
  73326. #ifndef SQLITE_OMIT_AUTHORIZATION
  73327. if( pDef ){
  73328. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  73329. if( auth!=SQLITE_OK ){
  73330. if( auth==SQLITE_DENY ){
  73331. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  73332. pDef->zName);
  73333. pNC->nErr++;
  73334. }
  73335. pExpr->op = TK_NULL;
  73336. return WRC_Prune;
  73337. }
  73338. }
  73339. #endif
  73340. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  73341. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  73342. pNC->nErr++;
  73343. is_agg = 0;
  73344. }else if( no_such_func && pParse->db->init.busy==0 ){
  73345. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  73346. pNC->nErr++;
  73347. }else if( wrong_num_args ){
  73348. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  73349. nId, zId);
  73350. pNC->nErr++;
  73351. }
  73352. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  73353. sqlite3WalkExprList(pWalker, pList);
  73354. if( is_agg ){
  73355. NameContext *pNC2 = pNC;
  73356. pExpr->op = TK_AGG_FUNCTION;
  73357. pExpr->op2 = 0;
  73358. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  73359. pExpr->op2++;
  73360. pNC2 = pNC2->pNext;
  73361. }
  73362. if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
  73363. pNC->ncFlags |= NC_AllowAgg;
  73364. }
  73365. /* FIX ME: Compute pExpr->affinity based on the expected return
  73366. ** type of the function
  73367. */
  73368. return WRC_Prune;
  73369. }
  73370. #ifndef SQLITE_OMIT_SUBQUERY
  73371. case TK_SELECT:
  73372. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  73373. #endif
  73374. case TK_IN: {
  73375. testcase( pExpr->op==TK_IN );
  73376. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  73377. int nRef = pNC->nRef;
  73378. notValidCheckConstraint(pParse, pNC, "subqueries");
  73379. notValidPartIdxWhere(pParse, pNC, "subqueries");
  73380. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  73381. assert( pNC->nRef>=nRef );
  73382. if( nRef!=pNC->nRef ){
  73383. ExprSetProperty(pExpr, EP_VarSelect);
  73384. }
  73385. }
  73386. break;
  73387. }
  73388. case TK_VARIABLE: {
  73389. notValidCheckConstraint(pParse, pNC, "parameters");
  73390. notValidPartIdxWhere(pParse, pNC, "parameters");
  73391. break;
  73392. }
  73393. }
  73394. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  73395. }
  73396. /*
  73397. ** pEList is a list of expressions which are really the result set of the
  73398. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  73399. ** This routine checks to see if pE is a simple identifier which corresponds
  73400. ** to the AS-name of one of the terms of the expression list. If it is,
  73401. ** this routine return an integer between 1 and N where N is the number of
  73402. ** elements in pEList, corresponding to the matching entry. If there is
  73403. ** no match, or if pE is not a simple identifier, then this routine
  73404. ** return 0.
  73405. **
  73406. ** pEList has been resolved. pE has not.
  73407. */
  73408. static int resolveAsName(
  73409. Parse *pParse, /* Parsing context for error messages */
  73410. ExprList *pEList, /* List of expressions to scan */
  73411. Expr *pE /* Expression we are trying to match */
  73412. ){
  73413. int i; /* Loop counter */
  73414. UNUSED_PARAMETER(pParse);
  73415. if( pE->op==TK_ID ){
  73416. char *zCol = pE->u.zToken;
  73417. for(i=0; i<pEList->nExpr; i++){
  73418. char *zAs = pEList->a[i].zName;
  73419. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  73420. return i+1;
  73421. }
  73422. }
  73423. }
  73424. return 0;
  73425. }
  73426. /*
  73427. ** pE is a pointer to an expression which is a single term in the
  73428. ** ORDER BY of a compound SELECT. The expression has not been
  73429. ** name resolved.
  73430. **
  73431. ** At the point this routine is called, we already know that the
  73432. ** ORDER BY term is not an integer index into the result set. That
  73433. ** case is handled by the calling routine.
  73434. **
  73435. ** Attempt to match pE against result set columns in the left-most
  73436. ** SELECT statement. Return the index i of the matching column,
  73437. ** as an indication to the caller that it should sort by the i-th column.
  73438. ** The left-most column is 1. In other words, the value returned is the
  73439. ** same integer value that would be used in the SQL statement to indicate
  73440. ** the column.
  73441. **
  73442. ** If there is no match, return 0. Return -1 if an error occurs.
  73443. */
  73444. static int resolveOrderByTermToExprList(
  73445. Parse *pParse, /* Parsing context for error messages */
  73446. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  73447. Expr *pE /* The specific ORDER BY term */
  73448. ){
  73449. int i; /* Loop counter */
  73450. ExprList *pEList; /* The columns of the result set */
  73451. NameContext nc; /* Name context for resolving pE */
  73452. sqlite3 *db; /* Database connection */
  73453. int rc; /* Return code from subprocedures */
  73454. u8 savedSuppErr; /* Saved value of db->suppressErr */
  73455. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  73456. pEList = pSelect->pEList;
  73457. /* Resolve all names in the ORDER BY term expression
  73458. */
  73459. memset(&nc, 0, sizeof(nc));
  73460. nc.pParse = pParse;
  73461. nc.pSrcList = pSelect->pSrc;
  73462. nc.pEList = pEList;
  73463. nc.ncFlags = NC_AllowAgg;
  73464. nc.nErr = 0;
  73465. db = pParse->db;
  73466. savedSuppErr = db->suppressErr;
  73467. db->suppressErr = 1;
  73468. rc = sqlite3ResolveExprNames(&nc, pE);
  73469. db->suppressErr = savedSuppErr;
  73470. if( rc ) return 0;
  73471. /* Try to match the ORDER BY expression against an expression
  73472. ** in the result set. Return an 1-based index of the matching
  73473. ** result-set entry.
  73474. */
  73475. for(i=0; i<pEList->nExpr; i++){
  73476. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  73477. return i+1;
  73478. }
  73479. }
  73480. /* If no match, return 0. */
  73481. return 0;
  73482. }
  73483. /*
  73484. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  73485. */
  73486. static void resolveOutOfRangeError(
  73487. Parse *pParse, /* The error context into which to write the error */
  73488. const char *zType, /* "ORDER" or "GROUP" */
  73489. int i, /* The index (1-based) of the term out of range */
  73490. int mx /* Largest permissible value of i */
  73491. ){
  73492. sqlite3ErrorMsg(pParse,
  73493. "%r %s BY term out of range - should be "
  73494. "between 1 and %d", i, zType, mx);
  73495. }
  73496. /*
  73497. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  73498. ** each term of the ORDER BY clause is a constant integer between 1
  73499. ** and N where N is the number of columns in the compound SELECT.
  73500. **
  73501. ** ORDER BY terms that are already an integer between 1 and N are
  73502. ** unmodified. ORDER BY terms that are integers outside the range of
  73503. ** 1 through N generate an error. ORDER BY terms that are expressions
  73504. ** are matched against result set expressions of compound SELECT
  73505. ** beginning with the left-most SELECT and working toward the right.
  73506. ** At the first match, the ORDER BY expression is transformed into
  73507. ** the integer column number.
  73508. **
  73509. ** Return the number of errors seen.
  73510. */
  73511. static int resolveCompoundOrderBy(
  73512. Parse *pParse, /* Parsing context. Leave error messages here */
  73513. Select *pSelect /* The SELECT statement containing the ORDER BY */
  73514. ){
  73515. int i;
  73516. ExprList *pOrderBy;
  73517. ExprList *pEList;
  73518. sqlite3 *db;
  73519. int moreToDo = 1;
  73520. pOrderBy = pSelect->pOrderBy;
  73521. if( pOrderBy==0 ) return 0;
  73522. db = pParse->db;
  73523. #if SQLITE_MAX_COLUMN
  73524. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  73525. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  73526. return 1;
  73527. }
  73528. #endif
  73529. for(i=0; i<pOrderBy->nExpr; i++){
  73530. pOrderBy->a[i].done = 0;
  73531. }
  73532. pSelect->pNext = 0;
  73533. while( pSelect->pPrior ){
  73534. pSelect->pPrior->pNext = pSelect;
  73535. pSelect = pSelect->pPrior;
  73536. }
  73537. while( pSelect && moreToDo ){
  73538. struct ExprList_item *pItem;
  73539. moreToDo = 0;
  73540. pEList = pSelect->pEList;
  73541. assert( pEList!=0 );
  73542. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73543. int iCol = -1;
  73544. Expr *pE, *pDup;
  73545. if( pItem->done ) continue;
  73546. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  73547. if( sqlite3ExprIsInteger(pE, &iCol) ){
  73548. if( iCol<=0 || iCol>pEList->nExpr ){
  73549. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  73550. return 1;
  73551. }
  73552. }else{
  73553. iCol = resolveAsName(pParse, pEList, pE);
  73554. if( iCol==0 ){
  73555. pDup = sqlite3ExprDup(db, pE, 0);
  73556. if( !db->mallocFailed ){
  73557. assert(pDup);
  73558. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  73559. }
  73560. sqlite3ExprDelete(db, pDup);
  73561. }
  73562. }
  73563. if( iCol>0 ){
  73564. /* Convert the ORDER BY term into an integer column number iCol,
  73565. ** taking care to preserve the COLLATE clause if it exists */
  73566. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  73567. if( pNew==0 ) return 1;
  73568. pNew->flags |= EP_IntValue;
  73569. pNew->u.iValue = iCol;
  73570. if( pItem->pExpr==pE ){
  73571. pItem->pExpr = pNew;
  73572. }else{
  73573. assert( pItem->pExpr->op==TK_COLLATE );
  73574. assert( pItem->pExpr->pLeft==pE );
  73575. pItem->pExpr->pLeft = pNew;
  73576. }
  73577. sqlite3ExprDelete(db, pE);
  73578. pItem->iOrderByCol = (u16)iCol;
  73579. pItem->done = 1;
  73580. }else{
  73581. moreToDo = 1;
  73582. }
  73583. }
  73584. pSelect = pSelect->pNext;
  73585. }
  73586. for(i=0; i<pOrderBy->nExpr; i++){
  73587. if( pOrderBy->a[i].done==0 ){
  73588. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  73589. "column in the result set", i+1);
  73590. return 1;
  73591. }
  73592. }
  73593. return 0;
  73594. }
  73595. /*
  73596. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  73597. ** the SELECT statement pSelect. If any term is reference to a
  73598. ** result set expression (as determined by the ExprList.a.iOrderByCol field)
  73599. ** then convert that term into a copy of the corresponding result set
  73600. ** column.
  73601. **
  73602. ** If any errors are detected, add an error message to pParse and
  73603. ** return non-zero. Return zero if no errors are seen.
  73604. */
  73605. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  73606. Parse *pParse, /* Parsing context. Leave error messages here */
  73607. Select *pSelect, /* The SELECT statement containing the clause */
  73608. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  73609. const char *zType /* "ORDER" or "GROUP" */
  73610. ){
  73611. int i;
  73612. sqlite3 *db = pParse->db;
  73613. ExprList *pEList;
  73614. struct ExprList_item *pItem;
  73615. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  73616. #if SQLITE_MAX_COLUMN
  73617. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  73618. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  73619. return 1;
  73620. }
  73621. #endif
  73622. pEList = pSelect->pEList;
  73623. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  73624. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73625. if( pItem->iOrderByCol ){
  73626. if( pItem->iOrderByCol>pEList->nExpr ){
  73627. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  73628. return 1;
  73629. }
  73630. resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
  73631. }
  73632. }
  73633. return 0;
  73634. }
  73635. /*
  73636. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  73637. ** The Name context of the SELECT statement is pNC. zType is either
  73638. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  73639. **
  73640. ** This routine resolves each term of the clause into an expression.
  73641. ** If the order-by term is an integer I between 1 and N (where N is the
  73642. ** number of columns in the result set of the SELECT) then the expression
  73643. ** in the resolution is a copy of the I-th result-set expression. If
  73644. ** the order-by term is an identifier that corresponds to the AS-name of
  73645. ** a result-set expression, then the term resolves to a copy of the
  73646. ** result-set expression. Otherwise, the expression is resolved in
  73647. ** the usual way - using sqlite3ResolveExprNames().
  73648. **
  73649. ** This routine returns the number of errors. If errors occur, then
  73650. ** an appropriate error message might be left in pParse. (OOM errors
  73651. ** excepted.)
  73652. */
  73653. static int resolveOrderGroupBy(
  73654. NameContext *pNC, /* The name context of the SELECT statement */
  73655. Select *pSelect, /* The SELECT statement holding pOrderBy */
  73656. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  73657. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  73658. ){
  73659. int i, j; /* Loop counters */
  73660. int iCol; /* Column number */
  73661. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  73662. Parse *pParse; /* Parsing context */
  73663. int nResult; /* Number of terms in the result set */
  73664. if( pOrderBy==0 ) return 0;
  73665. nResult = pSelect->pEList->nExpr;
  73666. pParse = pNC->pParse;
  73667. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  73668. Expr *pE = pItem->pExpr;
  73669. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  73670. if( zType[0]!='G' ){
  73671. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  73672. if( iCol>0 ){
  73673. /* If an AS-name match is found, mark this ORDER BY column as being
  73674. ** a copy of the iCol-th result-set column. The subsequent call to
  73675. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  73676. ** copy of the iCol-th result-set expression. */
  73677. pItem->iOrderByCol = (u16)iCol;
  73678. continue;
  73679. }
  73680. }
  73681. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  73682. /* The ORDER BY term is an integer constant. Again, set the column
  73683. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  73684. ** order-by term to a copy of the result-set expression */
  73685. if( iCol<1 || iCol>0xffff ){
  73686. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  73687. return 1;
  73688. }
  73689. pItem->iOrderByCol = (u16)iCol;
  73690. continue;
  73691. }
  73692. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  73693. pItem->iOrderByCol = 0;
  73694. if( sqlite3ResolveExprNames(pNC, pE) ){
  73695. return 1;
  73696. }
  73697. for(j=0; j<pSelect->pEList->nExpr; j++){
  73698. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  73699. pItem->iOrderByCol = j+1;
  73700. }
  73701. }
  73702. }
  73703. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  73704. }
  73705. /*
  73706. ** Resolve names in the SELECT statement p and all of its descendents.
  73707. */
  73708. static int resolveSelectStep(Walker *pWalker, Select *p){
  73709. NameContext *pOuterNC; /* Context that contains this SELECT */
  73710. NameContext sNC; /* Name context of this SELECT */
  73711. int isCompound; /* True if p is a compound select */
  73712. int nCompound; /* Number of compound terms processed so far */
  73713. Parse *pParse; /* Parsing context */
  73714. ExprList *pEList; /* Result set expression list */
  73715. int i; /* Loop counter */
  73716. ExprList *pGroupBy; /* The GROUP BY clause */
  73717. Select *pLeftmost; /* Left-most of SELECT of a compound */
  73718. sqlite3 *db; /* Database connection */
  73719. assert( p!=0 );
  73720. if( p->selFlags & SF_Resolved ){
  73721. return WRC_Prune;
  73722. }
  73723. pOuterNC = pWalker->u.pNC;
  73724. pParse = pWalker->pParse;
  73725. db = pParse->db;
  73726. /* Normally sqlite3SelectExpand() will be called first and will have
  73727. ** already expanded this SELECT. However, if this is a subquery within
  73728. ** an expression, sqlite3ResolveExprNames() will be called without a
  73729. ** prior call to sqlite3SelectExpand(). When that happens, let
  73730. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  73731. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  73732. ** this routine in the correct order.
  73733. */
  73734. if( (p->selFlags & SF_Expanded)==0 ){
  73735. sqlite3SelectPrep(pParse, p, pOuterNC);
  73736. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  73737. }
  73738. isCompound = p->pPrior!=0;
  73739. nCompound = 0;
  73740. pLeftmost = p;
  73741. while( p ){
  73742. assert( (p->selFlags & SF_Expanded)!=0 );
  73743. assert( (p->selFlags & SF_Resolved)==0 );
  73744. p->selFlags |= SF_Resolved;
  73745. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  73746. ** are not allowed to refer to any names, so pass an empty NameContext.
  73747. */
  73748. memset(&sNC, 0, sizeof(sNC));
  73749. sNC.pParse = pParse;
  73750. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  73751. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  73752. return WRC_Abort;
  73753. }
  73754. /* Recursively resolve names in all subqueries
  73755. */
  73756. for(i=0; i<p->pSrc->nSrc; i++){
  73757. struct SrcList_item *pItem = &p->pSrc->a[i];
  73758. if( pItem->pSelect ){
  73759. NameContext *pNC; /* Used to iterate name contexts */
  73760. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  73761. const char *zSavedContext = pParse->zAuthContext;
  73762. /* Count the total number of references to pOuterNC and all of its
  73763. ** parent contexts. After resolving references to expressions in
  73764. ** pItem->pSelect, check if this value has changed. If so, then
  73765. ** SELECT statement pItem->pSelect must be correlated. Set the
  73766. ** pItem->isCorrelated flag if this is the case. */
  73767. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  73768. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  73769. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  73770. pParse->zAuthContext = zSavedContext;
  73771. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  73772. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  73773. assert( pItem->isCorrelated==0 && nRef<=0 );
  73774. pItem->isCorrelated = (nRef!=0);
  73775. }
  73776. }
  73777. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  73778. ** resolve the result-set expression list.
  73779. */
  73780. sNC.ncFlags = NC_AllowAgg;
  73781. sNC.pSrcList = p->pSrc;
  73782. sNC.pNext = pOuterNC;
  73783. /* Resolve names in the result set. */
  73784. pEList = p->pEList;
  73785. assert( pEList!=0 );
  73786. for(i=0; i<pEList->nExpr; i++){
  73787. Expr *pX = pEList->a[i].pExpr;
  73788. if( sqlite3ResolveExprNames(&sNC, pX) ){
  73789. return WRC_Abort;
  73790. }
  73791. }
  73792. /* If there are no aggregate functions in the result-set, and no GROUP BY
  73793. ** expression, do not allow aggregates in any of the other expressions.
  73794. */
  73795. assert( (p->selFlags & SF_Aggregate)==0 );
  73796. pGroupBy = p->pGroupBy;
  73797. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  73798. p->selFlags |= SF_Aggregate;
  73799. }else{
  73800. sNC.ncFlags &= ~NC_AllowAgg;
  73801. }
  73802. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  73803. */
  73804. if( p->pHaving && !pGroupBy ){
  73805. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  73806. return WRC_Abort;
  73807. }
  73808. /* Add the output column list to the name-context before parsing the
  73809. ** other expressions in the SELECT statement. This is so that
  73810. ** expressions in the WHERE clause (etc.) can refer to expressions by
  73811. ** aliases in the result set.
  73812. **
  73813. ** Minor point: If this is the case, then the expression will be
  73814. ** re-evaluated for each reference to it.
  73815. */
  73816. sNC.pEList = p->pEList;
  73817. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  73818. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  73819. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  73820. ** outer queries
  73821. */
  73822. sNC.pNext = 0;
  73823. sNC.ncFlags |= NC_AllowAgg;
  73824. /* Process the ORDER BY clause for singleton SELECT statements.
  73825. ** The ORDER BY clause for compounds SELECT statements is handled
  73826. ** below, after all of the result-sets for all of the elements of
  73827. ** the compound have been resolved.
  73828. */
  73829. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  73830. return WRC_Abort;
  73831. }
  73832. if( db->mallocFailed ){
  73833. return WRC_Abort;
  73834. }
  73835. /* Resolve the GROUP BY clause. At the same time, make sure
  73836. ** the GROUP BY clause does not contain aggregate functions.
  73837. */
  73838. if( pGroupBy ){
  73839. struct ExprList_item *pItem;
  73840. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  73841. return WRC_Abort;
  73842. }
  73843. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  73844. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  73845. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  73846. "the GROUP BY clause");
  73847. return WRC_Abort;
  73848. }
  73849. }
  73850. }
  73851. /* Advance to the next term of the compound
  73852. */
  73853. p = p->pPrior;
  73854. nCompound++;
  73855. }
  73856. /* Resolve the ORDER BY on a compound SELECT after all terms of
  73857. ** the compound have been resolved.
  73858. */
  73859. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  73860. return WRC_Abort;
  73861. }
  73862. return WRC_Prune;
  73863. }
  73864. /*
  73865. ** This routine walks an expression tree and resolves references to
  73866. ** table columns and result-set columns. At the same time, do error
  73867. ** checking on function usage and set a flag if any aggregate functions
  73868. ** are seen.
  73869. **
  73870. ** To resolve table columns references we look for nodes (or subtrees) of the
  73871. ** form X.Y.Z or Y.Z or just Z where
  73872. **
  73873. ** X: The name of a database. Ex: "main" or "temp" or
  73874. ** the symbolic name assigned to an ATTACH-ed database.
  73875. **
  73876. ** Y: The name of a table in a FROM clause. Or in a trigger
  73877. ** one of the special names "old" or "new".
  73878. **
  73879. ** Z: The name of a column in table Y.
  73880. **
  73881. ** The node at the root of the subtree is modified as follows:
  73882. **
  73883. ** Expr.op Changed to TK_COLUMN
  73884. ** Expr.pTab Points to the Table object for X.Y
  73885. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  73886. ** Expr.iTable The VDBE cursor number for X.Y
  73887. **
  73888. **
  73889. ** To resolve result-set references, look for expression nodes of the
  73890. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  73891. ** size of an AS clause in the result-set of a SELECT. The Z expression
  73892. ** is replaced by a copy of the left-hand side of the result-set expression.
  73893. ** Table-name and function resolution occurs on the substituted expression
  73894. ** tree. For example, in:
  73895. **
  73896. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  73897. **
  73898. ** The "x" term of the order by is replaced by "a+b" to render:
  73899. **
  73900. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  73901. **
  73902. ** Function calls are checked to make sure that the function is
  73903. ** defined and that the correct number of arguments are specified.
  73904. ** If the function is an aggregate function, then the NC_HasAgg flag is
  73905. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  73906. ** If an expression contains aggregate functions then the EP_Agg
  73907. ** property on the expression is set.
  73908. **
  73909. ** An error message is left in pParse if anything is amiss. The number
  73910. ** if errors is returned.
  73911. */
  73912. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  73913. NameContext *pNC, /* Namespace to resolve expressions in. */
  73914. Expr *pExpr /* The expression to be analyzed. */
  73915. ){
  73916. u8 savedHasAgg;
  73917. Walker w;
  73918. if( pExpr==0 ) return 0;
  73919. #if SQLITE_MAX_EXPR_DEPTH>0
  73920. {
  73921. Parse *pParse = pNC->pParse;
  73922. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  73923. return 1;
  73924. }
  73925. pParse->nHeight += pExpr->nHeight;
  73926. }
  73927. #endif
  73928. savedHasAgg = pNC->ncFlags & NC_HasAgg;
  73929. pNC->ncFlags &= ~NC_HasAgg;
  73930. memset(&w, 0, sizeof(w));
  73931. w.xExprCallback = resolveExprStep;
  73932. w.xSelectCallback = resolveSelectStep;
  73933. w.pParse = pNC->pParse;
  73934. w.u.pNC = pNC;
  73935. sqlite3WalkExpr(&w, pExpr);
  73936. #if SQLITE_MAX_EXPR_DEPTH>0
  73937. pNC->pParse->nHeight -= pExpr->nHeight;
  73938. #endif
  73939. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  73940. ExprSetProperty(pExpr, EP_Error);
  73941. }
  73942. if( pNC->ncFlags & NC_HasAgg ){
  73943. ExprSetProperty(pExpr, EP_Agg);
  73944. }else if( savedHasAgg ){
  73945. pNC->ncFlags |= NC_HasAgg;
  73946. }
  73947. return ExprHasProperty(pExpr, EP_Error);
  73948. }
  73949. /*
  73950. ** Resolve all names in all expressions of a SELECT and in all
  73951. ** decendents of the SELECT, including compounds off of p->pPrior,
  73952. ** subqueries in expressions, and subqueries used as FROM clause
  73953. ** terms.
  73954. **
  73955. ** See sqlite3ResolveExprNames() for a description of the kinds of
  73956. ** transformations that occur.
  73957. **
  73958. ** All SELECT statements should have been expanded using
  73959. ** sqlite3SelectExpand() prior to invoking this routine.
  73960. */
  73961. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  73962. Parse *pParse, /* The parser context */
  73963. Select *p, /* The SELECT statement being coded. */
  73964. NameContext *pOuterNC /* Name context for parent SELECT statement */
  73965. ){
  73966. Walker w;
  73967. assert( p!=0 );
  73968. memset(&w, 0, sizeof(w));
  73969. w.xExprCallback = resolveExprStep;
  73970. w.xSelectCallback = resolveSelectStep;
  73971. w.pParse = pParse;
  73972. w.u.pNC = pOuterNC;
  73973. sqlite3WalkSelect(&w, p);
  73974. }
  73975. /*
  73976. ** Resolve names in expressions that can only reference a single table:
  73977. **
  73978. ** * CHECK constraints
  73979. ** * WHERE clauses on partial indices
  73980. **
  73981. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  73982. ** is set to -1 and the Expr.iColumn value is set to the column number.
  73983. **
  73984. ** Any errors cause an error message to be set in pParse.
  73985. */
  73986. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  73987. Parse *pParse, /* Parsing context */
  73988. Table *pTab, /* The table being referenced */
  73989. int type, /* NC_IsCheck or NC_PartIdx */
  73990. Expr *pExpr, /* Expression to resolve. May be NULL. */
  73991. ExprList *pList /* Expression list to resolve. May be NUL. */
  73992. ){
  73993. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  73994. NameContext sNC; /* Name context for pParse->pNewTable */
  73995. int i; /* Loop counter */
  73996. assert( type==NC_IsCheck || type==NC_PartIdx );
  73997. memset(&sNC, 0, sizeof(sNC));
  73998. memset(&sSrc, 0, sizeof(sSrc));
  73999. sSrc.nSrc = 1;
  74000. sSrc.a[0].zName = pTab->zName;
  74001. sSrc.a[0].pTab = pTab;
  74002. sSrc.a[0].iCursor = -1;
  74003. sNC.pParse = pParse;
  74004. sNC.pSrcList = &sSrc;
  74005. sNC.ncFlags = type;
  74006. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  74007. if( pList ){
  74008. for(i=0; i<pList->nExpr; i++){
  74009. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  74010. return;
  74011. }
  74012. }
  74013. }
  74014. }
  74015. /************** End of resolve.c *********************************************/
  74016. /************** Begin file expr.c ********************************************/
  74017. /*
  74018. ** 2001 September 15
  74019. **
  74020. ** The author disclaims copyright to this source code. In place of
  74021. ** a legal notice, here is a blessing:
  74022. **
  74023. ** May you do good and not evil.
  74024. ** May you find forgiveness for yourself and forgive others.
  74025. ** May you share freely, never taking more than you give.
  74026. **
  74027. *************************************************************************
  74028. ** This file contains routines used for analyzing expressions and
  74029. ** for generating VDBE code that evaluates expressions in SQLite.
  74030. */
  74031. /*
  74032. ** Return the 'affinity' of the expression pExpr if any.
  74033. **
  74034. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  74035. ** or a sub-select with a column as the return value, then the
  74036. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  74037. ** indicating no affinity for the expression.
  74038. **
  74039. ** i.e. the WHERE clause expresssions in the following statements all
  74040. ** have an affinity:
  74041. **
  74042. ** CREATE TABLE t1(a);
  74043. ** SELECT * FROM t1 WHERE a;
  74044. ** SELECT a AS b FROM t1 WHERE b;
  74045. ** SELECT * FROM t1 WHERE (select a from t1);
  74046. */
  74047. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  74048. int op;
  74049. pExpr = sqlite3ExprSkipCollate(pExpr);
  74050. op = pExpr->op;
  74051. if( op==TK_SELECT ){
  74052. assert( pExpr->flags&EP_xIsSelect );
  74053. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  74054. }
  74055. #ifndef SQLITE_OMIT_CAST
  74056. if( op==TK_CAST ){
  74057. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  74058. return sqlite3AffinityType(pExpr->u.zToken, 0);
  74059. }
  74060. #endif
  74061. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  74062. && pExpr->pTab!=0
  74063. ){
  74064. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  74065. ** a TK_COLUMN but was previously evaluated and cached in a register */
  74066. int j = pExpr->iColumn;
  74067. if( j<0 ) return SQLITE_AFF_INTEGER;
  74068. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  74069. return pExpr->pTab->aCol[j].affinity;
  74070. }
  74071. return pExpr->affinity;
  74072. }
  74073. /*
  74074. ** Set the collating sequence for expression pExpr to be the collating
  74075. ** sequence named by pToken. Return a pointer to a new Expr node that
  74076. ** implements the COLLATE operator.
  74077. **
  74078. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  74079. ** and the pExpr parameter is returned unchanged.
  74080. */
  74081. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr *pExpr, Token *pCollName){
  74082. if( pCollName->n>0 ){
  74083. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  74084. if( pNew ){
  74085. pNew->pLeft = pExpr;
  74086. pNew->flags |= EP_Collate|EP_Skip;
  74087. pExpr = pNew;
  74088. }
  74089. }
  74090. return pExpr;
  74091. }
  74092. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  74093. Token s;
  74094. assert( zC!=0 );
  74095. s.z = zC;
  74096. s.n = sqlite3Strlen30(s.z);
  74097. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  74098. }
  74099. /*
  74100. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  74101. ** or likelihood() function at the root of an expression.
  74102. */
  74103. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  74104. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  74105. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  74106. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74107. assert( pExpr->x.pList->nExpr>0 );
  74108. assert( pExpr->op==TK_FUNCTION );
  74109. pExpr = pExpr->x.pList->a[0].pExpr;
  74110. }else{
  74111. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  74112. pExpr = pExpr->pLeft;
  74113. }
  74114. }
  74115. return pExpr;
  74116. }
  74117. /*
  74118. ** Return the collation sequence for the expression pExpr. If
  74119. ** there is no defined collating sequence, return NULL.
  74120. **
  74121. ** The collating sequence might be determined by a COLLATE operator
  74122. ** or by the presence of a column with a defined collating sequence.
  74123. ** COLLATE operators take first precedence. Left operands take
  74124. ** precedence over right operands.
  74125. */
  74126. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  74127. sqlite3 *db = pParse->db;
  74128. CollSeq *pColl = 0;
  74129. Expr *p = pExpr;
  74130. while( p ){
  74131. int op = p->op;
  74132. if( op==TK_CAST || op==TK_UPLUS ){
  74133. p = p->pLeft;
  74134. continue;
  74135. }
  74136. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  74137. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  74138. break;
  74139. }
  74140. if( p->pTab!=0
  74141. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  74142. || op==TK_REGISTER || op==TK_TRIGGER)
  74143. ){
  74144. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  74145. ** a TK_COLUMN but was previously evaluated and cached in a register */
  74146. int j = p->iColumn;
  74147. if( j>=0 ){
  74148. const char *zColl = p->pTab->aCol[j].zColl;
  74149. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  74150. }
  74151. break;
  74152. }
  74153. if( p->flags & EP_Collate ){
  74154. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  74155. p = p->pLeft;
  74156. }else{
  74157. p = p->pRight;
  74158. }
  74159. }else{
  74160. break;
  74161. }
  74162. }
  74163. if( sqlite3CheckCollSeq(pParse, pColl) ){
  74164. pColl = 0;
  74165. }
  74166. return pColl;
  74167. }
  74168. /*
  74169. ** pExpr is an operand of a comparison operator. aff2 is the
  74170. ** type affinity of the other operand. This routine returns the
  74171. ** type affinity that should be used for the comparison operator.
  74172. */
  74173. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  74174. char aff1 = sqlite3ExprAffinity(pExpr);
  74175. if( aff1 && aff2 ){
  74176. /* Both sides of the comparison are columns. If one has numeric
  74177. ** affinity, use that. Otherwise use no affinity.
  74178. */
  74179. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  74180. return SQLITE_AFF_NUMERIC;
  74181. }else{
  74182. return SQLITE_AFF_NONE;
  74183. }
  74184. }else if( !aff1 && !aff2 ){
  74185. /* Neither side of the comparison is a column. Compare the
  74186. ** results directly.
  74187. */
  74188. return SQLITE_AFF_NONE;
  74189. }else{
  74190. /* One side is a column, the other is not. Use the columns affinity. */
  74191. assert( aff1==0 || aff2==0 );
  74192. return (aff1 + aff2);
  74193. }
  74194. }
  74195. /*
  74196. ** pExpr is a comparison operator. Return the type affinity that should
  74197. ** be applied to both operands prior to doing the comparison.
  74198. */
  74199. static char comparisonAffinity(Expr *pExpr){
  74200. char aff;
  74201. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  74202. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  74203. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  74204. assert( pExpr->pLeft );
  74205. aff = sqlite3ExprAffinity(pExpr->pLeft);
  74206. if( pExpr->pRight ){
  74207. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  74208. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74209. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  74210. }else if( !aff ){
  74211. aff = SQLITE_AFF_NONE;
  74212. }
  74213. return aff;
  74214. }
  74215. /*
  74216. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  74217. ** idx_affinity is the affinity of an indexed column. Return true
  74218. ** if the index with affinity idx_affinity may be used to implement
  74219. ** the comparison in pExpr.
  74220. */
  74221. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  74222. char aff = comparisonAffinity(pExpr);
  74223. switch( aff ){
  74224. case SQLITE_AFF_NONE:
  74225. return 1;
  74226. case SQLITE_AFF_TEXT:
  74227. return idx_affinity==SQLITE_AFF_TEXT;
  74228. default:
  74229. return sqlite3IsNumericAffinity(idx_affinity);
  74230. }
  74231. }
  74232. /*
  74233. ** Return the P5 value that should be used for a binary comparison
  74234. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  74235. */
  74236. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  74237. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  74238. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  74239. return aff;
  74240. }
  74241. /*
  74242. ** Return a pointer to the collation sequence that should be used by
  74243. ** a binary comparison operator comparing pLeft and pRight.
  74244. **
  74245. ** If the left hand expression has a collating sequence type, then it is
  74246. ** used. Otherwise the collation sequence for the right hand expression
  74247. ** is used, or the default (BINARY) if neither expression has a collating
  74248. ** type.
  74249. **
  74250. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  74251. ** it is not considered.
  74252. */
  74253. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  74254. Parse *pParse,
  74255. Expr *pLeft,
  74256. Expr *pRight
  74257. ){
  74258. CollSeq *pColl;
  74259. assert( pLeft );
  74260. if( pLeft->flags & EP_Collate ){
  74261. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  74262. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  74263. pColl = sqlite3ExprCollSeq(pParse, pRight);
  74264. }else{
  74265. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  74266. if( !pColl ){
  74267. pColl = sqlite3ExprCollSeq(pParse, pRight);
  74268. }
  74269. }
  74270. return pColl;
  74271. }
  74272. /*
  74273. ** Generate code for a comparison operator.
  74274. */
  74275. static int codeCompare(
  74276. Parse *pParse, /* The parsing (and code generating) context */
  74277. Expr *pLeft, /* The left operand */
  74278. Expr *pRight, /* The right operand */
  74279. int opcode, /* The comparison opcode */
  74280. int in1, int in2, /* Register holding operands */
  74281. int dest, /* Jump here if true. */
  74282. int jumpIfNull /* If true, jump if either operand is NULL */
  74283. ){
  74284. int p5;
  74285. int addr;
  74286. CollSeq *p4;
  74287. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  74288. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  74289. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  74290. (void*)p4, P4_COLLSEQ);
  74291. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  74292. return addr;
  74293. }
  74294. #if SQLITE_MAX_EXPR_DEPTH>0
  74295. /*
  74296. ** Check that argument nHeight is less than or equal to the maximum
  74297. ** expression depth allowed. If it is not, leave an error message in
  74298. ** pParse.
  74299. */
  74300. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  74301. int rc = SQLITE_OK;
  74302. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  74303. if( nHeight>mxHeight ){
  74304. sqlite3ErrorMsg(pParse,
  74305. "Expression tree is too large (maximum depth %d)", mxHeight
  74306. );
  74307. rc = SQLITE_ERROR;
  74308. }
  74309. return rc;
  74310. }
  74311. /* The following three functions, heightOfExpr(), heightOfExprList()
  74312. ** and heightOfSelect(), are used to determine the maximum height
  74313. ** of any expression tree referenced by the structure passed as the
  74314. ** first argument.
  74315. **
  74316. ** If this maximum height is greater than the current value pointed
  74317. ** to by pnHeight, the second parameter, then set *pnHeight to that
  74318. ** value.
  74319. */
  74320. static void heightOfExpr(Expr *p, int *pnHeight){
  74321. if( p ){
  74322. if( p->nHeight>*pnHeight ){
  74323. *pnHeight = p->nHeight;
  74324. }
  74325. }
  74326. }
  74327. static void heightOfExprList(ExprList *p, int *pnHeight){
  74328. if( p ){
  74329. int i;
  74330. for(i=0; i<p->nExpr; i++){
  74331. heightOfExpr(p->a[i].pExpr, pnHeight);
  74332. }
  74333. }
  74334. }
  74335. static void heightOfSelect(Select *p, int *pnHeight){
  74336. if( p ){
  74337. heightOfExpr(p->pWhere, pnHeight);
  74338. heightOfExpr(p->pHaving, pnHeight);
  74339. heightOfExpr(p->pLimit, pnHeight);
  74340. heightOfExpr(p->pOffset, pnHeight);
  74341. heightOfExprList(p->pEList, pnHeight);
  74342. heightOfExprList(p->pGroupBy, pnHeight);
  74343. heightOfExprList(p->pOrderBy, pnHeight);
  74344. heightOfSelect(p->pPrior, pnHeight);
  74345. }
  74346. }
  74347. /*
  74348. ** Set the Expr.nHeight variable in the structure passed as an
  74349. ** argument. An expression with no children, Expr.pList or
  74350. ** Expr.pSelect member has a height of 1. Any other expression
  74351. ** has a height equal to the maximum height of any other
  74352. ** referenced Expr plus one.
  74353. */
  74354. static void exprSetHeight(Expr *p){
  74355. int nHeight = 0;
  74356. heightOfExpr(p->pLeft, &nHeight);
  74357. heightOfExpr(p->pRight, &nHeight);
  74358. if( ExprHasProperty(p, EP_xIsSelect) ){
  74359. heightOfSelect(p->x.pSelect, &nHeight);
  74360. }else{
  74361. heightOfExprList(p->x.pList, &nHeight);
  74362. }
  74363. p->nHeight = nHeight + 1;
  74364. }
  74365. /*
  74366. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  74367. ** the height is greater than the maximum allowed expression depth,
  74368. ** leave an error in pParse.
  74369. */
  74370. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  74371. exprSetHeight(p);
  74372. sqlite3ExprCheckHeight(pParse, p->nHeight);
  74373. }
  74374. /*
  74375. ** Return the maximum height of any expression tree referenced
  74376. ** by the select statement passed as an argument.
  74377. */
  74378. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  74379. int nHeight = 0;
  74380. heightOfSelect(p, &nHeight);
  74381. return nHeight;
  74382. }
  74383. #else
  74384. #define exprSetHeight(y)
  74385. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  74386. /*
  74387. ** This routine is the core allocator for Expr nodes.
  74388. **
  74389. ** Construct a new expression node and return a pointer to it. Memory
  74390. ** for this node and for the pToken argument is a single allocation
  74391. ** obtained from sqlite3DbMalloc(). The calling function
  74392. ** is responsible for making sure the node eventually gets freed.
  74393. **
  74394. ** If dequote is true, then the token (if it exists) is dequoted.
  74395. ** If dequote is false, no dequoting is performance. The deQuote
  74396. ** parameter is ignored if pToken is NULL or if the token does not
  74397. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  74398. ** then the EP_DblQuoted flag is set on the expression node.
  74399. **
  74400. ** Special case: If op==TK_INTEGER and pToken points to a string that
  74401. ** can be translated into a 32-bit integer, then the token is not
  74402. ** stored in u.zToken. Instead, the integer values is written
  74403. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  74404. ** is allocated to hold the integer text and the dequote flag is ignored.
  74405. */
  74406. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  74407. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  74408. int op, /* Expression opcode */
  74409. const Token *pToken, /* Token argument. Might be NULL */
  74410. int dequote /* True to dequote */
  74411. ){
  74412. Expr *pNew;
  74413. int nExtra = 0;
  74414. int iValue = 0;
  74415. if( pToken ){
  74416. if( op!=TK_INTEGER || pToken->z==0
  74417. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  74418. nExtra = pToken->n+1;
  74419. assert( iValue>=0 );
  74420. }
  74421. }
  74422. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  74423. if( pNew ){
  74424. pNew->op = (u8)op;
  74425. pNew->iAgg = -1;
  74426. if( pToken ){
  74427. if( nExtra==0 ){
  74428. pNew->flags |= EP_IntValue;
  74429. pNew->u.iValue = iValue;
  74430. }else{
  74431. int c;
  74432. pNew->u.zToken = (char*)&pNew[1];
  74433. assert( pToken->z!=0 || pToken->n==0 );
  74434. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  74435. pNew->u.zToken[pToken->n] = 0;
  74436. if( dequote && nExtra>=3
  74437. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  74438. sqlite3Dequote(pNew->u.zToken);
  74439. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  74440. }
  74441. }
  74442. }
  74443. #if SQLITE_MAX_EXPR_DEPTH>0
  74444. pNew->nHeight = 1;
  74445. #endif
  74446. }
  74447. return pNew;
  74448. }
  74449. /*
  74450. ** Allocate a new expression node from a zero-terminated token that has
  74451. ** already been dequoted.
  74452. */
  74453. SQLITE_PRIVATE Expr *sqlite3Expr(
  74454. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  74455. int op, /* Expression opcode */
  74456. const char *zToken /* Token argument. Might be NULL */
  74457. ){
  74458. Token x;
  74459. x.z = zToken;
  74460. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  74461. return sqlite3ExprAlloc(db, op, &x, 0);
  74462. }
  74463. /*
  74464. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  74465. **
  74466. ** If pRoot==NULL that means that a memory allocation error has occurred.
  74467. ** In that case, delete the subtrees pLeft and pRight.
  74468. */
  74469. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  74470. sqlite3 *db,
  74471. Expr *pRoot,
  74472. Expr *pLeft,
  74473. Expr *pRight
  74474. ){
  74475. if( pRoot==0 ){
  74476. assert( db->mallocFailed );
  74477. sqlite3ExprDelete(db, pLeft);
  74478. sqlite3ExprDelete(db, pRight);
  74479. }else{
  74480. if( pRight ){
  74481. pRoot->pRight = pRight;
  74482. pRoot->flags |= EP_Collate & pRight->flags;
  74483. }
  74484. if( pLeft ){
  74485. pRoot->pLeft = pLeft;
  74486. pRoot->flags |= EP_Collate & pLeft->flags;
  74487. }
  74488. exprSetHeight(pRoot);
  74489. }
  74490. }
  74491. /*
  74492. ** Allocate a Expr node which joins as many as two subtrees.
  74493. **
  74494. ** One or both of the subtrees can be NULL. Return a pointer to the new
  74495. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  74496. ** free the subtrees and return NULL.
  74497. */
  74498. SQLITE_PRIVATE Expr *sqlite3PExpr(
  74499. Parse *pParse, /* Parsing context */
  74500. int op, /* Expression opcode */
  74501. Expr *pLeft, /* Left operand */
  74502. Expr *pRight, /* Right operand */
  74503. const Token *pToken /* Argument token */
  74504. ){
  74505. Expr *p;
  74506. if( op==TK_AND && pLeft && pRight ){
  74507. /* Take advantage of short-circuit false optimization for AND */
  74508. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  74509. }else{
  74510. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  74511. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  74512. }
  74513. if( p ) {
  74514. sqlite3ExprCheckHeight(pParse, p->nHeight);
  74515. }
  74516. return p;
  74517. }
  74518. /*
  74519. ** Return 1 if an expression must be FALSE in all cases and 0 if the
  74520. ** expression might be true. This is an optimization. If is OK to
  74521. ** return 0 here even if the expression really is always false (a
  74522. ** false negative). But it is a bug to return 1 if the expression
  74523. ** might be true in some rare circumstances (a false positive.)
  74524. **
  74525. ** Note that if the expression is part of conditional for a
  74526. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  74527. ** is it true or false, so always return 0.
  74528. */
  74529. static int exprAlwaysFalse(Expr *p){
  74530. int v = 0;
  74531. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  74532. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  74533. return v==0;
  74534. }
  74535. /*
  74536. ** Join two expressions using an AND operator. If either expression is
  74537. ** NULL, then just return the other expression.
  74538. **
  74539. ** If one side or the other of the AND is known to be false, then instead
  74540. ** of returning an AND expression, just return a constant expression with
  74541. ** a value of false.
  74542. */
  74543. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  74544. if( pLeft==0 ){
  74545. return pRight;
  74546. }else if( pRight==0 ){
  74547. return pLeft;
  74548. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  74549. sqlite3ExprDelete(db, pLeft);
  74550. sqlite3ExprDelete(db, pRight);
  74551. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  74552. }else{
  74553. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  74554. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  74555. return pNew;
  74556. }
  74557. }
  74558. /*
  74559. ** Construct a new expression node for a function with multiple
  74560. ** arguments.
  74561. */
  74562. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  74563. Expr *pNew;
  74564. sqlite3 *db = pParse->db;
  74565. assert( pToken );
  74566. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  74567. if( pNew==0 ){
  74568. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  74569. return 0;
  74570. }
  74571. pNew->x.pList = pList;
  74572. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  74573. sqlite3ExprSetHeight(pParse, pNew);
  74574. return pNew;
  74575. }
  74576. /*
  74577. ** Assign a variable number to an expression that encodes a wildcard
  74578. ** in the original SQL statement.
  74579. **
  74580. ** Wildcards consisting of a single "?" are assigned the next sequential
  74581. ** variable number.
  74582. **
  74583. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  74584. ** sure "nnn" is not too be to avoid a denial of service attack when
  74585. ** the SQL statement comes from an external source.
  74586. **
  74587. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  74588. ** as the previous instance of the same wildcard. Or if this is the first
  74589. ** instance of the wildcard, the next sequenial variable number is
  74590. ** assigned.
  74591. */
  74592. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  74593. sqlite3 *db = pParse->db;
  74594. const char *z;
  74595. if( pExpr==0 ) return;
  74596. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  74597. z = pExpr->u.zToken;
  74598. assert( z!=0 );
  74599. assert( z[0]!=0 );
  74600. if( z[1]==0 ){
  74601. /* Wildcard of the form "?". Assign the next variable number */
  74602. assert( z[0]=='?' );
  74603. pExpr->iColumn = (ynVar)(++pParse->nVar);
  74604. }else{
  74605. ynVar x = 0;
  74606. u32 n = sqlite3Strlen30(z);
  74607. if( z[0]=='?' ){
  74608. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  74609. ** use it as the variable number */
  74610. i64 i;
  74611. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  74612. pExpr->iColumn = x = (ynVar)i;
  74613. testcase( i==0 );
  74614. testcase( i==1 );
  74615. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  74616. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  74617. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  74618. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  74619. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  74620. x = 0;
  74621. }
  74622. if( i>pParse->nVar ){
  74623. pParse->nVar = (int)i;
  74624. }
  74625. }else{
  74626. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  74627. ** number as the prior appearance of the same name, or if the name
  74628. ** has never appeared before, reuse the same variable number
  74629. */
  74630. ynVar i;
  74631. for(i=0; i<pParse->nzVar; i++){
  74632. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  74633. pExpr->iColumn = x = (ynVar)i+1;
  74634. break;
  74635. }
  74636. }
  74637. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  74638. }
  74639. if( x>0 ){
  74640. if( x>pParse->nzVar ){
  74641. char **a;
  74642. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  74643. if( a==0 ) return; /* Error reported through db->mallocFailed */
  74644. pParse->azVar = a;
  74645. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  74646. pParse->nzVar = x;
  74647. }
  74648. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  74649. sqlite3DbFree(db, pParse->azVar[x-1]);
  74650. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  74651. }
  74652. }
  74653. }
  74654. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  74655. sqlite3ErrorMsg(pParse, "too many SQL variables");
  74656. }
  74657. }
  74658. /*
  74659. ** Recursively delete an expression tree.
  74660. */
  74661. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  74662. if( p==0 ) return;
  74663. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  74664. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  74665. if( !ExprHasProperty(p, EP_TokenOnly) ){
  74666. /* The Expr.x union is never used at the same time as Expr.pRight */
  74667. assert( p->x.pList==0 || p->pRight==0 );
  74668. sqlite3ExprDelete(db, p->pLeft);
  74669. sqlite3ExprDelete(db, p->pRight);
  74670. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  74671. if( ExprHasProperty(p, EP_xIsSelect) ){
  74672. sqlite3SelectDelete(db, p->x.pSelect);
  74673. }else{
  74674. sqlite3ExprListDelete(db, p->x.pList);
  74675. }
  74676. }
  74677. if( !ExprHasProperty(p, EP_Static) ){
  74678. sqlite3DbFree(db, p);
  74679. }
  74680. }
  74681. /*
  74682. ** Return the number of bytes allocated for the expression structure
  74683. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  74684. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  74685. */
  74686. static int exprStructSize(Expr *p){
  74687. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  74688. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  74689. return EXPR_FULLSIZE;
  74690. }
  74691. /*
  74692. ** The dupedExpr*Size() routines each return the number of bytes required
  74693. ** to store a copy of an expression or expression tree. They differ in
  74694. ** how much of the tree is measured.
  74695. **
  74696. ** dupedExprStructSize() Size of only the Expr structure
  74697. ** dupedExprNodeSize() Size of Expr + space for token
  74698. ** dupedExprSize() Expr + token + subtree components
  74699. **
  74700. ***************************************************************************
  74701. **
  74702. ** The dupedExprStructSize() function returns two values OR-ed together:
  74703. ** (1) the space required for a copy of the Expr structure only and
  74704. ** (2) the EP_xxx flags that indicate what the structure size should be.
  74705. ** The return values is always one of:
  74706. **
  74707. ** EXPR_FULLSIZE
  74708. ** EXPR_REDUCEDSIZE | EP_Reduced
  74709. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  74710. **
  74711. ** The size of the structure can be found by masking the return value
  74712. ** of this routine with 0xfff. The flags can be found by masking the
  74713. ** return value with EP_Reduced|EP_TokenOnly.
  74714. **
  74715. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  74716. ** (unreduced) Expr objects as they or originally constructed by the parser.
  74717. ** During expression analysis, extra information is computed and moved into
  74718. ** later parts of teh Expr object and that extra information might get chopped
  74719. ** off if the expression is reduced. Note also that it does not work to
  74720. ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  74721. ** to reduce a pristine expression tree from the parser. The implementation
  74722. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  74723. ** to enforce this constraint.
  74724. */
  74725. static int dupedExprStructSize(Expr *p, int flags){
  74726. int nSize;
  74727. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  74728. assert( EXPR_FULLSIZE<=0xfff );
  74729. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  74730. if( 0==(flags&EXPRDUP_REDUCE) ){
  74731. nSize = EXPR_FULLSIZE;
  74732. }else{
  74733. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  74734. assert( !ExprHasProperty(p, EP_FromJoin) );
  74735. assert( !ExprHasProperty(p, EP_MemToken) );
  74736. assert( !ExprHasProperty(p, EP_NoReduce) );
  74737. if( p->pLeft || p->x.pList ){
  74738. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  74739. }else{
  74740. assert( p->pRight==0 );
  74741. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  74742. }
  74743. }
  74744. return nSize;
  74745. }
  74746. /*
  74747. ** This function returns the space in bytes required to store the copy
  74748. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  74749. ** string is defined.)
  74750. */
  74751. static int dupedExprNodeSize(Expr *p, int flags){
  74752. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  74753. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  74754. nByte += sqlite3Strlen30(p->u.zToken)+1;
  74755. }
  74756. return ROUND8(nByte);
  74757. }
  74758. /*
  74759. ** Return the number of bytes required to create a duplicate of the
  74760. ** expression passed as the first argument. The second argument is a
  74761. ** mask containing EXPRDUP_XXX flags.
  74762. **
  74763. ** The value returned includes space to create a copy of the Expr struct
  74764. ** itself and the buffer referred to by Expr.u.zToken, if any.
  74765. **
  74766. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  74767. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  74768. ** and Expr.pRight variables (but not for any structures pointed to or
  74769. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  74770. */
  74771. static int dupedExprSize(Expr *p, int flags){
  74772. int nByte = 0;
  74773. if( p ){
  74774. nByte = dupedExprNodeSize(p, flags);
  74775. if( flags&EXPRDUP_REDUCE ){
  74776. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  74777. }
  74778. }
  74779. return nByte;
  74780. }
  74781. /*
  74782. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  74783. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  74784. ** to store the copy of expression p, the copies of p->u.zToken
  74785. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  74786. ** if any. Before returning, *pzBuffer is set to the first byte passed the
  74787. ** portion of the buffer copied into by this function.
  74788. */
  74789. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  74790. Expr *pNew = 0; /* Value to return */
  74791. if( p ){
  74792. const int isReduced = (flags&EXPRDUP_REDUCE);
  74793. u8 *zAlloc;
  74794. u32 staticFlag = 0;
  74795. assert( pzBuffer==0 || isReduced );
  74796. /* Figure out where to write the new Expr structure. */
  74797. if( pzBuffer ){
  74798. zAlloc = *pzBuffer;
  74799. staticFlag = EP_Static;
  74800. }else{
  74801. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  74802. }
  74803. pNew = (Expr *)zAlloc;
  74804. if( pNew ){
  74805. /* Set nNewSize to the size allocated for the structure pointed to
  74806. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  74807. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  74808. ** by the copy of the p->u.zToken string (if any).
  74809. */
  74810. const unsigned nStructSize = dupedExprStructSize(p, flags);
  74811. const int nNewSize = nStructSize & 0xfff;
  74812. int nToken;
  74813. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  74814. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  74815. }else{
  74816. nToken = 0;
  74817. }
  74818. if( isReduced ){
  74819. assert( ExprHasProperty(p, EP_Reduced)==0 );
  74820. memcpy(zAlloc, p, nNewSize);
  74821. }else{
  74822. int nSize = exprStructSize(p);
  74823. memcpy(zAlloc, p, nSize);
  74824. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  74825. }
  74826. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  74827. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  74828. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  74829. pNew->flags |= staticFlag;
  74830. /* Copy the p->u.zToken string, if any. */
  74831. if( nToken ){
  74832. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  74833. memcpy(zToken, p->u.zToken, nToken);
  74834. }
  74835. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  74836. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  74837. if( ExprHasProperty(p, EP_xIsSelect) ){
  74838. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  74839. }else{
  74840. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  74841. }
  74842. }
  74843. /* Fill in pNew->pLeft and pNew->pRight. */
  74844. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  74845. zAlloc += dupedExprNodeSize(p, flags);
  74846. if( ExprHasProperty(pNew, EP_Reduced) ){
  74847. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  74848. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  74849. }
  74850. if( pzBuffer ){
  74851. *pzBuffer = zAlloc;
  74852. }
  74853. }else{
  74854. if( !ExprHasProperty(p, EP_TokenOnly) ){
  74855. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  74856. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  74857. }
  74858. }
  74859. }
  74860. }
  74861. return pNew;
  74862. }
  74863. /*
  74864. ** The following group of routines make deep copies of expressions,
  74865. ** expression lists, ID lists, and select statements. The copies can
  74866. ** be deleted (by being passed to their respective ...Delete() routines)
  74867. ** without effecting the originals.
  74868. **
  74869. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  74870. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  74871. ** by subsequent calls to sqlite*ListAppend() routines.
  74872. **
  74873. ** Any tables that the SrcList might point to are not duplicated.
  74874. **
  74875. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  74876. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  74877. ** truncated version of the usual Expr structure that will be stored as
  74878. ** part of the in-memory representation of the database schema.
  74879. */
  74880. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  74881. return exprDup(db, p, flags, 0);
  74882. }
  74883. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  74884. ExprList *pNew;
  74885. struct ExprList_item *pItem, *pOldItem;
  74886. int i;
  74887. if( p==0 ) return 0;
  74888. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  74889. if( pNew==0 ) return 0;
  74890. pNew->iECursor = 0;
  74891. pNew->nExpr = i = p->nExpr;
  74892. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  74893. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  74894. if( pItem==0 ){
  74895. sqlite3DbFree(db, pNew);
  74896. return 0;
  74897. }
  74898. pOldItem = p->a;
  74899. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  74900. Expr *pOldExpr = pOldItem->pExpr;
  74901. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  74902. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74903. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  74904. pItem->sortOrder = pOldItem->sortOrder;
  74905. pItem->done = 0;
  74906. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  74907. pItem->iOrderByCol = pOldItem->iOrderByCol;
  74908. pItem->iAlias = pOldItem->iAlias;
  74909. }
  74910. return pNew;
  74911. }
  74912. /*
  74913. ** If cursors, triggers, views and subqueries are all omitted from
  74914. ** the build, then none of the following routines, except for
  74915. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  74916. ** called with a NULL argument.
  74917. */
  74918. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  74919. || !defined(SQLITE_OMIT_SUBQUERY)
  74920. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  74921. SrcList *pNew;
  74922. int i;
  74923. int nByte;
  74924. if( p==0 ) return 0;
  74925. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  74926. pNew = sqlite3DbMallocRaw(db, nByte );
  74927. if( pNew==0 ) return 0;
  74928. pNew->nSrc = pNew->nAlloc = p->nSrc;
  74929. for(i=0; i<p->nSrc; i++){
  74930. struct SrcList_item *pNewItem = &pNew->a[i];
  74931. struct SrcList_item *pOldItem = &p->a[i];
  74932. Table *pTab;
  74933. pNewItem->pSchema = pOldItem->pSchema;
  74934. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  74935. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74936. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  74937. pNewItem->jointype = pOldItem->jointype;
  74938. pNewItem->iCursor = pOldItem->iCursor;
  74939. pNewItem->addrFillSub = pOldItem->addrFillSub;
  74940. pNewItem->regReturn = pOldItem->regReturn;
  74941. pNewItem->isCorrelated = pOldItem->isCorrelated;
  74942. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  74943. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  74944. pNewItem->notIndexed = pOldItem->notIndexed;
  74945. pNewItem->pIndex = pOldItem->pIndex;
  74946. pTab = pNewItem->pTab = pOldItem->pTab;
  74947. if( pTab ){
  74948. pTab->nRef++;
  74949. }
  74950. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  74951. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  74952. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  74953. pNewItem->colUsed = pOldItem->colUsed;
  74954. }
  74955. return pNew;
  74956. }
  74957. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  74958. IdList *pNew;
  74959. int i;
  74960. if( p==0 ) return 0;
  74961. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  74962. if( pNew==0 ) return 0;
  74963. pNew->nId = p->nId;
  74964. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  74965. if( pNew->a==0 ){
  74966. sqlite3DbFree(db, pNew);
  74967. return 0;
  74968. }
  74969. /* Note that because the size of the allocation for p->a[] is not
  74970. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  74971. ** on the duplicate created by this function. */
  74972. for(i=0; i<p->nId; i++){
  74973. struct IdList_item *pNewItem = &pNew->a[i];
  74974. struct IdList_item *pOldItem = &p->a[i];
  74975. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  74976. pNewItem->idx = pOldItem->idx;
  74977. }
  74978. return pNew;
  74979. }
  74980. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  74981. Select *pNew, *pPrior;
  74982. if( p==0 ) return 0;
  74983. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  74984. if( pNew==0 ) return 0;
  74985. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  74986. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  74987. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  74988. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  74989. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  74990. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  74991. pNew->op = p->op;
  74992. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  74993. if( pPrior ) pPrior->pNext = pNew;
  74994. pNew->pNext = 0;
  74995. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  74996. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  74997. pNew->iLimit = 0;
  74998. pNew->iOffset = 0;
  74999. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  75000. pNew->pRightmost = 0;
  75001. pNew->addrOpenEphm[0] = -1;
  75002. pNew->addrOpenEphm[1] = -1;
  75003. pNew->addrOpenEphm[2] = -1;
  75004. return pNew;
  75005. }
  75006. #else
  75007. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  75008. assert( p==0 );
  75009. return 0;
  75010. }
  75011. #endif
  75012. /*
  75013. ** Add a new element to the end of an expression list. If pList is
  75014. ** initially NULL, then create a new expression list.
  75015. **
  75016. ** If a memory allocation error occurs, the entire list is freed and
  75017. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  75018. ** that the new entry was successfully appended.
  75019. */
  75020. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  75021. Parse *pParse, /* Parsing context */
  75022. ExprList *pList, /* List to which to append. Might be NULL */
  75023. Expr *pExpr /* Expression to be appended. Might be NULL */
  75024. ){
  75025. sqlite3 *db = pParse->db;
  75026. if( pList==0 ){
  75027. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  75028. if( pList==0 ){
  75029. goto no_mem;
  75030. }
  75031. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  75032. if( pList->a==0 ) goto no_mem;
  75033. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  75034. struct ExprList_item *a;
  75035. assert( pList->nExpr>0 );
  75036. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  75037. if( a==0 ){
  75038. goto no_mem;
  75039. }
  75040. pList->a = a;
  75041. }
  75042. assert( pList->a!=0 );
  75043. if( 1 ){
  75044. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  75045. memset(pItem, 0, sizeof(*pItem));
  75046. pItem->pExpr = pExpr;
  75047. }
  75048. return pList;
  75049. no_mem:
  75050. /* Avoid leaking memory if malloc has failed. */
  75051. sqlite3ExprDelete(db, pExpr);
  75052. sqlite3ExprListDelete(db, pList);
  75053. return 0;
  75054. }
  75055. /*
  75056. ** Set the ExprList.a[].zName element of the most recently added item
  75057. ** on the expression list.
  75058. **
  75059. ** pList might be NULL following an OOM error. But pName should never be
  75060. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  75061. ** is set.
  75062. */
  75063. SQLITE_PRIVATE void sqlite3ExprListSetName(
  75064. Parse *pParse, /* Parsing context */
  75065. ExprList *pList, /* List to which to add the span. */
  75066. Token *pName, /* Name to be added */
  75067. int dequote /* True to cause the name to be dequoted */
  75068. ){
  75069. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  75070. if( pList ){
  75071. struct ExprList_item *pItem;
  75072. assert( pList->nExpr>0 );
  75073. pItem = &pList->a[pList->nExpr-1];
  75074. assert( pItem->zName==0 );
  75075. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  75076. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  75077. }
  75078. }
  75079. /*
  75080. ** Set the ExprList.a[].zSpan element of the most recently added item
  75081. ** on the expression list.
  75082. **
  75083. ** pList might be NULL following an OOM error. But pSpan should never be
  75084. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  75085. ** is set.
  75086. */
  75087. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  75088. Parse *pParse, /* Parsing context */
  75089. ExprList *pList, /* List to which to add the span. */
  75090. ExprSpan *pSpan /* The span to be added */
  75091. ){
  75092. sqlite3 *db = pParse->db;
  75093. assert( pList!=0 || db->mallocFailed!=0 );
  75094. if( pList ){
  75095. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  75096. assert( pList->nExpr>0 );
  75097. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  75098. sqlite3DbFree(db, pItem->zSpan);
  75099. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  75100. (int)(pSpan->zEnd - pSpan->zStart));
  75101. }
  75102. }
  75103. /*
  75104. ** If the expression list pEList contains more than iLimit elements,
  75105. ** leave an error message in pParse.
  75106. */
  75107. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  75108. Parse *pParse,
  75109. ExprList *pEList,
  75110. const char *zObject
  75111. ){
  75112. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  75113. testcase( pEList && pEList->nExpr==mx );
  75114. testcase( pEList && pEList->nExpr==mx+1 );
  75115. if( pEList && pEList->nExpr>mx ){
  75116. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  75117. }
  75118. }
  75119. /*
  75120. ** Delete an entire expression list.
  75121. */
  75122. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  75123. int i;
  75124. struct ExprList_item *pItem;
  75125. if( pList==0 ) return;
  75126. assert( pList->a!=0 || pList->nExpr==0 );
  75127. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  75128. sqlite3ExprDelete(db, pItem->pExpr);
  75129. sqlite3DbFree(db, pItem->zName);
  75130. sqlite3DbFree(db, pItem->zSpan);
  75131. }
  75132. sqlite3DbFree(db, pList->a);
  75133. sqlite3DbFree(db, pList);
  75134. }
  75135. /*
  75136. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  75137. ** to an integer. These routines are checking an expression to see
  75138. ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
  75139. ** not constant.
  75140. **
  75141. ** These callback routines are used to implement the following:
  75142. **
  75143. ** sqlite3ExprIsConstant()
  75144. ** sqlite3ExprIsConstantNotJoin()
  75145. ** sqlite3ExprIsConstantOrFunction()
  75146. **
  75147. */
  75148. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  75149. /* If pWalker->u.i is 3 then any term of the expression that comes from
  75150. ** the ON or USING clauses of a join disqualifies the expression
  75151. ** from being considered constant. */
  75152. if( pWalker->u.i==3 && ExprHasProperty(pExpr, EP_FromJoin) ){
  75153. pWalker->u.i = 0;
  75154. return WRC_Abort;
  75155. }
  75156. switch( pExpr->op ){
  75157. /* Consider functions to be constant if all their arguments are constant
  75158. ** and pWalker->u.i==2 */
  75159. case TK_FUNCTION:
  75160. if( pWalker->u.i==2 ) return 0;
  75161. /* Fall through */
  75162. case TK_ID:
  75163. case TK_COLUMN:
  75164. case TK_AGG_FUNCTION:
  75165. case TK_AGG_COLUMN:
  75166. testcase( pExpr->op==TK_ID );
  75167. testcase( pExpr->op==TK_COLUMN );
  75168. testcase( pExpr->op==TK_AGG_FUNCTION );
  75169. testcase( pExpr->op==TK_AGG_COLUMN );
  75170. pWalker->u.i = 0;
  75171. return WRC_Abort;
  75172. default:
  75173. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  75174. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  75175. return WRC_Continue;
  75176. }
  75177. }
  75178. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  75179. UNUSED_PARAMETER(NotUsed);
  75180. pWalker->u.i = 0;
  75181. return WRC_Abort;
  75182. }
  75183. static int exprIsConst(Expr *p, int initFlag){
  75184. Walker w;
  75185. memset(&w, 0, sizeof(w));
  75186. w.u.i = initFlag;
  75187. w.xExprCallback = exprNodeIsConstant;
  75188. w.xSelectCallback = selectNodeIsConstant;
  75189. sqlite3WalkExpr(&w, p);
  75190. return w.u.i;
  75191. }
  75192. /*
  75193. ** Walk an expression tree. Return 1 if the expression is constant
  75194. ** and 0 if it involves variables or function calls.
  75195. **
  75196. ** For the purposes of this function, a double-quoted string (ex: "abc")
  75197. ** is considered a variable but a single-quoted string (ex: 'abc') is
  75198. ** a constant.
  75199. */
  75200. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  75201. return exprIsConst(p, 1);
  75202. }
  75203. /*
  75204. ** Walk an expression tree. Return 1 if the expression is constant
  75205. ** that does no originate from the ON or USING clauses of a join.
  75206. ** Return 0 if it involves variables or function calls or terms from
  75207. ** an ON or USING clause.
  75208. */
  75209. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  75210. return exprIsConst(p, 3);
  75211. }
  75212. /*
  75213. ** Walk an expression tree. Return 1 if the expression is constant
  75214. ** or a function call with constant arguments. Return and 0 if there
  75215. ** are any variables.
  75216. **
  75217. ** For the purposes of this function, a double-quoted string (ex: "abc")
  75218. ** is considered a variable but a single-quoted string (ex: 'abc') is
  75219. ** a constant.
  75220. */
  75221. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
  75222. return exprIsConst(p, 2);
  75223. }
  75224. /*
  75225. ** If the expression p codes a constant integer that is small enough
  75226. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  75227. ** in *pValue. If the expression is not an integer or if it is too big
  75228. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  75229. */
  75230. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  75231. int rc = 0;
  75232. /* If an expression is an integer literal that fits in a signed 32-bit
  75233. ** integer, then the EP_IntValue flag will have already been set */
  75234. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  75235. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  75236. if( p->flags & EP_IntValue ){
  75237. *pValue = p->u.iValue;
  75238. return 1;
  75239. }
  75240. switch( p->op ){
  75241. case TK_UPLUS: {
  75242. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  75243. break;
  75244. }
  75245. case TK_UMINUS: {
  75246. int v;
  75247. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  75248. assert( v!=(-2147483647-1) );
  75249. *pValue = -v;
  75250. rc = 1;
  75251. }
  75252. break;
  75253. }
  75254. default: break;
  75255. }
  75256. return rc;
  75257. }
  75258. /*
  75259. ** Return FALSE if there is no chance that the expression can be NULL.
  75260. **
  75261. ** If the expression might be NULL or if the expression is too complex
  75262. ** to tell return TRUE.
  75263. **
  75264. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  75265. ** when we know that a value cannot be NULL. Hence, a false positive
  75266. ** (returning TRUE when in fact the expression can never be NULL) might
  75267. ** be a small performance hit but is otherwise harmless. On the other
  75268. ** hand, a false negative (returning FALSE when the result could be NULL)
  75269. ** will likely result in an incorrect answer. So when in doubt, return
  75270. ** TRUE.
  75271. */
  75272. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  75273. u8 op;
  75274. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  75275. op = p->op;
  75276. if( op==TK_REGISTER ) op = p->op2;
  75277. switch( op ){
  75278. case TK_INTEGER:
  75279. case TK_STRING:
  75280. case TK_FLOAT:
  75281. case TK_BLOB:
  75282. return 0;
  75283. default:
  75284. return 1;
  75285. }
  75286. }
  75287. /*
  75288. ** Generate an OP_IsNull instruction that tests register iReg and jumps
  75289. ** to location iDest if the value in iReg is NULL. The value in iReg
  75290. ** was computed by pExpr. If we can look at pExpr at compile-time and
  75291. ** determine that it can never generate a NULL, then the OP_IsNull operation
  75292. ** can be omitted.
  75293. */
  75294. SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
  75295. Vdbe *v, /* The VDBE under construction */
  75296. const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
  75297. int iReg, /* Test the value in this register for NULL */
  75298. int iDest /* Jump here if the value is null */
  75299. ){
  75300. if( sqlite3ExprCanBeNull(pExpr) ){
  75301. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
  75302. }
  75303. }
  75304. /*
  75305. ** Return TRUE if the given expression is a constant which would be
  75306. ** unchanged by OP_Affinity with the affinity given in the second
  75307. ** argument.
  75308. **
  75309. ** This routine is used to determine if the OP_Affinity operation
  75310. ** can be omitted. When in doubt return FALSE. A false negative
  75311. ** is harmless. A false positive, however, can result in the wrong
  75312. ** answer.
  75313. */
  75314. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  75315. u8 op;
  75316. if( aff==SQLITE_AFF_NONE ) return 1;
  75317. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  75318. op = p->op;
  75319. if( op==TK_REGISTER ) op = p->op2;
  75320. switch( op ){
  75321. case TK_INTEGER: {
  75322. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  75323. }
  75324. case TK_FLOAT: {
  75325. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  75326. }
  75327. case TK_STRING: {
  75328. return aff==SQLITE_AFF_TEXT;
  75329. }
  75330. case TK_BLOB: {
  75331. return 1;
  75332. }
  75333. case TK_COLUMN: {
  75334. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  75335. return p->iColumn<0
  75336. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  75337. }
  75338. default: {
  75339. return 0;
  75340. }
  75341. }
  75342. }
  75343. /*
  75344. ** Return TRUE if the given string is a row-id column name.
  75345. */
  75346. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  75347. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  75348. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  75349. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  75350. return 0;
  75351. }
  75352. /*
  75353. ** Return true if we are able to the IN operator optimization on a
  75354. ** query of the form
  75355. **
  75356. ** x IN (SELECT ...)
  75357. **
  75358. ** Where the SELECT... clause is as specified by the parameter to this
  75359. ** routine.
  75360. **
  75361. ** The Select object passed in has already been preprocessed and no
  75362. ** errors have been found.
  75363. */
  75364. #ifndef SQLITE_OMIT_SUBQUERY
  75365. static int isCandidateForInOpt(Select *p){
  75366. SrcList *pSrc;
  75367. ExprList *pEList;
  75368. Table *pTab;
  75369. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  75370. if( p->pPrior ) return 0; /* Not a compound SELECT */
  75371. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  75372. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  75373. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  75374. return 0; /* No DISTINCT keyword and no aggregate functions */
  75375. }
  75376. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  75377. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  75378. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  75379. if( p->pWhere ) return 0; /* Has no WHERE clause */
  75380. pSrc = p->pSrc;
  75381. assert( pSrc!=0 );
  75382. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  75383. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  75384. pTab = pSrc->a[0].pTab;
  75385. if( NEVER(pTab==0) ) return 0;
  75386. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  75387. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  75388. pEList = p->pEList;
  75389. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  75390. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  75391. return 1;
  75392. }
  75393. #endif /* SQLITE_OMIT_SUBQUERY */
  75394. /*
  75395. ** Code an OP_Once instruction and allocate space for its flag. Return the
  75396. ** address of the new instruction.
  75397. */
  75398. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  75399. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  75400. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  75401. }
  75402. /*
  75403. ** This function is used by the implementation of the IN (...) operator.
  75404. ** The pX parameter is the expression on the RHS of the IN operator, which
  75405. ** might be either a list of expressions or a subquery.
  75406. **
  75407. ** The job of this routine is to find or create a b-tree object that can
  75408. ** be used either to test for membership in the RHS set or to iterate through
  75409. ** all members of the RHS set, skipping duplicates.
  75410. **
  75411. ** A cursor is opened on the b-tree object that the RHS of the IN operator
  75412. ** and pX->iTable is set to the index of that cursor.
  75413. **
  75414. ** The returned value of this function indicates the b-tree type, as follows:
  75415. **
  75416. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  75417. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  75418. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  75419. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  75420. ** populated epheremal table.
  75421. **
  75422. ** An existing b-tree might be used if the RHS expression pX is a simple
  75423. ** subquery such as:
  75424. **
  75425. ** SELECT <column> FROM <table>
  75426. **
  75427. ** If the RHS of the IN operator is a list or a more complex subquery, then
  75428. ** an ephemeral table might need to be generated from the RHS and then
  75429. ** pX->iTable made to point to the ephermeral table instead of an
  75430. ** existing table.
  75431. **
  75432. ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
  75433. ** through the set members, skipping any duplicates. In this case an
  75434. ** epheremal table must be used unless the selected <column> is guaranteed
  75435. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  75436. ** has a UNIQUE constraint or UNIQUE index.
  75437. **
  75438. ** If the prNotFound parameter is not 0, then the b-tree will be used
  75439. ** for fast set membership tests. In this case an epheremal table must
  75440. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  75441. ** be found with <column> as its left-most column.
  75442. **
  75443. ** When the b-tree is being used for membership tests, the calling function
  75444. ** needs to know whether or not the structure contains an SQL NULL
  75445. ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
  75446. ** If there is any chance that the (...) might contain a NULL value at
  75447. ** runtime, then a register is allocated and the register number written
  75448. ** to *prNotFound. If there is no chance that the (...) contains a
  75449. ** NULL value, then *prNotFound is left unchanged.
  75450. **
  75451. ** If a register is allocated and its location stored in *prNotFound, then
  75452. ** its initial value is NULL. If the (...) does not remain constant
  75453. ** for the duration of the query (i.e. the SELECT within the (...)
  75454. ** is a correlated subquery) then the value of the allocated register is
  75455. ** reset to NULL each time the subquery is rerun. This allows the
  75456. ** caller to use vdbe code equivalent to the following:
  75457. **
  75458. ** if( register==NULL ){
  75459. ** has_null = <test if data structure contains null>
  75460. ** register = 1
  75461. ** }
  75462. **
  75463. ** in order to avoid running the <test if data structure contains null>
  75464. ** test more often than is necessary.
  75465. */
  75466. #ifndef SQLITE_OMIT_SUBQUERY
  75467. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
  75468. Select *p; /* SELECT to the right of IN operator */
  75469. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  75470. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  75471. int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
  75472. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  75473. assert( pX->op==TK_IN );
  75474. /* Check to see if an existing table or index can be used to
  75475. ** satisfy the query. This is preferable to generating a new
  75476. ** ephemeral table.
  75477. */
  75478. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  75479. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  75480. sqlite3 *db = pParse->db; /* Database connection */
  75481. Table *pTab; /* Table <table>. */
  75482. Expr *pExpr; /* Expression <column> */
  75483. int iCol; /* Index of column <column> */
  75484. int iDb; /* Database idx for pTab */
  75485. assert( p ); /* Because of isCandidateForInOpt(p) */
  75486. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  75487. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  75488. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  75489. pTab = p->pSrc->a[0].pTab;
  75490. pExpr = p->pEList->a[0].pExpr;
  75491. iCol = pExpr->iColumn;
  75492. /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
  75493. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  75494. sqlite3CodeVerifySchema(pParse, iDb);
  75495. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  75496. /* This function is only called from two places. In both cases the vdbe
  75497. ** has already been allocated. So assume sqlite3GetVdbe() is always
  75498. ** successful here.
  75499. */
  75500. assert(v);
  75501. if( iCol<0 ){
  75502. int iAddr;
  75503. iAddr = sqlite3CodeOnce(pParse);
  75504. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  75505. eType = IN_INDEX_ROWID;
  75506. sqlite3VdbeJumpHere(v, iAddr);
  75507. }else{
  75508. Index *pIdx; /* Iterator variable */
  75509. /* The collation sequence used by the comparison. If an index is to
  75510. ** be used in place of a temp-table, it must be ordered according
  75511. ** to this collation sequence. */
  75512. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  75513. /* Check that the affinity that will be used to perform the
  75514. ** comparison is the same as the affinity of the column. If
  75515. ** it is not, it is not possible to use any index.
  75516. */
  75517. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  75518. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  75519. if( (pIdx->aiColumn[0]==iCol)
  75520. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  75521. && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
  75522. ){
  75523. int iAddr;
  75524. char *pKey;
  75525. pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
  75526. iAddr = sqlite3CodeOnce(pParse);
  75527. sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
  75528. pKey,P4_KEYINFO_HANDOFF);
  75529. VdbeComment((v, "%s", pIdx->zName));
  75530. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  75531. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  75532. sqlite3VdbeJumpHere(v, iAddr);
  75533. if( prNotFound && !pTab->aCol[iCol].notNull ){
  75534. *prNotFound = ++pParse->nMem;
  75535. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  75536. }
  75537. }
  75538. }
  75539. }
  75540. }
  75541. if( eType==0 ){
  75542. /* Could not found an existing table or index to use as the RHS b-tree.
  75543. ** We will have to generate an ephemeral table to do the job.
  75544. */
  75545. u32 savedNQueryLoop = pParse->nQueryLoop;
  75546. int rMayHaveNull = 0;
  75547. eType = IN_INDEX_EPH;
  75548. if( prNotFound ){
  75549. *prNotFound = rMayHaveNull = ++pParse->nMem;
  75550. sqlite3VdbeAddOp2(v, OP_Null, 0, *prNotFound);
  75551. }else{
  75552. testcase( pParse->nQueryLoop>0 );
  75553. pParse->nQueryLoop = 0;
  75554. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  75555. eType = IN_INDEX_ROWID;
  75556. }
  75557. }
  75558. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  75559. pParse->nQueryLoop = savedNQueryLoop;
  75560. }else{
  75561. pX->iTable = iTab;
  75562. }
  75563. return eType;
  75564. }
  75565. #endif
  75566. /*
  75567. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  75568. ** or IN operators. Examples:
  75569. **
  75570. ** (SELECT a FROM b) -- subquery
  75571. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  75572. ** x IN (4,5,11) -- IN operator with list on right-hand side
  75573. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  75574. **
  75575. ** The pExpr parameter describes the expression that contains the IN
  75576. ** operator or subquery.
  75577. **
  75578. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  75579. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  75580. ** to some integer key column of a table B-Tree. In this case, use an
  75581. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  75582. ** (slower) variable length keys B-Tree.
  75583. **
  75584. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  75585. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  75586. ** Furthermore, the IN is in a WHERE clause and that we really want
  75587. ** to iterate over the RHS of the IN operator in order to quickly locate
  75588. ** all corresponding LHS elements. All this routine does is initialize
  75589. ** the register given by rMayHaveNull to NULL. Calling routines will take
  75590. ** care of changing this register value to non-NULL if the RHS is NULL-free.
  75591. **
  75592. ** If rMayHaveNull is zero, that means that the subquery is being used
  75593. ** for membership testing only. There is no need to initialize any
  75594. ** registers to indicate the presence or absence of NULLs on the RHS.
  75595. **
  75596. ** For a SELECT or EXISTS operator, return the register that holds the
  75597. ** result. For IN operators or if an error occurs, the return value is 0.
  75598. */
  75599. #ifndef SQLITE_OMIT_SUBQUERY
  75600. SQLITE_PRIVATE int sqlite3CodeSubselect(
  75601. Parse *pParse, /* Parsing context */
  75602. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  75603. int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
  75604. int isRowid /* If true, LHS of IN operator is a rowid */
  75605. ){
  75606. int testAddr = -1; /* One-time test address */
  75607. int rReg = 0; /* Register storing resulting */
  75608. Vdbe *v = sqlite3GetVdbe(pParse);
  75609. if( NEVER(v==0) ) return 0;
  75610. sqlite3ExprCachePush(pParse);
  75611. /* This code must be run in its entirety every time it is encountered
  75612. ** if any of the following is true:
  75613. **
  75614. ** * The right-hand side is a correlated subquery
  75615. ** * The right-hand side is an expression list containing variables
  75616. ** * We are inside a trigger
  75617. **
  75618. ** If all of the above are false, then we can run this code just once
  75619. ** save the results, and reuse the same result on subsequent invocations.
  75620. */
  75621. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  75622. testAddr = sqlite3CodeOnce(pParse);
  75623. }
  75624. #ifndef SQLITE_OMIT_EXPLAIN
  75625. if( pParse->explain==2 ){
  75626. char *zMsg = sqlite3MPrintf(
  75627. pParse->db, "EXECUTE %s%s SUBQUERY %d", testAddr>=0?"":"CORRELATED ",
  75628. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  75629. );
  75630. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  75631. }
  75632. #endif
  75633. switch( pExpr->op ){
  75634. case TK_IN: {
  75635. char affinity; /* Affinity of the LHS of the IN */
  75636. int addr; /* Address of OP_OpenEphemeral instruction */
  75637. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  75638. KeyInfo *pKeyInfo = 0; /* Key information */
  75639. if( rMayHaveNull ){
  75640. sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
  75641. }
  75642. affinity = sqlite3ExprAffinity(pLeft);
  75643. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  75644. ** expression it is handled the same way. An ephemeral table is
  75645. ** filled with single-field index keys representing the results
  75646. ** from the SELECT or the <exprlist>.
  75647. **
  75648. ** If the 'x' expression is a column value, or the SELECT...
  75649. ** statement returns a column value, then the affinity of that
  75650. ** column is used to build the index keys. If both 'x' and the
  75651. ** SELECT... statement are columns, then numeric affinity is used
  75652. ** if either column has NUMERIC or INTEGER affinity. If neither
  75653. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  75654. ** is used.
  75655. */
  75656. pExpr->iTable = pParse->nTab++;
  75657. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  75658. if( rMayHaveNull==0 ) sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  75659. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1);
  75660. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75661. /* Case 1: expr IN (SELECT ...)
  75662. **
  75663. ** Generate code to write the results of the select into the temporary
  75664. ** table allocated and opened above.
  75665. */
  75666. SelectDest dest;
  75667. ExprList *pEList;
  75668. assert( !isRowid );
  75669. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  75670. dest.affSdst = (u8)affinity;
  75671. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  75672. pExpr->x.pSelect->iLimit = 0;
  75673. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  75674. if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
  75675. sqlite3DbFree(pParse->db, pKeyInfo);
  75676. return 0;
  75677. }
  75678. pEList = pExpr->x.pSelect->pEList;
  75679. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  75680. assert( pEList!=0 );
  75681. assert( pEList->nExpr>0 );
  75682. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  75683. pEList->a[0].pExpr);
  75684. }else if( ALWAYS(pExpr->x.pList!=0) ){
  75685. /* Case 2: expr IN (exprlist)
  75686. **
  75687. ** For each expression, build an index key from the evaluation and
  75688. ** store it in the temporary table. If <expr> is a column, then use
  75689. ** that columns affinity when building index keys. If <expr> is not
  75690. ** a column, use numeric affinity.
  75691. */
  75692. int i;
  75693. ExprList *pList = pExpr->x.pList;
  75694. struct ExprList_item *pItem;
  75695. int r1, r2, r3;
  75696. if( !affinity ){
  75697. affinity = SQLITE_AFF_NONE;
  75698. }
  75699. if( pKeyInfo ){
  75700. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  75701. }
  75702. /* Loop through each expression in <exprlist>. */
  75703. r1 = sqlite3GetTempReg(pParse);
  75704. r2 = sqlite3GetTempReg(pParse);
  75705. sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  75706. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  75707. Expr *pE2 = pItem->pExpr;
  75708. int iValToIns;
  75709. /* If the expression is not constant then we will need to
  75710. ** disable the test that was generated above that makes sure
  75711. ** this code only executes once. Because for a non-constant
  75712. ** expression we need to rerun this code each time.
  75713. */
  75714. if( testAddr>=0 && !sqlite3ExprIsConstant(pE2) ){
  75715. sqlite3VdbeChangeToNoop(v, testAddr);
  75716. testAddr = -1;
  75717. }
  75718. /* Evaluate the expression and insert it into the temp table */
  75719. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  75720. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  75721. }else{
  75722. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  75723. if( isRowid ){
  75724. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  75725. sqlite3VdbeCurrentAddr(v)+2);
  75726. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  75727. }else{
  75728. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  75729. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  75730. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  75731. }
  75732. }
  75733. }
  75734. sqlite3ReleaseTempReg(pParse, r1);
  75735. sqlite3ReleaseTempReg(pParse, r2);
  75736. }
  75737. if( pKeyInfo ){
  75738. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO_HANDOFF);
  75739. }
  75740. break;
  75741. }
  75742. case TK_EXISTS:
  75743. case TK_SELECT:
  75744. default: {
  75745. /* If this has to be a scalar SELECT. Generate code to put the
  75746. ** value of this select in a memory cell and record the number
  75747. ** of the memory cell in iColumn. If this is an EXISTS, write
  75748. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  75749. ** and record that memory cell in iColumn.
  75750. */
  75751. Select *pSel; /* SELECT statement to encode */
  75752. SelectDest dest; /* How to deal with SELECt result */
  75753. testcase( pExpr->op==TK_EXISTS );
  75754. testcase( pExpr->op==TK_SELECT );
  75755. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  75756. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  75757. pSel = pExpr->x.pSelect;
  75758. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  75759. if( pExpr->op==TK_SELECT ){
  75760. dest.eDest = SRT_Mem;
  75761. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  75762. VdbeComment((v, "Init subquery result"));
  75763. }else{
  75764. dest.eDest = SRT_Exists;
  75765. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  75766. VdbeComment((v, "Init EXISTS result"));
  75767. }
  75768. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  75769. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  75770. &sqlite3IntTokens[1]);
  75771. pSel->iLimit = 0;
  75772. if( sqlite3Select(pParse, pSel, &dest) ){
  75773. return 0;
  75774. }
  75775. rReg = dest.iSDParm;
  75776. ExprSetVVAProperty(pExpr, EP_NoReduce);
  75777. break;
  75778. }
  75779. }
  75780. if( testAddr>=0 ){
  75781. sqlite3VdbeJumpHere(v, testAddr);
  75782. }
  75783. sqlite3ExprCachePop(pParse, 1);
  75784. return rReg;
  75785. }
  75786. #endif /* SQLITE_OMIT_SUBQUERY */
  75787. #ifndef SQLITE_OMIT_SUBQUERY
  75788. /*
  75789. ** Generate code for an IN expression.
  75790. **
  75791. ** x IN (SELECT ...)
  75792. ** x IN (value, value, ...)
  75793. **
  75794. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  75795. ** is an array of zero or more values. The expression is true if the LHS is
  75796. ** contained within the RHS. The value of the expression is unknown (NULL)
  75797. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  75798. ** RHS contains one or more NULL values.
  75799. **
  75800. ** This routine generates code will jump to destIfFalse if the LHS is not
  75801. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  75802. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  75803. ** within the RHS then fall through.
  75804. */
  75805. static void sqlite3ExprCodeIN(
  75806. Parse *pParse, /* Parsing and code generating context */
  75807. Expr *pExpr, /* The IN expression */
  75808. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  75809. int destIfNull /* Jump here if the results are unknown due to NULLs */
  75810. ){
  75811. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  75812. char affinity; /* Comparison affinity to use */
  75813. int eType; /* Type of the RHS */
  75814. int r1; /* Temporary use register */
  75815. Vdbe *v; /* Statement under construction */
  75816. /* Compute the RHS. After this step, the table with cursor
  75817. ** pExpr->iTable will contains the values that make up the RHS.
  75818. */
  75819. v = pParse->pVdbe;
  75820. assert( v!=0 ); /* OOM detected prior to this routine */
  75821. VdbeNoopComment((v, "begin IN expr"));
  75822. eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
  75823. /* Figure out the affinity to use to create a key from the results
  75824. ** of the expression. affinityStr stores a static string suitable for
  75825. ** P4 of OP_MakeRecord.
  75826. */
  75827. affinity = comparisonAffinity(pExpr);
  75828. /* Code the LHS, the <expr> from "<expr> IN (...)".
  75829. */
  75830. sqlite3ExprCachePush(pParse);
  75831. r1 = sqlite3GetTempReg(pParse);
  75832. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  75833. /* If the LHS is NULL, then the result is either false or NULL depending
  75834. ** on whether the RHS is empty or not, respectively.
  75835. */
  75836. if( destIfNull==destIfFalse ){
  75837. /* Shortcut for the common case where the false and NULL outcomes are
  75838. ** the same. */
  75839. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
  75840. }else{
  75841. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
  75842. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  75843. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  75844. sqlite3VdbeJumpHere(v, addr1);
  75845. }
  75846. if( eType==IN_INDEX_ROWID ){
  75847. /* In this case, the RHS is the ROWID of table b-tree
  75848. */
  75849. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
  75850. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  75851. }else{
  75852. /* In this case, the RHS is an index b-tree.
  75853. */
  75854. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  75855. /* If the set membership test fails, then the result of the
  75856. ** "x IN (...)" expression must be either 0 or NULL. If the set
  75857. ** contains no NULL values, then the result is 0. If the set
  75858. ** contains one or more NULL values, then the result of the
  75859. ** expression is also NULL.
  75860. */
  75861. if( rRhsHasNull==0 || destIfFalse==destIfNull ){
  75862. /* This branch runs if it is known at compile time that the RHS
  75863. ** cannot contain NULL values. This happens as the result
  75864. ** of a "NOT NULL" constraint in the database schema.
  75865. **
  75866. ** Also run this branch if NULL is equivalent to FALSE
  75867. ** for this particular IN operator.
  75868. */
  75869. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  75870. }else{
  75871. /* In this branch, the RHS of the IN might contain a NULL and
  75872. ** the presence of a NULL on the RHS makes a difference in the
  75873. ** outcome.
  75874. */
  75875. int j1, j2, j3;
  75876. /* First check to see if the LHS is contained in the RHS. If so,
  75877. ** then the presence of NULLs in the RHS does not matter, so jump
  75878. ** over all of the code that follows.
  75879. */
  75880. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  75881. /* Here we begin generating code that runs if the LHS is not
  75882. ** contained within the RHS. Generate additional code that
  75883. ** tests the RHS for NULLs. If the RHS contains a NULL then
  75884. ** jump to destIfNull. If there are no NULLs in the RHS then
  75885. ** jump to destIfFalse.
  75886. */
  75887. j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
  75888. j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
  75889. sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
  75890. sqlite3VdbeJumpHere(v, j3);
  75891. sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
  75892. sqlite3VdbeJumpHere(v, j2);
  75893. /* Jump to the appropriate target depending on whether or not
  75894. ** the RHS contains a NULL
  75895. */
  75896. sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
  75897. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  75898. /* The OP_Found at the top of this branch jumps here when true,
  75899. ** causing the overall IN expression evaluation to fall through.
  75900. */
  75901. sqlite3VdbeJumpHere(v, j1);
  75902. }
  75903. }
  75904. sqlite3ReleaseTempReg(pParse, r1);
  75905. sqlite3ExprCachePop(pParse, 1);
  75906. VdbeComment((v, "end IN expr"));
  75907. }
  75908. #endif /* SQLITE_OMIT_SUBQUERY */
  75909. /*
  75910. ** Duplicate an 8-byte value
  75911. */
  75912. static char *dup8bytes(Vdbe *v, const char *in){
  75913. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  75914. if( out ){
  75915. memcpy(out, in, 8);
  75916. }
  75917. return out;
  75918. }
  75919. #ifndef SQLITE_OMIT_FLOATING_POINT
  75920. /*
  75921. ** Generate an instruction that will put the floating point
  75922. ** value described by z[0..n-1] into register iMem.
  75923. **
  75924. ** The z[] string will probably not be zero-terminated. But the
  75925. ** z[n] character is guaranteed to be something that does not look
  75926. ** like the continuation of the number.
  75927. */
  75928. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  75929. if( ALWAYS(z!=0) ){
  75930. double value;
  75931. char *zV;
  75932. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  75933. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  75934. if( negateFlag ) value = -value;
  75935. zV = dup8bytes(v, (char*)&value);
  75936. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  75937. }
  75938. }
  75939. #endif
  75940. /*
  75941. ** Generate an instruction that will put the integer describe by
  75942. ** text z[0..n-1] into register iMem.
  75943. **
  75944. ** Expr.u.zToken is always UTF8 and zero-terminated.
  75945. */
  75946. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  75947. Vdbe *v = pParse->pVdbe;
  75948. if( pExpr->flags & EP_IntValue ){
  75949. int i = pExpr->u.iValue;
  75950. assert( i>=0 );
  75951. if( negFlag ) i = -i;
  75952. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  75953. }else{
  75954. int c;
  75955. i64 value;
  75956. const char *z = pExpr->u.zToken;
  75957. assert( z!=0 );
  75958. c = sqlite3Atoi64(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  75959. if( c==0 || (c==2 && negFlag) ){
  75960. char *zV;
  75961. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  75962. zV = dup8bytes(v, (char*)&value);
  75963. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  75964. }else{
  75965. #ifdef SQLITE_OMIT_FLOATING_POINT
  75966. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  75967. #else
  75968. codeReal(v, z, negFlag, iMem);
  75969. #endif
  75970. }
  75971. }
  75972. }
  75973. /*
  75974. ** Clear a cache entry.
  75975. */
  75976. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  75977. if( p->tempReg ){
  75978. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  75979. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  75980. }
  75981. p->tempReg = 0;
  75982. }
  75983. }
  75984. /*
  75985. ** Record in the column cache that a particular column from a
  75986. ** particular table is stored in a particular register.
  75987. */
  75988. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  75989. int i;
  75990. int minLru;
  75991. int idxLru;
  75992. struct yColCache *p;
  75993. assert( iReg>0 ); /* Register numbers are always positive */
  75994. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  75995. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  75996. ** for testing only - to verify that SQLite always gets the same answer
  75997. ** with and without the column cache.
  75998. */
  75999. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  76000. /* First replace any existing entry.
  76001. **
  76002. ** Actually, the way the column cache is currently used, we are guaranteed
  76003. ** that the object will never already be in cache. Verify this guarantee.
  76004. */
  76005. #ifndef NDEBUG
  76006. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76007. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  76008. }
  76009. #endif
  76010. /* Find an empty slot and replace it */
  76011. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76012. if( p->iReg==0 ){
  76013. p->iLevel = pParse->iCacheLevel;
  76014. p->iTable = iTab;
  76015. p->iColumn = iCol;
  76016. p->iReg = iReg;
  76017. p->tempReg = 0;
  76018. p->lru = pParse->iCacheCnt++;
  76019. return;
  76020. }
  76021. }
  76022. /* Replace the last recently used */
  76023. minLru = 0x7fffffff;
  76024. idxLru = -1;
  76025. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76026. if( p->lru<minLru ){
  76027. idxLru = i;
  76028. minLru = p->lru;
  76029. }
  76030. }
  76031. if( ALWAYS(idxLru>=0) ){
  76032. p = &pParse->aColCache[idxLru];
  76033. p->iLevel = pParse->iCacheLevel;
  76034. p->iTable = iTab;
  76035. p->iColumn = iCol;
  76036. p->iReg = iReg;
  76037. p->tempReg = 0;
  76038. p->lru = pParse->iCacheCnt++;
  76039. return;
  76040. }
  76041. }
  76042. /*
  76043. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  76044. ** Purge the range of registers from the column cache.
  76045. */
  76046. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  76047. int i;
  76048. int iLast = iReg + nReg - 1;
  76049. struct yColCache *p;
  76050. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76051. int r = p->iReg;
  76052. if( r>=iReg && r<=iLast ){
  76053. cacheEntryClear(pParse, p);
  76054. p->iReg = 0;
  76055. }
  76056. }
  76057. }
  76058. /*
  76059. ** Remember the current column cache context. Any new entries added
  76060. ** added to the column cache after this call are removed when the
  76061. ** corresponding pop occurs.
  76062. */
  76063. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  76064. pParse->iCacheLevel++;
  76065. }
  76066. /*
  76067. ** Remove from the column cache any entries that were added since the
  76068. ** the previous N Push operations. In other words, restore the cache
  76069. ** to the state it was in N Pushes ago.
  76070. */
  76071. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
  76072. int i;
  76073. struct yColCache *p;
  76074. assert( N>0 );
  76075. assert( pParse->iCacheLevel>=N );
  76076. pParse->iCacheLevel -= N;
  76077. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76078. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  76079. cacheEntryClear(pParse, p);
  76080. p->iReg = 0;
  76081. }
  76082. }
  76083. }
  76084. /*
  76085. ** When a cached column is reused, make sure that its register is
  76086. ** no longer available as a temp register. ticket #3879: that same
  76087. ** register might be in the cache in multiple places, so be sure to
  76088. ** get them all.
  76089. */
  76090. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  76091. int i;
  76092. struct yColCache *p;
  76093. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76094. if( p->iReg==iReg ){
  76095. p->tempReg = 0;
  76096. }
  76097. }
  76098. }
  76099. /*
  76100. ** Generate code to extract the value of the iCol-th column of a table.
  76101. */
  76102. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  76103. Vdbe *v, /* The VDBE under construction */
  76104. Table *pTab, /* The table containing the value */
  76105. int iTabCur, /* The cursor for this table */
  76106. int iCol, /* Index of the column to extract */
  76107. int regOut /* Extract the valud into this register */
  76108. ){
  76109. if( iCol<0 || iCol==pTab->iPKey ){
  76110. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  76111. }else{
  76112. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  76113. sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
  76114. }
  76115. if( iCol>=0 ){
  76116. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  76117. }
  76118. }
  76119. /*
  76120. ** Generate code that will extract the iColumn-th column from
  76121. ** table pTab and store the column value in a register. An effort
  76122. ** is made to store the column value in register iReg, but this is
  76123. ** not guaranteed. The location of the column value is returned.
  76124. **
  76125. ** There must be an open cursor to pTab in iTable when this routine
  76126. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  76127. */
  76128. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  76129. Parse *pParse, /* Parsing and code generating context */
  76130. Table *pTab, /* Description of the table we are reading from */
  76131. int iColumn, /* Index of the table column */
  76132. int iTable, /* The cursor pointing to the table */
  76133. int iReg, /* Store results here */
  76134. u8 p5 /* P5 value for OP_Column */
  76135. ){
  76136. Vdbe *v = pParse->pVdbe;
  76137. int i;
  76138. struct yColCache *p;
  76139. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76140. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  76141. p->lru = pParse->iCacheCnt++;
  76142. sqlite3ExprCachePinRegister(pParse, p->iReg);
  76143. return p->iReg;
  76144. }
  76145. }
  76146. assert( v!=0 );
  76147. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  76148. if( p5 ){
  76149. sqlite3VdbeChangeP5(v, p5);
  76150. }else{
  76151. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  76152. }
  76153. return iReg;
  76154. }
  76155. /*
  76156. ** Clear all column cache entries.
  76157. */
  76158. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  76159. int i;
  76160. struct yColCache *p;
  76161. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76162. if( p->iReg ){
  76163. cacheEntryClear(pParse, p);
  76164. p->iReg = 0;
  76165. }
  76166. }
  76167. }
  76168. /*
  76169. ** Record the fact that an affinity change has occurred on iCount
  76170. ** registers starting with iStart.
  76171. */
  76172. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  76173. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  76174. }
  76175. /*
  76176. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  76177. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  76178. */
  76179. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  76180. int i;
  76181. struct yColCache *p;
  76182. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  76183. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg-1);
  76184. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76185. int x = p->iReg;
  76186. if( x>=iFrom && x<iFrom+nReg ){
  76187. p->iReg += iTo-iFrom;
  76188. }
  76189. }
  76190. }
  76191. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  76192. /*
  76193. ** Return true if any register in the range iFrom..iTo (inclusive)
  76194. ** is used as part of the column cache.
  76195. **
  76196. ** This routine is used within assert() and testcase() macros only
  76197. ** and does not appear in a normal build.
  76198. */
  76199. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  76200. int i;
  76201. struct yColCache *p;
  76202. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  76203. int r = p->iReg;
  76204. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  76205. }
  76206. return 0;
  76207. }
  76208. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  76209. /*
  76210. ** Convert an expression node to a TK_REGISTER
  76211. */
  76212. static void exprToRegister(Expr *p, int iReg){
  76213. p->op2 = p->op;
  76214. p->op = TK_REGISTER;
  76215. p->iTable = iReg;
  76216. ExprClearProperty(p, EP_Skip);
  76217. }
  76218. /*
  76219. ** Generate code into the current Vdbe to evaluate the given
  76220. ** expression. Attempt to store the results in register "target".
  76221. ** Return the register where results are stored.
  76222. **
  76223. ** With this routine, there is no guarantee that results will
  76224. ** be stored in target. The result might be stored in some other
  76225. ** register if it is convenient to do so. The calling function
  76226. ** must check the return code and move the results to the desired
  76227. ** register.
  76228. */
  76229. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  76230. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  76231. int op; /* The opcode being coded */
  76232. int inReg = target; /* Results stored in register inReg */
  76233. int regFree1 = 0; /* If non-zero free this temporary register */
  76234. int regFree2 = 0; /* If non-zero free this temporary register */
  76235. int r1, r2, r3, r4; /* Various register numbers */
  76236. sqlite3 *db = pParse->db; /* The database connection */
  76237. assert( target>0 && target<=pParse->nMem );
  76238. if( v==0 ){
  76239. assert( pParse->db->mallocFailed );
  76240. return 0;
  76241. }
  76242. if( pExpr==0 ){
  76243. op = TK_NULL;
  76244. }else{
  76245. op = pExpr->op;
  76246. }
  76247. switch( op ){
  76248. case TK_AGG_COLUMN: {
  76249. AggInfo *pAggInfo = pExpr->pAggInfo;
  76250. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  76251. if( !pAggInfo->directMode ){
  76252. assert( pCol->iMem>0 );
  76253. inReg = pCol->iMem;
  76254. break;
  76255. }else if( pAggInfo->useSortingIdx ){
  76256. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  76257. pCol->iSorterColumn, target);
  76258. break;
  76259. }
  76260. /* Otherwise, fall thru into the TK_COLUMN case */
  76261. }
  76262. case TK_COLUMN: {
  76263. int iTab = pExpr->iTable;
  76264. if( iTab<0 ){
  76265. if( pParse->ckBase>0 ){
  76266. /* Generating CHECK constraints or inserting into partial index */
  76267. inReg = pExpr->iColumn + pParse->ckBase;
  76268. break;
  76269. }else{
  76270. /* Deleting from a partial index */
  76271. iTab = pParse->iPartIdxTab;
  76272. }
  76273. }
  76274. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  76275. pExpr->iColumn, iTab, target,
  76276. pExpr->op2);
  76277. break;
  76278. }
  76279. case TK_INTEGER: {
  76280. codeInteger(pParse, pExpr, 0, target);
  76281. break;
  76282. }
  76283. #ifndef SQLITE_OMIT_FLOATING_POINT
  76284. case TK_FLOAT: {
  76285. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76286. codeReal(v, pExpr->u.zToken, 0, target);
  76287. break;
  76288. }
  76289. #endif
  76290. case TK_STRING: {
  76291. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76292. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  76293. break;
  76294. }
  76295. case TK_NULL: {
  76296. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76297. break;
  76298. }
  76299. #ifndef SQLITE_OMIT_BLOB_LITERAL
  76300. case TK_BLOB: {
  76301. int n;
  76302. const char *z;
  76303. char *zBlob;
  76304. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76305. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  76306. assert( pExpr->u.zToken[1]=='\'' );
  76307. z = &pExpr->u.zToken[2];
  76308. n = sqlite3Strlen30(z) - 1;
  76309. assert( z[n]=='\'' );
  76310. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  76311. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  76312. break;
  76313. }
  76314. #endif
  76315. case TK_VARIABLE: {
  76316. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76317. assert( pExpr->u.zToken!=0 );
  76318. assert( pExpr->u.zToken[0]!=0 );
  76319. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  76320. if( pExpr->u.zToken[1]!=0 ){
  76321. assert( pExpr->u.zToken[0]=='?'
  76322. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  76323. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  76324. }
  76325. break;
  76326. }
  76327. case TK_REGISTER: {
  76328. inReg = pExpr->iTable;
  76329. break;
  76330. }
  76331. case TK_AS: {
  76332. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76333. break;
  76334. }
  76335. #ifndef SQLITE_OMIT_CAST
  76336. case TK_CAST: {
  76337. /* Expressions of the form: CAST(pLeft AS token) */
  76338. int aff, to_op;
  76339. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76340. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76341. aff = sqlite3AffinityType(pExpr->u.zToken, 0);
  76342. to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
  76343. assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
  76344. assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
  76345. assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
  76346. assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
  76347. assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
  76348. testcase( to_op==OP_ToText );
  76349. testcase( to_op==OP_ToBlob );
  76350. testcase( to_op==OP_ToNumeric );
  76351. testcase( to_op==OP_ToInt );
  76352. testcase( to_op==OP_ToReal );
  76353. if( inReg!=target ){
  76354. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  76355. inReg = target;
  76356. }
  76357. sqlite3VdbeAddOp1(v, to_op, inReg);
  76358. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  76359. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  76360. break;
  76361. }
  76362. #endif /* SQLITE_OMIT_CAST */
  76363. case TK_LT:
  76364. case TK_LE:
  76365. case TK_GT:
  76366. case TK_GE:
  76367. case TK_NE:
  76368. case TK_EQ: {
  76369. assert( TK_LT==OP_Lt );
  76370. assert( TK_LE==OP_Le );
  76371. assert( TK_GT==OP_Gt );
  76372. assert( TK_GE==OP_Ge );
  76373. assert( TK_EQ==OP_Eq );
  76374. assert( TK_NE==OP_Ne );
  76375. testcase( op==TK_LT );
  76376. testcase( op==TK_LE );
  76377. testcase( op==TK_GT );
  76378. testcase( op==TK_GE );
  76379. testcase( op==TK_EQ );
  76380. testcase( op==TK_NE );
  76381. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76382. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76383. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  76384. r1, r2, inReg, SQLITE_STOREP2);
  76385. testcase( regFree1==0 );
  76386. testcase( regFree2==0 );
  76387. break;
  76388. }
  76389. case TK_IS:
  76390. case TK_ISNOT: {
  76391. testcase( op==TK_IS );
  76392. testcase( op==TK_ISNOT );
  76393. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76394. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76395. op = (op==TK_IS) ? TK_EQ : TK_NE;
  76396. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  76397. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  76398. testcase( regFree1==0 );
  76399. testcase( regFree2==0 );
  76400. break;
  76401. }
  76402. case TK_AND:
  76403. case TK_OR:
  76404. case TK_PLUS:
  76405. case TK_STAR:
  76406. case TK_MINUS:
  76407. case TK_REM:
  76408. case TK_BITAND:
  76409. case TK_BITOR:
  76410. case TK_SLASH:
  76411. case TK_LSHIFT:
  76412. case TK_RSHIFT:
  76413. case TK_CONCAT: {
  76414. assert( TK_AND==OP_And );
  76415. assert( TK_OR==OP_Or );
  76416. assert( TK_PLUS==OP_Add );
  76417. assert( TK_MINUS==OP_Subtract );
  76418. assert( TK_REM==OP_Remainder );
  76419. assert( TK_BITAND==OP_BitAnd );
  76420. assert( TK_BITOR==OP_BitOr );
  76421. assert( TK_SLASH==OP_Divide );
  76422. assert( TK_LSHIFT==OP_ShiftLeft );
  76423. assert( TK_RSHIFT==OP_ShiftRight );
  76424. assert( TK_CONCAT==OP_Concat );
  76425. testcase( op==TK_AND );
  76426. testcase( op==TK_OR );
  76427. testcase( op==TK_PLUS );
  76428. testcase( op==TK_MINUS );
  76429. testcase( op==TK_REM );
  76430. testcase( op==TK_BITAND );
  76431. testcase( op==TK_BITOR );
  76432. testcase( op==TK_SLASH );
  76433. testcase( op==TK_LSHIFT );
  76434. testcase( op==TK_RSHIFT );
  76435. testcase( op==TK_CONCAT );
  76436. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76437. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  76438. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  76439. testcase( regFree1==0 );
  76440. testcase( regFree2==0 );
  76441. break;
  76442. }
  76443. case TK_UMINUS: {
  76444. Expr *pLeft = pExpr->pLeft;
  76445. assert( pLeft );
  76446. if( pLeft->op==TK_INTEGER ){
  76447. codeInteger(pParse, pLeft, 1, target);
  76448. #ifndef SQLITE_OMIT_FLOATING_POINT
  76449. }else if( pLeft->op==TK_FLOAT ){
  76450. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76451. codeReal(v, pLeft->u.zToken, 1, target);
  76452. #endif
  76453. }else{
  76454. regFree1 = r1 = sqlite3GetTempReg(pParse);
  76455. sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
  76456. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  76457. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  76458. testcase( regFree2==0 );
  76459. }
  76460. inReg = target;
  76461. break;
  76462. }
  76463. case TK_BITNOT:
  76464. case TK_NOT: {
  76465. assert( TK_BITNOT==OP_BitNot );
  76466. assert( TK_NOT==OP_Not );
  76467. testcase( op==TK_BITNOT );
  76468. testcase( op==TK_NOT );
  76469. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76470. testcase( regFree1==0 );
  76471. inReg = target;
  76472. sqlite3VdbeAddOp2(v, op, r1, inReg);
  76473. break;
  76474. }
  76475. case TK_ISNULL:
  76476. case TK_NOTNULL: {
  76477. int addr;
  76478. assert( TK_ISNULL==OP_IsNull );
  76479. assert( TK_NOTNULL==OP_NotNull );
  76480. testcase( op==TK_ISNULL );
  76481. testcase( op==TK_NOTNULL );
  76482. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  76483. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  76484. testcase( regFree1==0 );
  76485. addr = sqlite3VdbeAddOp1(v, op, r1);
  76486. sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
  76487. sqlite3VdbeJumpHere(v, addr);
  76488. break;
  76489. }
  76490. case TK_AGG_FUNCTION: {
  76491. AggInfo *pInfo = pExpr->pAggInfo;
  76492. if( pInfo==0 ){
  76493. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76494. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  76495. }else{
  76496. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  76497. }
  76498. break;
  76499. }
  76500. case TK_CONST_FUNC:
  76501. case TK_FUNCTION: {
  76502. ExprList *pFarg; /* List of function arguments */
  76503. int nFarg; /* Number of function arguments */
  76504. FuncDef *pDef; /* The function definition object */
  76505. int nId; /* Length of the function name in bytes */
  76506. const char *zId; /* The function name */
  76507. int constMask = 0; /* Mask of function arguments that are constant */
  76508. int i; /* Loop counter */
  76509. u8 enc = ENC(db); /* The text encoding used by this database */
  76510. CollSeq *pColl = 0; /* A collating sequence */
  76511. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  76512. testcase( op==TK_CONST_FUNC );
  76513. testcase( op==TK_FUNCTION );
  76514. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  76515. pFarg = 0;
  76516. }else{
  76517. pFarg = pExpr->x.pList;
  76518. }
  76519. nFarg = pFarg ? pFarg->nExpr : 0;
  76520. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76521. zId = pExpr->u.zToken;
  76522. nId = sqlite3Strlen30(zId);
  76523. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  76524. if( pDef==0 ){
  76525. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  76526. break;
  76527. }
  76528. /* Attempt a direct implementation of the built-in COALESCE() and
  76529. ** IFNULL() functions. This avoids unnecessary evalation of
  76530. ** arguments past the first non-NULL argument.
  76531. */
  76532. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  76533. int endCoalesce = sqlite3VdbeMakeLabel(v);
  76534. assert( nFarg>=2 );
  76535. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  76536. for(i=1; i<nFarg; i++){
  76537. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  76538. sqlite3ExprCacheRemove(pParse, target, 1);
  76539. sqlite3ExprCachePush(pParse);
  76540. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  76541. sqlite3ExprCachePop(pParse, 1);
  76542. }
  76543. sqlite3VdbeResolveLabel(v, endCoalesce);
  76544. break;
  76545. }
  76546. /* The UNLIKELY() function is a no-op. The result is the value
  76547. ** of the first argument.
  76548. */
  76549. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  76550. assert( nFarg>=1 );
  76551. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  76552. break;
  76553. }
  76554. if( pFarg ){
  76555. r1 = sqlite3GetTempRange(pParse, nFarg);
  76556. /* For length() and typeof() functions with a column argument,
  76557. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  76558. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  76559. ** loading.
  76560. */
  76561. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  76562. u8 exprOp;
  76563. assert( nFarg==1 );
  76564. assert( pFarg->a[0].pExpr!=0 );
  76565. exprOp = pFarg->a[0].pExpr->op;
  76566. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  76567. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  76568. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  76569. testcase( (pDef->funcFlags&~SQLITE_FUNC_ENCMASK)
  76570. ==SQLITE_FUNC_LENGTH );
  76571. pFarg->a[0].pExpr->op2 = pDef->funcFlags&~SQLITE_FUNC_ENCMASK;
  76572. }
  76573. }
  76574. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  76575. sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
  76576. sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
  76577. }else{
  76578. r1 = 0;
  76579. }
  76580. #ifndef SQLITE_OMIT_VIRTUALTABLE
  76581. /* Possibly overload the function if the first argument is
  76582. ** a virtual table column.
  76583. **
  76584. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  76585. ** second argument, not the first, as the argument to test to
  76586. ** see if it is a column in a virtual table. This is done because
  76587. ** the left operand of infix functions (the operand we want to
  76588. ** control overloading) ends up as the second argument to the
  76589. ** function. The expression "A glob B" is equivalent to
  76590. ** "glob(B,A). We want to use the A in "A glob B" to test
  76591. ** for function overloading. But we use the B term in "glob(B,A)".
  76592. */
  76593. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  76594. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  76595. }else if( nFarg>0 ){
  76596. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  76597. }
  76598. #endif
  76599. for(i=0; i<nFarg; i++){
  76600. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  76601. constMask |= (1<<i);
  76602. }
  76603. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  76604. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  76605. }
  76606. }
  76607. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  76608. if( !pColl ) pColl = db->pDfltColl;
  76609. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  76610. }
  76611. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  76612. (char*)pDef, P4_FUNCDEF);
  76613. sqlite3VdbeChangeP5(v, (u8)nFarg);
  76614. if( nFarg ){
  76615. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  76616. }
  76617. break;
  76618. }
  76619. #ifndef SQLITE_OMIT_SUBQUERY
  76620. case TK_EXISTS:
  76621. case TK_SELECT: {
  76622. testcase( op==TK_EXISTS );
  76623. testcase( op==TK_SELECT );
  76624. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  76625. break;
  76626. }
  76627. case TK_IN: {
  76628. int destIfFalse = sqlite3VdbeMakeLabel(v);
  76629. int destIfNull = sqlite3VdbeMakeLabel(v);
  76630. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76631. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  76632. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  76633. sqlite3VdbeResolveLabel(v, destIfFalse);
  76634. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  76635. sqlite3VdbeResolveLabel(v, destIfNull);
  76636. break;
  76637. }
  76638. #endif /* SQLITE_OMIT_SUBQUERY */
  76639. /*
  76640. ** x BETWEEN y AND z
  76641. **
  76642. ** This is equivalent to
  76643. **
  76644. ** x>=y AND x<=z
  76645. **
  76646. ** X is stored in pExpr->pLeft.
  76647. ** Y is stored in pExpr->pList->a[0].pExpr.
  76648. ** Z is stored in pExpr->pList->a[1].pExpr.
  76649. */
  76650. case TK_BETWEEN: {
  76651. Expr *pLeft = pExpr->pLeft;
  76652. struct ExprList_item *pLItem = pExpr->x.pList->a;
  76653. Expr *pRight = pLItem->pExpr;
  76654. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  76655. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  76656. testcase( regFree1==0 );
  76657. testcase( regFree2==0 );
  76658. r3 = sqlite3GetTempReg(pParse);
  76659. r4 = sqlite3GetTempReg(pParse);
  76660. codeCompare(pParse, pLeft, pRight, OP_Ge,
  76661. r1, r2, r3, SQLITE_STOREP2);
  76662. pLItem++;
  76663. pRight = pLItem->pExpr;
  76664. sqlite3ReleaseTempReg(pParse, regFree2);
  76665. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  76666. testcase( regFree2==0 );
  76667. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  76668. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  76669. sqlite3ReleaseTempReg(pParse, r3);
  76670. sqlite3ReleaseTempReg(pParse, r4);
  76671. break;
  76672. }
  76673. case TK_COLLATE:
  76674. case TK_UPLUS: {
  76675. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  76676. break;
  76677. }
  76678. case TK_TRIGGER: {
  76679. /* If the opcode is TK_TRIGGER, then the expression is a reference
  76680. ** to a column in the new.* or old.* pseudo-tables available to
  76681. ** trigger programs. In this case Expr.iTable is set to 1 for the
  76682. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  76683. ** is set to the column of the pseudo-table to read, or to -1 to
  76684. ** read the rowid field.
  76685. **
  76686. ** The expression is implemented using an OP_Param opcode. The p1
  76687. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  76688. ** to reference another column of the old.* pseudo-table, where
  76689. ** i is the index of the column. For a new.rowid reference, p1 is
  76690. ** set to (n+1), where n is the number of columns in each pseudo-table.
  76691. ** For a reference to any other column in the new.* pseudo-table, p1
  76692. ** is set to (n+2+i), where n and i are as defined previously. For
  76693. ** example, if the table on which triggers are being fired is
  76694. ** declared as:
  76695. **
  76696. ** CREATE TABLE t1(a, b);
  76697. **
  76698. ** Then p1 is interpreted as follows:
  76699. **
  76700. ** p1==0 -> old.rowid p1==3 -> new.rowid
  76701. ** p1==1 -> old.a p1==4 -> new.a
  76702. ** p1==2 -> old.b p1==5 -> new.b
  76703. */
  76704. Table *pTab = pExpr->pTab;
  76705. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  76706. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  76707. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  76708. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  76709. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  76710. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  76711. VdbeComment((v, "%s.%s -> $%d",
  76712. (pExpr->iTable ? "new" : "old"),
  76713. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  76714. target
  76715. ));
  76716. #ifndef SQLITE_OMIT_FLOATING_POINT
  76717. /* If the column has REAL affinity, it may currently be stored as an
  76718. ** integer. Use OP_RealAffinity to make sure it is really real. */
  76719. if( pExpr->iColumn>=0
  76720. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  76721. ){
  76722. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  76723. }
  76724. #endif
  76725. break;
  76726. }
  76727. /*
  76728. ** Form A:
  76729. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  76730. **
  76731. ** Form B:
  76732. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  76733. **
  76734. ** Form A is can be transformed into the equivalent form B as follows:
  76735. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  76736. ** WHEN x=eN THEN rN ELSE y END
  76737. **
  76738. ** X (if it exists) is in pExpr->pLeft.
  76739. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  76740. ** odd. The Y is also optional. If the number of elements in x.pList
  76741. ** is even, then Y is omitted and the "otherwise" result is NULL.
  76742. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  76743. **
  76744. ** The result of the expression is the Ri for the first matching Ei,
  76745. ** or if there is no matching Ei, the ELSE term Y, or if there is
  76746. ** no ELSE term, NULL.
  76747. */
  76748. default: assert( op==TK_CASE ); {
  76749. int endLabel; /* GOTO label for end of CASE stmt */
  76750. int nextCase; /* GOTO label for next WHEN clause */
  76751. int nExpr; /* 2x number of WHEN terms */
  76752. int i; /* Loop counter */
  76753. ExprList *pEList; /* List of WHEN terms */
  76754. struct ExprList_item *aListelem; /* Array of WHEN terms */
  76755. Expr opCompare; /* The X==Ei expression */
  76756. Expr cacheX; /* Cached expression X */
  76757. Expr *pX; /* The X expression */
  76758. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  76759. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  76760. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  76761. assert(pExpr->x.pList->nExpr > 0);
  76762. pEList = pExpr->x.pList;
  76763. aListelem = pEList->a;
  76764. nExpr = pEList->nExpr;
  76765. endLabel = sqlite3VdbeMakeLabel(v);
  76766. if( (pX = pExpr->pLeft)!=0 ){
  76767. cacheX = *pX;
  76768. testcase( pX->op==TK_COLUMN );
  76769. testcase( pX->op==TK_REGISTER );
  76770. exprToRegister(&cacheX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  76771. testcase( regFree1==0 );
  76772. opCompare.op = TK_EQ;
  76773. opCompare.pLeft = &cacheX;
  76774. pTest = &opCompare;
  76775. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  76776. ** The value in regFree1 might get SCopy-ed into the file result.
  76777. ** So make sure that the regFree1 register is not reused for other
  76778. ** purposes and possibly overwritten. */
  76779. regFree1 = 0;
  76780. }
  76781. for(i=0; i<nExpr-1; i=i+2){
  76782. sqlite3ExprCachePush(pParse);
  76783. if( pX ){
  76784. assert( pTest!=0 );
  76785. opCompare.pRight = aListelem[i].pExpr;
  76786. }else{
  76787. pTest = aListelem[i].pExpr;
  76788. }
  76789. nextCase = sqlite3VdbeMakeLabel(v);
  76790. testcase( pTest->op==TK_COLUMN );
  76791. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  76792. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  76793. testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
  76794. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  76795. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  76796. sqlite3ExprCachePop(pParse, 1);
  76797. sqlite3VdbeResolveLabel(v, nextCase);
  76798. }
  76799. if( (nExpr&1)!=0 ){
  76800. sqlite3ExprCachePush(pParse);
  76801. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  76802. sqlite3ExprCachePop(pParse, 1);
  76803. }else{
  76804. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  76805. }
  76806. assert( db->mallocFailed || pParse->nErr>0
  76807. || pParse->iCacheLevel==iCacheLevel );
  76808. sqlite3VdbeResolveLabel(v, endLabel);
  76809. break;
  76810. }
  76811. #ifndef SQLITE_OMIT_TRIGGER
  76812. case TK_RAISE: {
  76813. assert( pExpr->affinity==OE_Rollback
  76814. || pExpr->affinity==OE_Abort
  76815. || pExpr->affinity==OE_Fail
  76816. || pExpr->affinity==OE_Ignore
  76817. );
  76818. if( !pParse->pTriggerTab ){
  76819. sqlite3ErrorMsg(pParse,
  76820. "RAISE() may only be used within a trigger-program");
  76821. return 0;
  76822. }
  76823. if( pExpr->affinity==OE_Abort ){
  76824. sqlite3MayAbort(pParse);
  76825. }
  76826. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  76827. if( pExpr->affinity==OE_Ignore ){
  76828. sqlite3VdbeAddOp4(
  76829. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  76830. }else{
  76831. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  76832. pExpr->affinity, pExpr->u.zToken, 0);
  76833. }
  76834. break;
  76835. }
  76836. #endif
  76837. }
  76838. sqlite3ReleaseTempReg(pParse, regFree1);
  76839. sqlite3ReleaseTempReg(pParse, regFree2);
  76840. return inReg;
  76841. }
  76842. /*
  76843. ** Generate code to evaluate an expression and store the results
  76844. ** into a register. Return the register number where the results
  76845. ** are stored.
  76846. **
  76847. ** If the register is a temporary register that can be deallocated,
  76848. ** then write its number into *pReg. If the result register is not
  76849. ** a temporary, then set *pReg to zero.
  76850. */
  76851. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  76852. int r1 = sqlite3GetTempReg(pParse);
  76853. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  76854. if( r2==r1 ){
  76855. *pReg = r1;
  76856. }else{
  76857. sqlite3ReleaseTempReg(pParse, r1);
  76858. *pReg = 0;
  76859. }
  76860. return r2;
  76861. }
  76862. /*
  76863. ** Generate code that will evaluate expression pExpr and store the
  76864. ** results in register target. The results are guaranteed to appear
  76865. ** in register target.
  76866. */
  76867. SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  76868. int inReg;
  76869. assert( target>0 && target<=pParse->nMem );
  76870. if( pExpr && pExpr->op==TK_REGISTER ){
  76871. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  76872. }else{
  76873. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  76874. assert( pParse->pVdbe || pParse->db->mallocFailed );
  76875. if( inReg!=target && pParse->pVdbe ){
  76876. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  76877. }
  76878. }
  76879. return target;
  76880. }
  76881. /*
  76882. ** Generate code that evalutes the given expression and puts the result
  76883. ** in register target.
  76884. **
  76885. ** Also make a copy of the expression results into another "cache" register
  76886. ** and modify the expression so that the next time it is evaluated,
  76887. ** the result is a copy of the cache register.
  76888. **
  76889. ** This routine is used for expressions that are used multiple
  76890. ** times. They are evaluated once and the results of the expression
  76891. ** are reused.
  76892. */
  76893. SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  76894. Vdbe *v = pParse->pVdbe;
  76895. int inReg;
  76896. inReg = sqlite3ExprCode(pParse, pExpr, target);
  76897. assert( target>0 );
  76898. /* This routine is called for terms to INSERT or UPDATE. And the only
  76899. ** other place where expressions can be converted into TK_REGISTER is
  76900. ** in WHERE clause processing. So as currently implemented, there is
  76901. ** no way for a TK_REGISTER to exist here. But it seems prudent to
  76902. ** keep the ALWAYS() in case the conditions above change with future
  76903. ** modifications or enhancements. */
  76904. if( ALWAYS(pExpr->op!=TK_REGISTER) ){
  76905. int iMem;
  76906. iMem = ++pParse->nMem;
  76907. sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
  76908. exprToRegister(pExpr, iMem);
  76909. }
  76910. return inReg;
  76911. }
  76912. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  76913. /*
  76914. ** Generate a human-readable explanation of an expression tree.
  76915. */
  76916. SQLITE_PRIVATE void sqlite3ExplainExpr(Vdbe *pOut, Expr *pExpr){
  76917. int op; /* The opcode being coded */
  76918. const char *zBinOp = 0; /* Binary operator */
  76919. const char *zUniOp = 0; /* Unary operator */
  76920. if( pExpr==0 ){
  76921. op = TK_NULL;
  76922. }else{
  76923. op = pExpr->op;
  76924. }
  76925. switch( op ){
  76926. case TK_AGG_COLUMN: {
  76927. sqlite3ExplainPrintf(pOut, "AGG{%d:%d}",
  76928. pExpr->iTable, pExpr->iColumn);
  76929. break;
  76930. }
  76931. case TK_COLUMN: {
  76932. if( pExpr->iTable<0 ){
  76933. /* This only happens when coding check constraints */
  76934. sqlite3ExplainPrintf(pOut, "COLUMN(%d)", pExpr->iColumn);
  76935. }else{
  76936. sqlite3ExplainPrintf(pOut, "{%d:%d}",
  76937. pExpr->iTable, pExpr->iColumn);
  76938. }
  76939. break;
  76940. }
  76941. case TK_INTEGER: {
  76942. if( pExpr->flags & EP_IntValue ){
  76943. sqlite3ExplainPrintf(pOut, "%d", pExpr->u.iValue);
  76944. }else{
  76945. sqlite3ExplainPrintf(pOut, "%s", pExpr->u.zToken);
  76946. }
  76947. break;
  76948. }
  76949. #ifndef SQLITE_OMIT_FLOATING_POINT
  76950. case TK_FLOAT: {
  76951. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  76952. break;
  76953. }
  76954. #endif
  76955. case TK_STRING: {
  76956. sqlite3ExplainPrintf(pOut,"%Q", pExpr->u.zToken);
  76957. break;
  76958. }
  76959. case TK_NULL: {
  76960. sqlite3ExplainPrintf(pOut,"NULL");
  76961. break;
  76962. }
  76963. #ifndef SQLITE_OMIT_BLOB_LITERAL
  76964. case TK_BLOB: {
  76965. sqlite3ExplainPrintf(pOut,"%s", pExpr->u.zToken);
  76966. break;
  76967. }
  76968. #endif
  76969. case TK_VARIABLE: {
  76970. sqlite3ExplainPrintf(pOut,"VARIABLE(%s,%d)",
  76971. pExpr->u.zToken, pExpr->iColumn);
  76972. break;
  76973. }
  76974. case TK_REGISTER: {
  76975. sqlite3ExplainPrintf(pOut,"REGISTER(%d)", pExpr->iTable);
  76976. break;
  76977. }
  76978. case TK_AS: {
  76979. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  76980. break;
  76981. }
  76982. #ifndef SQLITE_OMIT_CAST
  76983. case TK_CAST: {
  76984. /* Expressions of the form: CAST(pLeft AS token) */
  76985. const char *zAff = "unk";
  76986. switch( sqlite3AffinityType(pExpr->u.zToken, 0) ){
  76987. case SQLITE_AFF_TEXT: zAff = "TEXT"; break;
  76988. case SQLITE_AFF_NONE: zAff = "NONE"; break;
  76989. case SQLITE_AFF_NUMERIC: zAff = "NUMERIC"; break;
  76990. case SQLITE_AFF_INTEGER: zAff = "INTEGER"; break;
  76991. case SQLITE_AFF_REAL: zAff = "REAL"; break;
  76992. }
  76993. sqlite3ExplainPrintf(pOut, "CAST-%s(", zAff);
  76994. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  76995. sqlite3ExplainPrintf(pOut, ")");
  76996. break;
  76997. }
  76998. #endif /* SQLITE_OMIT_CAST */
  76999. case TK_LT: zBinOp = "LT"; break;
  77000. case TK_LE: zBinOp = "LE"; break;
  77001. case TK_GT: zBinOp = "GT"; break;
  77002. case TK_GE: zBinOp = "GE"; break;
  77003. case TK_NE: zBinOp = "NE"; break;
  77004. case TK_EQ: zBinOp = "EQ"; break;
  77005. case TK_IS: zBinOp = "IS"; break;
  77006. case TK_ISNOT: zBinOp = "ISNOT"; break;
  77007. case TK_AND: zBinOp = "AND"; break;
  77008. case TK_OR: zBinOp = "OR"; break;
  77009. case TK_PLUS: zBinOp = "ADD"; break;
  77010. case TK_STAR: zBinOp = "MUL"; break;
  77011. case TK_MINUS: zBinOp = "SUB"; break;
  77012. case TK_REM: zBinOp = "REM"; break;
  77013. case TK_BITAND: zBinOp = "BITAND"; break;
  77014. case TK_BITOR: zBinOp = "BITOR"; break;
  77015. case TK_SLASH: zBinOp = "DIV"; break;
  77016. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  77017. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  77018. case TK_CONCAT: zBinOp = "CONCAT"; break;
  77019. case TK_UMINUS: zUniOp = "UMINUS"; break;
  77020. case TK_UPLUS: zUniOp = "UPLUS"; break;
  77021. case TK_BITNOT: zUniOp = "BITNOT"; break;
  77022. case TK_NOT: zUniOp = "NOT"; break;
  77023. case TK_ISNULL: zUniOp = "ISNULL"; break;
  77024. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  77025. case TK_COLLATE: {
  77026. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77027. sqlite3ExplainPrintf(pOut,".COLLATE(%s)",pExpr->u.zToken);
  77028. break;
  77029. }
  77030. case TK_AGG_FUNCTION:
  77031. case TK_CONST_FUNC:
  77032. case TK_FUNCTION: {
  77033. ExprList *pFarg; /* List of function arguments */
  77034. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  77035. pFarg = 0;
  77036. }else{
  77037. pFarg = pExpr->x.pList;
  77038. }
  77039. if( op==TK_AGG_FUNCTION ){
  77040. sqlite3ExplainPrintf(pOut, "AGG_FUNCTION%d:%s(",
  77041. pExpr->op2, pExpr->u.zToken);
  77042. }else{
  77043. sqlite3ExplainPrintf(pOut, "FUNCTION:%s(", pExpr->u.zToken);
  77044. }
  77045. if( pFarg ){
  77046. sqlite3ExplainExprList(pOut, pFarg);
  77047. }
  77048. sqlite3ExplainPrintf(pOut, ")");
  77049. break;
  77050. }
  77051. #ifndef SQLITE_OMIT_SUBQUERY
  77052. case TK_EXISTS: {
  77053. sqlite3ExplainPrintf(pOut, "EXISTS(");
  77054. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77055. sqlite3ExplainPrintf(pOut,")");
  77056. break;
  77057. }
  77058. case TK_SELECT: {
  77059. sqlite3ExplainPrintf(pOut, "(");
  77060. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77061. sqlite3ExplainPrintf(pOut, ")");
  77062. break;
  77063. }
  77064. case TK_IN: {
  77065. sqlite3ExplainPrintf(pOut, "IN(");
  77066. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77067. sqlite3ExplainPrintf(pOut, ",");
  77068. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77069. sqlite3ExplainSelect(pOut, pExpr->x.pSelect);
  77070. }else{
  77071. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  77072. }
  77073. sqlite3ExplainPrintf(pOut, ")");
  77074. break;
  77075. }
  77076. #endif /* SQLITE_OMIT_SUBQUERY */
  77077. /*
  77078. ** x BETWEEN y AND z
  77079. **
  77080. ** This is equivalent to
  77081. **
  77082. ** x>=y AND x<=z
  77083. **
  77084. ** X is stored in pExpr->pLeft.
  77085. ** Y is stored in pExpr->pList->a[0].pExpr.
  77086. ** Z is stored in pExpr->pList->a[1].pExpr.
  77087. */
  77088. case TK_BETWEEN: {
  77089. Expr *pX = pExpr->pLeft;
  77090. Expr *pY = pExpr->x.pList->a[0].pExpr;
  77091. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  77092. sqlite3ExplainPrintf(pOut, "BETWEEN(");
  77093. sqlite3ExplainExpr(pOut, pX);
  77094. sqlite3ExplainPrintf(pOut, ",");
  77095. sqlite3ExplainExpr(pOut, pY);
  77096. sqlite3ExplainPrintf(pOut, ",");
  77097. sqlite3ExplainExpr(pOut, pZ);
  77098. sqlite3ExplainPrintf(pOut, ")");
  77099. break;
  77100. }
  77101. case TK_TRIGGER: {
  77102. /* If the opcode is TK_TRIGGER, then the expression is a reference
  77103. ** to a column in the new.* or old.* pseudo-tables available to
  77104. ** trigger programs. In this case Expr.iTable is set to 1 for the
  77105. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  77106. ** is set to the column of the pseudo-table to read, or to -1 to
  77107. ** read the rowid field.
  77108. */
  77109. sqlite3ExplainPrintf(pOut, "%s(%d)",
  77110. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  77111. break;
  77112. }
  77113. case TK_CASE: {
  77114. sqlite3ExplainPrintf(pOut, "CASE(");
  77115. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77116. sqlite3ExplainPrintf(pOut, ",");
  77117. sqlite3ExplainExprList(pOut, pExpr->x.pList);
  77118. break;
  77119. }
  77120. #ifndef SQLITE_OMIT_TRIGGER
  77121. case TK_RAISE: {
  77122. const char *zType = "unk";
  77123. switch( pExpr->affinity ){
  77124. case OE_Rollback: zType = "rollback"; break;
  77125. case OE_Abort: zType = "abort"; break;
  77126. case OE_Fail: zType = "fail"; break;
  77127. case OE_Ignore: zType = "ignore"; break;
  77128. }
  77129. sqlite3ExplainPrintf(pOut, "RAISE-%s(%s)", zType, pExpr->u.zToken);
  77130. break;
  77131. }
  77132. #endif
  77133. }
  77134. if( zBinOp ){
  77135. sqlite3ExplainPrintf(pOut,"%s(", zBinOp);
  77136. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77137. sqlite3ExplainPrintf(pOut,",");
  77138. sqlite3ExplainExpr(pOut, pExpr->pRight);
  77139. sqlite3ExplainPrintf(pOut,")");
  77140. }else if( zUniOp ){
  77141. sqlite3ExplainPrintf(pOut,"%s(", zUniOp);
  77142. sqlite3ExplainExpr(pOut, pExpr->pLeft);
  77143. sqlite3ExplainPrintf(pOut,")");
  77144. }
  77145. }
  77146. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  77147. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  77148. /*
  77149. ** Generate a human-readable explanation of an expression list.
  77150. */
  77151. SQLITE_PRIVATE void sqlite3ExplainExprList(Vdbe *pOut, ExprList *pList){
  77152. int i;
  77153. if( pList==0 || pList->nExpr==0 ){
  77154. sqlite3ExplainPrintf(pOut, "(empty-list)");
  77155. return;
  77156. }else if( pList->nExpr==1 ){
  77157. sqlite3ExplainExpr(pOut, pList->a[0].pExpr);
  77158. }else{
  77159. sqlite3ExplainPush(pOut);
  77160. for(i=0; i<pList->nExpr; i++){
  77161. sqlite3ExplainPrintf(pOut, "item[%d] = ", i);
  77162. sqlite3ExplainPush(pOut);
  77163. sqlite3ExplainExpr(pOut, pList->a[i].pExpr);
  77164. sqlite3ExplainPop(pOut);
  77165. if( pList->a[i].zName ){
  77166. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  77167. }
  77168. if( pList->a[i].bSpanIsTab ){
  77169. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  77170. }
  77171. if( i<pList->nExpr-1 ){
  77172. sqlite3ExplainNL(pOut);
  77173. }
  77174. }
  77175. sqlite3ExplainPop(pOut);
  77176. }
  77177. }
  77178. #endif /* SQLITE_DEBUG */
  77179. /*
  77180. ** Return TRUE if pExpr is an constant expression that is appropriate
  77181. ** for factoring out of a loop. Appropriate expressions are:
  77182. **
  77183. ** * Any expression that evaluates to two or more opcodes.
  77184. **
  77185. ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
  77186. ** or OP_Variable that does not need to be placed in a
  77187. ** specific register.
  77188. **
  77189. ** There is no point in factoring out single-instruction constant
  77190. ** expressions that need to be placed in a particular register.
  77191. ** We could factor them out, but then we would end up adding an
  77192. ** OP_SCopy instruction to move the value into the correct register
  77193. ** later. We might as well just use the original instruction and
  77194. ** avoid the OP_SCopy.
  77195. */
  77196. static int isAppropriateForFactoring(Expr *p){
  77197. if( !sqlite3ExprIsConstantNotJoin(p) ){
  77198. return 0; /* Only constant expressions are appropriate for factoring */
  77199. }
  77200. if( (p->flags & EP_FixedDest)==0 ){
  77201. return 1; /* Any constant without a fixed destination is appropriate */
  77202. }
  77203. while( p->op==TK_UPLUS ) p = p->pLeft;
  77204. switch( p->op ){
  77205. #ifndef SQLITE_OMIT_BLOB_LITERAL
  77206. case TK_BLOB:
  77207. #endif
  77208. case TK_VARIABLE:
  77209. case TK_INTEGER:
  77210. case TK_FLOAT:
  77211. case TK_NULL:
  77212. case TK_STRING: {
  77213. testcase( p->op==TK_BLOB );
  77214. testcase( p->op==TK_VARIABLE );
  77215. testcase( p->op==TK_INTEGER );
  77216. testcase( p->op==TK_FLOAT );
  77217. testcase( p->op==TK_NULL );
  77218. testcase( p->op==TK_STRING );
  77219. /* Single-instruction constants with a fixed destination are
  77220. ** better done in-line. If we factor them, they will just end
  77221. ** up generating an OP_SCopy to move the value to the destination
  77222. ** register. */
  77223. return 0;
  77224. }
  77225. case TK_UMINUS: {
  77226. if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
  77227. return 0;
  77228. }
  77229. break;
  77230. }
  77231. default: {
  77232. break;
  77233. }
  77234. }
  77235. return 1;
  77236. }
  77237. /*
  77238. ** If pExpr is a constant expression that is appropriate for
  77239. ** factoring out of a loop, then evaluate the expression
  77240. ** into a register and convert the expression into a TK_REGISTER
  77241. ** expression.
  77242. */
  77243. static int evalConstExpr(Walker *pWalker, Expr *pExpr){
  77244. Parse *pParse = pWalker->pParse;
  77245. switch( pExpr->op ){
  77246. case TK_IN:
  77247. case TK_REGISTER: {
  77248. return WRC_Prune;
  77249. }
  77250. case TK_COLLATE: {
  77251. return WRC_Continue;
  77252. }
  77253. case TK_FUNCTION:
  77254. case TK_AGG_FUNCTION:
  77255. case TK_CONST_FUNC: {
  77256. /* The arguments to a function have a fixed destination.
  77257. ** Mark them this way to avoid generated unneeded OP_SCopy
  77258. ** instructions.
  77259. */
  77260. ExprList *pList = pExpr->x.pList;
  77261. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77262. if( pList ){
  77263. int i = pList->nExpr;
  77264. struct ExprList_item *pItem = pList->a;
  77265. for(; i>0; i--, pItem++){
  77266. if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
  77267. }
  77268. }
  77269. break;
  77270. }
  77271. }
  77272. if( isAppropriateForFactoring(pExpr) ){
  77273. int r1 = ++pParse->nMem;
  77274. int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  77275. /* If r2!=r1, it means that register r1 is never used. That is harmless
  77276. ** but suboptimal, so we want to know about the situation to fix it.
  77277. ** Hence the following assert: */
  77278. assert( r2==r1 );
  77279. exprToRegister(pExpr, r2);
  77280. return WRC_Prune;
  77281. }
  77282. return WRC_Continue;
  77283. }
  77284. /*
  77285. ** Preevaluate constant subexpressions within pExpr and store the
  77286. ** results in registers. Modify pExpr so that the constant subexpresions
  77287. ** are TK_REGISTER opcodes that refer to the precomputed values.
  77288. **
  77289. ** This routine is a no-op if the jump to the cookie-check code has
  77290. ** already occur. Since the cookie-check jump is generated prior to
  77291. ** any other serious processing, this check ensures that there is no
  77292. ** way to accidently bypass the constant initializations.
  77293. **
  77294. ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
  77295. ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
  77296. ** interface. This allows test logic to verify that the same answer is
  77297. ** obtained for queries regardless of whether or not constants are
  77298. ** precomputed into registers or if they are inserted in-line.
  77299. */
  77300. SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
  77301. Walker w;
  77302. if( pParse->cookieGoto ) return;
  77303. if( OptimizationDisabled(pParse->db, SQLITE_FactorOutConst) ) return;
  77304. memset(&w, 0, sizeof(w));
  77305. w.xExprCallback = evalConstExpr;
  77306. w.pParse = pParse;
  77307. sqlite3WalkExpr(&w, pExpr);
  77308. }
  77309. /*
  77310. ** Generate code that pushes the value of every element of the given
  77311. ** expression list into a sequence of registers beginning at target.
  77312. **
  77313. ** Return the number of elements evaluated.
  77314. */
  77315. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  77316. Parse *pParse, /* Parsing context */
  77317. ExprList *pList, /* The expression list to be coded */
  77318. int target, /* Where to write results */
  77319. int doHardCopy /* Make a hard copy of every element */
  77320. ){
  77321. struct ExprList_item *pItem;
  77322. int i, n;
  77323. assert( pList!=0 );
  77324. assert( target>0 );
  77325. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  77326. n = pList->nExpr;
  77327. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  77328. Expr *pExpr = pItem->pExpr;
  77329. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  77330. if( inReg!=target+i ){
  77331. sqlite3VdbeAddOp2(pParse->pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
  77332. inReg, target+i);
  77333. }
  77334. }
  77335. return n;
  77336. }
  77337. /*
  77338. ** Generate code for a BETWEEN operator.
  77339. **
  77340. ** x BETWEEN y AND z
  77341. **
  77342. ** The above is equivalent to
  77343. **
  77344. ** x>=y AND x<=z
  77345. **
  77346. ** Code it as such, taking care to do the common subexpression
  77347. ** elementation of x.
  77348. */
  77349. static void exprCodeBetween(
  77350. Parse *pParse, /* Parsing and code generating context */
  77351. Expr *pExpr, /* The BETWEEN expression */
  77352. int dest, /* Jump here if the jump is taken */
  77353. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  77354. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  77355. ){
  77356. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  77357. Expr compLeft; /* The x>=y term */
  77358. Expr compRight; /* The x<=z term */
  77359. Expr exprX; /* The x subexpression */
  77360. int regFree1 = 0; /* Temporary use register */
  77361. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77362. exprX = *pExpr->pLeft;
  77363. exprAnd.op = TK_AND;
  77364. exprAnd.pLeft = &compLeft;
  77365. exprAnd.pRight = &compRight;
  77366. compLeft.op = TK_GE;
  77367. compLeft.pLeft = &exprX;
  77368. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  77369. compRight.op = TK_LE;
  77370. compRight.pLeft = &exprX;
  77371. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  77372. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  77373. if( jumpIfTrue ){
  77374. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  77375. }else{
  77376. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  77377. }
  77378. sqlite3ReleaseTempReg(pParse, regFree1);
  77379. /* Ensure adequate test coverage */
  77380. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  77381. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  77382. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  77383. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  77384. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  77385. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  77386. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  77387. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  77388. }
  77389. /*
  77390. ** Generate code for a boolean expression such that a jump is made
  77391. ** to the label "dest" if the expression is true but execution
  77392. ** continues straight thru if the expression is false.
  77393. **
  77394. ** If the expression evaluates to NULL (neither true nor false), then
  77395. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  77396. **
  77397. ** This code depends on the fact that certain token values (ex: TK_EQ)
  77398. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  77399. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  77400. ** the make process cause these values to align. Assert()s in the code
  77401. ** below verify that the numbers are aligned correctly.
  77402. */
  77403. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  77404. Vdbe *v = pParse->pVdbe;
  77405. int op = 0;
  77406. int regFree1 = 0;
  77407. int regFree2 = 0;
  77408. int r1, r2;
  77409. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  77410. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  77411. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  77412. op = pExpr->op;
  77413. switch( op ){
  77414. case TK_AND: {
  77415. int d2 = sqlite3VdbeMakeLabel(v);
  77416. testcase( jumpIfNull==0 );
  77417. sqlite3ExprCachePush(pParse);
  77418. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  77419. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  77420. sqlite3VdbeResolveLabel(v, d2);
  77421. sqlite3ExprCachePop(pParse, 1);
  77422. break;
  77423. }
  77424. case TK_OR: {
  77425. testcase( jumpIfNull==0 );
  77426. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  77427. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  77428. break;
  77429. }
  77430. case TK_NOT: {
  77431. testcase( jumpIfNull==0 );
  77432. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  77433. break;
  77434. }
  77435. case TK_LT:
  77436. case TK_LE:
  77437. case TK_GT:
  77438. case TK_GE:
  77439. case TK_NE:
  77440. case TK_EQ: {
  77441. assert( TK_LT==OP_Lt );
  77442. assert( TK_LE==OP_Le );
  77443. assert( TK_GT==OP_Gt );
  77444. assert( TK_GE==OP_Ge );
  77445. assert( TK_EQ==OP_Eq );
  77446. assert( TK_NE==OP_Ne );
  77447. testcase( op==TK_LT );
  77448. testcase( op==TK_LE );
  77449. testcase( op==TK_GT );
  77450. testcase( op==TK_GE );
  77451. testcase( op==TK_EQ );
  77452. testcase( op==TK_NE );
  77453. testcase( jumpIfNull==0 );
  77454. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77455. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77456. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77457. r1, r2, dest, jumpIfNull);
  77458. testcase( regFree1==0 );
  77459. testcase( regFree2==0 );
  77460. break;
  77461. }
  77462. case TK_IS:
  77463. case TK_ISNOT: {
  77464. testcase( op==TK_IS );
  77465. testcase( op==TK_ISNOT );
  77466. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77467. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77468. op = (op==TK_IS) ? TK_EQ : TK_NE;
  77469. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77470. r1, r2, dest, SQLITE_NULLEQ);
  77471. testcase( regFree1==0 );
  77472. testcase( regFree2==0 );
  77473. break;
  77474. }
  77475. case TK_ISNULL:
  77476. case TK_NOTNULL: {
  77477. assert( TK_ISNULL==OP_IsNull );
  77478. assert( TK_NOTNULL==OP_NotNull );
  77479. testcase( op==TK_ISNULL );
  77480. testcase( op==TK_NOTNULL );
  77481. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77482. sqlite3VdbeAddOp2(v, op, r1, dest);
  77483. testcase( regFree1==0 );
  77484. break;
  77485. }
  77486. case TK_BETWEEN: {
  77487. testcase( jumpIfNull==0 );
  77488. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  77489. break;
  77490. }
  77491. #ifndef SQLITE_OMIT_SUBQUERY
  77492. case TK_IN: {
  77493. int destIfFalse = sqlite3VdbeMakeLabel(v);
  77494. int destIfNull = jumpIfNull ? dest : destIfFalse;
  77495. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  77496. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  77497. sqlite3VdbeResolveLabel(v, destIfFalse);
  77498. break;
  77499. }
  77500. #endif
  77501. default: {
  77502. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  77503. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  77504. testcase( regFree1==0 );
  77505. testcase( jumpIfNull==0 );
  77506. break;
  77507. }
  77508. }
  77509. sqlite3ReleaseTempReg(pParse, regFree1);
  77510. sqlite3ReleaseTempReg(pParse, regFree2);
  77511. }
  77512. /*
  77513. ** Generate code for a boolean expression such that a jump is made
  77514. ** to the label "dest" if the expression is false but execution
  77515. ** continues straight thru if the expression is true.
  77516. **
  77517. ** If the expression evaluates to NULL (neither true nor false) then
  77518. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  77519. ** is 0.
  77520. */
  77521. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  77522. Vdbe *v = pParse->pVdbe;
  77523. int op = 0;
  77524. int regFree1 = 0;
  77525. int regFree2 = 0;
  77526. int r1, r2;
  77527. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  77528. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  77529. if( pExpr==0 ) return;
  77530. /* The value of pExpr->op and op are related as follows:
  77531. **
  77532. ** pExpr->op op
  77533. ** --------- ----------
  77534. ** TK_ISNULL OP_NotNull
  77535. ** TK_NOTNULL OP_IsNull
  77536. ** TK_NE OP_Eq
  77537. ** TK_EQ OP_Ne
  77538. ** TK_GT OP_Le
  77539. ** TK_LE OP_Gt
  77540. ** TK_GE OP_Lt
  77541. ** TK_LT OP_Ge
  77542. **
  77543. ** For other values of pExpr->op, op is undefined and unused.
  77544. ** The value of TK_ and OP_ constants are arranged such that we
  77545. ** can compute the mapping above using the following expression.
  77546. ** Assert()s verify that the computation is correct.
  77547. */
  77548. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  77549. /* Verify correct alignment of TK_ and OP_ constants
  77550. */
  77551. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  77552. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  77553. assert( pExpr->op!=TK_NE || op==OP_Eq );
  77554. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  77555. assert( pExpr->op!=TK_LT || op==OP_Ge );
  77556. assert( pExpr->op!=TK_LE || op==OP_Gt );
  77557. assert( pExpr->op!=TK_GT || op==OP_Le );
  77558. assert( pExpr->op!=TK_GE || op==OP_Lt );
  77559. switch( pExpr->op ){
  77560. case TK_AND: {
  77561. testcase( jumpIfNull==0 );
  77562. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  77563. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  77564. break;
  77565. }
  77566. case TK_OR: {
  77567. int d2 = sqlite3VdbeMakeLabel(v);
  77568. testcase( jumpIfNull==0 );
  77569. sqlite3ExprCachePush(pParse);
  77570. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  77571. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  77572. sqlite3VdbeResolveLabel(v, d2);
  77573. sqlite3ExprCachePop(pParse, 1);
  77574. break;
  77575. }
  77576. case TK_NOT: {
  77577. testcase( jumpIfNull==0 );
  77578. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  77579. break;
  77580. }
  77581. case TK_LT:
  77582. case TK_LE:
  77583. case TK_GT:
  77584. case TK_GE:
  77585. case TK_NE:
  77586. case TK_EQ: {
  77587. testcase( op==TK_LT );
  77588. testcase( op==TK_LE );
  77589. testcase( op==TK_GT );
  77590. testcase( op==TK_GE );
  77591. testcase( op==TK_EQ );
  77592. testcase( op==TK_NE );
  77593. testcase( jumpIfNull==0 );
  77594. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77595. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77596. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77597. r1, r2, dest, jumpIfNull);
  77598. testcase( regFree1==0 );
  77599. testcase( regFree2==0 );
  77600. break;
  77601. }
  77602. case TK_IS:
  77603. case TK_ISNOT: {
  77604. testcase( pExpr->op==TK_IS );
  77605. testcase( pExpr->op==TK_ISNOT );
  77606. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77607. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77608. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  77609. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77610. r1, r2, dest, SQLITE_NULLEQ);
  77611. testcase( regFree1==0 );
  77612. testcase( regFree2==0 );
  77613. break;
  77614. }
  77615. case TK_ISNULL:
  77616. case TK_NOTNULL: {
  77617. testcase( op==TK_ISNULL );
  77618. testcase( op==TK_NOTNULL );
  77619. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77620. sqlite3VdbeAddOp2(v, op, r1, dest);
  77621. testcase( regFree1==0 );
  77622. break;
  77623. }
  77624. case TK_BETWEEN: {
  77625. testcase( jumpIfNull==0 );
  77626. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  77627. break;
  77628. }
  77629. #ifndef SQLITE_OMIT_SUBQUERY
  77630. case TK_IN: {
  77631. if( jumpIfNull ){
  77632. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  77633. }else{
  77634. int destIfNull = sqlite3VdbeMakeLabel(v);
  77635. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  77636. sqlite3VdbeResolveLabel(v, destIfNull);
  77637. }
  77638. break;
  77639. }
  77640. #endif
  77641. default: {
  77642. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  77643. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  77644. testcase( regFree1==0 );
  77645. testcase( jumpIfNull==0 );
  77646. break;
  77647. }
  77648. }
  77649. sqlite3ReleaseTempReg(pParse, regFree1);
  77650. sqlite3ReleaseTempReg(pParse, regFree2);
  77651. }
  77652. /*
  77653. ** Do a deep comparison of two expression trees. Return 0 if the two
  77654. ** expressions are completely identical. Return 1 if they differ only
  77655. ** by a COLLATE operator at the top level. Return 2 if there are differences
  77656. ** other than the top-level COLLATE operator.
  77657. **
  77658. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  77659. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  77660. **
  77661. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  77662. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  77663. **
  77664. ** Sometimes this routine will return 2 even if the two expressions
  77665. ** really are equivalent. If we cannot prove that the expressions are
  77666. ** identical, we return 2 just to be safe. So if this routine
  77667. ** returns 2, then you do not really know for certain if the two
  77668. ** expressions are the same. But if you get a 0 or 1 return, then you
  77669. ** can be sure the expressions are the same. In the places where
  77670. ** this routine is used, it does not hurt to get an extra 2 - that
  77671. ** just might result in some slightly slower code. But returning
  77672. ** an incorrect 0 or 1 could lead to a malfunction.
  77673. */
  77674. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  77675. if( pA==0||pB==0 ){
  77676. return pB==pA ? 0 : 2;
  77677. }
  77678. assert( !ExprHasProperty(pA, EP_TokenOnly|EP_Reduced) );
  77679. assert( !ExprHasProperty(pB, EP_TokenOnly|EP_Reduced) );
  77680. if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
  77681. return 2;
  77682. }
  77683. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  77684. if( pA->op!=pB->op && (pA->op!=TK_REGISTER || pA->op2!=pB->op) ){
  77685. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  77686. return 1;
  77687. }
  77688. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  77689. return 1;
  77690. }
  77691. return 2;
  77692. }
  77693. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  77694. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  77695. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  77696. if( pA->iColumn!=pB->iColumn ) return 2;
  77697. if( pA->iTable!=pB->iTable
  77698. && pA->op!=TK_REGISTER
  77699. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  77700. if( ExprHasProperty(pA, EP_IntValue) ){
  77701. if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
  77702. return 2;
  77703. }
  77704. }else if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken){
  77705. if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
  77706. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  77707. return pA->op==TK_COLLATE ? 1 : 2;
  77708. }
  77709. }
  77710. return 0;
  77711. }
  77712. /*
  77713. ** Compare two ExprList objects. Return 0 if they are identical and
  77714. ** non-zero if they differ in any way.
  77715. **
  77716. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  77717. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  77718. **
  77719. ** This routine might return non-zero for equivalent ExprLists. The
  77720. ** only consequence will be disabled optimizations. But this routine
  77721. ** must never return 0 if the two ExprList objects are different, or
  77722. ** a malfunction will result.
  77723. **
  77724. ** Two NULL pointers are considered to be the same. But a NULL pointer
  77725. ** always differs from a non-NULL pointer.
  77726. */
  77727. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  77728. int i;
  77729. if( pA==0 && pB==0 ) return 0;
  77730. if( pA==0 || pB==0 ) return 1;
  77731. if( pA->nExpr!=pB->nExpr ) return 1;
  77732. for(i=0; i<pA->nExpr; i++){
  77733. Expr *pExprA = pA->a[i].pExpr;
  77734. Expr *pExprB = pB->a[i].pExpr;
  77735. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  77736. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  77737. }
  77738. return 0;
  77739. }
  77740. /*
  77741. ** Return true if we can prove the pE2 will always be true if pE1 is
  77742. ** true. Return false if we cannot complete the proof or if pE2 might
  77743. ** be false. Examples:
  77744. **
  77745. ** pE1: x==5 pE2: x==5 Result: true
  77746. ** pE1: x>0 pE2: x==5 Result: false
  77747. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  77748. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  77749. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  77750. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  77751. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  77752. **
  77753. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  77754. ** Expr.iTable<0 then assume a table number given by iTab.
  77755. **
  77756. ** When in doubt, return false. Returning true might give a performance
  77757. ** improvement. Returning false might cause a performance reduction, but
  77758. ** it will always give the correct answer and is hence always safe.
  77759. */
  77760. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  77761. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  77762. return 1;
  77763. }
  77764. if( pE2->op==TK_OR
  77765. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  77766. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  77767. ){
  77768. return 1;
  77769. }
  77770. if( pE2->op==TK_NOTNULL
  77771. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  77772. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  77773. ){
  77774. return 1;
  77775. }
  77776. return 0;
  77777. }
  77778. /*
  77779. ** An instance of the following structure is used by the tree walker
  77780. ** to count references to table columns in the arguments of an
  77781. ** aggregate function, in order to implement the
  77782. ** sqlite3FunctionThisSrc() routine.
  77783. */
  77784. struct SrcCount {
  77785. SrcList *pSrc; /* One particular FROM clause in a nested query */
  77786. int nThis; /* Number of references to columns in pSrcList */
  77787. int nOther; /* Number of references to columns in other FROM clauses */
  77788. };
  77789. /*
  77790. ** Count the number of references to columns.
  77791. */
  77792. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  77793. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  77794. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  77795. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  77796. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  77797. ** NEVER() will need to be removed. */
  77798. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  77799. int i;
  77800. struct SrcCount *p = pWalker->u.pSrcCount;
  77801. SrcList *pSrc = p->pSrc;
  77802. for(i=0; i<pSrc->nSrc; i++){
  77803. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  77804. }
  77805. if( i<pSrc->nSrc ){
  77806. p->nThis++;
  77807. }else{
  77808. p->nOther++;
  77809. }
  77810. }
  77811. return WRC_Continue;
  77812. }
  77813. /*
  77814. ** Determine if any of the arguments to the pExpr Function reference
  77815. ** pSrcList. Return true if they do. Also return true if the function
  77816. ** has no arguments or has only constant arguments. Return false if pExpr
  77817. ** references columns but not columns of tables found in pSrcList.
  77818. */
  77819. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  77820. Walker w;
  77821. struct SrcCount cnt;
  77822. assert( pExpr->op==TK_AGG_FUNCTION );
  77823. memset(&w, 0, sizeof(w));
  77824. w.xExprCallback = exprSrcCount;
  77825. w.u.pSrcCount = &cnt;
  77826. cnt.pSrc = pSrcList;
  77827. cnt.nThis = 0;
  77828. cnt.nOther = 0;
  77829. sqlite3WalkExprList(&w, pExpr->x.pList);
  77830. return cnt.nThis>0 || cnt.nOther==0;
  77831. }
  77832. /*
  77833. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  77834. ** the new element. Return a negative number if malloc fails.
  77835. */
  77836. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  77837. int i;
  77838. pInfo->aCol = sqlite3ArrayAllocate(
  77839. db,
  77840. pInfo->aCol,
  77841. sizeof(pInfo->aCol[0]),
  77842. &pInfo->nColumn,
  77843. &i
  77844. );
  77845. return i;
  77846. }
  77847. /*
  77848. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  77849. ** the new element. Return a negative number if malloc fails.
  77850. */
  77851. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  77852. int i;
  77853. pInfo->aFunc = sqlite3ArrayAllocate(
  77854. db,
  77855. pInfo->aFunc,
  77856. sizeof(pInfo->aFunc[0]),
  77857. &pInfo->nFunc,
  77858. &i
  77859. );
  77860. return i;
  77861. }
  77862. /*
  77863. ** This is the xExprCallback for a tree walker. It is used to
  77864. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  77865. ** for additional information.
  77866. */
  77867. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  77868. int i;
  77869. NameContext *pNC = pWalker->u.pNC;
  77870. Parse *pParse = pNC->pParse;
  77871. SrcList *pSrcList = pNC->pSrcList;
  77872. AggInfo *pAggInfo = pNC->pAggInfo;
  77873. switch( pExpr->op ){
  77874. case TK_AGG_COLUMN:
  77875. case TK_COLUMN: {
  77876. testcase( pExpr->op==TK_AGG_COLUMN );
  77877. testcase( pExpr->op==TK_COLUMN );
  77878. /* Check to see if the column is in one of the tables in the FROM
  77879. ** clause of the aggregate query */
  77880. if( ALWAYS(pSrcList!=0) ){
  77881. struct SrcList_item *pItem = pSrcList->a;
  77882. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  77883. struct AggInfo_col *pCol;
  77884. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  77885. if( pExpr->iTable==pItem->iCursor ){
  77886. /* If we reach this point, it means that pExpr refers to a table
  77887. ** that is in the FROM clause of the aggregate query.
  77888. **
  77889. ** Make an entry for the column in pAggInfo->aCol[] if there
  77890. ** is not an entry there already.
  77891. */
  77892. int k;
  77893. pCol = pAggInfo->aCol;
  77894. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  77895. if( pCol->iTable==pExpr->iTable &&
  77896. pCol->iColumn==pExpr->iColumn ){
  77897. break;
  77898. }
  77899. }
  77900. if( (k>=pAggInfo->nColumn)
  77901. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  77902. ){
  77903. pCol = &pAggInfo->aCol[k];
  77904. pCol->pTab = pExpr->pTab;
  77905. pCol->iTable = pExpr->iTable;
  77906. pCol->iColumn = pExpr->iColumn;
  77907. pCol->iMem = ++pParse->nMem;
  77908. pCol->iSorterColumn = -1;
  77909. pCol->pExpr = pExpr;
  77910. if( pAggInfo->pGroupBy ){
  77911. int j, n;
  77912. ExprList *pGB = pAggInfo->pGroupBy;
  77913. struct ExprList_item *pTerm = pGB->a;
  77914. n = pGB->nExpr;
  77915. for(j=0; j<n; j++, pTerm++){
  77916. Expr *pE = pTerm->pExpr;
  77917. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  77918. pE->iColumn==pExpr->iColumn ){
  77919. pCol->iSorterColumn = j;
  77920. break;
  77921. }
  77922. }
  77923. }
  77924. if( pCol->iSorterColumn<0 ){
  77925. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  77926. }
  77927. }
  77928. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  77929. ** because it was there before or because we just created it).
  77930. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  77931. ** pAggInfo->aCol[] entry.
  77932. */
  77933. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77934. pExpr->pAggInfo = pAggInfo;
  77935. pExpr->op = TK_AGG_COLUMN;
  77936. pExpr->iAgg = (i16)k;
  77937. break;
  77938. } /* endif pExpr->iTable==pItem->iCursor */
  77939. } /* end loop over pSrcList */
  77940. }
  77941. return WRC_Prune;
  77942. }
  77943. case TK_AGG_FUNCTION: {
  77944. if( (pNC->ncFlags & NC_InAggFunc)==0
  77945. && pWalker->walkerDepth==pExpr->op2
  77946. ){
  77947. /* Check to see if pExpr is a duplicate of another aggregate
  77948. ** function that is already in the pAggInfo structure
  77949. */
  77950. struct AggInfo_func *pItem = pAggInfo->aFunc;
  77951. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  77952. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  77953. break;
  77954. }
  77955. }
  77956. if( i>=pAggInfo->nFunc ){
  77957. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  77958. */
  77959. u8 enc = ENC(pParse->db);
  77960. i = addAggInfoFunc(pParse->db, pAggInfo);
  77961. if( i>=0 ){
  77962. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77963. pItem = &pAggInfo->aFunc[i];
  77964. pItem->pExpr = pExpr;
  77965. pItem->iMem = ++pParse->nMem;
  77966. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77967. pItem->pFunc = sqlite3FindFunction(pParse->db,
  77968. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  77969. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  77970. if( pExpr->flags & EP_Distinct ){
  77971. pItem->iDistinct = pParse->nTab++;
  77972. }else{
  77973. pItem->iDistinct = -1;
  77974. }
  77975. }
  77976. }
  77977. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  77978. */
  77979. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  77980. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77981. pExpr->iAgg = (i16)i;
  77982. pExpr->pAggInfo = pAggInfo;
  77983. return WRC_Prune;
  77984. }else{
  77985. return WRC_Continue;
  77986. }
  77987. }
  77988. }
  77989. return WRC_Continue;
  77990. }
  77991. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  77992. UNUSED_PARAMETER(pWalker);
  77993. UNUSED_PARAMETER(pSelect);
  77994. return WRC_Continue;
  77995. }
  77996. /*
  77997. ** Analyze the pExpr expression looking for aggregate functions and
  77998. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  77999. ** points to. Additional entries are made on the AggInfo object as
  78000. ** necessary.
  78001. **
  78002. ** This routine should only be called after the expression has been
  78003. ** analyzed by sqlite3ResolveExprNames().
  78004. */
  78005. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  78006. Walker w;
  78007. memset(&w, 0, sizeof(w));
  78008. w.xExprCallback = analyzeAggregate;
  78009. w.xSelectCallback = analyzeAggregatesInSelect;
  78010. w.u.pNC = pNC;
  78011. assert( pNC->pSrcList!=0 );
  78012. sqlite3WalkExpr(&w, pExpr);
  78013. }
  78014. /*
  78015. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  78016. ** expression list. Return the number of errors.
  78017. **
  78018. ** If an error is found, the analysis is cut short.
  78019. */
  78020. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  78021. struct ExprList_item *pItem;
  78022. int i;
  78023. if( pList ){
  78024. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  78025. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  78026. }
  78027. }
  78028. }
  78029. /*
  78030. ** Allocate a single new register for use to hold some intermediate result.
  78031. */
  78032. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  78033. if( pParse->nTempReg==0 ){
  78034. return ++pParse->nMem;
  78035. }
  78036. return pParse->aTempReg[--pParse->nTempReg];
  78037. }
  78038. /*
  78039. ** Deallocate a register, making available for reuse for some other
  78040. ** purpose.
  78041. **
  78042. ** If a register is currently being used by the column cache, then
  78043. ** the dallocation is deferred until the column cache line that uses
  78044. ** the register becomes stale.
  78045. */
  78046. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  78047. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  78048. int i;
  78049. struct yColCache *p;
  78050. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  78051. if( p->iReg==iReg ){
  78052. p->tempReg = 1;
  78053. return;
  78054. }
  78055. }
  78056. pParse->aTempReg[pParse->nTempReg++] = iReg;
  78057. }
  78058. }
  78059. /*
  78060. ** Allocate or deallocate a block of nReg consecutive registers
  78061. */
  78062. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  78063. int i, n;
  78064. i = pParse->iRangeReg;
  78065. n = pParse->nRangeReg;
  78066. if( nReg<=n ){
  78067. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  78068. pParse->iRangeReg += nReg;
  78069. pParse->nRangeReg -= nReg;
  78070. }else{
  78071. i = pParse->nMem+1;
  78072. pParse->nMem += nReg;
  78073. }
  78074. return i;
  78075. }
  78076. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  78077. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  78078. if( nReg>pParse->nRangeReg ){
  78079. pParse->nRangeReg = nReg;
  78080. pParse->iRangeReg = iReg;
  78081. }
  78082. }
  78083. /*
  78084. ** Mark all temporary registers as being unavailable for reuse.
  78085. */
  78086. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  78087. pParse->nTempReg = 0;
  78088. pParse->nRangeReg = 0;
  78089. }
  78090. /************** End of expr.c ************************************************/
  78091. /************** Begin file alter.c *******************************************/
  78092. /*
  78093. ** 2005 February 15
  78094. **
  78095. ** The author disclaims copyright to this source code. In place of
  78096. ** a legal notice, here is a blessing:
  78097. **
  78098. ** May you do good and not evil.
  78099. ** May you find forgiveness for yourself and forgive others.
  78100. ** May you share freely, never taking more than you give.
  78101. **
  78102. *************************************************************************
  78103. ** This file contains C code routines that used to generate VDBE code
  78104. ** that implements the ALTER TABLE command.
  78105. */
  78106. /*
  78107. ** The code in this file only exists if we are not omitting the
  78108. ** ALTER TABLE logic from the build.
  78109. */
  78110. #ifndef SQLITE_OMIT_ALTERTABLE
  78111. /*
  78112. ** This function is used by SQL generated to implement the
  78113. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  78114. ** CREATE INDEX command. The second is a table name. The table name in
  78115. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  78116. ** argument and the result returned. Examples:
  78117. **
  78118. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  78119. ** -> 'CREATE TABLE def(a, b, c)'
  78120. **
  78121. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  78122. ** -> 'CREATE INDEX i ON def(a, b, c)'
  78123. */
  78124. static void renameTableFunc(
  78125. sqlite3_context *context,
  78126. int NotUsed,
  78127. sqlite3_value **argv
  78128. ){
  78129. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  78130. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  78131. int token;
  78132. Token tname;
  78133. unsigned char const *zCsr = zSql;
  78134. int len = 0;
  78135. char *zRet;
  78136. sqlite3 *db = sqlite3_context_db_handle(context);
  78137. UNUSED_PARAMETER(NotUsed);
  78138. /* The principle used to locate the table name in the CREATE TABLE
  78139. ** statement is that the table name is the first non-space token that
  78140. ** is immediately followed by a TK_LP or TK_USING token.
  78141. */
  78142. if( zSql ){
  78143. do {
  78144. if( !*zCsr ){
  78145. /* Ran out of input before finding an opening bracket. Return NULL. */
  78146. return;
  78147. }
  78148. /* Store the token that zCsr points to in tname. */
  78149. tname.z = (char*)zCsr;
  78150. tname.n = len;
  78151. /* Advance zCsr to the next token. Store that token type in 'token',
  78152. ** and its length in 'len' (to be used next iteration of this loop).
  78153. */
  78154. do {
  78155. zCsr += len;
  78156. len = sqlite3GetToken(zCsr, &token);
  78157. } while( token==TK_SPACE );
  78158. assert( len>0 );
  78159. } while( token!=TK_LP && token!=TK_USING );
  78160. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  78161. zTableName, tname.z+tname.n);
  78162. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  78163. }
  78164. }
  78165. /*
  78166. ** This C function implements an SQL user function that is used by SQL code
  78167. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  78168. ** of any foreign key constraints that use the table being renamed as the
  78169. ** parent table. It is passed three arguments:
  78170. **
  78171. ** 1) The complete text of the CREATE TABLE statement being modified,
  78172. ** 2) The old name of the table being renamed, and
  78173. ** 3) The new name of the table being renamed.
  78174. **
  78175. ** It returns the new CREATE TABLE statement. For example:
  78176. **
  78177. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  78178. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  78179. */
  78180. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78181. static void renameParentFunc(
  78182. sqlite3_context *context,
  78183. int NotUsed,
  78184. sqlite3_value **argv
  78185. ){
  78186. sqlite3 *db = sqlite3_context_db_handle(context);
  78187. char *zOutput = 0;
  78188. char *zResult;
  78189. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  78190. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  78191. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  78192. unsigned const char *z; /* Pointer to token */
  78193. int n; /* Length of token z */
  78194. int token; /* Type of token */
  78195. UNUSED_PARAMETER(NotUsed);
  78196. for(z=zInput; *z; z=z+n){
  78197. n = sqlite3GetToken(z, &token);
  78198. if( token==TK_REFERENCES ){
  78199. char *zParent;
  78200. do {
  78201. z += n;
  78202. n = sqlite3GetToken(z, &token);
  78203. }while( token==TK_SPACE );
  78204. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  78205. if( zParent==0 ) break;
  78206. sqlite3Dequote(zParent);
  78207. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  78208. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  78209. (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
  78210. );
  78211. sqlite3DbFree(db, zOutput);
  78212. zOutput = zOut;
  78213. zInput = &z[n];
  78214. }
  78215. sqlite3DbFree(db, zParent);
  78216. }
  78217. }
  78218. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  78219. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  78220. sqlite3DbFree(db, zOutput);
  78221. }
  78222. #endif
  78223. #ifndef SQLITE_OMIT_TRIGGER
  78224. /* This function is used by SQL generated to implement the
  78225. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  78226. ** statement. The second is a table name. The table name in the CREATE
  78227. ** TRIGGER statement is replaced with the third argument and the result
  78228. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  78229. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  78230. */
  78231. static void renameTriggerFunc(
  78232. sqlite3_context *context,
  78233. int NotUsed,
  78234. sqlite3_value **argv
  78235. ){
  78236. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  78237. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  78238. int token;
  78239. Token tname;
  78240. int dist = 3;
  78241. unsigned char const *zCsr = zSql;
  78242. int len = 0;
  78243. char *zRet;
  78244. sqlite3 *db = sqlite3_context_db_handle(context);
  78245. UNUSED_PARAMETER(NotUsed);
  78246. /* The principle used to locate the table name in the CREATE TRIGGER
  78247. ** statement is that the table name is the first token that is immediatedly
  78248. ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
  78249. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  78250. */
  78251. if( zSql ){
  78252. do {
  78253. if( !*zCsr ){
  78254. /* Ran out of input before finding the table name. Return NULL. */
  78255. return;
  78256. }
  78257. /* Store the token that zCsr points to in tname. */
  78258. tname.z = (char*)zCsr;
  78259. tname.n = len;
  78260. /* Advance zCsr to the next token. Store that token type in 'token',
  78261. ** and its length in 'len' (to be used next iteration of this loop).
  78262. */
  78263. do {
  78264. zCsr += len;
  78265. len = sqlite3GetToken(zCsr, &token);
  78266. }while( token==TK_SPACE );
  78267. assert( len>0 );
  78268. /* Variable 'dist' stores the number of tokens read since the most
  78269. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  78270. ** token is read and 'dist' equals 2, the condition stated above
  78271. ** to be met.
  78272. **
  78273. ** Note that ON cannot be a database, table or column name, so
  78274. ** there is no need to worry about syntax like
  78275. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  78276. */
  78277. dist++;
  78278. if( token==TK_DOT || token==TK_ON ){
  78279. dist = 0;
  78280. }
  78281. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  78282. /* Variable tname now contains the token that is the old table-name
  78283. ** in the CREATE TRIGGER statement.
  78284. */
  78285. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql,
  78286. zTableName, tname.z+tname.n);
  78287. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  78288. }
  78289. }
  78290. #endif /* !SQLITE_OMIT_TRIGGER */
  78291. /*
  78292. ** Register built-in functions used to help implement ALTER TABLE
  78293. */
  78294. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  78295. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  78296. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  78297. #ifndef SQLITE_OMIT_TRIGGER
  78298. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  78299. #endif
  78300. #ifndef SQLITE_OMIT_FOREIGN_KEY
  78301. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  78302. #endif
  78303. };
  78304. int i;
  78305. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  78306. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  78307. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  78308. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  78309. }
  78310. }
  78311. /*
  78312. ** This function is used to create the text of expressions of the form:
  78313. **
  78314. ** name=<constant1> OR name=<constant2> OR ...
  78315. **
  78316. ** If argument zWhere is NULL, then a pointer string containing the text
  78317. ** "name=<constant>" is returned, where <constant> is the quoted version
  78318. ** of the string passed as argument zConstant. The returned buffer is
  78319. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  78320. ** caller to ensure that it is eventually freed.
  78321. **
  78322. ** If argument zWhere is not NULL, then the string returned is
  78323. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  78324. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  78325. **
  78326. */
  78327. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  78328. char *zNew;
  78329. if( !zWhere ){
  78330. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  78331. }else{
  78332. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  78333. sqlite3DbFree(db, zWhere);
  78334. }
  78335. return zNew;
  78336. }
  78337. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78338. /*
  78339. ** Generate the text of a WHERE expression which can be used to select all
  78340. ** tables that have foreign key constraints that refer to table pTab (i.e.
  78341. ** constraints for which pTab is the parent table) from the sqlite_master
  78342. ** table.
  78343. */
  78344. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  78345. FKey *p;
  78346. char *zWhere = 0;
  78347. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78348. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  78349. }
  78350. return zWhere;
  78351. }
  78352. #endif
  78353. /*
  78354. ** Generate the text of a WHERE expression which can be used to select all
  78355. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  78356. ** table pTab has no temporary triggers, or is itself stored in the
  78357. ** temporary database, NULL is returned.
  78358. */
  78359. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  78360. Trigger *pTrig;
  78361. char *zWhere = 0;
  78362. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  78363. /* If the table is not located in the temp-db (in which case NULL is
  78364. ** returned, loop through the tables list of triggers. For each trigger
  78365. ** that is not part of the temp-db schema, add a clause to the WHERE
  78366. ** expression being built up in zWhere.
  78367. */
  78368. if( pTab->pSchema!=pTempSchema ){
  78369. sqlite3 *db = pParse->db;
  78370. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  78371. if( pTrig->pSchema==pTempSchema ){
  78372. zWhere = whereOrName(db, zWhere, pTrig->zName);
  78373. }
  78374. }
  78375. }
  78376. if( zWhere ){
  78377. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  78378. sqlite3DbFree(pParse->db, zWhere);
  78379. zWhere = zNew;
  78380. }
  78381. return zWhere;
  78382. }
  78383. /*
  78384. ** Generate code to drop and reload the internal representation of table
  78385. ** pTab from the database, including triggers and temporary triggers.
  78386. ** Argument zName is the name of the table in the database schema at
  78387. ** the time the generated code is executed. This can be different from
  78388. ** pTab->zName if this function is being called to code part of an
  78389. ** "ALTER TABLE RENAME TO" statement.
  78390. */
  78391. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  78392. Vdbe *v;
  78393. char *zWhere;
  78394. int iDb; /* Index of database containing pTab */
  78395. #ifndef SQLITE_OMIT_TRIGGER
  78396. Trigger *pTrig;
  78397. #endif
  78398. v = sqlite3GetVdbe(pParse);
  78399. if( NEVER(v==0) ) return;
  78400. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  78401. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78402. assert( iDb>=0 );
  78403. #ifndef SQLITE_OMIT_TRIGGER
  78404. /* Drop any table triggers from the internal schema. */
  78405. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  78406. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  78407. assert( iTrigDb==iDb || iTrigDb==1 );
  78408. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  78409. }
  78410. #endif
  78411. /* Drop the table and index from the internal schema. */
  78412. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  78413. /* Reload the table, index and permanent trigger schemas. */
  78414. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  78415. if( !zWhere ) return;
  78416. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  78417. #ifndef SQLITE_OMIT_TRIGGER
  78418. /* Now, if the table is not stored in the temp database, reload any temp
  78419. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  78420. */
  78421. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  78422. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  78423. }
  78424. #endif
  78425. }
  78426. /*
  78427. ** Parameter zName is the name of a table that is about to be altered
  78428. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  78429. ** If the table is a system table, this function leaves an error message
  78430. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  78431. **
  78432. ** Or, if zName is not a system table, zero is returned.
  78433. */
  78434. static int isSystemTable(Parse *pParse, const char *zName){
  78435. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  78436. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  78437. return 1;
  78438. }
  78439. return 0;
  78440. }
  78441. /*
  78442. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  78443. ** command.
  78444. */
  78445. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  78446. Parse *pParse, /* Parser context. */
  78447. SrcList *pSrc, /* The table to rename. */
  78448. Token *pName /* The new table name. */
  78449. ){
  78450. int iDb; /* Database that contains the table */
  78451. char *zDb; /* Name of database iDb */
  78452. Table *pTab; /* Table being renamed */
  78453. char *zName = 0; /* NULL-terminated version of pName */
  78454. sqlite3 *db = pParse->db; /* Database connection */
  78455. int nTabName; /* Number of UTF-8 characters in zTabName */
  78456. const char *zTabName; /* Original name of the table */
  78457. Vdbe *v;
  78458. #ifndef SQLITE_OMIT_TRIGGER
  78459. char *zWhere = 0; /* Where clause to locate temp triggers */
  78460. #endif
  78461. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  78462. int savedDbFlags; /* Saved value of db->flags */
  78463. savedDbFlags = db->flags;
  78464. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  78465. assert( pSrc->nSrc==1 );
  78466. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  78467. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  78468. if( !pTab ) goto exit_rename_table;
  78469. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  78470. zDb = db->aDb[iDb].zName;
  78471. db->flags |= SQLITE_PreferBuiltin;
  78472. /* Get a NULL terminated version of the new table name. */
  78473. zName = sqlite3NameFromToken(db, pName);
  78474. if( !zName ) goto exit_rename_table;
  78475. /* Check that a table or index named 'zName' does not already exist
  78476. ** in database iDb. If so, this is an error.
  78477. */
  78478. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  78479. sqlite3ErrorMsg(pParse,
  78480. "there is already another table or index with this name: %s", zName);
  78481. goto exit_rename_table;
  78482. }
  78483. /* Make sure it is not a system table being altered, or a reserved name
  78484. ** that the table is being renamed to.
  78485. */
  78486. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  78487. goto exit_rename_table;
  78488. }
  78489. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  78490. exit_rename_table;
  78491. }
  78492. #ifndef SQLITE_OMIT_VIEW
  78493. if( pTab->pSelect ){
  78494. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  78495. goto exit_rename_table;
  78496. }
  78497. #endif
  78498. #ifndef SQLITE_OMIT_AUTHORIZATION
  78499. /* Invoke the authorization callback. */
  78500. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  78501. goto exit_rename_table;
  78502. }
  78503. #endif
  78504. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78505. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  78506. goto exit_rename_table;
  78507. }
  78508. if( IsVirtual(pTab) ){
  78509. pVTab = sqlite3GetVTable(db, pTab);
  78510. if( pVTab->pVtab->pModule->xRename==0 ){
  78511. pVTab = 0;
  78512. }
  78513. }
  78514. #endif
  78515. /* Begin a transaction and code the VerifyCookie for database iDb.
  78516. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  78517. ** schema). Open a statement transaction if the table is a virtual
  78518. ** table.
  78519. */
  78520. v = sqlite3GetVdbe(pParse);
  78521. if( v==0 ){
  78522. goto exit_rename_table;
  78523. }
  78524. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  78525. sqlite3ChangeCookie(pParse, iDb);
  78526. /* If this is a virtual table, invoke the xRename() function if
  78527. ** one is defined. The xRename() callback will modify the names
  78528. ** of any resources used by the v-table implementation (including other
  78529. ** SQLite tables) that are identified by the name of the virtual table.
  78530. */
  78531. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78532. if( pVTab ){
  78533. int i = ++pParse->nMem;
  78534. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  78535. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  78536. sqlite3MayAbort(pParse);
  78537. }
  78538. #endif
  78539. /* figure out how many UTF-8 characters are in zName */
  78540. zTabName = pTab->zName;
  78541. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  78542. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78543. if( db->flags&SQLITE_ForeignKeys ){
  78544. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  78545. ** statements corresponding to all child tables of foreign key constraints
  78546. ** for which the renamed table is the parent table. */
  78547. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  78548. sqlite3NestedParse(pParse,
  78549. "UPDATE \"%w\".%s SET "
  78550. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  78551. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  78552. sqlite3DbFree(db, zWhere);
  78553. }
  78554. }
  78555. #endif
  78556. /* Modify the sqlite_master table to use the new table name. */
  78557. sqlite3NestedParse(pParse,
  78558. "UPDATE %Q.%s SET "
  78559. #ifdef SQLITE_OMIT_TRIGGER
  78560. "sql = sqlite_rename_table(sql, %Q), "
  78561. #else
  78562. "sql = CASE "
  78563. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  78564. "ELSE sqlite_rename_table(sql, %Q) END, "
  78565. #endif
  78566. "tbl_name = %Q, "
  78567. "name = CASE "
  78568. "WHEN type='table' THEN %Q "
  78569. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  78570. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  78571. "ELSE name END "
  78572. "WHERE tbl_name=%Q COLLATE nocase AND "
  78573. "(type='table' OR type='index' OR type='trigger');",
  78574. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  78575. #ifndef SQLITE_OMIT_TRIGGER
  78576. zName,
  78577. #endif
  78578. zName, nTabName, zTabName
  78579. );
  78580. #ifndef SQLITE_OMIT_AUTOINCREMENT
  78581. /* If the sqlite_sequence table exists in this database, then update
  78582. ** it with the new table name.
  78583. */
  78584. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  78585. sqlite3NestedParse(pParse,
  78586. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  78587. zDb, zName, pTab->zName);
  78588. }
  78589. #endif
  78590. #ifndef SQLITE_OMIT_TRIGGER
  78591. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  78592. ** table. Don't do this if the table being ALTERed is itself located in
  78593. ** the temp database.
  78594. */
  78595. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  78596. sqlite3NestedParse(pParse,
  78597. "UPDATE sqlite_temp_master SET "
  78598. "sql = sqlite_rename_trigger(sql, %Q), "
  78599. "tbl_name = %Q "
  78600. "WHERE %s;", zName, zName, zWhere);
  78601. sqlite3DbFree(db, zWhere);
  78602. }
  78603. #endif
  78604. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  78605. if( db->flags&SQLITE_ForeignKeys ){
  78606. FKey *p;
  78607. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  78608. Table *pFrom = p->pFrom;
  78609. if( pFrom!=pTab ){
  78610. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  78611. }
  78612. }
  78613. }
  78614. #endif
  78615. /* Drop and reload the internal table schema. */
  78616. reloadTableSchema(pParse, pTab, zName);
  78617. exit_rename_table:
  78618. sqlite3SrcListDelete(db, pSrc);
  78619. sqlite3DbFree(db, zName);
  78620. db->flags = savedDbFlags;
  78621. }
  78622. /*
  78623. ** Generate code to make sure the file format number is at least minFormat.
  78624. ** The generated code will increase the file format number if necessary.
  78625. */
  78626. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  78627. Vdbe *v;
  78628. v = sqlite3GetVdbe(pParse);
  78629. /* The VDBE should have been allocated before this routine is called.
  78630. ** If that allocation failed, we would have quit before reaching this
  78631. ** point */
  78632. if( ALWAYS(v) ){
  78633. int r1 = sqlite3GetTempReg(pParse);
  78634. int r2 = sqlite3GetTempReg(pParse);
  78635. int j1;
  78636. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  78637. sqlite3VdbeUsesBtree(v, iDb);
  78638. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  78639. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  78640. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  78641. sqlite3VdbeJumpHere(v, j1);
  78642. sqlite3ReleaseTempReg(pParse, r1);
  78643. sqlite3ReleaseTempReg(pParse, r2);
  78644. }
  78645. }
  78646. /*
  78647. ** This function is called after an "ALTER TABLE ... ADD" statement
  78648. ** has been parsed. Argument pColDef contains the text of the new
  78649. ** column definition.
  78650. **
  78651. ** The Table structure pParse->pNewTable was extended to include
  78652. ** the new column during parsing.
  78653. */
  78654. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  78655. Table *pNew; /* Copy of pParse->pNewTable */
  78656. Table *pTab; /* Table being altered */
  78657. int iDb; /* Database number */
  78658. const char *zDb; /* Database name */
  78659. const char *zTab; /* Table name */
  78660. char *zCol; /* Null-terminated column definition */
  78661. Column *pCol; /* The new column */
  78662. Expr *pDflt; /* Default value for the new column */
  78663. sqlite3 *db; /* The database connection; */
  78664. db = pParse->db;
  78665. if( pParse->nErr || db->mallocFailed ) return;
  78666. pNew = pParse->pNewTable;
  78667. assert( pNew );
  78668. assert( sqlite3BtreeHoldsAllMutexes(db) );
  78669. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  78670. zDb = db->aDb[iDb].zName;
  78671. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  78672. pCol = &pNew->aCol[pNew->nCol-1];
  78673. pDflt = pCol->pDflt;
  78674. pTab = sqlite3FindTable(db, zTab, zDb);
  78675. assert( pTab );
  78676. #ifndef SQLITE_OMIT_AUTHORIZATION
  78677. /* Invoke the authorization callback. */
  78678. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  78679. return;
  78680. }
  78681. #endif
  78682. /* If the default value for the new column was specified with a
  78683. ** literal NULL, then set pDflt to 0. This simplifies checking
  78684. ** for an SQL NULL default below.
  78685. */
  78686. if( pDflt && pDflt->op==TK_NULL ){
  78687. pDflt = 0;
  78688. }
  78689. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  78690. ** If there is a NOT NULL constraint, then the default value for the
  78691. ** column must not be NULL.
  78692. */
  78693. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  78694. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  78695. return;
  78696. }
  78697. if( pNew->pIndex ){
  78698. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  78699. return;
  78700. }
  78701. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  78702. sqlite3ErrorMsg(pParse,
  78703. "Cannot add a REFERENCES column with non-NULL default value");
  78704. return;
  78705. }
  78706. if( pCol->notNull && !pDflt ){
  78707. sqlite3ErrorMsg(pParse,
  78708. "Cannot add a NOT NULL column with default value NULL");
  78709. return;
  78710. }
  78711. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  78712. ** can handle (i.e. not CURRENT_TIME etc.)
  78713. */
  78714. if( pDflt ){
  78715. sqlite3_value *pVal = 0;
  78716. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  78717. db->mallocFailed = 1;
  78718. return;
  78719. }
  78720. if( !pVal ){
  78721. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  78722. return;
  78723. }
  78724. sqlite3ValueFree(pVal);
  78725. }
  78726. /* Modify the CREATE TABLE statement. */
  78727. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  78728. if( zCol ){
  78729. char *zEnd = &zCol[pColDef->n-1];
  78730. int savedDbFlags = db->flags;
  78731. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  78732. *zEnd-- = '\0';
  78733. }
  78734. db->flags |= SQLITE_PreferBuiltin;
  78735. sqlite3NestedParse(pParse,
  78736. "UPDATE \"%w\".%s SET "
  78737. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  78738. "WHERE type = 'table' AND name = %Q",
  78739. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  78740. zTab
  78741. );
  78742. sqlite3DbFree(db, zCol);
  78743. db->flags = savedDbFlags;
  78744. }
  78745. /* If the default value of the new column is NULL, then set the file
  78746. ** format to 2. If the default value of the new column is not NULL,
  78747. ** the file format becomes 3.
  78748. */
  78749. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  78750. /* Reload the schema of the modified table. */
  78751. reloadTableSchema(pParse, pTab, pTab->zName);
  78752. }
  78753. /*
  78754. ** This function is called by the parser after the table-name in
  78755. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  78756. ** pSrc is the full-name of the table being altered.
  78757. **
  78758. ** This routine makes a (partial) copy of the Table structure
  78759. ** for the table being altered and sets Parse.pNewTable to point
  78760. ** to it. Routines called by the parser as the column definition
  78761. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  78762. ** the copy. The copy of the Table structure is deleted by tokenize.c
  78763. ** after parsing is finished.
  78764. **
  78765. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  78766. ** coding the "ALTER TABLE ... ADD" statement.
  78767. */
  78768. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  78769. Table *pNew;
  78770. Table *pTab;
  78771. Vdbe *v;
  78772. int iDb;
  78773. int i;
  78774. int nAlloc;
  78775. sqlite3 *db = pParse->db;
  78776. /* Look up the table being altered. */
  78777. assert( pParse->pNewTable==0 );
  78778. assert( sqlite3BtreeHoldsAllMutexes(db) );
  78779. if( db->mallocFailed ) goto exit_begin_add_column;
  78780. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  78781. if( !pTab ) goto exit_begin_add_column;
  78782. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78783. if( IsVirtual(pTab) ){
  78784. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  78785. goto exit_begin_add_column;
  78786. }
  78787. #endif
  78788. /* Make sure this is not an attempt to ALTER a view. */
  78789. if( pTab->pSelect ){
  78790. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  78791. goto exit_begin_add_column;
  78792. }
  78793. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  78794. goto exit_begin_add_column;
  78795. }
  78796. assert( pTab->addColOffset>0 );
  78797. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  78798. /* Put a copy of the Table struct in Parse.pNewTable for the
  78799. ** sqlite3AddColumn() function and friends to modify. But modify
  78800. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  78801. ** prefix, we insure that the name will not collide with an existing
  78802. ** table because user table are not allowed to have the "sqlite_"
  78803. ** prefix on their name.
  78804. */
  78805. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  78806. if( !pNew ) goto exit_begin_add_column;
  78807. pParse->pNewTable = pNew;
  78808. pNew->nRef = 1;
  78809. pNew->nCol = pTab->nCol;
  78810. assert( pNew->nCol>0 );
  78811. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  78812. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  78813. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  78814. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  78815. if( !pNew->aCol || !pNew->zName ){
  78816. db->mallocFailed = 1;
  78817. goto exit_begin_add_column;
  78818. }
  78819. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  78820. for(i=0; i<pNew->nCol; i++){
  78821. Column *pCol = &pNew->aCol[i];
  78822. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  78823. pCol->zColl = 0;
  78824. pCol->zType = 0;
  78825. pCol->pDflt = 0;
  78826. pCol->zDflt = 0;
  78827. }
  78828. pNew->pSchema = db->aDb[iDb].pSchema;
  78829. pNew->addColOffset = pTab->addColOffset;
  78830. pNew->nRef = 1;
  78831. /* Begin a transaction and increment the schema cookie. */
  78832. sqlite3BeginWriteOperation(pParse, 0, iDb);
  78833. v = sqlite3GetVdbe(pParse);
  78834. if( !v ) goto exit_begin_add_column;
  78835. sqlite3ChangeCookie(pParse, iDb);
  78836. exit_begin_add_column:
  78837. sqlite3SrcListDelete(db, pSrc);
  78838. return;
  78839. }
  78840. #endif /* SQLITE_ALTER_TABLE */
  78841. /************** End of alter.c ***********************************************/
  78842. /************** Begin file analyze.c *****************************************/
  78843. /*
  78844. ** 2005-07-08
  78845. **
  78846. ** The author disclaims copyright to this source code. In place of
  78847. ** a legal notice, here is a blessing:
  78848. **
  78849. ** May you do good and not evil.
  78850. ** May you find forgiveness for yourself and forgive others.
  78851. ** May you share freely, never taking more than you give.
  78852. **
  78853. *************************************************************************
  78854. ** This file contains code associated with the ANALYZE command.
  78855. **
  78856. ** The ANALYZE command gather statistics about the content of tables
  78857. ** and indices. These statistics are made available to the query planner
  78858. ** to help it make better decisions about how to perform queries.
  78859. **
  78860. ** The following system tables are or have been supported:
  78861. **
  78862. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  78863. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  78864. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  78865. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  78866. **
  78867. ** Additional tables might be added in future releases of SQLite.
  78868. ** The sqlite_stat2 table is not created or used unless the SQLite version
  78869. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  78870. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  78871. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  78872. ** created and used by SQLite versions 3.7.9 and later and with
  78873. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  78874. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  78875. ** version of sqlite_stat3 and is only available when compiled with
  78876. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  78877. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  78878. ** are both enabled, then STAT4 takes precedence.
  78879. **
  78880. ** For most applications, sqlite_stat1 provides all the statisics required
  78881. ** for the query planner to make good choices.
  78882. **
  78883. ** Format of sqlite_stat1:
  78884. **
  78885. ** There is normally one row per index, with the index identified by the
  78886. ** name in the idx column. The tbl column is the name of the table to
  78887. ** which the index belongs. In each such row, the stat column will be
  78888. ** a string consisting of a list of integers. The first integer in this
  78889. ** list is the number of rows in the index. (This is the same as the
  78890. ** number of rows in the table, except for partial indices.) The second
  78891. ** integer is the average number of rows in the index that have the same
  78892. ** value in the first column of the index. The third integer is the average
  78893. ** number of rows in the index that have the same value for the first two
  78894. ** columns. The N-th integer (for N>1) is the average number of rows in
  78895. ** the index which have the same value for the first N-1 columns. For
  78896. ** a K-column index, there will be K+1 integers in the stat column. If
  78897. ** the index is unique, then the last integer will be 1.
  78898. **
  78899. ** The list of integers in the stat column can optionally be followed
  78900. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  78901. ** must be separated from the last integer by a single space. If the
  78902. ** "unordered" keyword is present, then the query planner assumes that
  78903. ** the index is unordered and will not use the index for a range query.
  78904. **
  78905. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  78906. ** column contains a single integer which is the (estimated) number of
  78907. ** rows in the table identified by sqlite_stat1.tbl.
  78908. **
  78909. ** Format of sqlite_stat2:
  78910. **
  78911. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  78912. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  78913. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  78914. ** about the distribution of keys within an index. The index is identified by
  78915. ** the "idx" column and the "tbl" column is the name of the table to which
  78916. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  78917. ** table for each index.
  78918. **
  78919. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  78920. ** inclusive are samples of the left-most key value in the index taken at
  78921. ** evenly spaced points along the index. Let the number of samples be S
  78922. ** (10 in the standard build) and let C be the number of rows in the index.
  78923. ** Then the sampled rows are given by:
  78924. **
  78925. ** rownumber = (i*C*2 + C)/(S*2)
  78926. **
  78927. ** For i between 0 and S-1. Conceptually, the index space is divided into
  78928. ** S uniform buckets and the samples are the middle row from each bucket.
  78929. **
  78930. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  78931. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  78932. ** writes the sqlite_stat2 table. This version of SQLite only supports
  78933. ** sqlite_stat3.
  78934. **
  78935. ** Format for sqlite_stat3:
  78936. **
  78937. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  78938. ** sqlite_stat4 format will be described first. Further information
  78939. ** about sqlite_stat3 follows the sqlite_stat4 description.
  78940. **
  78941. ** Format for sqlite_stat4:
  78942. **
  78943. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  78944. ** to aid the query planner in choosing good indices based on the values
  78945. ** that indexed columns are compared against in the WHERE clauses of
  78946. ** queries.
  78947. **
  78948. ** The sqlite_stat4 table contains multiple entries for each index.
  78949. ** The idx column names the index and the tbl column is the table of the
  78950. ** index. If the idx and tbl columns are the same, then the sample is
  78951. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  78952. ** binary encoding of a key from the index. The nEq column is a
  78953. ** list of integers. The first integer is the approximate number
  78954. ** of entries in the index whose left-most column exactly matches
  78955. ** the left-most column of the sample. The second integer in nEq
  78956. ** is the approximate number of entries in the index where the
  78957. ** first two columns match the first two columns of the sample.
  78958. ** And so forth. nLt is another list of integers that show the approximate
  78959. ** number of entries that are strictly less than the sample. The first
  78960. ** integer in nLt contains the number of entries in the index where the
  78961. ** left-most column is less than the left-most column of the sample.
  78962. ** The K-th integer in the nLt entry is the number of index entries
  78963. ** where the first K columns are less than the first K columns of the
  78964. ** sample. The nDLt column is like nLt except that it contains the
  78965. ** number of distinct entries in the index that are less than the
  78966. ** sample.
  78967. **
  78968. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  78969. ** The ANALYZE command will typically generate sqlite_stat4 tables
  78970. ** that contain between 10 and 40 samples which are distributed across
  78971. ** the key space, though not uniformly, and which include samples with
  78972. ** large nEq values.
  78973. **
  78974. ** Format for sqlite_stat3 redux:
  78975. **
  78976. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  78977. ** looks at the left-most column of the index. The sqlite_stat3.sample
  78978. ** column contains the actual value of the left-most column instead
  78979. ** of a blob encoding of the complete index key as is found in
  78980. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  78981. ** all contain just a single integer which is the same as the first
  78982. ** integer in the equivalent columns in sqlite_stat4.
  78983. */
  78984. #ifndef SQLITE_OMIT_ANALYZE
  78985. #if defined(SQLITE_ENABLE_STAT4)
  78986. # define IsStat4 1
  78987. # define IsStat3 0
  78988. #elif defined(SQLITE_ENABLE_STAT3)
  78989. # define IsStat4 0
  78990. # define IsStat3 1
  78991. #else
  78992. # define IsStat4 0
  78993. # define IsStat3 0
  78994. # undef SQLITE_STAT4_SAMPLES
  78995. # define SQLITE_STAT4_SAMPLES 1
  78996. #endif
  78997. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  78998. /*
  78999. ** This routine generates code that opens the sqlite_statN tables.
  79000. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  79001. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  79002. ** appropriate compile-time options are provided.
  79003. **
  79004. ** If the sqlite_statN tables do not previously exist, it is created.
  79005. **
  79006. ** Argument zWhere may be a pointer to a buffer containing a table name,
  79007. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  79008. ** the sqlite_statN tables associated with the named table are deleted.
  79009. ** If zWhere==0, then code is generated to delete all stat table entries.
  79010. */
  79011. static void openStatTable(
  79012. Parse *pParse, /* Parsing context */
  79013. int iDb, /* The database we are looking in */
  79014. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  79015. const char *zWhere, /* Delete entries for this table or index */
  79016. const char *zWhereType /* Either "tbl" or "idx" */
  79017. ){
  79018. static const struct {
  79019. const char *zName;
  79020. const char *zCols;
  79021. } aTable[] = {
  79022. { "sqlite_stat1", "tbl,idx,stat" },
  79023. #if defined(SQLITE_ENABLE_STAT4)
  79024. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  79025. { "sqlite_stat3", 0 },
  79026. #elif defined(SQLITE_ENABLE_STAT3)
  79027. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  79028. { "sqlite_stat4", 0 },
  79029. #else
  79030. { "sqlite_stat3", 0 },
  79031. { "sqlite_stat4", 0 },
  79032. #endif
  79033. };
  79034. int i;
  79035. sqlite3 *db = pParse->db;
  79036. Db *pDb;
  79037. Vdbe *v = sqlite3GetVdbe(pParse);
  79038. int aRoot[ArraySize(aTable)];
  79039. u8 aCreateTbl[ArraySize(aTable)];
  79040. if( v==0 ) return;
  79041. assert( sqlite3BtreeHoldsAllMutexes(db) );
  79042. assert( sqlite3VdbeDb(v)==db );
  79043. pDb = &db->aDb[iDb];
  79044. /* Create new statistic tables if they do not exist, or clear them
  79045. ** if they do already exist.
  79046. */
  79047. for(i=0; i<ArraySize(aTable); i++){
  79048. const char *zTab = aTable[i].zName;
  79049. Table *pStat;
  79050. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  79051. if( aTable[i].zCols ){
  79052. /* The sqlite_statN table does not exist. Create it. Note that a
  79053. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  79054. ** of the new table in register pParse->regRoot. This is important
  79055. ** because the OpenWrite opcode below will be needing it. */
  79056. sqlite3NestedParse(pParse,
  79057. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  79058. );
  79059. aRoot[i] = pParse->regRoot;
  79060. aCreateTbl[i] = OPFLAG_P2ISREG;
  79061. }
  79062. }else{
  79063. /* The table already exists. If zWhere is not NULL, delete all entries
  79064. ** associated with the table zWhere. If zWhere is NULL, delete the
  79065. ** entire contents of the table. */
  79066. aRoot[i] = pStat->tnum;
  79067. aCreateTbl[i] = 0;
  79068. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  79069. if( zWhere ){
  79070. sqlite3NestedParse(pParse,
  79071. "DELETE FROM %Q.%s WHERE %s=%Q",
  79072. pDb->zName, zTab, zWhereType, zWhere
  79073. );
  79074. }else{
  79075. /* The sqlite_stat[134] table already exists. Delete all rows. */
  79076. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  79077. }
  79078. }
  79079. }
  79080. /* Open the sqlite_stat[134] tables for writing. */
  79081. for(i=0; aTable[i].zCols; i++){
  79082. assert( i<ArraySize(aTable) );
  79083. sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
  79084. sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
  79085. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  79086. }
  79087. }
  79088. /*
  79089. ** Recommended number of samples for sqlite_stat4
  79090. */
  79091. #ifndef SQLITE_STAT4_SAMPLES
  79092. # define SQLITE_STAT4_SAMPLES 24
  79093. #endif
  79094. /*
  79095. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  79096. ** share an instance of the following structure to hold their state
  79097. ** information.
  79098. */
  79099. typedef struct Stat4Accum Stat4Accum;
  79100. typedef struct Stat4Sample Stat4Sample;
  79101. struct Stat4Sample {
  79102. tRowcnt *anEq; /* sqlite_stat4.nEq */
  79103. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  79104. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79105. tRowcnt *anLt; /* sqlite_stat4.nLt */
  79106. i64 iRowid; /* Rowid in main table of the key */
  79107. u8 isPSample; /* True if a periodic sample */
  79108. int iCol; /* If !isPSample, the reason for inclusion */
  79109. u32 iHash; /* Tiebreaker hash */
  79110. #endif
  79111. };
  79112. struct Stat4Accum {
  79113. tRowcnt nRow; /* Number of rows in the entire table */
  79114. tRowcnt nPSample; /* How often to do a periodic sample */
  79115. int nCol; /* Number of columns in index + rowid */
  79116. int mxSample; /* Maximum number of samples to accumulate */
  79117. Stat4Sample current; /* Current row as a Stat4Sample */
  79118. u32 iPrn; /* Pseudo-random number used for sampling */
  79119. Stat4Sample *aBest; /* Array of (nCol-1) best samples */
  79120. int iMin; /* Index in a[] of entry with minimum score */
  79121. int nSample; /* Current number of samples */
  79122. int iGet; /* Index of current sample accessed by stat_get() */
  79123. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  79124. };
  79125. /*
  79126. ** Implementation of the stat_init(N,C) SQL function. The two parameters
  79127. ** are the number of rows in the table or index (C) and the number of columns
  79128. ** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
  79129. **
  79130. ** This routine allocates the Stat4Accum object in heap memory. The return
  79131. ** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
  79132. ** the size of the blob is sizeof(void*) bytes).
  79133. */
  79134. static void statInit(
  79135. sqlite3_context *context,
  79136. int argc,
  79137. sqlite3_value **argv
  79138. ){
  79139. Stat4Accum *p;
  79140. int nCol; /* Number of columns in index being sampled */
  79141. int nColUp; /* nCol rounded up for alignment */
  79142. int n; /* Bytes of space to allocate */
  79143. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79144. int mxSample = SQLITE_STAT4_SAMPLES;
  79145. #endif
  79146. /* Decode the three function arguments */
  79147. UNUSED_PARAMETER(argc);
  79148. nCol = sqlite3_value_int(argv[0]);
  79149. assert( nCol>1 ); /* >1 because it includes the rowid column */
  79150. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  79151. /* Allocate the space required for the Stat4Accum object */
  79152. n = sizeof(*p)
  79153. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  79154. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  79155. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79156. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  79157. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  79158. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  79159. #endif
  79160. ;
  79161. p = sqlite3MallocZero(n);
  79162. if( p==0 ){
  79163. sqlite3_result_error_nomem(context);
  79164. return;
  79165. }
  79166. p->nRow = 0;
  79167. p->nCol = nCol;
  79168. p->current.anDLt = (tRowcnt*)&p[1];
  79169. p->current.anEq = &p->current.anDLt[nColUp];
  79170. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79171. {
  79172. u8 *pSpace; /* Allocated space not yet assigned */
  79173. int i; /* Used to iterate through p->aSample[] */
  79174. p->iGet = -1;
  79175. p->mxSample = mxSample;
  79176. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
  79177. p->current.anLt = &p->current.anEq[nColUp];
  79178. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
  79179. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  79180. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  79181. p->aBest = &p->a[mxSample];
  79182. pSpace = (u8*)(&p->a[mxSample+nCol]);
  79183. for(i=0; i<(mxSample+nCol); i++){
  79184. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79185. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79186. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  79187. }
  79188. assert( (pSpace - (u8*)p)==n );
  79189. for(i=0; i<nCol; i++){
  79190. p->aBest[i].iCol = i;
  79191. }
  79192. }
  79193. #endif
  79194. /* Return a pointer to the allocated object to the caller */
  79195. sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
  79196. }
  79197. static const FuncDef statInitFuncdef = {
  79198. 1+IsStat34, /* nArg */
  79199. SQLITE_UTF8, /* funcFlags */
  79200. 0, /* pUserData */
  79201. 0, /* pNext */
  79202. statInit, /* xFunc */
  79203. 0, /* xStep */
  79204. 0, /* xFinalize */
  79205. "stat_init", /* zName */
  79206. 0, /* pHash */
  79207. 0 /* pDestructor */
  79208. };
  79209. #ifdef SQLITE_ENABLE_STAT4
  79210. /*
  79211. ** pNew and pOld are both candidate non-periodic samples selected for
  79212. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  79213. ** considering only any trailing columns and the sample hash value, this
  79214. ** function returns true if sample pNew is to be preferred over pOld.
  79215. ** In other words, if we assume that the cardinalities of the selected
  79216. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  79217. **
  79218. ** This function assumes that for each argument sample, the contents of
  79219. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  79220. */
  79221. static int sampleIsBetterPost(
  79222. Stat4Accum *pAccum,
  79223. Stat4Sample *pNew,
  79224. Stat4Sample *pOld
  79225. ){
  79226. int nCol = pAccum->nCol;
  79227. int i;
  79228. assert( pNew->iCol==pOld->iCol );
  79229. for(i=pNew->iCol+1; i<nCol; i++){
  79230. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  79231. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  79232. }
  79233. if( pNew->iHash>pOld->iHash ) return 1;
  79234. return 0;
  79235. }
  79236. #endif
  79237. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79238. /*
  79239. ** Return true if pNew is to be preferred over pOld.
  79240. **
  79241. ** This function assumes that for each argument sample, the contents of
  79242. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  79243. */
  79244. static int sampleIsBetter(
  79245. Stat4Accum *pAccum,
  79246. Stat4Sample *pNew,
  79247. Stat4Sample *pOld
  79248. ){
  79249. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  79250. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  79251. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  79252. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  79253. if( (nEqNew>nEqOld) ) return 1;
  79254. #ifdef SQLITE_ENABLE_STAT4
  79255. if( nEqNew==nEqOld ){
  79256. if( pNew->iCol<pOld->iCol ) return 1;
  79257. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  79258. }
  79259. return 0;
  79260. #else
  79261. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  79262. #endif
  79263. }
  79264. /*
  79265. ** Copy the contents of object (*pFrom) into (*pTo).
  79266. */
  79267. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  79268. pTo->iRowid = pFrom->iRowid;
  79269. pTo->isPSample = pFrom->isPSample;
  79270. pTo->iCol = pFrom->iCol;
  79271. pTo->iHash = pFrom->iHash;
  79272. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  79273. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  79274. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  79275. }
  79276. /*
  79277. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  79278. ** remove the least desirable sample from p->a[] to make room.
  79279. */
  79280. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  79281. Stat4Sample *pSample;
  79282. int i;
  79283. assert( IsStat4 || nEqZero==0 );
  79284. #ifdef SQLITE_ENABLE_STAT4
  79285. if( pNew->isPSample==0 ){
  79286. Stat4Sample *pUpgrade = 0;
  79287. assert( pNew->anEq[pNew->iCol]>0 );
  79288. /* This sample is being added because the prefix that ends in column
  79289. ** iCol occurs many times in the table. However, if we have already
  79290. ** added a sample that shares this prefix, there is no need to add
  79291. ** this one. Instead, upgrade the priority of the highest priority
  79292. ** existing sample that shares this prefix. */
  79293. for(i=p->nSample-1; i>=0; i--){
  79294. Stat4Sample *pOld = &p->a[i];
  79295. if( pOld->anEq[pNew->iCol]==0 ){
  79296. if( pOld->isPSample ) return;
  79297. assert( pOld->iCol>pNew->iCol );
  79298. assert( sampleIsBetter(p, pNew, pOld) );
  79299. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  79300. pUpgrade = pOld;
  79301. }
  79302. }
  79303. }
  79304. if( pUpgrade ){
  79305. pUpgrade->iCol = pNew->iCol;
  79306. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  79307. goto find_new_min;
  79308. }
  79309. }
  79310. #endif
  79311. /* If necessary, remove sample iMin to make room for the new sample. */
  79312. if( p->nSample>=p->mxSample ){
  79313. Stat4Sample *pMin = &p->a[p->iMin];
  79314. tRowcnt *anEq = pMin->anEq;
  79315. tRowcnt *anLt = pMin->anLt;
  79316. tRowcnt *anDLt = pMin->anDLt;
  79317. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  79318. pSample = &p->a[p->nSample-1];
  79319. pSample->anEq = anEq;
  79320. pSample->anDLt = anDLt;
  79321. pSample->anLt = anLt;
  79322. p->nSample = p->mxSample-1;
  79323. }
  79324. /* The "rows less-than" for the rowid column must be greater than that
  79325. ** for the last sample in the p->a[] array. Otherwise, the samples would
  79326. ** be out of order. */
  79327. #ifdef SQLITE_ENABLE_STAT4
  79328. assert( p->nSample==0
  79329. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  79330. #endif
  79331. /* Insert the new sample */
  79332. pSample = &p->a[p->nSample];
  79333. sampleCopy(p, pSample, pNew);
  79334. p->nSample++;
  79335. /* Zero the first nEqZero entries in the anEq[] array. */
  79336. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  79337. #ifdef SQLITE_ENABLE_STAT4
  79338. find_new_min:
  79339. #endif
  79340. if( p->nSample>=p->mxSample ){
  79341. int iMin = -1;
  79342. for(i=0; i<p->mxSample; i++){
  79343. if( p->a[i].isPSample ) continue;
  79344. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  79345. iMin = i;
  79346. }
  79347. }
  79348. assert( iMin>=0 );
  79349. p->iMin = iMin;
  79350. }
  79351. }
  79352. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79353. /*
  79354. ** Field iChng of the index being scanned has changed. So at this point
  79355. ** p->current contains a sample that reflects the previous row of the
  79356. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  79357. ** correct at this point.
  79358. */
  79359. static void samplePushPrevious(Stat4Accum *p, int iChng){
  79360. #ifdef SQLITE_ENABLE_STAT4
  79361. int i;
  79362. /* Check if any samples from the aBest[] array should be pushed
  79363. ** into IndexSample.a[] at this point. */
  79364. for(i=(p->nCol-2); i>=iChng; i--){
  79365. Stat4Sample *pBest = &p->aBest[i];
  79366. pBest->anEq[i] = p->current.anEq[i];
  79367. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  79368. sampleInsert(p, pBest, i);
  79369. }
  79370. }
  79371. /* Update the anEq[] fields of any samples already collected. */
  79372. for(i=p->nSample-1; i>=0; i--){
  79373. int j;
  79374. for(j=iChng; j<p->nCol; j++){
  79375. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  79376. }
  79377. }
  79378. #endif
  79379. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  79380. if( iChng==0 ){
  79381. tRowcnt nLt = p->current.anLt[0];
  79382. tRowcnt nEq = p->current.anEq[0];
  79383. /* Check if this is to be a periodic sample. If so, add it. */
  79384. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  79385. p->current.isPSample = 1;
  79386. sampleInsert(p, &p->current, 0);
  79387. p->current.isPSample = 0;
  79388. }else
  79389. /* Or if it is a non-periodic sample. Add it in this case too. */
  79390. if( p->nSample<p->mxSample
  79391. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  79392. ){
  79393. sampleInsert(p, &p->current, 0);
  79394. }
  79395. }
  79396. #endif
  79397. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  79398. UNUSED_PARAMETER( p );
  79399. UNUSED_PARAMETER( iChng );
  79400. #endif
  79401. }
  79402. /*
  79403. ** Implementation of the stat_push SQL function: stat_push(P,R,C)
  79404. ** Arguments:
  79405. **
  79406. ** P Pointer to the Stat4Accum object created by stat_init()
  79407. ** C Index of left-most column to differ from previous row
  79408. ** R Rowid for the current row
  79409. **
  79410. ** The SQL function always returns NULL.
  79411. **
  79412. ** The R parameter is only used for STAT3 and STAT4.
  79413. */
  79414. static void statPush(
  79415. sqlite3_context *context,
  79416. int argc,
  79417. sqlite3_value **argv
  79418. ){
  79419. int i;
  79420. /* The three function arguments */
  79421. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  79422. int iChng = sqlite3_value_int(argv[1]);
  79423. UNUSED_PARAMETER( argc );
  79424. UNUSED_PARAMETER( context );
  79425. assert( p->nCol>1 ); /* Includes rowid field */
  79426. assert( iChng<p->nCol );
  79427. if( p->nRow==0 ){
  79428. /* This is the first call to this function. Do initialization. */
  79429. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  79430. }else{
  79431. /* Second and subsequent calls get processed here */
  79432. samplePushPrevious(p, iChng);
  79433. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  79434. ** to the current row of the index. */
  79435. for(i=0; i<iChng; i++){
  79436. p->current.anEq[i]++;
  79437. }
  79438. for(i=iChng; i<p->nCol; i++){
  79439. p->current.anDLt[i]++;
  79440. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79441. p->current.anLt[i] += p->current.anEq[i];
  79442. #endif
  79443. p->current.anEq[i] = 1;
  79444. }
  79445. }
  79446. p->nRow++;
  79447. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79448. p->current.iRowid = sqlite3_value_int64(argv[2]);
  79449. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  79450. #endif
  79451. #ifdef SQLITE_ENABLE_STAT4
  79452. {
  79453. tRowcnt nLt = p->current.anLt[p->nCol-1];
  79454. /* Check if this is to be a periodic sample. If so, add it. */
  79455. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  79456. p->current.isPSample = 1;
  79457. p->current.iCol = 0;
  79458. sampleInsert(p, &p->current, p->nCol-1);
  79459. p->current.isPSample = 0;
  79460. }
  79461. /* Update the aBest[] array. */
  79462. for(i=0; i<(p->nCol-1); i++){
  79463. p->current.iCol = i;
  79464. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  79465. sampleCopy(p, &p->aBest[i], &p->current);
  79466. }
  79467. }
  79468. }
  79469. #endif
  79470. }
  79471. static const FuncDef statPushFuncdef = {
  79472. 2+IsStat34, /* nArg */
  79473. SQLITE_UTF8, /* funcFlags */
  79474. 0, /* pUserData */
  79475. 0, /* pNext */
  79476. statPush, /* xFunc */
  79477. 0, /* xStep */
  79478. 0, /* xFinalize */
  79479. "stat_push", /* zName */
  79480. 0, /* pHash */
  79481. 0 /* pDestructor */
  79482. };
  79483. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  79484. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  79485. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  79486. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  79487. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  79488. /*
  79489. ** Implementation of the stat_get(P,J) SQL function. This routine is
  79490. ** used to query the results. Content is returned for parameter J
  79491. ** which is one of the STAT_GET_xxxx values defined above.
  79492. **
  79493. ** If neither STAT3 nor STAT4 are enabled, then J is always
  79494. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  79495. ** a one-parameter function, stat_get(P), that always returns the
  79496. ** stat1 table entry information.
  79497. */
  79498. static void statGet(
  79499. sqlite3_context *context,
  79500. int argc,
  79501. sqlite3_value **argv
  79502. ){
  79503. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  79504. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79505. /* STAT3 and STAT4 have a parameter on this routine. */
  79506. int eCall = sqlite3_value_int(argv[1]);
  79507. assert( argc==2 );
  79508. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  79509. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  79510. || eCall==STAT_GET_NDLT
  79511. );
  79512. if( eCall==STAT_GET_STAT1 )
  79513. #else
  79514. assert( argc==1 );
  79515. #endif
  79516. {
  79517. /* Return the value to store in the "stat" column of the sqlite_stat1
  79518. ** table for this index.
  79519. **
  79520. ** The value is a string composed of a list of integers describing
  79521. ** the index. The first integer in the list is the total number of
  79522. ** entries in the index. There is one additional integer in the list
  79523. ** for each indexed column. This additional integer is an estimate of
  79524. ** the number of rows matched by a stabbing query on the index using
  79525. ** a key with the corresponding number of fields. In other words,
  79526. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  79527. ** "100 10 2", then SQLite estimates that:
  79528. **
  79529. ** * the index contains 100 rows,
  79530. ** * "WHERE a=?" matches 10 rows, and
  79531. ** * "WHERE a=? AND b=?" matches 2 rows.
  79532. **
  79533. ** If D is the count of distinct values and K is the total number of
  79534. ** rows, then each estimate is computed as:
  79535. **
  79536. ** I = (K+D-1)/D
  79537. */
  79538. char *z;
  79539. int i;
  79540. char *zRet = sqlite3MallocZero(p->nCol * 25);
  79541. if( zRet==0 ){
  79542. sqlite3_result_error_nomem(context);
  79543. return;
  79544. }
  79545. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  79546. z = zRet + sqlite3Strlen30(zRet);
  79547. for(i=0; i<(p->nCol-1); i++){
  79548. u64 nDistinct = p->current.anDLt[i] + 1;
  79549. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  79550. sqlite3_snprintf(24, z, " %llu", iVal);
  79551. z += sqlite3Strlen30(z);
  79552. assert( p->current.anEq[i] );
  79553. }
  79554. assert( z[0]=='\0' && z>zRet );
  79555. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  79556. }
  79557. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79558. else if( eCall==STAT_GET_ROWID ){
  79559. if( p->iGet<0 ){
  79560. samplePushPrevious(p, 0);
  79561. p->iGet = 0;
  79562. }
  79563. if( p->iGet<p->nSample ){
  79564. sqlite3_result_int64(context, p->a[p->iGet].iRowid);
  79565. }
  79566. }else{
  79567. tRowcnt *aCnt = 0;
  79568. assert( p->iGet<p->nSample );
  79569. switch( eCall ){
  79570. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  79571. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  79572. default: {
  79573. aCnt = p->a[p->iGet].anDLt;
  79574. p->iGet++;
  79575. break;
  79576. }
  79577. }
  79578. if( IsStat3 ){
  79579. sqlite3_result_int64(context, (i64)aCnt[0]);
  79580. }else{
  79581. char *zRet = sqlite3MallocZero(p->nCol * 25);
  79582. if( zRet==0 ){
  79583. sqlite3_result_error_nomem(context);
  79584. }else{
  79585. int i;
  79586. char *z = zRet;
  79587. for(i=0; i<p->nCol; i++){
  79588. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  79589. z += sqlite3Strlen30(z);
  79590. }
  79591. assert( z[0]=='\0' && z>zRet );
  79592. z[-1] = '\0';
  79593. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  79594. }
  79595. }
  79596. }
  79597. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79598. #ifndef SQLITE_DEBUG
  79599. UNUSED_PARAMETER( argc );
  79600. #endif
  79601. }
  79602. static const FuncDef statGetFuncdef = {
  79603. 1+IsStat34, /* nArg */
  79604. SQLITE_UTF8, /* funcFlags */
  79605. 0, /* pUserData */
  79606. 0, /* pNext */
  79607. statGet, /* xFunc */
  79608. 0, /* xStep */
  79609. 0, /* xFinalize */
  79610. "stat_get", /* zName */
  79611. 0, /* pHash */
  79612. 0 /* pDestructor */
  79613. };
  79614. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  79615. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  79616. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79617. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  79618. #elif SQLITE_DEBUG
  79619. assert( iParam==STAT_GET_STAT1 );
  79620. #else
  79621. UNUSED_PARAMETER( iParam );
  79622. #endif
  79623. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  79624. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  79625. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  79626. }
  79627. /*
  79628. ** Generate code to do an analysis of all indices associated with
  79629. ** a single table.
  79630. */
  79631. static void analyzeOneTable(
  79632. Parse *pParse, /* Parser context */
  79633. Table *pTab, /* Table whose indices are to be analyzed */
  79634. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  79635. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  79636. int iMem, /* Available memory locations begin here */
  79637. int iTab /* Next available cursor */
  79638. ){
  79639. sqlite3 *db = pParse->db; /* Database handle */
  79640. Index *pIdx; /* An index to being analyzed */
  79641. int iIdxCur; /* Cursor open on index being analyzed */
  79642. int iTabCur; /* Table cursor */
  79643. Vdbe *v; /* The virtual machine being built up */
  79644. int i; /* Loop counter */
  79645. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  79646. int iDb; /* Index of database containing pTab */
  79647. u8 needTableCnt = 1; /* True to count the table */
  79648. int regNewRowid = iMem++; /* Rowid for the inserted record */
  79649. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  79650. int regChng = iMem++; /* Index of changed index field */
  79651. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79652. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  79653. #endif
  79654. int regTemp = iMem++; /* Temporary use register */
  79655. int regTabname = iMem++; /* Register containing table name */
  79656. int regIdxname = iMem++; /* Register containing index name */
  79657. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  79658. int regPrev = iMem; /* MUST BE LAST (see below) */
  79659. pParse->nMem = MAX(pParse->nMem, iMem);
  79660. v = sqlite3GetVdbe(pParse);
  79661. if( v==0 || NEVER(pTab==0) ){
  79662. return;
  79663. }
  79664. if( pTab->tnum==0 ){
  79665. /* Do not gather statistics on views or virtual tables */
  79666. return;
  79667. }
  79668. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  79669. /* Do not gather statistics on system tables */
  79670. return;
  79671. }
  79672. assert( sqlite3BtreeHoldsAllMutexes(db) );
  79673. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  79674. assert( iDb>=0 );
  79675. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79676. #ifndef SQLITE_OMIT_AUTHORIZATION
  79677. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  79678. db->aDb[iDb].zName ) ){
  79679. return;
  79680. }
  79681. #endif
  79682. /* Establish a read-lock on the table at the shared-cache level.
  79683. ** Open a read-only cursor on the table. Also allocate a cursor number
  79684. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  79685. ** this time though. */
  79686. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  79687. iTabCur = iTab++;
  79688. iIdxCur = iTab++;
  79689. pParse->nTab = MAX(pParse->nTab, iTab);
  79690. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  79691. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  79692. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  79693. int nCol; /* Number of columns indexed by pIdx */
  79694. KeyInfo *pKey; /* KeyInfo structure for pIdx */
  79695. int *aGotoChng; /* Array of jump instruction addresses */
  79696. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  79697. int addrGotoChng0; /* Address of "Goto addr_chng_0" */
  79698. int addrNextRow; /* Address of "next_row:" */
  79699. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  79700. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  79701. VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
  79702. nCol = pIdx->nColumn;
  79703. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
  79704. if( aGotoChng==0 ) continue;
  79705. pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  79706. /* Populate the register containing the index name. */
  79707. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
  79708. /*
  79709. ** Pseudo-code for loop that calls stat_push():
  79710. **
  79711. ** Rewind csr
  79712. ** if eof(csr) goto end_of_scan;
  79713. ** regChng = 0
  79714. ** goto chng_addr_0;
  79715. **
  79716. ** next_row:
  79717. ** regChng = 0
  79718. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  79719. ** regChng = 1
  79720. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  79721. ** ...
  79722. ** regChng = N
  79723. ** goto chng_addr_N
  79724. **
  79725. ** chng_addr_0:
  79726. ** regPrev(0) = idx(0)
  79727. ** chng_addr_1:
  79728. ** regPrev(1) = idx(1)
  79729. ** ...
  79730. **
  79731. ** chng_addr_N:
  79732. ** regRowid = idx(rowid)
  79733. ** stat_push(P, regChng, regRowid)
  79734. ** Next csr
  79735. ** if !eof(csr) goto next_row;
  79736. **
  79737. ** end_of_scan:
  79738. */
  79739. /* Make sure there are enough memory cells allocated to accommodate
  79740. ** the regPrev array and a trailing rowid (the rowid slot is required
  79741. ** when building a record to insert into the sample column of
  79742. ** the sqlite_stat4 table. */
  79743. pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
  79744. /* Open a read-only cursor on the index being analyzed. */
  79745. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  79746. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  79747. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  79748. VdbeComment((v, "%s", pIdx->zName));
  79749. /* Invoke the stat_init() function. The arguments are:
  79750. **
  79751. ** (1) the number of columns in the index including the rowid,
  79752. ** (2) the number of rows in the index,
  79753. **
  79754. ** The second argument is only used for STAT3 and STAT4
  79755. */
  79756. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79757. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
  79758. #endif
  79759. sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
  79760. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  79761. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  79762. sqlite3VdbeChangeP5(v, 1+IsStat34);
  79763. /* Implementation of the following:
  79764. **
  79765. ** Rewind csr
  79766. ** if eof(csr) goto end_of_scan;
  79767. ** regChng = 0
  79768. ** goto next_push_0;
  79769. **
  79770. */
  79771. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  79772. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  79773. addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
  79774. /*
  79775. ** next_row:
  79776. ** regChng = 0
  79777. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  79778. ** regChng = 1
  79779. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  79780. ** ...
  79781. ** regChng = N
  79782. ** goto chng_addr_N
  79783. */
  79784. addrNextRow = sqlite3VdbeCurrentAddr(v);
  79785. for(i=0; i<nCol; i++){
  79786. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  79787. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  79788. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  79789. aGotoChng[i] =
  79790. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  79791. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  79792. }
  79793. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
  79794. aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
  79795. /*
  79796. ** chng_addr_0:
  79797. ** regPrev(0) = idx(0)
  79798. ** chng_addr_1:
  79799. ** regPrev(1) = idx(1)
  79800. ** ...
  79801. */
  79802. sqlite3VdbeJumpHere(v, addrGotoChng0);
  79803. for(i=0; i<nCol; i++){
  79804. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  79805. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  79806. }
  79807. /*
  79808. ** chng_addr_N:
  79809. ** regRowid = idx(rowid) // STAT34 only
  79810. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  79811. ** Next csr
  79812. ** if !eof(csr) goto next_row;
  79813. */
  79814. sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
  79815. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79816. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  79817. assert( regRowid==(regStat4+2) );
  79818. #endif
  79819. assert( regChng==(regStat4+1) );
  79820. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  79821. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  79822. sqlite3VdbeChangeP5(v, 2+IsStat34);
  79823. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
  79824. /* Add the entry to the stat1 table. */
  79825. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  79826. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  79827. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  79828. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  79829. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79830. /* Add the entries to the stat3 or stat4 table. */
  79831. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  79832. {
  79833. int regEq = regStat1;
  79834. int regLt = regStat1+1;
  79835. int regDLt = regStat1+2;
  79836. int regSample = regStat1+3;
  79837. int regCol = regStat1+4;
  79838. int regSampleRowid = regCol + nCol;
  79839. int addrNext;
  79840. int addrIsNull;
  79841. pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
  79842. addrNext = sqlite3VdbeCurrentAddr(v);
  79843. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  79844. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  79845. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  79846. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  79847. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  79848. sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
  79849. #ifdef SQLITE_ENABLE_STAT3
  79850. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  79851. pIdx->aiColumn[0], regSample);
  79852. #else
  79853. for(i=0; i<nCol; i++){
  79854. int iCol = pIdx->aiColumn[i];
  79855. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  79856. }
  79857. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
  79858. #endif
  79859. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
  79860. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  79861. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  79862. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
  79863. sqlite3VdbeJumpHere(v, addrIsNull);
  79864. }
  79865. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  79866. /* End of analysis */
  79867. sqlite3VdbeJumpHere(v, addrRewind);
  79868. sqlite3DbFree(db, aGotoChng);
  79869. }
  79870. /* Create a single sqlite_stat1 entry containing NULL as the index
  79871. ** name and the row count as the content.
  79872. */
  79873. if( pOnlyIdx==0 && needTableCnt ){
  79874. VdbeComment((v, "%s", pTab->zName));
  79875. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  79876. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
  79877. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  79878. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
  79879. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  79880. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  79881. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  79882. sqlite3VdbeJumpHere(v, jZeroRows);
  79883. }
  79884. }
  79885. /*
  79886. ** Generate code that will cause the most recent index analysis to
  79887. ** be loaded into internal hash tables where is can be used.
  79888. */
  79889. static void loadAnalysis(Parse *pParse, int iDb){
  79890. Vdbe *v = sqlite3GetVdbe(pParse);
  79891. if( v ){
  79892. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  79893. }
  79894. }
  79895. /*
  79896. ** Generate code that will do an analysis of an entire database
  79897. */
  79898. static void analyzeDatabase(Parse *pParse, int iDb){
  79899. sqlite3 *db = pParse->db;
  79900. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  79901. HashElem *k;
  79902. int iStatCur;
  79903. int iMem;
  79904. int iTab;
  79905. sqlite3BeginWriteOperation(pParse, 0, iDb);
  79906. iStatCur = pParse->nTab;
  79907. pParse->nTab += 3;
  79908. openStatTable(pParse, iDb, iStatCur, 0, 0);
  79909. iMem = pParse->nMem+1;
  79910. iTab = pParse->nTab;
  79911. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  79912. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  79913. Table *pTab = (Table*)sqliteHashData(k);
  79914. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  79915. }
  79916. loadAnalysis(pParse, iDb);
  79917. }
  79918. /*
  79919. ** Generate code that will do an analysis of a single table in
  79920. ** a database. If pOnlyIdx is not NULL then it is a single index
  79921. ** in pTab that should be analyzed.
  79922. */
  79923. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  79924. int iDb;
  79925. int iStatCur;
  79926. assert( pTab!=0 );
  79927. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79928. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  79929. sqlite3BeginWriteOperation(pParse, 0, iDb);
  79930. iStatCur = pParse->nTab;
  79931. pParse->nTab += 3;
  79932. if( pOnlyIdx ){
  79933. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  79934. }else{
  79935. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  79936. }
  79937. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  79938. loadAnalysis(pParse, iDb);
  79939. }
  79940. /*
  79941. ** Generate code for the ANALYZE command. The parser calls this routine
  79942. ** when it recognizes an ANALYZE command.
  79943. **
  79944. ** ANALYZE -- 1
  79945. ** ANALYZE <database> -- 2
  79946. ** ANALYZE ?<database>.?<tablename> -- 3
  79947. **
  79948. ** Form 1 causes all indices in all attached databases to be analyzed.
  79949. ** Form 2 analyzes all indices the single database named.
  79950. ** Form 3 analyzes all indices associated with the named table.
  79951. */
  79952. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  79953. sqlite3 *db = pParse->db;
  79954. int iDb;
  79955. int i;
  79956. char *z, *zDb;
  79957. Table *pTab;
  79958. Index *pIdx;
  79959. Token *pTableName;
  79960. /* Read the database schema. If an error occurs, leave an error message
  79961. ** and code in pParse and return NULL. */
  79962. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79963. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  79964. return;
  79965. }
  79966. assert( pName2!=0 || pName1==0 );
  79967. if( pName1==0 ){
  79968. /* Form 1: Analyze everything */
  79969. for(i=0; i<db->nDb; i++){
  79970. if( i==1 ) continue; /* Do not analyze the TEMP database */
  79971. analyzeDatabase(pParse, i);
  79972. }
  79973. }else if( pName2->n==0 ){
  79974. /* Form 2: Analyze the database or table named */
  79975. iDb = sqlite3FindDb(db, pName1);
  79976. if( iDb>=0 ){
  79977. analyzeDatabase(pParse, iDb);
  79978. }else{
  79979. z = sqlite3NameFromToken(db, pName1);
  79980. if( z ){
  79981. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  79982. analyzeTable(pParse, pIdx->pTable, pIdx);
  79983. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  79984. analyzeTable(pParse, pTab, 0);
  79985. }
  79986. sqlite3DbFree(db, z);
  79987. }
  79988. }
  79989. }else{
  79990. /* Form 3: Analyze the fully qualified table name */
  79991. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  79992. if( iDb>=0 ){
  79993. zDb = db->aDb[iDb].zName;
  79994. z = sqlite3NameFromToken(db, pTableName);
  79995. if( z ){
  79996. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  79997. analyzeTable(pParse, pIdx->pTable, pIdx);
  79998. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  79999. analyzeTable(pParse, pTab, 0);
  80000. }
  80001. sqlite3DbFree(db, z);
  80002. }
  80003. }
  80004. }
  80005. }
  80006. /*
  80007. ** Used to pass information from the analyzer reader through to the
  80008. ** callback routine.
  80009. */
  80010. typedef struct analysisInfo analysisInfo;
  80011. struct analysisInfo {
  80012. sqlite3 *db;
  80013. const char *zDatabase;
  80014. };
  80015. /*
  80016. ** The first argument points to a nul-terminated string containing a
  80017. ** list of space separated integers. Read the first nOut of these into
  80018. ** the array aOut[].
  80019. */
  80020. static void decodeIntArray(
  80021. char *zIntArray, /* String containing int array to decode */
  80022. int nOut, /* Number of slots in aOut[] */
  80023. tRowcnt *aOut, /* Store integers here */
  80024. Index *pIndex /* Handle extra flags for this index, if not NULL */
  80025. ){
  80026. char *z = zIntArray;
  80027. int c;
  80028. int i;
  80029. tRowcnt v;
  80030. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80031. if( z==0 ) z = "";
  80032. #else
  80033. if( NEVER(z==0) ) z = "";
  80034. #endif
  80035. for(i=0; *z && i<nOut; i++){
  80036. v = 0;
  80037. while( (c=z[0])>='0' && c<='9' ){
  80038. v = v*10 + c - '0';
  80039. z++;
  80040. }
  80041. aOut[i] = v;
  80042. if( *z==' ' ) z++;
  80043. }
  80044. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  80045. assert( pIndex!=0 );
  80046. #else
  80047. if( pIndex )
  80048. #endif
  80049. {
  80050. if( strcmp(z, "unordered")==0 ){
  80051. pIndex->bUnordered = 1;
  80052. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  80053. int v32 = 0;
  80054. sqlite3GetInt32(z+3, &v32);
  80055. pIndex->szIdxRow = sqlite3LogEst(v32);
  80056. }
  80057. }
  80058. }
  80059. /*
  80060. ** This callback is invoked once for each index when reading the
  80061. ** sqlite_stat1 table.
  80062. **
  80063. ** argv[0] = name of the table
  80064. ** argv[1] = name of the index (might be NULL)
  80065. ** argv[2] = results of analysis - on integer for each column
  80066. **
  80067. ** Entries for which argv[1]==NULL simply record the number of rows in
  80068. ** the table.
  80069. */
  80070. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  80071. analysisInfo *pInfo = (analysisInfo*)pData;
  80072. Index *pIndex;
  80073. Table *pTable;
  80074. const char *z;
  80075. assert( argc==3 );
  80076. UNUSED_PARAMETER2(NotUsed, argc);
  80077. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  80078. return 0;
  80079. }
  80080. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  80081. if( pTable==0 ){
  80082. return 0;
  80083. }
  80084. if( argv[1] ){
  80085. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  80086. }else{
  80087. pIndex = 0;
  80088. }
  80089. z = argv[2];
  80090. if( pIndex ){
  80091. decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, pIndex);
  80092. if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
  80093. }else{
  80094. Index fakeIdx;
  80095. fakeIdx.szIdxRow = pTable->szTabRow;
  80096. decodeIntArray((char*)z, 1, &pTable->nRowEst, &fakeIdx);
  80097. pTable->szTabRow = fakeIdx.szIdxRow;
  80098. }
  80099. return 0;
  80100. }
  80101. /*
  80102. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  80103. ** and its contents.
  80104. */
  80105. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  80106. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80107. if( pIdx->aSample ){
  80108. int j;
  80109. for(j=0; j<pIdx->nSample; j++){
  80110. IndexSample *p = &pIdx->aSample[j];
  80111. sqlite3DbFree(db, p->p);
  80112. }
  80113. sqlite3DbFree(db, pIdx->aSample);
  80114. }
  80115. if( db && db->pnBytesFreed==0 ){
  80116. pIdx->nSample = 0;
  80117. pIdx->aSample = 0;
  80118. }
  80119. #else
  80120. UNUSED_PARAMETER(db);
  80121. UNUSED_PARAMETER(pIdx);
  80122. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  80123. }
  80124. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80125. /*
  80126. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  80127. ** stored in pIdx->aSample[].
  80128. */
  80129. static void initAvgEq(Index *pIdx){
  80130. if( pIdx ){
  80131. IndexSample *aSample = pIdx->aSample;
  80132. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  80133. int iCol;
  80134. for(iCol=0; iCol<pIdx->nColumn; iCol++){
  80135. int i; /* Used to iterate through samples */
  80136. tRowcnt sumEq = 0; /* Sum of the nEq values */
  80137. tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
  80138. tRowcnt avgEq = 0;
  80139. tRowcnt nDLt = pFinal->anDLt[iCol];
  80140. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  80141. ** occur in the stat4 table for this index before pFinal. Set
  80142. ** sumEq to the sum of the nEq values for column iCol for the same
  80143. ** set (adding the value only once where there exist dupicate
  80144. ** prefixes). */
  80145. for(i=0; i<(pIdx->nSample-1); i++){
  80146. if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
  80147. sumEq += aSample[i].anEq[iCol];
  80148. nSum++;
  80149. }
  80150. }
  80151. if( nDLt>nSum ){
  80152. avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
  80153. }
  80154. if( avgEq==0 ) avgEq = 1;
  80155. pIdx->aAvgEq[iCol] = avgEq;
  80156. if( pIdx->nSampleCol==1 ) break;
  80157. }
  80158. }
  80159. }
  80160. /*
  80161. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  80162. ** into the relevant Index.aSample[] arrays.
  80163. **
  80164. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  80165. ** data equivalent to the following (statements are different for stat3,
  80166. ** see the caller of this function for details):
  80167. **
  80168. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  80169. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  80170. **
  80171. ** where %Q is replaced with the database name before the SQL is executed.
  80172. */
  80173. static int loadStatTbl(
  80174. sqlite3 *db, /* Database handle */
  80175. int bStat3, /* Assume single column records only */
  80176. const char *zSql1, /* SQL statement 1 (see above) */
  80177. const char *zSql2, /* SQL statement 2 (see above) */
  80178. const char *zDb /* Database name (e.g. "main") */
  80179. ){
  80180. int rc; /* Result codes from subroutines */
  80181. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  80182. char *zSql; /* Text of the SQL statement */
  80183. Index *pPrevIdx = 0; /* Previous index in the loop */
  80184. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  80185. assert( db->lookaside.bEnabled==0 );
  80186. zSql = sqlite3MPrintf(db, zSql1, zDb);
  80187. if( !zSql ){
  80188. return SQLITE_NOMEM;
  80189. }
  80190. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  80191. sqlite3DbFree(db, zSql);
  80192. if( rc ) return rc;
  80193. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  80194. int nIdxCol = 1; /* Number of columns in stat4 records */
  80195. int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
  80196. char *zIndex; /* Index name */
  80197. Index *pIdx; /* Pointer to the index object */
  80198. int nSample; /* Number of samples */
  80199. int nByte; /* Bytes of space required */
  80200. int i; /* Bytes of space required */
  80201. tRowcnt *pSpace;
  80202. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  80203. if( zIndex==0 ) continue;
  80204. nSample = sqlite3_column_int(pStmt, 1);
  80205. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  80206. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  80207. /* Index.nSample is non-zero at this point if data has already been
  80208. ** loaded from the stat4 table. In this case ignore stat3 data. */
  80209. if( pIdx==0 || pIdx->nSample ) continue;
  80210. if( bStat3==0 ){
  80211. nIdxCol = pIdx->nColumn+1;
  80212. nAvgCol = pIdx->nColumn;
  80213. }
  80214. pIdx->nSampleCol = nIdxCol;
  80215. nByte = sizeof(IndexSample) * nSample;
  80216. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  80217. nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  80218. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  80219. if( pIdx->aSample==0 ){
  80220. sqlite3_finalize(pStmt);
  80221. return SQLITE_NOMEM;
  80222. }
  80223. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  80224. pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
  80225. for(i=0; i<nSample; i++){
  80226. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  80227. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  80228. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  80229. }
  80230. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  80231. }
  80232. rc = sqlite3_finalize(pStmt);
  80233. if( rc ) return rc;
  80234. zSql = sqlite3MPrintf(db, zSql2, zDb);
  80235. if( !zSql ){
  80236. return SQLITE_NOMEM;
  80237. }
  80238. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  80239. sqlite3DbFree(db, zSql);
  80240. if( rc ) return rc;
  80241. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  80242. char *zIndex; /* Index name */
  80243. Index *pIdx; /* Pointer to the index object */
  80244. int nCol = 1; /* Number of columns in index */
  80245. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  80246. if( zIndex==0 ) continue;
  80247. pIdx = sqlite3FindIndex(db, zIndex, zDb);
  80248. if( pIdx==0 ) continue;
  80249. /* This next condition is true if data has already been loaded from
  80250. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  80251. nCol = pIdx->nSampleCol;
  80252. if( bStat3 && nCol>1 ) continue;
  80253. if( pIdx!=pPrevIdx ){
  80254. initAvgEq(pPrevIdx);
  80255. pPrevIdx = pIdx;
  80256. }
  80257. pSample = &pIdx->aSample[pIdx->nSample];
  80258. decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
  80259. decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
  80260. decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
  80261. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  80262. ** This is in case the sample record is corrupted. In that case, the
  80263. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  80264. ** end of the allocated buffer before it realizes it is dealing with
  80265. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  80266. ** a buffer overread. */
  80267. pSample->n = sqlite3_column_bytes(pStmt, 4);
  80268. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  80269. if( pSample->p==0 ){
  80270. sqlite3_finalize(pStmt);
  80271. return SQLITE_NOMEM;
  80272. }
  80273. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  80274. pIdx->nSample++;
  80275. }
  80276. rc = sqlite3_finalize(pStmt);
  80277. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  80278. return rc;
  80279. }
  80280. /*
  80281. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  80282. ** the Index.aSample[] arrays of all indices.
  80283. */
  80284. static int loadStat4(sqlite3 *db, const char *zDb){
  80285. int rc = SQLITE_OK; /* Result codes from subroutines */
  80286. assert( db->lookaside.bEnabled==0 );
  80287. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  80288. rc = loadStatTbl(db, 0,
  80289. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  80290. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  80291. zDb
  80292. );
  80293. }
  80294. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  80295. rc = loadStatTbl(db, 1,
  80296. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  80297. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  80298. zDb
  80299. );
  80300. }
  80301. return rc;
  80302. }
  80303. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  80304. /*
  80305. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  80306. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  80307. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  80308. ** Index.aSample[] arrays.
  80309. **
  80310. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  80311. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  80312. ** during compilation and the sqlite_stat3/4 table is present, no data is
  80313. ** read from it.
  80314. **
  80315. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  80316. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  80317. ** returned. However, in this case, data is read from the sqlite_stat1
  80318. ** table (if it is present) before returning.
  80319. **
  80320. ** If an OOM error occurs, this function always sets db->mallocFailed.
  80321. ** This means if the caller does not care about other errors, the return
  80322. ** code may be ignored.
  80323. */
  80324. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  80325. analysisInfo sInfo;
  80326. HashElem *i;
  80327. char *zSql;
  80328. int rc;
  80329. assert( iDb>=0 && iDb<db->nDb );
  80330. assert( db->aDb[iDb].pBt!=0 );
  80331. /* Clear any prior statistics */
  80332. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  80333. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  80334. Index *pIdx = sqliteHashData(i);
  80335. sqlite3DefaultRowEst(pIdx);
  80336. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80337. sqlite3DeleteIndexSamples(db, pIdx);
  80338. pIdx->aSample = 0;
  80339. #endif
  80340. }
  80341. /* Check to make sure the sqlite_stat1 table exists */
  80342. sInfo.db = db;
  80343. sInfo.zDatabase = db->aDb[iDb].zName;
  80344. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  80345. return SQLITE_ERROR;
  80346. }
  80347. /* Load new statistics out of the sqlite_stat1 table */
  80348. zSql = sqlite3MPrintf(db,
  80349. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  80350. if( zSql==0 ){
  80351. rc = SQLITE_NOMEM;
  80352. }else{
  80353. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  80354. sqlite3DbFree(db, zSql);
  80355. }
  80356. /* Load the statistics from the sqlite_stat4 table. */
  80357. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80358. if( rc==SQLITE_OK ){
  80359. int lookasideEnabled = db->lookaside.bEnabled;
  80360. db->lookaside.bEnabled = 0;
  80361. rc = loadStat4(db, sInfo.zDatabase);
  80362. db->lookaside.bEnabled = lookasideEnabled;
  80363. }
  80364. #endif
  80365. if( rc==SQLITE_NOMEM ){
  80366. db->mallocFailed = 1;
  80367. }
  80368. return rc;
  80369. }
  80370. #endif /* SQLITE_OMIT_ANALYZE */
  80371. /************** End of analyze.c *********************************************/
  80372. /************** Begin file attach.c ******************************************/
  80373. /*
  80374. ** 2003 April 6
  80375. **
  80376. ** The author disclaims copyright to this source code. In place of
  80377. ** a legal notice, here is a blessing:
  80378. **
  80379. ** May you do good and not evil.
  80380. ** May you find forgiveness for yourself and forgive others.
  80381. ** May you share freely, never taking more than you give.
  80382. **
  80383. *************************************************************************
  80384. ** This file contains code used to implement the ATTACH and DETACH commands.
  80385. */
  80386. #ifndef SQLITE_OMIT_ATTACH
  80387. /*
  80388. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  80389. ** is slightly different from resolving a normal SQL expression, because simple
  80390. ** identifiers are treated as strings, not possible column names or aliases.
  80391. **
  80392. ** i.e. if the parser sees:
  80393. **
  80394. ** ATTACH DATABASE abc AS def
  80395. **
  80396. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  80397. ** looking for columns of the same name.
  80398. **
  80399. ** This only applies to the root node of pExpr, so the statement:
  80400. **
  80401. ** ATTACH DATABASE abc||def AS 'db2'
  80402. **
  80403. ** will fail because neither abc or def can be resolved.
  80404. */
  80405. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  80406. {
  80407. int rc = SQLITE_OK;
  80408. if( pExpr ){
  80409. if( pExpr->op!=TK_ID ){
  80410. rc = sqlite3ResolveExprNames(pName, pExpr);
  80411. if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
  80412. sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
  80413. return SQLITE_ERROR;
  80414. }
  80415. }else{
  80416. pExpr->op = TK_STRING;
  80417. }
  80418. }
  80419. return rc;
  80420. }
  80421. /*
  80422. ** An SQL user-function registered to do the work of an ATTACH statement. The
  80423. ** three arguments to the function come directly from an attach statement:
  80424. **
  80425. ** ATTACH DATABASE x AS y KEY z
  80426. **
  80427. ** SELECT sqlite_attach(x, y, z)
  80428. **
  80429. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  80430. ** third argument.
  80431. */
  80432. static void attachFunc(
  80433. sqlite3_context *context,
  80434. int NotUsed,
  80435. sqlite3_value **argv
  80436. ){
  80437. int i;
  80438. int rc = 0;
  80439. sqlite3 *db = sqlite3_context_db_handle(context);
  80440. const char *zName;
  80441. const char *zFile;
  80442. char *zPath = 0;
  80443. char *zErr = 0;
  80444. unsigned int flags;
  80445. Db *aNew;
  80446. char *zErrDyn = 0;
  80447. sqlite3_vfs *pVfs;
  80448. UNUSED_PARAMETER(NotUsed);
  80449. zFile = (const char *)sqlite3_value_text(argv[0]);
  80450. zName = (const char *)sqlite3_value_text(argv[1]);
  80451. if( zFile==0 ) zFile = "";
  80452. if( zName==0 ) zName = "";
  80453. /* Check for the following errors:
  80454. **
  80455. ** * Too many attached databases,
  80456. ** * Transaction currently open
  80457. ** * Specified database name already being used.
  80458. */
  80459. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  80460. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  80461. db->aLimit[SQLITE_LIMIT_ATTACHED]
  80462. );
  80463. goto attach_error;
  80464. }
  80465. if( !db->autoCommit ){
  80466. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  80467. goto attach_error;
  80468. }
  80469. for(i=0; i<db->nDb; i++){
  80470. char *z = db->aDb[i].zName;
  80471. assert( z && zName );
  80472. if( sqlite3StrICmp(z, zName)==0 ){
  80473. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  80474. goto attach_error;
  80475. }
  80476. }
  80477. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  80478. ** hash tables.
  80479. */
  80480. if( db->aDb==db->aDbStatic ){
  80481. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  80482. if( aNew==0 ) return;
  80483. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  80484. }else{
  80485. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  80486. if( aNew==0 ) return;
  80487. }
  80488. db->aDb = aNew;
  80489. aNew = &db->aDb[db->nDb];
  80490. memset(aNew, 0, sizeof(*aNew));
  80491. /* Open the database file. If the btree is successfully opened, use
  80492. ** it to obtain the database schema. At this point the schema may
  80493. ** or may not be initialized.
  80494. */
  80495. flags = db->openFlags;
  80496. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  80497. if( rc!=SQLITE_OK ){
  80498. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  80499. sqlite3_result_error(context, zErr, -1);
  80500. sqlite3_free(zErr);
  80501. return;
  80502. }
  80503. assert( pVfs );
  80504. flags |= SQLITE_OPEN_MAIN_DB;
  80505. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  80506. sqlite3_free( zPath );
  80507. db->nDb++;
  80508. if( rc==SQLITE_CONSTRAINT ){
  80509. rc = SQLITE_ERROR;
  80510. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  80511. }else if( rc==SQLITE_OK ){
  80512. Pager *pPager;
  80513. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  80514. if( !aNew->pSchema ){
  80515. rc = SQLITE_NOMEM;
  80516. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  80517. zErrDyn = sqlite3MPrintf(db,
  80518. "attached databases must use the same text encoding as main database");
  80519. rc = SQLITE_ERROR;
  80520. }
  80521. pPager = sqlite3BtreePager(aNew->pBt);
  80522. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  80523. sqlite3BtreeSecureDelete(aNew->pBt,
  80524. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  80525. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  80526. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  80527. #endif
  80528. }
  80529. aNew->safety_level = 3;
  80530. aNew->zName = sqlite3DbStrDup(db, zName);
  80531. if( rc==SQLITE_OK && aNew->zName==0 ){
  80532. rc = SQLITE_NOMEM;
  80533. }
  80534. #ifdef SQLITE_HAS_CODEC
  80535. if( rc==SQLITE_OK ){
  80536. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  80537. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  80538. int nKey;
  80539. char *zKey;
  80540. int t = sqlite3_value_type(argv[2]);
  80541. switch( t ){
  80542. case SQLITE_INTEGER:
  80543. case SQLITE_FLOAT:
  80544. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  80545. rc = SQLITE_ERROR;
  80546. break;
  80547. case SQLITE_TEXT:
  80548. case SQLITE_BLOB:
  80549. nKey = sqlite3_value_bytes(argv[2]);
  80550. zKey = (char *)sqlite3_value_blob(argv[2]);
  80551. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  80552. break;
  80553. case SQLITE_NULL:
  80554. /* No key specified. Use the key from the main database */
  80555. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  80556. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  80557. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  80558. }
  80559. break;
  80560. }
  80561. }
  80562. #endif
  80563. /* If the file was opened successfully, read the schema for the new database.
  80564. ** If this fails, or if opening the file failed, then close the file and
  80565. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  80566. ** we found it.
  80567. */
  80568. if( rc==SQLITE_OK ){
  80569. sqlite3BtreeEnterAll(db);
  80570. rc = sqlite3Init(db, &zErrDyn);
  80571. sqlite3BtreeLeaveAll(db);
  80572. }
  80573. if( rc ){
  80574. int iDb = db->nDb - 1;
  80575. assert( iDb>=2 );
  80576. if( db->aDb[iDb].pBt ){
  80577. sqlite3BtreeClose(db->aDb[iDb].pBt);
  80578. db->aDb[iDb].pBt = 0;
  80579. db->aDb[iDb].pSchema = 0;
  80580. }
  80581. sqlite3ResetAllSchemasOfConnection(db);
  80582. db->nDb = iDb;
  80583. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  80584. db->mallocFailed = 1;
  80585. sqlite3DbFree(db, zErrDyn);
  80586. zErrDyn = sqlite3MPrintf(db, "out of memory");
  80587. }else if( zErrDyn==0 ){
  80588. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  80589. }
  80590. goto attach_error;
  80591. }
  80592. return;
  80593. attach_error:
  80594. /* Return an error if we get here */
  80595. if( zErrDyn ){
  80596. sqlite3_result_error(context, zErrDyn, -1);
  80597. sqlite3DbFree(db, zErrDyn);
  80598. }
  80599. if( rc ) sqlite3_result_error_code(context, rc);
  80600. }
  80601. /*
  80602. ** An SQL user-function registered to do the work of an DETACH statement. The
  80603. ** three arguments to the function come directly from a detach statement:
  80604. **
  80605. ** DETACH DATABASE x
  80606. **
  80607. ** SELECT sqlite_detach(x)
  80608. */
  80609. static void detachFunc(
  80610. sqlite3_context *context,
  80611. int NotUsed,
  80612. sqlite3_value **argv
  80613. ){
  80614. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  80615. sqlite3 *db = sqlite3_context_db_handle(context);
  80616. int i;
  80617. Db *pDb = 0;
  80618. char zErr[128];
  80619. UNUSED_PARAMETER(NotUsed);
  80620. if( zName==0 ) zName = "";
  80621. for(i=0; i<db->nDb; i++){
  80622. pDb = &db->aDb[i];
  80623. if( pDb->pBt==0 ) continue;
  80624. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  80625. }
  80626. if( i>=db->nDb ){
  80627. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  80628. goto detach_error;
  80629. }
  80630. if( i<2 ){
  80631. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  80632. goto detach_error;
  80633. }
  80634. if( !db->autoCommit ){
  80635. sqlite3_snprintf(sizeof(zErr), zErr,
  80636. "cannot DETACH database within transaction");
  80637. goto detach_error;
  80638. }
  80639. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  80640. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  80641. goto detach_error;
  80642. }
  80643. sqlite3BtreeClose(pDb->pBt);
  80644. pDb->pBt = 0;
  80645. pDb->pSchema = 0;
  80646. sqlite3ResetAllSchemasOfConnection(db);
  80647. return;
  80648. detach_error:
  80649. sqlite3_result_error(context, zErr, -1);
  80650. }
  80651. /*
  80652. ** This procedure generates VDBE code for a single invocation of either the
  80653. ** sqlite_detach() or sqlite_attach() SQL user functions.
  80654. */
  80655. static void codeAttach(
  80656. Parse *pParse, /* The parser context */
  80657. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  80658. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  80659. Expr *pAuthArg, /* Expression to pass to authorization callback */
  80660. Expr *pFilename, /* Name of database file */
  80661. Expr *pDbname, /* Name of the database to use internally */
  80662. Expr *pKey /* Database key for encryption extension */
  80663. ){
  80664. int rc;
  80665. NameContext sName;
  80666. Vdbe *v;
  80667. sqlite3* db = pParse->db;
  80668. int regArgs;
  80669. memset(&sName, 0, sizeof(NameContext));
  80670. sName.pParse = pParse;
  80671. if(
  80672. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  80673. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  80674. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  80675. ){
  80676. pParse->nErr++;
  80677. goto attach_end;
  80678. }
  80679. #ifndef SQLITE_OMIT_AUTHORIZATION
  80680. if( pAuthArg ){
  80681. char *zAuthArg;
  80682. if( pAuthArg->op==TK_STRING ){
  80683. zAuthArg = pAuthArg->u.zToken;
  80684. }else{
  80685. zAuthArg = 0;
  80686. }
  80687. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  80688. if(rc!=SQLITE_OK ){
  80689. goto attach_end;
  80690. }
  80691. }
  80692. #endif /* SQLITE_OMIT_AUTHORIZATION */
  80693. v = sqlite3GetVdbe(pParse);
  80694. regArgs = sqlite3GetTempRange(pParse, 4);
  80695. sqlite3ExprCode(pParse, pFilename, regArgs);
  80696. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  80697. sqlite3ExprCode(pParse, pKey, regArgs+2);
  80698. assert( v || db->mallocFailed );
  80699. if( v ){
  80700. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  80701. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  80702. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  80703. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  80704. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  80705. ** statement only). For DETACH, set it to false (expire all existing
  80706. ** statements).
  80707. */
  80708. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  80709. }
  80710. attach_end:
  80711. sqlite3ExprDelete(db, pFilename);
  80712. sqlite3ExprDelete(db, pDbname);
  80713. sqlite3ExprDelete(db, pKey);
  80714. }
  80715. /*
  80716. ** Called by the parser to compile a DETACH statement.
  80717. **
  80718. ** DETACH pDbname
  80719. */
  80720. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  80721. static const FuncDef detach_func = {
  80722. 1, /* nArg */
  80723. SQLITE_UTF8, /* funcFlags */
  80724. 0, /* pUserData */
  80725. 0, /* pNext */
  80726. detachFunc, /* xFunc */
  80727. 0, /* xStep */
  80728. 0, /* xFinalize */
  80729. "sqlite_detach", /* zName */
  80730. 0, /* pHash */
  80731. 0 /* pDestructor */
  80732. };
  80733. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  80734. }
  80735. /*
  80736. ** Called by the parser to compile an ATTACH statement.
  80737. **
  80738. ** ATTACH p AS pDbname KEY pKey
  80739. */
  80740. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  80741. static const FuncDef attach_func = {
  80742. 3, /* nArg */
  80743. SQLITE_UTF8, /* funcFlags */
  80744. 0, /* pUserData */
  80745. 0, /* pNext */
  80746. attachFunc, /* xFunc */
  80747. 0, /* xStep */
  80748. 0, /* xFinalize */
  80749. "sqlite_attach", /* zName */
  80750. 0, /* pHash */
  80751. 0 /* pDestructor */
  80752. };
  80753. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  80754. }
  80755. #endif /* SQLITE_OMIT_ATTACH */
  80756. /*
  80757. ** Initialize a DbFixer structure. This routine must be called prior
  80758. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  80759. */
  80760. SQLITE_PRIVATE void sqlite3FixInit(
  80761. DbFixer *pFix, /* The fixer to be initialized */
  80762. Parse *pParse, /* Error messages will be written here */
  80763. int iDb, /* This is the database that must be used */
  80764. const char *zType, /* "view", "trigger", or "index" */
  80765. const Token *pName /* Name of the view, trigger, or index */
  80766. ){
  80767. sqlite3 *db;
  80768. db = pParse->db;
  80769. assert( db->nDb>iDb );
  80770. pFix->pParse = pParse;
  80771. pFix->zDb = db->aDb[iDb].zName;
  80772. pFix->pSchema = db->aDb[iDb].pSchema;
  80773. pFix->zType = zType;
  80774. pFix->pName = pName;
  80775. pFix->bVarOnly = (iDb==1);
  80776. }
  80777. /*
  80778. ** The following set of routines walk through the parse tree and assign
  80779. ** a specific database to all table references where the database name
  80780. ** was left unspecified in the original SQL statement. The pFix structure
  80781. ** must have been initialized by a prior call to sqlite3FixInit().
  80782. **
  80783. ** These routines are used to make sure that an index, trigger, or
  80784. ** view in one database does not refer to objects in a different database.
  80785. ** (Exception: indices, triggers, and views in the TEMP database are
  80786. ** allowed to refer to anything.) If a reference is explicitly made
  80787. ** to an object in a different database, an error message is added to
  80788. ** pParse->zErrMsg and these routines return non-zero. If everything
  80789. ** checks out, these routines return 0.
  80790. */
  80791. SQLITE_PRIVATE int sqlite3FixSrcList(
  80792. DbFixer *pFix, /* Context of the fixation */
  80793. SrcList *pList /* The Source list to check and modify */
  80794. ){
  80795. int i;
  80796. const char *zDb;
  80797. struct SrcList_item *pItem;
  80798. if( NEVER(pList==0) ) return 0;
  80799. zDb = pFix->zDb;
  80800. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  80801. if( pFix->bVarOnly==0 ){
  80802. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  80803. sqlite3ErrorMsg(pFix->pParse,
  80804. "%s %T cannot reference objects in database %s",
  80805. pFix->zType, pFix->pName, pItem->zDatabase);
  80806. return 1;
  80807. }
  80808. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  80809. pItem->zDatabase = 0;
  80810. pItem->pSchema = pFix->pSchema;
  80811. }
  80812. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  80813. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  80814. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  80815. #endif
  80816. }
  80817. return 0;
  80818. }
  80819. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  80820. SQLITE_PRIVATE int sqlite3FixSelect(
  80821. DbFixer *pFix, /* Context of the fixation */
  80822. Select *pSelect /* The SELECT statement to be fixed to one database */
  80823. ){
  80824. while( pSelect ){
  80825. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  80826. return 1;
  80827. }
  80828. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  80829. return 1;
  80830. }
  80831. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  80832. return 1;
  80833. }
  80834. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  80835. return 1;
  80836. }
  80837. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  80838. return 1;
  80839. }
  80840. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  80841. return 1;
  80842. }
  80843. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  80844. return 1;
  80845. }
  80846. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  80847. return 1;
  80848. }
  80849. pSelect = pSelect->pPrior;
  80850. }
  80851. return 0;
  80852. }
  80853. SQLITE_PRIVATE int sqlite3FixExpr(
  80854. DbFixer *pFix, /* Context of the fixation */
  80855. Expr *pExpr /* The expression to be fixed to one database */
  80856. ){
  80857. while( pExpr ){
  80858. if( pExpr->op==TK_VARIABLE ){
  80859. if( pFix->pParse->db->init.busy ){
  80860. pExpr->op = TK_NULL;
  80861. }else{
  80862. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  80863. return 1;
  80864. }
  80865. }
  80866. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  80867. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  80868. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  80869. }else{
  80870. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  80871. }
  80872. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  80873. return 1;
  80874. }
  80875. pExpr = pExpr->pLeft;
  80876. }
  80877. return 0;
  80878. }
  80879. SQLITE_PRIVATE int sqlite3FixExprList(
  80880. DbFixer *pFix, /* Context of the fixation */
  80881. ExprList *pList /* The expression to be fixed to one database */
  80882. ){
  80883. int i;
  80884. struct ExprList_item *pItem;
  80885. if( pList==0 ) return 0;
  80886. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  80887. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  80888. return 1;
  80889. }
  80890. }
  80891. return 0;
  80892. }
  80893. #endif
  80894. #ifndef SQLITE_OMIT_TRIGGER
  80895. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  80896. DbFixer *pFix, /* Context of the fixation */
  80897. TriggerStep *pStep /* The trigger step be fixed to one database */
  80898. ){
  80899. while( pStep ){
  80900. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  80901. return 1;
  80902. }
  80903. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  80904. return 1;
  80905. }
  80906. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  80907. return 1;
  80908. }
  80909. pStep = pStep->pNext;
  80910. }
  80911. return 0;
  80912. }
  80913. #endif
  80914. /************** End of attach.c **********************************************/
  80915. /************** Begin file auth.c ********************************************/
  80916. /*
  80917. ** 2003 January 11
  80918. **
  80919. ** The author disclaims copyright to this source code. In place of
  80920. ** a legal notice, here is a blessing:
  80921. **
  80922. ** May you do good and not evil.
  80923. ** May you find forgiveness for yourself and forgive others.
  80924. ** May you share freely, never taking more than you give.
  80925. **
  80926. *************************************************************************
  80927. ** This file contains code used to implement the sqlite3_set_authorizer()
  80928. ** API. This facility is an optional feature of the library. Embedded
  80929. ** systems that do not need this facility may omit it by recompiling
  80930. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  80931. */
  80932. /*
  80933. ** All of the code in this file may be omitted by defining a single
  80934. ** macro.
  80935. */
  80936. #ifndef SQLITE_OMIT_AUTHORIZATION
  80937. /*
  80938. ** Set or clear the access authorization function.
  80939. **
  80940. ** The access authorization function is be called during the compilation
  80941. ** phase to verify that the user has read and/or write access permission on
  80942. ** various fields of the database. The first argument to the auth function
  80943. ** is a copy of the 3rd argument to this routine. The second argument
  80944. ** to the auth function is one of these constants:
  80945. **
  80946. ** SQLITE_CREATE_INDEX
  80947. ** SQLITE_CREATE_TABLE
  80948. ** SQLITE_CREATE_TEMP_INDEX
  80949. ** SQLITE_CREATE_TEMP_TABLE
  80950. ** SQLITE_CREATE_TEMP_TRIGGER
  80951. ** SQLITE_CREATE_TEMP_VIEW
  80952. ** SQLITE_CREATE_TRIGGER
  80953. ** SQLITE_CREATE_VIEW
  80954. ** SQLITE_DELETE
  80955. ** SQLITE_DROP_INDEX
  80956. ** SQLITE_DROP_TABLE
  80957. ** SQLITE_DROP_TEMP_INDEX
  80958. ** SQLITE_DROP_TEMP_TABLE
  80959. ** SQLITE_DROP_TEMP_TRIGGER
  80960. ** SQLITE_DROP_TEMP_VIEW
  80961. ** SQLITE_DROP_TRIGGER
  80962. ** SQLITE_DROP_VIEW
  80963. ** SQLITE_INSERT
  80964. ** SQLITE_PRAGMA
  80965. ** SQLITE_READ
  80966. ** SQLITE_SELECT
  80967. ** SQLITE_TRANSACTION
  80968. ** SQLITE_UPDATE
  80969. **
  80970. ** The third and fourth arguments to the auth function are the name of
  80971. ** the table and the column that are being accessed. The auth function
  80972. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  80973. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  80974. ** means that the SQL statement will never-run - the sqlite3_exec() call
  80975. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  80976. ** should run but attempts to read the specified column will return NULL
  80977. ** and attempts to write the column will be ignored.
  80978. **
  80979. ** Setting the auth function to NULL disables this hook. The default
  80980. ** setting of the auth function is NULL.
  80981. */
  80982. SQLITE_API int sqlite3_set_authorizer(
  80983. sqlite3 *db,
  80984. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  80985. void *pArg
  80986. ){
  80987. sqlite3_mutex_enter(db->mutex);
  80988. db->xAuth = xAuth;
  80989. db->pAuthArg = pArg;
  80990. sqlite3ExpirePreparedStatements(db);
  80991. sqlite3_mutex_leave(db->mutex);
  80992. return SQLITE_OK;
  80993. }
  80994. /*
  80995. ** Write an error message into pParse->zErrMsg that explains that the
  80996. ** user-supplied authorization function returned an illegal value.
  80997. */
  80998. static void sqliteAuthBadReturnCode(Parse *pParse){
  80999. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  81000. pParse->rc = SQLITE_ERROR;
  81001. }
  81002. /*
  81003. ** Invoke the authorization callback for permission to read column zCol from
  81004. ** table zTab in database zDb. This function assumes that an authorization
  81005. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  81006. **
  81007. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  81008. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  81009. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  81010. */
  81011. SQLITE_PRIVATE int sqlite3AuthReadCol(
  81012. Parse *pParse, /* The parser context */
  81013. const char *zTab, /* Table name */
  81014. const char *zCol, /* Column name */
  81015. int iDb /* Index of containing database. */
  81016. ){
  81017. sqlite3 *db = pParse->db; /* Database handle */
  81018. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  81019. int rc; /* Auth callback return code */
  81020. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
  81021. if( rc==SQLITE_DENY ){
  81022. if( db->nDb>2 || iDb!=0 ){
  81023. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  81024. }else{
  81025. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  81026. }
  81027. pParse->rc = SQLITE_AUTH;
  81028. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  81029. sqliteAuthBadReturnCode(pParse);
  81030. }
  81031. return rc;
  81032. }
  81033. /*
  81034. ** The pExpr should be a TK_COLUMN expression. The table referred to
  81035. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  81036. ** Check to see if it is OK to read this particular column.
  81037. **
  81038. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  81039. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  81040. ** then generate an error.
  81041. */
  81042. SQLITE_PRIVATE void sqlite3AuthRead(
  81043. Parse *pParse, /* The parser context */
  81044. Expr *pExpr, /* The expression to check authorization on */
  81045. Schema *pSchema, /* The schema of the expression */
  81046. SrcList *pTabList /* All table that pExpr might refer to */
  81047. ){
  81048. sqlite3 *db = pParse->db;
  81049. Table *pTab = 0; /* The table being read */
  81050. const char *zCol; /* Name of the column of the table */
  81051. int iSrc; /* Index in pTabList->a[] of table being read */
  81052. int iDb; /* The index of the database the expression refers to */
  81053. int iCol; /* Index of column in table */
  81054. if( db->xAuth==0 ) return;
  81055. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  81056. if( iDb<0 ){
  81057. /* An attempt to read a column out of a subquery or other
  81058. ** temporary table. */
  81059. return;
  81060. }
  81061. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  81062. if( pExpr->op==TK_TRIGGER ){
  81063. pTab = pParse->pTriggerTab;
  81064. }else{
  81065. assert( pTabList );
  81066. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  81067. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  81068. pTab = pTabList->a[iSrc].pTab;
  81069. break;
  81070. }
  81071. }
  81072. }
  81073. iCol = pExpr->iColumn;
  81074. if( NEVER(pTab==0) ) return;
  81075. if( iCol>=0 ){
  81076. assert( iCol<pTab->nCol );
  81077. zCol = pTab->aCol[iCol].zName;
  81078. }else if( pTab->iPKey>=0 ){
  81079. assert( pTab->iPKey<pTab->nCol );
  81080. zCol = pTab->aCol[pTab->iPKey].zName;
  81081. }else{
  81082. zCol = "ROWID";
  81083. }
  81084. assert( iDb>=0 && iDb<db->nDb );
  81085. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  81086. pExpr->op = TK_NULL;
  81087. }
  81088. }
  81089. /*
  81090. ** Do an authorization check using the code and arguments given. Return
  81091. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  81092. ** is returned, then the error count and error message in pParse are
  81093. ** modified appropriately.
  81094. */
  81095. SQLITE_PRIVATE int sqlite3AuthCheck(
  81096. Parse *pParse,
  81097. int code,
  81098. const char *zArg1,
  81099. const char *zArg2,
  81100. const char *zArg3
  81101. ){
  81102. sqlite3 *db = pParse->db;
  81103. int rc;
  81104. /* Don't do any authorization checks if the database is initialising
  81105. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  81106. */
  81107. if( db->init.busy || IN_DECLARE_VTAB ){
  81108. return SQLITE_OK;
  81109. }
  81110. if( db->xAuth==0 ){
  81111. return SQLITE_OK;
  81112. }
  81113. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  81114. if( rc==SQLITE_DENY ){
  81115. sqlite3ErrorMsg(pParse, "not authorized");
  81116. pParse->rc = SQLITE_AUTH;
  81117. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  81118. rc = SQLITE_DENY;
  81119. sqliteAuthBadReturnCode(pParse);
  81120. }
  81121. return rc;
  81122. }
  81123. /*
  81124. ** Push an authorization context. After this routine is called, the
  81125. ** zArg3 argument to authorization callbacks will be zContext until
  81126. ** popped. Or if pParse==0, this routine is a no-op.
  81127. */
  81128. SQLITE_PRIVATE void sqlite3AuthContextPush(
  81129. Parse *pParse,
  81130. AuthContext *pContext,
  81131. const char *zContext
  81132. ){
  81133. assert( pParse );
  81134. pContext->pParse = pParse;
  81135. pContext->zAuthContext = pParse->zAuthContext;
  81136. pParse->zAuthContext = zContext;
  81137. }
  81138. /*
  81139. ** Pop an authorization context that was previously pushed
  81140. ** by sqlite3AuthContextPush
  81141. */
  81142. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  81143. if( pContext->pParse ){
  81144. pContext->pParse->zAuthContext = pContext->zAuthContext;
  81145. pContext->pParse = 0;
  81146. }
  81147. }
  81148. #endif /* SQLITE_OMIT_AUTHORIZATION */
  81149. /************** End of auth.c ************************************************/
  81150. /************** Begin file build.c *******************************************/
  81151. /*
  81152. ** 2001 September 15
  81153. **
  81154. ** The author disclaims copyright to this source code. In place of
  81155. ** a legal notice, here is a blessing:
  81156. **
  81157. ** May you do good and not evil.
  81158. ** May you find forgiveness for yourself and forgive others.
  81159. ** May you share freely, never taking more than you give.
  81160. **
  81161. *************************************************************************
  81162. ** This file contains C code routines that are called by the SQLite parser
  81163. ** when syntax rules are reduced. The routines in this file handle the
  81164. ** following kinds of SQL syntax:
  81165. **
  81166. ** CREATE TABLE
  81167. ** DROP TABLE
  81168. ** CREATE INDEX
  81169. ** DROP INDEX
  81170. ** creating ID lists
  81171. ** BEGIN TRANSACTION
  81172. ** COMMIT
  81173. ** ROLLBACK
  81174. */
  81175. /*
  81176. ** This routine is called when a new SQL statement is beginning to
  81177. ** be parsed. Initialize the pParse structure as needed.
  81178. */
  81179. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  81180. pParse->explain = (u8)explainFlag;
  81181. pParse->nVar = 0;
  81182. }
  81183. #ifndef SQLITE_OMIT_SHARED_CACHE
  81184. /*
  81185. ** The TableLock structure is only used by the sqlite3TableLock() and
  81186. ** codeTableLocks() functions.
  81187. */
  81188. struct TableLock {
  81189. int iDb; /* The database containing the table to be locked */
  81190. int iTab; /* The root page of the table to be locked */
  81191. u8 isWriteLock; /* True for write lock. False for a read lock */
  81192. const char *zName; /* Name of the table */
  81193. };
  81194. /*
  81195. ** Record the fact that we want to lock a table at run-time.
  81196. **
  81197. ** The table to be locked has root page iTab and is found in database iDb.
  81198. ** A read or a write lock can be taken depending on isWritelock.
  81199. **
  81200. ** This routine just records the fact that the lock is desired. The
  81201. ** code to make the lock occur is generated by a later call to
  81202. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  81203. */
  81204. SQLITE_PRIVATE void sqlite3TableLock(
  81205. Parse *pParse, /* Parsing context */
  81206. int iDb, /* Index of the database containing the table to lock */
  81207. int iTab, /* Root page number of the table to be locked */
  81208. u8 isWriteLock, /* True for a write lock */
  81209. const char *zName /* Name of the table to be locked */
  81210. ){
  81211. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  81212. int i;
  81213. int nBytes;
  81214. TableLock *p;
  81215. assert( iDb>=0 );
  81216. for(i=0; i<pToplevel->nTableLock; i++){
  81217. p = &pToplevel->aTableLock[i];
  81218. if( p->iDb==iDb && p->iTab==iTab ){
  81219. p->isWriteLock = (p->isWriteLock || isWriteLock);
  81220. return;
  81221. }
  81222. }
  81223. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  81224. pToplevel->aTableLock =
  81225. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  81226. if( pToplevel->aTableLock ){
  81227. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  81228. p->iDb = iDb;
  81229. p->iTab = iTab;
  81230. p->isWriteLock = isWriteLock;
  81231. p->zName = zName;
  81232. }else{
  81233. pToplevel->nTableLock = 0;
  81234. pToplevel->db->mallocFailed = 1;
  81235. }
  81236. }
  81237. /*
  81238. ** Code an OP_TableLock instruction for each table locked by the
  81239. ** statement (configured by calls to sqlite3TableLock()).
  81240. */
  81241. static void codeTableLocks(Parse *pParse){
  81242. int i;
  81243. Vdbe *pVdbe;
  81244. pVdbe = sqlite3GetVdbe(pParse);
  81245. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  81246. for(i=0; i<pParse->nTableLock; i++){
  81247. TableLock *p = &pParse->aTableLock[i];
  81248. int p1 = p->iDb;
  81249. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  81250. p->zName, P4_STATIC);
  81251. }
  81252. }
  81253. #else
  81254. #define codeTableLocks(x)
  81255. #endif
  81256. /*
  81257. ** This routine is called after a single SQL statement has been
  81258. ** parsed and a VDBE program to execute that statement has been
  81259. ** prepared. This routine puts the finishing touches on the
  81260. ** VDBE program and resets the pParse structure for the next
  81261. ** parse.
  81262. **
  81263. ** Note that if an error occurred, it might be the case that
  81264. ** no VDBE code was generated.
  81265. */
  81266. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  81267. sqlite3 *db;
  81268. Vdbe *v;
  81269. assert( pParse->pToplevel==0 );
  81270. db = pParse->db;
  81271. if( db->mallocFailed ) return;
  81272. if( pParse->nested ) return;
  81273. if( pParse->nErr ) return;
  81274. /* Begin by generating some termination code at the end of the
  81275. ** vdbe program
  81276. */
  81277. v = sqlite3GetVdbe(pParse);
  81278. assert( !pParse->isMultiWrite
  81279. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  81280. if( v ){
  81281. sqlite3VdbeAddOp0(v, OP_Halt);
  81282. /* The cookie mask contains one bit for each database file open.
  81283. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  81284. ** set for each database that is used. Generate code to start a
  81285. ** transaction on each used database and to verify the schema cookie
  81286. ** on each used database.
  81287. */
  81288. if( pParse->cookieGoto>0 ){
  81289. yDbMask mask;
  81290. int iDb;
  81291. sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
  81292. for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
  81293. if( (mask & pParse->cookieMask)==0 ) continue;
  81294. sqlite3VdbeUsesBtree(v, iDb);
  81295. sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
  81296. if( db->init.busy==0 ){
  81297. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81298. sqlite3VdbeAddOp3(v, OP_VerifyCookie,
  81299. iDb, pParse->cookieValue[iDb],
  81300. db->aDb[iDb].pSchema->iGeneration);
  81301. }
  81302. }
  81303. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81304. {
  81305. int i;
  81306. for(i=0; i<pParse->nVtabLock; i++){
  81307. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  81308. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  81309. }
  81310. pParse->nVtabLock = 0;
  81311. }
  81312. #endif
  81313. /* Once all the cookies have been verified and transactions opened,
  81314. ** obtain the required table-locks. This is a no-op unless the
  81315. ** shared-cache feature is enabled.
  81316. */
  81317. codeTableLocks(pParse);
  81318. /* Initialize any AUTOINCREMENT data structures required.
  81319. */
  81320. sqlite3AutoincrementBegin(pParse);
  81321. /* Finally, jump back to the beginning of the executable code. */
  81322. sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
  81323. }
  81324. }
  81325. /* Get the VDBE program ready for execution
  81326. */
  81327. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  81328. #ifdef SQLITE_DEBUG
  81329. FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  81330. sqlite3VdbeTrace(v, trace);
  81331. #endif
  81332. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  81333. /* A minimum of one cursor is required if autoincrement is used
  81334. * See ticket [a696379c1f08866] */
  81335. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  81336. sqlite3VdbeMakeReady(v, pParse);
  81337. pParse->rc = SQLITE_DONE;
  81338. pParse->colNamesSet = 0;
  81339. }else{
  81340. pParse->rc = SQLITE_ERROR;
  81341. }
  81342. pParse->nTab = 0;
  81343. pParse->nMem = 0;
  81344. pParse->nSet = 0;
  81345. pParse->nVar = 0;
  81346. pParse->cookieMask = 0;
  81347. pParse->cookieGoto = 0;
  81348. }
  81349. /*
  81350. ** Run the parser and code generator recursively in order to generate
  81351. ** code for the SQL statement given onto the end of the pParse context
  81352. ** currently under construction. When the parser is run recursively
  81353. ** this way, the final OP_Halt is not appended and other initialization
  81354. ** and finalization steps are omitted because those are handling by the
  81355. ** outermost parser.
  81356. **
  81357. ** Not everything is nestable. This facility is designed to permit
  81358. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  81359. ** care if you decide to try to use this routine for some other purposes.
  81360. */
  81361. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  81362. va_list ap;
  81363. char *zSql;
  81364. char *zErrMsg = 0;
  81365. sqlite3 *db = pParse->db;
  81366. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  81367. char saveBuf[SAVE_SZ];
  81368. if( pParse->nErr ) return;
  81369. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  81370. va_start(ap, zFormat);
  81371. zSql = sqlite3VMPrintf(db, zFormat, ap);
  81372. va_end(ap);
  81373. if( zSql==0 ){
  81374. return; /* A malloc must have failed */
  81375. }
  81376. pParse->nested++;
  81377. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  81378. memset(&pParse->nVar, 0, SAVE_SZ);
  81379. sqlite3RunParser(pParse, zSql, &zErrMsg);
  81380. sqlite3DbFree(db, zErrMsg);
  81381. sqlite3DbFree(db, zSql);
  81382. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  81383. pParse->nested--;
  81384. }
  81385. /*
  81386. ** Locate the in-memory structure that describes a particular database
  81387. ** table given the name of that table and (optionally) the name of the
  81388. ** database containing the table. Return NULL if not found.
  81389. **
  81390. ** If zDatabase is 0, all databases are searched for the table and the
  81391. ** first matching table is returned. (No checking for duplicate table
  81392. ** names is done.) The search order is TEMP first, then MAIN, then any
  81393. ** auxiliary databases added using the ATTACH command.
  81394. **
  81395. ** See also sqlite3LocateTable().
  81396. */
  81397. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  81398. Table *p = 0;
  81399. int i;
  81400. int nName;
  81401. assert( zName!=0 );
  81402. nName = sqlite3Strlen30(zName);
  81403. /* All mutexes are required for schema access. Make sure we hold them. */
  81404. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  81405. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  81406. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  81407. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  81408. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  81409. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
  81410. if( p ) break;
  81411. }
  81412. return p;
  81413. }
  81414. /*
  81415. ** Locate the in-memory structure that describes a particular database
  81416. ** table given the name of that table and (optionally) the name of the
  81417. ** database containing the table. Return NULL if not found. Also leave an
  81418. ** error message in pParse->zErrMsg.
  81419. **
  81420. ** The difference between this routine and sqlite3FindTable() is that this
  81421. ** routine leaves an error message in pParse->zErrMsg where
  81422. ** sqlite3FindTable() does not.
  81423. */
  81424. SQLITE_PRIVATE Table *sqlite3LocateTable(
  81425. Parse *pParse, /* context in which to report errors */
  81426. int isView, /* True if looking for a VIEW rather than a TABLE */
  81427. const char *zName, /* Name of the table we are looking for */
  81428. const char *zDbase /* Name of the database. Might be NULL */
  81429. ){
  81430. Table *p;
  81431. /* Read the database schema. If an error occurs, leave an error message
  81432. ** and code in pParse and return NULL. */
  81433. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81434. return 0;
  81435. }
  81436. p = sqlite3FindTable(pParse->db, zName, zDbase);
  81437. if( p==0 ){
  81438. const char *zMsg = isView ? "no such view" : "no such table";
  81439. if( zDbase ){
  81440. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  81441. }else{
  81442. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  81443. }
  81444. pParse->checkSchema = 1;
  81445. }
  81446. return p;
  81447. }
  81448. /*
  81449. ** Locate the table identified by *p.
  81450. **
  81451. ** This is a wrapper around sqlite3LocateTable(). The difference between
  81452. ** sqlite3LocateTable() and this function is that this function restricts
  81453. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  81454. ** non-NULL if it is part of a view or trigger program definition. See
  81455. ** sqlite3FixSrcList() for details.
  81456. */
  81457. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  81458. Parse *pParse,
  81459. int isView,
  81460. struct SrcList_item *p
  81461. ){
  81462. const char *zDb;
  81463. assert( p->pSchema==0 || p->zDatabase==0 );
  81464. if( p->pSchema ){
  81465. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  81466. zDb = pParse->db->aDb[iDb].zName;
  81467. }else{
  81468. zDb = p->zDatabase;
  81469. }
  81470. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  81471. }
  81472. /*
  81473. ** Locate the in-memory structure that describes
  81474. ** a particular index given the name of that index
  81475. ** and the name of the database that contains the index.
  81476. ** Return NULL if not found.
  81477. **
  81478. ** If zDatabase is 0, all databases are searched for the
  81479. ** table and the first matching index is returned. (No checking
  81480. ** for duplicate index names is done.) The search order is
  81481. ** TEMP first, then MAIN, then any auxiliary databases added
  81482. ** using the ATTACH command.
  81483. */
  81484. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  81485. Index *p = 0;
  81486. int i;
  81487. int nName = sqlite3Strlen30(zName);
  81488. /* All mutexes are required for schema access. Make sure we hold them. */
  81489. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  81490. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  81491. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  81492. Schema *pSchema = db->aDb[j].pSchema;
  81493. assert( pSchema );
  81494. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  81495. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  81496. p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
  81497. if( p ) break;
  81498. }
  81499. return p;
  81500. }
  81501. /*
  81502. ** Reclaim the memory used by an index
  81503. */
  81504. static void freeIndex(sqlite3 *db, Index *p){
  81505. #ifndef SQLITE_OMIT_ANALYZE
  81506. sqlite3DeleteIndexSamples(db, p);
  81507. #endif
  81508. sqlite3ExprDelete(db, p->pPartIdxWhere);
  81509. sqlite3DbFree(db, p->zColAff);
  81510. sqlite3DbFree(db, p);
  81511. }
  81512. /*
  81513. ** For the index called zIdxName which is found in the database iDb,
  81514. ** unlike that index from its Table then remove the index from
  81515. ** the index hash table and free all memory structures associated
  81516. ** with the index.
  81517. */
  81518. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  81519. Index *pIndex;
  81520. int len;
  81521. Hash *pHash;
  81522. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81523. pHash = &db->aDb[iDb].pSchema->idxHash;
  81524. len = sqlite3Strlen30(zIdxName);
  81525. pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
  81526. if( ALWAYS(pIndex) ){
  81527. if( pIndex->pTable->pIndex==pIndex ){
  81528. pIndex->pTable->pIndex = pIndex->pNext;
  81529. }else{
  81530. Index *p;
  81531. /* Justification of ALWAYS(); The index must be on the list of
  81532. ** indices. */
  81533. p = pIndex->pTable->pIndex;
  81534. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  81535. if( ALWAYS(p && p->pNext==pIndex) ){
  81536. p->pNext = pIndex->pNext;
  81537. }
  81538. }
  81539. freeIndex(db, pIndex);
  81540. }
  81541. db->flags |= SQLITE_InternChanges;
  81542. }
  81543. /*
  81544. ** Look through the list of open database files in db->aDb[] and if
  81545. ** any have been closed, remove them from the list. Reallocate the
  81546. ** db->aDb[] structure to a smaller size, if possible.
  81547. **
  81548. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  81549. ** are never candidates for being collapsed.
  81550. */
  81551. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  81552. int i, j;
  81553. for(i=j=2; i<db->nDb; i++){
  81554. struct Db *pDb = &db->aDb[i];
  81555. if( pDb->pBt==0 ){
  81556. sqlite3DbFree(db, pDb->zName);
  81557. pDb->zName = 0;
  81558. continue;
  81559. }
  81560. if( j<i ){
  81561. db->aDb[j] = db->aDb[i];
  81562. }
  81563. j++;
  81564. }
  81565. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  81566. db->nDb = j;
  81567. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  81568. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  81569. sqlite3DbFree(db, db->aDb);
  81570. db->aDb = db->aDbStatic;
  81571. }
  81572. }
  81573. /*
  81574. ** Reset the schema for the database at index iDb. Also reset the
  81575. ** TEMP schema.
  81576. */
  81577. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  81578. Db *pDb;
  81579. assert( iDb<db->nDb );
  81580. /* Case 1: Reset the single schema identified by iDb */
  81581. pDb = &db->aDb[iDb];
  81582. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81583. assert( pDb->pSchema!=0 );
  81584. sqlite3SchemaClear(pDb->pSchema);
  81585. /* If any database other than TEMP is reset, then also reset TEMP
  81586. ** since TEMP might be holding triggers that reference tables in the
  81587. ** other database.
  81588. */
  81589. if( iDb!=1 ){
  81590. pDb = &db->aDb[1];
  81591. assert( pDb->pSchema!=0 );
  81592. sqlite3SchemaClear(pDb->pSchema);
  81593. }
  81594. return;
  81595. }
  81596. /*
  81597. ** Erase all schema information from all attached databases (including
  81598. ** "main" and "temp") for a single database connection.
  81599. */
  81600. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  81601. int i;
  81602. sqlite3BtreeEnterAll(db);
  81603. for(i=0; i<db->nDb; i++){
  81604. Db *pDb = &db->aDb[i];
  81605. if( pDb->pSchema ){
  81606. sqlite3SchemaClear(pDb->pSchema);
  81607. }
  81608. }
  81609. db->flags &= ~SQLITE_InternChanges;
  81610. sqlite3VtabUnlockList(db);
  81611. sqlite3BtreeLeaveAll(db);
  81612. sqlite3CollapseDatabaseArray(db);
  81613. }
  81614. /*
  81615. ** This routine is called when a commit occurs.
  81616. */
  81617. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  81618. db->flags &= ~SQLITE_InternChanges;
  81619. }
  81620. /*
  81621. ** Delete memory allocated for the column names of a table or view (the
  81622. ** Table.aCol[] array).
  81623. */
  81624. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  81625. int i;
  81626. Column *pCol;
  81627. assert( pTable!=0 );
  81628. if( (pCol = pTable->aCol)!=0 ){
  81629. for(i=0; i<pTable->nCol; i++, pCol++){
  81630. sqlite3DbFree(db, pCol->zName);
  81631. sqlite3ExprDelete(db, pCol->pDflt);
  81632. sqlite3DbFree(db, pCol->zDflt);
  81633. sqlite3DbFree(db, pCol->zType);
  81634. sqlite3DbFree(db, pCol->zColl);
  81635. }
  81636. sqlite3DbFree(db, pTable->aCol);
  81637. }
  81638. }
  81639. /*
  81640. ** Remove the memory data structures associated with the given
  81641. ** Table. No changes are made to disk by this routine.
  81642. **
  81643. ** This routine just deletes the data structure. It does not unlink
  81644. ** the table data structure from the hash table. But it does destroy
  81645. ** memory structures of the indices and foreign keys associated with
  81646. ** the table.
  81647. **
  81648. ** The db parameter is optional. It is needed if the Table object
  81649. ** contains lookaside memory. (Table objects in the schema do not use
  81650. ** lookaside memory, but some ephemeral Table objects do.) Or the
  81651. ** db parameter can be used with db->pnBytesFreed to measure the memory
  81652. ** used by the Table object.
  81653. */
  81654. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  81655. Index *pIndex, *pNext;
  81656. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  81657. assert( !pTable || pTable->nRef>0 );
  81658. /* Do not delete the table until the reference count reaches zero. */
  81659. if( !pTable ) return;
  81660. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  81661. /* Record the number of outstanding lookaside allocations in schema Tables
  81662. ** prior to doing any free() operations. Since schema Tables do not use
  81663. ** lookaside, this number should not change. */
  81664. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  81665. db->lookaside.nOut : 0 );
  81666. /* Delete all indices associated with this table. */
  81667. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  81668. pNext = pIndex->pNext;
  81669. assert( pIndex->pSchema==pTable->pSchema );
  81670. if( !db || db->pnBytesFreed==0 ){
  81671. char *zName = pIndex->zName;
  81672. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  81673. &pIndex->pSchema->idxHash, zName, sqlite3Strlen30(zName), 0
  81674. );
  81675. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  81676. assert( pOld==pIndex || pOld==0 );
  81677. }
  81678. freeIndex(db, pIndex);
  81679. }
  81680. /* Delete any foreign keys attached to this table. */
  81681. sqlite3FkDelete(db, pTable);
  81682. /* Delete the Table structure itself.
  81683. */
  81684. sqliteDeleteColumnNames(db, pTable);
  81685. sqlite3DbFree(db, pTable->zName);
  81686. sqlite3DbFree(db, pTable->zColAff);
  81687. sqlite3SelectDelete(db, pTable->pSelect);
  81688. #ifndef SQLITE_OMIT_CHECK
  81689. sqlite3ExprListDelete(db, pTable->pCheck);
  81690. #endif
  81691. #ifndef SQLITE_OMIT_VIRTUALTABLE
  81692. sqlite3VtabClear(db, pTable);
  81693. #endif
  81694. sqlite3DbFree(db, pTable);
  81695. /* Verify that no lookaside memory was used by schema tables */
  81696. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  81697. }
  81698. /*
  81699. ** Unlink the given table from the hash tables and the delete the
  81700. ** table structure with all its indices and foreign keys.
  81701. */
  81702. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  81703. Table *p;
  81704. Db *pDb;
  81705. assert( db!=0 );
  81706. assert( iDb>=0 && iDb<db->nDb );
  81707. assert( zTabName );
  81708. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81709. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  81710. pDb = &db->aDb[iDb];
  81711. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
  81712. sqlite3Strlen30(zTabName),0);
  81713. sqlite3DeleteTable(db, p);
  81714. db->flags |= SQLITE_InternChanges;
  81715. }
  81716. /*
  81717. ** Given a token, return a string that consists of the text of that
  81718. ** token. Space to hold the returned string
  81719. ** is obtained from sqliteMalloc() and must be freed by the calling
  81720. ** function.
  81721. **
  81722. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  81723. ** surround the body of the token are removed.
  81724. **
  81725. ** Tokens are often just pointers into the original SQL text and so
  81726. ** are not \000 terminated and are not persistent. The returned string
  81727. ** is \000 terminated and is persistent.
  81728. */
  81729. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  81730. char *zName;
  81731. if( pName ){
  81732. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  81733. sqlite3Dequote(zName);
  81734. }else{
  81735. zName = 0;
  81736. }
  81737. return zName;
  81738. }
  81739. /*
  81740. ** Open the sqlite_master table stored in database number iDb for
  81741. ** writing. The table is opened using cursor 0.
  81742. */
  81743. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  81744. Vdbe *v = sqlite3GetVdbe(p);
  81745. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  81746. sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
  81747. sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32); /* 5 column table */
  81748. if( p->nTab==0 ){
  81749. p->nTab = 1;
  81750. }
  81751. }
  81752. /*
  81753. ** Parameter zName points to a nul-terminated buffer containing the name
  81754. ** of a database ("main", "temp" or the name of an attached db). This
  81755. ** function returns the index of the named database in db->aDb[], or
  81756. ** -1 if the named db cannot be found.
  81757. */
  81758. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  81759. int i = -1; /* Database number */
  81760. if( zName ){
  81761. Db *pDb;
  81762. int n = sqlite3Strlen30(zName);
  81763. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  81764. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  81765. 0==sqlite3StrICmp(pDb->zName, zName) ){
  81766. break;
  81767. }
  81768. }
  81769. }
  81770. return i;
  81771. }
  81772. /*
  81773. ** The token *pName contains the name of a database (either "main" or
  81774. ** "temp" or the name of an attached db). This routine returns the
  81775. ** index of the named database in db->aDb[], or -1 if the named db
  81776. ** does not exist.
  81777. */
  81778. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  81779. int i; /* Database number */
  81780. char *zName; /* Name we are searching for */
  81781. zName = sqlite3NameFromToken(db, pName);
  81782. i = sqlite3FindDbName(db, zName);
  81783. sqlite3DbFree(db, zName);
  81784. return i;
  81785. }
  81786. /* The table or view or trigger name is passed to this routine via tokens
  81787. ** pName1 and pName2. If the table name was fully qualified, for example:
  81788. **
  81789. ** CREATE TABLE xxx.yyy (...);
  81790. **
  81791. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  81792. ** the table name is not fully qualified, i.e.:
  81793. **
  81794. ** CREATE TABLE yyy(...);
  81795. **
  81796. ** Then pName1 is set to "yyy" and pName2 is "".
  81797. **
  81798. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  81799. ** pName2) that stores the unqualified table name. The index of the
  81800. ** database "xxx" is returned.
  81801. */
  81802. SQLITE_PRIVATE int sqlite3TwoPartName(
  81803. Parse *pParse, /* Parsing and code generating context */
  81804. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  81805. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  81806. Token **pUnqual /* Write the unqualified object name here */
  81807. ){
  81808. int iDb; /* Database holding the object */
  81809. sqlite3 *db = pParse->db;
  81810. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  81811. if( db->init.busy ) {
  81812. sqlite3ErrorMsg(pParse, "corrupt database");
  81813. pParse->nErr++;
  81814. return -1;
  81815. }
  81816. *pUnqual = pName2;
  81817. iDb = sqlite3FindDb(db, pName1);
  81818. if( iDb<0 ){
  81819. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  81820. pParse->nErr++;
  81821. return -1;
  81822. }
  81823. }else{
  81824. assert( db->init.iDb==0 || db->init.busy );
  81825. iDb = db->init.iDb;
  81826. *pUnqual = pName1;
  81827. }
  81828. return iDb;
  81829. }
  81830. /*
  81831. ** This routine is used to check if the UTF-8 string zName is a legal
  81832. ** unqualified name for a new schema object (table, index, view or
  81833. ** trigger). All names are legal except those that begin with the string
  81834. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  81835. ** is reserved for internal use.
  81836. */
  81837. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  81838. if( !pParse->db->init.busy && pParse->nested==0
  81839. && (pParse->db->flags & SQLITE_WriteSchema)==0
  81840. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  81841. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  81842. return SQLITE_ERROR;
  81843. }
  81844. return SQLITE_OK;
  81845. }
  81846. /*
  81847. ** Begin constructing a new table representation in memory. This is
  81848. ** the first of several action routines that get called in response
  81849. ** to a CREATE TABLE statement. In particular, this routine is called
  81850. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  81851. ** flag is true if the table should be stored in the auxiliary database
  81852. ** file instead of in the main database file. This is normally the case
  81853. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  81854. ** CREATE and TABLE.
  81855. **
  81856. ** The new table record is initialized and put in pParse->pNewTable.
  81857. ** As more of the CREATE TABLE statement is parsed, additional action
  81858. ** routines will be called to add more information to this record.
  81859. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  81860. ** is called to complete the construction of the new table record.
  81861. */
  81862. SQLITE_PRIVATE void sqlite3StartTable(
  81863. Parse *pParse, /* Parser context */
  81864. Token *pName1, /* First part of the name of the table or view */
  81865. Token *pName2, /* Second part of the name of the table or view */
  81866. int isTemp, /* True if this is a TEMP table */
  81867. int isView, /* True if this is a VIEW */
  81868. int isVirtual, /* True if this is a VIRTUAL table */
  81869. int noErr /* Do nothing if table already exists */
  81870. ){
  81871. Table *pTable;
  81872. char *zName = 0; /* The name of the new table */
  81873. sqlite3 *db = pParse->db;
  81874. Vdbe *v;
  81875. int iDb; /* Database number to create the table in */
  81876. Token *pName; /* Unqualified name of the table to create */
  81877. /* The table or view name to create is passed to this routine via tokens
  81878. ** pName1 and pName2. If the table name was fully qualified, for example:
  81879. **
  81880. ** CREATE TABLE xxx.yyy (...);
  81881. **
  81882. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  81883. ** the table name is not fully qualified, i.e.:
  81884. **
  81885. ** CREATE TABLE yyy(...);
  81886. **
  81887. ** Then pName1 is set to "yyy" and pName2 is "".
  81888. **
  81889. ** The call below sets the pName pointer to point at the token (pName1 or
  81890. ** pName2) that stores the unqualified table name. The variable iDb is
  81891. ** set to the index of the database that the table or view is to be
  81892. ** created in.
  81893. */
  81894. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  81895. if( iDb<0 ) return;
  81896. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  81897. /* If creating a temp table, the name may not be qualified. Unless
  81898. ** the database name is "temp" anyway. */
  81899. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  81900. return;
  81901. }
  81902. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  81903. pParse->sNameToken = *pName;
  81904. zName = sqlite3NameFromToken(db, pName);
  81905. if( zName==0 ) return;
  81906. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  81907. goto begin_table_error;
  81908. }
  81909. if( db->init.iDb==1 ) isTemp = 1;
  81910. #ifndef SQLITE_OMIT_AUTHORIZATION
  81911. assert( (isTemp & 1)==isTemp );
  81912. {
  81913. int code;
  81914. char *zDb = db->aDb[iDb].zName;
  81915. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  81916. goto begin_table_error;
  81917. }
  81918. if( isView ){
  81919. if( !OMIT_TEMPDB && isTemp ){
  81920. code = SQLITE_CREATE_TEMP_VIEW;
  81921. }else{
  81922. code = SQLITE_CREATE_VIEW;
  81923. }
  81924. }else{
  81925. if( !OMIT_TEMPDB && isTemp ){
  81926. code = SQLITE_CREATE_TEMP_TABLE;
  81927. }else{
  81928. code = SQLITE_CREATE_TABLE;
  81929. }
  81930. }
  81931. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  81932. goto begin_table_error;
  81933. }
  81934. }
  81935. #endif
  81936. /* Make sure the new table name does not collide with an existing
  81937. ** index or table name in the same database. Issue an error message if
  81938. ** it does. The exception is if the statement being parsed was passed
  81939. ** to an sqlite3_declare_vtab() call. In that case only the column names
  81940. ** and types will be used, so there is no need to test for namespace
  81941. ** collisions.
  81942. */
  81943. if( !IN_DECLARE_VTAB ){
  81944. char *zDb = db->aDb[iDb].zName;
  81945. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81946. goto begin_table_error;
  81947. }
  81948. pTable = sqlite3FindTable(db, zName, zDb);
  81949. if( pTable ){
  81950. if( !noErr ){
  81951. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  81952. }else{
  81953. assert( !db->init.busy );
  81954. sqlite3CodeVerifySchema(pParse, iDb);
  81955. }
  81956. goto begin_table_error;
  81957. }
  81958. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  81959. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  81960. goto begin_table_error;
  81961. }
  81962. }
  81963. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  81964. if( pTable==0 ){
  81965. db->mallocFailed = 1;
  81966. pParse->rc = SQLITE_NOMEM;
  81967. pParse->nErr++;
  81968. goto begin_table_error;
  81969. }
  81970. pTable->zName = zName;
  81971. pTable->iPKey = -1;
  81972. pTable->pSchema = db->aDb[iDb].pSchema;
  81973. pTable->nRef = 1;
  81974. pTable->nRowEst = 1048576;
  81975. assert( pParse->pNewTable==0 );
  81976. pParse->pNewTable = pTable;
  81977. /* If this is the magic sqlite_sequence table used by autoincrement,
  81978. ** then record a pointer to this table in the main database structure
  81979. ** so that INSERT can find the table easily.
  81980. */
  81981. #ifndef SQLITE_OMIT_AUTOINCREMENT
  81982. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  81983. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81984. pTable->pSchema->pSeqTab = pTable;
  81985. }
  81986. #endif
  81987. /* Begin generating the code that will insert the table record into
  81988. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  81989. ** and allocate the record number for the table entry now. Before any
  81990. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  81991. ** indices to be created and the table record must come before the
  81992. ** indices. Hence, the record number for the table must be allocated
  81993. ** now.
  81994. */
  81995. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  81996. int j1;
  81997. int fileFormat;
  81998. int reg1, reg2, reg3;
  81999. sqlite3BeginWriteOperation(pParse, 0, iDb);
  82000. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82001. if( isVirtual ){
  82002. sqlite3VdbeAddOp0(v, OP_VBegin);
  82003. }
  82004. #endif
  82005. /* If the file format and encoding in the database have not been set,
  82006. ** set them now.
  82007. */
  82008. reg1 = pParse->regRowid = ++pParse->nMem;
  82009. reg2 = pParse->regRoot = ++pParse->nMem;
  82010. reg3 = ++pParse->nMem;
  82011. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  82012. sqlite3VdbeUsesBtree(v, iDb);
  82013. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
  82014. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  82015. 1 : SQLITE_MAX_FILE_FORMAT;
  82016. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  82017. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  82018. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  82019. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  82020. sqlite3VdbeJumpHere(v, j1);
  82021. /* This just creates a place-holder record in the sqlite_master table.
  82022. ** The record created does not contain anything yet. It will be replaced
  82023. ** by the real entry in code generated at sqlite3EndTable().
  82024. **
  82025. ** The rowid for the new entry is left in register pParse->regRowid.
  82026. ** The root page number of the new table is left in reg pParse->regRoot.
  82027. ** The rowid and root page number values are needed by the code that
  82028. ** sqlite3EndTable will generate.
  82029. */
  82030. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  82031. if( isView || isVirtual ){
  82032. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  82033. }else
  82034. #endif
  82035. {
  82036. sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  82037. }
  82038. sqlite3OpenMasterTable(pParse, iDb);
  82039. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  82040. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  82041. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  82042. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  82043. sqlite3VdbeAddOp0(v, OP_Close);
  82044. }
  82045. /* Normal (non-error) return. */
  82046. return;
  82047. /* If an error occurs, we jump here */
  82048. begin_table_error:
  82049. sqlite3DbFree(db, zName);
  82050. return;
  82051. }
  82052. /*
  82053. ** This macro is used to compare two strings in a case-insensitive manner.
  82054. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  82055. ** produces larger code.
  82056. **
  82057. ** WARNING: This macro is not compatible with the strcmp() family. It
  82058. ** returns true if the two strings are equal, otherwise false.
  82059. */
  82060. #define STRICMP(x, y) (\
  82061. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  82062. sqlite3UpperToLower[*(unsigned char *)(y)] \
  82063. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  82064. /*
  82065. ** Add a new column to the table currently being constructed.
  82066. **
  82067. ** The parser calls this routine once for each column declaration
  82068. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  82069. ** first to get things going. Then this routine is called for each
  82070. ** column.
  82071. */
  82072. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  82073. Table *p;
  82074. int i;
  82075. char *z;
  82076. Column *pCol;
  82077. sqlite3 *db = pParse->db;
  82078. if( (p = pParse->pNewTable)==0 ) return;
  82079. #if SQLITE_MAX_COLUMN
  82080. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  82081. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  82082. return;
  82083. }
  82084. #endif
  82085. z = sqlite3NameFromToken(db, pName);
  82086. if( z==0 ) return;
  82087. for(i=0; i<p->nCol; i++){
  82088. if( STRICMP(z, p->aCol[i].zName) ){
  82089. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  82090. sqlite3DbFree(db, z);
  82091. return;
  82092. }
  82093. }
  82094. if( (p->nCol & 0x7)==0 ){
  82095. Column *aNew;
  82096. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  82097. if( aNew==0 ){
  82098. sqlite3DbFree(db, z);
  82099. return;
  82100. }
  82101. p->aCol = aNew;
  82102. }
  82103. pCol = &p->aCol[p->nCol];
  82104. memset(pCol, 0, sizeof(p->aCol[0]));
  82105. pCol->zName = z;
  82106. /* If there is no type specified, columns have the default affinity
  82107. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  82108. ** be called next to set pCol->affinity correctly.
  82109. */
  82110. pCol->affinity = SQLITE_AFF_NONE;
  82111. pCol->szEst = 1;
  82112. p->nCol++;
  82113. }
  82114. /*
  82115. ** This routine is called by the parser while in the middle of
  82116. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  82117. ** been seen on a column. This routine sets the notNull flag on
  82118. ** the column currently under construction.
  82119. */
  82120. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  82121. Table *p;
  82122. p = pParse->pNewTable;
  82123. if( p==0 || NEVER(p->nCol<1) ) return;
  82124. p->aCol[p->nCol-1].notNull = (u8)onError;
  82125. }
  82126. /*
  82127. ** Scan the column type name zType (length nType) and return the
  82128. ** associated affinity type.
  82129. **
  82130. ** This routine does a case-independent search of zType for the
  82131. ** substrings in the following table. If one of the substrings is
  82132. ** found, the corresponding affinity is returned. If zType contains
  82133. ** more than one of the substrings, entries toward the top of
  82134. ** the table take priority. For example, if zType is 'BLOBINT',
  82135. ** SQLITE_AFF_INTEGER is returned.
  82136. **
  82137. ** Substring | Affinity
  82138. ** --------------------------------
  82139. ** 'INT' | SQLITE_AFF_INTEGER
  82140. ** 'CHAR' | SQLITE_AFF_TEXT
  82141. ** 'CLOB' | SQLITE_AFF_TEXT
  82142. ** 'TEXT' | SQLITE_AFF_TEXT
  82143. ** 'BLOB' | SQLITE_AFF_NONE
  82144. ** 'REAL' | SQLITE_AFF_REAL
  82145. ** 'FLOA' | SQLITE_AFF_REAL
  82146. ** 'DOUB' | SQLITE_AFF_REAL
  82147. **
  82148. ** If none of the substrings in the above table are found,
  82149. ** SQLITE_AFF_NUMERIC is returned.
  82150. */
  82151. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  82152. u32 h = 0;
  82153. char aff = SQLITE_AFF_NUMERIC;
  82154. const char *zChar = 0;
  82155. if( zIn==0 ) return aff;
  82156. while( zIn[0] ){
  82157. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  82158. zIn++;
  82159. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  82160. aff = SQLITE_AFF_TEXT;
  82161. zChar = zIn;
  82162. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  82163. aff = SQLITE_AFF_TEXT;
  82164. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  82165. aff = SQLITE_AFF_TEXT;
  82166. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  82167. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  82168. aff = SQLITE_AFF_NONE;
  82169. if( zIn[0]=='(' ) zChar = zIn;
  82170. #ifndef SQLITE_OMIT_FLOATING_POINT
  82171. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  82172. && aff==SQLITE_AFF_NUMERIC ){
  82173. aff = SQLITE_AFF_REAL;
  82174. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  82175. && aff==SQLITE_AFF_NUMERIC ){
  82176. aff = SQLITE_AFF_REAL;
  82177. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  82178. && aff==SQLITE_AFF_NUMERIC ){
  82179. aff = SQLITE_AFF_REAL;
  82180. #endif
  82181. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  82182. aff = SQLITE_AFF_INTEGER;
  82183. break;
  82184. }
  82185. }
  82186. /* If pszEst is not NULL, store an estimate of the field size. The
  82187. ** estimate is scaled so that the size of an integer is 1. */
  82188. if( pszEst ){
  82189. *pszEst = 1; /* default size is approx 4 bytes */
  82190. if( aff<=SQLITE_AFF_NONE ){
  82191. if( zChar ){
  82192. while( zChar[0] ){
  82193. if( sqlite3Isdigit(zChar[0]) ){
  82194. int v = 0;
  82195. sqlite3GetInt32(zChar, &v);
  82196. v = v/4 + 1;
  82197. if( v>255 ) v = 255;
  82198. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  82199. break;
  82200. }
  82201. zChar++;
  82202. }
  82203. }else{
  82204. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  82205. }
  82206. }
  82207. }
  82208. return aff;
  82209. }
  82210. /*
  82211. ** This routine is called by the parser while in the middle of
  82212. ** parsing a CREATE TABLE statement. The pFirst token is the first
  82213. ** token in the sequence of tokens that describe the type of the
  82214. ** column currently under construction. pLast is the last token
  82215. ** in the sequence. Use this information to construct a string
  82216. ** that contains the typename of the column and store that string
  82217. ** in zType.
  82218. */
  82219. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  82220. Table *p;
  82221. Column *pCol;
  82222. p = pParse->pNewTable;
  82223. if( p==0 || NEVER(p->nCol<1) ) return;
  82224. pCol = &p->aCol[p->nCol-1];
  82225. assert( pCol->zType==0 );
  82226. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  82227. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  82228. }
  82229. /*
  82230. ** The expression is the default value for the most recently added column
  82231. ** of the table currently under construction.
  82232. **
  82233. ** Default value expressions must be constant. Raise an exception if this
  82234. ** is not the case.
  82235. **
  82236. ** This routine is called by the parser while in the middle of
  82237. ** parsing a CREATE TABLE statement.
  82238. */
  82239. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  82240. Table *p;
  82241. Column *pCol;
  82242. sqlite3 *db = pParse->db;
  82243. p = pParse->pNewTable;
  82244. if( p!=0 ){
  82245. pCol = &(p->aCol[p->nCol-1]);
  82246. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
  82247. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  82248. pCol->zName);
  82249. }else{
  82250. /* A copy of pExpr is used instead of the original, as pExpr contains
  82251. ** tokens that point to volatile memory. The 'span' of the expression
  82252. ** is required by pragma table_info.
  82253. */
  82254. sqlite3ExprDelete(db, pCol->pDflt);
  82255. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  82256. sqlite3DbFree(db, pCol->zDflt);
  82257. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  82258. (int)(pSpan->zEnd - pSpan->zStart));
  82259. }
  82260. }
  82261. sqlite3ExprDelete(db, pSpan->pExpr);
  82262. }
  82263. /*
  82264. ** Designate the PRIMARY KEY for the table. pList is a list of names
  82265. ** of columns that form the primary key. If pList is NULL, then the
  82266. ** most recently added column of the table is the primary key.
  82267. **
  82268. ** A table can have at most one primary key. If the table already has
  82269. ** a primary key (and this is the second primary key) then create an
  82270. ** error.
  82271. **
  82272. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  82273. ** then we will try to use that column as the rowid. Set the Table.iPKey
  82274. ** field of the table under construction to be the index of the
  82275. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  82276. ** no INTEGER PRIMARY KEY.
  82277. **
  82278. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  82279. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  82280. */
  82281. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  82282. Parse *pParse, /* Parsing context */
  82283. ExprList *pList, /* List of field names to be indexed */
  82284. int onError, /* What to do with a uniqueness conflict */
  82285. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  82286. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  82287. ){
  82288. Table *pTab = pParse->pNewTable;
  82289. char *zType = 0;
  82290. int iCol = -1, i;
  82291. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  82292. if( pTab->tabFlags & TF_HasPrimaryKey ){
  82293. sqlite3ErrorMsg(pParse,
  82294. "table \"%s\" has more than one primary key", pTab->zName);
  82295. goto primary_key_exit;
  82296. }
  82297. pTab->tabFlags |= TF_HasPrimaryKey;
  82298. if( pList==0 ){
  82299. iCol = pTab->nCol - 1;
  82300. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  82301. }else{
  82302. for(i=0; i<pList->nExpr; i++){
  82303. for(iCol=0; iCol<pTab->nCol; iCol++){
  82304. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  82305. break;
  82306. }
  82307. }
  82308. if( iCol<pTab->nCol ){
  82309. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  82310. }
  82311. }
  82312. if( pList->nExpr>1 ) iCol = -1;
  82313. }
  82314. if( iCol>=0 && iCol<pTab->nCol ){
  82315. zType = pTab->aCol[iCol].zType;
  82316. }
  82317. if( zType && sqlite3StrICmp(zType, "INTEGER")==0
  82318. && sortOrder==SQLITE_SO_ASC ){
  82319. pTab->iPKey = iCol;
  82320. pTab->keyConf = (u8)onError;
  82321. assert( autoInc==0 || autoInc==1 );
  82322. pTab->tabFlags |= autoInc*TF_Autoincrement;
  82323. }else if( autoInc ){
  82324. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82325. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  82326. "INTEGER PRIMARY KEY");
  82327. #endif
  82328. }else{
  82329. Index *p;
  82330. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  82331. 0, sortOrder, 0);
  82332. if( p ){
  82333. p->autoIndex = 2;
  82334. }
  82335. pList = 0;
  82336. }
  82337. primary_key_exit:
  82338. sqlite3ExprListDelete(pParse->db, pList);
  82339. return;
  82340. }
  82341. /*
  82342. ** Add a new CHECK constraint to the table currently under construction.
  82343. */
  82344. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  82345. Parse *pParse, /* Parsing context */
  82346. Expr *pCheckExpr /* The check expression */
  82347. ){
  82348. #ifndef SQLITE_OMIT_CHECK
  82349. Table *pTab = pParse->pNewTable;
  82350. if( pTab && !IN_DECLARE_VTAB ){
  82351. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  82352. if( pParse->constraintName.n ){
  82353. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  82354. }
  82355. }else
  82356. #endif
  82357. {
  82358. sqlite3ExprDelete(pParse->db, pCheckExpr);
  82359. }
  82360. }
  82361. /*
  82362. ** Set the collation function of the most recently parsed table column
  82363. ** to the CollSeq given.
  82364. */
  82365. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  82366. Table *p;
  82367. int i;
  82368. char *zColl; /* Dequoted name of collation sequence */
  82369. sqlite3 *db;
  82370. if( (p = pParse->pNewTable)==0 ) return;
  82371. i = p->nCol-1;
  82372. db = pParse->db;
  82373. zColl = sqlite3NameFromToken(db, pToken);
  82374. if( !zColl ) return;
  82375. if( sqlite3LocateCollSeq(pParse, zColl) ){
  82376. Index *pIdx;
  82377. sqlite3DbFree(db, p->aCol[i].zColl);
  82378. p->aCol[i].zColl = zColl;
  82379. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  82380. ** then an index may have been created on this column before the
  82381. ** collation type was added. Correct this if it is the case.
  82382. */
  82383. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  82384. assert( pIdx->nColumn==1 );
  82385. if( pIdx->aiColumn[0]==i ){
  82386. pIdx->azColl[0] = p->aCol[i].zColl;
  82387. }
  82388. }
  82389. }else{
  82390. sqlite3DbFree(db, zColl);
  82391. }
  82392. }
  82393. /*
  82394. ** This function returns the collation sequence for database native text
  82395. ** encoding identified by the string zName, length nName.
  82396. **
  82397. ** If the requested collation sequence is not available, or not available
  82398. ** in the database native encoding, the collation factory is invoked to
  82399. ** request it. If the collation factory does not supply such a sequence,
  82400. ** and the sequence is available in another text encoding, then that is
  82401. ** returned instead.
  82402. **
  82403. ** If no versions of the requested collations sequence are available, or
  82404. ** another error occurs, NULL is returned and an error message written into
  82405. ** pParse.
  82406. **
  82407. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  82408. ** invokes the collation factory if the named collation cannot be found
  82409. ** and generates an error message.
  82410. **
  82411. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  82412. */
  82413. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  82414. sqlite3 *db = pParse->db;
  82415. u8 enc = ENC(db);
  82416. u8 initbusy = db->init.busy;
  82417. CollSeq *pColl;
  82418. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  82419. if( !initbusy && (!pColl || !pColl->xCmp) ){
  82420. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  82421. }
  82422. return pColl;
  82423. }
  82424. /*
  82425. ** Generate code that will increment the schema cookie.
  82426. **
  82427. ** The schema cookie is used to determine when the schema for the
  82428. ** database changes. After each schema change, the cookie value
  82429. ** changes. When a process first reads the schema it records the
  82430. ** cookie. Thereafter, whenever it goes to access the database,
  82431. ** it checks the cookie to make sure the schema has not changed
  82432. ** since it was last read.
  82433. **
  82434. ** This plan is not completely bullet-proof. It is possible for
  82435. ** the schema to change multiple times and for the cookie to be
  82436. ** set back to prior value. But schema changes are infrequent
  82437. ** and the probability of hitting the same cookie value is only
  82438. ** 1 chance in 2^32. So we're safe enough.
  82439. */
  82440. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  82441. int r1 = sqlite3GetTempReg(pParse);
  82442. sqlite3 *db = pParse->db;
  82443. Vdbe *v = pParse->pVdbe;
  82444. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82445. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  82446. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  82447. sqlite3ReleaseTempReg(pParse, r1);
  82448. }
  82449. /*
  82450. ** Measure the number of characters needed to output the given
  82451. ** identifier. The number returned includes any quotes used
  82452. ** but does not include the null terminator.
  82453. **
  82454. ** The estimate is conservative. It might be larger that what is
  82455. ** really needed.
  82456. */
  82457. static int identLength(const char *z){
  82458. int n;
  82459. for(n=0; *z; n++, z++){
  82460. if( *z=='"' ){ n++; }
  82461. }
  82462. return n + 2;
  82463. }
  82464. /*
  82465. ** The first parameter is a pointer to an output buffer. The second
  82466. ** parameter is a pointer to an integer that contains the offset at
  82467. ** which to write into the output buffer. This function copies the
  82468. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  82469. ** to the specified offset in the buffer and updates *pIdx to refer
  82470. ** to the first byte after the last byte written before returning.
  82471. **
  82472. ** If the string zSignedIdent consists entirely of alpha-numeric
  82473. ** characters, does not begin with a digit and is not an SQL keyword,
  82474. ** then it is copied to the output buffer exactly as it is. Otherwise,
  82475. ** it is quoted using double-quotes.
  82476. */
  82477. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  82478. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  82479. int i, j, needQuote;
  82480. i = *pIdx;
  82481. for(j=0; zIdent[j]; j++){
  82482. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  82483. }
  82484. needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
  82485. if( !needQuote ){
  82486. needQuote = zIdent[j];
  82487. }
  82488. if( needQuote ) z[i++] = '"';
  82489. for(j=0; zIdent[j]; j++){
  82490. z[i++] = zIdent[j];
  82491. if( zIdent[j]=='"' ) z[i++] = '"';
  82492. }
  82493. if( needQuote ) z[i++] = '"';
  82494. z[i] = 0;
  82495. *pIdx = i;
  82496. }
  82497. /*
  82498. ** Generate a CREATE TABLE statement appropriate for the given
  82499. ** table. Memory to hold the text of the statement is obtained
  82500. ** from sqliteMalloc() and must be freed by the calling function.
  82501. */
  82502. static char *createTableStmt(sqlite3 *db, Table *p){
  82503. int i, k, n;
  82504. char *zStmt;
  82505. char *zSep, *zSep2, *zEnd;
  82506. Column *pCol;
  82507. n = 0;
  82508. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  82509. n += identLength(pCol->zName) + 5;
  82510. }
  82511. n += identLength(p->zName);
  82512. if( n<50 ){
  82513. zSep = "";
  82514. zSep2 = ",";
  82515. zEnd = ")";
  82516. }else{
  82517. zSep = "\n ";
  82518. zSep2 = ",\n ";
  82519. zEnd = "\n)";
  82520. }
  82521. n += 35 + 6*p->nCol;
  82522. zStmt = sqlite3DbMallocRaw(0, n);
  82523. if( zStmt==0 ){
  82524. db->mallocFailed = 1;
  82525. return 0;
  82526. }
  82527. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  82528. k = sqlite3Strlen30(zStmt);
  82529. identPut(zStmt, &k, p->zName);
  82530. zStmt[k++] = '(';
  82531. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  82532. static const char * const azType[] = {
  82533. /* SQLITE_AFF_TEXT */ " TEXT",
  82534. /* SQLITE_AFF_NONE */ "",
  82535. /* SQLITE_AFF_NUMERIC */ " NUM",
  82536. /* SQLITE_AFF_INTEGER */ " INT",
  82537. /* SQLITE_AFF_REAL */ " REAL"
  82538. };
  82539. int len;
  82540. const char *zType;
  82541. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  82542. k += sqlite3Strlen30(&zStmt[k]);
  82543. zSep = zSep2;
  82544. identPut(zStmt, &k, pCol->zName);
  82545. assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
  82546. assert( pCol->affinity-SQLITE_AFF_TEXT < ArraySize(azType) );
  82547. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  82548. testcase( pCol->affinity==SQLITE_AFF_NONE );
  82549. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  82550. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  82551. testcase( pCol->affinity==SQLITE_AFF_REAL );
  82552. zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
  82553. len = sqlite3Strlen30(zType);
  82554. assert( pCol->affinity==SQLITE_AFF_NONE
  82555. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  82556. memcpy(&zStmt[k], zType, len);
  82557. k += len;
  82558. assert( k<=n );
  82559. }
  82560. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  82561. return zStmt;
  82562. }
  82563. /*
  82564. ** Estimate the total row width for a table.
  82565. */
  82566. static void estimateTableWidth(Table *pTab){
  82567. unsigned wTable = 0;
  82568. const Column *pTabCol;
  82569. int i;
  82570. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  82571. wTable += pTabCol->szEst;
  82572. }
  82573. if( pTab->iPKey<0 ) wTable++;
  82574. pTab->szTabRow = sqlite3LogEst(wTable*4);
  82575. }
  82576. /*
  82577. ** Estimate the average size of a row for an index.
  82578. */
  82579. static void estimateIndexWidth(Index *pIdx){
  82580. unsigned wIndex = 1;
  82581. int i;
  82582. const Column *aCol = pIdx->pTable->aCol;
  82583. for(i=0; i<pIdx->nColumn; i++){
  82584. assert( pIdx->aiColumn[i]>=0 && pIdx->aiColumn[i]<pIdx->pTable->nCol );
  82585. wIndex += aCol[pIdx->aiColumn[i]].szEst;
  82586. }
  82587. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  82588. }
  82589. /*
  82590. ** This routine is called to report the final ")" that terminates
  82591. ** a CREATE TABLE statement.
  82592. **
  82593. ** The table structure that other action routines have been building
  82594. ** is added to the internal hash tables, assuming no errors have
  82595. ** occurred.
  82596. **
  82597. ** An entry for the table is made in the master table on disk, unless
  82598. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  82599. ** it means we are reading the sqlite_master table because we just
  82600. ** connected to the database or because the sqlite_master table has
  82601. ** recently changed, so the entry for this table already exists in
  82602. ** the sqlite_master table. We do not want to create it again.
  82603. **
  82604. ** If the pSelect argument is not NULL, it means that this routine
  82605. ** was called to create a table generated from a
  82606. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  82607. ** the new table will match the result set of the SELECT.
  82608. */
  82609. SQLITE_PRIVATE void sqlite3EndTable(
  82610. Parse *pParse, /* Parse context */
  82611. Token *pCons, /* The ',' token after the last column defn. */
  82612. Token *pEnd, /* The final ')' token in the CREATE TABLE */
  82613. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  82614. ){
  82615. Table *p; /* The new table */
  82616. sqlite3 *db = pParse->db; /* The database connection */
  82617. int iDb; /* Database in which the table lives */
  82618. Index *pIdx; /* An implied index of the table */
  82619. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  82620. return;
  82621. }
  82622. p = pParse->pNewTable;
  82623. if( p==0 ) return;
  82624. assert( !db->init.busy || !pSelect );
  82625. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  82626. #ifndef SQLITE_OMIT_CHECK
  82627. /* Resolve names in all CHECK constraint expressions.
  82628. */
  82629. if( p->pCheck ){
  82630. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  82631. }
  82632. #endif /* !defined(SQLITE_OMIT_CHECK) */
  82633. /* Estimate the average row size for the table and for all implied indices */
  82634. estimateTableWidth(p);
  82635. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  82636. estimateIndexWidth(pIdx);
  82637. }
  82638. /* If the db->init.busy is 1 it means we are reading the SQL off the
  82639. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  82640. ** So do not write to the disk again. Extract the root page number
  82641. ** for the table from the db->init.newTnum field. (The page number
  82642. ** should have been put there by the sqliteOpenCb routine.)
  82643. */
  82644. if( db->init.busy ){
  82645. p->tnum = db->init.newTnum;
  82646. }
  82647. /* If not initializing, then create a record for the new table
  82648. ** in the SQLITE_MASTER table of the database.
  82649. **
  82650. ** If this is a TEMPORARY table, write the entry into the auxiliary
  82651. ** file instead of into the main database file.
  82652. */
  82653. if( !db->init.busy ){
  82654. int n;
  82655. Vdbe *v;
  82656. char *zType; /* "view" or "table" */
  82657. char *zType2; /* "VIEW" or "TABLE" */
  82658. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  82659. v = sqlite3GetVdbe(pParse);
  82660. if( NEVER(v==0) ) return;
  82661. sqlite3VdbeAddOp1(v, OP_Close, 0);
  82662. /*
  82663. ** Initialize zType for the new view or table.
  82664. */
  82665. if( p->pSelect==0 ){
  82666. /* A regular table */
  82667. zType = "table";
  82668. zType2 = "TABLE";
  82669. #ifndef SQLITE_OMIT_VIEW
  82670. }else{
  82671. /* A view */
  82672. zType = "view";
  82673. zType2 = "VIEW";
  82674. #endif
  82675. }
  82676. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  82677. ** statement to populate the new table. The root-page number for the
  82678. ** new table is in register pParse->regRoot.
  82679. **
  82680. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  82681. ** suitable state to query for the column names and types to be used
  82682. ** by the new table.
  82683. **
  82684. ** A shared-cache write-lock is not required to write to the new table,
  82685. ** as a schema-lock must have already been obtained to create it. Since
  82686. ** a schema-lock excludes all other database users, the write-lock would
  82687. ** be redundant.
  82688. */
  82689. if( pSelect ){
  82690. SelectDest dest;
  82691. Table *pSelTab;
  82692. assert(pParse->nTab==1);
  82693. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  82694. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  82695. pParse->nTab = 2;
  82696. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  82697. sqlite3Select(pParse, pSelect, &dest);
  82698. sqlite3VdbeAddOp1(v, OP_Close, 1);
  82699. if( pParse->nErr==0 ){
  82700. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  82701. if( pSelTab==0 ) return;
  82702. assert( p->aCol==0 );
  82703. p->nCol = pSelTab->nCol;
  82704. p->aCol = pSelTab->aCol;
  82705. pSelTab->nCol = 0;
  82706. pSelTab->aCol = 0;
  82707. sqlite3DeleteTable(db, pSelTab);
  82708. }
  82709. }
  82710. /* Compute the complete text of the CREATE statement */
  82711. if( pSelect ){
  82712. zStmt = createTableStmt(db, p);
  82713. }else{
  82714. n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
  82715. zStmt = sqlite3MPrintf(db,
  82716. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  82717. );
  82718. }
  82719. /* A slot for the record has already been allocated in the
  82720. ** SQLITE_MASTER table. We just need to update that slot with all
  82721. ** the information we've collected.
  82722. */
  82723. sqlite3NestedParse(pParse,
  82724. "UPDATE %Q.%s "
  82725. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  82726. "WHERE rowid=#%d",
  82727. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  82728. zType,
  82729. p->zName,
  82730. p->zName,
  82731. pParse->regRoot,
  82732. zStmt,
  82733. pParse->regRowid
  82734. );
  82735. sqlite3DbFree(db, zStmt);
  82736. sqlite3ChangeCookie(pParse, iDb);
  82737. #ifndef SQLITE_OMIT_AUTOINCREMENT
  82738. /* Check to see if we need to create an sqlite_sequence table for
  82739. ** keeping track of autoincrement keys.
  82740. */
  82741. if( p->tabFlags & TF_Autoincrement ){
  82742. Db *pDb = &db->aDb[iDb];
  82743. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82744. if( pDb->pSchema->pSeqTab==0 ){
  82745. sqlite3NestedParse(pParse,
  82746. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  82747. pDb->zName
  82748. );
  82749. }
  82750. }
  82751. #endif
  82752. /* Reparse everything to update our internal data structures */
  82753. sqlite3VdbeAddParseSchemaOp(v, iDb,
  82754. sqlite3MPrintf(db, "tbl_name='%q'", p->zName));
  82755. }
  82756. /* Add the table to the in-memory representation of the database.
  82757. */
  82758. if( db->init.busy ){
  82759. Table *pOld;
  82760. Schema *pSchema = p->pSchema;
  82761. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82762. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
  82763. sqlite3Strlen30(p->zName),p);
  82764. if( pOld ){
  82765. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  82766. db->mallocFailed = 1;
  82767. return;
  82768. }
  82769. pParse->pNewTable = 0;
  82770. db->flags |= SQLITE_InternChanges;
  82771. #ifndef SQLITE_OMIT_ALTERTABLE
  82772. if( !p->pSelect ){
  82773. const char *zName = (const char *)pParse->sNameToken.z;
  82774. int nName;
  82775. assert( !pSelect && pCons && pEnd );
  82776. if( pCons->z==0 ){
  82777. pCons = pEnd;
  82778. }
  82779. nName = (int)((const char *)pCons->z - zName);
  82780. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  82781. }
  82782. #endif
  82783. }
  82784. }
  82785. #ifndef SQLITE_OMIT_VIEW
  82786. /*
  82787. ** The parser calls this routine in order to create a new VIEW
  82788. */
  82789. SQLITE_PRIVATE void sqlite3CreateView(
  82790. Parse *pParse, /* The parsing context */
  82791. Token *pBegin, /* The CREATE token that begins the statement */
  82792. Token *pName1, /* The token that holds the name of the view */
  82793. Token *pName2, /* The token that holds the name of the view */
  82794. Select *pSelect, /* A SELECT statement that will become the new view */
  82795. int isTemp, /* TRUE for a TEMPORARY view */
  82796. int noErr /* Suppress error messages if VIEW already exists */
  82797. ){
  82798. Table *p;
  82799. int n;
  82800. const char *z;
  82801. Token sEnd;
  82802. DbFixer sFix;
  82803. Token *pName = 0;
  82804. int iDb;
  82805. sqlite3 *db = pParse->db;
  82806. if( pParse->nVar>0 ){
  82807. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  82808. sqlite3SelectDelete(db, pSelect);
  82809. return;
  82810. }
  82811. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  82812. p = pParse->pNewTable;
  82813. if( p==0 || pParse->nErr ){
  82814. sqlite3SelectDelete(db, pSelect);
  82815. return;
  82816. }
  82817. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  82818. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  82819. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  82820. if( sqlite3FixSelect(&sFix, pSelect) ){
  82821. sqlite3SelectDelete(db, pSelect);
  82822. return;
  82823. }
  82824. /* Make a copy of the entire SELECT statement that defines the view.
  82825. ** This will force all the Expr.token.z values to be dynamically
  82826. ** allocated rather than point to the input string - which means that
  82827. ** they will persist after the current sqlite3_exec() call returns.
  82828. */
  82829. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  82830. sqlite3SelectDelete(db, pSelect);
  82831. if( db->mallocFailed ){
  82832. return;
  82833. }
  82834. if( !db->init.busy ){
  82835. sqlite3ViewGetColumnNames(pParse, p);
  82836. }
  82837. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  82838. ** the end.
  82839. */
  82840. sEnd = pParse->sLastToken;
  82841. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  82842. sEnd.z += sEnd.n;
  82843. }
  82844. sEnd.n = 0;
  82845. n = (int)(sEnd.z - pBegin->z);
  82846. z = pBegin->z;
  82847. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  82848. sEnd.z = &z[n-1];
  82849. sEnd.n = 1;
  82850. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  82851. sqlite3EndTable(pParse, 0, &sEnd, 0);
  82852. return;
  82853. }
  82854. #endif /* SQLITE_OMIT_VIEW */
  82855. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  82856. /*
  82857. ** The Table structure pTable is really a VIEW. Fill in the names of
  82858. ** the columns of the view in the pTable structure. Return the number
  82859. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  82860. */
  82861. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  82862. Table *pSelTab; /* A fake table from which we get the result set */
  82863. Select *pSel; /* Copy of the SELECT that implements the view */
  82864. int nErr = 0; /* Number of errors encountered */
  82865. int n; /* Temporarily holds the number of cursors assigned */
  82866. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  82867. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  82868. assert( pTable );
  82869. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82870. if( sqlite3VtabCallConnect(pParse, pTable) ){
  82871. return SQLITE_ERROR;
  82872. }
  82873. if( IsVirtual(pTable) ) return 0;
  82874. #endif
  82875. #ifndef SQLITE_OMIT_VIEW
  82876. /* A positive nCol means the columns names for this view are
  82877. ** already known.
  82878. */
  82879. if( pTable->nCol>0 ) return 0;
  82880. /* A negative nCol is a special marker meaning that we are currently
  82881. ** trying to compute the column names. If we enter this routine with
  82882. ** a negative nCol, it means two or more views form a loop, like this:
  82883. **
  82884. ** CREATE VIEW one AS SELECT * FROM two;
  82885. ** CREATE VIEW two AS SELECT * FROM one;
  82886. **
  82887. ** Actually, the error above is now caught prior to reaching this point.
  82888. ** But the following test is still important as it does come up
  82889. ** in the following:
  82890. **
  82891. ** CREATE TABLE main.ex1(a);
  82892. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  82893. ** SELECT * FROM temp.ex1;
  82894. */
  82895. if( pTable->nCol<0 ){
  82896. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  82897. return 1;
  82898. }
  82899. assert( pTable->nCol>=0 );
  82900. /* If we get this far, it means we need to compute the table names.
  82901. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  82902. ** "*" elements in the results set of the view and will assign cursors
  82903. ** to the elements of the FROM clause. But we do not want these changes
  82904. ** to be permanent. So the computation is done on a copy of the SELECT
  82905. ** statement that defines the view.
  82906. */
  82907. assert( pTable->pSelect );
  82908. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  82909. if( pSel ){
  82910. u8 enableLookaside = db->lookaside.bEnabled;
  82911. n = pParse->nTab;
  82912. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  82913. pTable->nCol = -1;
  82914. db->lookaside.bEnabled = 0;
  82915. #ifndef SQLITE_OMIT_AUTHORIZATION
  82916. xAuth = db->xAuth;
  82917. db->xAuth = 0;
  82918. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  82919. db->xAuth = xAuth;
  82920. #else
  82921. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  82922. #endif
  82923. db->lookaside.bEnabled = enableLookaside;
  82924. pParse->nTab = n;
  82925. if( pSelTab ){
  82926. assert( pTable->aCol==0 );
  82927. pTable->nCol = pSelTab->nCol;
  82928. pTable->aCol = pSelTab->aCol;
  82929. pSelTab->nCol = 0;
  82930. pSelTab->aCol = 0;
  82931. sqlite3DeleteTable(db, pSelTab);
  82932. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  82933. pTable->pSchema->flags |= DB_UnresetViews;
  82934. }else{
  82935. pTable->nCol = 0;
  82936. nErr++;
  82937. }
  82938. sqlite3SelectDelete(db, pSel);
  82939. } else {
  82940. nErr++;
  82941. }
  82942. #endif /* SQLITE_OMIT_VIEW */
  82943. return nErr;
  82944. }
  82945. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  82946. #ifndef SQLITE_OMIT_VIEW
  82947. /*
  82948. ** Clear the column names from every VIEW in database idx.
  82949. */
  82950. static void sqliteViewResetAll(sqlite3 *db, int idx){
  82951. HashElem *i;
  82952. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  82953. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  82954. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  82955. Table *pTab = sqliteHashData(i);
  82956. if( pTab->pSelect ){
  82957. sqliteDeleteColumnNames(db, pTab);
  82958. pTab->aCol = 0;
  82959. pTab->nCol = 0;
  82960. }
  82961. }
  82962. DbClearProperty(db, idx, DB_UnresetViews);
  82963. }
  82964. #else
  82965. # define sqliteViewResetAll(A,B)
  82966. #endif /* SQLITE_OMIT_VIEW */
  82967. /*
  82968. ** This function is called by the VDBE to adjust the internal schema
  82969. ** used by SQLite when the btree layer moves a table root page. The
  82970. ** root-page of a table or index in database iDb has changed from iFrom
  82971. ** to iTo.
  82972. **
  82973. ** Ticket #1728: The symbol table might still contain information
  82974. ** on tables and/or indices that are the process of being deleted.
  82975. ** If you are unlucky, one of those deleted indices or tables might
  82976. ** have the same rootpage number as the real table or index that is
  82977. ** being moved. So we cannot stop searching after the first match
  82978. ** because the first match might be for one of the deleted indices
  82979. ** or tables and not the table/index that is actually being moved.
  82980. ** We must continue looping until all tables and indices with
  82981. ** rootpage==iFrom have been converted to have a rootpage of iTo
  82982. ** in order to be certain that we got the right one.
  82983. */
  82984. #ifndef SQLITE_OMIT_AUTOVACUUM
  82985. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  82986. HashElem *pElem;
  82987. Hash *pHash;
  82988. Db *pDb;
  82989. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  82990. pDb = &db->aDb[iDb];
  82991. pHash = &pDb->pSchema->tblHash;
  82992. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  82993. Table *pTab = sqliteHashData(pElem);
  82994. if( pTab->tnum==iFrom ){
  82995. pTab->tnum = iTo;
  82996. }
  82997. }
  82998. pHash = &pDb->pSchema->idxHash;
  82999. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  83000. Index *pIdx = sqliteHashData(pElem);
  83001. if( pIdx->tnum==iFrom ){
  83002. pIdx->tnum = iTo;
  83003. }
  83004. }
  83005. }
  83006. #endif
  83007. /*
  83008. ** Write code to erase the table with root-page iTable from database iDb.
  83009. ** Also write code to modify the sqlite_master table and internal schema
  83010. ** if a root-page of another table is moved by the btree-layer whilst
  83011. ** erasing iTable (this can happen with an auto-vacuum database).
  83012. */
  83013. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  83014. Vdbe *v = sqlite3GetVdbe(pParse);
  83015. int r1 = sqlite3GetTempReg(pParse);
  83016. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  83017. sqlite3MayAbort(pParse);
  83018. #ifndef SQLITE_OMIT_AUTOVACUUM
  83019. /* OP_Destroy stores an in integer r1. If this integer
  83020. ** is non-zero, then it is the root page number of a table moved to
  83021. ** location iTable. The following code modifies the sqlite_master table to
  83022. ** reflect this.
  83023. **
  83024. ** The "#NNN" in the SQL is a special constant that means whatever value
  83025. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  83026. ** token for additional information.
  83027. */
  83028. sqlite3NestedParse(pParse,
  83029. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  83030. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  83031. #endif
  83032. sqlite3ReleaseTempReg(pParse, r1);
  83033. }
  83034. /*
  83035. ** Write VDBE code to erase table pTab and all associated indices on disk.
  83036. ** Code to update the sqlite_master tables and internal schema definitions
  83037. ** in case a root-page belonging to another table is moved by the btree layer
  83038. ** is also added (this can happen with an auto-vacuum database).
  83039. */
  83040. static void destroyTable(Parse *pParse, Table *pTab){
  83041. #ifdef SQLITE_OMIT_AUTOVACUUM
  83042. Index *pIdx;
  83043. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83044. destroyRootPage(pParse, pTab->tnum, iDb);
  83045. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83046. destroyRootPage(pParse, pIdx->tnum, iDb);
  83047. }
  83048. #else
  83049. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  83050. ** is not defined), then it is important to call OP_Destroy on the
  83051. ** table and index root-pages in order, starting with the numerically
  83052. ** largest root-page number. This guarantees that none of the root-pages
  83053. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  83054. ** following were coded:
  83055. **
  83056. ** OP_Destroy 4 0
  83057. ** ...
  83058. ** OP_Destroy 5 0
  83059. **
  83060. ** and root page 5 happened to be the largest root-page number in the
  83061. ** database, then root page 5 would be moved to page 4 by the
  83062. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  83063. ** a free-list page.
  83064. */
  83065. int iTab = pTab->tnum;
  83066. int iDestroyed = 0;
  83067. while( 1 ){
  83068. Index *pIdx;
  83069. int iLargest = 0;
  83070. if( iDestroyed==0 || iTab<iDestroyed ){
  83071. iLargest = iTab;
  83072. }
  83073. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83074. int iIdx = pIdx->tnum;
  83075. assert( pIdx->pSchema==pTab->pSchema );
  83076. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  83077. iLargest = iIdx;
  83078. }
  83079. }
  83080. if( iLargest==0 ){
  83081. return;
  83082. }else{
  83083. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  83084. assert( iDb>=0 && iDb<pParse->db->nDb );
  83085. destroyRootPage(pParse, iLargest, iDb);
  83086. iDestroyed = iLargest;
  83087. }
  83088. }
  83089. #endif
  83090. }
  83091. /*
  83092. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  83093. ** after a DROP INDEX or DROP TABLE command.
  83094. */
  83095. static void sqlite3ClearStatTables(
  83096. Parse *pParse, /* The parsing context */
  83097. int iDb, /* The database number */
  83098. const char *zType, /* "idx" or "tbl" */
  83099. const char *zName /* Name of index or table */
  83100. ){
  83101. int i;
  83102. const char *zDbName = pParse->db->aDb[iDb].zName;
  83103. for(i=1; i<=4; i++){
  83104. char zTab[24];
  83105. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  83106. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  83107. sqlite3NestedParse(pParse,
  83108. "DELETE FROM %Q.%s WHERE %s=%Q",
  83109. zDbName, zTab, zType, zName
  83110. );
  83111. }
  83112. }
  83113. }
  83114. /*
  83115. ** Generate code to drop a table.
  83116. */
  83117. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  83118. Vdbe *v;
  83119. sqlite3 *db = pParse->db;
  83120. Trigger *pTrigger;
  83121. Db *pDb = &db->aDb[iDb];
  83122. v = sqlite3GetVdbe(pParse);
  83123. assert( v!=0 );
  83124. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83125. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83126. if( IsVirtual(pTab) ){
  83127. sqlite3VdbeAddOp0(v, OP_VBegin);
  83128. }
  83129. #endif
  83130. /* Drop all triggers associated with the table being dropped. Code
  83131. ** is generated to remove entries from sqlite_master and/or
  83132. ** sqlite_temp_master if required.
  83133. */
  83134. pTrigger = sqlite3TriggerList(pParse, pTab);
  83135. while( pTrigger ){
  83136. assert( pTrigger->pSchema==pTab->pSchema ||
  83137. pTrigger->pSchema==db->aDb[1].pSchema );
  83138. sqlite3DropTriggerPtr(pParse, pTrigger);
  83139. pTrigger = pTrigger->pNext;
  83140. }
  83141. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83142. /* Remove any entries of the sqlite_sequence table associated with
  83143. ** the table being dropped. This is done before the table is dropped
  83144. ** at the btree level, in case the sqlite_sequence table needs to
  83145. ** move as a result of the drop (can happen in auto-vacuum mode).
  83146. */
  83147. if( pTab->tabFlags & TF_Autoincrement ){
  83148. sqlite3NestedParse(pParse,
  83149. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  83150. pDb->zName, pTab->zName
  83151. );
  83152. }
  83153. #endif
  83154. /* Drop all SQLITE_MASTER table and index entries that refer to the
  83155. ** table. The program name loops through the master table and deletes
  83156. ** every row that refers to a table of the same name as the one being
  83157. ** dropped. Triggers are handled separately because a trigger can be
  83158. ** created in the temp database that refers to a table in another
  83159. ** database.
  83160. */
  83161. sqlite3NestedParse(pParse,
  83162. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  83163. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  83164. if( !isView && !IsVirtual(pTab) ){
  83165. destroyTable(pParse, pTab);
  83166. }
  83167. /* Remove the table entry from SQLite's internal schema and modify
  83168. ** the schema cookie.
  83169. */
  83170. if( IsVirtual(pTab) ){
  83171. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  83172. }
  83173. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  83174. sqlite3ChangeCookie(pParse, iDb);
  83175. sqliteViewResetAll(db, iDb);
  83176. }
  83177. /*
  83178. ** This routine is called to do the work of a DROP TABLE statement.
  83179. ** pName is the name of the table to be dropped.
  83180. */
  83181. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  83182. Table *pTab;
  83183. Vdbe *v;
  83184. sqlite3 *db = pParse->db;
  83185. int iDb;
  83186. if( db->mallocFailed ){
  83187. goto exit_drop_table;
  83188. }
  83189. assert( pParse->nErr==0 );
  83190. assert( pName->nSrc==1 );
  83191. if( noErr ) db->suppressErr++;
  83192. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  83193. if( noErr ) db->suppressErr--;
  83194. if( pTab==0 ){
  83195. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  83196. goto exit_drop_table;
  83197. }
  83198. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83199. assert( iDb>=0 && iDb<db->nDb );
  83200. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  83201. ** it is initialized.
  83202. */
  83203. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  83204. goto exit_drop_table;
  83205. }
  83206. #ifndef SQLITE_OMIT_AUTHORIZATION
  83207. {
  83208. int code;
  83209. const char *zTab = SCHEMA_TABLE(iDb);
  83210. const char *zDb = db->aDb[iDb].zName;
  83211. const char *zArg2 = 0;
  83212. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  83213. goto exit_drop_table;
  83214. }
  83215. if( isView ){
  83216. if( !OMIT_TEMPDB && iDb==1 ){
  83217. code = SQLITE_DROP_TEMP_VIEW;
  83218. }else{
  83219. code = SQLITE_DROP_VIEW;
  83220. }
  83221. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83222. }else if( IsVirtual(pTab) ){
  83223. code = SQLITE_DROP_VTABLE;
  83224. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  83225. #endif
  83226. }else{
  83227. if( !OMIT_TEMPDB && iDb==1 ){
  83228. code = SQLITE_DROP_TEMP_TABLE;
  83229. }else{
  83230. code = SQLITE_DROP_TABLE;
  83231. }
  83232. }
  83233. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  83234. goto exit_drop_table;
  83235. }
  83236. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  83237. goto exit_drop_table;
  83238. }
  83239. }
  83240. #endif
  83241. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  83242. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  83243. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  83244. goto exit_drop_table;
  83245. }
  83246. #ifndef SQLITE_OMIT_VIEW
  83247. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  83248. ** on a table.
  83249. */
  83250. if( isView && pTab->pSelect==0 ){
  83251. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  83252. goto exit_drop_table;
  83253. }
  83254. if( !isView && pTab->pSelect ){
  83255. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  83256. goto exit_drop_table;
  83257. }
  83258. #endif
  83259. /* Generate code to remove the table from the master table
  83260. ** on disk.
  83261. */
  83262. v = sqlite3GetVdbe(pParse);
  83263. if( v ){
  83264. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83265. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  83266. sqlite3FkDropTable(pParse, pName, pTab);
  83267. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  83268. }
  83269. exit_drop_table:
  83270. sqlite3SrcListDelete(db, pName);
  83271. }
  83272. /*
  83273. ** This routine is called to create a new foreign key on the table
  83274. ** currently under construction. pFromCol determines which columns
  83275. ** in the current table point to the foreign key. If pFromCol==0 then
  83276. ** connect the key to the last column inserted. pTo is the name of
  83277. ** the table referred to. pToCol is a list of tables in the other
  83278. ** pTo table that the foreign key points to. flags contains all
  83279. ** information about the conflict resolution algorithms specified
  83280. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  83281. **
  83282. ** An FKey structure is created and added to the table currently
  83283. ** under construction in the pParse->pNewTable field.
  83284. **
  83285. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  83286. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  83287. */
  83288. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  83289. Parse *pParse, /* Parsing context */
  83290. ExprList *pFromCol, /* Columns in this table that point to other table */
  83291. Token *pTo, /* Name of the other table */
  83292. ExprList *pToCol, /* Columns in the other table */
  83293. int flags /* Conflict resolution algorithms. */
  83294. ){
  83295. sqlite3 *db = pParse->db;
  83296. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83297. FKey *pFKey = 0;
  83298. FKey *pNextTo;
  83299. Table *p = pParse->pNewTable;
  83300. int nByte;
  83301. int i;
  83302. int nCol;
  83303. char *z;
  83304. assert( pTo!=0 );
  83305. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  83306. if( pFromCol==0 ){
  83307. int iCol = p->nCol-1;
  83308. if( NEVER(iCol<0) ) goto fk_end;
  83309. if( pToCol && pToCol->nExpr!=1 ){
  83310. sqlite3ErrorMsg(pParse, "foreign key on %s"
  83311. " should reference only one column of table %T",
  83312. p->aCol[iCol].zName, pTo);
  83313. goto fk_end;
  83314. }
  83315. nCol = 1;
  83316. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  83317. sqlite3ErrorMsg(pParse,
  83318. "number of columns in foreign key does not match the number of "
  83319. "columns in the referenced table");
  83320. goto fk_end;
  83321. }else{
  83322. nCol = pFromCol->nExpr;
  83323. }
  83324. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  83325. if( pToCol ){
  83326. for(i=0; i<pToCol->nExpr; i++){
  83327. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  83328. }
  83329. }
  83330. pFKey = sqlite3DbMallocZero(db, nByte );
  83331. if( pFKey==0 ){
  83332. goto fk_end;
  83333. }
  83334. pFKey->pFrom = p;
  83335. pFKey->pNextFrom = p->pFKey;
  83336. z = (char*)&pFKey->aCol[nCol];
  83337. pFKey->zTo = z;
  83338. memcpy(z, pTo->z, pTo->n);
  83339. z[pTo->n] = 0;
  83340. sqlite3Dequote(z);
  83341. z += pTo->n+1;
  83342. pFKey->nCol = nCol;
  83343. if( pFromCol==0 ){
  83344. pFKey->aCol[0].iFrom = p->nCol-1;
  83345. }else{
  83346. for(i=0; i<nCol; i++){
  83347. int j;
  83348. for(j=0; j<p->nCol; j++){
  83349. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  83350. pFKey->aCol[i].iFrom = j;
  83351. break;
  83352. }
  83353. }
  83354. if( j>=p->nCol ){
  83355. sqlite3ErrorMsg(pParse,
  83356. "unknown column \"%s\" in foreign key definition",
  83357. pFromCol->a[i].zName);
  83358. goto fk_end;
  83359. }
  83360. }
  83361. }
  83362. if( pToCol ){
  83363. for(i=0; i<nCol; i++){
  83364. int n = sqlite3Strlen30(pToCol->a[i].zName);
  83365. pFKey->aCol[i].zCol = z;
  83366. memcpy(z, pToCol->a[i].zName, n);
  83367. z[n] = 0;
  83368. z += n+1;
  83369. }
  83370. }
  83371. pFKey->isDeferred = 0;
  83372. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  83373. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  83374. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  83375. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  83376. pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
  83377. );
  83378. if( pNextTo==pFKey ){
  83379. db->mallocFailed = 1;
  83380. goto fk_end;
  83381. }
  83382. if( pNextTo ){
  83383. assert( pNextTo->pPrevTo==0 );
  83384. pFKey->pNextTo = pNextTo;
  83385. pNextTo->pPrevTo = pFKey;
  83386. }
  83387. /* Link the foreign key to the table as the last step.
  83388. */
  83389. p->pFKey = pFKey;
  83390. pFKey = 0;
  83391. fk_end:
  83392. sqlite3DbFree(db, pFKey);
  83393. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  83394. sqlite3ExprListDelete(db, pFromCol);
  83395. sqlite3ExprListDelete(db, pToCol);
  83396. }
  83397. /*
  83398. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  83399. ** clause is seen as part of a foreign key definition. The isDeferred
  83400. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  83401. ** The behavior of the most recently created foreign key is adjusted
  83402. ** accordingly.
  83403. */
  83404. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  83405. #ifndef SQLITE_OMIT_FOREIGN_KEY
  83406. Table *pTab;
  83407. FKey *pFKey;
  83408. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  83409. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  83410. pFKey->isDeferred = (u8)isDeferred;
  83411. #endif
  83412. }
  83413. /*
  83414. ** Generate code that will erase and refill index *pIdx. This is
  83415. ** used to initialize a newly created index or to recompute the
  83416. ** content of an index in response to a REINDEX command.
  83417. **
  83418. ** if memRootPage is not negative, it means that the index is newly
  83419. ** created. The register specified by memRootPage contains the
  83420. ** root page number of the index. If memRootPage is negative, then
  83421. ** the index already exists and must be cleared before being refilled and
  83422. ** the root page number of the index is taken from pIndex->tnum.
  83423. */
  83424. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  83425. Table *pTab = pIndex->pTable; /* The table that is indexed */
  83426. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  83427. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  83428. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  83429. int addr1; /* Address of top of loop */
  83430. int addr2; /* Address to jump to for next iteration */
  83431. int tnum; /* Root page of index */
  83432. int iPartIdxLabel; /* Jump to this label to skip a row */
  83433. Vdbe *v; /* Generate code into this virtual machine */
  83434. KeyInfo *pKey; /* KeyInfo for index */
  83435. int regRecord; /* Register holding assemblied index record */
  83436. sqlite3 *db = pParse->db; /* The database connection */
  83437. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  83438. #ifndef SQLITE_OMIT_AUTHORIZATION
  83439. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  83440. db->aDb[iDb].zName ) ){
  83441. return;
  83442. }
  83443. #endif
  83444. /* Require a write-lock on the table to perform this operation */
  83445. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  83446. v = sqlite3GetVdbe(pParse);
  83447. if( v==0 ) return;
  83448. if( memRootPage>=0 ){
  83449. tnum = memRootPage;
  83450. }else{
  83451. tnum = pIndex->tnum;
  83452. sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  83453. }
  83454. pKey = sqlite3IndexKeyinfo(pParse, pIndex);
  83455. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  83456. (char *)pKey, P4_KEYINFO_HANDOFF);
  83457. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  83458. /* Open the sorter cursor if we are to use one. */
  83459. iSorter = pParse->nTab++;
  83460. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, 0, (char*)pKey, P4_KEYINFO);
  83461. /* Open the table. Loop through all rows of the table, inserting index
  83462. ** records into the sorter. */
  83463. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  83464. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
  83465. regRecord = sqlite3GetTempReg(pParse);
  83466. sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1, &iPartIdxLabel);
  83467. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  83468. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  83469. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
  83470. sqlite3VdbeJumpHere(v, addr1);
  83471. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0);
  83472. if( pIndex->onError!=OE_None ){
  83473. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  83474. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  83475. addr2 = sqlite3VdbeCurrentAddr(v);
  83476. sqlite3VdbeAddOp3(v, OP_SorterCompare, iSorter, j2, regRecord);
  83477. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  83478. OE_Abort, "indexed columns are not unique", P4_STATIC
  83479. );
  83480. }else{
  83481. addr2 = sqlite3VdbeCurrentAddr(v);
  83482. }
  83483. sqlite3VdbeAddOp2(v, OP_SorterData, iSorter, regRecord);
  83484. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  83485. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  83486. sqlite3ReleaseTempReg(pParse, regRecord);
  83487. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2);
  83488. sqlite3VdbeJumpHere(v, addr1);
  83489. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  83490. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  83491. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  83492. }
  83493. /*
  83494. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  83495. ** and pTblList is the name of the table that is to be indexed. Both will
  83496. ** be NULL for a primary key or an index that is created to satisfy a
  83497. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  83498. ** as the table to be indexed. pParse->pNewTable is a table that is
  83499. ** currently being constructed by a CREATE TABLE statement.
  83500. **
  83501. ** pList is a list of columns to be indexed. pList will be NULL if this
  83502. ** is a primary key or unique-constraint on the most recent column added
  83503. ** to the table currently under construction.
  83504. **
  83505. ** If the index is created successfully, return a pointer to the new Index
  83506. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  83507. ** as the tables primary key (Index.autoIndex==2).
  83508. */
  83509. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  83510. Parse *pParse, /* All information about this parse */
  83511. Token *pName1, /* First part of index name. May be NULL */
  83512. Token *pName2, /* Second part of index name. May be NULL */
  83513. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  83514. ExprList *pList, /* A list of columns to be indexed */
  83515. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  83516. Token *pStart, /* The CREATE token that begins this statement */
  83517. Expr *pPIWhere, /* WHERE clause for partial indices */
  83518. int sortOrder, /* Sort order of primary key when pList==NULL */
  83519. int ifNotExist /* Omit error if index already exists */
  83520. ){
  83521. Index *pRet = 0; /* Pointer to return */
  83522. Table *pTab = 0; /* Table to be indexed */
  83523. Index *pIndex = 0; /* The index to be created */
  83524. char *zName = 0; /* Name of the index */
  83525. int nName; /* Number of characters in zName */
  83526. int i, j;
  83527. Token nullId; /* Fake token for an empty ID list */
  83528. DbFixer sFix; /* For assigning database names to pTable */
  83529. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  83530. sqlite3 *db = pParse->db;
  83531. Db *pDb; /* The specific table containing the indexed database */
  83532. int iDb; /* Index of the database that is being written */
  83533. Token *pName = 0; /* Unqualified name of the index to create */
  83534. struct ExprList_item *pListItem; /* For looping over pList */
  83535. const Column *pTabCol; /* A column in the table */
  83536. int nCol; /* Number of columns */
  83537. int nExtra = 0; /* Space allocated for zExtra[] */
  83538. char *zExtra; /* Extra space after the Index object */
  83539. assert( pParse->nErr==0 ); /* Never called with prior errors */
  83540. if( db->mallocFailed || IN_DECLARE_VTAB ){
  83541. goto exit_create_index;
  83542. }
  83543. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83544. goto exit_create_index;
  83545. }
  83546. /*
  83547. ** Find the table that is to be indexed. Return early if not found.
  83548. */
  83549. if( pTblName!=0 ){
  83550. /* Use the two-part index name to determine the database
  83551. ** to search for the table. 'Fix' the table name to this db
  83552. ** before looking up the table.
  83553. */
  83554. assert( pName1 && pName2 );
  83555. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  83556. if( iDb<0 ) goto exit_create_index;
  83557. assert( pName && pName->z );
  83558. #ifndef SQLITE_OMIT_TEMPDB
  83559. /* If the index name was unqualified, check if the table
  83560. ** is a temp table. If so, set the database to 1. Do not do this
  83561. ** if initialising a database schema.
  83562. */
  83563. if( !db->init.busy ){
  83564. pTab = sqlite3SrcListLookup(pParse, pTblName);
  83565. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  83566. iDb = 1;
  83567. }
  83568. }
  83569. #endif
  83570. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  83571. if( sqlite3FixSrcList(&sFix, pTblName) ){
  83572. /* Because the parser constructs pTblName from a single identifier,
  83573. ** sqlite3FixSrcList can never fail. */
  83574. assert(0);
  83575. }
  83576. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  83577. assert( db->mallocFailed==0 || pTab==0 );
  83578. if( pTab==0 ) goto exit_create_index;
  83579. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  83580. sqlite3ErrorMsg(pParse,
  83581. "cannot create a TEMP index on non-TEMP table \"%s\"",
  83582. pTab->zName);
  83583. goto exit_create_index;
  83584. }
  83585. }else{
  83586. assert( pName==0 );
  83587. assert( pStart==0 );
  83588. pTab = pParse->pNewTable;
  83589. if( !pTab ) goto exit_create_index;
  83590. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  83591. }
  83592. pDb = &db->aDb[iDb];
  83593. assert( pTab!=0 );
  83594. assert( pParse->nErr==0 );
  83595. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  83596. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  83597. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  83598. goto exit_create_index;
  83599. }
  83600. #ifndef SQLITE_OMIT_VIEW
  83601. if( pTab->pSelect ){
  83602. sqlite3ErrorMsg(pParse, "views may not be indexed");
  83603. goto exit_create_index;
  83604. }
  83605. #endif
  83606. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83607. if( IsVirtual(pTab) ){
  83608. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  83609. goto exit_create_index;
  83610. }
  83611. #endif
  83612. /*
  83613. ** Find the name of the index. Make sure there is not already another
  83614. ** index or table with the same name.
  83615. **
  83616. ** Exception: If we are reading the names of permanent indices from the
  83617. ** sqlite_master table (because some other process changed the schema) and
  83618. ** one of the index names collides with the name of a temporary table or
  83619. ** index, then we will continue to process this index.
  83620. **
  83621. ** If pName==0 it means that we are
  83622. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  83623. ** own name.
  83624. */
  83625. if( pName ){
  83626. zName = sqlite3NameFromToken(db, pName);
  83627. if( zName==0 ) goto exit_create_index;
  83628. assert( pName->z!=0 );
  83629. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  83630. goto exit_create_index;
  83631. }
  83632. if( !db->init.busy ){
  83633. if( sqlite3FindTable(db, zName, 0)!=0 ){
  83634. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  83635. goto exit_create_index;
  83636. }
  83637. }
  83638. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  83639. if( !ifNotExist ){
  83640. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  83641. }else{
  83642. assert( !db->init.busy );
  83643. sqlite3CodeVerifySchema(pParse, iDb);
  83644. }
  83645. goto exit_create_index;
  83646. }
  83647. }else{
  83648. int n;
  83649. Index *pLoop;
  83650. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  83651. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  83652. if( zName==0 ){
  83653. goto exit_create_index;
  83654. }
  83655. }
  83656. /* Check for authorization to create an index.
  83657. */
  83658. #ifndef SQLITE_OMIT_AUTHORIZATION
  83659. {
  83660. const char *zDb = pDb->zName;
  83661. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  83662. goto exit_create_index;
  83663. }
  83664. i = SQLITE_CREATE_INDEX;
  83665. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  83666. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  83667. goto exit_create_index;
  83668. }
  83669. }
  83670. #endif
  83671. /* If pList==0, it means this routine was called to make a primary
  83672. ** key out of the last column added to the table under construction.
  83673. ** So create a fake list to simulate this.
  83674. */
  83675. if( pList==0 ){
  83676. nullId.z = pTab->aCol[pTab->nCol-1].zName;
  83677. nullId.n = sqlite3Strlen30((char*)nullId.z);
  83678. pList = sqlite3ExprListAppend(pParse, 0, 0);
  83679. if( pList==0 ) goto exit_create_index;
  83680. sqlite3ExprListSetName(pParse, pList, &nullId, 0);
  83681. pList->a[0].sortOrder = (u8)sortOrder;
  83682. }
  83683. /* Figure out how many bytes of space are required to store explicitly
  83684. ** specified collation sequence names.
  83685. */
  83686. for(i=0; i<pList->nExpr; i++){
  83687. Expr *pExpr = pList->a[i].pExpr;
  83688. if( pExpr ){
  83689. assert( pExpr->op==TK_COLLATE );
  83690. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  83691. }
  83692. }
  83693. /*
  83694. ** Allocate the index structure.
  83695. */
  83696. nName = sqlite3Strlen30(zName);
  83697. nCol = pList->nExpr;
  83698. pIndex = sqlite3DbMallocZero(db,
  83699. ROUND8(sizeof(Index)) + /* Index structure */
  83700. ROUND8(sizeof(tRowcnt)*(nCol+1)) + /* Index.aiRowEst */
  83701. sizeof(char *)*nCol + /* Index.azColl */
  83702. sizeof(int)*nCol + /* Index.aiColumn */
  83703. sizeof(u8)*nCol + /* Index.aSortOrder */
  83704. nName + 1 + /* Index.zName */
  83705. nExtra /* Collation sequence names */
  83706. );
  83707. if( db->mallocFailed ){
  83708. goto exit_create_index;
  83709. }
  83710. zExtra = (char*)pIndex;
  83711. pIndex->aiRowEst = (tRowcnt*)&zExtra[ROUND8(sizeof(Index))];
  83712. pIndex->azColl = (char**)
  83713. ((char*)pIndex->aiRowEst + ROUND8(sizeof(tRowcnt)*nCol+1));
  83714. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowEst) );
  83715. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  83716. pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
  83717. pIndex->aSortOrder = (u8 *)(&pIndex->aiColumn[nCol]);
  83718. pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
  83719. zExtra = (char *)(&pIndex->zName[nName+1]);
  83720. memcpy(pIndex->zName, zName, nName+1);
  83721. pIndex->pTable = pTab;
  83722. pIndex->nColumn = pList->nExpr;
  83723. pIndex->onError = (u8)onError;
  83724. pIndex->uniqNotNull = onError==OE_Abort;
  83725. pIndex->autoIndex = (u8)(pName==0);
  83726. pIndex->pSchema = db->aDb[iDb].pSchema;
  83727. if( pPIWhere ){
  83728. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  83729. pIndex->pPartIdxWhere = pPIWhere;
  83730. pPIWhere = 0;
  83731. }
  83732. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83733. /* Check to see if we should honor DESC requests on index columns
  83734. */
  83735. if( pDb->pSchema->file_format>=4 ){
  83736. sortOrderMask = -1; /* Honor DESC */
  83737. }else{
  83738. sortOrderMask = 0; /* Ignore DESC */
  83739. }
  83740. /* Scan the names of the columns of the table to be indexed and
  83741. ** load the column indices into the Index structure. Report an error
  83742. ** if any column is not found.
  83743. **
  83744. ** TODO: Add a test to make sure that the same column is not named
  83745. ** more than once within the same index. Only the first instance of
  83746. ** the column will ever be used by the optimizer. Note that using the
  83747. ** same column more than once cannot be an error because that would
  83748. ** break backwards compatibility - it needs to be a warning.
  83749. */
  83750. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  83751. const char *zColName = pListItem->zName;
  83752. int requestedSortOrder;
  83753. char *zColl; /* Collation sequence name */
  83754. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  83755. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  83756. }
  83757. if( j>=pTab->nCol ){
  83758. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  83759. pTab->zName, zColName);
  83760. pParse->checkSchema = 1;
  83761. goto exit_create_index;
  83762. }
  83763. pIndex->aiColumn[i] = j;
  83764. if( pListItem->pExpr ){
  83765. int nColl;
  83766. assert( pListItem->pExpr->op==TK_COLLATE );
  83767. zColl = pListItem->pExpr->u.zToken;
  83768. nColl = sqlite3Strlen30(zColl) + 1;
  83769. assert( nExtra>=nColl );
  83770. memcpy(zExtra, zColl, nColl);
  83771. zColl = zExtra;
  83772. zExtra += nColl;
  83773. nExtra -= nColl;
  83774. }else{
  83775. zColl = pTab->aCol[j].zColl;
  83776. if( !zColl ) zColl = "BINARY";
  83777. }
  83778. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  83779. goto exit_create_index;
  83780. }
  83781. pIndex->azColl[i] = zColl;
  83782. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  83783. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  83784. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  83785. }
  83786. sqlite3DefaultRowEst(pIndex);
  83787. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  83788. if( pTab==pParse->pNewTable ){
  83789. /* This routine has been called to create an automatic index as a
  83790. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  83791. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  83792. ** i.e. one of:
  83793. **
  83794. ** CREATE TABLE t(x PRIMARY KEY, y);
  83795. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  83796. **
  83797. ** Either way, check to see if the table already has such an index. If
  83798. ** so, don't bother creating this one. This only applies to
  83799. ** automatically created indices. Users can do as they wish with
  83800. ** explicit indices.
  83801. **
  83802. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  83803. ** (and thus suppressing the second one) even if they have different
  83804. ** sort orders.
  83805. **
  83806. ** If there are different collating sequences or if the columns of
  83807. ** the constraint occur in different orders, then the constraints are
  83808. ** considered distinct and both result in separate indices.
  83809. */
  83810. Index *pIdx;
  83811. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  83812. int k;
  83813. assert( pIdx->onError!=OE_None );
  83814. assert( pIdx->autoIndex );
  83815. assert( pIndex->onError!=OE_None );
  83816. if( pIdx->nColumn!=pIndex->nColumn ) continue;
  83817. for(k=0; k<pIdx->nColumn; k++){
  83818. const char *z1;
  83819. const char *z2;
  83820. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  83821. z1 = pIdx->azColl[k];
  83822. z2 = pIndex->azColl[k];
  83823. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  83824. }
  83825. if( k==pIdx->nColumn ){
  83826. if( pIdx->onError!=pIndex->onError ){
  83827. /* This constraint creates the same index as a previous
  83828. ** constraint specified somewhere in the CREATE TABLE statement.
  83829. ** However the ON CONFLICT clauses are different. If both this
  83830. ** constraint and the previous equivalent constraint have explicit
  83831. ** ON CONFLICT clauses this is an error. Otherwise, use the
  83832. ** explicitly specified behavior for the index.
  83833. */
  83834. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  83835. sqlite3ErrorMsg(pParse,
  83836. "conflicting ON CONFLICT clauses specified", 0);
  83837. }
  83838. if( pIdx->onError==OE_Default ){
  83839. pIdx->onError = pIndex->onError;
  83840. }
  83841. }
  83842. goto exit_create_index;
  83843. }
  83844. }
  83845. }
  83846. /* Link the new Index structure to its table and to the other
  83847. ** in-memory database structures.
  83848. */
  83849. if( db->init.busy ){
  83850. Index *p;
  83851. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  83852. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  83853. pIndex->zName, sqlite3Strlen30(pIndex->zName),
  83854. pIndex);
  83855. if( p ){
  83856. assert( p==pIndex ); /* Malloc must have failed */
  83857. db->mallocFailed = 1;
  83858. goto exit_create_index;
  83859. }
  83860. db->flags |= SQLITE_InternChanges;
  83861. if( pTblName!=0 ){
  83862. pIndex->tnum = db->init.newTnum;
  83863. }
  83864. }
  83865. /* If the db->init.busy is 0 then create the index on disk. This
  83866. ** involves writing the index into the master table and filling in the
  83867. ** index with the current table contents.
  83868. **
  83869. ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  83870. ** command. db->init.busy is 1 when a database is opened and
  83871. ** CREATE INDEX statements are read out of the master table. In
  83872. ** the latter case the index already exists on disk, which is why
  83873. ** we don't want to recreate it.
  83874. **
  83875. ** If pTblName==0 it means this index is generated as a primary key
  83876. ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  83877. ** has just been created, it contains no data and the index initialization
  83878. ** step can be skipped.
  83879. */
  83880. else if( pParse->nErr==0 ){
  83881. Vdbe *v;
  83882. char *zStmt;
  83883. int iMem = ++pParse->nMem;
  83884. v = sqlite3GetVdbe(pParse);
  83885. if( v==0 ) goto exit_create_index;
  83886. /* Create the rootpage for the index
  83887. */
  83888. sqlite3BeginWriteOperation(pParse, 1, iDb);
  83889. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  83890. /* Gather the complete text of the CREATE INDEX statement into
  83891. ** the zStmt variable
  83892. */
  83893. if( pStart ){
  83894. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  83895. if( pName->z[n-1]==';' ) n--;
  83896. /* A named index with an explicit CREATE INDEX statement */
  83897. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  83898. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  83899. }else{
  83900. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  83901. /* zStmt = sqlite3MPrintf(""); */
  83902. zStmt = 0;
  83903. }
  83904. /* Add an entry in sqlite_master for this index
  83905. */
  83906. sqlite3NestedParse(pParse,
  83907. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  83908. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  83909. pIndex->zName,
  83910. pTab->zName,
  83911. iMem,
  83912. zStmt
  83913. );
  83914. sqlite3DbFree(db, zStmt);
  83915. /* Fill the index with data and reparse the schema. Code an OP_Expire
  83916. ** to invalidate all pre-compiled statements.
  83917. */
  83918. if( pTblName ){
  83919. sqlite3RefillIndex(pParse, pIndex, iMem);
  83920. sqlite3ChangeCookie(pParse, iDb);
  83921. sqlite3VdbeAddParseSchemaOp(v, iDb,
  83922. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  83923. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  83924. }
  83925. }
  83926. /* When adding an index to the list of indices for a table, make
  83927. ** sure all indices labeled OE_Replace come after all those labeled
  83928. ** OE_Ignore. This is necessary for the correct constraint check
  83929. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  83930. ** UPDATE and INSERT statements.
  83931. */
  83932. if( db->init.busy || pTblName==0 ){
  83933. if( onError!=OE_Replace || pTab->pIndex==0
  83934. || pTab->pIndex->onError==OE_Replace){
  83935. pIndex->pNext = pTab->pIndex;
  83936. pTab->pIndex = pIndex;
  83937. }else{
  83938. Index *pOther = pTab->pIndex;
  83939. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  83940. pOther = pOther->pNext;
  83941. }
  83942. pIndex->pNext = pOther->pNext;
  83943. pOther->pNext = pIndex;
  83944. }
  83945. pRet = pIndex;
  83946. pIndex = 0;
  83947. }
  83948. /* Clean up before exiting */
  83949. exit_create_index:
  83950. if( pIndex ) freeIndex(db, pIndex);
  83951. sqlite3ExprDelete(db, pPIWhere);
  83952. sqlite3ExprListDelete(db, pList);
  83953. sqlite3SrcListDelete(db, pTblName);
  83954. sqlite3DbFree(db, zName);
  83955. return pRet;
  83956. }
  83957. /*
  83958. ** Fill the Index.aiRowEst[] array with default information - information
  83959. ** to be used when we have not run the ANALYZE command.
  83960. **
  83961. ** aiRowEst[0] is suppose to contain the number of elements in the index.
  83962. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  83963. ** number of rows in the table that match any particular value of the
  83964. ** first column of the index. aiRowEst[2] is an estimate of the number
  83965. ** of rows that match any particular combiniation of the first 2 columns
  83966. ** of the index. And so forth. It must always be the case that
  83967. *
  83968. ** aiRowEst[N]<=aiRowEst[N-1]
  83969. ** aiRowEst[N]>=1
  83970. **
  83971. ** Apart from that, we have little to go on besides intuition as to
  83972. ** how aiRowEst[] should be initialized. The numbers generated here
  83973. ** are based on typical values found in actual indices.
  83974. */
  83975. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  83976. tRowcnt *a = pIdx->aiRowEst;
  83977. int i;
  83978. tRowcnt n;
  83979. assert( a!=0 );
  83980. a[0] = pIdx->pTable->nRowEst;
  83981. if( a[0]<10 ) a[0] = 10;
  83982. n = 10;
  83983. for(i=1; i<=pIdx->nColumn; i++){
  83984. a[i] = n;
  83985. if( n>5 ) n--;
  83986. }
  83987. if( pIdx->onError!=OE_None ){
  83988. a[pIdx->nColumn] = 1;
  83989. }
  83990. }
  83991. /*
  83992. ** This routine will drop an existing named index. This routine
  83993. ** implements the DROP INDEX statement.
  83994. */
  83995. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  83996. Index *pIndex;
  83997. Vdbe *v;
  83998. sqlite3 *db = pParse->db;
  83999. int iDb;
  84000. assert( pParse->nErr==0 ); /* Never called with prior errors */
  84001. if( db->mallocFailed ){
  84002. goto exit_drop_index;
  84003. }
  84004. assert( pName->nSrc==1 );
  84005. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  84006. goto exit_drop_index;
  84007. }
  84008. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  84009. if( pIndex==0 ){
  84010. if( !ifExists ){
  84011. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  84012. }else{
  84013. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  84014. }
  84015. pParse->checkSchema = 1;
  84016. goto exit_drop_index;
  84017. }
  84018. if( pIndex->autoIndex ){
  84019. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  84020. "or PRIMARY KEY constraint cannot be dropped", 0);
  84021. goto exit_drop_index;
  84022. }
  84023. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  84024. #ifndef SQLITE_OMIT_AUTHORIZATION
  84025. {
  84026. int code = SQLITE_DROP_INDEX;
  84027. Table *pTab = pIndex->pTable;
  84028. const char *zDb = db->aDb[iDb].zName;
  84029. const char *zTab = SCHEMA_TABLE(iDb);
  84030. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  84031. goto exit_drop_index;
  84032. }
  84033. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  84034. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  84035. goto exit_drop_index;
  84036. }
  84037. }
  84038. #endif
  84039. /* Generate code to remove the index and from the master table */
  84040. v = sqlite3GetVdbe(pParse);
  84041. if( v ){
  84042. sqlite3BeginWriteOperation(pParse, 1, iDb);
  84043. sqlite3NestedParse(pParse,
  84044. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  84045. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  84046. );
  84047. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  84048. sqlite3ChangeCookie(pParse, iDb);
  84049. destroyRootPage(pParse, pIndex->tnum, iDb);
  84050. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  84051. }
  84052. exit_drop_index:
  84053. sqlite3SrcListDelete(db, pName);
  84054. }
  84055. /*
  84056. ** pArray is a pointer to an array of objects. Each object in the
  84057. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  84058. ** to extend the array so that there is space for a new object at the end.
  84059. **
  84060. ** When this function is called, *pnEntry contains the current size of
  84061. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  84062. ** in total).
  84063. **
  84064. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  84065. ** space allocated for the new object is zeroed, *pnEntry updated to
  84066. ** reflect the new size of the array and a pointer to the new allocation
  84067. ** returned. *pIdx is set to the index of the new array entry in this case.
  84068. **
  84069. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  84070. ** unchanged and a copy of pArray returned.
  84071. */
  84072. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  84073. sqlite3 *db, /* Connection to notify of malloc failures */
  84074. void *pArray, /* Array of objects. Might be reallocated */
  84075. int szEntry, /* Size of each object in the array */
  84076. int *pnEntry, /* Number of objects currently in use */
  84077. int *pIdx /* Write the index of a new slot here */
  84078. ){
  84079. char *z;
  84080. int n = *pnEntry;
  84081. if( (n & (n-1))==0 ){
  84082. int sz = (n==0) ? 1 : 2*n;
  84083. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  84084. if( pNew==0 ){
  84085. *pIdx = -1;
  84086. return pArray;
  84087. }
  84088. pArray = pNew;
  84089. }
  84090. z = (char*)pArray;
  84091. memset(&z[n * szEntry], 0, szEntry);
  84092. *pIdx = n;
  84093. ++*pnEntry;
  84094. return pArray;
  84095. }
  84096. /*
  84097. ** Append a new element to the given IdList. Create a new IdList if
  84098. ** need be.
  84099. **
  84100. ** A new IdList is returned, or NULL if malloc() fails.
  84101. */
  84102. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  84103. int i;
  84104. if( pList==0 ){
  84105. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  84106. if( pList==0 ) return 0;
  84107. }
  84108. pList->a = sqlite3ArrayAllocate(
  84109. db,
  84110. pList->a,
  84111. sizeof(pList->a[0]),
  84112. &pList->nId,
  84113. &i
  84114. );
  84115. if( i<0 ){
  84116. sqlite3IdListDelete(db, pList);
  84117. return 0;
  84118. }
  84119. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  84120. return pList;
  84121. }
  84122. /*
  84123. ** Delete an IdList.
  84124. */
  84125. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  84126. int i;
  84127. if( pList==0 ) return;
  84128. for(i=0; i<pList->nId; i++){
  84129. sqlite3DbFree(db, pList->a[i].zName);
  84130. }
  84131. sqlite3DbFree(db, pList->a);
  84132. sqlite3DbFree(db, pList);
  84133. }
  84134. /*
  84135. ** Return the index in pList of the identifier named zId. Return -1
  84136. ** if not found.
  84137. */
  84138. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  84139. int i;
  84140. if( pList==0 ) return -1;
  84141. for(i=0; i<pList->nId; i++){
  84142. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  84143. }
  84144. return -1;
  84145. }
  84146. /*
  84147. ** Expand the space allocated for the given SrcList object by
  84148. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  84149. ** New slots are zeroed.
  84150. **
  84151. ** For example, suppose a SrcList initially contains two entries: A,B.
  84152. ** To append 3 new entries onto the end, do this:
  84153. **
  84154. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  84155. **
  84156. ** After the call above it would contain: A, B, nil, nil, nil.
  84157. ** If the iStart argument had been 1 instead of 2, then the result
  84158. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  84159. ** the iStart value would be 0. The result then would
  84160. ** be: nil, nil, nil, A, B.
  84161. **
  84162. ** If a memory allocation fails the SrcList is unchanged. The
  84163. ** db->mallocFailed flag will be set to true.
  84164. */
  84165. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  84166. sqlite3 *db, /* Database connection to notify of OOM errors */
  84167. SrcList *pSrc, /* The SrcList to be enlarged */
  84168. int nExtra, /* Number of new slots to add to pSrc->a[] */
  84169. int iStart /* Index in pSrc->a[] of first new slot */
  84170. ){
  84171. int i;
  84172. /* Sanity checking on calling parameters */
  84173. assert( iStart>=0 );
  84174. assert( nExtra>=1 );
  84175. assert( pSrc!=0 );
  84176. assert( iStart<=pSrc->nSrc );
  84177. /* Allocate additional space if needed */
  84178. if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
  84179. SrcList *pNew;
  84180. int nAlloc = pSrc->nSrc+nExtra;
  84181. int nGot;
  84182. pNew = sqlite3DbRealloc(db, pSrc,
  84183. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  84184. if( pNew==0 ){
  84185. assert( db->mallocFailed );
  84186. return pSrc;
  84187. }
  84188. pSrc = pNew;
  84189. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  84190. pSrc->nAlloc = (u8)nGot;
  84191. }
  84192. /* Move existing slots that come after the newly inserted slots
  84193. ** out of the way */
  84194. for(i=pSrc->nSrc-1; i>=iStart; i--){
  84195. pSrc->a[i+nExtra] = pSrc->a[i];
  84196. }
  84197. pSrc->nSrc += (i8)nExtra;
  84198. /* Zero the newly allocated slots */
  84199. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  84200. for(i=iStart; i<iStart+nExtra; i++){
  84201. pSrc->a[i].iCursor = -1;
  84202. }
  84203. /* Return a pointer to the enlarged SrcList */
  84204. return pSrc;
  84205. }
  84206. /*
  84207. ** Append a new table name to the given SrcList. Create a new SrcList if
  84208. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  84209. **
  84210. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  84211. ** SrcList might be the same as the SrcList that was input or it might be
  84212. ** a new one. If an OOM error does occurs, then the prior value of pList
  84213. ** that is input to this routine is automatically freed.
  84214. **
  84215. ** If pDatabase is not null, it means that the table has an optional
  84216. ** database name prefix. Like this: "database.table". The pDatabase
  84217. ** points to the table name and the pTable points to the database name.
  84218. ** The SrcList.a[].zName field is filled with the table name which might
  84219. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  84220. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  84221. ** or with NULL if no database is specified.
  84222. **
  84223. ** In other words, if call like this:
  84224. **
  84225. ** sqlite3SrcListAppend(D,A,B,0);
  84226. **
  84227. ** Then B is a table name and the database name is unspecified. If called
  84228. ** like this:
  84229. **
  84230. ** sqlite3SrcListAppend(D,A,B,C);
  84231. **
  84232. ** Then C is the table name and B is the database name. If C is defined
  84233. ** then so is B. In other words, we never have a case where:
  84234. **
  84235. ** sqlite3SrcListAppend(D,A,0,C);
  84236. **
  84237. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  84238. ** before being added to the SrcList.
  84239. */
  84240. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  84241. sqlite3 *db, /* Connection to notify of malloc failures */
  84242. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  84243. Token *pTable, /* Table to append */
  84244. Token *pDatabase /* Database of the table */
  84245. ){
  84246. struct SrcList_item *pItem;
  84247. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  84248. if( pList==0 ){
  84249. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  84250. if( pList==0 ) return 0;
  84251. pList->nAlloc = 1;
  84252. }
  84253. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  84254. if( db->mallocFailed ){
  84255. sqlite3SrcListDelete(db, pList);
  84256. return 0;
  84257. }
  84258. pItem = &pList->a[pList->nSrc-1];
  84259. if( pDatabase && pDatabase->z==0 ){
  84260. pDatabase = 0;
  84261. }
  84262. if( pDatabase ){
  84263. Token *pTemp = pDatabase;
  84264. pDatabase = pTable;
  84265. pTable = pTemp;
  84266. }
  84267. pItem->zName = sqlite3NameFromToken(db, pTable);
  84268. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  84269. return pList;
  84270. }
  84271. /*
  84272. ** Assign VdbeCursor index numbers to all tables in a SrcList
  84273. */
  84274. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  84275. int i;
  84276. struct SrcList_item *pItem;
  84277. assert(pList || pParse->db->mallocFailed );
  84278. if( pList ){
  84279. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  84280. if( pItem->iCursor>=0 ) break;
  84281. pItem->iCursor = pParse->nTab++;
  84282. if( pItem->pSelect ){
  84283. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  84284. }
  84285. }
  84286. }
  84287. }
  84288. /*
  84289. ** Delete an entire SrcList including all its substructure.
  84290. */
  84291. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  84292. int i;
  84293. struct SrcList_item *pItem;
  84294. if( pList==0 ) return;
  84295. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  84296. sqlite3DbFree(db, pItem->zDatabase);
  84297. sqlite3DbFree(db, pItem->zName);
  84298. sqlite3DbFree(db, pItem->zAlias);
  84299. sqlite3DbFree(db, pItem->zIndex);
  84300. sqlite3DeleteTable(db, pItem->pTab);
  84301. sqlite3SelectDelete(db, pItem->pSelect);
  84302. sqlite3ExprDelete(db, pItem->pOn);
  84303. sqlite3IdListDelete(db, pItem->pUsing);
  84304. }
  84305. sqlite3DbFree(db, pList);
  84306. }
  84307. /*
  84308. ** This routine is called by the parser to add a new term to the
  84309. ** end of a growing FROM clause. The "p" parameter is the part of
  84310. ** the FROM clause that has already been constructed. "p" is NULL
  84311. ** if this is the first term of the FROM clause. pTable and pDatabase
  84312. ** are the name of the table and database named in the FROM clause term.
  84313. ** pDatabase is NULL if the database name qualifier is missing - the
  84314. ** usual case. If the term has a alias, then pAlias points to the
  84315. ** alias token. If the term is a subquery, then pSubquery is the
  84316. ** SELECT statement that the subquery encodes. The pTable and
  84317. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  84318. ** parameters are the content of the ON and USING clauses.
  84319. **
  84320. ** Return a new SrcList which encodes is the FROM with the new
  84321. ** term added.
  84322. */
  84323. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  84324. Parse *pParse, /* Parsing context */
  84325. SrcList *p, /* The left part of the FROM clause already seen */
  84326. Token *pTable, /* Name of the table to add to the FROM clause */
  84327. Token *pDatabase, /* Name of the database containing pTable */
  84328. Token *pAlias, /* The right-hand side of the AS subexpression */
  84329. Select *pSubquery, /* A subquery used in place of a table name */
  84330. Expr *pOn, /* The ON clause of a join */
  84331. IdList *pUsing /* The USING clause of a join */
  84332. ){
  84333. struct SrcList_item *pItem;
  84334. sqlite3 *db = pParse->db;
  84335. if( !p && (pOn || pUsing) ){
  84336. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  84337. (pOn ? "ON" : "USING")
  84338. );
  84339. goto append_from_error;
  84340. }
  84341. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  84342. if( p==0 || NEVER(p->nSrc==0) ){
  84343. goto append_from_error;
  84344. }
  84345. pItem = &p->a[p->nSrc-1];
  84346. assert( pAlias!=0 );
  84347. if( pAlias->n ){
  84348. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  84349. }
  84350. pItem->pSelect = pSubquery;
  84351. pItem->pOn = pOn;
  84352. pItem->pUsing = pUsing;
  84353. return p;
  84354. append_from_error:
  84355. assert( p==0 );
  84356. sqlite3ExprDelete(db, pOn);
  84357. sqlite3IdListDelete(db, pUsing);
  84358. sqlite3SelectDelete(db, pSubquery);
  84359. return 0;
  84360. }
  84361. /*
  84362. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  84363. ** element of the source-list passed as the second argument.
  84364. */
  84365. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  84366. assert( pIndexedBy!=0 );
  84367. if( p && ALWAYS(p->nSrc>0) ){
  84368. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  84369. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  84370. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  84371. /* A "NOT INDEXED" clause was supplied. See parse.y
  84372. ** construct "indexed_opt" for details. */
  84373. pItem->notIndexed = 1;
  84374. }else{
  84375. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  84376. }
  84377. }
  84378. }
  84379. /*
  84380. ** When building up a FROM clause in the parser, the join operator
  84381. ** is initially attached to the left operand. But the code generator
  84382. ** expects the join operator to be on the right operand. This routine
  84383. ** Shifts all join operators from left to right for an entire FROM
  84384. ** clause.
  84385. **
  84386. ** Example: Suppose the join is like this:
  84387. **
  84388. ** A natural cross join B
  84389. **
  84390. ** The operator is "natural cross join". The A and B operands are stored
  84391. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  84392. ** operator with A. This routine shifts that operator over to B.
  84393. */
  84394. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  84395. if( p ){
  84396. int i;
  84397. assert( p->a || p->nSrc==0 );
  84398. for(i=p->nSrc-1; i>0; i--){
  84399. p->a[i].jointype = p->a[i-1].jointype;
  84400. }
  84401. p->a[0].jointype = 0;
  84402. }
  84403. }
  84404. /*
  84405. ** Begin a transaction
  84406. */
  84407. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  84408. sqlite3 *db;
  84409. Vdbe *v;
  84410. int i;
  84411. assert( pParse!=0 );
  84412. db = pParse->db;
  84413. assert( db!=0 );
  84414. /* if( db->aDb[0].pBt==0 ) return; */
  84415. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  84416. return;
  84417. }
  84418. v = sqlite3GetVdbe(pParse);
  84419. if( !v ) return;
  84420. if( type!=TK_DEFERRED ){
  84421. for(i=0; i<db->nDb; i++){
  84422. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  84423. sqlite3VdbeUsesBtree(v, i);
  84424. }
  84425. }
  84426. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  84427. }
  84428. /*
  84429. ** Commit a transaction
  84430. */
  84431. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  84432. Vdbe *v;
  84433. assert( pParse!=0 );
  84434. assert( pParse->db!=0 );
  84435. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  84436. return;
  84437. }
  84438. v = sqlite3GetVdbe(pParse);
  84439. if( v ){
  84440. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  84441. }
  84442. }
  84443. /*
  84444. ** Rollback a transaction
  84445. */
  84446. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  84447. Vdbe *v;
  84448. assert( pParse!=0 );
  84449. assert( pParse->db!=0 );
  84450. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  84451. return;
  84452. }
  84453. v = sqlite3GetVdbe(pParse);
  84454. if( v ){
  84455. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  84456. }
  84457. }
  84458. /*
  84459. ** This function is called by the parser when it parses a command to create,
  84460. ** release or rollback an SQL savepoint.
  84461. */
  84462. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  84463. char *zName = sqlite3NameFromToken(pParse->db, pName);
  84464. if( zName ){
  84465. Vdbe *v = sqlite3GetVdbe(pParse);
  84466. #ifndef SQLITE_OMIT_AUTHORIZATION
  84467. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  84468. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  84469. #endif
  84470. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  84471. sqlite3DbFree(pParse->db, zName);
  84472. return;
  84473. }
  84474. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  84475. }
  84476. }
  84477. /*
  84478. ** Make sure the TEMP database is open and available for use. Return
  84479. ** the number of errors. Leave any error messages in the pParse structure.
  84480. */
  84481. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  84482. sqlite3 *db = pParse->db;
  84483. if( db->aDb[1].pBt==0 && !pParse->explain ){
  84484. int rc;
  84485. Btree *pBt;
  84486. static const int flags =
  84487. SQLITE_OPEN_READWRITE |
  84488. SQLITE_OPEN_CREATE |
  84489. SQLITE_OPEN_EXCLUSIVE |
  84490. SQLITE_OPEN_DELETEONCLOSE |
  84491. SQLITE_OPEN_TEMP_DB;
  84492. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  84493. if( rc!=SQLITE_OK ){
  84494. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  84495. "file for storing temporary tables");
  84496. pParse->rc = rc;
  84497. return 1;
  84498. }
  84499. db->aDb[1].pBt = pBt;
  84500. assert( db->aDb[1].pSchema );
  84501. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  84502. db->mallocFailed = 1;
  84503. return 1;
  84504. }
  84505. }
  84506. return 0;
  84507. }
  84508. /*
  84509. ** Generate VDBE code that will verify the schema cookie and start
  84510. ** a read-transaction for all named database files.
  84511. **
  84512. ** It is important that all schema cookies be verified and all
  84513. ** read transactions be started before anything else happens in
  84514. ** the VDBE program. But this routine can be called after much other
  84515. ** code has been generated. So here is what we do:
  84516. **
  84517. ** The first time this routine is called, we code an OP_Goto that
  84518. ** will jump to a subroutine at the end of the program. Then we
  84519. ** record every database that needs its schema verified in the
  84520. ** pParse->cookieMask field. Later, after all other code has been
  84521. ** generated, the subroutine that does the cookie verifications and
  84522. ** starts the transactions will be coded and the OP_Goto P2 value
  84523. ** will be made to point to that subroutine. The generation of the
  84524. ** cookie verification subroutine code happens in sqlite3FinishCoding().
  84525. **
  84526. ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
  84527. ** schema on any databases. This can be used to position the OP_Goto
  84528. ** early in the code, before we know if any database tables will be used.
  84529. */
  84530. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  84531. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84532. #ifndef SQLITE_OMIT_TRIGGER
  84533. if( pToplevel!=pParse ){
  84534. /* This branch is taken if a trigger is currently being coded. In this
  84535. ** case, set cookieGoto to a non-zero value to show that this function
  84536. ** has been called. This is used by the sqlite3ExprCodeConstants()
  84537. ** function. */
  84538. pParse->cookieGoto = -1;
  84539. }
  84540. #endif
  84541. if( pToplevel->cookieGoto==0 ){
  84542. Vdbe *v = sqlite3GetVdbe(pToplevel);
  84543. if( v==0 ) return; /* This only happens if there was a prior error */
  84544. pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
  84545. }
  84546. if( iDb>=0 ){
  84547. sqlite3 *db = pToplevel->db;
  84548. yDbMask mask;
  84549. assert( iDb<db->nDb );
  84550. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  84551. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  84552. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84553. mask = ((yDbMask)1)<<iDb;
  84554. if( (pToplevel->cookieMask & mask)==0 ){
  84555. pToplevel->cookieMask |= mask;
  84556. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  84557. if( !OMIT_TEMPDB && iDb==1 ){
  84558. sqlite3OpenTempDatabase(pToplevel);
  84559. }
  84560. }
  84561. }
  84562. }
  84563. /*
  84564. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  84565. ** attached database. Otherwise, invoke it for the database named zDb only.
  84566. */
  84567. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  84568. sqlite3 *db = pParse->db;
  84569. int i;
  84570. for(i=0; i<db->nDb; i++){
  84571. Db *pDb = &db->aDb[i];
  84572. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  84573. sqlite3CodeVerifySchema(pParse, i);
  84574. }
  84575. }
  84576. }
  84577. /*
  84578. ** Generate VDBE code that prepares for doing an operation that
  84579. ** might change the database.
  84580. **
  84581. ** This routine starts a new transaction if we are not already within
  84582. ** a transaction. If we are already within a transaction, then a checkpoint
  84583. ** is set if the setStatement parameter is true. A checkpoint should
  84584. ** be set for operations that might fail (due to a constraint) part of
  84585. ** the way through and which will need to undo some writes without having to
  84586. ** rollback the whole transaction. For operations where all constraints
  84587. ** can be checked before any changes are made to the database, it is never
  84588. ** necessary to undo a write and the checkpoint should not be set.
  84589. */
  84590. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  84591. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84592. sqlite3CodeVerifySchema(pParse, iDb);
  84593. pToplevel->writeMask |= ((yDbMask)1)<<iDb;
  84594. pToplevel->isMultiWrite |= setStatement;
  84595. }
  84596. /*
  84597. ** Indicate that the statement currently under construction might write
  84598. ** more than one entry (example: deleting one row then inserting another,
  84599. ** inserting multiple rows in a table, or inserting a row and index entries.)
  84600. ** If an abort occurs after some of these writes have completed, then it will
  84601. ** be necessary to undo the completed writes.
  84602. */
  84603. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  84604. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84605. pToplevel->isMultiWrite = 1;
  84606. }
  84607. /*
  84608. ** The code generator calls this routine if is discovers that it is
  84609. ** possible to abort a statement prior to completion. In order to
  84610. ** perform this abort without corrupting the database, we need to make
  84611. ** sure that the statement is protected by a statement transaction.
  84612. **
  84613. ** Technically, we only need to set the mayAbort flag if the
  84614. ** isMultiWrite flag was previously set. There is a time dependency
  84615. ** such that the abort must occur after the multiwrite. This makes
  84616. ** some statements involving the REPLACE conflict resolution algorithm
  84617. ** go a little faster. But taking advantage of this time dependency
  84618. ** makes it more difficult to prove that the code is correct (in
  84619. ** particular, it prevents us from writing an effective
  84620. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  84621. ** to take the safe route and skip the optimization.
  84622. */
  84623. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  84624. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  84625. pToplevel->mayAbort = 1;
  84626. }
  84627. /*
  84628. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  84629. ** error. The onError parameter determines which (if any) of the statement
  84630. ** and/or current transaction is rolled back.
  84631. */
  84632. SQLITE_PRIVATE void sqlite3HaltConstraint(
  84633. Parse *pParse, /* Parsing context */
  84634. int errCode, /* extended error code */
  84635. int onError, /* Constraint type */
  84636. char *p4, /* Error message */
  84637. int p4type /* P4_STATIC or P4_TRANSIENT */
  84638. ){
  84639. Vdbe *v = sqlite3GetVdbe(pParse);
  84640. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  84641. if( onError==OE_Abort ){
  84642. sqlite3MayAbort(pParse);
  84643. }
  84644. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  84645. }
  84646. /*
  84647. ** Check to see if pIndex uses the collating sequence pColl. Return
  84648. ** true if it does and false if it does not.
  84649. */
  84650. #ifndef SQLITE_OMIT_REINDEX
  84651. static int collationMatch(const char *zColl, Index *pIndex){
  84652. int i;
  84653. assert( zColl!=0 );
  84654. for(i=0; i<pIndex->nColumn; i++){
  84655. const char *z = pIndex->azColl[i];
  84656. assert( z!=0 );
  84657. if( 0==sqlite3StrICmp(z, zColl) ){
  84658. return 1;
  84659. }
  84660. }
  84661. return 0;
  84662. }
  84663. #endif
  84664. /*
  84665. ** Recompute all indices of pTab that use the collating sequence pColl.
  84666. ** If pColl==0 then recompute all indices of pTab.
  84667. */
  84668. #ifndef SQLITE_OMIT_REINDEX
  84669. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  84670. Index *pIndex; /* An index associated with pTab */
  84671. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  84672. if( zColl==0 || collationMatch(zColl, pIndex) ){
  84673. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84674. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84675. sqlite3RefillIndex(pParse, pIndex, -1);
  84676. }
  84677. }
  84678. }
  84679. #endif
  84680. /*
  84681. ** Recompute all indices of all tables in all databases where the
  84682. ** indices use the collating sequence pColl. If pColl==0 then recompute
  84683. ** all indices everywhere.
  84684. */
  84685. #ifndef SQLITE_OMIT_REINDEX
  84686. static void reindexDatabases(Parse *pParse, char const *zColl){
  84687. Db *pDb; /* A single database */
  84688. int iDb; /* The database index number */
  84689. sqlite3 *db = pParse->db; /* The database connection */
  84690. HashElem *k; /* For looping over tables in pDb */
  84691. Table *pTab; /* A table in the database */
  84692. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  84693. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  84694. assert( pDb!=0 );
  84695. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  84696. pTab = (Table*)sqliteHashData(k);
  84697. reindexTable(pParse, pTab, zColl);
  84698. }
  84699. }
  84700. }
  84701. #endif
  84702. /*
  84703. ** Generate code for the REINDEX command.
  84704. **
  84705. ** REINDEX -- 1
  84706. ** REINDEX <collation> -- 2
  84707. ** REINDEX ?<database>.?<tablename> -- 3
  84708. ** REINDEX ?<database>.?<indexname> -- 4
  84709. **
  84710. ** Form 1 causes all indices in all attached databases to be rebuilt.
  84711. ** Form 2 rebuilds all indices in all databases that use the named
  84712. ** collating function. Forms 3 and 4 rebuild the named index or all
  84713. ** indices associated with the named table.
  84714. */
  84715. #ifndef SQLITE_OMIT_REINDEX
  84716. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  84717. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  84718. char *z; /* Name of a table or index */
  84719. const char *zDb; /* Name of the database */
  84720. Table *pTab; /* A table in the database */
  84721. Index *pIndex; /* An index associated with pTab */
  84722. int iDb; /* The database index number */
  84723. sqlite3 *db = pParse->db; /* The database connection */
  84724. Token *pObjName; /* Name of the table or index to be reindexed */
  84725. /* Read the database schema. If an error occurs, leave an error message
  84726. ** and code in pParse and return NULL. */
  84727. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  84728. return;
  84729. }
  84730. if( pName1==0 ){
  84731. reindexDatabases(pParse, 0);
  84732. return;
  84733. }else if( NEVER(pName2==0) || pName2->z==0 ){
  84734. char *zColl;
  84735. assert( pName1->z );
  84736. zColl = sqlite3NameFromToken(pParse->db, pName1);
  84737. if( !zColl ) return;
  84738. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  84739. if( pColl ){
  84740. reindexDatabases(pParse, zColl);
  84741. sqlite3DbFree(db, zColl);
  84742. return;
  84743. }
  84744. sqlite3DbFree(db, zColl);
  84745. }
  84746. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  84747. if( iDb<0 ) return;
  84748. z = sqlite3NameFromToken(db, pObjName);
  84749. if( z==0 ) return;
  84750. zDb = db->aDb[iDb].zName;
  84751. pTab = sqlite3FindTable(db, z, zDb);
  84752. if( pTab ){
  84753. reindexTable(pParse, pTab, 0);
  84754. sqlite3DbFree(db, z);
  84755. return;
  84756. }
  84757. pIndex = sqlite3FindIndex(db, z, zDb);
  84758. sqlite3DbFree(db, z);
  84759. if( pIndex ){
  84760. sqlite3BeginWriteOperation(pParse, 0, iDb);
  84761. sqlite3RefillIndex(pParse, pIndex, -1);
  84762. return;
  84763. }
  84764. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  84765. }
  84766. #endif
  84767. /*
  84768. ** Return a dynamicly allocated KeyInfo structure that can be used
  84769. ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
  84770. **
  84771. ** If successful, a pointer to the new structure is returned. In this case
  84772. ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
  84773. ** pointer. If an error occurs (out of memory or missing collation
  84774. ** sequence), NULL is returned and the state of pParse updated to reflect
  84775. ** the error.
  84776. */
  84777. SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
  84778. int i;
  84779. int nCol = pIdx->nColumn;
  84780. KeyInfo *pKey;
  84781. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol);
  84782. if( pKey ){
  84783. for(i=0; i<nCol; i++){
  84784. char *zColl = pIdx->azColl[i];
  84785. assert( zColl );
  84786. pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
  84787. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  84788. }
  84789. }
  84790. if( pParse->nErr ){
  84791. sqlite3DbFree(pParse->db, pKey);
  84792. pKey = 0;
  84793. }
  84794. return pKey;
  84795. }
  84796. /************** End of build.c ***********************************************/
  84797. /************** Begin file callback.c ****************************************/
  84798. /*
  84799. ** 2005 May 23
  84800. **
  84801. ** The author disclaims copyright to this source code. In place of
  84802. ** a legal notice, here is a blessing:
  84803. **
  84804. ** May you do good and not evil.
  84805. ** May you find forgiveness for yourself and forgive others.
  84806. ** May you share freely, never taking more than you give.
  84807. **
  84808. *************************************************************************
  84809. **
  84810. ** This file contains functions used to access the internal hash tables
  84811. ** of user defined functions and collation sequences.
  84812. */
  84813. /*
  84814. ** Invoke the 'collation needed' callback to request a collation sequence
  84815. ** in the encoding enc of name zName, length nName.
  84816. */
  84817. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  84818. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  84819. if( db->xCollNeeded ){
  84820. char *zExternal = sqlite3DbStrDup(db, zName);
  84821. if( !zExternal ) return;
  84822. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  84823. sqlite3DbFree(db, zExternal);
  84824. }
  84825. #ifndef SQLITE_OMIT_UTF16
  84826. if( db->xCollNeeded16 ){
  84827. char const *zExternal;
  84828. sqlite3_value *pTmp = sqlite3ValueNew(db);
  84829. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  84830. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  84831. if( zExternal ){
  84832. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  84833. }
  84834. sqlite3ValueFree(pTmp);
  84835. }
  84836. #endif
  84837. }
  84838. /*
  84839. ** This routine is called if the collation factory fails to deliver a
  84840. ** collation function in the best encoding but there may be other versions
  84841. ** of this collation function (for other text encodings) available. Use one
  84842. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  84843. ** possible.
  84844. */
  84845. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  84846. CollSeq *pColl2;
  84847. char *z = pColl->zName;
  84848. int i;
  84849. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  84850. for(i=0; i<3; i++){
  84851. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  84852. if( pColl2->xCmp!=0 ){
  84853. memcpy(pColl, pColl2, sizeof(CollSeq));
  84854. pColl->xDel = 0; /* Do not copy the destructor */
  84855. return SQLITE_OK;
  84856. }
  84857. }
  84858. return SQLITE_ERROR;
  84859. }
  84860. /*
  84861. ** This function is responsible for invoking the collation factory callback
  84862. ** or substituting a collation sequence of a different encoding when the
  84863. ** requested collation sequence is not available in the desired encoding.
  84864. **
  84865. ** If it is not NULL, then pColl must point to the database native encoding
  84866. ** collation sequence with name zName, length nName.
  84867. **
  84868. ** The return value is either the collation sequence to be used in database
  84869. ** db for collation type name zName, length nName, or NULL, if no collation
  84870. ** sequence can be found. If no collation is found, leave an error message.
  84871. **
  84872. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  84873. */
  84874. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  84875. Parse *pParse, /* Parsing context */
  84876. u8 enc, /* The desired encoding for the collating sequence */
  84877. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  84878. const char *zName /* Collating sequence name */
  84879. ){
  84880. CollSeq *p;
  84881. sqlite3 *db = pParse->db;
  84882. p = pColl;
  84883. if( !p ){
  84884. p = sqlite3FindCollSeq(db, enc, zName, 0);
  84885. }
  84886. if( !p || !p->xCmp ){
  84887. /* No collation sequence of this type for this encoding is registered.
  84888. ** Call the collation factory to see if it can supply us with one.
  84889. */
  84890. callCollNeeded(db, enc, zName);
  84891. p = sqlite3FindCollSeq(db, enc, zName, 0);
  84892. }
  84893. if( p && !p->xCmp && synthCollSeq(db, p) ){
  84894. p = 0;
  84895. }
  84896. assert( !p || p->xCmp );
  84897. if( p==0 ){
  84898. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  84899. }
  84900. return p;
  84901. }
  84902. /*
  84903. ** This routine is called on a collation sequence before it is used to
  84904. ** check that it is defined. An undefined collation sequence exists when
  84905. ** a database is loaded that contains references to collation sequences
  84906. ** that have not been defined by sqlite3_create_collation() etc.
  84907. **
  84908. ** If required, this routine calls the 'collation needed' callback to
  84909. ** request a definition of the collating sequence. If this doesn't work,
  84910. ** an equivalent collating sequence that uses a text encoding different
  84911. ** from the main database is substituted, if one is available.
  84912. */
  84913. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  84914. if( pColl ){
  84915. const char *zName = pColl->zName;
  84916. sqlite3 *db = pParse->db;
  84917. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  84918. if( !p ){
  84919. return SQLITE_ERROR;
  84920. }
  84921. assert( p==pColl );
  84922. }
  84923. return SQLITE_OK;
  84924. }
  84925. /*
  84926. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  84927. ** specified by zName and nName is not found and parameter 'create' is
  84928. ** true, then create a new entry. Otherwise return NULL.
  84929. **
  84930. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  84931. ** array of three CollSeq structures. The first is the collation sequence
  84932. ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  84933. **
  84934. ** Stored immediately after the three collation sequences is a copy of
  84935. ** the collation sequence name. A pointer to this string is stored in
  84936. ** each collation sequence structure.
  84937. */
  84938. static CollSeq *findCollSeqEntry(
  84939. sqlite3 *db, /* Database connection */
  84940. const char *zName, /* Name of the collating sequence */
  84941. int create /* Create a new entry if true */
  84942. ){
  84943. CollSeq *pColl;
  84944. int nName = sqlite3Strlen30(zName);
  84945. pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  84946. if( 0==pColl && create ){
  84947. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
  84948. if( pColl ){
  84949. CollSeq *pDel = 0;
  84950. pColl[0].zName = (char*)&pColl[3];
  84951. pColl[0].enc = SQLITE_UTF8;
  84952. pColl[1].zName = (char*)&pColl[3];
  84953. pColl[1].enc = SQLITE_UTF16LE;
  84954. pColl[2].zName = (char*)&pColl[3];
  84955. pColl[2].enc = SQLITE_UTF16BE;
  84956. memcpy(pColl[0].zName, zName, nName);
  84957. pColl[0].zName[nName] = 0;
  84958. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
  84959. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  84960. ** return the pColl pointer to be deleted (because it wasn't added
  84961. ** to the hash table).
  84962. */
  84963. assert( pDel==0 || pDel==pColl );
  84964. if( pDel!=0 ){
  84965. db->mallocFailed = 1;
  84966. sqlite3DbFree(db, pDel);
  84967. pColl = 0;
  84968. }
  84969. }
  84970. }
  84971. return pColl;
  84972. }
  84973. /*
  84974. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  84975. ** Return the CollSeq* pointer for the collation sequence named zName
  84976. ** for the encoding 'enc' from the database 'db'.
  84977. **
  84978. ** If the entry specified is not found and 'create' is true, then create a
  84979. ** new entry. Otherwise return NULL.
  84980. **
  84981. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  84982. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  84983. ** if necessary and generates an error message if the collating sequence
  84984. ** cannot be found.
  84985. **
  84986. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  84987. */
  84988. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  84989. sqlite3 *db,
  84990. u8 enc,
  84991. const char *zName,
  84992. int create
  84993. ){
  84994. CollSeq *pColl;
  84995. if( zName ){
  84996. pColl = findCollSeqEntry(db, zName, create);
  84997. }else{
  84998. pColl = db->pDfltColl;
  84999. }
  85000. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  85001. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  85002. if( pColl ) pColl += enc-1;
  85003. return pColl;
  85004. }
  85005. /* During the search for the best function definition, this procedure
  85006. ** is called to test how well the function passed as the first argument
  85007. ** matches the request for a function with nArg arguments in a system
  85008. ** that uses encoding enc. The value returned indicates how well the
  85009. ** request is matched. A higher value indicates a better match.
  85010. **
  85011. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  85012. ** is also -1. In other words, we are searching for a function that
  85013. ** takes a variable number of arguments.
  85014. **
  85015. ** If nArg is -2 that means that we are searching for any function
  85016. ** regardless of the number of arguments it uses, so return a positive
  85017. ** match score for any
  85018. **
  85019. ** The returned value is always between 0 and 6, as follows:
  85020. **
  85021. ** 0: Not a match.
  85022. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  85023. ** 2: UTF16 byte order change required and function takes any number of args.
  85024. ** 3: encoding matches and function takes any number of arguments
  85025. ** 4: UTF8/16 conversion required - argument count matches exactly
  85026. ** 5: UTF16 byte order conversion required - argument count matches exactly
  85027. ** 6: Perfect match: encoding and argument count match exactly.
  85028. **
  85029. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  85030. ** a perfect match and any function with both xStep and xFunc NULL is
  85031. ** a non-match.
  85032. */
  85033. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  85034. static int matchQuality(
  85035. FuncDef *p, /* The function we are evaluating for match quality */
  85036. int nArg, /* Desired number of arguments. (-1)==any */
  85037. u8 enc /* Desired text encoding */
  85038. ){
  85039. int match;
  85040. /* nArg of -2 is a special case */
  85041. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  85042. /* Wrong number of arguments means "no match" */
  85043. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  85044. /* Give a better score to a function with a specific number of arguments
  85045. ** than to function that accepts any number of arguments. */
  85046. if( p->nArg==nArg ){
  85047. match = 4;
  85048. }else{
  85049. match = 1;
  85050. }
  85051. /* Bonus points if the text encoding matches */
  85052. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  85053. match += 2; /* Exact encoding match */
  85054. }else if( (enc & p->funcFlags & 2)!=0 ){
  85055. match += 1; /* Both are UTF16, but with different byte orders */
  85056. }
  85057. return match;
  85058. }
  85059. /*
  85060. ** Search a FuncDefHash for a function with the given name. Return
  85061. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  85062. */
  85063. static FuncDef *functionSearch(
  85064. FuncDefHash *pHash, /* Hash table to search */
  85065. int h, /* Hash of the name */
  85066. const char *zFunc, /* Name of function */
  85067. int nFunc /* Number of bytes in zFunc */
  85068. ){
  85069. FuncDef *p;
  85070. for(p=pHash->a[h]; p; p=p->pHash){
  85071. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  85072. return p;
  85073. }
  85074. }
  85075. return 0;
  85076. }
  85077. /*
  85078. ** Insert a new FuncDef into a FuncDefHash hash table.
  85079. */
  85080. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  85081. FuncDefHash *pHash, /* The hash table into which to insert */
  85082. FuncDef *pDef /* The function definition to insert */
  85083. ){
  85084. FuncDef *pOther;
  85085. int nName = sqlite3Strlen30(pDef->zName);
  85086. u8 c1 = (u8)pDef->zName[0];
  85087. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  85088. pOther = functionSearch(pHash, h, pDef->zName, nName);
  85089. if( pOther ){
  85090. assert( pOther!=pDef && pOther->pNext!=pDef );
  85091. pDef->pNext = pOther->pNext;
  85092. pOther->pNext = pDef;
  85093. }else{
  85094. pDef->pNext = 0;
  85095. pDef->pHash = pHash->a[h];
  85096. pHash->a[h] = pDef;
  85097. }
  85098. }
  85099. /*
  85100. ** Locate a user function given a name, a number of arguments and a flag
  85101. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  85102. ** pointer to the FuncDef structure that defines that function, or return
  85103. ** NULL if the function does not exist.
  85104. **
  85105. ** If the createFlag argument is true, then a new (blank) FuncDef
  85106. ** structure is created and liked into the "db" structure if a
  85107. ** no matching function previously existed.
  85108. **
  85109. ** If nArg is -2, then the first valid function found is returned. A
  85110. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  85111. ** case is used to see if zName is a valid function name for some number
  85112. ** of arguments. If nArg is -2, then createFlag must be 0.
  85113. **
  85114. ** If createFlag is false, then a function with the required name and
  85115. ** number of arguments may be returned even if the eTextRep flag does not
  85116. ** match that requested.
  85117. */
  85118. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  85119. sqlite3 *db, /* An open database */
  85120. const char *zName, /* Name of the function. Not null-terminated */
  85121. int nName, /* Number of characters in the name */
  85122. int nArg, /* Number of arguments. -1 means any number */
  85123. u8 enc, /* Preferred text encoding */
  85124. u8 createFlag /* Create new entry if true and does not otherwise exist */
  85125. ){
  85126. FuncDef *p; /* Iterator variable */
  85127. FuncDef *pBest = 0; /* Best match found so far */
  85128. int bestScore = 0; /* Score of best match */
  85129. int h; /* Hash value */
  85130. assert( nArg>=(-2) );
  85131. assert( nArg>=(-1) || createFlag==0 );
  85132. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  85133. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  85134. /* First search for a match amongst the application-defined functions.
  85135. */
  85136. p = functionSearch(&db->aFunc, h, zName, nName);
  85137. while( p ){
  85138. int score = matchQuality(p, nArg, enc);
  85139. if( score>bestScore ){
  85140. pBest = p;
  85141. bestScore = score;
  85142. }
  85143. p = p->pNext;
  85144. }
  85145. /* If no match is found, search the built-in functions.
  85146. **
  85147. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  85148. ** functions even if a prior app-defined function was found. And give
  85149. ** priority to built-in functions.
  85150. **
  85151. ** Except, if createFlag is true, that means that we are trying to
  85152. ** install a new function. Whatever FuncDef structure is returned it will
  85153. ** have fields overwritten with new information appropriate for the
  85154. ** new function. But the FuncDefs for built-in functions are read-only.
  85155. ** So we must not search for built-ins when creating a new function.
  85156. */
  85157. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  85158. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  85159. bestScore = 0;
  85160. p = functionSearch(pHash, h, zName, nName);
  85161. while( p ){
  85162. int score = matchQuality(p, nArg, enc);
  85163. if( score>bestScore ){
  85164. pBest = p;
  85165. bestScore = score;
  85166. }
  85167. p = p->pNext;
  85168. }
  85169. }
  85170. /* If the createFlag parameter is true and the search did not reveal an
  85171. ** exact match for the name, number of arguments and encoding, then add a
  85172. ** new entry to the hash table and return it.
  85173. */
  85174. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  85175. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  85176. pBest->zName = (char *)&pBest[1];
  85177. pBest->nArg = (u16)nArg;
  85178. pBest->funcFlags = enc;
  85179. memcpy(pBest->zName, zName, nName);
  85180. pBest->zName[nName] = 0;
  85181. sqlite3FuncDefInsert(&db->aFunc, pBest);
  85182. }
  85183. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  85184. return pBest;
  85185. }
  85186. return 0;
  85187. }
  85188. /*
  85189. ** Free all resources held by the schema structure. The void* argument points
  85190. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  85191. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  85192. ** of the schema hash tables).
  85193. **
  85194. ** The Schema.cache_size variable is not cleared.
  85195. */
  85196. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  85197. Hash temp1;
  85198. Hash temp2;
  85199. HashElem *pElem;
  85200. Schema *pSchema = (Schema *)p;
  85201. temp1 = pSchema->tblHash;
  85202. temp2 = pSchema->trigHash;
  85203. sqlite3HashInit(&pSchema->trigHash);
  85204. sqlite3HashClear(&pSchema->idxHash);
  85205. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  85206. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  85207. }
  85208. sqlite3HashClear(&temp2);
  85209. sqlite3HashInit(&pSchema->tblHash);
  85210. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  85211. Table *pTab = sqliteHashData(pElem);
  85212. sqlite3DeleteTable(0, pTab);
  85213. }
  85214. sqlite3HashClear(&temp1);
  85215. sqlite3HashClear(&pSchema->fkeyHash);
  85216. pSchema->pSeqTab = 0;
  85217. if( pSchema->flags & DB_SchemaLoaded ){
  85218. pSchema->iGeneration++;
  85219. pSchema->flags &= ~DB_SchemaLoaded;
  85220. }
  85221. }
  85222. /*
  85223. ** Find and return the schema associated with a BTree. Create
  85224. ** a new one if necessary.
  85225. */
  85226. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  85227. Schema * p;
  85228. if( pBt ){
  85229. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  85230. }else{
  85231. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  85232. }
  85233. if( !p ){
  85234. db->mallocFailed = 1;
  85235. }else if ( 0==p->file_format ){
  85236. sqlite3HashInit(&p->tblHash);
  85237. sqlite3HashInit(&p->idxHash);
  85238. sqlite3HashInit(&p->trigHash);
  85239. sqlite3HashInit(&p->fkeyHash);
  85240. p->enc = SQLITE_UTF8;
  85241. }
  85242. return p;
  85243. }
  85244. /************** End of callback.c ********************************************/
  85245. /************** Begin file delete.c ******************************************/
  85246. /*
  85247. ** 2001 September 15
  85248. **
  85249. ** The author disclaims copyright to this source code. In place of
  85250. ** a legal notice, here is a blessing:
  85251. **
  85252. ** May you do good and not evil.
  85253. ** May you find forgiveness for yourself and forgive others.
  85254. ** May you share freely, never taking more than you give.
  85255. **
  85256. *************************************************************************
  85257. ** This file contains C code routines that are called by the parser
  85258. ** in order to generate code for DELETE FROM statements.
  85259. */
  85260. /*
  85261. ** While a SrcList can in general represent multiple tables and subqueries
  85262. ** (as in the FROM clause of a SELECT statement) in this case it contains
  85263. ** the name of a single table, as one might find in an INSERT, DELETE,
  85264. ** or UPDATE statement. Look up that table in the symbol table and
  85265. ** return a pointer. Set an error message and return NULL if the table
  85266. ** name is not found or if any other error occurs.
  85267. **
  85268. ** The following fields are initialized appropriate in pSrc:
  85269. **
  85270. ** pSrc->a[0].pTab Pointer to the Table object
  85271. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  85272. **
  85273. */
  85274. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  85275. struct SrcList_item *pItem = pSrc->a;
  85276. Table *pTab;
  85277. assert( pItem && pSrc->nSrc==1 );
  85278. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  85279. sqlite3DeleteTable(pParse->db, pItem->pTab);
  85280. pItem->pTab = pTab;
  85281. if( pTab ){
  85282. pTab->nRef++;
  85283. }
  85284. if( sqlite3IndexedByLookup(pParse, pItem) ){
  85285. pTab = 0;
  85286. }
  85287. return pTab;
  85288. }
  85289. /*
  85290. ** Check to make sure the given table is writable. If it is not
  85291. ** writable, generate an error message and return 1. If it is
  85292. ** writable return 0;
  85293. */
  85294. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  85295. /* A table is not writable under the following circumstances:
  85296. **
  85297. ** 1) It is a virtual table and no implementation of the xUpdate method
  85298. ** has been provided, or
  85299. ** 2) It is a system table (i.e. sqlite_master), this call is not
  85300. ** part of a nested parse and writable_schema pragma has not
  85301. ** been specified.
  85302. **
  85303. ** In either case leave an error message in pParse and return non-zero.
  85304. */
  85305. if( ( IsVirtual(pTab)
  85306. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  85307. || ( (pTab->tabFlags & TF_Readonly)!=0
  85308. && (pParse->db->flags & SQLITE_WriteSchema)==0
  85309. && pParse->nested==0 )
  85310. ){
  85311. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  85312. return 1;
  85313. }
  85314. #ifndef SQLITE_OMIT_VIEW
  85315. if( !viewOk && pTab->pSelect ){
  85316. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  85317. return 1;
  85318. }
  85319. #endif
  85320. return 0;
  85321. }
  85322. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  85323. /*
  85324. ** Evaluate a view and store its result in an ephemeral table. The
  85325. ** pWhere argument is an optional WHERE clause that restricts the
  85326. ** set of rows in the view that are to be added to the ephemeral table.
  85327. */
  85328. SQLITE_PRIVATE void sqlite3MaterializeView(
  85329. Parse *pParse, /* Parsing context */
  85330. Table *pView, /* View definition */
  85331. Expr *pWhere, /* Optional WHERE clause to be added */
  85332. int iCur /* Cursor number for ephemerial table */
  85333. ){
  85334. SelectDest dest;
  85335. Select *pSel;
  85336. SrcList *pFrom;
  85337. sqlite3 *db = pParse->db;
  85338. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  85339. pWhere = sqlite3ExprDup(db, pWhere, 0);
  85340. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  85341. if( pFrom ){
  85342. assert( pFrom->nSrc==1 );
  85343. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  85344. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  85345. assert( pFrom->a[0].pOn==0 );
  85346. assert( pFrom->a[0].pUsing==0 );
  85347. }
  85348. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  85349. if( pSel ) pSel->selFlags |= SF_Materialize;
  85350. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  85351. sqlite3Select(pParse, pSel, &dest);
  85352. sqlite3SelectDelete(db, pSel);
  85353. }
  85354. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  85355. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  85356. /*
  85357. ** Generate an expression tree to implement the WHERE, ORDER BY,
  85358. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  85359. **
  85360. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  85361. ** \__________________________/
  85362. ** pLimitWhere (pInClause)
  85363. */
  85364. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  85365. Parse *pParse, /* The parser context */
  85366. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  85367. Expr *pWhere, /* The WHERE clause. May be null */
  85368. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  85369. Expr *pLimit, /* The LIMIT clause. May be null */
  85370. Expr *pOffset, /* The OFFSET clause. May be null */
  85371. char *zStmtType /* Either DELETE or UPDATE. For error messages. */
  85372. ){
  85373. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  85374. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  85375. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  85376. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  85377. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  85378. Select *pSelect = NULL; /* Complete SELECT tree */
  85379. /* Check that there isn't an ORDER BY without a LIMIT clause.
  85380. */
  85381. if( pOrderBy && (pLimit == 0) ) {
  85382. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  85383. goto limit_where_cleanup_2;
  85384. }
  85385. /* We only need to generate a select expression if there
  85386. ** is a limit/offset term to enforce.
  85387. */
  85388. if( pLimit == 0 ) {
  85389. /* if pLimit is null, pOffset will always be null as well. */
  85390. assert( pOffset == 0 );
  85391. return pWhere;
  85392. }
  85393. /* Generate a select expression tree to enforce the limit/offset
  85394. ** term for the DELETE or UPDATE statement. For example:
  85395. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  85396. ** becomes:
  85397. ** DELETE FROM table_a WHERE rowid IN (
  85398. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  85399. ** );
  85400. */
  85401. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  85402. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  85403. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  85404. if( pEList == 0 ) goto limit_where_cleanup_2;
  85405. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  85406. ** and the SELECT subtree. */
  85407. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  85408. if( pSelectSrc == 0 ) {
  85409. sqlite3ExprListDelete(pParse->db, pEList);
  85410. goto limit_where_cleanup_2;
  85411. }
  85412. /* generate the SELECT expression tree. */
  85413. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  85414. pOrderBy,0,pLimit,pOffset);
  85415. if( pSelect == 0 ) return 0;
  85416. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  85417. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  85418. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  85419. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  85420. if( pInClause == 0 ) goto limit_where_cleanup_1;
  85421. pInClause->x.pSelect = pSelect;
  85422. pInClause->flags |= EP_xIsSelect;
  85423. sqlite3ExprSetHeight(pParse, pInClause);
  85424. return pInClause;
  85425. /* something went wrong. clean up anything allocated. */
  85426. limit_where_cleanup_1:
  85427. sqlite3SelectDelete(pParse->db, pSelect);
  85428. return 0;
  85429. limit_where_cleanup_2:
  85430. sqlite3ExprDelete(pParse->db, pWhere);
  85431. sqlite3ExprListDelete(pParse->db, pOrderBy);
  85432. sqlite3ExprDelete(pParse->db, pLimit);
  85433. sqlite3ExprDelete(pParse->db, pOffset);
  85434. return 0;
  85435. }
  85436. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  85437. /*
  85438. ** Generate code for a DELETE FROM statement.
  85439. **
  85440. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  85441. ** \________/ \________________/
  85442. ** pTabList pWhere
  85443. */
  85444. SQLITE_PRIVATE void sqlite3DeleteFrom(
  85445. Parse *pParse, /* The parser context */
  85446. SrcList *pTabList, /* The table from which we should delete things */
  85447. Expr *pWhere /* The WHERE clause. May be null */
  85448. ){
  85449. Vdbe *v; /* The virtual database engine */
  85450. Table *pTab; /* The table from which records will be deleted */
  85451. const char *zDb; /* Name of database holding pTab */
  85452. int end, addr = 0; /* A couple addresses of generated code */
  85453. int i; /* Loop counter */
  85454. WhereInfo *pWInfo; /* Information about the WHERE clause */
  85455. Index *pIdx; /* For looping over indices of the table */
  85456. int iCur; /* VDBE Cursor number for pTab */
  85457. sqlite3 *db; /* Main database structure */
  85458. AuthContext sContext; /* Authorization context */
  85459. NameContext sNC; /* Name context to resolve expressions in */
  85460. int iDb; /* Database number */
  85461. int memCnt = -1; /* Memory cell used for change counting */
  85462. int rcauth; /* Value returned by authorization callback */
  85463. #ifndef SQLITE_OMIT_TRIGGER
  85464. int isView; /* True if attempting to delete from a view */
  85465. Trigger *pTrigger; /* List of table triggers, if required */
  85466. #endif
  85467. memset(&sContext, 0, sizeof(sContext));
  85468. db = pParse->db;
  85469. if( pParse->nErr || db->mallocFailed ){
  85470. goto delete_from_cleanup;
  85471. }
  85472. assert( pTabList->nSrc==1 );
  85473. /* Locate the table which we want to delete. This table has to be
  85474. ** put in an SrcList structure because some of the subroutines we
  85475. ** will be calling are designed to work with multiple tables and expect
  85476. ** an SrcList* parameter instead of just a Table* parameter.
  85477. */
  85478. pTab = sqlite3SrcListLookup(pParse, pTabList);
  85479. if( pTab==0 ) goto delete_from_cleanup;
  85480. /* Figure out if we have any triggers and if the table being
  85481. ** deleted from is a view
  85482. */
  85483. #ifndef SQLITE_OMIT_TRIGGER
  85484. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  85485. isView = pTab->pSelect!=0;
  85486. #else
  85487. # define pTrigger 0
  85488. # define isView 0
  85489. #endif
  85490. #ifdef SQLITE_OMIT_VIEW
  85491. # undef isView
  85492. # define isView 0
  85493. #endif
  85494. /* If pTab is really a view, make sure it has been initialized.
  85495. */
  85496. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  85497. goto delete_from_cleanup;
  85498. }
  85499. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  85500. goto delete_from_cleanup;
  85501. }
  85502. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85503. assert( iDb<db->nDb );
  85504. zDb = db->aDb[iDb].zName;
  85505. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  85506. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  85507. if( rcauth==SQLITE_DENY ){
  85508. goto delete_from_cleanup;
  85509. }
  85510. assert(!isView || pTrigger);
  85511. /* Assign cursor number to the table and all its indices.
  85512. */
  85513. assert( pTabList->nSrc==1 );
  85514. iCur = pTabList->a[0].iCursor = pParse->nTab++;
  85515. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85516. pParse->nTab++;
  85517. }
  85518. /* Start the view context
  85519. */
  85520. if( isView ){
  85521. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  85522. }
  85523. /* Begin generating code.
  85524. */
  85525. v = sqlite3GetVdbe(pParse);
  85526. if( v==0 ){
  85527. goto delete_from_cleanup;
  85528. }
  85529. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  85530. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85531. /* If we are trying to delete from a view, realize that view into
  85532. ** a ephemeral table.
  85533. */
  85534. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  85535. if( isView ){
  85536. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  85537. }
  85538. #endif
  85539. /* Resolve the column names in the WHERE clause.
  85540. */
  85541. memset(&sNC, 0, sizeof(sNC));
  85542. sNC.pParse = pParse;
  85543. sNC.pSrcList = pTabList;
  85544. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  85545. goto delete_from_cleanup;
  85546. }
  85547. /* Initialize the counter of the number of rows deleted, if
  85548. ** we are counting rows.
  85549. */
  85550. if( db->flags & SQLITE_CountRows ){
  85551. memCnt = ++pParse->nMem;
  85552. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  85553. }
  85554. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  85555. /* Special case: A DELETE without a WHERE clause deletes everything.
  85556. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  85557. ** this optimization caused the row change count (the value returned by
  85558. ** API function sqlite3_count_changes) to be set incorrectly. */
  85559. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  85560. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  85561. ){
  85562. assert( !isView );
  85563. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  85564. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  85565. pTab->zName, P4_STATIC);
  85566. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85567. assert( pIdx->pSchema==pTab->pSchema );
  85568. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  85569. }
  85570. }else
  85571. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  85572. /* The usual case: There is a WHERE clause so we have to scan through
  85573. ** the table and pick which records to delete.
  85574. */
  85575. {
  85576. int iRowSet = ++pParse->nMem; /* Register for rowset of rows to delete */
  85577. int iRowid = ++pParse->nMem; /* Used for storing rowid values. */
  85578. int regRowid; /* Actual register containing rowids */
  85579. /* Collect rowids of every row to be deleted.
  85580. */
  85581. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  85582. pWInfo = sqlite3WhereBegin(
  85583. pParse, pTabList, pWhere, 0, 0, WHERE_DUPLICATES_OK, 0
  85584. );
  85585. if( pWInfo==0 ) goto delete_from_cleanup;
  85586. regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid, 0);
  85587. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
  85588. if( db->flags & SQLITE_CountRows ){
  85589. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  85590. }
  85591. sqlite3WhereEnd(pWInfo);
  85592. /* Delete every item whose key was written to the list during the
  85593. ** database scan. We have to delete items after the scan is complete
  85594. ** because deleting an item can change the scan order. */
  85595. end = sqlite3VdbeMakeLabel(v);
  85596. /* Unless this is a view, open cursors for the table we are
  85597. ** deleting from and all its indices. If this is a view, then the
  85598. ** only effect this statement has is to fire the INSTEAD OF
  85599. ** triggers. */
  85600. if( !isView ){
  85601. sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
  85602. }
  85603. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
  85604. /* Delete the row */
  85605. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85606. if( IsVirtual(pTab) ){
  85607. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  85608. sqlite3VtabMakeWritable(pParse, pTab);
  85609. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
  85610. sqlite3VdbeChangeP5(v, OE_Abort);
  85611. sqlite3MayAbort(pParse);
  85612. }else
  85613. #endif
  85614. {
  85615. int count = (pParse->nested==0); /* True to count changes */
  85616. sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
  85617. }
  85618. /* End of the delete loop */
  85619. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  85620. sqlite3VdbeResolveLabel(v, end);
  85621. /* Close the cursors open on the table and its indexes. */
  85622. if( !isView && !IsVirtual(pTab) ){
  85623. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  85624. sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
  85625. }
  85626. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  85627. }
  85628. }
  85629. /* Update the sqlite_sequence table by storing the content of the
  85630. ** maximum rowid counter values recorded while inserting into
  85631. ** autoincrement tables.
  85632. */
  85633. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  85634. sqlite3AutoincrementEnd(pParse);
  85635. }
  85636. /* Return the number of rows that were deleted. If this routine is
  85637. ** generating code because of a call to sqlite3NestedParse(), do not
  85638. ** invoke the callback function.
  85639. */
  85640. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  85641. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  85642. sqlite3VdbeSetNumCols(v, 1);
  85643. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  85644. }
  85645. delete_from_cleanup:
  85646. sqlite3AuthContextPop(&sContext);
  85647. sqlite3SrcListDelete(db, pTabList);
  85648. sqlite3ExprDelete(db, pWhere);
  85649. return;
  85650. }
  85651. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  85652. ** thely may interfere with compilation of other functions in this file
  85653. ** (or in another file, if this file becomes part of the amalgamation). */
  85654. #ifdef isView
  85655. #undef isView
  85656. #endif
  85657. #ifdef pTrigger
  85658. #undef pTrigger
  85659. #endif
  85660. /*
  85661. ** This routine generates VDBE code that causes a single row of a
  85662. ** single table to be deleted.
  85663. **
  85664. ** The VDBE must be in a particular state when this routine is called.
  85665. ** These are the requirements:
  85666. **
  85667. ** 1. A read/write cursor pointing to pTab, the table containing the row
  85668. ** to be deleted, must be opened as cursor number $iCur.
  85669. **
  85670. ** 2. Read/write cursors for all indices of pTab must be open as
  85671. ** cursor number base+i for the i-th index.
  85672. **
  85673. ** 3. The record number of the row to be deleted must be stored in
  85674. ** memory cell iRowid.
  85675. **
  85676. ** This routine generates code to remove both the table record and all
  85677. ** index entries that point to that record.
  85678. */
  85679. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  85680. Parse *pParse, /* Parsing context */
  85681. Table *pTab, /* Table containing the row to be deleted */
  85682. int iCur, /* Cursor number for the table */
  85683. int iRowid, /* Memory cell that contains the rowid to delete */
  85684. int count, /* If non-zero, increment the row change counter */
  85685. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  85686. int onconf /* Default ON CONFLICT policy for triggers */
  85687. ){
  85688. Vdbe *v = pParse->pVdbe; /* Vdbe */
  85689. int iOld = 0; /* First register in OLD.* array */
  85690. int iLabel; /* Label resolved to end of generated code */
  85691. /* Vdbe is guaranteed to have been allocated by this stage. */
  85692. assert( v );
  85693. /* Seek cursor iCur to the row to delete. If this row no longer exists
  85694. ** (this can happen if a trigger program has already deleted it), do
  85695. ** not attempt to delete it or fire any DELETE triggers. */
  85696. iLabel = sqlite3VdbeMakeLabel(v);
  85697. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  85698. /* If there are any triggers to fire, allocate a range of registers to
  85699. ** use for the old.* references in the triggers. */
  85700. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  85701. u32 mask; /* Mask of OLD.* columns in use */
  85702. int iCol; /* Iterator used while populating OLD.* */
  85703. /* TODO: Could use temporary registers here. Also could attempt to
  85704. ** avoid copying the contents of the rowid register. */
  85705. mask = sqlite3TriggerColmask(
  85706. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  85707. );
  85708. mask |= sqlite3FkOldmask(pParse, pTab);
  85709. iOld = pParse->nMem+1;
  85710. pParse->nMem += (1 + pTab->nCol);
  85711. /* Populate the OLD.* pseudo-table register array. These values will be
  85712. ** used by any BEFORE and AFTER triggers that exist. */
  85713. sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
  85714. for(iCol=0; iCol<pTab->nCol; iCol++){
  85715. if( mask==0xffffffff || mask&(1<<iCol) ){
  85716. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld+iCol+1);
  85717. }
  85718. }
  85719. /* Invoke BEFORE DELETE trigger programs. */
  85720. sqlite3CodeRowTrigger(pParse, pTrigger,
  85721. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  85722. );
  85723. /* Seek the cursor to the row to be deleted again. It may be that
  85724. ** the BEFORE triggers coded above have already removed the row
  85725. ** being deleted. Do not attempt to delete the row a second time, and
  85726. ** do not fire AFTER triggers. */
  85727. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
  85728. /* Do FK processing. This call checks that any FK constraints that
  85729. ** refer to this table (i.e. constraints attached to other tables)
  85730. ** are not violated by deleting this row. */
  85731. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  85732. }
  85733. /* Delete the index and table entries. Skip this step if pTab is really
  85734. ** a view (in which case the only effect of the DELETE statement is to
  85735. ** fire the INSTEAD OF triggers). */
  85736. if( pTab->pSelect==0 ){
  85737. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
  85738. sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
  85739. if( count ){
  85740. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  85741. }
  85742. }
  85743. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  85744. ** handle rows (possibly in other tables) that refer via a foreign key
  85745. ** to the row just deleted. */
  85746. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  85747. /* Invoke AFTER DELETE trigger programs. */
  85748. sqlite3CodeRowTrigger(pParse, pTrigger,
  85749. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  85750. );
  85751. /* Jump here if the row had already been deleted before any BEFORE
  85752. ** trigger programs were invoked. Or if a trigger program throws a
  85753. ** RAISE(IGNORE) exception. */
  85754. sqlite3VdbeResolveLabel(v, iLabel);
  85755. }
  85756. /*
  85757. ** This routine generates VDBE code that causes the deletion of all
  85758. ** index entries associated with a single row of a single table.
  85759. **
  85760. ** The VDBE must be in a particular state when this routine is called.
  85761. ** These are the requirements:
  85762. **
  85763. ** 1. A read/write cursor pointing to pTab, the table containing the row
  85764. ** to be deleted, must be opened as cursor number "iCur".
  85765. **
  85766. ** 2. Read/write cursors for all indices of pTab must be open as
  85767. ** cursor number iCur+i for the i-th index.
  85768. **
  85769. ** 3. The "iCur" cursor must be pointing to the row that is to be
  85770. ** deleted.
  85771. */
  85772. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  85773. Parse *pParse, /* Parsing and code generating context */
  85774. Table *pTab, /* Table containing the row to be deleted */
  85775. int iCur, /* Cursor number for the table */
  85776. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  85777. ){
  85778. int i;
  85779. Index *pIdx;
  85780. int r1;
  85781. int iPartIdxLabel;
  85782. Vdbe *v = pParse->pVdbe;
  85783. for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  85784. if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
  85785. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0, &iPartIdxLabel);
  85786. sqlite3VdbeAddOp3(v, OP_IdxDelete, iCur+i, r1, pIdx->nColumn+1);
  85787. sqlite3VdbeResolveLabel(v, iPartIdxLabel);
  85788. }
  85789. }
  85790. /*
  85791. ** Generate code that will assemble an index key and put it in register
  85792. ** regOut. The key with be for index pIdx which is an index on pTab.
  85793. ** iCur is the index of a cursor open on the pTab table and pointing to
  85794. ** the entry that needs indexing.
  85795. **
  85796. ** Return a register number which is the first in a block of
  85797. ** registers that holds the elements of the index key. The
  85798. ** block of registers has already been deallocated by the time
  85799. ** this routine returns.
  85800. **
  85801. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  85802. ** to that label if pIdx is a partial index that should be skipped.
  85803. ** A partial index should be skipped if its WHERE clause evaluates
  85804. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  85805. ** will be set to zero which is an empty label that is ignored by
  85806. ** sqlite3VdbeResolveLabel().
  85807. */
  85808. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  85809. Parse *pParse, /* Parsing context */
  85810. Index *pIdx, /* The index for which to generate a key */
  85811. int iCur, /* Cursor number for the pIdx->pTable table */
  85812. int regOut, /* Write the new index key to this register */
  85813. int doMakeRec, /* Run the OP_MakeRecord instruction if true */
  85814. int *piPartIdxLabel /* OUT: Jump to this label to skip partial index */
  85815. ){
  85816. Vdbe *v = pParse->pVdbe;
  85817. int j;
  85818. Table *pTab = pIdx->pTable;
  85819. int regBase;
  85820. int nCol;
  85821. if( piPartIdxLabel ){
  85822. if( pIdx->pPartIdxWhere ){
  85823. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  85824. pParse->iPartIdxTab = iCur;
  85825. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  85826. SQLITE_JUMPIFNULL);
  85827. }else{
  85828. *piPartIdxLabel = 0;
  85829. }
  85830. }
  85831. nCol = pIdx->nColumn;
  85832. regBase = sqlite3GetTempRange(pParse, nCol+1);
  85833. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
  85834. for(j=0; j<nCol; j++){
  85835. int idx = pIdx->aiColumn[j];
  85836. if( idx==pTab->iPKey ){
  85837. sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
  85838. }else{
  85839. sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
  85840. sqlite3ColumnDefault(v, pTab, idx, -1);
  85841. }
  85842. }
  85843. if( doMakeRec ){
  85844. const char *zAff;
  85845. if( pTab->pSelect
  85846. || OptimizationDisabled(pParse->db, SQLITE_IdxRealAsInt)
  85847. ){
  85848. zAff = 0;
  85849. }else{
  85850. zAff = sqlite3IndexAffinityStr(v, pIdx);
  85851. }
  85852. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
  85853. sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
  85854. }
  85855. sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
  85856. return regBase;
  85857. }
  85858. /************** End of delete.c **********************************************/
  85859. /************** Begin file func.c ********************************************/
  85860. /*
  85861. ** 2002 February 23
  85862. **
  85863. ** The author disclaims copyright to this source code. In place of
  85864. ** a legal notice, here is a blessing:
  85865. **
  85866. ** May you do good and not evil.
  85867. ** May you find forgiveness for yourself and forgive others.
  85868. ** May you share freely, never taking more than you give.
  85869. **
  85870. *************************************************************************
  85871. ** This file contains the C functions that implement various SQL
  85872. ** functions of SQLite.
  85873. **
  85874. ** There is only one exported symbol in this file - the function
  85875. ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  85876. ** All other code has file scope.
  85877. */
  85878. /* #include <stdlib.h> */
  85879. /* #include <assert.h> */
  85880. /*
  85881. ** Return the collating function associated with a function.
  85882. */
  85883. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  85884. return context->pColl;
  85885. }
  85886. /*
  85887. ** Indicate that the accumulator load should be skipped on this
  85888. ** iteration of the aggregate loop.
  85889. */
  85890. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  85891. context->skipFlag = 1;
  85892. }
  85893. /*
  85894. ** Implementation of the non-aggregate min() and max() functions
  85895. */
  85896. static void minmaxFunc(
  85897. sqlite3_context *context,
  85898. int argc,
  85899. sqlite3_value **argv
  85900. ){
  85901. int i;
  85902. int mask; /* 0 for min() or 0xffffffff for max() */
  85903. int iBest;
  85904. CollSeq *pColl;
  85905. assert( argc>1 );
  85906. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  85907. pColl = sqlite3GetFuncCollSeq(context);
  85908. assert( pColl );
  85909. assert( mask==-1 || mask==0 );
  85910. iBest = 0;
  85911. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  85912. for(i=1; i<argc; i++){
  85913. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  85914. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  85915. testcase( mask==0 );
  85916. iBest = i;
  85917. }
  85918. }
  85919. sqlite3_result_value(context, argv[iBest]);
  85920. }
  85921. /*
  85922. ** Return the type of the argument.
  85923. */
  85924. static void typeofFunc(
  85925. sqlite3_context *context,
  85926. int NotUsed,
  85927. sqlite3_value **argv
  85928. ){
  85929. const char *z = 0;
  85930. UNUSED_PARAMETER(NotUsed);
  85931. switch( sqlite3_value_type(argv[0]) ){
  85932. case SQLITE_INTEGER: z = "integer"; break;
  85933. case SQLITE_TEXT: z = "text"; break;
  85934. case SQLITE_FLOAT: z = "real"; break;
  85935. case SQLITE_BLOB: z = "blob"; break;
  85936. default: z = "null"; break;
  85937. }
  85938. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  85939. }
  85940. /*
  85941. ** Implementation of the length() function
  85942. */
  85943. static void lengthFunc(
  85944. sqlite3_context *context,
  85945. int argc,
  85946. sqlite3_value **argv
  85947. ){
  85948. int len;
  85949. assert( argc==1 );
  85950. UNUSED_PARAMETER(argc);
  85951. switch( sqlite3_value_type(argv[0]) ){
  85952. case SQLITE_BLOB:
  85953. case SQLITE_INTEGER:
  85954. case SQLITE_FLOAT: {
  85955. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  85956. break;
  85957. }
  85958. case SQLITE_TEXT: {
  85959. const unsigned char *z = sqlite3_value_text(argv[0]);
  85960. if( z==0 ) return;
  85961. len = 0;
  85962. while( *z ){
  85963. len++;
  85964. SQLITE_SKIP_UTF8(z);
  85965. }
  85966. sqlite3_result_int(context, len);
  85967. break;
  85968. }
  85969. default: {
  85970. sqlite3_result_null(context);
  85971. break;
  85972. }
  85973. }
  85974. }
  85975. /*
  85976. ** Implementation of the abs() function.
  85977. **
  85978. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  85979. ** the numeric argument X.
  85980. */
  85981. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  85982. assert( argc==1 );
  85983. UNUSED_PARAMETER(argc);
  85984. switch( sqlite3_value_type(argv[0]) ){
  85985. case SQLITE_INTEGER: {
  85986. i64 iVal = sqlite3_value_int64(argv[0]);
  85987. if( iVal<0 ){
  85988. if( (iVal<<1)==0 ){
  85989. /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
  85990. ** abs(X) throws an integer overflow error since there is no
  85991. ** equivalent positive 64-bit two complement value. */
  85992. sqlite3_result_error(context, "integer overflow", -1);
  85993. return;
  85994. }
  85995. iVal = -iVal;
  85996. }
  85997. sqlite3_result_int64(context, iVal);
  85998. break;
  85999. }
  86000. case SQLITE_NULL: {
  86001. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  86002. sqlite3_result_null(context);
  86003. break;
  86004. }
  86005. default: {
  86006. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  86007. ** something that can be converted into a number, we have:
  86008. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  86009. ** cannot be converted to a numeric value.
  86010. */
  86011. double rVal = sqlite3_value_double(argv[0]);
  86012. if( rVal<0 ) rVal = -rVal;
  86013. sqlite3_result_double(context, rVal);
  86014. break;
  86015. }
  86016. }
  86017. }
  86018. /*
  86019. ** Implementation of the instr() function.
  86020. **
  86021. ** instr(haystack,needle) finds the first occurrence of needle
  86022. ** in haystack and returns the number of previous characters plus 1,
  86023. ** or 0 if needle does not occur within haystack.
  86024. **
  86025. ** If both haystack and needle are BLOBs, then the result is one more than
  86026. ** the number of bytes in haystack prior to the first occurrence of needle,
  86027. ** or 0 if needle never occurs in haystack.
  86028. */
  86029. static void instrFunc(
  86030. sqlite3_context *context,
  86031. int argc,
  86032. sqlite3_value **argv
  86033. ){
  86034. const unsigned char *zHaystack;
  86035. const unsigned char *zNeedle;
  86036. int nHaystack;
  86037. int nNeedle;
  86038. int typeHaystack, typeNeedle;
  86039. int N = 1;
  86040. int isText;
  86041. UNUSED_PARAMETER(argc);
  86042. typeHaystack = sqlite3_value_type(argv[0]);
  86043. typeNeedle = sqlite3_value_type(argv[1]);
  86044. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  86045. nHaystack = sqlite3_value_bytes(argv[0]);
  86046. nNeedle = sqlite3_value_bytes(argv[1]);
  86047. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  86048. zHaystack = sqlite3_value_blob(argv[0]);
  86049. zNeedle = sqlite3_value_blob(argv[1]);
  86050. isText = 0;
  86051. }else{
  86052. zHaystack = sqlite3_value_text(argv[0]);
  86053. zNeedle = sqlite3_value_text(argv[1]);
  86054. isText = 1;
  86055. }
  86056. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  86057. N++;
  86058. do{
  86059. nHaystack--;
  86060. zHaystack++;
  86061. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  86062. }
  86063. if( nNeedle>nHaystack ) N = 0;
  86064. sqlite3_result_int(context, N);
  86065. }
  86066. /*
  86067. ** Implementation of the substr() function.
  86068. **
  86069. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  86070. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  86071. ** of x. If x is text, then we actually count UTF-8 characters.
  86072. ** If x is a blob, then we count bytes.
  86073. **
  86074. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  86075. **
  86076. ** If p2 is negative, return the p2 characters preceding p1.
  86077. */
  86078. static void substrFunc(
  86079. sqlite3_context *context,
  86080. int argc,
  86081. sqlite3_value **argv
  86082. ){
  86083. const unsigned char *z;
  86084. const unsigned char *z2;
  86085. int len;
  86086. int p0type;
  86087. i64 p1, p2;
  86088. int negP2 = 0;
  86089. assert( argc==3 || argc==2 );
  86090. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  86091. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  86092. ){
  86093. return;
  86094. }
  86095. p0type = sqlite3_value_type(argv[0]);
  86096. p1 = sqlite3_value_int(argv[1]);
  86097. if( p0type==SQLITE_BLOB ){
  86098. len = sqlite3_value_bytes(argv[0]);
  86099. z = sqlite3_value_blob(argv[0]);
  86100. if( z==0 ) return;
  86101. assert( len==sqlite3_value_bytes(argv[0]) );
  86102. }else{
  86103. z = sqlite3_value_text(argv[0]);
  86104. if( z==0 ) return;
  86105. len = 0;
  86106. if( p1<0 ){
  86107. for(z2=z; *z2; len++){
  86108. SQLITE_SKIP_UTF8(z2);
  86109. }
  86110. }
  86111. }
  86112. if( argc==3 ){
  86113. p2 = sqlite3_value_int(argv[2]);
  86114. if( p2<0 ){
  86115. p2 = -p2;
  86116. negP2 = 1;
  86117. }
  86118. }else{
  86119. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  86120. }
  86121. if( p1<0 ){
  86122. p1 += len;
  86123. if( p1<0 ){
  86124. p2 += p1;
  86125. if( p2<0 ) p2 = 0;
  86126. p1 = 0;
  86127. }
  86128. }else if( p1>0 ){
  86129. p1--;
  86130. }else if( p2>0 ){
  86131. p2--;
  86132. }
  86133. if( negP2 ){
  86134. p1 -= p2;
  86135. if( p1<0 ){
  86136. p2 += p1;
  86137. p1 = 0;
  86138. }
  86139. }
  86140. assert( p1>=0 && p2>=0 );
  86141. if( p0type!=SQLITE_BLOB ){
  86142. while( *z && p1 ){
  86143. SQLITE_SKIP_UTF8(z);
  86144. p1--;
  86145. }
  86146. for(z2=z; *z2 && p2; p2--){
  86147. SQLITE_SKIP_UTF8(z2);
  86148. }
  86149. sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
  86150. }else{
  86151. if( p1+p2>len ){
  86152. p2 = len-p1;
  86153. if( p2<0 ) p2 = 0;
  86154. }
  86155. sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
  86156. }
  86157. }
  86158. /*
  86159. ** Implementation of the round() function
  86160. */
  86161. #ifndef SQLITE_OMIT_FLOATING_POINT
  86162. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86163. int n = 0;
  86164. double r;
  86165. char *zBuf;
  86166. assert( argc==1 || argc==2 );
  86167. if( argc==2 ){
  86168. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  86169. n = sqlite3_value_int(argv[1]);
  86170. if( n>30 ) n = 30;
  86171. if( n<0 ) n = 0;
  86172. }
  86173. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  86174. r = sqlite3_value_double(argv[0]);
  86175. /* If Y==0 and X will fit in a 64-bit int,
  86176. ** handle the rounding directly,
  86177. ** otherwise use printf.
  86178. */
  86179. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  86180. r = (double)((sqlite_int64)(r+0.5));
  86181. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  86182. r = -(double)((sqlite_int64)((-r)+0.5));
  86183. }else{
  86184. zBuf = sqlite3_mprintf("%.*f",n,r);
  86185. if( zBuf==0 ){
  86186. sqlite3_result_error_nomem(context);
  86187. return;
  86188. }
  86189. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  86190. sqlite3_free(zBuf);
  86191. }
  86192. sqlite3_result_double(context, r);
  86193. }
  86194. #endif
  86195. /*
  86196. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  86197. ** allocation fails, call sqlite3_result_error_nomem() to notify
  86198. ** the database handle that malloc() has failed and return NULL.
  86199. ** If nByte is larger than the maximum string or blob length, then
  86200. ** raise an SQLITE_TOOBIG exception and return NULL.
  86201. */
  86202. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  86203. char *z;
  86204. sqlite3 *db = sqlite3_context_db_handle(context);
  86205. assert( nByte>0 );
  86206. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86207. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  86208. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86209. sqlite3_result_error_toobig(context);
  86210. z = 0;
  86211. }else{
  86212. z = sqlite3Malloc((int)nByte);
  86213. if( !z ){
  86214. sqlite3_result_error_nomem(context);
  86215. }
  86216. }
  86217. return z;
  86218. }
  86219. /*
  86220. ** Implementation of the upper() and lower() SQL functions.
  86221. */
  86222. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86223. char *z1;
  86224. const char *z2;
  86225. int i, n;
  86226. UNUSED_PARAMETER(argc);
  86227. z2 = (char*)sqlite3_value_text(argv[0]);
  86228. n = sqlite3_value_bytes(argv[0]);
  86229. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  86230. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  86231. if( z2 ){
  86232. z1 = contextMalloc(context, ((i64)n)+1);
  86233. if( z1 ){
  86234. for(i=0; i<n; i++){
  86235. z1[i] = (char)sqlite3Toupper(z2[i]);
  86236. }
  86237. sqlite3_result_text(context, z1, n, sqlite3_free);
  86238. }
  86239. }
  86240. }
  86241. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86242. char *z1;
  86243. const char *z2;
  86244. int i, n;
  86245. UNUSED_PARAMETER(argc);
  86246. z2 = (char*)sqlite3_value_text(argv[0]);
  86247. n = sqlite3_value_bytes(argv[0]);
  86248. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  86249. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  86250. if( z2 ){
  86251. z1 = contextMalloc(context, ((i64)n)+1);
  86252. if( z1 ){
  86253. for(i=0; i<n; i++){
  86254. z1[i] = sqlite3Tolower(z2[i]);
  86255. }
  86256. sqlite3_result_text(context, z1, n, sqlite3_free);
  86257. }
  86258. }
  86259. }
  86260. /*
  86261. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  86262. ** as VDBE code so that unused argument values do not have to be computed.
  86263. ** However, we still need some kind of function implementation for this
  86264. ** routines in the function table. The noopFunc macro provides this.
  86265. ** noopFunc will never be called so it doesn't matter what the implementation
  86266. ** is. We might as well use the "version()" function as a substitute.
  86267. */
  86268. #define noopFunc versionFunc /* Substitute function - never called */
  86269. /*
  86270. ** Implementation of random(). Return a random integer.
  86271. */
  86272. static void randomFunc(
  86273. sqlite3_context *context,
  86274. int NotUsed,
  86275. sqlite3_value **NotUsed2
  86276. ){
  86277. sqlite_int64 r;
  86278. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86279. sqlite3_randomness(sizeof(r), &r);
  86280. if( r<0 ){
  86281. /* We need to prevent a random number of 0x8000000000000000
  86282. ** (or -9223372036854775808) since when you do abs() of that
  86283. ** number of you get the same value back again. To do this
  86284. ** in a way that is testable, mask the sign bit off of negative
  86285. ** values, resulting in a positive value. Then take the
  86286. ** 2s complement of that positive value. The end result can
  86287. ** therefore be no less than -9223372036854775807.
  86288. */
  86289. r = -(r & LARGEST_INT64);
  86290. }
  86291. sqlite3_result_int64(context, r);
  86292. }
  86293. /*
  86294. ** Implementation of randomblob(N). Return a random blob
  86295. ** that is N bytes long.
  86296. */
  86297. static void randomBlob(
  86298. sqlite3_context *context,
  86299. int argc,
  86300. sqlite3_value **argv
  86301. ){
  86302. int n;
  86303. unsigned char *p;
  86304. assert( argc==1 );
  86305. UNUSED_PARAMETER(argc);
  86306. n = sqlite3_value_int(argv[0]);
  86307. if( n<1 ){
  86308. n = 1;
  86309. }
  86310. p = contextMalloc(context, n);
  86311. if( p ){
  86312. sqlite3_randomness(n, p);
  86313. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  86314. }
  86315. }
  86316. /*
  86317. ** Implementation of the last_insert_rowid() SQL function. The return
  86318. ** value is the same as the sqlite3_last_insert_rowid() API function.
  86319. */
  86320. static void last_insert_rowid(
  86321. sqlite3_context *context,
  86322. int NotUsed,
  86323. sqlite3_value **NotUsed2
  86324. ){
  86325. sqlite3 *db = sqlite3_context_db_handle(context);
  86326. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86327. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  86328. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  86329. ** function. */
  86330. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  86331. }
  86332. /*
  86333. ** Implementation of the changes() SQL function.
  86334. **
  86335. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  86336. ** around the sqlite3_changes() C/C++ function and hence follows the same
  86337. ** rules for counting changes.
  86338. */
  86339. static void changes(
  86340. sqlite3_context *context,
  86341. int NotUsed,
  86342. sqlite3_value **NotUsed2
  86343. ){
  86344. sqlite3 *db = sqlite3_context_db_handle(context);
  86345. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86346. sqlite3_result_int(context, sqlite3_changes(db));
  86347. }
  86348. /*
  86349. ** Implementation of the total_changes() SQL function. The return value is
  86350. ** the same as the sqlite3_total_changes() API function.
  86351. */
  86352. static void total_changes(
  86353. sqlite3_context *context,
  86354. int NotUsed,
  86355. sqlite3_value **NotUsed2
  86356. ){
  86357. sqlite3 *db = sqlite3_context_db_handle(context);
  86358. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86359. /* IMP: R-52756-41993 This function is a wrapper around the
  86360. ** sqlite3_total_changes() C/C++ interface. */
  86361. sqlite3_result_int(context, sqlite3_total_changes(db));
  86362. }
  86363. /*
  86364. ** A structure defining how to do GLOB-style comparisons.
  86365. */
  86366. struct compareInfo {
  86367. u8 matchAll;
  86368. u8 matchOne;
  86369. u8 matchSet;
  86370. u8 noCase;
  86371. };
  86372. /*
  86373. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  86374. ** character is exactly one byte in size. Also, all characters are
  86375. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  86376. ** whereas only characters less than 0x80 do in ASCII.
  86377. */
  86378. #if defined(SQLITE_EBCDIC)
  86379. # define sqlite3Utf8Read(A) (*((*A)++))
  86380. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  86381. #else
  86382. # define GlobUpperToLower(A) if( !((A)&~0x7f) ){ A = sqlite3UpperToLower[A]; }
  86383. #endif
  86384. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  86385. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  86386. ** case. Thus 'a' LIKE 'A' would be true. */
  86387. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  86388. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  86389. ** is case sensitive causing 'a' LIKE 'A' to be false */
  86390. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  86391. /*
  86392. ** Compare two UTF-8 strings for equality where the first string can
  86393. ** potentially be a "glob" expression. Return true (1) if they
  86394. ** are the same and false (0) if they are different.
  86395. **
  86396. ** Globbing rules:
  86397. **
  86398. ** '*' Matches any sequence of zero or more characters.
  86399. **
  86400. ** '?' Matches exactly one character.
  86401. **
  86402. ** [...] Matches one character from the enclosed list of
  86403. ** characters.
  86404. **
  86405. ** [^...] Matches one character not in the enclosed list.
  86406. **
  86407. ** With the [...] and [^...] matching, a ']' character can be included
  86408. ** in the list by making it the first character after '[' or '^'. A
  86409. ** range of characters can be specified using '-'. Example:
  86410. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  86411. ** it the last character in the list.
  86412. **
  86413. ** This routine is usually quick, but can be N**2 in the worst case.
  86414. **
  86415. ** Hints: to match '*' or '?', put them in "[]". Like this:
  86416. **
  86417. ** abc[*]xyz Matches "abc*xyz" only
  86418. */
  86419. static int patternCompare(
  86420. const u8 *zPattern, /* The glob pattern */
  86421. const u8 *zString, /* The string to compare against the glob */
  86422. const struct compareInfo *pInfo, /* Information about how to do the compare */
  86423. u32 esc /* The escape character */
  86424. ){
  86425. u32 c, c2;
  86426. int invert;
  86427. int seen;
  86428. u8 matchOne = pInfo->matchOne;
  86429. u8 matchAll = pInfo->matchAll;
  86430. u8 matchSet = pInfo->matchSet;
  86431. u8 noCase = pInfo->noCase;
  86432. int prevEscape = 0; /* True if the previous character was 'escape' */
  86433. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  86434. if( c==matchAll && !prevEscape ){
  86435. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  86436. || c == matchOne ){
  86437. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  86438. return 0;
  86439. }
  86440. }
  86441. if( c==0 ){
  86442. return 1;
  86443. }else if( c==esc ){
  86444. c = sqlite3Utf8Read(&zPattern);
  86445. if( c==0 ){
  86446. return 0;
  86447. }
  86448. }else if( c==matchSet ){
  86449. assert( esc==0 ); /* This is GLOB, not LIKE */
  86450. assert( matchSet<0x80 ); /* '[' is a single-byte character */
  86451. while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  86452. SQLITE_SKIP_UTF8(zString);
  86453. }
  86454. return *zString!=0;
  86455. }
  86456. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  86457. if( noCase ){
  86458. GlobUpperToLower(c2);
  86459. GlobUpperToLower(c);
  86460. while( c2 != 0 && c2 != c ){
  86461. c2 = sqlite3Utf8Read(&zString);
  86462. GlobUpperToLower(c2);
  86463. }
  86464. }else{
  86465. while( c2 != 0 && c2 != c ){
  86466. c2 = sqlite3Utf8Read(&zString);
  86467. }
  86468. }
  86469. if( c2==0 ) return 0;
  86470. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  86471. }
  86472. return 0;
  86473. }else if( c==matchOne && !prevEscape ){
  86474. if( sqlite3Utf8Read(&zString)==0 ){
  86475. return 0;
  86476. }
  86477. }else if( c==matchSet ){
  86478. u32 prior_c = 0;
  86479. assert( esc==0 ); /* This only occurs for GLOB, not LIKE */
  86480. seen = 0;
  86481. invert = 0;
  86482. c = sqlite3Utf8Read(&zString);
  86483. if( c==0 ) return 0;
  86484. c2 = sqlite3Utf8Read(&zPattern);
  86485. if( c2=='^' ){
  86486. invert = 1;
  86487. c2 = sqlite3Utf8Read(&zPattern);
  86488. }
  86489. if( c2==']' ){
  86490. if( c==']' ) seen = 1;
  86491. c2 = sqlite3Utf8Read(&zPattern);
  86492. }
  86493. while( c2 && c2!=']' ){
  86494. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  86495. c2 = sqlite3Utf8Read(&zPattern);
  86496. if( c>=prior_c && c<=c2 ) seen = 1;
  86497. prior_c = 0;
  86498. }else{
  86499. if( c==c2 ){
  86500. seen = 1;
  86501. }
  86502. prior_c = c2;
  86503. }
  86504. c2 = sqlite3Utf8Read(&zPattern);
  86505. }
  86506. if( c2==0 || (seen ^ invert)==0 ){
  86507. return 0;
  86508. }
  86509. }else if( esc==c && !prevEscape ){
  86510. prevEscape = 1;
  86511. }else{
  86512. c2 = sqlite3Utf8Read(&zString);
  86513. if( noCase ){
  86514. GlobUpperToLower(c);
  86515. GlobUpperToLower(c2);
  86516. }
  86517. if( c!=c2 ){
  86518. return 0;
  86519. }
  86520. prevEscape = 0;
  86521. }
  86522. }
  86523. return *zString==0;
  86524. }
  86525. /*
  86526. ** The sqlite3_strglob() interface.
  86527. */
  86528. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  86529. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  86530. }
  86531. /*
  86532. ** Count the number of times that the LIKE operator (or GLOB which is
  86533. ** just a variation of LIKE) gets called. This is used for testing
  86534. ** only.
  86535. */
  86536. #ifdef SQLITE_TEST
  86537. SQLITE_API int sqlite3_like_count = 0;
  86538. #endif
  86539. /*
  86540. ** Implementation of the like() SQL function. This function implements
  86541. ** the build-in LIKE operator. The first argument to the function is the
  86542. ** pattern and the second argument is the string. So, the SQL statements:
  86543. **
  86544. ** A LIKE B
  86545. **
  86546. ** is implemented as like(B,A).
  86547. **
  86548. ** This same function (with a different compareInfo structure) computes
  86549. ** the GLOB operator.
  86550. */
  86551. static void likeFunc(
  86552. sqlite3_context *context,
  86553. int argc,
  86554. sqlite3_value **argv
  86555. ){
  86556. const unsigned char *zA, *zB;
  86557. u32 escape = 0;
  86558. int nPat;
  86559. sqlite3 *db = sqlite3_context_db_handle(context);
  86560. zB = sqlite3_value_text(argv[0]);
  86561. zA = sqlite3_value_text(argv[1]);
  86562. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  86563. ** of deep recursion and N*N behavior in patternCompare().
  86564. */
  86565. nPat = sqlite3_value_bytes(argv[0]);
  86566. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  86567. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  86568. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  86569. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  86570. return;
  86571. }
  86572. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  86573. if( argc==3 ){
  86574. /* The escape character string must consist of a single UTF-8 character.
  86575. ** Otherwise, return an error.
  86576. */
  86577. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  86578. if( zEsc==0 ) return;
  86579. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  86580. sqlite3_result_error(context,
  86581. "ESCAPE expression must be a single character", -1);
  86582. return;
  86583. }
  86584. escape = sqlite3Utf8Read(&zEsc);
  86585. }
  86586. if( zA && zB ){
  86587. struct compareInfo *pInfo = sqlite3_user_data(context);
  86588. #ifdef SQLITE_TEST
  86589. sqlite3_like_count++;
  86590. #endif
  86591. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  86592. }
  86593. }
  86594. /*
  86595. ** Implementation of the NULLIF(x,y) function. The result is the first
  86596. ** argument if the arguments are different. The result is NULL if the
  86597. ** arguments are equal to each other.
  86598. */
  86599. static void nullifFunc(
  86600. sqlite3_context *context,
  86601. int NotUsed,
  86602. sqlite3_value **argv
  86603. ){
  86604. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  86605. UNUSED_PARAMETER(NotUsed);
  86606. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  86607. sqlite3_result_value(context, argv[0]);
  86608. }
  86609. }
  86610. /*
  86611. ** Implementation of the sqlite_version() function. The result is the version
  86612. ** of the SQLite library that is running.
  86613. */
  86614. static void versionFunc(
  86615. sqlite3_context *context,
  86616. int NotUsed,
  86617. sqlite3_value **NotUsed2
  86618. ){
  86619. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86620. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  86621. ** sqlite3_libversion() C-interface. */
  86622. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  86623. }
  86624. /*
  86625. ** Implementation of the sqlite_source_id() function. The result is a string
  86626. ** that identifies the particular version of the source code used to build
  86627. ** SQLite.
  86628. */
  86629. static void sourceidFunc(
  86630. sqlite3_context *context,
  86631. int NotUsed,
  86632. sqlite3_value **NotUsed2
  86633. ){
  86634. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  86635. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  86636. ** sqlite3_sourceid() C interface. */
  86637. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  86638. }
  86639. /*
  86640. ** Implementation of the sqlite_log() function. This is a wrapper around
  86641. ** sqlite3_log(). The return value is NULL. The function exists purely for
  86642. ** its side-effects.
  86643. */
  86644. static void errlogFunc(
  86645. sqlite3_context *context,
  86646. int argc,
  86647. sqlite3_value **argv
  86648. ){
  86649. UNUSED_PARAMETER(argc);
  86650. UNUSED_PARAMETER(context);
  86651. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  86652. }
  86653. /*
  86654. ** Implementation of the sqlite_compileoption_used() function.
  86655. ** The result is an integer that identifies if the compiler option
  86656. ** was used to build SQLite.
  86657. */
  86658. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  86659. static void compileoptionusedFunc(
  86660. sqlite3_context *context,
  86661. int argc,
  86662. sqlite3_value **argv
  86663. ){
  86664. const char *zOptName;
  86665. assert( argc==1 );
  86666. UNUSED_PARAMETER(argc);
  86667. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  86668. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  86669. ** function.
  86670. */
  86671. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  86672. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  86673. }
  86674. }
  86675. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  86676. /*
  86677. ** Implementation of the sqlite_compileoption_get() function.
  86678. ** The result is a string that identifies the compiler options
  86679. ** used to build SQLite.
  86680. */
  86681. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  86682. static void compileoptiongetFunc(
  86683. sqlite3_context *context,
  86684. int argc,
  86685. sqlite3_value **argv
  86686. ){
  86687. int n;
  86688. assert( argc==1 );
  86689. UNUSED_PARAMETER(argc);
  86690. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  86691. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  86692. */
  86693. n = sqlite3_value_int(argv[0]);
  86694. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  86695. }
  86696. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  86697. /* Array for converting from half-bytes (nybbles) into ASCII hex
  86698. ** digits. */
  86699. static const char hexdigits[] = {
  86700. '0', '1', '2', '3', '4', '5', '6', '7',
  86701. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  86702. };
  86703. /*
  86704. ** Implementation of the QUOTE() function. This function takes a single
  86705. ** argument. If the argument is numeric, the return value is the same as
  86706. ** the argument. If the argument is NULL, the return value is the string
  86707. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  86708. ** single-quote escapes.
  86709. */
  86710. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  86711. assert( argc==1 );
  86712. UNUSED_PARAMETER(argc);
  86713. switch( sqlite3_value_type(argv[0]) ){
  86714. case SQLITE_FLOAT: {
  86715. double r1, r2;
  86716. char zBuf[50];
  86717. r1 = sqlite3_value_double(argv[0]);
  86718. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  86719. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  86720. if( r1!=r2 ){
  86721. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  86722. }
  86723. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  86724. break;
  86725. }
  86726. case SQLITE_INTEGER: {
  86727. sqlite3_result_value(context, argv[0]);
  86728. break;
  86729. }
  86730. case SQLITE_BLOB: {
  86731. char *zText = 0;
  86732. char const *zBlob = sqlite3_value_blob(argv[0]);
  86733. int nBlob = sqlite3_value_bytes(argv[0]);
  86734. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  86735. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  86736. if( zText ){
  86737. int i;
  86738. for(i=0; i<nBlob; i++){
  86739. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  86740. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  86741. }
  86742. zText[(nBlob*2)+2] = '\'';
  86743. zText[(nBlob*2)+3] = '\0';
  86744. zText[0] = 'X';
  86745. zText[1] = '\'';
  86746. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  86747. sqlite3_free(zText);
  86748. }
  86749. break;
  86750. }
  86751. case SQLITE_TEXT: {
  86752. int i,j;
  86753. u64 n;
  86754. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  86755. char *z;
  86756. if( zArg==0 ) return;
  86757. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  86758. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  86759. if( z ){
  86760. z[0] = '\'';
  86761. for(i=0, j=1; zArg[i]; i++){
  86762. z[j++] = zArg[i];
  86763. if( zArg[i]=='\'' ){
  86764. z[j++] = '\'';
  86765. }
  86766. }
  86767. z[j++] = '\'';
  86768. z[j] = 0;
  86769. sqlite3_result_text(context, z, j, sqlite3_free);
  86770. }
  86771. break;
  86772. }
  86773. default: {
  86774. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  86775. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  86776. break;
  86777. }
  86778. }
  86779. }
  86780. /*
  86781. ** The unicode() function. Return the integer unicode code-point value
  86782. ** for the first character of the input string.
  86783. */
  86784. static void unicodeFunc(
  86785. sqlite3_context *context,
  86786. int argc,
  86787. sqlite3_value **argv
  86788. ){
  86789. const unsigned char *z = sqlite3_value_text(argv[0]);
  86790. (void)argc;
  86791. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  86792. }
  86793. /*
  86794. ** The char() function takes zero or more arguments, each of which is
  86795. ** an integer. It constructs a string where each character of the string
  86796. ** is the unicode character for the corresponding integer argument.
  86797. */
  86798. static void charFunc(
  86799. sqlite3_context *context,
  86800. int argc,
  86801. sqlite3_value **argv
  86802. ){
  86803. unsigned char *z, *zOut;
  86804. int i;
  86805. zOut = z = sqlite3_malloc( argc*4 );
  86806. if( z==0 ){
  86807. sqlite3_result_error_nomem(context);
  86808. return;
  86809. }
  86810. for(i=0; i<argc; i++){
  86811. sqlite3_int64 x;
  86812. unsigned c;
  86813. x = sqlite3_value_int64(argv[i]);
  86814. if( x<0 || x>0x10ffff ) x = 0xfffd;
  86815. c = (unsigned)(x & 0x1fffff);
  86816. if( c<0x00080 ){
  86817. *zOut++ = (u8)(c&0xFF);
  86818. }else if( c<0x00800 ){
  86819. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  86820. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86821. }else if( c<0x10000 ){
  86822. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  86823. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  86824. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86825. }else{
  86826. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  86827. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  86828. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  86829. *zOut++ = 0x80 + (u8)(c & 0x3F);
  86830. } \
  86831. }
  86832. sqlite3_result_text(context, (char*)z, (int)(zOut-z), sqlite3_free);
  86833. }
  86834. /*
  86835. ** The hex() function. Interpret the argument as a blob. Return
  86836. ** a hexadecimal rendering as text.
  86837. */
  86838. static void hexFunc(
  86839. sqlite3_context *context,
  86840. int argc,
  86841. sqlite3_value **argv
  86842. ){
  86843. int i, n;
  86844. const unsigned char *pBlob;
  86845. char *zHex, *z;
  86846. assert( argc==1 );
  86847. UNUSED_PARAMETER(argc);
  86848. pBlob = sqlite3_value_blob(argv[0]);
  86849. n = sqlite3_value_bytes(argv[0]);
  86850. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  86851. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  86852. if( zHex ){
  86853. for(i=0; i<n; i++, pBlob++){
  86854. unsigned char c = *pBlob;
  86855. *(z++) = hexdigits[(c>>4)&0xf];
  86856. *(z++) = hexdigits[c&0xf];
  86857. }
  86858. *z = 0;
  86859. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  86860. }
  86861. }
  86862. /*
  86863. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  86864. */
  86865. static void zeroblobFunc(
  86866. sqlite3_context *context,
  86867. int argc,
  86868. sqlite3_value **argv
  86869. ){
  86870. i64 n;
  86871. sqlite3 *db = sqlite3_context_db_handle(context);
  86872. assert( argc==1 );
  86873. UNUSED_PARAMETER(argc);
  86874. n = sqlite3_value_int64(argv[0]);
  86875. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86876. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  86877. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86878. sqlite3_result_error_toobig(context);
  86879. }else{
  86880. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  86881. }
  86882. }
  86883. /*
  86884. ** The replace() function. Three arguments are all strings: call
  86885. ** them A, B, and C. The result is also a string which is derived
  86886. ** from A by replacing every occurrence of B with C. The match
  86887. ** must be exact. Collating sequences are not used.
  86888. */
  86889. static void replaceFunc(
  86890. sqlite3_context *context,
  86891. int argc,
  86892. sqlite3_value **argv
  86893. ){
  86894. const unsigned char *zStr; /* The input string A */
  86895. const unsigned char *zPattern; /* The pattern string B */
  86896. const unsigned char *zRep; /* The replacement string C */
  86897. unsigned char *zOut; /* The output */
  86898. int nStr; /* Size of zStr */
  86899. int nPattern; /* Size of zPattern */
  86900. int nRep; /* Size of zRep */
  86901. i64 nOut; /* Maximum size of zOut */
  86902. int loopLimit; /* Last zStr[] that might match zPattern[] */
  86903. int i, j; /* Loop counters */
  86904. assert( argc==3 );
  86905. UNUSED_PARAMETER(argc);
  86906. zStr = sqlite3_value_text(argv[0]);
  86907. if( zStr==0 ) return;
  86908. nStr = sqlite3_value_bytes(argv[0]);
  86909. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  86910. zPattern = sqlite3_value_text(argv[1]);
  86911. if( zPattern==0 ){
  86912. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  86913. || sqlite3_context_db_handle(context)->mallocFailed );
  86914. return;
  86915. }
  86916. if( zPattern[0]==0 ){
  86917. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  86918. sqlite3_result_value(context, argv[0]);
  86919. return;
  86920. }
  86921. nPattern = sqlite3_value_bytes(argv[1]);
  86922. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  86923. zRep = sqlite3_value_text(argv[2]);
  86924. if( zRep==0 ) return;
  86925. nRep = sqlite3_value_bytes(argv[2]);
  86926. assert( zRep==sqlite3_value_text(argv[2]) );
  86927. nOut = nStr + 1;
  86928. assert( nOut<SQLITE_MAX_LENGTH );
  86929. zOut = contextMalloc(context, (i64)nOut);
  86930. if( zOut==0 ){
  86931. return;
  86932. }
  86933. loopLimit = nStr - nPattern;
  86934. for(i=j=0; i<=loopLimit; i++){
  86935. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  86936. zOut[j++] = zStr[i];
  86937. }else{
  86938. u8 *zOld;
  86939. sqlite3 *db = sqlite3_context_db_handle(context);
  86940. nOut += nRep - nPattern;
  86941. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86942. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  86943. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  86944. sqlite3_result_error_toobig(context);
  86945. sqlite3_free(zOut);
  86946. return;
  86947. }
  86948. zOld = zOut;
  86949. zOut = sqlite3_realloc(zOut, (int)nOut);
  86950. if( zOut==0 ){
  86951. sqlite3_result_error_nomem(context);
  86952. sqlite3_free(zOld);
  86953. return;
  86954. }
  86955. memcpy(&zOut[j], zRep, nRep);
  86956. j += nRep;
  86957. i += nPattern-1;
  86958. }
  86959. }
  86960. assert( j+nStr-i+1==nOut );
  86961. memcpy(&zOut[j], &zStr[i], nStr-i);
  86962. j += nStr - i;
  86963. assert( j<=nOut );
  86964. zOut[j] = 0;
  86965. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  86966. }
  86967. /*
  86968. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  86969. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  86970. */
  86971. static void trimFunc(
  86972. sqlite3_context *context,
  86973. int argc,
  86974. sqlite3_value **argv
  86975. ){
  86976. const unsigned char *zIn; /* Input string */
  86977. const unsigned char *zCharSet; /* Set of characters to trim */
  86978. int nIn; /* Number of bytes in input */
  86979. int flags; /* 1: trimleft 2: trimright 3: trim */
  86980. int i; /* Loop counter */
  86981. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  86982. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  86983. int nChar; /* Number of characters in zCharSet */
  86984. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  86985. return;
  86986. }
  86987. zIn = sqlite3_value_text(argv[0]);
  86988. if( zIn==0 ) return;
  86989. nIn = sqlite3_value_bytes(argv[0]);
  86990. assert( zIn==sqlite3_value_text(argv[0]) );
  86991. if( argc==1 ){
  86992. static const unsigned char lenOne[] = { 1 };
  86993. static unsigned char * const azOne[] = { (u8*)" " };
  86994. nChar = 1;
  86995. aLen = (u8*)lenOne;
  86996. azChar = (unsigned char **)azOne;
  86997. zCharSet = 0;
  86998. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  86999. return;
  87000. }else{
  87001. const unsigned char *z;
  87002. for(z=zCharSet, nChar=0; *z; nChar++){
  87003. SQLITE_SKIP_UTF8(z);
  87004. }
  87005. if( nChar>0 ){
  87006. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  87007. if( azChar==0 ){
  87008. return;
  87009. }
  87010. aLen = (unsigned char*)&azChar[nChar];
  87011. for(z=zCharSet, nChar=0; *z; nChar++){
  87012. azChar[nChar] = (unsigned char *)z;
  87013. SQLITE_SKIP_UTF8(z);
  87014. aLen[nChar] = (u8)(z - azChar[nChar]);
  87015. }
  87016. }
  87017. }
  87018. if( nChar>0 ){
  87019. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  87020. if( flags & 1 ){
  87021. while( nIn>0 ){
  87022. int len = 0;
  87023. for(i=0; i<nChar; i++){
  87024. len = aLen[i];
  87025. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  87026. }
  87027. if( i>=nChar ) break;
  87028. zIn += len;
  87029. nIn -= len;
  87030. }
  87031. }
  87032. if( flags & 2 ){
  87033. while( nIn>0 ){
  87034. int len = 0;
  87035. for(i=0; i<nChar; i++){
  87036. len = aLen[i];
  87037. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  87038. }
  87039. if( i>=nChar ) break;
  87040. nIn -= len;
  87041. }
  87042. }
  87043. if( zCharSet ){
  87044. sqlite3_free(azChar);
  87045. }
  87046. }
  87047. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  87048. }
  87049. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  87050. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  87051. ** when SQLite is built.
  87052. */
  87053. #ifdef SQLITE_SOUNDEX
  87054. /*
  87055. ** Compute the soundex encoding of a word.
  87056. **
  87057. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  87058. ** soundex encoding of the string X.
  87059. */
  87060. static void soundexFunc(
  87061. sqlite3_context *context,
  87062. int argc,
  87063. sqlite3_value **argv
  87064. ){
  87065. char zResult[8];
  87066. const u8 *zIn;
  87067. int i, j;
  87068. static const unsigned char iCode[] = {
  87069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87073. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  87074. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  87075. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  87076. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  87077. };
  87078. assert( argc==1 );
  87079. zIn = (u8*)sqlite3_value_text(argv[0]);
  87080. if( zIn==0 ) zIn = (u8*)"";
  87081. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  87082. if( zIn[i] ){
  87083. u8 prevcode = iCode[zIn[i]&0x7f];
  87084. zResult[0] = sqlite3Toupper(zIn[i]);
  87085. for(j=1; j<4 && zIn[i]; i++){
  87086. int code = iCode[zIn[i]&0x7f];
  87087. if( code>0 ){
  87088. if( code!=prevcode ){
  87089. prevcode = code;
  87090. zResult[j++] = code + '0';
  87091. }
  87092. }else{
  87093. prevcode = 0;
  87094. }
  87095. }
  87096. while( j<4 ){
  87097. zResult[j++] = '0';
  87098. }
  87099. zResult[j] = 0;
  87100. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  87101. }else{
  87102. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  87103. ** is NULL or contains no ASCII alphabetic characters. */
  87104. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  87105. }
  87106. }
  87107. #endif /* SQLITE_SOUNDEX */
  87108. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  87109. /*
  87110. ** A function that loads a shared-library extension then returns NULL.
  87111. */
  87112. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  87113. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  87114. const char *zProc;
  87115. sqlite3 *db = sqlite3_context_db_handle(context);
  87116. char *zErrMsg = 0;
  87117. if( argc==2 ){
  87118. zProc = (const char *)sqlite3_value_text(argv[1]);
  87119. }else{
  87120. zProc = 0;
  87121. }
  87122. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  87123. sqlite3_result_error(context, zErrMsg, -1);
  87124. sqlite3_free(zErrMsg);
  87125. }
  87126. }
  87127. #endif
  87128. /*
  87129. ** An instance of the following structure holds the context of a
  87130. ** sum() or avg() aggregate computation.
  87131. */
  87132. typedef struct SumCtx SumCtx;
  87133. struct SumCtx {
  87134. double rSum; /* Floating point sum */
  87135. i64 iSum; /* Integer sum */
  87136. i64 cnt; /* Number of elements summed */
  87137. u8 overflow; /* True if integer overflow seen */
  87138. u8 approx; /* True if non-integer value was input to the sum */
  87139. };
  87140. /*
  87141. ** Routines used to compute the sum, average, and total.
  87142. **
  87143. ** The SUM() function follows the (broken) SQL standard which means
  87144. ** that it returns NULL if it sums over no inputs. TOTAL returns
  87145. ** 0.0 in that case. In addition, TOTAL always returns a float where
  87146. ** SUM might return an integer if it never encounters a floating point
  87147. ** value. TOTAL never fails, but SUM might through an exception if
  87148. ** it overflows an integer.
  87149. */
  87150. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  87151. SumCtx *p;
  87152. int type;
  87153. assert( argc==1 );
  87154. UNUSED_PARAMETER(argc);
  87155. p = sqlite3_aggregate_context(context, sizeof(*p));
  87156. type = sqlite3_value_numeric_type(argv[0]);
  87157. if( p && type!=SQLITE_NULL ){
  87158. p->cnt++;
  87159. if( type==SQLITE_INTEGER ){
  87160. i64 v = sqlite3_value_int64(argv[0]);
  87161. p->rSum += v;
  87162. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  87163. p->overflow = 1;
  87164. }
  87165. }else{
  87166. p->rSum += sqlite3_value_double(argv[0]);
  87167. p->approx = 1;
  87168. }
  87169. }
  87170. }
  87171. static void sumFinalize(sqlite3_context *context){
  87172. SumCtx *p;
  87173. p = sqlite3_aggregate_context(context, 0);
  87174. if( p && p->cnt>0 ){
  87175. if( p->overflow ){
  87176. sqlite3_result_error(context,"integer overflow",-1);
  87177. }else if( p->approx ){
  87178. sqlite3_result_double(context, p->rSum);
  87179. }else{
  87180. sqlite3_result_int64(context, p->iSum);
  87181. }
  87182. }
  87183. }
  87184. static void avgFinalize(sqlite3_context *context){
  87185. SumCtx *p;
  87186. p = sqlite3_aggregate_context(context, 0);
  87187. if( p && p->cnt>0 ){
  87188. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  87189. }
  87190. }
  87191. static void totalFinalize(sqlite3_context *context){
  87192. SumCtx *p;
  87193. p = sqlite3_aggregate_context(context, 0);
  87194. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  87195. sqlite3_result_double(context, p ? p->rSum : (double)0);
  87196. }
  87197. /*
  87198. ** The following structure keeps track of state information for the
  87199. ** count() aggregate function.
  87200. */
  87201. typedef struct CountCtx CountCtx;
  87202. struct CountCtx {
  87203. i64 n;
  87204. };
  87205. /*
  87206. ** Routines to implement the count() aggregate function.
  87207. */
  87208. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  87209. CountCtx *p;
  87210. p = sqlite3_aggregate_context(context, sizeof(*p));
  87211. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  87212. p->n++;
  87213. }
  87214. #ifndef SQLITE_OMIT_DEPRECATED
  87215. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  87216. ** sure it still operates correctly, verify that its count agrees with our
  87217. ** internal count when using count(*) and when the total count can be
  87218. ** expressed as a 32-bit integer. */
  87219. assert( argc==1 || p==0 || p->n>0x7fffffff
  87220. || p->n==sqlite3_aggregate_count(context) );
  87221. #endif
  87222. }
  87223. static void countFinalize(sqlite3_context *context){
  87224. CountCtx *p;
  87225. p = sqlite3_aggregate_context(context, 0);
  87226. sqlite3_result_int64(context, p ? p->n : 0);
  87227. }
  87228. /*
  87229. ** Routines to implement min() and max() aggregate functions.
  87230. */
  87231. static void minmaxStep(
  87232. sqlite3_context *context,
  87233. int NotUsed,
  87234. sqlite3_value **argv
  87235. ){
  87236. Mem *pArg = (Mem *)argv[0];
  87237. Mem *pBest;
  87238. UNUSED_PARAMETER(NotUsed);
  87239. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  87240. if( !pBest ) return;
  87241. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  87242. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  87243. }else if( pBest->flags ){
  87244. int max;
  87245. int cmp;
  87246. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  87247. /* This step function is used for both the min() and max() aggregates,
  87248. ** the only difference between the two being that the sense of the
  87249. ** comparison is inverted. For the max() aggregate, the
  87250. ** sqlite3_user_data() function returns (void *)-1. For min() it
  87251. ** returns (void *)db, where db is the sqlite3* database pointer.
  87252. ** Therefore the next statement sets variable 'max' to 1 for the max()
  87253. ** aggregate, or 0 for min().
  87254. */
  87255. max = sqlite3_user_data(context)!=0;
  87256. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  87257. if( (max && cmp<0) || (!max && cmp>0) ){
  87258. sqlite3VdbeMemCopy(pBest, pArg);
  87259. }else{
  87260. sqlite3SkipAccumulatorLoad(context);
  87261. }
  87262. }else{
  87263. sqlite3VdbeMemCopy(pBest, pArg);
  87264. }
  87265. }
  87266. static void minMaxFinalize(sqlite3_context *context){
  87267. sqlite3_value *pRes;
  87268. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  87269. if( pRes ){
  87270. if( pRes->flags ){
  87271. sqlite3_result_value(context, pRes);
  87272. }
  87273. sqlite3VdbeMemRelease(pRes);
  87274. }
  87275. }
  87276. /*
  87277. ** group_concat(EXPR, ?SEPARATOR?)
  87278. */
  87279. static void groupConcatStep(
  87280. sqlite3_context *context,
  87281. int argc,
  87282. sqlite3_value **argv
  87283. ){
  87284. const char *zVal;
  87285. StrAccum *pAccum;
  87286. const char *zSep;
  87287. int nVal, nSep;
  87288. assert( argc==1 || argc==2 );
  87289. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  87290. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  87291. if( pAccum ){
  87292. sqlite3 *db = sqlite3_context_db_handle(context);
  87293. int firstTerm = pAccum->useMalloc==0;
  87294. pAccum->useMalloc = 2;
  87295. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  87296. if( !firstTerm ){
  87297. if( argc==2 ){
  87298. zSep = (char*)sqlite3_value_text(argv[1]);
  87299. nSep = sqlite3_value_bytes(argv[1]);
  87300. }else{
  87301. zSep = ",";
  87302. nSep = 1;
  87303. }
  87304. sqlite3StrAccumAppend(pAccum, zSep, nSep);
  87305. }
  87306. zVal = (char*)sqlite3_value_text(argv[0]);
  87307. nVal = sqlite3_value_bytes(argv[0]);
  87308. sqlite3StrAccumAppend(pAccum, zVal, nVal);
  87309. }
  87310. }
  87311. static void groupConcatFinalize(sqlite3_context *context){
  87312. StrAccum *pAccum;
  87313. pAccum = sqlite3_aggregate_context(context, 0);
  87314. if( pAccum ){
  87315. if( pAccum->accError==STRACCUM_TOOBIG ){
  87316. sqlite3_result_error_toobig(context);
  87317. }else if( pAccum->accError==STRACCUM_NOMEM ){
  87318. sqlite3_result_error_nomem(context);
  87319. }else{
  87320. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  87321. sqlite3_free);
  87322. }
  87323. }
  87324. }
  87325. /*
  87326. ** This routine does per-connection function registration. Most
  87327. ** of the built-in functions above are part of the global function set.
  87328. ** This routine only deals with those that are not global.
  87329. */
  87330. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  87331. int rc = sqlite3_overload_function(db, "MATCH", 2);
  87332. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  87333. if( rc==SQLITE_NOMEM ){
  87334. db->mallocFailed = 1;
  87335. }
  87336. }
  87337. /*
  87338. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  87339. */
  87340. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  87341. FuncDef *pDef;
  87342. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  87343. 2, SQLITE_UTF8, 0);
  87344. if( ALWAYS(pDef) ){
  87345. pDef->funcFlags |= flagVal;
  87346. }
  87347. }
  87348. /*
  87349. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  87350. ** parameter determines whether or not the LIKE operator is case
  87351. ** sensitive. GLOB is always case sensitive.
  87352. */
  87353. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  87354. struct compareInfo *pInfo;
  87355. if( caseSensitive ){
  87356. pInfo = (struct compareInfo*)&likeInfoAlt;
  87357. }else{
  87358. pInfo = (struct compareInfo*)&likeInfoNorm;
  87359. }
  87360. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  87361. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  87362. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  87363. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  87364. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  87365. setLikeOptFlag(db, "like",
  87366. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  87367. }
  87368. /*
  87369. ** pExpr points to an expression which implements a function. If
  87370. ** it is appropriate to apply the LIKE optimization to that function
  87371. ** then set aWc[0] through aWc[2] to the wildcard characters and
  87372. ** return TRUE. If the function is not a LIKE-style function then
  87373. ** return FALSE.
  87374. */
  87375. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  87376. FuncDef *pDef;
  87377. if( pExpr->op!=TK_FUNCTION
  87378. || !pExpr->x.pList
  87379. || pExpr->x.pList->nExpr!=2
  87380. ){
  87381. return 0;
  87382. }
  87383. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  87384. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  87385. sqlite3Strlen30(pExpr->u.zToken),
  87386. 2, SQLITE_UTF8, 0);
  87387. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  87388. return 0;
  87389. }
  87390. /* The memcpy() statement assumes that the wildcard characters are
  87391. ** the first three statements in the compareInfo structure. The
  87392. ** asserts() that follow verify that assumption
  87393. */
  87394. memcpy(aWc, pDef->pUserData, 3);
  87395. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  87396. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  87397. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  87398. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  87399. return 1;
  87400. }
  87401. /*
  87402. ** All all of the FuncDef structures in the aBuiltinFunc[] array above
  87403. ** to the global function hash table. This occurs at start-time (as
  87404. ** a consequence of calling sqlite3_initialize()).
  87405. **
  87406. ** After this routine runs
  87407. */
  87408. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  87409. /*
  87410. ** The following array holds FuncDef structures for all of the functions
  87411. ** defined in this file.
  87412. **
  87413. ** The array cannot be constant since changes are made to the
  87414. ** FuncDef.pHash elements at start-time. The elements of this array
  87415. ** are read-only after initialization is complete.
  87416. */
  87417. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  87418. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  87419. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  87420. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  87421. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  87422. FUNCTION(trim, 1, 3, 0, trimFunc ),
  87423. FUNCTION(trim, 2, 3, 0, trimFunc ),
  87424. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  87425. FUNCTION(min, 0, 0, 1, 0 ),
  87426. AGGREGATE(min, 1, 0, 1, minmaxStep, minMaxFinalize ),
  87427. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  87428. FUNCTION(max, 0, 1, 1, 0 ),
  87429. AGGREGATE(max, 1, 1, 1, minmaxStep, minMaxFinalize ),
  87430. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  87431. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  87432. FUNCTION(instr, 2, 0, 0, instrFunc ),
  87433. FUNCTION(substr, 2, 0, 0, substrFunc ),
  87434. FUNCTION(substr, 3, 0, 0, substrFunc ),
  87435. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  87436. FUNCTION(char, -1, 0, 0, charFunc ),
  87437. FUNCTION(abs, 1, 0, 0, absFunc ),
  87438. #ifndef SQLITE_OMIT_FLOATING_POINT
  87439. FUNCTION(round, 1, 0, 0, roundFunc ),
  87440. FUNCTION(round, 2, 0, 0, roundFunc ),
  87441. #endif
  87442. FUNCTION(upper, 1, 0, 0, upperFunc ),
  87443. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  87444. FUNCTION(coalesce, 1, 0, 0, 0 ),
  87445. FUNCTION(coalesce, 0, 0, 0, 0 ),
  87446. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  87447. FUNCTION(hex, 1, 0, 0, hexFunc ),
  87448. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  87449. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  87450. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  87451. FUNCTION(random, 0, 0, 0, randomFunc ),
  87452. FUNCTION(randomblob, 1, 0, 0, randomBlob ),
  87453. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  87454. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  87455. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  87456. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  87457. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  87458. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  87459. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  87460. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  87461. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  87462. FUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  87463. FUNCTION(changes, 0, 0, 0, changes ),
  87464. FUNCTION(total_changes, 0, 0, 0, total_changes ),
  87465. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  87466. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  87467. #ifdef SQLITE_SOUNDEX
  87468. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  87469. #endif
  87470. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  87471. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  87472. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  87473. #endif
  87474. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  87475. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  87476. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  87477. /* AGGREGATE(count, 0, 0, 0, countStep, countFinalize ), */
  87478. {0,SQLITE_UTF8|SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0,0},
  87479. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  87480. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  87481. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  87482. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87483. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  87484. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87485. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  87486. #else
  87487. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  87488. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  87489. #endif
  87490. };
  87491. int i;
  87492. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  87493. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  87494. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  87495. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  87496. }
  87497. sqlite3RegisterDateTimeFunctions();
  87498. #ifndef SQLITE_OMIT_ALTERTABLE
  87499. sqlite3AlterFunctions();
  87500. #endif
  87501. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  87502. sqlite3AnalyzeFunctions();
  87503. #endif
  87504. }
  87505. /************** End of func.c ************************************************/
  87506. /************** Begin file fkey.c ********************************************/
  87507. /*
  87508. **
  87509. ** The author disclaims copyright to this source code. In place of
  87510. ** a legal notice, here is a blessing:
  87511. **
  87512. ** May you do good and not evil.
  87513. ** May you find forgiveness for yourself and forgive others.
  87514. ** May you share freely, never taking more than you give.
  87515. **
  87516. *************************************************************************
  87517. ** This file contains code used by the compiler to add foreign key
  87518. ** support to compiled SQL statements.
  87519. */
  87520. #ifndef SQLITE_OMIT_FOREIGN_KEY
  87521. #ifndef SQLITE_OMIT_TRIGGER
  87522. /*
  87523. ** Deferred and Immediate FKs
  87524. ** --------------------------
  87525. **
  87526. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  87527. ** If an immediate foreign key constraint is violated,
  87528. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  87529. ** statement transaction rolled back. If a
  87530. ** deferred foreign key constraint is violated, no action is taken
  87531. ** immediately. However if the application attempts to commit the
  87532. ** transaction before fixing the constraint violation, the attempt fails.
  87533. **
  87534. ** Deferred constraints are implemented using a simple counter associated
  87535. ** with the database handle. The counter is set to zero each time a
  87536. ** database transaction is opened. Each time a statement is executed
  87537. ** that causes a foreign key violation, the counter is incremented. Each
  87538. ** time a statement is executed that removes an existing violation from
  87539. ** the database, the counter is decremented. When the transaction is
  87540. ** committed, the commit fails if the current value of the counter is
  87541. ** greater than zero. This scheme has two big drawbacks:
  87542. **
  87543. ** * When a commit fails due to a deferred foreign key constraint,
  87544. ** there is no way to tell which foreign constraint is not satisfied,
  87545. ** or which row it is not satisfied for.
  87546. **
  87547. ** * If the database contains foreign key violations when the
  87548. ** transaction is opened, this may cause the mechanism to malfunction.
  87549. **
  87550. ** Despite these problems, this approach is adopted as it seems simpler
  87551. ** than the alternatives.
  87552. **
  87553. ** INSERT operations:
  87554. **
  87555. ** I.1) For each FK for which the table is the child table, search
  87556. ** the parent table for a match. If none is found increment the
  87557. ** constraint counter.
  87558. **
  87559. ** I.2) For each FK for which the table is the parent table,
  87560. ** search the child table for rows that correspond to the new
  87561. ** row in the parent table. Decrement the counter for each row
  87562. ** found (as the constraint is now satisfied).
  87563. **
  87564. ** DELETE operations:
  87565. **
  87566. ** D.1) For each FK for which the table is the child table,
  87567. ** search the parent table for a row that corresponds to the
  87568. ** deleted row in the child table. If such a row is not found,
  87569. ** decrement the counter.
  87570. **
  87571. ** D.2) For each FK for which the table is the parent table, search
  87572. ** the child table for rows that correspond to the deleted row
  87573. ** in the parent table. For each found increment the counter.
  87574. **
  87575. ** UPDATE operations:
  87576. **
  87577. ** An UPDATE command requires that all 4 steps above are taken, but only
  87578. ** for FK constraints for which the affected columns are actually
  87579. ** modified (values must be compared at runtime).
  87580. **
  87581. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  87582. ** This simplifies the implementation a bit.
  87583. **
  87584. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  87585. ** resolution is considered to delete rows before the new row is inserted.
  87586. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  87587. ** is thrown, even if the FK constraint would be satisfied after the new
  87588. ** row is inserted.
  87589. **
  87590. ** Immediate constraints are usually handled similarly. The only difference
  87591. ** is that the counter used is stored as part of each individual statement
  87592. ** object (struct Vdbe). If, after the statement has run, its immediate
  87593. ** constraint counter is greater than zero,
  87594. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  87595. ** and the statement transaction is rolled back. An exception is an INSERT
  87596. ** statement that inserts a single row only (no triggers). In this case,
  87597. ** instead of using a counter, an exception is thrown immediately if the
  87598. ** INSERT violates a foreign key constraint. This is necessary as such
  87599. ** an INSERT does not open a statement transaction.
  87600. **
  87601. ** TODO: How should dropping a table be handled? How should renaming a
  87602. ** table be handled?
  87603. **
  87604. **
  87605. ** Query API Notes
  87606. ** ---------------
  87607. **
  87608. ** Before coding an UPDATE or DELETE row operation, the code-generator
  87609. ** for those two operations needs to know whether or not the operation
  87610. ** requires any FK processing and, if so, which columns of the original
  87611. ** row are required by the FK processing VDBE code (i.e. if FKs were
  87612. ** implemented using triggers, which of the old.* columns would be
  87613. ** accessed). No information is required by the code-generator before
  87614. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  87615. ** generation code to query for this information are:
  87616. **
  87617. ** sqlite3FkRequired() - Test to see if FK processing is required.
  87618. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  87619. **
  87620. **
  87621. ** Externally accessible module functions
  87622. ** --------------------------------------
  87623. **
  87624. ** sqlite3FkCheck() - Check for foreign key violations.
  87625. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  87626. ** sqlite3FkDelete() - Delete an FKey structure.
  87627. */
  87628. /*
  87629. ** VDBE Calling Convention
  87630. ** -----------------------
  87631. **
  87632. ** Example:
  87633. **
  87634. ** For the following INSERT statement:
  87635. **
  87636. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  87637. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  87638. **
  87639. ** Register (x): 2 (type integer)
  87640. ** Register (x+1): 1 (type integer)
  87641. ** Register (x+2): NULL (type NULL)
  87642. ** Register (x+3): 3.1 (type real)
  87643. */
  87644. /*
  87645. ** A foreign key constraint requires that the key columns in the parent
  87646. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  87647. ** Given that pParent is the parent table for foreign key constraint pFKey,
  87648. ** search the schema for a unique index on the parent key columns.
  87649. **
  87650. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  87651. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  87652. ** is set to point to the unique index.
  87653. **
  87654. ** If the parent key consists of a single column (the foreign key constraint
  87655. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  87656. ** Otherwise, it is set to point to an allocated array of size N, where
  87657. ** N is the number of columns in the parent key. The first element of the
  87658. ** array is the index of the child table column that is mapped by the FK
  87659. ** constraint to the parent table column stored in the left-most column
  87660. ** of index *ppIdx. The second element of the array is the index of the
  87661. ** child table column that corresponds to the second left-most column of
  87662. ** *ppIdx, and so on.
  87663. **
  87664. ** If the required index cannot be found, either because:
  87665. **
  87666. ** 1) The named parent key columns do not exist, or
  87667. **
  87668. ** 2) The named parent key columns do exist, but are not subject to a
  87669. ** UNIQUE or PRIMARY KEY constraint, or
  87670. **
  87671. ** 3) No parent key columns were provided explicitly as part of the
  87672. ** foreign key definition, and the parent table does not have a
  87673. ** PRIMARY KEY, or
  87674. **
  87675. ** 4) No parent key columns were provided explicitly as part of the
  87676. ** foreign key definition, and the PRIMARY KEY of the parent table
  87677. ** consists of a a different number of columns to the child key in
  87678. ** the child table.
  87679. **
  87680. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  87681. ** into pParse. If an OOM error occurs, non-zero is returned and the
  87682. ** pParse->db->mallocFailed flag is set.
  87683. */
  87684. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  87685. Parse *pParse, /* Parse context to store any error in */
  87686. Table *pParent, /* Parent table of FK constraint pFKey */
  87687. FKey *pFKey, /* Foreign key to find index for */
  87688. Index **ppIdx, /* OUT: Unique index on parent table */
  87689. int **paiCol /* OUT: Map of index columns in pFKey */
  87690. ){
  87691. Index *pIdx = 0; /* Value to return via *ppIdx */
  87692. int *aiCol = 0; /* Value to return via *paiCol */
  87693. int nCol = pFKey->nCol; /* Number of columns in parent key */
  87694. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  87695. /* The caller is responsible for zeroing output parameters. */
  87696. assert( ppIdx && *ppIdx==0 );
  87697. assert( !paiCol || *paiCol==0 );
  87698. assert( pParse );
  87699. /* If this is a non-composite (single column) foreign key, check if it
  87700. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  87701. ** and *paiCol set to zero and return early.
  87702. **
  87703. ** Otherwise, for a composite foreign key (more than one column), allocate
  87704. ** space for the aiCol array (returned via output parameter *paiCol).
  87705. ** Non-composite foreign keys do not require the aiCol array.
  87706. */
  87707. if( nCol==1 ){
  87708. /* The FK maps to the IPK if any of the following are true:
  87709. **
  87710. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  87711. ** mapped to the primary key of table pParent, or
  87712. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  87713. ** PRIMARY KEY.
  87714. */
  87715. if( pParent->iPKey>=0 ){
  87716. if( !zKey ) return 0;
  87717. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  87718. }
  87719. }else if( paiCol ){
  87720. assert( nCol>1 );
  87721. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  87722. if( !aiCol ) return 1;
  87723. *paiCol = aiCol;
  87724. }
  87725. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  87726. if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){
  87727. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  87728. ** of columns. If each indexed column corresponds to a foreign key
  87729. ** column of pFKey, then this index is a winner. */
  87730. if( zKey==0 ){
  87731. /* If zKey is NULL, then this foreign key is implicitly mapped to
  87732. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  87733. ** identified by the test (Index.autoIndex==2). */
  87734. if( pIdx->autoIndex==2 ){
  87735. if( aiCol ){
  87736. int i;
  87737. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  87738. }
  87739. break;
  87740. }
  87741. }else{
  87742. /* If zKey is non-NULL, then this foreign key was declared to
  87743. ** map to an explicit list of columns in table pParent. Check if this
  87744. ** index matches those columns. Also, check that the index uses
  87745. ** the default collation sequences for each column. */
  87746. int i, j;
  87747. for(i=0; i<nCol; i++){
  87748. int iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  87749. char *zDfltColl; /* Def. collation for column */
  87750. char *zIdxCol; /* Name of indexed column */
  87751. /* If the index uses a collation sequence that is different from
  87752. ** the default collation sequence for the column, this index is
  87753. ** unusable. Bail out early in this case. */
  87754. zDfltColl = pParent->aCol[iCol].zColl;
  87755. if( !zDfltColl ){
  87756. zDfltColl = "BINARY";
  87757. }
  87758. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  87759. zIdxCol = pParent->aCol[iCol].zName;
  87760. for(j=0; j<nCol; j++){
  87761. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  87762. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  87763. break;
  87764. }
  87765. }
  87766. if( j==nCol ) break;
  87767. }
  87768. if( i==nCol ) break; /* pIdx is usable */
  87769. }
  87770. }
  87771. }
  87772. if( !pIdx ){
  87773. if( !pParse->disableTriggers ){
  87774. sqlite3ErrorMsg(pParse,
  87775. "foreign key mismatch - \"%w\" referencing \"%w\"",
  87776. pFKey->pFrom->zName, pFKey->zTo);
  87777. }
  87778. sqlite3DbFree(pParse->db, aiCol);
  87779. return 1;
  87780. }
  87781. *ppIdx = pIdx;
  87782. return 0;
  87783. }
  87784. /*
  87785. ** This function is called when a row is inserted into or deleted from the
  87786. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  87787. ** on the child table of pFKey, this function is invoked twice for each row
  87788. ** affected - once to "delete" the old row, and then again to "insert" the
  87789. ** new row.
  87790. **
  87791. ** Each time it is called, this function generates VDBE code to locate the
  87792. ** row in the parent table that corresponds to the row being inserted into
  87793. ** or deleted from the child table. If the parent row can be found, no
  87794. ** special action is taken. Otherwise, if the parent row can *not* be
  87795. ** found in the parent table:
  87796. **
  87797. ** Operation | FK type | Action taken
  87798. ** --------------------------------------------------------------------------
  87799. ** INSERT immediate Increment the "immediate constraint counter".
  87800. **
  87801. ** DELETE immediate Decrement the "immediate constraint counter".
  87802. **
  87803. ** INSERT deferred Increment the "deferred constraint counter".
  87804. **
  87805. ** DELETE deferred Decrement the "deferred constraint counter".
  87806. **
  87807. ** These operations are identified in the comment at the top of this file
  87808. ** (fkey.c) as "I.1" and "D.1".
  87809. */
  87810. static void fkLookupParent(
  87811. Parse *pParse, /* Parse context */
  87812. int iDb, /* Index of database housing pTab */
  87813. Table *pTab, /* Parent table of FK pFKey */
  87814. Index *pIdx, /* Unique index on parent key columns in pTab */
  87815. FKey *pFKey, /* Foreign key constraint */
  87816. int *aiCol, /* Map from parent key columns to child table columns */
  87817. int regData, /* Address of array containing child table row */
  87818. int nIncr, /* Increment constraint counter by this */
  87819. int isIgnore /* If true, pretend pTab contains all NULL values */
  87820. ){
  87821. int i; /* Iterator variable */
  87822. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  87823. int iCur = pParse->nTab - 1; /* Cursor number to use */
  87824. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  87825. /* If nIncr is less than zero, then check at runtime if there are any
  87826. ** outstanding constraints to resolve. If there are not, there is no need
  87827. ** to check if deleting this row resolves any outstanding violations.
  87828. **
  87829. ** Check if any of the key columns in the child table row are NULL. If
  87830. ** any are, then the constraint is considered satisfied. No need to
  87831. ** search for a matching row in the parent table. */
  87832. if( nIncr<0 ){
  87833. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  87834. }
  87835. for(i=0; i<pFKey->nCol; i++){
  87836. int iReg = aiCol[i] + regData + 1;
  87837. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
  87838. }
  87839. if( isIgnore==0 ){
  87840. if( pIdx==0 ){
  87841. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  87842. ** column of the parent table (table pTab). */
  87843. int iMustBeInt; /* Address of MustBeInt instruction */
  87844. int regTemp = sqlite3GetTempReg(pParse);
  87845. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  87846. ** apply the affinity of the parent key). If this fails, then there
  87847. ** is no matching parent key. Before using MustBeInt, make a copy of
  87848. ** the value. Otherwise, the value inserted into the child key column
  87849. ** will have INTEGER affinity applied to it, which may not be correct. */
  87850. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  87851. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  87852. /* If the parent table is the same as the child table, and we are about
  87853. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  87854. ** then check if the row being inserted matches itself. If so, do not
  87855. ** increment the constraint-counter. */
  87856. if( pTab==pFKey->pFrom && nIncr==1 ){
  87857. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
  87858. }
  87859. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  87860. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
  87861. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  87862. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  87863. sqlite3VdbeJumpHere(v, iMustBeInt);
  87864. sqlite3ReleaseTempReg(pParse, regTemp);
  87865. }else{
  87866. int nCol = pFKey->nCol;
  87867. int regTemp = sqlite3GetTempRange(pParse, nCol);
  87868. int regRec = sqlite3GetTempReg(pParse);
  87869. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  87870. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  87871. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  87872. for(i=0; i<nCol; i++){
  87873. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  87874. }
  87875. /* If the parent table is the same as the child table, and we are about
  87876. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  87877. ** then check if the row being inserted matches itself. If so, do not
  87878. ** increment the constraint-counter.
  87879. **
  87880. ** If any of the parent-key values are NULL, then the row cannot match
  87881. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  87882. ** of the parent-key values are NULL (at this point it is known that
  87883. ** none of the child key values are).
  87884. */
  87885. if( pTab==pFKey->pFrom && nIncr==1 ){
  87886. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  87887. for(i=0; i<nCol; i++){
  87888. int iChild = aiCol[i]+1+regData;
  87889. int iParent = pIdx->aiColumn[i]+1+regData;
  87890. assert( aiCol[i]!=pTab->iPKey );
  87891. if( pIdx->aiColumn[i]==pTab->iPKey ){
  87892. /* The parent key is a composite key that includes the IPK column */
  87893. iParent = regData;
  87894. }
  87895. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
  87896. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  87897. }
  87898. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  87899. }
  87900. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
  87901. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  87902. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
  87903. sqlite3ReleaseTempReg(pParse, regRec);
  87904. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  87905. }
  87906. }
  87907. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  87908. && !pParse->pToplevel
  87909. && !pParse->isMultiWrite
  87910. ){
  87911. /* Special case: If this is an INSERT statement that will insert exactly
  87912. ** one row into the table, raise a constraint immediately instead of
  87913. ** incrementing a counter. This is necessary as the VM code is being
  87914. ** generated for will not open a statement transaction. */
  87915. assert( nIncr==1 );
  87916. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  87917. OE_Abort, "foreign key constraint failed", P4_STATIC
  87918. );
  87919. }else{
  87920. if( nIncr>0 && pFKey->isDeferred==0 ){
  87921. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  87922. }
  87923. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  87924. }
  87925. sqlite3VdbeResolveLabel(v, iOk);
  87926. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  87927. }
  87928. /*
  87929. ** This function is called to generate code executed when a row is deleted
  87930. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  87931. ** deferred, when a row is inserted into the same table. When generating
  87932. ** code for an SQL UPDATE operation, this function may be called twice -
  87933. ** once to "delete" the old row and once to "insert" the new row.
  87934. **
  87935. ** The code generated by this function scans through the rows in the child
  87936. ** table that correspond to the parent table row being deleted or inserted.
  87937. ** For each child row found, one of the following actions is taken:
  87938. **
  87939. ** Operation | FK type | Action taken
  87940. ** --------------------------------------------------------------------------
  87941. ** DELETE immediate Increment the "immediate constraint counter".
  87942. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  87943. ** throw a "foreign key constraint failed" exception.
  87944. **
  87945. ** INSERT immediate Decrement the "immediate constraint counter".
  87946. **
  87947. ** DELETE deferred Increment the "deferred constraint counter".
  87948. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  87949. ** throw a "foreign key constraint failed" exception.
  87950. **
  87951. ** INSERT deferred Decrement the "deferred constraint counter".
  87952. **
  87953. ** These operations are identified in the comment at the top of this file
  87954. ** (fkey.c) as "I.2" and "D.2".
  87955. */
  87956. static void fkScanChildren(
  87957. Parse *pParse, /* Parse context */
  87958. SrcList *pSrc, /* SrcList containing the table to scan */
  87959. Table *pTab,
  87960. Index *pIdx, /* Foreign key index */
  87961. FKey *pFKey, /* Foreign key relationship */
  87962. int *aiCol, /* Map from pIdx cols to child table cols */
  87963. int regData, /* Referenced table data starts here */
  87964. int nIncr /* Amount to increment deferred counter by */
  87965. ){
  87966. sqlite3 *db = pParse->db; /* Database handle */
  87967. int i; /* Iterator variable */
  87968. Expr *pWhere = 0; /* WHERE clause to scan with */
  87969. NameContext sNameContext; /* Context used to resolve WHERE clause */
  87970. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  87971. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  87972. Vdbe *v = sqlite3GetVdbe(pParse);
  87973. assert( !pIdx || pIdx->pTable==pTab );
  87974. if( nIncr<0 ){
  87975. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  87976. }
  87977. /* Create an Expr object representing an SQL expression like:
  87978. **
  87979. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  87980. **
  87981. ** The collation sequence used for the comparison should be that of
  87982. ** the parent key columns. The affinity of the parent key column should
  87983. ** be applied to each child key value before the comparison takes place.
  87984. */
  87985. for(i=0; i<pFKey->nCol; i++){
  87986. Expr *pLeft; /* Value from parent table row */
  87987. Expr *pRight; /* Column ref to child table */
  87988. Expr *pEq; /* Expression (pLeft = pRight) */
  87989. int iCol; /* Index of column in child table */
  87990. const char *zCol; /* Name of column in child table */
  87991. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  87992. if( pLeft ){
  87993. /* Set the collation sequence and affinity of the LHS of each TK_EQ
  87994. ** expression to the parent key column defaults. */
  87995. if( pIdx ){
  87996. Column *pCol;
  87997. const char *zColl;
  87998. iCol = pIdx->aiColumn[i];
  87999. pCol = &pTab->aCol[iCol];
  88000. if( pTab->iPKey==iCol ) iCol = -1;
  88001. pLeft->iTable = regData+iCol+1;
  88002. pLeft->affinity = pCol->affinity;
  88003. zColl = pCol->zColl;
  88004. if( zColl==0 ) zColl = db->pDfltColl->zName;
  88005. pLeft = sqlite3ExprAddCollateString(pParse, pLeft, zColl);
  88006. }else{
  88007. pLeft->iTable = regData;
  88008. pLeft->affinity = SQLITE_AFF_INTEGER;
  88009. }
  88010. }
  88011. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  88012. assert( iCol>=0 );
  88013. zCol = pFKey->pFrom->aCol[iCol].zName;
  88014. pRight = sqlite3Expr(db, TK_ID, zCol);
  88015. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  88016. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88017. }
  88018. /* If the child table is the same as the parent table, and this scan
  88019. ** is taking place as part of a DELETE operation (operation D.2), omit the
  88020. ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE
  88021. ** clause, where $rowid is the rowid of the row being deleted. */
  88022. if( pTab==pFKey->pFrom && nIncr>0 ){
  88023. Expr *pEq; /* Expression (pLeft = pRight) */
  88024. Expr *pLeft; /* Value from parent table row */
  88025. Expr *pRight; /* Column ref to child table */
  88026. pLeft = sqlite3Expr(db, TK_REGISTER, 0);
  88027. pRight = sqlite3Expr(db, TK_COLUMN, 0);
  88028. if( pLeft && pRight ){
  88029. pLeft->iTable = regData;
  88030. pLeft->affinity = SQLITE_AFF_INTEGER;
  88031. pRight->iTable = pSrc->a[0].iCursor;
  88032. pRight->iColumn = -1;
  88033. }
  88034. pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  88035. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88036. }
  88037. /* Resolve the references in the WHERE clause. */
  88038. memset(&sNameContext, 0, sizeof(NameContext));
  88039. sNameContext.pSrcList = pSrc;
  88040. sNameContext.pParse = pParse;
  88041. sqlite3ResolveExprNames(&sNameContext, pWhere);
  88042. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  88043. ** clause. If the constraint is not deferred, throw an exception for
  88044. ** each row found. Otherwise, for deferred constraints, increment the
  88045. ** deferred constraint counter by nIncr for each row selected. */
  88046. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  88047. if( nIncr>0 && pFKey->isDeferred==0 ){
  88048. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  88049. }
  88050. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  88051. if( pWInfo ){
  88052. sqlite3WhereEnd(pWInfo);
  88053. }
  88054. /* Clean up the WHERE clause constructed above. */
  88055. sqlite3ExprDelete(db, pWhere);
  88056. if( iFkIfZero ){
  88057. sqlite3VdbeJumpHere(v, iFkIfZero);
  88058. }
  88059. }
  88060. /*
  88061. ** This function returns a pointer to the head of a linked list of FK
  88062. ** constraints for which table pTab is the parent table. For example,
  88063. ** given the following schema:
  88064. **
  88065. ** CREATE TABLE t1(a PRIMARY KEY);
  88066. ** CREATE TABLE t2(b REFERENCES t1(a);
  88067. **
  88068. ** Calling this function with table "t1" as an argument returns a pointer
  88069. ** to the FKey structure representing the foreign key constraint on table
  88070. ** "t2". Calling this function with "t2" as the argument would return a
  88071. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  88072. ** table).
  88073. */
  88074. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  88075. int nName = sqlite3Strlen30(pTab->zName);
  88076. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
  88077. }
  88078. /*
  88079. ** The second argument is a Trigger structure allocated by the
  88080. ** fkActionTrigger() routine. This function deletes the Trigger structure
  88081. ** and all of its sub-components.
  88082. **
  88083. ** The Trigger structure or any of its sub-components may be allocated from
  88084. ** the lookaside buffer belonging to database handle dbMem.
  88085. */
  88086. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  88087. if( p ){
  88088. TriggerStep *pStep = p->step_list;
  88089. sqlite3ExprDelete(dbMem, pStep->pWhere);
  88090. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  88091. sqlite3SelectDelete(dbMem, pStep->pSelect);
  88092. sqlite3ExprDelete(dbMem, p->pWhen);
  88093. sqlite3DbFree(dbMem, p);
  88094. }
  88095. }
  88096. /*
  88097. ** This function is called to generate code that runs when table pTab is
  88098. ** being dropped from the database. The SrcList passed as the second argument
  88099. ** to this function contains a single entry guaranteed to resolve to
  88100. ** table pTab.
  88101. **
  88102. ** Normally, no code is required. However, if either
  88103. **
  88104. ** (a) The table is the parent table of a FK constraint, or
  88105. ** (b) The table is the child table of a deferred FK constraint and it is
  88106. ** determined at runtime that there are outstanding deferred FK
  88107. ** constraint violations in the database,
  88108. **
  88109. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  88110. ** the table from the database. Triggers are disabled while running this
  88111. ** DELETE, but foreign key actions are not.
  88112. */
  88113. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  88114. sqlite3 *db = pParse->db;
  88115. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  88116. int iSkip = 0;
  88117. Vdbe *v = sqlite3GetVdbe(pParse);
  88118. assert( v ); /* VDBE has already been allocated */
  88119. if( sqlite3FkReferences(pTab)==0 ){
  88120. /* Search for a deferred foreign key constraint for which this table
  88121. ** is the child table. If one cannot be found, return without
  88122. ** generating any VDBE code. If one can be found, then jump over
  88123. ** the entire DELETE if there are no outstanding deferred constraints
  88124. ** when this statement is run. */
  88125. FKey *p;
  88126. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88127. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  88128. }
  88129. if( !p ) return;
  88130. iSkip = sqlite3VdbeMakeLabel(v);
  88131. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
  88132. }
  88133. pParse->disableTriggers = 1;
  88134. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  88135. pParse->disableTriggers = 0;
  88136. /* If the DELETE has generated immediate foreign key constraint
  88137. ** violations, halt the VDBE and return an error at this point, before
  88138. ** any modifications to the schema are made. This is because statement
  88139. ** transactions are not able to rollback schema changes.
  88140. **
  88141. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  88142. ** the statement transaction will not be rolled back even if FK
  88143. ** constraints are violated.
  88144. */
  88145. if( (db->flags & SQLITE_DeferFKs)==0 ){
  88146. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  88147. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  88148. OE_Abort, "foreign key constraint failed", P4_STATIC
  88149. );
  88150. }
  88151. if( iSkip ){
  88152. sqlite3VdbeResolveLabel(v, iSkip);
  88153. }
  88154. }
  88155. }
  88156. /*
  88157. ** The second argument points to an FKey object representing a foreign key
  88158. ** for which pTab is the child table. An UPDATE statement against pTab
  88159. ** is currently being processed. For each column of the table that is
  88160. ** actually updated, the corresponding element in the aChange[] array
  88161. ** is zero or greater (if a column is unmodified the corresponding element
  88162. ** is set to -1). If the rowid column is modified by the UPDATE statement
  88163. ** the bChngRowid argument is non-zero.
  88164. **
  88165. ** This function returns true if any of the columns that are part of the
  88166. ** child key for FK constraint *p are modified.
  88167. */
  88168. static int fkChildIsModified(
  88169. Table *pTab, /* Table being updated */
  88170. FKey *p, /* Foreign key for which pTab is the child */
  88171. int *aChange, /* Array indicating modified columns */
  88172. int bChngRowid /* True if rowid is modified by this update */
  88173. ){
  88174. int i;
  88175. for(i=0; i<p->nCol; i++){
  88176. int iChildKey = p->aCol[i].iFrom;
  88177. if( aChange[iChildKey]>=0 ) return 1;
  88178. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  88179. }
  88180. return 0;
  88181. }
  88182. /*
  88183. ** The second argument points to an FKey object representing a foreign key
  88184. ** for which pTab is the parent table. An UPDATE statement against pTab
  88185. ** is currently being processed. For each column of the table that is
  88186. ** actually updated, the corresponding element in the aChange[] array
  88187. ** is zero or greater (if a column is unmodified the corresponding element
  88188. ** is set to -1). If the rowid column is modified by the UPDATE statement
  88189. ** the bChngRowid argument is non-zero.
  88190. **
  88191. ** This function returns true if any of the columns that are part of the
  88192. ** parent key for FK constraint *p are modified.
  88193. */
  88194. static int fkParentIsModified(
  88195. Table *pTab,
  88196. FKey *p,
  88197. int *aChange,
  88198. int bChngRowid
  88199. ){
  88200. int i;
  88201. for(i=0; i<p->nCol; i++){
  88202. char *zKey = p->aCol[i].zCol;
  88203. int iKey;
  88204. for(iKey=0; iKey<pTab->nCol; iKey++){
  88205. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  88206. Column *pCol = &pTab->aCol[iKey];
  88207. if( zKey ){
  88208. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  88209. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  88210. return 1;
  88211. }
  88212. }
  88213. }
  88214. }
  88215. return 0;
  88216. }
  88217. /*
  88218. ** This function is called when inserting, deleting or updating a row of
  88219. ** table pTab to generate VDBE code to perform foreign key constraint
  88220. ** processing for the operation.
  88221. **
  88222. ** For a DELETE operation, parameter regOld is passed the index of the
  88223. ** first register in an array of (pTab->nCol+1) registers containing the
  88224. ** rowid of the row being deleted, followed by each of the column values
  88225. ** of the row being deleted, from left to right. Parameter regNew is passed
  88226. ** zero in this case.
  88227. **
  88228. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  88229. ** first register of an array of (pTab->nCol+1) registers containing the new
  88230. ** row data.
  88231. **
  88232. ** For an UPDATE operation, this function is called twice. Once before
  88233. ** the original record is deleted from the table using the calling convention
  88234. ** described for DELETE. Then again after the original record is deleted
  88235. ** but before the new record is inserted using the INSERT convention.
  88236. */
  88237. SQLITE_PRIVATE void sqlite3FkCheck(
  88238. Parse *pParse, /* Parse context */
  88239. Table *pTab, /* Row is being deleted from this table */
  88240. int regOld, /* Previous row data is stored here */
  88241. int regNew, /* New row data is stored here */
  88242. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  88243. int bChngRowid /* True if rowid is UPDATEd */
  88244. ){
  88245. sqlite3 *db = pParse->db; /* Database handle */
  88246. FKey *pFKey; /* Used to iterate through FKs */
  88247. int iDb; /* Index of database containing pTab */
  88248. const char *zDb; /* Name of database containing pTab */
  88249. int isIgnoreErrors = pParse->disableTriggers;
  88250. /* Exactly one of regOld and regNew should be non-zero. */
  88251. assert( (regOld==0)!=(regNew==0) );
  88252. /* If foreign-keys are disabled, this function is a no-op. */
  88253. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  88254. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  88255. zDb = db->aDb[iDb].zName;
  88256. /* Loop through all the foreign key constraints for which pTab is the
  88257. ** child table (the table that the foreign key definition is part of). */
  88258. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  88259. Table *pTo; /* Parent table of foreign key pFKey */
  88260. Index *pIdx = 0; /* Index on key columns in pTo */
  88261. int *aiFree = 0;
  88262. int *aiCol;
  88263. int iCol;
  88264. int i;
  88265. int isIgnore = 0;
  88266. if( aChange
  88267. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  88268. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  88269. ){
  88270. continue;
  88271. }
  88272. /* Find the parent table of this foreign key. Also find a unique index
  88273. ** on the parent key columns in the parent table. If either of these
  88274. ** schema items cannot be located, set an error in pParse and return
  88275. ** early. */
  88276. if( pParse->disableTriggers ){
  88277. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  88278. }else{
  88279. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  88280. }
  88281. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  88282. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  88283. if( !isIgnoreErrors || db->mallocFailed ) return;
  88284. if( pTo==0 ){
  88285. /* If isIgnoreErrors is true, then a table is being dropped. In this
  88286. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  88287. ** before actually dropping it in order to check FK constraints.
  88288. ** If the parent table of an FK constraint on the current table is
  88289. ** missing, behave as if it is empty. i.e. decrement the relevant
  88290. ** FK counter for each row of the current table with non-NULL keys.
  88291. */
  88292. Vdbe *v = sqlite3GetVdbe(pParse);
  88293. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  88294. for(i=0; i<pFKey->nCol; i++){
  88295. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  88296. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump);
  88297. }
  88298. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  88299. }
  88300. continue;
  88301. }
  88302. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  88303. if( aiFree ){
  88304. aiCol = aiFree;
  88305. }else{
  88306. iCol = pFKey->aCol[0].iFrom;
  88307. aiCol = &iCol;
  88308. }
  88309. for(i=0; i<pFKey->nCol; i++){
  88310. if( aiCol[i]==pTab->iPKey ){
  88311. aiCol[i] = -1;
  88312. }
  88313. #ifndef SQLITE_OMIT_AUTHORIZATION
  88314. /* Request permission to read the parent key columns. If the
  88315. ** authorization callback returns SQLITE_IGNORE, behave as if any
  88316. ** values read from the parent table are NULL. */
  88317. if( db->xAuth ){
  88318. int rcauth;
  88319. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  88320. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  88321. isIgnore = (rcauth==SQLITE_IGNORE);
  88322. }
  88323. #endif
  88324. }
  88325. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  88326. ** a cursor to use to search the unique index on the parent key columns
  88327. ** in the parent table. */
  88328. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  88329. pParse->nTab++;
  88330. if( regOld!=0 ){
  88331. /* A row is being removed from the child table. Search for the parent.
  88332. ** If the parent does not exist, removing the child row resolves an
  88333. ** outstanding foreign key constraint violation. */
  88334. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  88335. }
  88336. if( regNew!=0 ){
  88337. /* A row is being added to the child table. If a parent row cannot
  88338. ** be found, adding the child row has violated the FK constraint. */
  88339. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  88340. }
  88341. sqlite3DbFree(db, aiFree);
  88342. }
  88343. /* Loop through all the foreign key constraints that refer to this table */
  88344. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  88345. Index *pIdx = 0; /* Foreign key index for pFKey */
  88346. SrcList *pSrc;
  88347. int *aiCol = 0;
  88348. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  88349. continue;
  88350. }
  88351. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  88352. && !pParse->pToplevel && !pParse->isMultiWrite
  88353. ){
  88354. assert( regOld==0 && regNew!=0 );
  88355. /* Inserting a single row into a parent table cannot cause an immediate
  88356. ** foreign key violation. So do nothing in this case. */
  88357. continue;
  88358. }
  88359. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  88360. if( !isIgnoreErrors || db->mallocFailed ) return;
  88361. continue;
  88362. }
  88363. assert( aiCol || pFKey->nCol==1 );
  88364. /* Create a SrcList structure containing a single table (the table
  88365. ** the foreign key that refers to this table is attached to). This
  88366. ** is required for the sqlite3WhereXXX() interface. */
  88367. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  88368. if( pSrc ){
  88369. struct SrcList_item *pItem = pSrc->a;
  88370. pItem->pTab = pFKey->pFrom;
  88371. pItem->zName = pFKey->pFrom->zName;
  88372. pItem->pTab->nRef++;
  88373. pItem->iCursor = pParse->nTab++;
  88374. if( regNew!=0 ){
  88375. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  88376. }
  88377. if( regOld!=0 ){
  88378. /* If there is a RESTRICT action configured for the current operation
  88379. ** on the parent table of this FK, then throw an exception
  88380. ** immediately if the FK constraint is violated, even if this is a
  88381. ** deferred trigger. That's what RESTRICT means. To defer checking
  88382. ** the constraint, the FK should specify NO ACTION (represented
  88383. ** using OE_None). NO ACTION is the default. */
  88384. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  88385. }
  88386. pItem->zName = 0;
  88387. sqlite3SrcListDelete(db, pSrc);
  88388. }
  88389. sqlite3DbFree(db, aiCol);
  88390. }
  88391. }
  88392. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  88393. /*
  88394. ** This function is called before generating code to update or delete a
  88395. ** row contained in table pTab.
  88396. */
  88397. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  88398. Parse *pParse, /* Parse context */
  88399. Table *pTab /* Table being modified */
  88400. ){
  88401. u32 mask = 0;
  88402. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88403. FKey *p;
  88404. int i;
  88405. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88406. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  88407. }
  88408. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  88409. Index *pIdx = 0;
  88410. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  88411. if( pIdx ){
  88412. for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  88413. }
  88414. }
  88415. }
  88416. return mask;
  88417. }
  88418. /*
  88419. ** This function is called before generating code to update or delete a
  88420. ** row contained in table pTab. If the operation is a DELETE, then
  88421. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  88422. ** to an array of size N, where N is the number of columns in table pTab.
  88423. ** If the i'th column is not modified by the UPDATE, then the corresponding
  88424. ** entry in the aChange[] array is set to -1. If the column is modified,
  88425. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  88426. ** UPDATE statement modifies the rowid fields of the table.
  88427. **
  88428. ** If any foreign key processing will be required, this function returns
  88429. ** true. If there is no foreign key related processing, this function
  88430. ** returns false.
  88431. */
  88432. SQLITE_PRIVATE int sqlite3FkRequired(
  88433. Parse *pParse, /* Parse context */
  88434. Table *pTab, /* Table being modified */
  88435. int *aChange, /* Non-NULL for UPDATE operations */
  88436. int chngRowid /* True for UPDATE that affects rowid */
  88437. ){
  88438. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88439. if( !aChange ){
  88440. /* A DELETE operation. Foreign key processing is required if the
  88441. ** table in question is either the child or parent table for any
  88442. ** foreign key constraint. */
  88443. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  88444. }else{
  88445. /* This is an UPDATE. Foreign key processing is only required if the
  88446. ** operation modifies one or more child or parent key columns. */
  88447. FKey *p;
  88448. /* Check if any child key columns are being modified. */
  88449. for(p=pTab->pFKey; p; p=p->pNextFrom){
  88450. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  88451. }
  88452. /* Check if any parent key columns are being modified. */
  88453. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  88454. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  88455. }
  88456. }
  88457. }
  88458. return 0;
  88459. }
  88460. /*
  88461. ** This function is called when an UPDATE or DELETE operation is being
  88462. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  88463. ** If the current operation is an UPDATE, then the pChanges parameter is
  88464. ** passed a pointer to the list of columns being modified. If it is a
  88465. ** DELETE, pChanges is passed a NULL pointer.
  88466. **
  88467. ** It returns a pointer to a Trigger structure containing a trigger
  88468. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  88469. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  88470. ** returned (these actions require no special handling by the triggers
  88471. ** sub-system, code for them is created by fkScanChildren()).
  88472. **
  88473. ** For example, if pFKey is the foreign key and pTab is table "p" in
  88474. ** the following schema:
  88475. **
  88476. ** CREATE TABLE p(pk PRIMARY KEY);
  88477. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  88478. **
  88479. ** then the returned trigger structure is equivalent to:
  88480. **
  88481. ** CREATE TRIGGER ... DELETE ON p BEGIN
  88482. ** DELETE FROM c WHERE ck = old.pk;
  88483. ** END;
  88484. **
  88485. ** The returned pointer is cached as part of the foreign key object. It
  88486. ** is eventually freed along with the rest of the foreign key object by
  88487. ** sqlite3FkDelete().
  88488. */
  88489. static Trigger *fkActionTrigger(
  88490. Parse *pParse, /* Parse context */
  88491. Table *pTab, /* Table being updated or deleted from */
  88492. FKey *pFKey, /* Foreign key to get action for */
  88493. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  88494. ){
  88495. sqlite3 *db = pParse->db; /* Database handle */
  88496. int action; /* One of OE_None, OE_Cascade etc. */
  88497. Trigger *pTrigger; /* Trigger definition to return */
  88498. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  88499. action = pFKey->aAction[iAction];
  88500. pTrigger = pFKey->apTrigger[iAction];
  88501. if( action!=OE_None && !pTrigger ){
  88502. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  88503. char const *zFrom; /* Name of child table */
  88504. int nFrom; /* Length in bytes of zFrom */
  88505. Index *pIdx = 0; /* Parent key index for this FK */
  88506. int *aiCol = 0; /* child table cols -> parent key cols */
  88507. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  88508. Expr *pWhere = 0; /* WHERE clause of trigger step */
  88509. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  88510. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  88511. int i; /* Iterator variable */
  88512. Expr *pWhen = 0; /* WHEN clause for the trigger */
  88513. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  88514. assert( aiCol || pFKey->nCol==1 );
  88515. for(i=0; i<pFKey->nCol; i++){
  88516. Token tOld = { "old", 3 }; /* Literal "old" token */
  88517. Token tNew = { "new", 3 }; /* Literal "new" token */
  88518. Token tFromCol; /* Name of column in child table */
  88519. Token tToCol; /* Name of column in parent table */
  88520. int iFromCol; /* Idx of column in child table */
  88521. Expr *pEq; /* tFromCol = OLD.tToCol */
  88522. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  88523. assert( iFromCol>=0 );
  88524. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  88525. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  88526. tToCol.n = sqlite3Strlen30(tToCol.z);
  88527. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  88528. /* Create the expression "OLD.zToCol = zFromCol". It is important
  88529. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  88530. ** that the affinity and collation sequence associated with the
  88531. ** parent table are used for the comparison. */
  88532. pEq = sqlite3PExpr(pParse, TK_EQ,
  88533. sqlite3PExpr(pParse, TK_DOT,
  88534. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  88535. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  88536. , 0),
  88537. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  88538. , 0);
  88539. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  88540. /* For ON UPDATE, construct the next term of the WHEN clause.
  88541. ** The final WHEN clause will be like this:
  88542. **
  88543. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  88544. */
  88545. if( pChanges ){
  88546. pEq = sqlite3PExpr(pParse, TK_IS,
  88547. sqlite3PExpr(pParse, TK_DOT,
  88548. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  88549. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  88550. 0),
  88551. sqlite3PExpr(pParse, TK_DOT,
  88552. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  88553. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  88554. 0),
  88555. 0);
  88556. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  88557. }
  88558. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  88559. Expr *pNew;
  88560. if( action==OE_Cascade ){
  88561. pNew = sqlite3PExpr(pParse, TK_DOT,
  88562. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  88563. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  88564. , 0);
  88565. }else if( action==OE_SetDflt ){
  88566. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  88567. if( pDflt ){
  88568. pNew = sqlite3ExprDup(db, pDflt, 0);
  88569. }else{
  88570. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  88571. }
  88572. }else{
  88573. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  88574. }
  88575. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  88576. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  88577. }
  88578. }
  88579. sqlite3DbFree(db, aiCol);
  88580. zFrom = pFKey->pFrom->zName;
  88581. nFrom = sqlite3Strlen30(zFrom);
  88582. if( action==OE_Restrict ){
  88583. Token tFrom;
  88584. Expr *pRaise;
  88585. tFrom.z = zFrom;
  88586. tFrom.n = nFrom;
  88587. pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
  88588. if( pRaise ){
  88589. pRaise->affinity = OE_Abort;
  88590. }
  88591. pSelect = sqlite3SelectNew(pParse,
  88592. sqlite3ExprListAppend(pParse, 0, pRaise),
  88593. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  88594. pWhere,
  88595. 0, 0, 0, 0, 0, 0
  88596. );
  88597. pWhere = 0;
  88598. }
  88599. /* Disable lookaside memory allocation */
  88600. enableLookaside = db->lookaside.bEnabled;
  88601. db->lookaside.bEnabled = 0;
  88602. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  88603. sizeof(Trigger) + /* struct Trigger */
  88604. sizeof(TriggerStep) + /* Single step in trigger program */
  88605. nFrom + 1 /* Space for pStep->target.z */
  88606. );
  88607. if( pTrigger ){
  88608. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  88609. pStep->target.z = (char *)&pStep[1];
  88610. pStep->target.n = nFrom;
  88611. memcpy((char *)pStep->target.z, zFrom, nFrom);
  88612. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  88613. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  88614. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  88615. if( pWhen ){
  88616. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  88617. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  88618. }
  88619. }
  88620. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  88621. db->lookaside.bEnabled = enableLookaside;
  88622. sqlite3ExprDelete(db, pWhere);
  88623. sqlite3ExprDelete(db, pWhen);
  88624. sqlite3ExprListDelete(db, pList);
  88625. sqlite3SelectDelete(db, pSelect);
  88626. if( db->mallocFailed==1 ){
  88627. fkTriggerDelete(db, pTrigger);
  88628. return 0;
  88629. }
  88630. assert( pStep!=0 );
  88631. switch( action ){
  88632. case OE_Restrict:
  88633. pStep->op = TK_SELECT;
  88634. break;
  88635. case OE_Cascade:
  88636. if( !pChanges ){
  88637. pStep->op = TK_DELETE;
  88638. break;
  88639. }
  88640. default:
  88641. pStep->op = TK_UPDATE;
  88642. }
  88643. pStep->pTrig = pTrigger;
  88644. pTrigger->pSchema = pTab->pSchema;
  88645. pTrigger->pTabSchema = pTab->pSchema;
  88646. pFKey->apTrigger[iAction] = pTrigger;
  88647. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  88648. }
  88649. return pTrigger;
  88650. }
  88651. /*
  88652. ** This function is called when deleting or updating a row to implement
  88653. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  88654. */
  88655. SQLITE_PRIVATE void sqlite3FkActions(
  88656. Parse *pParse, /* Parse context */
  88657. Table *pTab, /* Table being updated or deleted from */
  88658. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  88659. int regOld, /* Address of array containing old row */
  88660. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  88661. int bChngRowid /* True if rowid is UPDATEd */
  88662. ){
  88663. /* If foreign-key support is enabled, iterate through all FKs that
  88664. ** refer to table pTab. If there is an action associated with the FK
  88665. ** for this operation (either update or delete), invoke the associated
  88666. ** trigger sub-program. */
  88667. if( pParse->db->flags&SQLITE_ForeignKeys ){
  88668. FKey *pFKey; /* Iterator variable */
  88669. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  88670. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  88671. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  88672. if( pAct ){
  88673. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  88674. }
  88675. }
  88676. }
  88677. }
  88678. }
  88679. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  88680. /*
  88681. ** Free all memory associated with foreign key definitions attached to
  88682. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  88683. ** hash table.
  88684. */
  88685. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  88686. FKey *pFKey; /* Iterator variable */
  88687. FKey *pNext; /* Copy of pFKey->pNextFrom */
  88688. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  88689. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  88690. /* Remove the FK from the fkeyHash hash table. */
  88691. if( !db || db->pnBytesFreed==0 ){
  88692. if( pFKey->pPrevTo ){
  88693. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  88694. }else{
  88695. void *p = (void *)pFKey->pNextTo;
  88696. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  88697. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), p);
  88698. }
  88699. if( pFKey->pNextTo ){
  88700. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  88701. }
  88702. }
  88703. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  88704. ** classified as either immediate or deferred.
  88705. */
  88706. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  88707. /* Delete any triggers created to implement actions for this FK. */
  88708. #ifndef SQLITE_OMIT_TRIGGER
  88709. fkTriggerDelete(db, pFKey->apTrigger[0]);
  88710. fkTriggerDelete(db, pFKey->apTrigger[1]);
  88711. #endif
  88712. pNext = pFKey->pNextFrom;
  88713. sqlite3DbFree(db, pFKey);
  88714. }
  88715. }
  88716. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  88717. /************** End of fkey.c ************************************************/
  88718. /************** Begin file insert.c ******************************************/
  88719. /*
  88720. ** 2001 September 15
  88721. **
  88722. ** The author disclaims copyright to this source code. In place of
  88723. ** a legal notice, here is a blessing:
  88724. **
  88725. ** May you do good and not evil.
  88726. ** May you find forgiveness for yourself and forgive others.
  88727. ** May you share freely, never taking more than you give.
  88728. **
  88729. *************************************************************************
  88730. ** This file contains C code routines that are called by the parser
  88731. ** to handle INSERT statements in SQLite.
  88732. */
  88733. /*
  88734. ** Generate code that will open a table for reading.
  88735. */
  88736. SQLITE_PRIVATE void sqlite3OpenTable(
  88737. Parse *p, /* Generate code into this VDBE */
  88738. int iCur, /* The cursor number of the table */
  88739. int iDb, /* The database index in sqlite3.aDb[] */
  88740. Table *pTab, /* The table to be opened */
  88741. int opcode /* OP_OpenRead or OP_OpenWrite */
  88742. ){
  88743. Vdbe *v;
  88744. assert( !IsVirtual(pTab) );
  88745. v = sqlite3GetVdbe(p);
  88746. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  88747. sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
  88748. sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
  88749. sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
  88750. VdbeComment((v, "%s", pTab->zName));
  88751. }
  88752. /*
  88753. ** Return a pointer to the column affinity string associated with index
  88754. ** pIdx. A column affinity string has one character for each column in
  88755. ** the table, according to the affinity of the column:
  88756. **
  88757. ** Character Column affinity
  88758. ** ------------------------------
  88759. ** 'a' TEXT
  88760. ** 'b' NONE
  88761. ** 'c' NUMERIC
  88762. ** 'd' INTEGER
  88763. ** 'e' REAL
  88764. **
  88765. ** An extra 'd' is appended to the end of the string to cover the
  88766. ** rowid that appears as the last column in every index.
  88767. **
  88768. ** Memory for the buffer containing the column index affinity string
  88769. ** is managed along with the rest of the Index structure. It will be
  88770. ** released when sqlite3DeleteIndex() is called.
  88771. */
  88772. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  88773. if( !pIdx->zColAff ){
  88774. /* The first time a column affinity string for a particular index is
  88775. ** required, it is allocated and populated here. It is then stored as
  88776. ** a member of the Index structure for subsequent use.
  88777. **
  88778. ** The column affinity string will eventually be deleted by
  88779. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  88780. ** up.
  88781. */
  88782. int n;
  88783. Table *pTab = pIdx->pTable;
  88784. sqlite3 *db = sqlite3VdbeDb(v);
  88785. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+2);
  88786. if( !pIdx->zColAff ){
  88787. db->mallocFailed = 1;
  88788. return 0;
  88789. }
  88790. for(n=0; n<pIdx->nColumn; n++){
  88791. pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
  88792. }
  88793. pIdx->zColAff[n++] = SQLITE_AFF_INTEGER;
  88794. pIdx->zColAff[n] = 0;
  88795. }
  88796. return pIdx->zColAff;
  88797. }
  88798. /*
  88799. ** Set P4 of the most recently inserted opcode to a column affinity
  88800. ** string for table pTab. A column affinity string has one character
  88801. ** for each column indexed by the index, according to the affinity of the
  88802. ** column:
  88803. **
  88804. ** Character Column affinity
  88805. ** ------------------------------
  88806. ** 'a' TEXT
  88807. ** 'b' NONE
  88808. ** 'c' NUMERIC
  88809. ** 'd' INTEGER
  88810. ** 'e' REAL
  88811. */
  88812. SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
  88813. /* The first time a column affinity string for a particular table
  88814. ** is required, it is allocated and populated here. It is then
  88815. ** stored as a member of the Table structure for subsequent use.
  88816. **
  88817. ** The column affinity string will eventually be deleted by
  88818. ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
  88819. */
  88820. if( !pTab->zColAff ){
  88821. char *zColAff;
  88822. int i;
  88823. sqlite3 *db = sqlite3VdbeDb(v);
  88824. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  88825. if( !zColAff ){
  88826. db->mallocFailed = 1;
  88827. return;
  88828. }
  88829. for(i=0; i<pTab->nCol; i++){
  88830. zColAff[i] = pTab->aCol[i].affinity;
  88831. }
  88832. zColAff[pTab->nCol] = '\0';
  88833. pTab->zColAff = zColAff;
  88834. }
  88835. sqlite3VdbeChangeP4(v, -1, pTab->zColAff, P4_TRANSIENT);
  88836. }
  88837. /*
  88838. ** Return non-zero if the table pTab in database iDb or any of its indices
  88839. ** have been opened at any point in the VDBE program beginning at location
  88840. ** iStartAddr throught the end of the program. This is used to see if
  88841. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  88842. ** run without using temporary table for the results of the SELECT.
  88843. */
  88844. static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
  88845. Vdbe *v = sqlite3GetVdbe(p);
  88846. int i;
  88847. int iEnd = sqlite3VdbeCurrentAddr(v);
  88848. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88849. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  88850. #endif
  88851. for(i=iStartAddr; i<iEnd; i++){
  88852. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  88853. assert( pOp!=0 );
  88854. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  88855. Index *pIndex;
  88856. int tnum = pOp->p2;
  88857. if( tnum==pTab->tnum ){
  88858. return 1;
  88859. }
  88860. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  88861. if( tnum==pIndex->tnum ){
  88862. return 1;
  88863. }
  88864. }
  88865. }
  88866. #ifndef SQLITE_OMIT_VIRTUALTABLE
  88867. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  88868. assert( pOp->p4.pVtab!=0 );
  88869. assert( pOp->p4type==P4_VTAB );
  88870. return 1;
  88871. }
  88872. #endif
  88873. }
  88874. return 0;
  88875. }
  88876. #ifndef SQLITE_OMIT_AUTOINCREMENT
  88877. /*
  88878. ** Locate or create an AutoincInfo structure associated with table pTab
  88879. ** which is in database iDb. Return the register number for the register
  88880. ** that holds the maximum rowid.
  88881. **
  88882. ** There is at most one AutoincInfo structure per table even if the
  88883. ** same table is autoincremented multiple times due to inserts within
  88884. ** triggers. A new AutoincInfo structure is created if this is the
  88885. ** first use of table pTab. On 2nd and subsequent uses, the original
  88886. ** AutoincInfo structure is used.
  88887. **
  88888. ** Three memory locations are allocated:
  88889. **
  88890. ** (1) Register to hold the name of the pTab table.
  88891. ** (2) Register to hold the maximum ROWID of pTab.
  88892. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  88893. **
  88894. ** The 2nd register is the one that is returned. That is all the
  88895. ** insert routine needs to know about.
  88896. */
  88897. static int autoIncBegin(
  88898. Parse *pParse, /* Parsing context */
  88899. int iDb, /* Index of the database holding pTab */
  88900. Table *pTab /* The table we are writing to */
  88901. ){
  88902. int memId = 0; /* Register holding maximum rowid */
  88903. if( pTab->tabFlags & TF_Autoincrement ){
  88904. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  88905. AutoincInfo *pInfo;
  88906. pInfo = pToplevel->pAinc;
  88907. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  88908. if( pInfo==0 ){
  88909. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  88910. if( pInfo==0 ) return 0;
  88911. pInfo->pNext = pToplevel->pAinc;
  88912. pToplevel->pAinc = pInfo;
  88913. pInfo->pTab = pTab;
  88914. pInfo->iDb = iDb;
  88915. pToplevel->nMem++; /* Register to hold name of table */
  88916. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  88917. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  88918. }
  88919. memId = pInfo->regCtr;
  88920. }
  88921. return memId;
  88922. }
  88923. /*
  88924. ** This routine generates code that will initialize all of the
  88925. ** register used by the autoincrement tracker.
  88926. */
  88927. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  88928. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  88929. sqlite3 *db = pParse->db; /* The database connection */
  88930. Db *pDb; /* Database only autoinc table */
  88931. int memId; /* Register holding max rowid */
  88932. int addr; /* A VDBE address */
  88933. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  88934. /* This routine is never called during trigger-generation. It is
  88935. ** only called from the top-level */
  88936. assert( pParse->pTriggerTab==0 );
  88937. assert( pParse==sqlite3ParseToplevel(pParse) );
  88938. assert( v ); /* We failed long ago if this is not so */
  88939. for(p = pParse->pAinc; p; p = p->pNext){
  88940. pDb = &db->aDb[p->iDb];
  88941. memId = p->regCtr;
  88942. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  88943. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  88944. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  88945. addr = sqlite3VdbeCurrentAddr(v);
  88946. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  88947. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
  88948. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  88949. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
  88950. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  88951. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  88952. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  88953. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  88954. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
  88955. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  88956. sqlite3VdbeAddOp0(v, OP_Close);
  88957. }
  88958. }
  88959. /*
  88960. ** Update the maximum rowid for an autoincrement calculation.
  88961. **
  88962. ** This routine should be called when the top of the stack holds a
  88963. ** new rowid that is about to be inserted. If that new rowid is
  88964. ** larger than the maximum rowid in the memId memory cell, then the
  88965. ** memory cell is updated. The stack is unchanged.
  88966. */
  88967. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  88968. if( memId>0 ){
  88969. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  88970. }
  88971. }
  88972. /*
  88973. ** This routine generates the code needed to write autoincrement
  88974. ** maximum rowid values back into the sqlite_sequence register.
  88975. ** Every statement that might do an INSERT into an autoincrement
  88976. ** table (either directly or through triggers) needs to call this
  88977. ** routine just before the "exit" code.
  88978. */
  88979. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  88980. AutoincInfo *p;
  88981. Vdbe *v = pParse->pVdbe;
  88982. sqlite3 *db = pParse->db;
  88983. assert( v );
  88984. for(p = pParse->pAinc; p; p = p->pNext){
  88985. Db *pDb = &db->aDb[p->iDb];
  88986. int j1, j2, j3, j4, j5;
  88987. int iRec;
  88988. int memId = p->regCtr;
  88989. iRec = sqlite3GetTempReg(pParse);
  88990. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  88991. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  88992. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
  88993. j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
  88994. j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
  88995. j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
  88996. sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
  88997. sqlite3VdbeJumpHere(v, j2);
  88998. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  88999. j5 = sqlite3VdbeAddOp0(v, OP_Goto);
  89000. sqlite3VdbeJumpHere(v, j4);
  89001. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  89002. sqlite3VdbeJumpHere(v, j1);
  89003. sqlite3VdbeJumpHere(v, j5);
  89004. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  89005. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  89006. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  89007. sqlite3VdbeAddOp0(v, OP_Close);
  89008. sqlite3ReleaseTempReg(pParse, iRec);
  89009. }
  89010. }
  89011. #else
  89012. /*
  89013. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  89014. ** above are all no-ops
  89015. */
  89016. # define autoIncBegin(A,B,C) (0)
  89017. # define autoIncStep(A,B,C)
  89018. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  89019. /*
  89020. ** Generate code for a co-routine that will evaluate a subquery one
  89021. ** row at a time.
  89022. **
  89023. ** The pSelect parameter is the subquery that the co-routine will evaluation.
  89024. ** Information about the location of co-routine and the registers it will use
  89025. ** is returned by filling in the pDest object.
  89026. **
  89027. ** Registers are allocated as follows:
  89028. **
  89029. ** pDest->iSDParm The register holding the next entry-point of the
  89030. ** co-routine. Run the co-routine to its next breakpoint
  89031. ** by calling "OP_Yield $X" where $X is pDest->iSDParm.
  89032. **
  89033. ** pDest->iSDParm+1 The register holding the "completed" flag for the
  89034. ** co-routine. This register is 0 if the previous Yield
  89035. ** generated a new result row, or 1 if the subquery
  89036. ** has completed. If the Yield is called again
  89037. ** after this register becomes 1, then the VDBE will
  89038. ** halt with an SQLITE_INTERNAL error.
  89039. **
  89040. ** pDest->iSdst First result register.
  89041. **
  89042. ** pDest->nSdst Number of result registers.
  89043. **
  89044. ** This routine handles all of the register allocation and fills in the
  89045. ** pDest structure appropriately.
  89046. **
  89047. ** Here is a schematic of the generated code assuming that X is the
  89048. ** co-routine entry-point register reg[pDest->iSDParm], that EOF is the
  89049. ** completed flag reg[pDest->iSDParm+1], and R and S are the range of
  89050. ** registers that hold the result set, reg[pDest->iSdst] through
  89051. ** reg[pDest->iSdst+pDest->nSdst-1]:
  89052. **
  89053. ** X <- A
  89054. ** EOF <- 0
  89055. ** goto B
  89056. ** A: setup for the SELECT
  89057. ** loop rows in the SELECT
  89058. ** load results into registers R..S
  89059. ** yield X
  89060. ** end loop
  89061. ** cleanup after the SELECT
  89062. ** EOF <- 1
  89063. ** yield X
  89064. ** halt-error
  89065. ** B:
  89066. **
  89067. ** To use this subroutine, the caller generates code as follows:
  89068. **
  89069. ** [ Co-routine generated by this subroutine, shown above ]
  89070. ** S: yield X
  89071. ** if EOF goto E
  89072. ** if skip this row, goto C
  89073. ** if terminate loop, goto E
  89074. ** deal with this row
  89075. ** C: goto S
  89076. ** E:
  89077. */
  89078. SQLITE_PRIVATE int sqlite3CodeCoroutine(Parse *pParse, Select *pSelect, SelectDest *pDest){
  89079. int regYield; /* Register holding co-routine entry-point */
  89080. int regEof; /* Register holding co-routine completion flag */
  89081. int addrTop; /* Top of the co-routine */
  89082. int j1; /* Jump instruction */
  89083. int rc; /* Result code */
  89084. Vdbe *v; /* VDBE under construction */
  89085. regYield = ++pParse->nMem;
  89086. regEof = ++pParse->nMem;
  89087. v = sqlite3GetVdbe(pParse);
  89088. addrTop = sqlite3VdbeCurrentAddr(v);
  89089. sqlite3VdbeAddOp2(v, OP_Integer, addrTop+2, regYield); /* X <- A */
  89090. VdbeComment((v, "Co-routine entry point"));
  89091. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof); /* EOF <- 0 */
  89092. VdbeComment((v, "Co-routine completion flag"));
  89093. sqlite3SelectDestInit(pDest, SRT_Coroutine, regYield);
  89094. j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  89095. rc = sqlite3Select(pParse, pSelect, pDest);
  89096. assert( pParse->nErr==0 || rc );
  89097. if( pParse->db->mallocFailed && rc==SQLITE_OK ) rc = SQLITE_NOMEM;
  89098. if( rc ) return rc;
  89099. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof); /* EOF <- 1 */
  89100. sqlite3VdbeAddOp1(v, OP_Yield, regYield); /* yield X */
  89101. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
  89102. VdbeComment((v, "End of coroutine"));
  89103. sqlite3VdbeJumpHere(v, j1); /* label B: */
  89104. return rc;
  89105. }
  89106. /* Forward declaration */
  89107. static int xferOptimization(
  89108. Parse *pParse, /* Parser context */
  89109. Table *pDest, /* The table we are inserting into */
  89110. Select *pSelect, /* A SELECT statement to use as the data source */
  89111. int onError, /* How to handle constraint errors */
  89112. int iDbDest /* The database of pDest */
  89113. );
  89114. /*
  89115. ** This routine is call to handle SQL of the following forms:
  89116. **
  89117. ** insert into TABLE (IDLIST) values(EXPRLIST)
  89118. ** insert into TABLE (IDLIST) select
  89119. **
  89120. ** The IDLIST following the table name is always optional. If omitted,
  89121. ** then a list of all columns for the table is substituted. The IDLIST
  89122. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  89123. **
  89124. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  89125. ** statement above, and pSelect is NULL. For the second form, pList is
  89126. ** NULL and pSelect is a pointer to the select statement used to generate
  89127. ** data for the insert.
  89128. **
  89129. ** The code generated follows one of four templates. For a simple
  89130. ** select with data coming from a VALUES clause, the code executes
  89131. ** once straight down through. Pseudo-code follows (we call this
  89132. ** the "1st template"):
  89133. **
  89134. ** open write cursor to <table> and its indices
  89135. ** puts VALUES clause expressions onto the stack
  89136. ** write the resulting record into <table>
  89137. ** cleanup
  89138. **
  89139. ** The three remaining templates assume the statement is of the form
  89140. **
  89141. ** INSERT INTO <table> SELECT ...
  89142. **
  89143. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  89144. ** in other words if the SELECT pulls all columns from a single table
  89145. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  89146. ** if <table2> and <table1> are distinct tables but have identical
  89147. ** schemas, including all the same indices, then a special optimization
  89148. ** is invoked that copies raw records from <table2> over to <table1>.
  89149. ** See the xferOptimization() function for the implementation of this
  89150. ** template. This is the 2nd template.
  89151. **
  89152. ** open a write cursor to <table>
  89153. ** open read cursor on <table2>
  89154. ** transfer all records in <table2> over to <table>
  89155. ** close cursors
  89156. ** foreach index on <table>
  89157. ** open a write cursor on the <table> index
  89158. ** open a read cursor on the corresponding <table2> index
  89159. ** transfer all records from the read to the write cursors
  89160. ** close cursors
  89161. ** end foreach
  89162. **
  89163. ** The 3rd template is for when the second template does not apply
  89164. ** and the SELECT clause does not read from <table> at any time.
  89165. ** The generated code follows this template:
  89166. **
  89167. ** EOF <- 0
  89168. ** X <- A
  89169. ** goto B
  89170. ** A: setup for the SELECT
  89171. ** loop over the rows in the SELECT
  89172. ** load values into registers R..R+n
  89173. ** yield X
  89174. ** end loop
  89175. ** cleanup after the SELECT
  89176. ** EOF <- 1
  89177. ** yield X
  89178. ** goto A
  89179. ** B: open write cursor to <table> and its indices
  89180. ** C: yield X
  89181. ** if EOF goto D
  89182. ** insert the select result into <table> from R..R+n
  89183. ** goto C
  89184. ** D: cleanup
  89185. **
  89186. ** The 4th template is used if the insert statement takes its
  89187. ** values from a SELECT but the data is being inserted into a table
  89188. ** that is also read as part of the SELECT. In the third form,
  89189. ** we have to use a intermediate table to store the results of
  89190. ** the select. The template is like this:
  89191. **
  89192. ** EOF <- 0
  89193. ** X <- A
  89194. ** goto B
  89195. ** A: setup for the SELECT
  89196. ** loop over the tables in the SELECT
  89197. ** load value into register R..R+n
  89198. ** yield X
  89199. ** end loop
  89200. ** cleanup after the SELECT
  89201. ** EOF <- 1
  89202. ** yield X
  89203. ** halt-error
  89204. ** B: open temp table
  89205. ** L: yield X
  89206. ** if EOF goto M
  89207. ** insert row from R..R+n into temp table
  89208. ** goto L
  89209. ** M: open write cursor to <table> and its indices
  89210. ** rewind temp table
  89211. ** C: loop over rows of intermediate table
  89212. ** transfer values form intermediate table into <table>
  89213. ** end loop
  89214. ** D: cleanup
  89215. */
  89216. SQLITE_PRIVATE void sqlite3Insert(
  89217. Parse *pParse, /* Parser context */
  89218. SrcList *pTabList, /* Name of table into which we are inserting */
  89219. ExprList *pList, /* List of values to be inserted */
  89220. Select *pSelect, /* A SELECT statement to use as the data source */
  89221. IdList *pColumn, /* Column names corresponding to IDLIST. */
  89222. int onError /* How to handle constraint errors */
  89223. ){
  89224. sqlite3 *db; /* The main database structure */
  89225. Table *pTab; /* The table to insert into. aka TABLE */
  89226. char *zTab; /* Name of the table into which we are inserting */
  89227. const char *zDb; /* Name of the database holding this table */
  89228. int i, j, idx; /* Loop counters */
  89229. Vdbe *v; /* Generate code into this virtual machine */
  89230. Index *pIdx; /* For looping over indices of the table */
  89231. int nColumn; /* Number of columns in the data */
  89232. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  89233. int baseCur = 0; /* VDBE Cursor number for pTab */
  89234. int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  89235. int endOfLoop; /* Label for the end of the insertion loop */
  89236. int useTempTable = 0; /* Store SELECT results in intermediate table */
  89237. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  89238. int addrInsTop = 0; /* Jump to label "D" */
  89239. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  89240. int addrSelect = 0; /* Address of coroutine that implements the SELECT */
  89241. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  89242. int iDb; /* Index of database holding TABLE */
  89243. Db *pDb; /* The database containing table being inserted into */
  89244. int appendFlag = 0; /* True if the insert is likely to be an append */
  89245. /* Register allocations */
  89246. int regFromSelect = 0;/* Base register for data coming from SELECT */
  89247. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  89248. int regRowCount = 0; /* Memory cell used for the row counter */
  89249. int regIns; /* Block of regs holding rowid+data being inserted */
  89250. int regRowid; /* registers holding insert rowid */
  89251. int regData; /* register holding first column to insert */
  89252. int regEof = 0; /* Register recording end of SELECT data */
  89253. int *aRegIdx = 0; /* One register allocated to each index */
  89254. #ifndef SQLITE_OMIT_TRIGGER
  89255. int isView; /* True if attempting to insert into a view */
  89256. Trigger *pTrigger; /* List of triggers on pTab, if required */
  89257. int tmask; /* Mask of trigger times */
  89258. #endif
  89259. db = pParse->db;
  89260. memset(&dest, 0, sizeof(dest));
  89261. if( pParse->nErr || db->mallocFailed ){
  89262. goto insert_cleanup;
  89263. }
  89264. /* Locate the table into which we will be inserting new information.
  89265. */
  89266. assert( pTabList->nSrc==1 );
  89267. zTab = pTabList->a[0].zName;
  89268. if( NEVER(zTab==0) ) goto insert_cleanup;
  89269. pTab = sqlite3SrcListLookup(pParse, pTabList);
  89270. if( pTab==0 ){
  89271. goto insert_cleanup;
  89272. }
  89273. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  89274. assert( iDb<db->nDb );
  89275. pDb = &db->aDb[iDb];
  89276. zDb = pDb->zName;
  89277. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  89278. goto insert_cleanup;
  89279. }
  89280. /* Figure out if we have any triggers and if the table being
  89281. ** inserted into is a view
  89282. */
  89283. #ifndef SQLITE_OMIT_TRIGGER
  89284. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  89285. isView = pTab->pSelect!=0;
  89286. #else
  89287. # define pTrigger 0
  89288. # define tmask 0
  89289. # define isView 0
  89290. #endif
  89291. #ifdef SQLITE_OMIT_VIEW
  89292. # undef isView
  89293. # define isView 0
  89294. #endif
  89295. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  89296. /* If pTab is really a view, make sure it has been initialized.
  89297. ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual
  89298. ** module table).
  89299. */
  89300. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  89301. goto insert_cleanup;
  89302. }
  89303. /* Ensure that:
  89304. * (a) the table is not read-only,
  89305. * (b) that if it is a view then ON INSERT triggers exist
  89306. */
  89307. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  89308. goto insert_cleanup;
  89309. }
  89310. /* Allocate a VDBE
  89311. */
  89312. v = sqlite3GetVdbe(pParse);
  89313. if( v==0 ) goto insert_cleanup;
  89314. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  89315. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  89316. #ifndef SQLITE_OMIT_XFER_OPT
  89317. /* If the statement is of the form
  89318. **
  89319. ** INSERT INTO <table1> SELECT * FROM <table2>;
  89320. **
  89321. ** Then special optimizations can be applied that make the transfer
  89322. ** very fast and which reduce fragmentation of indices.
  89323. **
  89324. ** This is the 2nd template.
  89325. */
  89326. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  89327. assert( !pTrigger );
  89328. assert( pList==0 );
  89329. goto insert_end;
  89330. }
  89331. #endif /* SQLITE_OMIT_XFER_OPT */
  89332. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  89333. ** sqlite_sequence table and store it in memory cell regAutoinc.
  89334. */
  89335. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  89336. /* Figure out how many columns of data are supplied. If the data
  89337. ** is coming from a SELECT statement, then generate a co-routine that
  89338. ** produces a single row of the SELECT on each invocation. The
  89339. ** co-routine is the common header to the 3rd and 4th templates.
  89340. */
  89341. if( pSelect ){
  89342. /* Data is coming from a SELECT. Generate a co-routine to run that
  89343. ** SELECT. */
  89344. int rc = sqlite3CodeCoroutine(pParse, pSelect, &dest);
  89345. if( rc ) goto insert_cleanup;
  89346. regEof = dest.iSDParm + 1;
  89347. regFromSelect = dest.iSdst;
  89348. assert( pSelect->pEList );
  89349. nColumn = pSelect->pEList->nExpr;
  89350. assert( dest.nSdst==nColumn );
  89351. /* Set useTempTable to TRUE if the result of the SELECT statement
  89352. ** should be written into a temporary table (template 4). Set to
  89353. ** FALSE if each* row of the SELECT can be written directly into
  89354. ** the destination table (template 3).
  89355. **
  89356. ** A temp table must be used if the table being updated is also one
  89357. ** of the tables being read by the SELECT statement. Also use a
  89358. ** temp table in the case of row triggers.
  89359. */
  89360. if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
  89361. useTempTable = 1;
  89362. }
  89363. if( useTempTable ){
  89364. /* Invoke the coroutine to extract information from the SELECT
  89365. ** and add it to a transient table srcTab. The code generated
  89366. ** here is from the 4th template:
  89367. **
  89368. ** B: open temp table
  89369. ** L: yield X
  89370. ** if EOF goto M
  89371. ** insert row from R..R+n into temp table
  89372. ** goto L
  89373. ** M: ...
  89374. */
  89375. int regRec; /* Register to hold packed record */
  89376. int regTempRowid; /* Register to hold temp table ROWID */
  89377. int addrTop; /* Label "L" */
  89378. int addrIf; /* Address of jump to M */
  89379. srcTab = pParse->nTab++;
  89380. regRec = sqlite3GetTempReg(pParse);
  89381. regTempRowid = sqlite3GetTempReg(pParse);
  89382. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  89383. addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  89384. addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
  89385. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  89386. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  89387. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  89388. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  89389. sqlite3VdbeJumpHere(v, addrIf);
  89390. sqlite3ReleaseTempReg(pParse, regRec);
  89391. sqlite3ReleaseTempReg(pParse, regTempRowid);
  89392. }
  89393. }else{
  89394. /* This is the case if the data for the INSERT is coming from a VALUES
  89395. ** clause
  89396. */
  89397. NameContext sNC;
  89398. memset(&sNC, 0, sizeof(sNC));
  89399. sNC.pParse = pParse;
  89400. srcTab = -1;
  89401. assert( useTempTable==0 );
  89402. nColumn = pList ? pList->nExpr : 0;
  89403. for(i=0; i<nColumn; i++){
  89404. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  89405. goto insert_cleanup;
  89406. }
  89407. }
  89408. }
  89409. /* Make sure the number of columns in the source data matches the number
  89410. ** of columns to be inserted into the table.
  89411. */
  89412. if( IsVirtual(pTab) ){
  89413. for(i=0; i<pTab->nCol; i++){
  89414. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  89415. }
  89416. }
  89417. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  89418. sqlite3ErrorMsg(pParse,
  89419. "table %S has %d columns but %d values were supplied",
  89420. pTabList, 0, pTab->nCol-nHidden, nColumn);
  89421. goto insert_cleanup;
  89422. }
  89423. if( pColumn!=0 && nColumn!=pColumn->nId ){
  89424. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  89425. goto insert_cleanup;
  89426. }
  89427. /* If the INSERT statement included an IDLIST term, then make sure
  89428. ** all elements of the IDLIST really are columns of the table and
  89429. ** remember the column indices.
  89430. **
  89431. ** If the table has an INTEGER PRIMARY KEY column and that column
  89432. ** is named in the IDLIST, then record in the keyColumn variable
  89433. ** the index into IDLIST of the primary key column. keyColumn is
  89434. ** the index of the primary key as it appears in IDLIST, not as
  89435. ** is appears in the original table. (The index of the primary
  89436. ** key in the original table is pTab->iPKey.)
  89437. */
  89438. if( pColumn ){
  89439. for(i=0; i<pColumn->nId; i++){
  89440. pColumn->a[i].idx = -1;
  89441. }
  89442. for(i=0; i<pColumn->nId; i++){
  89443. for(j=0; j<pTab->nCol; j++){
  89444. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  89445. pColumn->a[i].idx = j;
  89446. if( j==pTab->iPKey ){
  89447. keyColumn = i;
  89448. }
  89449. break;
  89450. }
  89451. }
  89452. if( j>=pTab->nCol ){
  89453. if( sqlite3IsRowid(pColumn->a[i].zName) ){
  89454. keyColumn = i;
  89455. }else{
  89456. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  89457. pTabList, 0, pColumn->a[i].zName);
  89458. pParse->checkSchema = 1;
  89459. goto insert_cleanup;
  89460. }
  89461. }
  89462. }
  89463. }
  89464. /* If there is no IDLIST term but the table has an integer primary
  89465. ** key, the set the keyColumn variable to the primary key column index
  89466. ** in the original table definition.
  89467. */
  89468. if( pColumn==0 && nColumn>0 ){
  89469. keyColumn = pTab->iPKey;
  89470. }
  89471. /* Initialize the count of rows to be inserted
  89472. */
  89473. if( db->flags & SQLITE_CountRows ){
  89474. regRowCount = ++pParse->nMem;
  89475. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  89476. }
  89477. /* If this is not a view, open the table and and all indices */
  89478. if( !isView ){
  89479. int nIdx;
  89480. baseCur = pParse->nTab;
  89481. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
  89482. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  89483. if( aRegIdx==0 ){
  89484. goto insert_cleanup;
  89485. }
  89486. for(i=0; i<nIdx; i++){
  89487. aRegIdx[i] = ++pParse->nMem;
  89488. }
  89489. }
  89490. /* This is the top of the main insertion loop */
  89491. if( useTempTable ){
  89492. /* This block codes the top of loop only. The complete loop is the
  89493. ** following pseudocode (template 4):
  89494. **
  89495. ** rewind temp table
  89496. ** C: loop over rows of intermediate table
  89497. ** transfer values form intermediate table into <table>
  89498. ** end loop
  89499. ** D: ...
  89500. */
  89501. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
  89502. addrCont = sqlite3VdbeCurrentAddr(v);
  89503. }else if( pSelect ){
  89504. /* This block codes the top of loop only. The complete loop is the
  89505. ** following pseudocode (template 3):
  89506. **
  89507. ** C: yield X
  89508. ** if EOF goto D
  89509. ** insert the select result into <table> from R..R+n
  89510. ** goto C
  89511. ** D: ...
  89512. */
  89513. addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  89514. addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
  89515. }
  89516. /* Allocate registers for holding the rowid of the new row,
  89517. ** the content of the new row, and the assemblied row record.
  89518. */
  89519. regRowid = regIns = pParse->nMem+1;
  89520. pParse->nMem += pTab->nCol + 1;
  89521. if( IsVirtual(pTab) ){
  89522. regRowid++;
  89523. pParse->nMem++;
  89524. }
  89525. regData = regRowid+1;
  89526. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  89527. */
  89528. endOfLoop = sqlite3VdbeMakeLabel(v);
  89529. if( tmask & TRIGGER_BEFORE ){
  89530. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  89531. /* build the NEW.* reference row. Note that if there is an INTEGER
  89532. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  89533. ** translated into a unique ID for the row. But on a BEFORE trigger,
  89534. ** we do not know what the unique ID will be (because the insert has
  89535. ** not happened yet) so we substitute a rowid of -1
  89536. */
  89537. if( keyColumn<0 ){
  89538. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  89539. }else{
  89540. int j1;
  89541. if( useTempTable ){
  89542. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
  89543. }else{
  89544. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  89545. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
  89546. }
  89547. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
  89548. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  89549. sqlite3VdbeJumpHere(v, j1);
  89550. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
  89551. }
  89552. /* Cannot have triggers on a virtual table. If it were possible,
  89553. ** this block would have to account for hidden column.
  89554. */
  89555. assert( !IsVirtual(pTab) );
  89556. /* Create the new column data
  89557. */
  89558. for(i=0; i<pTab->nCol; i++){
  89559. if( pColumn==0 ){
  89560. j = i;
  89561. }else{
  89562. for(j=0; j<pColumn->nId; j++){
  89563. if( pColumn->a[j].idx==i ) break;
  89564. }
  89565. }
  89566. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  89567. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  89568. }else if( useTempTable ){
  89569. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  89570. }else{
  89571. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  89572. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  89573. }
  89574. }
  89575. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  89576. ** do not attempt any conversions before assembling the record.
  89577. ** If this is a real table, attempt conversions as required by the
  89578. ** table column affinities.
  89579. */
  89580. if( !isView ){
  89581. sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
  89582. sqlite3TableAffinityStr(v, pTab);
  89583. }
  89584. /* Fire BEFORE or INSTEAD OF triggers */
  89585. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  89586. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  89587. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  89588. }
  89589. /* Push the record number for the new entry onto the stack. The
  89590. ** record number is a randomly generate integer created by NewRowid
  89591. ** except when the table has an INTEGER PRIMARY KEY column, in which
  89592. ** case the record number is the same as that column.
  89593. */
  89594. if( !isView ){
  89595. if( IsVirtual(pTab) ){
  89596. /* The row that the VUpdate opcode will delete: none */
  89597. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  89598. }
  89599. if( keyColumn>=0 ){
  89600. if( useTempTable ){
  89601. sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
  89602. }else if( pSelect ){
  89603. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
  89604. }else{
  89605. VdbeOp *pOp;
  89606. sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
  89607. pOp = sqlite3VdbeGetOp(v, -1);
  89608. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  89609. appendFlag = 1;
  89610. pOp->opcode = OP_NewRowid;
  89611. pOp->p1 = baseCur;
  89612. pOp->p2 = regRowid;
  89613. pOp->p3 = regAutoinc;
  89614. }
  89615. }
  89616. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  89617. ** to generate a unique primary key value.
  89618. */
  89619. if( !appendFlag ){
  89620. int j1;
  89621. if( !IsVirtual(pTab) ){
  89622. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
  89623. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  89624. sqlite3VdbeJumpHere(v, j1);
  89625. }else{
  89626. j1 = sqlite3VdbeCurrentAddr(v);
  89627. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
  89628. }
  89629. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
  89630. }
  89631. }else if( IsVirtual(pTab) ){
  89632. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  89633. }else{
  89634. sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
  89635. appendFlag = 1;
  89636. }
  89637. autoIncStep(pParse, regAutoinc, regRowid);
  89638. /* Push onto the stack, data for all columns of the new entry, beginning
  89639. ** with the first column.
  89640. */
  89641. nHidden = 0;
  89642. for(i=0; i<pTab->nCol; i++){
  89643. int iRegStore = regRowid+1+i;
  89644. if( i==pTab->iPKey ){
  89645. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  89646. ** Whenever this column is read, the record number will be substituted
  89647. ** in its place. So will fill this column with a NULL to avoid
  89648. ** taking up data space with information that will never be used. */
  89649. sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
  89650. continue;
  89651. }
  89652. if( pColumn==0 ){
  89653. if( IsHiddenColumn(&pTab->aCol[i]) ){
  89654. assert( IsVirtual(pTab) );
  89655. j = -1;
  89656. nHidden++;
  89657. }else{
  89658. j = i - nHidden;
  89659. }
  89660. }else{
  89661. for(j=0; j<pColumn->nId; j++){
  89662. if( pColumn->a[j].idx==i ) break;
  89663. }
  89664. }
  89665. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  89666. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
  89667. }else if( useTempTable ){
  89668. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  89669. }else if( pSelect ){
  89670. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  89671. }else{
  89672. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  89673. }
  89674. }
  89675. /* Generate code to check constraints and generate index keys and
  89676. ** do the insertion.
  89677. */
  89678. #ifndef SQLITE_OMIT_VIRTUALTABLE
  89679. if( IsVirtual(pTab) ){
  89680. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  89681. sqlite3VtabMakeWritable(pParse, pTab);
  89682. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  89683. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  89684. sqlite3MayAbort(pParse);
  89685. }else
  89686. #endif
  89687. {
  89688. int isReplace; /* Set to true if constraints may cause a replace */
  89689. sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
  89690. keyColumn>=0, 0, onError, endOfLoop, &isReplace
  89691. );
  89692. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  89693. sqlite3CompleteInsertion(
  89694. pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
  89695. );
  89696. }
  89697. }
  89698. /* Update the count of rows that are inserted
  89699. */
  89700. if( (db->flags & SQLITE_CountRows)!=0 ){
  89701. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  89702. }
  89703. if( pTrigger ){
  89704. /* Code AFTER triggers */
  89705. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  89706. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  89707. }
  89708. /* The bottom of the main insertion loop, if the data source
  89709. ** is a SELECT statement.
  89710. */
  89711. sqlite3VdbeResolveLabel(v, endOfLoop);
  89712. if( useTempTable ){
  89713. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
  89714. sqlite3VdbeJumpHere(v, addrInsTop);
  89715. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  89716. }else if( pSelect ){
  89717. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  89718. sqlite3VdbeJumpHere(v, addrInsTop);
  89719. }
  89720. if( !IsVirtual(pTab) && !isView ){
  89721. /* Close all tables opened */
  89722. sqlite3VdbeAddOp1(v, OP_Close, baseCur);
  89723. for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  89724. sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
  89725. }
  89726. }
  89727. insert_end:
  89728. /* Update the sqlite_sequence table by storing the content of the
  89729. ** maximum rowid counter values recorded while inserting into
  89730. ** autoincrement tables.
  89731. */
  89732. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  89733. sqlite3AutoincrementEnd(pParse);
  89734. }
  89735. /*
  89736. ** Return the number of rows inserted. If this routine is
  89737. ** generating code because of a call to sqlite3NestedParse(), do not
  89738. ** invoke the callback function.
  89739. */
  89740. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  89741. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  89742. sqlite3VdbeSetNumCols(v, 1);
  89743. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  89744. }
  89745. insert_cleanup:
  89746. sqlite3SrcListDelete(db, pTabList);
  89747. sqlite3ExprListDelete(db, pList);
  89748. sqlite3SelectDelete(db, pSelect);
  89749. sqlite3IdListDelete(db, pColumn);
  89750. sqlite3DbFree(db, aRegIdx);
  89751. }
  89752. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  89753. ** thely may interfere with compilation of other functions in this file
  89754. ** (or in another file, if this file becomes part of the amalgamation). */
  89755. #ifdef isView
  89756. #undef isView
  89757. #endif
  89758. #ifdef pTrigger
  89759. #undef pTrigger
  89760. #endif
  89761. #ifdef tmask
  89762. #undef tmask
  89763. #endif
  89764. /*
  89765. ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
  89766. **
  89767. ** The input is a range of consecutive registers as follows:
  89768. **
  89769. ** 1. The rowid of the row after the update.
  89770. **
  89771. ** 2. The data in the first column of the entry after the update.
  89772. **
  89773. ** i. Data from middle columns...
  89774. **
  89775. ** N. The data in the last column of the entry after the update.
  89776. **
  89777. ** The regRowid parameter is the index of the register containing (1).
  89778. **
  89779. ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
  89780. ** the address of a register containing the rowid before the update takes
  89781. ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
  89782. ** is false, indicating an INSERT statement, then a non-zero rowidChng
  89783. ** indicates that the rowid was explicitly specified as part of the
  89784. ** INSERT statement. If rowidChng is false, it means that the rowid is
  89785. ** computed automatically in an insert or that the rowid value is not
  89786. ** modified by an update.
  89787. **
  89788. ** The code generated by this routine store new index entries into
  89789. ** registers identified by aRegIdx[]. No index entry is created for
  89790. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  89791. ** the same as the order of indices on the linked list of indices
  89792. ** attached to the table.
  89793. **
  89794. ** This routine also generates code to check constraints. NOT NULL,
  89795. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  89796. ** then the appropriate action is performed. There are five possible
  89797. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  89798. **
  89799. ** Constraint type Action What Happens
  89800. ** --------------- ---------- ----------------------------------------
  89801. ** any ROLLBACK The current transaction is rolled back and
  89802. ** sqlite3_exec() returns immediately with a
  89803. ** return code of SQLITE_CONSTRAINT.
  89804. **
  89805. ** any ABORT Back out changes from the current command
  89806. ** only (do not do a complete rollback) then
  89807. ** cause sqlite3_exec() to return immediately
  89808. ** with SQLITE_CONSTRAINT.
  89809. **
  89810. ** any FAIL Sqlite3_exec() returns immediately with a
  89811. ** return code of SQLITE_CONSTRAINT. The
  89812. ** transaction is not rolled back and any
  89813. ** prior changes are retained.
  89814. **
  89815. ** any IGNORE The record number and data is popped from
  89816. ** the stack and there is an immediate jump
  89817. ** to label ignoreDest.
  89818. **
  89819. ** NOT NULL REPLACE The NULL value is replace by the default
  89820. ** value for that column. If the default value
  89821. ** is NULL, the action is the same as ABORT.
  89822. **
  89823. ** UNIQUE REPLACE The other row that conflicts with the row
  89824. ** being inserted is removed.
  89825. **
  89826. ** CHECK REPLACE Illegal. The results in an exception.
  89827. **
  89828. ** Which action to take is determined by the overrideError parameter.
  89829. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  89830. ** is used. Or if pParse->onError==OE_Default then the onError value
  89831. ** for the constraint is used.
  89832. **
  89833. ** The calling routine must open a read/write cursor for pTab with
  89834. ** cursor number "baseCur". All indices of pTab must also have open
  89835. ** read/write cursors with cursor number baseCur+i for the i-th cursor.
  89836. ** Except, if there is no possibility of a REPLACE action then
  89837. ** cursors do not need to be open for indices where aRegIdx[i]==0.
  89838. */
  89839. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  89840. Parse *pParse, /* The parser context */
  89841. Table *pTab, /* the table into which we are inserting */
  89842. int baseCur, /* Index of a read/write cursor pointing at pTab */
  89843. int regRowid, /* Index of the range of input registers */
  89844. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  89845. int rowidChng, /* True if the rowid might collide with existing entry */
  89846. int isUpdate, /* True for UPDATE, False for INSERT */
  89847. int overrideError, /* Override onError to this if not OE_Default */
  89848. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  89849. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  89850. ){
  89851. int i; /* loop counter */
  89852. Vdbe *v; /* VDBE under constrution */
  89853. int nCol; /* Number of columns */
  89854. int onError; /* Conflict resolution strategy */
  89855. int j1; /* Addresss of jump instruction */
  89856. int j2 = 0, j3; /* Addresses of jump instructions */
  89857. int regData; /* Register containing first data column */
  89858. int iCur; /* Table cursor number */
  89859. Index *pIdx; /* Pointer to one of the indices */
  89860. sqlite3 *db; /* Database connection */
  89861. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  89862. int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
  89863. db = pParse->db;
  89864. v = sqlite3GetVdbe(pParse);
  89865. assert( v!=0 );
  89866. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  89867. nCol = pTab->nCol;
  89868. regData = regRowid + 1;
  89869. /* Test all NOT NULL constraints.
  89870. */
  89871. for(i=0; i<nCol; i++){
  89872. if( i==pTab->iPKey ){
  89873. continue;
  89874. }
  89875. onError = pTab->aCol[i].notNull;
  89876. if( onError==OE_None ) continue;
  89877. if( overrideError!=OE_Default ){
  89878. onError = overrideError;
  89879. }else if( onError==OE_Default ){
  89880. onError = OE_Abort;
  89881. }
  89882. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  89883. onError = OE_Abort;
  89884. }
  89885. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  89886. || onError==OE_Ignore || onError==OE_Replace );
  89887. switch( onError ){
  89888. case OE_Abort:
  89889. sqlite3MayAbort(pParse);
  89890. case OE_Rollback:
  89891. case OE_Fail: {
  89892. char *zMsg;
  89893. sqlite3VdbeAddOp3(v, OP_HaltIfNull,
  89894. SQLITE_CONSTRAINT_NOTNULL, onError, regData+i);
  89895. zMsg = sqlite3MPrintf(db, "%s.%s may not be NULL",
  89896. pTab->zName, pTab->aCol[i].zName);
  89897. sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
  89898. break;
  89899. }
  89900. case OE_Ignore: {
  89901. sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
  89902. break;
  89903. }
  89904. default: {
  89905. assert( onError==OE_Replace );
  89906. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
  89907. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
  89908. sqlite3VdbeJumpHere(v, j1);
  89909. break;
  89910. }
  89911. }
  89912. }
  89913. /* Test all CHECK constraints
  89914. */
  89915. #ifndef SQLITE_OMIT_CHECK
  89916. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  89917. ExprList *pCheck = pTab->pCheck;
  89918. pParse->ckBase = regData;
  89919. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  89920. for(i=0; i<pCheck->nExpr; i++){
  89921. int allOk = sqlite3VdbeMakeLabel(v);
  89922. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  89923. if( onError==OE_Ignore ){
  89924. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  89925. }else{
  89926. char *zConsName = pCheck->a[i].zName;
  89927. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  89928. if( zConsName ){
  89929. zConsName = sqlite3MPrintf(db, "constraint %s failed", zConsName);
  89930. }else{
  89931. zConsName = 0;
  89932. }
  89933. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  89934. onError, zConsName, P4_DYNAMIC);
  89935. }
  89936. sqlite3VdbeResolveLabel(v, allOk);
  89937. }
  89938. }
  89939. #endif /* !defined(SQLITE_OMIT_CHECK) */
  89940. /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  89941. ** of the new record does not previously exist. Except, if this
  89942. ** is an UPDATE and the primary key is not changing, that is OK.
  89943. */
  89944. if( rowidChng ){
  89945. onError = pTab->keyConf;
  89946. if( overrideError!=OE_Default ){
  89947. onError = overrideError;
  89948. }else if( onError==OE_Default ){
  89949. onError = OE_Abort;
  89950. }
  89951. if( isUpdate ){
  89952. j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
  89953. }
  89954. j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
  89955. switch( onError ){
  89956. default: {
  89957. onError = OE_Abort;
  89958. /* Fall thru into the next case */
  89959. }
  89960. case OE_Rollback:
  89961. case OE_Abort:
  89962. case OE_Fail: {
  89963. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  89964. onError, "PRIMARY KEY must be unique", P4_STATIC);
  89965. break;
  89966. }
  89967. case OE_Replace: {
  89968. /* If there are DELETE triggers on this table and the
  89969. ** recursive-triggers flag is set, call GenerateRowDelete() to
  89970. ** remove the conflicting row from the table. This will fire
  89971. ** the triggers and remove both the table and index b-tree entries.
  89972. **
  89973. ** Otherwise, if there are no triggers or the recursive-triggers
  89974. ** flag is not set, but the table has one or more indexes, call
  89975. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  89976. ** only. The table b-tree entry will be replaced by the new entry
  89977. ** when it is inserted.
  89978. **
  89979. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  89980. ** also invoke MultiWrite() to indicate that this VDBE may require
  89981. ** statement rollback (if the statement is aborted after the delete
  89982. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  89983. ** but being more selective here allows statements like:
  89984. **
  89985. ** REPLACE INTO t(rowid) VALUES($newrowid)
  89986. **
  89987. ** to run without a statement journal if there are no indexes on the
  89988. ** table.
  89989. */
  89990. Trigger *pTrigger = 0;
  89991. if( db->flags&SQLITE_RecTriggers ){
  89992. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  89993. }
  89994. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  89995. sqlite3MultiWrite(pParse);
  89996. sqlite3GenerateRowDelete(
  89997. pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
  89998. );
  89999. }else if( pTab->pIndex ){
  90000. sqlite3MultiWrite(pParse);
  90001. sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
  90002. }
  90003. seenReplace = 1;
  90004. break;
  90005. }
  90006. case OE_Ignore: {
  90007. assert( seenReplace==0 );
  90008. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  90009. break;
  90010. }
  90011. }
  90012. sqlite3VdbeJumpHere(v, j3);
  90013. if( isUpdate ){
  90014. sqlite3VdbeJumpHere(v, j2);
  90015. }
  90016. }
  90017. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  90018. ** index and making sure that duplicate entries do not already exist.
  90019. ** Add the new records to the indices as we go.
  90020. */
  90021. for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  90022. int regIdx;
  90023. int regR;
  90024. int addrSkipRow = 0;
  90025. if( aRegIdx[iCur]==0 ) continue; /* Skip unused indices */
  90026. if( pIdx->pPartIdxWhere ){
  90027. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[iCur]);
  90028. addrSkipRow = sqlite3VdbeMakeLabel(v);
  90029. pParse->ckBase = regData;
  90030. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrSkipRow,
  90031. SQLITE_JUMPIFNULL);
  90032. pParse->ckBase = 0;
  90033. }
  90034. /* Create a key for accessing the index entry */
  90035. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
  90036. for(i=0; i<pIdx->nColumn; i++){
  90037. int idx = pIdx->aiColumn[i];
  90038. if( idx==pTab->iPKey ){
  90039. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  90040. }else{
  90041. sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
  90042. }
  90043. }
  90044. sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
  90045. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
  90046. sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
  90047. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
  90048. /* Find out what action to take in case there is an indexing conflict */
  90049. onError = pIdx->onError;
  90050. if( onError==OE_None ){
  90051. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  90052. sqlite3VdbeResolveLabel(v, addrSkipRow);
  90053. continue; /* pIdx is not a UNIQUE index */
  90054. }
  90055. if( overrideError!=OE_Default ){
  90056. onError = overrideError;
  90057. }else if( onError==OE_Default ){
  90058. onError = OE_Abort;
  90059. }
  90060. if( seenReplace ){
  90061. if( onError==OE_Ignore ) onError = OE_Replace;
  90062. else if( onError==OE_Fail ) onError = OE_Abort;
  90063. }
  90064. /* Check to see if the new index entry will be unique */
  90065. regR = sqlite3GetTempReg(pParse);
  90066. sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
  90067. j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
  90068. regR, SQLITE_INT_TO_PTR(regIdx),
  90069. P4_INT32);
  90070. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
  90071. /* Generate code that executes if the new index entry is not unique */
  90072. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  90073. || onError==OE_Ignore || onError==OE_Replace );
  90074. switch( onError ){
  90075. case OE_Rollback:
  90076. case OE_Abort:
  90077. case OE_Fail: {
  90078. int j;
  90079. StrAccum errMsg;
  90080. const char *zSep;
  90081. char *zErr;
  90082. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  90083. errMsg.db = db;
  90084. zSep = pIdx->nColumn>1 ? "columns " : "column ";
  90085. for(j=0; j<pIdx->nColumn; j++){
  90086. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  90087. sqlite3StrAccumAppend(&errMsg, zSep, -1);
  90088. zSep = ", ";
  90089. sqlite3StrAccumAppend(&errMsg, zCol, -1);
  90090. }
  90091. sqlite3StrAccumAppend(&errMsg,
  90092. pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
  90093. zErr = sqlite3StrAccumFinish(&errMsg);
  90094. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_UNIQUE,
  90095. onError, zErr, 0);
  90096. sqlite3DbFree(errMsg.db, zErr);
  90097. break;
  90098. }
  90099. case OE_Ignore: {
  90100. assert( seenReplace==0 );
  90101. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  90102. break;
  90103. }
  90104. default: {
  90105. Trigger *pTrigger = 0;
  90106. assert( onError==OE_Replace );
  90107. sqlite3MultiWrite(pParse);
  90108. if( db->flags&SQLITE_RecTriggers ){
  90109. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  90110. }
  90111. sqlite3GenerateRowDelete(
  90112. pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
  90113. );
  90114. seenReplace = 1;
  90115. break;
  90116. }
  90117. }
  90118. sqlite3VdbeJumpHere(v, j3);
  90119. sqlite3VdbeResolveLabel(v, addrSkipRow);
  90120. sqlite3ReleaseTempReg(pParse, regR);
  90121. }
  90122. if( pbMayReplace ){
  90123. *pbMayReplace = seenReplace;
  90124. }
  90125. }
  90126. /*
  90127. ** This routine generates code to finish the INSERT or UPDATE operation
  90128. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  90129. ** A consecutive range of registers starting at regRowid contains the
  90130. ** rowid and the content to be inserted.
  90131. **
  90132. ** The arguments to this routine should be the same as the first six
  90133. ** arguments to sqlite3GenerateConstraintChecks.
  90134. */
  90135. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  90136. Parse *pParse, /* The parser context */
  90137. Table *pTab, /* the table into which we are inserting */
  90138. int baseCur, /* Index of a read/write cursor pointing at pTab */
  90139. int regRowid, /* Range of content */
  90140. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  90141. int isUpdate, /* True for UPDATE, False for INSERT */
  90142. int appendBias, /* True if this is likely to be an append */
  90143. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  90144. ){
  90145. int i;
  90146. Vdbe *v;
  90147. Index *pIdx;
  90148. u8 pik_flags;
  90149. int regData;
  90150. int regRec;
  90151. v = sqlite3GetVdbe(pParse);
  90152. assert( v!=0 );
  90153. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  90154. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  90155. if( aRegIdx[i]==0 ) continue;
  90156. if( pIdx->pPartIdxWhere ){
  90157. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  90158. }
  90159. sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
  90160. if( useSeekResult ){
  90161. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  90162. }
  90163. }
  90164. regData = regRowid + 1;
  90165. regRec = sqlite3GetTempReg(pParse);
  90166. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  90167. sqlite3TableAffinityStr(v, pTab);
  90168. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  90169. if( pParse->nested ){
  90170. pik_flags = 0;
  90171. }else{
  90172. pik_flags = OPFLAG_NCHANGE;
  90173. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  90174. }
  90175. if( appendBias ){
  90176. pik_flags |= OPFLAG_APPEND;
  90177. }
  90178. if( useSeekResult ){
  90179. pik_flags |= OPFLAG_USESEEKRESULT;
  90180. }
  90181. sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
  90182. if( !pParse->nested ){
  90183. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  90184. }
  90185. sqlite3VdbeChangeP5(v, pik_flags);
  90186. }
  90187. /*
  90188. ** Generate code that will open cursors for a table and for all
  90189. ** indices of that table. The "baseCur" parameter is the cursor number used
  90190. ** for the table. Indices are opened on subsequent cursors.
  90191. **
  90192. ** Return the number of indices on the table.
  90193. */
  90194. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  90195. Parse *pParse, /* Parsing context */
  90196. Table *pTab, /* Table to be opened */
  90197. int baseCur, /* Cursor number assigned to the table */
  90198. int op /* OP_OpenRead or OP_OpenWrite */
  90199. ){
  90200. int i;
  90201. int iDb;
  90202. Index *pIdx;
  90203. Vdbe *v;
  90204. if( IsVirtual(pTab) ) return 0;
  90205. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  90206. v = sqlite3GetVdbe(pParse);
  90207. assert( v!=0 );
  90208. sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
  90209. for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  90210. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  90211. assert( pIdx->pSchema==pTab->pSchema );
  90212. sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
  90213. (char*)pKey, P4_KEYINFO_HANDOFF);
  90214. VdbeComment((v, "%s", pIdx->zName));
  90215. }
  90216. if( pParse->nTab<baseCur+i ){
  90217. pParse->nTab = baseCur+i;
  90218. }
  90219. return i-1;
  90220. }
  90221. #ifdef SQLITE_TEST
  90222. /*
  90223. ** The following global variable is incremented whenever the
  90224. ** transfer optimization is used. This is used for testing
  90225. ** purposes only - to make sure the transfer optimization really
  90226. ** is happening when it is suppose to.
  90227. */
  90228. SQLITE_API int sqlite3_xferopt_count;
  90229. #endif /* SQLITE_TEST */
  90230. #ifndef SQLITE_OMIT_XFER_OPT
  90231. /*
  90232. ** Check to collation names to see if they are compatible.
  90233. */
  90234. static int xferCompatibleCollation(const char *z1, const char *z2){
  90235. if( z1==0 ){
  90236. return z2==0;
  90237. }
  90238. if( z2==0 ){
  90239. return 0;
  90240. }
  90241. return sqlite3StrICmp(z1, z2)==0;
  90242. }
  90243. /*
  90244. ** Check to see if index pSrc is compatible as a source of data
  90245. ** for index pDest in an insert transfer optimization. The rules
  90246. ** for a compatible index:
  90247. **
  90248. ** * The index is over the same set of columns
  90249. ** * The same DESC and ASC markings occurs on all columns
  90250. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  90251. ** * The same collating sequence on each column
  90252. ** * The index has the exact same WHERE clause
  90253. */
  90254. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  90255. int i;
  90256. assert( pDest && pSrc );
  90257. assert( pDest->pTable!=pSrc->pTable );
  90258. if( pDest->nColumn!=pSrc->nColumn ){
  90259. return 0; /* Different number of columns */
  90260. }
  90261. if( pDest->onError!=pSrc->onError ){
  90262. return 0; /* Different conflict resolution strategies */
  90263. }
  90264. for(i=0; i<pSrc->nColumn; i++){
  90265. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  90266. return 0; /* Different columns indexed */
  90267. }
  90268. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  90269. return 0; /* Different sort orders */
  90270. }
  90271. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  90272. return 0; /* Different collating sequences */
  90273. }
  90274. }
  90275. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  90276. return 0; /* Different WHERE clauses */
  90277. }
  90278. /* If no test above fails then the indices must be compatible */
  90279. return 1;
  90280. }
  90281. /*
  90282. ** Attempt the transfer optimization on INSERTs of the form
  90283. **
  90284. ** INSERT INTO tab1 SELECT * FROM tab2;
  90285. **
  90286. ** The xfer optimization transfers raw records from tab2 over to tab1.
  90287. ** Columns are not decoded and reassemblied, which greatly improves
  90288. ** performance. Raw index records are transferred in the same way.
  90289. **
  90290. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  90291. ** There are lots of rules for determining compatibility - see comments
  90292. ** embedded in the code for details.
  90293. **
  90294. ** This routine returns TRUE if the optimization is guaranteed to be used.
  90295. ** Sometimes the xfer optimization will only work if the destination table
  90296. ** is empty - a factor that can only be determined at run-time. In that
  90297. ** case, this routine generates code for the xfer optimization but also
  90298. ** does a test to see if the destination table is empty and jumps over the
  90299. ** xfer optimization code if the test fails. In that case, this routine
  90300. ** returns FALSE so that the caller will know to go ahead and generate
  90301. ** an unoptimized transfer. This routine also returns FALSE if there
  90302. ** is no chance that the xfer optimization can be applied.
  90303. **
  90304. ** This optimization is particularly useful at making VACUUM run faster.
  90305. */
  90306. static int xferOptimization(
  90307. Parse *pParse, /* Parser context */
  90308. Table *pDest, /* The table we are inserting into */
  90309. Select *pSelect, /* A SELECT statement to use as the data source */
  90310. int onError, /* How to handle constraint errors */
  90311. int iDbDest /* The database of pDest */
  90312. ){
  90313. ExprList *pEList; /* The result set of the SELECT */
  90314. Table *pSrc; /* The table in the FROM clause of SELECT */
  90315. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  90316. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  90317. int i; /* Loop counter */
  90318. int iDbSrc; /* The database of pSrc */
  90319. int iSrc, iDest; /* Cursors from source and destination */
  90320. int addr1, addr2; /* Loop addresses */
  90321. int emptyDestTest; /* Address of test for empty pDest */
  90322. int emptySrcTest; /* Address of test for empty pSrc */
  90323. Vdbe *v; /* The VDBE we are building */
  90324. KeyInfo *pKey; /* Key information for an index */
  90325. int regAutoinc; /* Memory register used by AUTOINC */
  90326. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  90327. int regData, regRowid; /* Registers holding data and rowid */
  90328. if( pSelect==0 ){
  90329. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  90330. }
  90331. if( sqlite3TriggerList(pParse, pDest) ){
  90332. return 0; /* tab1 must not have triggers */
  90333. }
  90334. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90335. if( pDest->tabFlags & TF_Virtual ){
  90336. return 0; /* tab1 must not be a virtual table */
  90337. }
  90338. #endif
  90339. if( onError==OE_Default ){
  90340. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  90341. if( onError==OE_Default ) onError = OE_Abort;
  90342. }
  90343. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  90344. if( pSelect->pSrc->nSrc!=1 ){
  90345. return 0; /* FROM clause must have exactly one term */
  90346. }
  90347. if( pSelect->pSrc->a[0].pSelect ){
  90348. return 0; /* FROM clause cannot contain a subquery */
  90349. }
  90350. if( pSelect->pWhere ){
  90351. return 0; /* SELECT may not have a WHERE clause */
  90352. }
  90353. if( pSelect->pOrderBy ){
  90354. return 0; /* SELECT may not have an ORDER BY clause */
  90355. }
  90356. /* Do not need to test for a HAVING clause. If HAVING is present but
  90357. ** there is no ORDER BY, we will get an error. */
  90358. if( pSelect->pGroupBy ){
  90359. return 0; /* SELECT may not have a GROUP BY clause */
  90360. }
  90361. if( pSelect->pLimit ){
  90362. return 0; /* SELECT may not have a LIMIT clause */
  90363. }
  90364. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  90365. if( pSelect->pPrior ){
  90366. return 0; /* SELECT may not be a compound query */
  90367. }
  90368. if( pSelect->selFlags & SF_Distinct ){
  90369. return 0; /* SELECT may not be DISTINCT */
  90370. }
  90371. pEList = pSelect->pEList;
  90372. assert( pEList!=0 );
  90373. if( pEList->nExpr!=1 ){
  90374. return 0; /* The result set must have exactly one column */
  90375. }
  90376. assert( pEList->a[0].pExpr );
  90377. if( pEList->a[0].pExpr->op!=TK_ALL ){
  90378. return 0; /* The result set must be the special operator "*" */
  90379. }
  90380. /* At this point we have established that the statement is of the
  90381. ** correct syntactic form to participate in this optimization. Now
  90382. ** we have to check the semantics.
  90383. */
  90384. pItem = pSelect->pSrc->a;
  90385. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  90386. if( pSrc==0 ){
  90387. return 0; /* FROM clause does not contain a real table */
  90388. }
  90389. if( pSrc==pDest ){
  90390. return 0; /* tab1 and tab2 may not be the same table */
  90391. }
  90392. #ifndef SQLITE_OMIT_VIRTUALTABLE
  90393. if( pSrc->tabFlags & TF_Virtual ){
  90394. return 0; /* tab2 must not be a virtual table */
  90395. }
  90396. #endif
  90397. if( pSrc->pSelect ){
  90398. return 0; /* tab2 may not be a view */
  90399. }
  90400. if( pDest->nCol!=pSrc->nCol ){
  90401. return 0; /* Number of columns must be the same in tab1 and tab2 */
  90402. }
  90403. if( pDest->iPKey!=pSrc->iPKey ){
  90404. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  90405. }
  90406. for(i=0; i<pDest->nCol; i++){
  90407. if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
  90408. return 0; /* Affinity must be the same on all columns */
  90409. }
  90410. if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
  90411. return 0; /* Collating sequence must be the same on all columns */
  90412. }
  90413. if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
  90414. return 0; /* tab2 must be NOT NULL if tab1 is */
  90415. }
  90416. }
  90417. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  90418. if( pDestIdx->onError!=OE_None ){
  90419. destHasUniqueIdx = 1;
  90420. }
  90421. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  90422. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  90423. }
  90424. if( pSrcIdx==0 ){
  90425. return 0; /* pDestIdx has no corresponding index in pSrc */
  90426. }
  90427. }
  90428. #ifndef SQLITE_OMIT_CHECK
  90429. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  90430. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  90431. }
  90432. #endif
  90433. #ifndef SQLITE_OMIT_FOREIGN_KEY
  90434. /* Disallow the transfer optimization if the destination table constains
  90435. ** any foreign key constraints. This is more restrictive than necessary.
  90436. ** But the main beneficiary of the transfer optimization is the VACUUM
  90437. ** command, and the VACUUM command disables foreign key constraints. So
  90438. ** the extra complication to make this rule less restrictive is probably
  90439. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  90440. */
  90441. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  90442. return 0;
  90443. }
  90444. #endif
  90445. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  90446. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  90447. }
  90448. /* If we get this far, it means that the xfer optimization is at
  90449. ** least a possibility, though it might only work if the destination
  90450. ** table (tab1) is initially empty.
  90451. */
  90452. #ifdef SQLITE_TEST
  90453. sqlite3_xferopt_count++;
  90454. #endif
  90455. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  90456. v = sqlite3GetVdbe(pParse);
  90457. sqlite3CodeVerifySchema(pParse, iDbSrc);
  90458. iSrc = pParse->nTab++;
  90459. iDest = pParse->nTab++;
  90460. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  90461. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  90462. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  90463. || destHasUniqueIdx /* (2) */
  90464. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  90465. ){
  90466. /* In some circumstances, we are able to run the xfer optimization
  90467. ** only if the destination table is initially empty. This code makes
  90468. ** that determination. Conditions under which the destination must
  90469. ** be empty:
  90470. **
  90471. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  90472. ** (If the destination is not initially empty, the rowid fields
  90473. ** of index entries might need to change.)
  90474. **
  90475. ** (2) The destination has a unique index. (The xfer optimization
  90476. ** is unable to test uniqueness.)
  90477. **
  90478. ** (3) onError is something other than OE_Abort and OE_Rollback.
  90479. */
  90480. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
  90481. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  90482. sqlite3VdbeJumpHere(v, addr1);
  90483. }else{
  90484. emptyDestTest = 0;
  90485. }
  90486. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  90487. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  90488. regData = sqlite3GetTempReg(pParse);
  90489. regRowid = sqlite3GetTempReg(pParse);
  90490. if( pDest->iPKey>=0 ){
  90491. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  90492. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  90493. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_PRIMARYKEY,
  90494. onError, "PRIMARY KEY must be unique", P4_STATIC);
  90495. sqlite3VdbeJumpHere(v, addr2);
  90496. autoIncStep(pParse, regAutoinc, regRowid);
  90497. }else if( pDest->pIndex==0 ){
  90498. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  90499. }else{
  90500. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  90501. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  90502. }
  90503. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  90504. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  90505. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  90506. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  90507. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
  90508. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  90509. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  90510. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  90511. }
  90512. assert( pSrcIdx );
  90513. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  90514. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90515. pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
  90516. sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
  90517. (char*)pKey, P4_KEYINFO_HANDOFF);
  90518. VdbeComment((v, "%s", pSrcIdx->zName));
  90519. pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
  90520. sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
  90521. (char*)pKey, P4_KEYINFO_HANDOFF);
  90522. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  90523. VdbeComment((v, "%s", pDestIdx->zName));
  90524. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
  90525. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  90526. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  90527. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
  90528. sqlite3VdbeJumpHere(v, addr1);
  90529. }
  90530. sqlite3VdbeJumpHere(v, emptySrcTest);
  90531. sqlite3ReleaseTempReg(pParse, regRowid);
  90532. sqlite3ReleaseTempReg(pParse, regData);
  90533. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  90534. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90535. if( emptyDestTest ){
  90536. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  90537. sqlite3VdbeJumpHere(v, emptyDestTest);
  90538. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  90539. return 0;
  90540. }else{
  90541. return 1;
  90542. }
  90543. }
  90544. #endif /* SQLITE_OMIT_XFER_OPT */
  90545. /************** End of insert.c **********************************************/
  90546. /************** Begin file legacy.c ******************************************/
  90547. /*
  90548. ** 2001 September 15
  90549. **
  90550. ** The author disclaims copyright to this source code. In place of
  90551. ** a legal notice, here is a blessing:
  90552. **
  90553. ** May you do good and not evil.
  90554. ** May you find forgiveness for yourself and forgive others.
  90555. ** May you share freely, never taking more than you give.
  90556. **
  90557. *************************************************************************
  90558. ** Main file for the SQLite library. The routines in this file
  90559. ** implement the programmer interface to the library. Routines in
  90560. ** other files are for internal use by SQLite and should not be
  90561. ** accessed by users of the library.
  90562. */
  90563. /*
  90564. ** Execute SQL code. Return one of the SQLITE_ success/failure
  90565. ** codes. Also write an error message into memory obtained from
  90566. ** malloc() and make *pzErrMsg point to that message.
  90567. **
  90568. ** If the SQL is a query, then for each row in the query result
  90569. ** the xCallback() function is called. pArg becomes the first
  90570. ** argument to xCallback(). If xCallback=NULL then no callback
  90571. ** is invoked, even for queries.
  90572. */
  90573. SQLITE_API int sqlite3_exec(
  90574. sqlite3 *db, /* The database on which the SQL executes */
  90575. const char *zSql, /* The SQL to be executed */
  90576. sqlite3_callback xCallback, /* Invoke this callback routine */
  90577. void *pArg, /* First argument to xCallback() */
  90578. char **pzErrMsg /* Write error messages here */
  90579. ){
  90580. int rc = SQLITE_OK; /* Return code */
  90581. const char *zLeftover; /* Tail of unprocessed SQL */
  90582. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  90583. char **azCols = 0; /* Names of result columns */
  90584. int callbackIsInit; /* True if callback data is initialized */
  90585. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  90586. if( zSql==0 ) zSql = "";
  90587. sqlite3_mutex_enter(db->mutex);
  90588. sqlite3Error(db, SQLITE_OK, 0);
  90589. while( rc==SQLITE_OK && zSql[0] ){
  90590. int nCol;
  90591. char **azVals = 0;
  90592. pStmt = 0;
  90593. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  90594. assert( rc==SQLITE_OK || pStmt==0 );
  90595. if( rc!=SQLITE_OK ){
  90596. continue;
  90597. }
  90598. if( !pStmt ){
  90599. /* this happens for a comment or white-space */
  90600. zSql = zLeftover;
  90601. continue;
  90602. }
  90603. callbackIsInit = 0;
  90604. nCol = sqlite3_column_count(pStmt);
  90605. while( 1 ){
  90606. int i;
  90607. rc = sqlite3_step(pStmt);
  90608. /* Invoke the callback function if required */
  90609. if( xCallback && (SQLITE_ROW==rc ||
  90610. (SQLITE_DONE==rc && !callbackIsInit
  90611. && db->flags&SQLITE_NullCallback)) ){
  90612. if( !callbackIsInit ){
  90613. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  90614. if( azCols==0 ){
  90615. goto exec_out;
  90616. }
  90617. for(i=0; i<nCol; i++){
  90618. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  90619. /* sqlite3VdbeSetColName() installs column names as UTF8
  90620. ** strings so there is no way for sqlite3_column_name() to fail. */
  90621. assert( azCols[i]!=0 );
  90622. }
  90623. callbackIsInit = 1;
  90624. }
  90625. if( rc==SQLITE_ROW ){
  90626. azVals = &azCols[nCol];
  90627. for(i=0; i<nCol; i++){
  90628. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  90629. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  90630. db->mallocFailed = 1;
  90631. goto exec_out;
  90632. }
  90633. }
  90634. }
  90635. if( xCallback(pArg, nCol, azVals, azCols) ){
  90636. rc = SQLITE_ABORT;
  90637. sqlite3VdbeFinalize((Vdbe *)pStmt);
  90638. pStmt = 0;
  90639. sqlite3Error(db, SQLITE_ABORT, 0);
  90640. goto exec_out;
  90641. }
  90642. }
  90643. if( rc!=SQLITE_ROW ){
  90644. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  90645. pStmt = 0;
  90646. zSql = zLeftover;
  90647. while( sqlite3Isspace(zSql[0]) ) zSql++;
  90648. break;
  90649. }
  90650. }
  90651. sqlite3DbFree(db, azCols);
  90652. azCols = 0;
  90653. }
  90654. exec_out:
  90655. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  90656. sqlite3DbFree(db, azCols);
  90657. rc = sqlite3ApiExit(db, rc);
  90658. if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
  90659. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  90660. *pzErrMsg = sqlite3Malloc(nErrMsg);
  90661. if( *pzErrMsg ){
  90662. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  90663. }else{
  90664. rc = SQLITE_NOMEM;
  90665. sqlite3Error(db, SQLITE_NOMEM, 0);
  90666. }
  90667. }else if( pzErrMsg ){
  90668. *pzErrMsg = 0;
  90669. }
  90670. assert( (rc&db->errMask)==rc );
  90671. sqlite3_mutex_leave(db->mutex);
  90672. return rc;
  90673. }
  90674. /************** End of legacy.c **********************************************/
  90675. /************** Begin file loadext.c *****************************************/
  90676. /*
  90677. ** 2006 June 7
  90678. **
  90679. ** The author disclaims copyright to this source code. In place of
  90680. ** a legal notice, here is a blessing:
  90681. **
  90682. ** May you do good and not evil.
  90683. ** May you find forgiveness for yourself and forgive others.
  90684. ** May you share freely, never taking more than you give.
  90685. **
  90686. *************************************************************************
  90687. ** This file contains code used to dynamically load extensions into
  90688. ** the SQLite library.
  90689. */
  90690. #ifndef SQLITE_CORE
  90691. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  90692. #endif
  90693. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  90694. /************** Begin file sqlite3ext.h **************************************/
  90695. /*
  90696. ** 2006 June 7
  90697. **
  90698. ** The author disclaims copyright to this source code. In place of
  90699. ** a legal notice, here is a blessing:
  90700. **
  90701. ** May you do good and not evil.
  90702. ** May you find forgiveness for yourself and forgive others.
  90703. ** May you share freely, never taking more than you give.
  90704. **
  90705. *************************************************************************
  90706. ** This header file defines the SQLite interface for use by
  90707. ** shared libraries that want to be imported as extensions into
  90708. ** an SQLite instance. Shared libraries that intend to be loaded
  90709. ** as extensions by SQLite should #include this file instead of
  90710. ** sqlite3.h.
  90711. */
  90712. #ifndef _SQLITE3EXT_H_
  90713. #define _SQLITE3EXT_H_
  90714. typedef struct sqlite3_api_routines sqlite3_api_routines;
  90715. /*
  90716. ** The following structure holds pointers to all of the SQLite API
  90717. ** routines.
  90718. **
  90719. ** WARNING: In order to maintain backwards compatibility, add new
  90720. ** interfaces to the end of this structure only. If you insert new
  90721. ** interfaces in the middle of this structure, then older different
  90722. ** versions of SQLite will not be able to load each others' shared
  90723. ** libraries!
  90724. */
  90725. struct sqlite3_api_routines {
  90726. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  90727. int (*aggregate_count)(sqlite3_context*);
  90728. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  90729. int (*bind_double)(sqlite3_stmt*,int,double);
  90730. int (*bind_int)(sqlite3_stmt*,int,int);
  90731. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  90732. int (*bind_null)(sqlite3_stmt*,int);
  90733. int (*bind_parameter_count)(sqlite3_stmt*);
  90734. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  90735. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  90736. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  90737. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  90738. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  90739. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  90740. int (*busy_timeout)(sqlite3*,int ms);
  90741. int (*changes)(sqlite3*);
  90742. int (*close)(sqlite3*);
  90743. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  90744. int eTextRep,const char*));
  90745. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  90746. int eTextRep,const void*));
  90747. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  90748. int (*column_bytes)(sqlite3_stmt*,int iCol);
  90749. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  90750. int (*column_count)(sqlite3_stmt*pStmt);
  90751. const char * (*column_database_name)(sqlite3_stmt*,int);
  90752. const void * (*column_database_name16)(sqlite3_stmt*,int);
  90753. const char * (*column_decltype)(sqlite3_stmt*,int i);
  90754. const void * (*column_decltype16)(sqlite3_stmt*,int);
  90755. double (*column_double)(sqlite3_stmt*,int iCol);
  90756. int (*column_int)(sqlite3_stmt*,int iCol);
  90757. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  90758. const char * (*column_name)(sqlite3_stmt*,int);
  90759. const void * (*column_name16)(sqlite3_stmt*,int);
  90760. const char * (*column_origin_name)(sqlite3_stmt*,int);
  90761. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  90762. const char * (*column_table_name)(sqlite3_stmt*,int);
  90763. const void * (*column_table_name16)(sqlite3_stmt*,int);
  90764. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  90765. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  90766. int (*column_type)(sqlite3_stmt*,int iCol);
  90767. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  90768. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  90769. int (*complete)(const char*sql);
  90770. int (*complete16)(const void*sql);
  90771. int (*create_collation)(sqlite3*,const char*,int,void*,
  90772. int(*)(void*,int,const void*,int,const void*));
  90773. int (*create_collation16)(sqlite3*,const void*,int,void*,
  90774. int(*)(void*,int,const void*,int,const void*));
  90775. int (*create_function)(sqlite3*,const char*,int,int,void*,
  90776. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90777. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90778. void (*xFinal)(sqlite3_context*));
  90779. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  90780. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90781. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90782. void (*xFinal)(sqlite3_context*));
  90783. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  90784. int (*data_count)(sqlite3_stmt*pStmt);
  90785. sqlite3 * (*db_handle)(sqlite3_stmt*);
  90786. int (*declare_vtab)(sqlite3*,const char*);
  90787. int (*enable_shared_cache)(int);
  90788. int (*errcode)(sqlite3*db);
  90789. const char * (*errmsg)(sqlite3*);
  90790. const void * (*errmsg16)(sqlite3*);
  90791. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  90792. int (*expired)(sqlite3_stmt*);
  90793. int (*finalize)(sqlite3_stmt*pStmt);
  90794. void (*free)(void*);
  90795. void (*free_table)(char**result);
  90796. int (*get_autocommit)(sqlite3*);
  90797. void * (*get_auxdata)(sqlite3_context*,int);
  90798. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  90799. int (*global_recover)(void);
  90800. void (*interruptx)(sqlite3*);
  90801. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  90802. const char * (*libversion)(void);
  90803. int (*libversion_number)(void);
  90804. void *(*malloc)(int);
  90805. char * (*mprintf)(const char*,...);
  90806. int (*open)(const char*,sqlite3**);
  90807. int (*open16)(const void*,sqlite3**);
  90808. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  90809. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  90810. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  90811. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  90812. void *(*realloc)(void*,int);
  90813. int (*reset)(sqlite3_stmt*pStmt);
  90814. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  90815. void (*result_double)(sqlite3_context*,double);
  90816. void (*result_error)(sqlite3_context*,const char*,int);
  90817. void (*result_error16)(sqlite3_context*,const void*,int);
  90818. void (*result_int)(sqlite3_context*,int);
  90819. void (*result_int64)(sqlite3_context*,sqlite_int64);
  90820. void (*result_null)(sqlite3_context*);
  90821. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  90822. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  90823. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  90824. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  90825. void (*result_value)(sqlite3_context*,sqlite3_value*);
  90826. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  90827. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  90828. const char*,const char*),void*);
  90829. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  90830. char * (*snprintf)(int,char*,const char*,...);
  90831. int (*step)(sqlite3_stmt*);
  90832. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  90833. char const**,char const**,int*,int*,int*);
  90834. void (*thread_cleanup)(void);
  90835. int (*total_changes)(sqlite3*);
  90836. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  90837. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  90838. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  90839. sqlite_int64),void*);
  90840. void * (*user_data)(sqlite3_context*);
  90841. const void * (*value_blob)(sqlite3_value*);
  90842. int (*value_bytes)(sqlite3_value*);
  90843. int (*value_bytes16)(sqlite3_value*);
  90844. double (*value_double)(sqlite3_value*);
  90845. int (*value_int)(sqlite3_value*);
  90846. sqlite_int64 (*value_int64)(sqlite3_value*);
  90847. int (*value_numeric_type)(sqlite3_value*);
  90848. const unsigned char * (*value_text)(sqlite3_value*);
  90849. const void * (*value_text16)(sqlite3_value*);
  90850. const void * (*value_text16be)(sqlite3_value*);
  90851. const void * (*value_text16le)(sqlite3_value*);
  90852. int (*value_type)(sqlite3_value*);
  90853. char *(*vmprintf)(const char*,va_list);
  90854. /* Added ??? */
  90855. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  90856. /* Added by 3.3.13 */
  90857. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  90858. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  90859. int (*clear_bindings)(sqlite3_stmt*);
  90860. /* Added by 3.4.1 */
  90861. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  90862. void (*xDestroy)(void *));
  90863. /* Added by 3.5.0 */
  90864. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  90865. int (*blob_bytes)(sqlite3_blob*);
  90866. int (*blob_close)(sqlite3_blob*);
  90867. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  90868. int,sqlite3_blob**);
  90869. int (*blob_read)(sqlite3_blob*,void*,int,int);
  90870. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  90871. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  90872. int(*)(void*,int,const void*,int,const void*),
  90873. void(*)(void*));
  90874. int (*file_control)(sqlite3*,const char*,int,void*);
  90875. sqlite3_int64 (*memory_highwater)(int);
  90876. sqlite3_int64 (*memory_used)(void);
  90877. sqlite3_mutex *(*mutex_alloc)(int);
  90878. void (*mutex_enter)(sqlite3_mutex*);
  90879. void (*mutex_free)(sqlite3_mutex*);
  90880. void (*mutex_leave)(sqlite3_mutex*);
  90881. int (*mutex_try)(sqlite3_mutex*);
  90882. int (*open_v2)(const char*,sqlite3**,int,const char*);
  90883. int (*release_memory)(int);
  90884. void (*result_error_nomem)(sqlite3_context*);
  90885. void (*result_error_toobig)(sqlite3_context*);
  90886. int (*sleep)(int);
  90887. void (*soft_heap_limit)(int);
  90888. sqlite3_vfs *(*vfs_find)(const char*);
  90889. int (*vfs_register)(sqlite3_vfs*,int);
  90890. int (*vfs_unregister)(sqlite3_vfs*);
  90891. int (*xthreadsafe)(void);
  90892. void (*result_zeroblob)(sqlite3_context*,int);
  90893. void (*result_error_code)(sqlite3_context*,int);
  90894. int (*test_control)(int, ...);
  90895. void (*randomness)(int,void*);
  90896. sqlite3 *(*context_db_handle)(sqlite3_context*);
  90897. int (*extended_result_codes)(sqlite3*,int);
  90898. int (*limit)(sqlite3*,int,int);
  90899. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  90900. const char *(*sql)(sqlite3_stmt*);
  90901. int (*status)(int,int*,int*,int);
  90902. int (*backup_finish)(sqlite3_backup*);
  90903. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  90904. int (*backup_pagecount)(sqlite3_backup*);
  90905. int (*backup_remaining)(sqlite3_backup*);
  90906. int (*backup_step)(sqlite3_backup*,int);
  90907. const char *(*compileoption_get)(int);
  90908. int (*compileoption_used)(const char*);
  90909. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  90910. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  90911. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  90912. void (*xFinal)(sqlite3_context*),
  90913. void(*xDestroy)(void*));
  90914. int (*db_config)(sqlite3*,int,...);
  90915. sqlite3_mutex *(*db_mutex)(sqlite3*);
  90916. int (*db_status)(sqlite3*,int,int*,int*,int);
  90917. int (*extended_errcode)(sqlite3*);
  90918. void (*log)(int,const char*,...);
  90919. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  90920. const char *(*sourceid)(void);
  90921. int (*stmt_status)(sqlite3_stmt*,int,int);
  90922. int (*strnicmp)(const char*,const char*,int);
  90923. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  90924. int (*wal_autocheckpoint)(sqlite3*,int);
  90925. int (*wal_checkpoint)(sqlite3*,const char*);
  90926. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  90927. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  90928. int (*vtab_config)(sqlite3*,int op,...);
  90929. int (*vtab_on_conflict)(sqlite3*);
  90930. /* Version 3.7.16 and later */
  90931. int (*close_v2)(sqlite3*);
  90932. const char *(*db_filename)(sqlite3*,const char*);
  90933. int (*db_readonly)(sqlite3*,const char*);
  90934. int (*db_release_memory)(sqlite3*);
  90935. const char *(*errstr)(int);
  90936. int (*stmt_busy)(sqlite3_stmt*);
  90937. int (*stmt_readonly)(sqlite3_stmt*);
  90938. int (*stricmp)(const char*,const char*);
  90939. int (*uri_boolean)(const char*,const char*,int);
  90940. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  90941. const char *(*uri_parameter)(const char*,const char*);
  90942. char *(*vsnprintf)(int,char*,const char*,va_list);
  90943. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  90944. };
  90945. /*
  90946. ** The following macros redefine the API routines so that they are
  90947. ** redirected throught the global sqlite3_api structure.
  90948. **
  90949. ** This header file is also used by the loadext.c source file
  90950. ** (part of the main SQLite library - not an extension) so that
  90951. ** it can get access to the sqlite3_api_routines structure
  90952. ** definition. But the main library does not want to redefine
  90953. ** the API. So the redefinition macros are only valid if the
  90954. ** SQLITE_CORE macros is undefined.
  90955. */
  90956. #ifndef SQLITE_CORE
  90957. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  90958. #ifndef SQLITE_OMIT_DEPRECATED
  90959. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  90960. #endif
  90961. #define sqlite3_bind_blob sqlite3_api->bind_blob
  90962. #define sqlite3_bind_double sqlite3_api->bind_double
  90963. #define sqlite3_bind_int sqlite3_api->bind_int
  90964. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  90965. #define sqlite3_bind_null sqlite3_api->bind_null
  90966. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  90967. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  90968. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  90969. #define sqlite3_bind_text sqlite3_api->bind_text
  90970. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  90971. #define sqlite3_bind_value sqlite3_api->bind_value
  90972. #define sqlite3_busy_handler sqlite3_api->busy_handler
  90973. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  90974. #define sqlite3_changes sqlite3_api->changes
  90975. #define sqlite3_close sqlite3_api->close
  90976. #define sqlite3_collation_needed sqlite3_api->collation_needed
  90977. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  90978. #define sqlite3_column_blob sqlite3_api->column_blob
  90979. #define sqlite3_column_bytes sqlite3_api->column_bytes
  90980. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  90981. #define sqlite3_column_count sqlite3_api->column_count
  90982. #define sqlite3_column_database_name sqlite3_api->column_database_name
  90983. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  90984. #define sqlite3_column_decltype sqlite3_api->column_decltype
  90985. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  90986. #define sqlite3_column_double sqlite3_api->column_double
  90987. #define sqlite3_column_int sqlite3_api->column_int
  90988. #define sqlite3_column_int64 sqlite3_api->column_int64
  90989. #define sqlite3_column_name sqlite3_api->column_name
  90990. #define sqlite3_column_name16 sqlite3_api->column_name16
  90991. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  90992. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  90993. #define sqlite3_column_table_name sqlite3_api->column_table_name
  90994. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  90995. #define sqlite3_column_text sqlite3_api->column_text
  90996. #define sqlite3_column_text16 sqlite3_api->column_text16
  90997. #define sqlite3_column_type sqlite3_api->column_type
  90998. #define sqlite3_column_value sqlite3_api->column_value
  90999. #define sqlite3_commit_hook sqlite3_api->commit_hook
  91000. #define sqlite3_complete sqlite3_api->complete
  91001. #define sqlite3_complete16 sqlite3_api->complete16
  91002. #define sqlite3_create_collation sqlite3_api->create_collation
  91003. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  91004. #define sqlite3_create_function sqlite3_api->create_function
  91005. #define sqlite3_create_function16 sqlite3_api->create_function16
  91006. #define sqlite3_create_module sqlite3_api->create_module
  91007. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  91008. #define sqlite3_data_count sqlite3_api->data_count
  91009. #define sqlite3_db_handle sqlite3_api->db_handle
  91010. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  91011. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  91012. #define sqlite3_errcode sqlite3_api->errcode
  91013. #define sqlite3_errmsg sqlite3_api->errmsg
  91014. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  91015. #define sqlite3_exec sqlite3_api->exec
  91016. #ifndef SQLITE_OMIT_DEPRECATED
  91017. #define sqlite3_expired sqlite3_api->expired
  91018. #endif
  91019. #define sqlite3_finalize sqlite3_api->finalize
  91020. #define sqlite3_free sqlite3_api->free
  91021. #define sqlite3_free_table sqlite3_api->free_table
  91022. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  91023. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  91024. #define sqlite3_get_table sqlite3_api->get_table
  91025. #ifndef SQLITE_OMIT_DEPRECATED
  91026. #define sqlite3_global_recover sqlite3_api->global_recover
  91027. #endif
  91028. #define sqlite3_interrupt sqlite3_api->interruptx
  91029. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  91030. #define sqlite3_libversion sqlite3_api->libversion
  91031. #define sqlite3_libversion_number sqlite3_api->libversion_number
  91032. #define sqlite3_malloc sqlite3_api->malloc
  91033. #define sqlite3_mprintf sqlite3_api->mprintf
  91034. #define sqlite3_open sqlite3_api->open
  91035. #define sqlite3_open16 sqlite3_api->open16
  91036. #define sqlite3_prepare sqlite3_api->prepare
  91037. #define sqlite3_prepare16 sqlite3_api->prepare16
  91038. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  91039. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  91040. #define sqlite3_profile sqlite3_api->profile
  91041. #define sqlite3_progress_handler sqlite3_api->progress_handler
  91042. #define sqlite3_realloc sqlite3_api->realloc
  91043. #define sqlite3_reset sqlite3_api->reset
  91044. #define sqlite3_result_blob sqlite3_api->result_blob
  91045. #define sqlite3_result_double sqlite3_api->result_double
  91046. #define sqlite3_result_error sqlite3_api->result_error
  91047. #define sqlite3_result_error16 sqlite3_api->result_error16
  91048. #define sqlite3_result_int sqlite3_api->result_int
  91049. #define sqlite3_result_int64 sqlite3_api->result_int64
  91050. #define sqlite3_result_null sqlite3_api->result_null
  91051. #define sqlite3_result_text sqlite3_api->result_text
  91052. #define sqlite3_result_text16 sqlite3_api->result_text16
  91053. #define sqlite3_result_text16be sqlite3_api->result_text16be
  91054. #define sqlite3_result_text16le sqlite3_api->result_text16le
  91055. #define sqlite3_result_value sqlite3_api->result_value
  91056. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  91057. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  91058. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  91059. #define sqlite3_snprintf sqlite3_api->snprintf
  91060. #define sqlite3_step sqlite3_api->step
  91061. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  91062. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  91063. #define sqlite3_total_changes sqlite3_api->total_changes
  91064. #define sqlite3_trace sqlite3_api->trace
  91065. #ifndef SQLITE_OMIT_DEPRECATED
  91066. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  91067. #endif
  91068. #define sqlite3_update_hook sqlite3_api->update_hook
  91069. #define sqlite3_user_data sqlite3_api->user_data
  91070. #define sqlite3_value_blob sqlite3_api->value_blob
  91071. #define sqlite3_value_bytes sqlite3_api->value_bytes
  91072. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  91073. #define sqlite3_value_double sqlite3_api->value_double
  91074. #define sqlite3_value_int sqlite3_api->value_int
  91075. #define sqlite3_value_int64 sqlite3_api->value_int64
  91076. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  91077. #define sqlite3_value_text sqlite3_api->value_text
  91078. #define sqlite3_value_text16 sqlite3_api->value_text16
  91079. #define sqlite3_value_text16be sqlite3_api->value_text16be
  91080. #define sqlite3_value_text16le sqlite3_api->value_text16le
  91081. #define sqlite3_value_type sqlite3_api->value_type
  91082. #define sqlite3_vmprintf sqlite3_api->vmprintf
  91083. #define sqlite3_overload_function sqlite3_api->overload_function
  91084. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  91085. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  91086. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  91087. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  91088. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  91089. #define sqlite3_blob_close sqlite3_api->blob_close
  91090. #define sqlite3_blob_open sqlite3_api->blob_open
  91091. #define sqlite3_blob_read sqlite3_api->blob_read
  91092. #define sqlite3_blob_write sqlite3_api->blob_write
  91093. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  91094. #define sqlite3_file_control sqlite3_api->file_control
  91095. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  91096. #define sqlite3_memory_used sqlite3_api->memory_used
  91097. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  91098. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  91099. #define sqlite3_mutex_free sqlite3_api->mutex_free
  91100. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  91101. #define sqlite3_mutex_try sqlite3_api->mutex_try
  91102. #define sqlite3_open_v2 sqlite3_api->open_v2
  91103. #define sqlite3_release_memory sqlite3_api->release_memory
  91104. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  91105. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  91106. #define sqlite3_sleep sqlite3_api->sleep
  91107. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  91108. #define sqlite3_vfs_find sqlite3_api->vfs_find
  91109. #define sqlite3_vfs_register sqlite3_api->vfs_register
  91110. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  91111. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  91112. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  91113. #define sqlite3_result_error_code sqlite3_api->result_error_code
  91114. #define sqlite3_test_control sqlite3_api->test_control
  91115. #define sqlite3_randomness sqlite3_api->randomness
  91116. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  91117. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  91118. #define sqlite3_limit sqlite3_api->limit
  91119. #define sqlite3_next_stmt sqlite3_api->next_stmt
  91120. #define sqlite3_sql sqlite3_api->sql
  91121. #define sqlite3_status sqlite3_api->status
  91122. #define sqlite3_backup_finish sqlite3_api->backup_finish
  91123. #define sqlite3_backup_init sqlite3_api->backup_init
  91124. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  91125. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  91126. #define sqlite3_backup_step sqlite3_api->backup_step
  91127. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  91128. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  91129. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  91130. #define sqlite3_db_config sqlite3_api->db_config
  91131. #define sqlite3_db_mutex sqlite3_api->db_mutex
  91132. #define sqlite3_db_status sqlite3_api->db_status
  91133. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  91134. #define sqlite3_log sqlite3_api->log
  91135. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  91136. #define sqlite3_sourceid sqlite3_api->sourceid
  91137. #define sqlite3_stmt_status sqlite3_api->stmt_status
  91138. #define sqlite3_strnicmp sqlite3_api->strnicmp
  91139. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  91140. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  91141. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  91142. #define sqlite3_wal_hook sqlite3_api->wal_hook
  91143. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  91144. #define sqlite3_vtab_config sqlite3_api->vtab_config
  91145. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  91146. /* Version 3.7.16 and later */
  91147. #define sqlite3_close_v2 sqlite3_api->close_v2
  91148. #define sqlite3_db_filename sqlite3_api->db_filename
  91149. #define sqlite3_db_readonly sqlite3_api->db_readonly
  91150. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  91151. #define sqlite3_errstr sqlite3_api->errstr
  91152. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  91153. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  91154. #define sqlite3_stricmp sqlite3_api->stricmp
  91155. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  91156. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  91157. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  91158. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  91159. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  91160. #endif /* SQLITE_CORE */
  91161. #ifndef SQLITE_CORE
  91162. /* This case when the file really is being compiled as a loadable
  91163. ** extension */
  91164. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  91165. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  91166. # define SQLITE_EXTENSION_INIT3 \
  91167. extern const sqlite3_api_routines *sqlite3_api;
  91168. #else
  91169. /* This case when the file is being statically linked into the
  91170. ** application */
  91171. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  91172. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  91173. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  91174. #endif
  91175. #endif /* _SQLITE3EXT_H_ */
  91176. /************** End of sqlite3ext.h ******************************************/
  91177. /************** Continuing where we left off in loadext.c ********************/
  91178. /* #include <string.h> */
  91179. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  91180. /*
  91181. ** Some API routines are omitted when various features are
  91182. ** excluded from a build of SQLite. Substitute a NULL pointer
  91183. ** for any missing APIs.
  91184. */
  91185. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  91186. # define sqlite3_column_database_name 0
  91187. # define sqlite3_column_database_name16 0
  91188. # define sqlite3_column_table_name 0
  91189. # define sqlite3_column_table_name16 0
  91190. # define sqlite3_column_origin_name 0
  91191. # define sqlite3_column_origin_name16 0
  91192. # define sqlite3_table_column_metadata 0
  91193. #endif
  91194. #ifdef SQLITE_OMIT_AUTHORIZATION
  91195. # define sqlite3_set_authorizer 0
  91196. #endif
  91197. #ifdef SQLITE_OMIT_UTF16
  91198. # define sqlite3_bind_text16 0
  91199. # define sqlite3_collation_needed16 0
  91200. # define sqlite3_column_decltype16 0
  91201. # define sqlite3_column_name16 0
  91202. # define sqlite3_column_text16 0
  91203. # define sqlite3_complete16 0
  91204. # define sqlite3_create_collation16 0
  91205. # define sqlite3_create_function16 0
  91206. # define sqlite3_errmsg16 0
  91207. # define sqlite3_open16 0
  91208. # define sqlite3_prepare16 0
  91209. # define sqlite3_prepare16_v2 0
  91210. # define sqlite3_result_error16 0
  91211. # define sqlite3_result_text16 0
  91212. # define sqlite3_result_text16be 0
  91213. # define sqlite3_result_text16le 0
  91214. # define sqlite3_value_text16 0
  91215. # define sqlite3_value_text16be 0
  91216. # define sqlite3_value_text16le 0
  91217. # define sqlite3_column_database_name16 0
  91218. # define sqlite3_column_table_name16 0
  91219. # define sqlite3_column_origin_name16 0
  91220. #endif
  91221. #ifdef SQLITE_OMIT_COMPLETE
  91222. # define sqlite3_complete 0
  91223. # define sqlite3_complete16 0
  91224. #endif
  91225. #ifdef SQLITE_OMIT_DECLTYPE
  91226. # define sqlite3_column_decltype16 0
  91227. # define sqlite3_column_decltype 0
  91228. #endif
  91229. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  91230. # define sqlite3_progress_handler 0
  91231. #endif
  91232. #ifdef SQLITE_OMIT_VIRTUALTABLE
  91233. # define sqlite3_create_module 0
  91234. # define sqlite3_create_module_v2 0
  91235. # define sqlite3_declare_vtab 0
  91236. # define sqlite3_vtab_config 0
  91237. # define sqlite3_vtab_on_conflict 0
  91238. #endif
  91239. #ifdef SQLITE_OMIT_SHARED_CACHE
  91240. # define sqlite3_enable_shared_cache 0
  91241. #endif
  91242. #ifdef SQLITE_OMIT_TRACE
  91243. # define sqlite3_profile 0
  91244. # define sqlite3_trace 0
  91245. #endif
  91246. #ifdef SQLITE_OMIT_GET_TABLE
  91247. # define sqlite3_free_table 0
  91248. # define sqlite3_get_table 0
  91249. #endif
  91250. #ifdef SQLITE_OMIT_INCRBLOB
  91251. #define sqlite3_bind_zeroblob 0
  91252. #define sqlite3_blob_bytes 0
  91253. #define sqlite3_blob_close 0
  91254. #define sqlite3_blob_open 0
  91255. #define sqlite3_blob_read 0
  91256. #define sqlite3_blob_write 0
  91257. #define sqlite3_blob_reopen 0
  91258. #endif
  91259. /*
  91260. ** The following structure contains pointers to all SQLite API routines.
  91261. ** A pointer to this structure is passed into extensions when they are
  91262. ** loaded so that the extension can make calls back into the SQLite
  91263. ** library.
  91264. **
  91265. ** When adding new APIs, add them to the bottom of this structure
  91266. ** in order to preserve backwards compatibility.
  91267. **
  91268. ** Extensions that use newer APIs should first call the
  91269. ** sqlite3_libversion_number() to make sure that the API they
  91270. ** intend to use is supported by the library. Extensions should
  91271. ** also check to make sure that the pointer to the function is
  91272. ** not NULL before calling it.
  91273. */
  91274. static const sqlite3_api_routines sqlite3Apis = {
  91275. sqlite3_aggregate_context,
  91276. #ifndef SQLITE_OMIT_DEPRECATED
  91277. sqlite3_aggregate_count,
  91278. #else
  91279. 0,
  91280. #endif
  91281. sqlite3_bind_blob,
  91282. sqlite3_bind_double,
  91283. sqlite3_bind_int,
  91284. sqlite3_bind_int64,
  91285. sqlite3_bind_null,
  91286. sqlite3_bind_parameter_count,
  91287. sqlite3_bind_parameter_index,
  91288. sqlite3_bind_parameter_name,
  91289. sqlite3_bind_text,
  91290. sqlite3_bind_text16,
  91291. sqlite3_bind_value,
  91292. sqlite3_busy_handler,
  91293. sqlite3_busy_timeout,
  91294. sqlite3_changes,
  91295. sqlite3_close,
  91296. sqlite3_collation_needed,
  91297. sqlite3_collation_needed16,
  91298. sqlite3_column_blob,
  91299. sqlite3_column_bytes,
  91300. sqlite3_column_bytes16,
  91301. sqlite3_column_count,
  91302. sqlite3_column_database_name,
  91303. sqlite3_column_database_name16,
  91304. sqlite3_column_decltype,
  91305. sqlite3_column_decltype16,
  91306. sqlite3_column_double,
  91307. sqlite3_column_int,
  91308. sqlite3_column_int64,
  91309. sqlite3_column_name,
  91310. sqlite3_column_name16,
  91311. sqlite3_column_origin_name,
  91312. sqlite3_column_origin_name16,
  91313. sqlite3_column_table_name,
  91314. sqlite3_column_table_name16,
  91315. sqlite3_column_text,
  91316. sqlite3_column_text16,
  91317. sqlite3_column_type,
  91318. sqlite3_column_value,
  91319. sqlite3_commit_hook,
  91320. sqlite3_complete,
  91321. sqlite3_complete16,
  91322. sqlite3_create_collation,
  91323. sqlite3_create_collation16,
  91324. sqlite3_create_function,
  91325. sqlite3_create_function16,
  91326. sqlite3_create_module,
  91327. sqlite3_data_count,
  91328. sqlite3_db_handle,
  91329. sqlite3_declare_vtab,
  91330. sqlite3_enable_shared_cache,
  91331. sqlite3_errcode,
  91332. sqlite3_errmsg,
  91333. sqlite3_errmsg16,
  91334. sqlite3_exec,
  91335. #ifndef SQLITE_OMIT_DEPRECATED
  91336. sqlite3_expired,
  91337. #else
  91338. 0,
  91339. #endif
  91340. sqlite3_finalize,
  91341. sqlite3_free,
  91342. sqlite3_free_table,
  91343. sqlite3_get_autocommit,
  91344. sqlite3_get_auxdata,
  91345. sqlite3_get_table,
  91346. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  91347. sqlite3_interrupt,
  91348. sqlite3_last_insert_rowid,
  91349. sqlite3_libversion,
  91350. sqlite3_libversion_number,
  91351. sqlite3_malloc,
  91352. sqlite3_mprintf,
  91353. sqlite3_open,
  91354. sqlite3_open16,
  91355. sqlite3_prepare,
  91356. sqlite3_prepare16,
  91357. sqlite3_profile,
  91358. sqlite3_progress_handler,
  91359. sqlite3_realloc,
  91360. sqlite3_reset,
  91361. sqlite3_result_blob,
  91362. sqlite3_result_double,
  91363. sqlite3_result_error,
  91364. sqlite3_result_error16,
  91365. sqlite3_result_int,
  91366. sqlite3_result_int64,
  91367. sqlite3_result_null,
  91368. sqlite3_result_text,
  91369. sqlite3_result_text16,
  91370. sqlite3_result_text16be,
  91371. sqlite3_result_text16le,
  91372. sqlite3_result_value,
  91373. sqlite3_rollback_hook,
  91374. sqlite3_set_authorizer,
  91375. sqlite3_set_auxdata,
  91376. sqlite3_snprintf,
  91377. sqlite3_step,
  91378. sqlite3_table_column_metadata,
  91379. #ifndef SQLITE_OMIT_DEPRECATED
  91380. sqlite3_thread_cleanup,
  91381. #else
  91382. 0,
  91383. #endif
  91384. sqlite3_total_changes,
  91385. sqlite3_trace,
  91386. #ifndef SQLITE_OMIT_DEPRECATED
  91387. sqlite3_transfer_bindings,
  91388. #else
  91389. 0,
  91390. #endif
  91391. sqlite3_update_hook,
  91392. sqlite3_user_data,
  91393. sqlite3_value_blob,
  91394. sqlite3_value_bytes,
  91395. sqlite3_value_bytes16,
  91396. sqlite3_value_double,
  91397. sqlite3_value_int,
  91398. sqlite3_value_int64,
  91399. sqlite3_value_numeric_type,
  91400. sqlite3_value_text,
  91401. sqlite3_value_text16,
  91402. sqlite3_value_text16be,
  91403. sqlite3_value_text16le,
  91404. sqlite3_value_type,
  91405. sqlite3_vmprintf,
  91406. /*
  91407. ** The original API set ends here. All extensions can call any
  91408. ** of the APIs above provided that the pointer is not NULL. But
  91409. ** before calling APIs that follow, extension should check the
  91410. ** sqlite3_libversion_number() to make sure they are dealing with
  91411. ** a library that is new enough to support that API.
  91412. *************************************************************************
  91413. */
  91414. sqlite3_overload_function,
  91415. /*
  91416. ** Added after 3.3.13
  91417. */
  91418. sqlite3_prepare_v2,
  91419. sqlite3_prepare16_v2,
  91420. sqlite3_clear_bindings,
  91421. /*
  91422. ** Added for 3.4.1
  91423. */
  91424. sqlite3_create_module_v2,
  91425. /*
  91426. ** Added for 3.5.0
  91427. */
  91428. sqlite3_bind_zeroblob,
  91429. sqlite3_blob_bytes,
  91430. sqlite3_blob_close,
  91431. sqlite3_blob_open,
  91432. sqlite3_blob_read,
  91433. sqlite3_blob_write,
  91434. sqlite3_create_collation_v2,
  91435. sqlite3_file_control,
  91436. sqlite3_memory_highwater,
  91437. sqlite3_memory_used,
  91438. #ifdef SQLITE_MUTEX_OMIT
  91439. 0,
  91440. 0,
  91441. 0,
  91442. 0,
  91443. 0,
  91444. #else
  91445. sqlite3_mutex_alloc,
  91446. sqlite3_mutex_enter,
  91447. sqlite3_mutex_free,
  91448. sqlite3_mutex_leave,
  91449. sqlite3_mutex_try,
  91450. #endif
  91451. sqlite3_open_v2,
  91452. sqlite3_release_memory,
  91453. sqlite3_result_error_nomem,
  91454. sqlite3_result_error_toobig,
  91455. sqlite3_sleep,
  91456. sqlite3_soft_heap_limit,
  91457. sqlite3_vfs_find,
  91458. sqlite3_vfs_register,
  91459. sqlite3_vfs_unregister,
  91460. /*
  91461. ** Added for 3.5.8
  91462. */
  91463. sqlite3_threadsafe,
  91464. sqlite3_result_zeroblob,
  91465. sqlite3_result_error_code,
  91466. sqlite3_test_control,
  91467. sqlite3_randomness,
  91468. sqlite3_context_db_handle,
  91469. /*
  91470. ** Added for 3.6.0
  91471. */
  91472. sqlite3_extended_result_codes,
  91473. sqlite3_limit,
  91474. sqlite3_next_stmt,
  91475. sqlite3_sql,
  91476. sqlite3_status,
  91477. /*
  91478. ** Added for 3.7.4
  91479. */
  91480. sqlite3_backup_finish,
  91481. sqlite3_backup_init,
  91482. sqlite3_backup_pagecount,
  91483. sqlite3_backup_remaining,
  91484. sqlite3_backup_step,
  91485. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  91486. sqlite3_compileoption_get,
  91487. sqlite3_compileoption_used,
  91488. #else
  91489. 0,
  91490. 0,
  91491. #endif
  91492. sqlite3_create_function_v2,
  91493. sqlite3_db_config,
  91494. sqlite3_db_mutex,
  91495. sqlite3_db_status,
  91496. sqlite3_extended_errcode,
  91497. sqlite3_log,
  91498. sqlite3_soft_heap_limit64,
  91499. sqlite3_sourceid,
  91500. sqlite3_stmt_status,
  91501. sqlite3_strnicmp,
  91502. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  91503. sqlite3_unlock_notify,
  91504. #else
  91505. 0,
  91506. #endif
  91507. #ifndef SQLITE_OMIT_WAL
  91508. sqlite3_wal_autocheckpoint,
  91509. sqlite3_wal_checkpoint,
  91510. sqlite3_wal_hook,
  91511. #else
  91512. 0,
  91513. 0,
  91514. 0,
  91515. #endif
  91516. sqlite3_blob_reopen,
  91517. sqlite3_vtab_config,
  91518. sqlite3_vtab_on_conflict,
  91519. sqlite3_close_v2,
  91520. sqlite3_db_filename,
  91521. sqlite3_db_readonly,
  91522. sqlite3_db_release_memory,
  91523. sqlite3_errstr,
  91524. sqlite3_stmt_busy,
  91525. sqlite3_stmt_readonly,
  91526. sqlite3_stricmp,
  91527. sqlite3_uri_boolean,
  91528. sqlite3_uri_int64,
  91529. sqlite3_uri_parameter,
  91530. sqlite3_vsnprintf,
  91531. sqlite3_wal_checkpoint_v2
  91532. };
  91533. /*
  91534. ** Attempt to load an SQLite extension library contained in the file
  91535. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  91536. ** default entry point name (sqlite3_extension_init) is used. Use
  91537. ** of the default name is recommended.
  91538. **
  91539. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  91540. **
  91541. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  91542. ** error message text. The calling function should free this memory
  91543. ** by calling sqlite3DbFree(db, ).
  91544. */
  91545. static int sqlite3LoadExtension(
  91546. sqlite3 *db, /* Load the extension into this database connection */
  91547. const char *zFile, /* Name of the shared library containing extension */
  91548. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  91549. char **pzErrMsg /* Put error message here if not 0 */
  91550. ){
  91551. sqlite3_vfs *pVfs = db->pVfs;
  91552. void *handle;
  91553. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  91554. char *zErrmsg = 0;
  91555. const char *zEntry;
  91556. char *zAltEntry = 0;
  91557. void **aHandle;
  91558. int nMsg = 300 + sqlite3Strlen30(zFile);
  91559. int ii;
  91560. /* Shared library endings to try if zFile cannot be loaded as written */
  91561. static const char *azEndings[] = {
  91562. #if SQLITE_OS_WIN
  91563. "dll"
  91564. #elif defined(__APPLE__)
  91565. "dylib"
  91566. #else
  91567. "so"
  91568. #endif
  91569. };
  91570. if( pzErrMsg ) *pzErrMsg = 0;
  91571. /* Ticket #1863. To avoid a creating security problems for older
  91572. ** applications that relink against newer versions of SQLite, the
  91573. ** ability to run load_extension is turned off by default. One
  91574. ** must call sqlite3_enable_load_extension() to turn on extension
  91575. ** loading. Otherwise you get the following error.
  91576. */
  91577. if( (db->flags & SQLITE_LoadExtension)==0 ){
  91578. if( pzErrMsg ){
  91579. *pzErrMsg = sqlite3_mprintf("not authorized");
  91580. }
  91581. return SQLITE_ERROR;
  91582. }
  91583. zEntry = zProc ? zProc : "sqlite3_extension_init";
  91584. handle = sqlite3OsDlOpen(pVfs, zFile);
  91585. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  91586. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  91587. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  91588. if( zAltFile==0 ) return SQLITE_NOMEM;
  91589. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  91590. sqlite3_free(zAltFile);
  91591. }
  91592. #endif
  91593. if( handle==0 ){
  91594. if( pzErrMsg ){
  91595. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  91596. if( zErrmsg ){
  91597. sqlite3_snprintf(nMsg, zErrmsg,
  91598. "unable to open shared library [%s]", zFile);
  91599. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  91600. }
  91601. }
  91602. return SQLITE_ERROR;
  91603. }
  91604. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91605. sqlite3OsDlSym(pVfs, handle, zEntry);
  91606. /* If no entry point was specified and the default legacy
  91607. ** entry point name "sqlite3_extension_init" was not found, then
  91608. ** construct an entry point name "sqlite3_X_init" where the X is
  91609. ** replaced by the lowercase value of every ASCII alphabetic
  91610. ** character in the filename after the last "/" upto the first ".",
  91611. ** and eliding the first three characters if they are "lib".
  91612. ** Examples:
  91613. **
  91614. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  91615. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  91616. */
  91617. if( xInit==0 && zProc==0 ){
  91618. int iFile, iEntry, c;
  91619. int ncFile = sqlite3Strlen30(zFile);
  91620. zAltEntry = sqlite3_malloc(ncFile+30);
  91621. if( zAltEntry==0 ){
  91622. sqlite3OsDlClose(pVfs, handle);
  91623. return SQLITE_NOMEM;
  91624. }
  91625. memcpy(zAltEntry, "sqlite3_", 8);
  91626. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  91627. iFile++;
  91628. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  91629. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  91630. if( sqlite3Isalpha(c) ){
  91631. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  91632. }
  91633. }
  91634. memcpy(zAltEntry+iEntry, "_init", 6);
  91635. zEntry = zAltEntry;
  91636. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91637. sqlite3OsDlSym(pVfs, handle, zEntry);
  91638. }
  91639. if( xInit==0 ){
  91640. if( pzErrMsg ){
  91641. nMsg += sqlite3Strlen30(zEntry);
  91642. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  91643. if( zErrmsg ){
  91644. sqlite3_snprintf(nMsg, zErrmsg,
  91645. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  91646. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  91647. }
  91648. }
  91649. sqlite3OsDlClose(pVfs, handle);
  91650. sqlite3_free(zAltEntry);
  91651. return SQLITE_ERROR;
  91652. }
  91653. sqlite3_free(zAltEntry);
  91654. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  91655. if( pzErrMsg ){
  91656. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  91657. }
  91658. sqlite3_free(zErrmsg);
  91659. sqlite3OsDlClose(pVfs, handle);
  91660. return SQLITE_ERROR;
  91661. }
  91662. /* Append the new shared library handle to the db->aExtension array. */
  91663. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  91664. if( aHandle==0 ){
  91665. return SQLITE_NOMEM;
  91666. }
  91667. if( db->nExtension>0 ){
  91668. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  91669. }
  91670. sqlite3DbFree(db, db->aExtension);
  91671. db->aExtension = aHandle;
  91672. db->aExtension[db->nExtension++] = handle;
  91673. return SQLITE_OK;
  91674. }
  91675. SQLITE_API int sqlite3_load_extension(
  91676. sqlite3 *db, /* Load the extension into this database connection */
  91677. const char *zFile, /* Name of the shared library containing extension */
  91678. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  91679. char **pzErrMsg /* Put error message here if not 0 */
  91680. ){
  91681. int rc;
  91682. sqlite3_mutex_enter(db->mutex);
  91683. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  91684. rc = sqlite3ApiExit(db, rc);
  91685. sqlite3_mutex_leave(db->mutex);
  91686. return rc;
  91687. }
  91688. /*
  91689. ** Call this routine when the database connection is closing in order
  91690. ** to clean up loaded extensions
  91691. */
  91692. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  91693. int i;
  91694. assert( sqlite3_mutex_held(db->mutex) );
  91695. for(i=0; i<db->nExtension; i++){
  91696. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  91697. }
  91698. sqlite3DbFree(db, db->aExtension);
  91699. }
  91700. /*
  91701. ** Enable or disable extension loading. Extension loading is disabled by
  91702. ** default so as not to open security holes in older applications.
  91703. */
  91704. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  91705. sqlite3_mutex_enter(db->mutex);
  91706. if( onoff ){
  91707. db->flags |= SQLITE_LoadExtension;
  91708. }else{
  91709. db->flags &= ~SQLITE_LoadExtension;
  91710. }
  91711. sqlite3_mutex_leave(db->mutex);
  91712. return SQLITE_OK;
  91713. }
  91714. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  91715. /*
  91716. ** The auto-extension code added regardless of whether or not extension
  91717. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  91718. ** code if regular extension loading is not available. This is that
  91719. ** dummy pointer.
  91720. */
  91721. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  91722. static const sqlite3_api_routines sqlite3Apis = { 0 };
  91723. #endif
  91724. /*
  91725. ** The following object holds the list of automatically loaded
  91726. ** extensions.
  91727. **
  91728. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  91729. ** mutex must be held while accessing this list.
  91730. */
  91731. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  91732. static SQLITE_WSD struct sqlite3AutoExtList {
  91733. int nExt; /* Number of entries in aExt[] */
  91734. void (**aExt)(void); /* Pointers to the extension init functions */
  91735. } sqlite3Autoext = { 0, 0 };
  91736. /* The "wsdAutoext" macro will resolve to the autoextension
  91737. ** state vector. If writable static data is unsupported on the target,
  91738. ** we have to locate the state vector at run-time. In the more common
  91739. ** case where writable static data is supported, wsdStat can refer directly
  91740. ** to the "sqlite3Autoext" state vector declared above.
  91741. */
  91742. #ifdef SQLITE_OMIT_WSD
  91743. # define wsdAutoextInit \
  91744. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  91745. # define wsdAutoext x[0]
  91746. #else
  91747. # define wsdAutoextInit
  91748. # define wsdAutoext sqlite3Autoext
  91749. #endif
  91750. /*
  91751. ** Register a statically linked extension that is automatically
  91752. ** loaded by every new database connection.
  91753. */
  91754. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  91755. int rc = SQLITE_OK;
  91756. #ifndef SQLITE_OMIT_AUTOINIT
  91757. rc = sqlite3_initialize();
  91758. if( rc ){
  91759. return rc;
  91760. }else
  91761. #endif
  91762. {
  91763. int i;
  91764. #if SQLITE_THREADSAFE
  91765. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91766. #endif
  91767. wsdAutoextInit;
  91768. sqlite3_mutex_enter(mutex);
  91769. for(i=0; i<wsdAutoext.nExt; i++){
  91770. if( wsdAutoext.aExt[i]==xInit ) break;
  91771. }
  91772. if( i==wsdAutoext.nExt ){
  91773. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  91774. void (**aNew)(void);
  91775. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  91776. if( aNew==0 ){
  91777. rc = SQLITE_NOMEM;
  91778. }else{
  91779. wsdAutoext.aExt = aNew;
  91780. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  91781. wsdAutoext.nExt++;
  91782. }
  91783. }
  91784. sqlite3_mutex_leave(mutex);
  91785. assert( (rc&0xff)==rc );
  91786. return rc;
  91787. }
  91788. }
  91789. /*
  91790. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  91791. ** set of routines that is invoked for each new database connection, if it
  91792. ** is currently on the list. If xInit is not on the list, then this
  91793. ** routine is a no-op.
  91794. **
  91795. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  91796. ** was not on the list.
  91797. */
  91798. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  91799. #if SQLITE_THREADSAFE
  91800. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91801. #endif
  91802. int i;
  91803. int n = 0;
  91804. wsdAutoextInit;
  91805. sqlite3_mutex_enter(mutex);
  91806. for(i=wsdAutoext.nExt-1; i>=0; i--){
  91807. if( wsdAutoext.aExt[i]==xInit ){
  91808. wsdAutoext.nExt--;
  91809. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  91810. n++;
  91811. break;
  91812. }
  91813. }
  91814. sqlite3_mutex_leave(mutex);
  91815. return n;
  91816. }
  91817. /*
  91818. ** Reset the automatic extension loading mechanism.
  91819. */
  91820. SQLITE_API void sqlite3_reset_auto_extension(void){
  91821. #ifndef SQLITE_OMIT_AUTOINIT
  91822. if( sqlite3_initialize()==SQLITE_OK )
  91823. #endif
  91824. {
  91825. #if SQLITE_THREADSAFE
  91826. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91827. #endif
  91828. wsdAutoextInit;
  91829. sqlite3_mutex_enter(mutex);
  91830. sqlite3_free(wsdAutoext.aExt);
  91831. wsdAutoext.aExt = 0;
  91832. wsdAutoext.nExt = 0;
  91833. sqlite3_mutex_leave(mutex);
  91834. }
  91835. }
  91836. /*
  91837. ** Load all automatic extensions.
  91838. **
  91839. ** If anything goes wrong, set an error in the database connection.
  91840. */
  91841. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  91842. int i;
  91843. int go = 1;
  91844. int rc;
  91845. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  91846. wsdAutoextInit;
  91847. if( wsdAutoext.nExt==0 ){
  91848. /* Common case: early out without every having to acquire a mutex */
  91849. return;
  91850. }
  91851. for(i=0; go; i++){
  91852. char *zErrmsg;
  91853. #if SQLITE_THREADSAFE
  91854. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  91855. #endif
  91856. sqlite3_mutex_enter(mutex);
  91857. if( i>=wsdAutoext.nExt ){
  91858. xInit = 0;
  91859. go = 0;
  91860. }else{
  91861. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  91862. wsdAutoext.aExt[i];
  91863. }
  91864. sqlite3_mutex_leave(mutex);
  91865. zErrmsg = 0;
  91866. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  91867. sqlite3Error(db, rc,
  91868. "automatic extension loading failed: %s", zErrmsg);
  91869. go = 0;
  91870. }
  91871. sqlite3_free(zErrmsg);
  91872. }
  91873. }
  91874. /************** End of loadext.c *********************************************/
  91875. /************** Begin file pragma.c ******************************************/
  91876. /*
  91877. ** 2003 April 6
  91878. **
  91879. ** The author disclaims copyright to this source code. In place of
  91880. ** a legal notice, here is a blessing:
  91881. **
  91882. ** May you do good and not evil.
  91883. ** May you find forgiveness for yourself and forgive others.
  91884. ** May you share freely, never taking more than you give.
  91885. **
  91886. *************************************************************************
  91887. ** This file contains code used to implement the PRAGMA command.
  91888. */
  91889. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  91890. # if defined(__APPLE__)
  91891. # define SQLITE_ENABLE_LOCKING_STYLE 1
  91892. # else
  91893. # define SQLITE_ENABLE_LOCKING_STYLE 0
  91894. # endif
  91895. #endif
  91896. /***************************************************************************
  91897. ** The next block of code, including the PragTyp_XXXX macro definitions and
  91898. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  91899. **
  91900. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  91901. ** that script. Then copy/paste the output in place of the following:
  91902. */
  91903. #define PragTyp_HEADER_VALUE 0
  91904. #define PragTyp_AUTO_VACUUM 1
  91905. #define PragTyp_FLAG 2
  91906. #define PragTyp_BUSY_TIMEOUT 3
  91907. #define PragTyp_CACHE_SIZE 4
  91908. #define PragTyp_CASE_SENSITIVE_LIKE 5
  91909. #define PragTyp_COLLATION_LIST 6
  91910. #define PragTyp_COMPILE_OPTIONS 7
  91911. #define PragTyp_DATA_STORE_DIRECTORY 8
  91912. #define PragTyp_DATABASE_LIST 9
  91913. #define PragTyp_DEFAULT_CACHE_SIZE 10
  91914. #define PragTyp_ENCODING 11
  91915. #define PragTyp_FOREIGN_KEY_CHECK 12
  91916. #define PragTyp_FOREIGN_KEY_LIST 13
  91917. #define PragTyp_INCREMENTAL_VACUUM 14
  91918. #define PragTyp_INDEX_INFO 15
  91919. #define PragTyp_INDEX_LIST 16
  91920. #define PragTyp_INTEGRITY_CHECK 17
  91921. #define PragTyp_JOURNAL_MODE 18
  91922. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  91923. #define PragTyp_LOCK_PROXY_FILE 20
  91924. #define PragTyp_LOCKING_MODE 21
  91925. #define PragTyp_PAGE_COUNT 22
  91926. #define PragTyp_MMAP_SIZE 23
  91927. #define PragTyp_PAGE_SIZE 24
  91928. #define PragTyp_SECURE_DELETE 25
  91929. #define PragTyp_SHRINK_MEMORY 26
  91930. #define PragTyp_SOFT_HEAP_LIMIT 27
  91931. #define PragTyp_STATS 28
  91932. #define PragTyp_SYNCHRONOUS 29
  91933. #define PragTyp_TABLE_INFO 30
  91934. #define PragTyp_TEMP_STORE 31
  91935. #define PragTyp_TEMP_STORE_DIRECTORY 32
  91936. #define PragTyp_WAL_AUTOCHECKPOINT 33
  91937. #define PragTyp_WAL_CHECKPOINT 34
  91938. #define PragTyp_ACTIVATE_EXTENSIONS 35
  91939. #define PragTyp_HEXKEY 36
  91940. #define PragTyp_KEY 37
  91941. #define PragTyp_REKEY 38
  91942. #define PragTyp_LOCK_STATUS 39
  91943. #define PragTyp_PARSER_TRACE 40
  91944. #define PragFlag_NeedSchema 0x01
  91945. static const struct sPragmaNames {
  91946. const char *const zName; /* Name of pragma */
  91947. u8 ePragTyp; /* PragTyp_XXX value */
  91948. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  91949. u32 iArg; /* Extra argument */
  91950. } aPragmaNames[] = {
  91951. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  91952. { /* zName: */ "activate_extensions",
  91953. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  91954. /* ePragFlag: */ 0,
  91955. /* iArg: */ 0 },
  91956. #endif
  91957. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  91958. { /* zName: */ "application_id",
  91959. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  91960. /* ePragFlag: */ 0,
  91961. /* iArg: */ 0 },
  91962. #endif
  91963. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  91964. { /* zName: */ "auto_vacuum",
  91965. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  91966. /* ePragFlag: */ PragFlag_NeedSchema,
  91967. /* iArg: */ 0 },
  91968. #endif
  91969. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  91970. { /* zName: */ "automatic_index",
  91971. /* ePragTyp: */ PragTyp_FLAG,
  91972. /* ePragFlag: */ 0,
  91973. /* iArg: */ SQLITE_AutoIndex },
  91974. #endif
  91975. { /* zName: */ "busy_timeout",
  91976. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  91977. /* ePragFlag: */ 0,
  91978. /* iArg: */ 0 },
  91979. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  91980. { /* zName: */ "cache_size",
  91981. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  91982. /* ePragFlag: */ PragFlag_NeedSchema,
  91983. /* iArg: */ 0 },
  91984. #endif
  91985. { /* zName: */ "cache_spill",
  91986. /* ePragTyp: */ PragTyp_FLAG,
  91987. /* ePragFlag: */ 0,
  91988. /* iArg: */ SQLITE_CacheSpill },
  91989. { /* zName: */ "case_sensitive_like",
  91990. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  91991. /* ePragFlag: */ 0,
  91992. /* iArg: */ 0 },
  91993. { /* zName: */ "checkpoint_fullfsync",
  91994. /* ePragTyp: */ PragTyp_FLAG,
  91995. /* ePragFlag: */ 0,
  91996. /* iArg: */ SQLITE_CkptFullFSync },
  91997. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  91998. { /* zName: */ "collation_list",
  91999. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  92000. /* ePragFlag: */ 0,
  92001. /* iArg: */ 0 },
  92002. #endif
  92003. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  92004. { /* zName: */ "compile_options",
  92005. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  92006. /* ePragFlag: */ 0,
  92007. /* iArg: */ 0 },
  92008. #endif
  92009. { /* zName: */ "count_changes",
  92010. /* ePragTyp: */ PragTyp_FLAG,
  92011. /* ePragFlag: */ 0,
  92012. /* iArg: */ SQLITE_CountRows },
  92013. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  92014. { /* zName: */ "data_store_directory",
  92015. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  92016. /* ePragFlag: */ 0,
  92017. /* iArg: */ 0 },
  92018. #endif
  92019. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92020. { /* zName: */ "database_list",
  92021. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  92022. /* ePragFlag: */ PragFlag_NeedSchema,
  92023. /* iArg: */ 0 },
  92024. #endif
  92025. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  92026. { /* zName: */ "default_cache_size",
  92027. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  92028. /* ePragFlag: */ PragFlag_NeedSchema,
  92029. /* iArg: */ 0 },
  92030. #endif
  92031. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92032. { /* zName: */ "defer_foreign_keys",
  92033. /* ePragTyp: */ PragTyp_FLAG,
  92034. /* ePragFlag: */ 0,
  92035. /* iArg: */ SQLITE_DeferFKs },
  92036. #endif
  92037. { /* zName: */ "empty_result_callbacks",
  92038. /* ePragTyp: */ PragTyp_FLAG,
  92039. /* ePragFlag: */ 0,
  92040. /* iArg: */ SQLITE_NullCallback },
  92041. #if !defined(SQLITE_OMIT_UTF16)
  92042. { /* zName: */ "encoding",
  92043. /* ePragTyp: */ PragTyp_ENCODING,
  92044. /* ePragFlag: */ 0,
  92045. /* iArg: */ 0 },
  92046. #endif
  92047. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92048. { /* zName: */ "foreign_key_check",
  92049. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  92050. /* ePragFlag: */ PragFlag_NeedSchema,
  92051. /* iArg: */ 0 },
  92052. #endif
  92053. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  92054. { /* zName: */ "foreign_key_list",
  92055. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  92056. /* ePragFlag: */ PragFlag_NeedSchema,
  92057. /* iArg: */ 0 },
  92058. #endif
  92059. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  92060. { /* zName: */ "foreign_keys",
  92061. /* ePragTyp: */ PragTyp_FLAG,
  92062. /* ePragFlag: */ 0,
  92063. /* iArg: */ SQLITE_ForeignKeys },
  92064. #endif
  92065. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92066. { /* zName: */ "freelist_count",
  92067. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92068. /* ePragFlag: */ 0,
  92069. /* iArg: */ 0 },
  92070. #endif
  92071. { /* zName: */ "full_column_names",
  92072. /* ePragTyp: */ PragTyp_FLAG,
  92073. /* ePragFlag: */ 0,
  92074. /* iArg: */ SQLITE_FullColNames },
  92075. { /* zName: */ "fullfsync",
  92076. /* ePragTyp: */ PragTyp_FLAG,
  92077. /* ePragFlag: */ 0,
  92078. /* iArg: */ SQLITE_FullFSync },
  92079. #if defined(SQLITE_HAS_CODEC)
  92080. { /* zName: */ "hexkey",
  92081. /* ePragTyp: */ PragTyp_HEXKEY,
  92082. /* ePragFlag: */ 0,
  92083. /* iArg: */ 0 },
  92084. { /* zName: */ "hexrekey",
  92085. /* ePragTyp: */ PragTyp_HEXKEY,
  92086. /* ePragFlag: */ 0,
  92087. /* iArg: */ 0 },
  92088. #endif
  92089. #if !defined(SQLITE_OMIT_CHECK)
  92090. { /* zName: */ "ignore_check_constraints",
  92091. /* ePragTyp: */ PragTyp_FLAG,
  92092. /* ePragFlag: */ 0,
  92093. /* iArg: */ SQLITE_IgnoreChecks },
  92094. #endif
  92095. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  92096. { /* zName: */ "incremental_vacuum",
  92097. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  92098. /* ePragFlag: */ PragFlag_NeedSchema,
  92099. /* iArg: */ 0 },
  92100. #endif
  92101. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92102. { /* zName: */ "index_info",
  92103. /* ePragTyp: */ PragTyp_INDEX_INFO,
  92104. /* ePragFlag: */ PragFlag_NeedSchema,
  92105. /* iArg: */ 0 },
  92106. { /* zName: */ "index_list",
  92107. /* ePragTyp: */ PragTyp_INDEX_LIST,
  92108. /* ePragFlag: */ PragFlag_NeedSchema,
  92109. /* iArg: */ 0 },
  92110. #endif
  92111. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  92112. { /* zName: */ "integrity_check",
  92113. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  92114. /* ePragFlag: */ PragFlag_NeedSchema,
  92115. /* iArg: */ 0 },
  92116. #endif
  92117. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92118. { /* zName: */ "journal_mode",
  92119. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  92120. /* ePragFlag: */ PragFlag_NeedSchema,
  92121. /* iArg: */ 0 },
  92122. { /* zName: */ "journal_size_limit",
  92123. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  92124. /* ePragFlag: */ 0,
  92125. /* iArg: */ 0 },
  92126. #endif
  92127. #if defined(SQLITE_HAS_CODEC)
  92128. { /* zName: */ "key",
  92129. /* ePragTyp: */ PragTyp_KEY,
  92130. /* ePragFlag: */ 0,
  92131. /* iArg: */ 0 },
  92132. #endif
  92133. { /* zName: */ "legacy_file_format",
  92134. /* ePragTyp: */ PragTyp_FLAG,
  92135. /* ePragFlag: */ 0,
  92136. /* iArg: */ SQLITE_LegacyFileFmt },
  92137. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  92138. { /* zName: */ "lock_proxy_file",
  92139. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  92140. /* ePragFlag: */ 0,
  92141. /* iArg: */ 0 },
  92142. #endif
  92143. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  92144. { /* zName: */ "lock_status",
  92145. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  92146. /* ePragFlag: */ 0,
  92147. /* iArg: */ 0 },
  92148. #endif
  92149. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92150. { /* zName: */ "locking_mode",
  92151. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  92152. /* ePragFlag: */ 0,
  92153. /* iArg: */ 0 },
  92154. { /* zName: */ "max_page_count",
  92155. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  92156. /* ePragFlag: */ PragFlag_NeedSchema,
  92157. /* iArg: */ 0 },
  92158. { /* zName: */ "mmap_size",
  92159. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  92160. /* ePragFlag: */ 0,
  92161. /* iArg: */ 0 },
  92162. { /* zName: */ "page_count",
  92163. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  92164. /* ePragFlag: */ PragFlag_NeedSchema,
  92165. /* iArg: */ 0 },
  92166. { /* zName: */ "page_size",
  92167. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  92168. /* ePragFlag: */ 0,
  92169. /* iArg: */ 0 },
  92170. #endif
  92171. #if defined(SQLITE_DEBUG)
  92172. { /* zName: */ "parser_trace",
  92173. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  92174. /* ePragFlag: */ 0,
  92175. /* iArg: */ 0 },
  92176. #endif
  92177. { /* zName: */ "query_only",
  92178. /* ePragTyp: */ PragTyp_FLAG,
  92179. /* ePragFlag: */ 0,
  92180. /* iArg: */ SQLITE_QueryOnly },
  92181. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  92182. { /* zName: */ "quick_check",
  92183. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  92184. /* ePragFlag: */ PragFlag_NeedSchema,
  92185. /* iArg: */ 0 },
  92186. #endif
  92187. { /* zName: */ "read_uncommitted",
  92188. /* ePragTyp: */ PragTyp_FLAG,
  92189. /* ePragFlag: */ 0,
  92190. /* iArg: */ SQLITE_ReadUncommitted },
  92191. { /* zName: */ "recursive_triggers",
  92192. /* ePragTyp: */ PragTyp_FLAG,
  92193. /* ePragFlag: */ 0,
  92194. /* iArg: */ SQLITE_RecTriggers },
  92195. #if defined(SQLITE_HAS_CODEC)
  92196. { /* zName: */ "rekey",
  92197. /* ePragTyp: */ PragTyp_REKEY,
  92198. /* ePragFlag: */ 0,
  92199. /* iArg: */ 0 },
  92200. #endif
  92201. { /* zName: */ "reverse_unordered_selects",
  92202. /* ePragTyp: */ PragTyp_FLAG,
  92203. /* ePragFlag: */ 0,
  92204. /* iArg: */ SQLITE_ReverseOrder },
  92205. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92206. { /* zName: */ "schema_version",
  92207. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92208. /* ePragFlag: */ 0,
  92209. /* iArg: */ 0 },
  92210. #endif
  92211. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92212. { /* zName: */ "secure_delete",
  92213. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  92214. /* ePragFlag: */ 0,
  92215. /* iArg: */ 0 },
  92216. #endif
  92217. { /* zName: */ "short_column_names",
  92218. /* ePragTyp: */ PragTyp_FLAG,
  92219. /* ePragFlag: */ 0,
  92220. /* iArg: */ SQLITE_ShortColNames },
  92221. { /* zName: */ "shrink_memory",
  92222. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  92223. /* ePragFlag: */ 0,
  92224. /* iArg: */ 0 },
  92225. { /* zName: */ "soft_heap_limit",
  92226. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  92227. /* ePragFlag: */ 0,
  92228. /* iArg: */ 0 },
  92229. #if defined(SQLITE_DEBUG)
  92230. { /* zName: */ "sql_trace",
  92231. /* ePragTyp: */ PragTyp_FLAG,
  92232. /* ePragFlag: */ 0,
  92233. /* iArg: */ SQLITE_SqlTrace },
  92234. #endif
  92235. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92236. { /* zName: */ "stats",
  92237. /* ePragTyp: */ PragTyp_STATS,
  92238. /* ePragFlag: */ PragFlag_NeedSchema,
  92239. /* iArg: */ 0 },
  92240. #endif
  92241. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92242. { /* zName: */ "synchronous",
  92243. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  92244. /* ePragFlag: */ PragFlag_NeedSchema,
  92245. /* iArg: */ 0 },
  92246. #endif
  92247. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  92248. { /* zName: */ "table_info",
  92249. /* ePragTyp: */ PragTyp_TABLE_INFO,
  92250. /* ePragFlag: */ PragFlag_NeedSchema,
  92251. /* iArg: */ 0 },
  92252. #endif
  92253. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92254. { /* zName: */ "temp_store",
  92255. /* ePragTyp: */ PragTyp_TEMP_STORE,
  92256. /* ePragFlag: */ 0,
  92257. /* iArg: */ 0 },
  92258. { /* zName: */ "temp_store_directory",
  92259. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  92260. /* ePragFlag: */ 0,
  92261. /* iArg: */ 0 },
  92262. #endif
  92263. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  92264. { /* zName: */ "user_version",
  92265. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  92266. /* ePragFlag: */ 0,
  92267. /* iArg: */ 0 },
  92268. #endif
  92269. #if defined(SQLITE_DEBUG)
  92270. { /* zName: */ "vdbe_addoptrace",
  92271. /* ePragTyp: */ PragTyp_FLAG,
  92272. /* ePragFlag: */ 0,
  92273. /* iArg: */ SQLITE_VdbeAddopTrace },
  92274. { /* zName: */ "vdbe_debug",
  92275. /* ePragTyp: */ PragTyp_FLAG,
  92276. /* ePragFlag: */ 0,
  92277. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  92278. { /* zName: */ "vdbe_listing",
  92279. /* ePragTyp: */ PragTyp_FLAG,
  92280. /* ePragFlag: */ 0,
  92281. /* iArg: */ SQLITE_VdbeListing },
  92282. { /* zName: */ "vdbe_trace",
  92283. /* ePragTyp: */ PragTyp_FLAG,
  92284. /* ePragFlag: */ 0,
  92285. /* iArg: */ SQLITE_VdbeTrace },
  92286. #endif
  92287. #if !defined(SQLITE_OMIT_WAL)
  92288. { /* zName: */ "wal_autocheckpoint",
  92289. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  92290. /* ePragFlag: */ 0,
  92291. /* iArg: */ 0 },
  92292. { /* zName: */ "wal_checkpoint",
  92293. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  92294. /* ePragFlag: */ PragFlag_NeedSchema,
  92295. /* iArg: */ 0 },
  92296. #endif
  92297. { /* zName: */ "writable_schema",
  92298. /* ePragTyp: */ PragTyp_FLAG,
  92299. /* ePragFlag: */ 0,
  92300. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  92301. };
  92302. /* Number of pragmas: 56 on by default, 68 total. */
  92303. /* End of the automatically generated pragma table.
  92304. ***************************************************************************/
  92305. /*
  92306. ** Interpret the given string as a safety level. Return 0 for OFF,
  92307. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  92308. ** unrecognized string argument. The FULL option is disallowed
  92309. ** if the omitFull parameter it 1.
  92310. **
  92311. ** Note that the values returned are one less that the values that
  92312. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  92313. ** to support legacy SQL code. The safety level used to be boolean
  92314. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  92315. */
  92316. static u8 getSafetyLevel(const char *z, int omitFull, int dflt){
  92317. /* 123456789 123456789 */
  92318. static const char zText[] = "onoffalseyestruefull";
  92319. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  92320. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  92321. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  92322. int i, n;
  92323. if( sqlite3Isdigit(*z) ){
  92324. return (u8)sqlite3Atoi(z);
  92325. }
  92326. n = sqlite3Strlen30(z);
  92327. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  92328. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  92329. return iValue[i];
  92330. }
  92331. }
  92332. return dflt;
  92333. }
  92334. /*
  92335. ** Interpret the given string as a boolean value.
  92336. */
  92337. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, int dflt){
  92338. return getSafetyLevel(z,1,dflt)!=0;
  92339. }
  92340. /* The sqlite3GetBoolean() function is used by other modules but the
  92341. ** remainder of this file is specific to PRAGMA processing. So omit
  92342. ** the rest of the file if PRAGMAs are omitted from the build.
  92343. */
  92344. #if !defined(SQLITE_OMIT_PRAGMA)
  92345. /*
  92346. ** Interpret the given string as a locking mode value.
  92347. */
  92348. static int getLockingMode(const char *z){
  92349. if( z ){
  92350. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  92351. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  92352. }
  92353. return PAGER_LOCKINGMODE_QUERY;
  92354. }
  92355. #ifndef SQLITE_OMIT_AUTOVACUUM
  92356. /*
  92357. ** Interpret the given string as an auto-vacuum mode value.
  92358. **
  92359. ** The following strings, "none", "full" and "incremental" are
  92360. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  92361. */
  92362. static int getAutoVacuum(const char *z){
  92363. int i;
  92364. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  92365. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  92366. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  92367. i = sqlite3Atoi(z);
  92368. return (u8)((i>=0&&i<=2)?i:0);
  92369. }
  92370. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  92371. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92372. /*
  92373. ** Interpret the given string as a temp db location. Return 1 for file
  92374. ** backed temporary databases, 2 for the Red-Black tree in memory database
  92375. ** and 0 to use the compile-time default.
  92376. */
  92377. static int getTempStore(const char *z){
  92378. if( z[0]>='0' && z[0]<='2' ){
  92379. return z[0] - '0';
  92380. }else if( sqlite3StrICmp(z, "file")==0 ){
  92381. return 1;
  92382. }else if( sqlite3StrICmp(z, "memory")==0 ){
  92383. return 2;
  92384. }else{
  92385. return 0;
  92386. }
  92387. }
  92388. #endif /* SQLITE_PAGER_PRAGMAS */
  92389. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92390. /*
  92391. ** Invalidate temp storage, either when the temp storage is changed
  92392. ** from default, or when 'file' and the temp_store_directory has changed
  92393. */
  92394. static int invalidateTempStorage(Parse *pParse){
  92395. sqlite3 *db = pParse->db;
  92396. if( db->aDb[1].pBt!=0 ){
  92397. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  92398. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  92399. "from within a transaction");
  92400. return SQLITE_ERROR;
  92401. }
  92402. sqlite3BtreeClose(db->aDb[1].pBt);
  92403. db->aDb[1].pBt = 0;
  92404. sqlite3ResetAllSchemasOfConnection(db);
  92405. }
  92406. return SQLITE_OK;
  92407. }
  92408. #endif /* SQLITE_PAGER_PRAGMAS */
  92409. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92410. /*
  92411. ** If the TEMP database is open, close it and mark the database schema
  92412. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  92413. ** or DEFAULT_TEMP_STORE pragmas.
  92414. */
  92415. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  92416. int ts = getTempStore(zStorageType);
  92417. sqlite3 *db = pParse->db;
  92418. if( db->temp_store==ts ) return SQLITE_OK;
  92419. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  92420. return SQLITE_ERROR;
  92421. }
  92422. db->temp_store = (u8)ts;
  92423. return SQLITE_OK;
  92424. }
  92425. #endif /* SQLITE_PAGER_PRAGMAS */
  92426. /*
  92427. ** Generate code to return a single integer value.
  92428. */
  92429. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  92430. Vdbe *v = sqlite3GetVdbe(pParse);
  92431. int mem = ++pParse->nMem;
  92432. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  92433. if( pI64 ){
  92434. memcpy(pI64, &value, sizeof(value));
  92435. }
  92436. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  92437. sqlite3VdbeSetNumCols(v, 1);
  92438. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  92439. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  92440. }
  92441. /*
  92442. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  92443. ** set these values for all pagers.
  92444. */
  92445. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92446. static void setAllPagerFlags(sqlite3 *db){
  92447. if( db->autoCommit ){
  92448. Db *pDb = db->aDb;
  92449. int n = db->nDb;
  92450. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  92451. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  92452. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  92453. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  92454. == PAGER_FLAGS_MASK );
  92455. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  92456. while( (n--) > 0 ){
  92457. if( pDb->pBt ){
  92458. sqlite3BtreeSetPagerFlags(pDb->pBt,
  92459. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  92460. }
  92461. pDb++;
  92462. }
  92463. }
  92464. }
  92465. #else
  92466. # define setAllPagerFlags(X) /* no-op */
  92467. #endif
  92468. /*
  92469. ** Return a human-readable name for a constraint resolution action.
  92470. */
  92471. #ifndef SQLITE_OMIT_FOREIGN_KEY
  92472. static const char *actionName(u8 action){
  92473. const char *zName;
  92474. switch( action ){
  92475. case OE_SetNull: zName = "SET NULL"; break;
  92476. case OE_SetDflt: zName = "SET DEFAULT"; break;
  92477. case OE_Cascade: zName = "CASCADE"; break;
  92478. case OE_Restrict: zName = "RESTRICT"; break;
  92479. default: zName = "NO ACTION";
  92480. assert( action==OE_None ); break;
  92481. }
  92482. return zName;
  92483. }
  92484. #endif
  92485. /*
  92486. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  92487. ** defined in pager.h. This function returns the associated lowercase
  92488. ** journal-mode name.
  92489. */
  92490. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  92491. static char * const azModeName[] = {
  92492. "delete", "persist", "off", "truncate", "memory"
  92493. #ifndef SQLITE_OMIT_WAL
  92494. , "wal"
  92495. #endif
  92496. };
  92497. assert( PAGER_JOURNALMODE_DELETE==0 );
  92498. assert( PAGER_JOURNALMODE_PERSIST==1 );
  92499. assert( PAGER_JOURNALMODE_OFF==2 );
  92500. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  92501. assert( PAGER_JOURNALMODE_MEMORY==4 );
  92502. assert( PAGER_JOURNALMODE_WAL==5 );
  92503. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  92504. if( eMode==ArraySize(azModeName) ) return 0;
  92505. return azModeName[eMode];
  92506. }
  92507. /*
  92508. ** Process a pragma statement.
  92509. **
  92510. ** Pragmas are of this form:
  92511. **
  92512. ** PRAGMA [database.]id [= value]
  92513. **
  92514. ** The identifier might also be a string. The value is a string, and
  92515. ** identifier, or a number. If minusFlag is true, then the value is
  92516. ** a number that was preceded by a minus sign.
  92517. **
  92518. ** If the left side is "database.id" then pId1 is the database name
  92519. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  92520. ** id and pId2 is any empty string.
  92521. */
  92522. SQLITE_PRIVATE void sqlite3Pragma(
  92523. Parse *pParse,
  92524. Token *pId1, /* First part of [database.]id field */
  92525. Token *pId2, /* Second part of [database.]id field, or NULL */
  92526. Token *pValue, /* Token for <value>, or NULL */
  92527. int minusFlag /* True if a '-' sign preceded <value> */
  92528. ){
  92529. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  92530. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  92531. const char *zDb = 0; /* The database name */
  92532. Token *pId; /* Pointer to <id> token */
  92533. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  92534. int iDb; /* Database index for <database> */
  92535. int lwr, upr, mid; /* Binary search bounds */
  92536. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  92537. sqlite3 *db = pParse->db; /* The database connection */
  92538. Db *pDb; /* The specific database being pragmaed */
  92539. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  92540. if( v==0 ) return;
  92541. sqlite3VdbeRunOnlyOnce(v);
  92542. pParse->nMem = 2;
  92543. /* Interpret the [database.] part of the pragma statement. iDb is the
  92544. ** index of the database this pragma is being applied to in db.aDb[]. */
  92545. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  92546. if( iDb<0 ) return;
  92547. pDb = &db->aDb[iDb];
  92548. /* If the temp database has been explicitly named as part of the
  92549. ** pragma, make sure it is open.
  92550. */
  92551. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  92552. return;
  92553. }
  92554. zLeft = sqlite3NameFromToken(db, pId);
  92555. if( !zLeft ) return;
  92556. if( minusFlag ){
  92557. zRight = sqlite3MPrintf(db, "-%T", pValue);
  92558. }else{
  92559. zRight = sqlite3NameFromToken(db, pValue);
  92560. }
  92561. assert( pId2 );
  92562. zDb = pId2->n>0 ? pDb->zName : 0;
  92563. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  92564. goto pragma_out;
  92565. }
  92566. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  92567. ** connection. If it returns SQLITE_OK, then assume that the VFS
  92568. ** handled the pragma and generate a no-op prepared statement.
  92569. */
  92570. aFcntl[0] = 0;
  92571. aFcntl[1] = zLeft;
  92572. aFcntl[2] = zRight;
  92573. aFcntl[3] = 0;
  92574. db->busyHandler.nBusy = 0;
  92575. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  92576. if( rc==SQLITE_OK ){
  92577. if( aFcntl[0] ){
  92578. int mem = ++pParse->nMem;
  92579. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  92580. sqlite3VdbeSetNumCols(v, 1);
  92581. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  92582. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  92583. sqlite3_free(aFcntl[0]);
  92584. }
  92585. goto pragma_out;
  92586. }
  92587. if( rc!=SQLITE_NOTFOUND ){
  92588. if( aFcntl[0] ){
  92589. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  92590. sqlite3_free(aFcntl[0]);
  92591. }
  92592. pParse->nErr++;
  92593. pParse->rc = rc;
  92594. goto pragma_out;
  92595. }
  92596. /* Locate the pragma in the lookup table */
  92597. lwr = 0;
  92598. upr = ArraySize(aPragmaNames)-1;
  92599. while( lwr<=upr ){
  92600. mid = (lwr+upr)/2;
  92601. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  92602. if( rc==0 ) break;
  92603. if( rc<0 ){
  92604. upr = mid - 1;
  92605. }else{
  92606. lwr = mid + 1;
  92607. }
  92608. }
  92609. if( lwr>upr ) goto pragma_out;
  92610. /* Make sure the database schema is loaded if the pragma requires that */
  92611. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  92612. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  92613. }
  92614. /* Jump to the appropriate pragma handler */
  92615. switch( aPragmaNames[mid].ePragTyp ){
  92616. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  92617. /*
  92618. ** PRAGMA [database.]default_cache_size
  92619. ** PRAGMA [database.]default_cache_size=N
  92620. **
  92621. ** The first form reports the current persistent setting for the
  92622. ** page cache size. The value returned is the maximum number of
  92623. ** pages in the page cache. The second form sets both the current
  92624. ** page cache size value and the persistent page cache size value
  92625. ** stored in the database file.
  92626. **
  92627. ** Older versions of SQLite would set the default cache size to a
  92628. ** negative number to indicate synchronous=OFF. These days, synchronous
  92629. ** is always on by default regardless of the sign of the default cache
  92630. ** size. But continue to take the absolute value of the default cache
  92631. ** size of historical compatibility.
  92632. */
  92633. case PragTyp_DEFAULT_CACHE_SIZE: {
  92634. static const VdbeOpList getCacheSize[] = {
  92635. { OP_Transaction, 0, 0, 0}, /* 0 */
  92636. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  92637. { OP_IfPos, 1, 8, 0},
  92638. { OP_Integer, 0, 2, 0},
  92639. { OP_Subtract, 1, 2, 1},
  92640. { OP_IfPos, 1, 8, 0},
  92641. { OP_Integer, 0, 1, 0}, /* 6 */
  92642. { OP_Noop, 0, 0, 0},
  92643. { OP_ResultRow, 1, 1, 0},
  92644. };
  92645. int addr;
  92646. sqlite3VdbeUsesBtree(v, iDb);
  92647. if( !zRight ){
  92648. sqlite3VdbeSetNumCols(v, 1);
  92649. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  92650. pParse->nMem += 2;
  92651. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  92652. sqlite3VdbeChangeP1(v, addr, iDb);
  92653. sqlite3VdbeChangeP1(v, addr+1, iDb);
  92654. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  92655. }else{
  92656. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  92657. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92658. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  92659. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  92660. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92661. pDb->pSchema->cache_size = size;
  92662. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  92663. }
  92664. break;
  92665. }
  92666. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  92667. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  92668. /*
  92669. ** PRAGMA [database.]page_size
  92670. ** PRAGMA [database.]page_size=N
  92671. **
  92672. ** The first form reports the current setting for the
  92673. ** database page size in bytes. The second form sets the
  92674. ** database page size value. The value can only be set if
  92675. ** the database has not yet been created.
  92676. */
  92677. case PragTyp_PAGE_SIZE: {
  92678. Btree *pBt = pDb->pBt;
  92679. assert( pBt!=0 );
  92680. if( !zRight ){
  92681. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  92682. returnSingleInt(pParse, "page_size", size);
  92683. }else{
  92684. /* Malloc may fail when setting the page-size, as there is an internal
  92685. ** buffer that the pager module resizes using sqlite3_realloc().
  92686. */
  92687. db->nextPagesize = sqlite3Atoi(zRight);
  92688. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  92689. db->mallocFailed = 1;
  92690. }
  92691. }
  92692. break;
  92693. }
  92694. /*
  92695. ** PRAGMA [database.]secure_delete
  92696. ** PRAGMA [database.]secure_delete=ON/OFF
  92697. **
  92698. ** The first form reports the current setting for the
  92699. ** secure_delete flag. The second form changes the secure_delete
  92700. ** flag setting and reports thenew value.
  92701. */
  92702. case PragTyp_SECURE_DELETE: {
  92703. Btree *pBt = pDb->pBt;
  92704. int b = -1;
  92705. assert( pBt!=0 );
  92706. if( zRight ){
  92707. b = sqlite3GetBoolean(zRight, 0);
  92708. }
  92709. if( pId2->n==0 && b>=0 ){
  92710. int ii;
  92711. for(ii=0; ii<db->nDb; ii++){
  92712. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  92713. }
  92714. }
  92715. b = sqlite3BtreeSecureDelete(pBt, b);
  92716. returnSingleInt(pParse, "secure_delete", b);
  92717. break;
  92718. }
  92719. /*
  92720. ** PRAGMA [database.]max_page_count
  92721. ** PRAGMA [database.]max_page_count=N
  92722. **
  92723. ** The first form reports the current setting for the
  92724. ** maximum number of pages in the database file. The
  92725. ** second form attempts to change this setting. Both
  92726. ** forms return the current setting.
  92727. **
  92728. ** The absolute value of N is used. This is undocumented and might
  92729. ** change. The only purpose is to provide an easy way to test
  92730. ** the sqlite3AbsInt32() function.
  92731. **
  92732. ** PRAGMA [database.]page_count
  92733. **
  92734. ** Return the number of pages in the specified database.
  92735. */
  92736. case PragTyp_PAGE_COUNT: {
  92737. int iReg;
  92738. sqlite3CodeVerifySchema(pParse, iDb);
  92739. iReg = ++pParse->nMem;
  92740. if( sqlite3Tolower(zLeft[0])=='p' ){
  92741. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  92742. }else{
  92743. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  92744. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  92745. }
  92746. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  92747. sqlite3VdbeSetNumCols(v, 1);
  92748. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  92749. break;
  92750. }
  92751. /*
  92752. ** PRAGMA [database.]locking_mode
  92753. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  92754. */
  92755. case PragTyp_LOCKING_MODE: {
  92756. const char *zRet = "normal";
  92757. int eMode = getLockingMode(zRight);
  92758. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  92759. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  92760. ** the current default locking mode (which may be different to
  92761. ** the locking-mode of the main database).
  92762. */
  92763. eMode = db->dfltLockMode;
  92764. }else{
  92765. Pager *pPager;
  92766. if( pId2->n==0 ){
  92767. /* This indicates that no database name was specified as part
  92768. ** of the PRAGMA command. In this case the locking-mode must be
  92769. ** set on all attached databases, as well as the main db file.
  92770. **
  92771. ** Also, the sqlite3.dfltLockMode variable is set so that
  92772. ** any subsequently attached databases also use the specified
  92773. ** locking mode.
  92774. */
  92775. int ii;
  92776. assert(pDb==&db->aDb[0]);
  92777. for(ii=2; ii<db->nDb; ii++){
  92778. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  92779. sqlite3PagerLockingMode(pPager, eMode);
  92780. }
  92781. db->dfltLockMode = (u8)eMode;
  92782. }
  92783. pPager = sqlite3BtreePager(pDb->pBt);
  92784. eMode = sqlite3PagerLockingMode(pPager, eMode);
  92785. }
  92786. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  92787. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  92788. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  92789. zRet = "exclusive";
  92790. }
  92791. sqlite3VdbeSetNumCols(v, 1);
  92792. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  92793. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  92794. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  92795. break;
  92796. }
  92797. /*
  92798. ** PRAGMA [database.]journal_mode
  92799. ** PRAGMA [database.]journal_mode =
  92800. ** (delete|persist|off|truncate|memory|wal|off)
  92801. */
  92802. case PragTyp_JOURNAL_MODE: {
  92803. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  92804. int ii; /* Loop counter */
  92805. sqlite3VdbeSetNumCols(v, 1);
  92806. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  92807. if( zRight==0 ){
  92808. /* If there is no "=MODE" part of the pragma, do a query for the
  92809. ** current mode */
  92810. eMode = PAGER_JOURNALMODE_QUERY;
  92811. }else{
  92812. const char *zMode;
  92813. int n = sqlite3Strlen30(zRight);
  92814. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  92815. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  92816. }
  92817. if( !zMode ){
  92818. /* If the "=MODE" part does not match any known journal mode,
  92819. ** then do a query */
  92820. eMode = PAGER_JOURNALMODE_QUERY;
  92821. }
  92822. }
  92823. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  92824. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  92825. iDb = 0;
  92826. pId2->n = 1;
  92827. }
  92828. for(ii=db->nDb-1; ii>=0; ii--){
  92829. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  92830. sqlite3VdbeUsesBtree(v, ii);
  92831. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  92832. }
  92833. }
  92834. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  92835. break;
  92836. }
  92837. /*
  92838. ** PRAGMA [database.]journal_size_limit
  92839. ** PRAGMA [database.]journal_size_limit=N
  92840. **
  92841. ** Get or set the size limit on rollback journal files.
  92842. */
  92843. case PragTyp_JOURNAL_SIZE_LIMIT: {
  92844. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  92845. i64 iLimit = -2;
  92846. if( zRight ){
  92847. sqlite3Atoi64(zRight, &iLimit, sqlite3Strlen30(zRight), SQLITE_UTF8);
  92848. if( iLimit<-1 ) iLimit = -1;
  92849. }
  92850. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  92851. returnSingleInt(pParse, "journal_size_limit", iLimit);
  92852. break;
  92853. }
  92854. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  92855. /*
  92856. ** PRAGMA [database.]auto_vacuum
  92857. ** PRAGMA [database.]auto_vacuum=N
  92858. **
  92859. ** Get or set the value of the database 'auto-vacuum' parameter.
  92860. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  92861. */
  92862. #ifndef SQLITE_OMIT_AUTOVACUUM
  92863. case PragTyp_AUTO_VACUUM: {
  92864. Btree *pBt = pDb->pBt;
  92865. assert( pBt!=0 );
  92866. if( !zRight ){
  92867. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  92868. }else{
  92869. int eAuto = getAutoVacuum(zRight);
  92870. assert( eAuto>=0 && eAuto<=2 );
  92871. db->nextAutovac = (u8)eAuto;
  92872. /* Call SetAutoVacuum() to set initialize the internal auto and
  92873. ** incr-vacuum flags. This is required in case this connection
  92874. ** creates the database file. It is important that it is created
  92875. ** as an auto-vacuum capable db.
  92876. */
  92877. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  92878. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  92879. /* When setting the auto_vacuum mode to either "full" or
  92880. ** "incremental", write the value of meta[6] in the database
  92881. ** file. Before writing to meta[6], check that meta[3] indicates
  92882. ** that this really is an auto-vacuum capable database.
  92883. */
  92884. static const VdbeOpList setMeta6[] = {
  92885. { OP_Transaction, 0, 1, 0}, /* 0 */
  92886. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  92887. { OP_If, 1, 0, 0}, /* 2 */
  92888. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  92889. { OP_Integer, 0, 1, 0}, /* 4 */
  92890. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  92891. };
  92892. int iAddr;
  92893. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
  92894. sqlite3VdbeChangeP1(v, iAddr, iDb);
  92895. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  92896. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  92897. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  92898. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  92899. sqlite3VdbeUsesBtree(v, iDb);
  92900. }
  92901. }
  92902. break;
  92903. }
  92904. #endif
  92905. /*
  92906. ** PRAGMA [database.]incremental_vacuum(N)
  92907. **
  92908. ** Do N steps of incremental vacuuming on a database.
  92909. */
  92910. #ifndef SQLITE_OMIT_AUTOVACUUM
  92911. case PragTyp_INCREMENTAL_VACUUM: {
  92912. int iLimit, addr;
  92913. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  92914. iLimit = 0x7fffffff;
  92915. }
  92916. sqlite3BeginWriteOperation(pParse, 0, iDb);
  92917. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  92918. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
  92919. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  92920. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  92921. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
  92922. sqlite3VdbeJumpHere(v, addr);
  92923. break;
  92924. }
  92925. #endif
  92926. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  92927. /*
  92928. ** PRAGMA [database.]cache_size
  92929. ** PRAGMA [database.]cache_size=N
  92930. **
  92931. ** The first form reports the current local setting for the
  92932. ** page cache size. The second form sets the local
  92933. ** page cache size value. If N is positive then that is the
  92934. ** number of pages in the cache. If N is negative, then the
  92935. ** number of pages is adjusted so that the cache uses -N kibibytes
  92936. ** of memory.
  92937. */
  92938. case PragTyp_CACHE_SIZE: {
  92939. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92940. if( !zRight ){
  92941. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  92942. }else{
  92943. int size = sqlite3Atoi(zRight);
  92944. pDb->pSchema->cache_size = size;
  92945. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  92946. }
  92947. break;
  92948. }
  92949. /*
  92950. ** PRAGMA [database.]mmap_size(N)
  92951. **
  92952. ** Used to set mapping size limit. The mapping size limit is
  92953. ** used to limit the aggregate size of all memory mapped regions of the
  92954. ** database file. If this parameter is set to zero, then memory mapping
  92955. ** is not used at all. If N is negative, then the default memory map
  92956. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  92957. ** The parameter N is measured in bytes.
  92958. **
  92959. ** This value is advisory. The underlying VFS is free to memory map
  92960. ** as little or as much as it wants. Except, if N is set to 0 then the
  92961. ** upper layers will never invoke the xFetch interfaces to the VFS.
  92962. */
  92963. case PragTyp_MMAP_SIZE: {
  92964. sqlite3_int64 sz;
  92965. #if SQLITE_MAX_MMAP_SIZE>0
  92966. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  92967. if( zRight ){
  92968. int ii;
  92969. sqlite3Atoi64(zRight, &sz, sqlite3Strlen30(zRight), SQLITE_UTF8);
  92970. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  92971. if( pId2->n==0 ) db->szMmap = sz;
  92972. for(ii=db->nDb-1; ii>=0; ii--){
  92973. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  92974. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  92975. }
  92976. }
  92977. }
  92978. sz = -1;
  92979. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  92980. #else
  92981. sz = 0;
  92982. rc = SQLITE_OK;
  92983. #endif
  92984. if( rc==SQLITE_OK ){
  92985. returnSingleInt(pParse, "mmap_size", sz);
  92986. }else if( rc!=SQLITE_NOTFOUND ){
  92987. pParse->nErr++;
  92988. pParse->rc = rc;
  92989. }
  92990. break;
  92991. }
  92992. /*
  92993. ** PRAGMA temp_store
  92994. ** PRAGMA temp_store = "default"|"memory"|"file"
  92995. **
  92996. ** Return or set the local value of the temp_store flag. Changing
  92997. ** the local value does not make changes to the disk file and the default
  92998. ** value will be restored the next time the database is opened.
  92999. **
  93000. ** Note that it is possible for the library compile-time options to
  93001. ** override this setting
  93002. */
  93003. case PragTyp_TEMP_STORE: {
  93004. if( !zRight ){
  93005. returnSingleInt(pParse, "temp_store", db->temp_store);
  93006. }else{
  93007. changeTempStorage(pParse, zRight);
  93008. }
  93009. break;
  93010. }
  93011. /*
  93012. ** PRAGMA temp_store_directory
  93013. ** PRAGMA temp_store_directory = ""|"directory_name"
  93014. **
  93015. ** Return or set the local value of the temp_store_directory flag. Changing
  93016. ** the value sets a specific directory to be used for temporary files.
  93017. ** Setting to a null string reverts to the default temporary directory search.
  93018. ** If temporary directory is changed, then invalidateTempStorage.
  93019. **
  93020. */
  93021. case PragTyp_TEMP_STORE_DIRECTORY: {
  93022. if( !zRight ){
  93023. if( sqlite3_temp_directory ){
  93024. sqlite3VdbeSetNumCols(v, 1);
  93025. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93026. "temp_store_directory", SQLITE_STATIC);
  93027. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  93028. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93029. }
  93030. }else{
  93031. #ifndef SQLITE_OMIT_WSD
  93032. if( zRight[0] ){
  93033. int res;
  93034. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  93035. if( rc!=SQLITE_OK || res==0 ){
  93036. sqlite3ErrorMsg(pParse, "not a writable directory");
  93037. goto pragma_out;
  93038. }
  93039. }
  93040. if( SQLITE_TEMP_STORE==0
  93041. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  93042. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  93043. ){
  93044. invalidateTempStorage(pParse);
  93045. }
  93046. sqlite3_free(sqlite3_temp_directory);
  93047. if( zRight[0] ){
  93048. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  93049. }else{
  93050. sqlite3_temp_directory = 0;
  93051. }
  93052. #endif /* SQLITE_OMIT_WSD */
  93053. }
  93054. break;
  93055. }
  93056. #if SQLITE_OS_WIN
  93057. /*
  93058. ** PRAGMA data_store_directory
  93059. ** PRAGMA data_store_directory = ""|"directory_name"
  93060. **
  93061. ** Return or set the local value of the data_store_directory flag. Changing
  93062. ** the value sets a specific directory to be used for database files that
  93063. ** were specified with a relative pathname. Setting to a null string reverts
  93064. ** to the default database directory, which for database files specified with
  93065. ** a relative path will probably be based on the current directory for the
  93066. ** process. Database file specified with an absolute path are not impacted
  93067. ** by this setting, regardless of its value.
  93068. **
  93069. */
  93070. case PragTyp_DATA_STORE_DIRECTORY: {
  93071. if( !zRight ){
  93072. if( sqlite3_data_directory ){
  93073. sqlite3VdbeSetNumCols(v, 1);
  93074. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93075. "data_store_directory", SQLITE_STATIC);
  93076. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  93077. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93078. }
  93079. }else{
  93080. #ifndef SQLITE_OMIT_WSD
  93081. if( zRight[0] ){
  93082. int res;
  93083. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  93084. if( rc!=SQLITE_OK || res==0 ){
  93085. sqlite3ErrorMsg(pParse, "not a writable directory");
  93086. goto pragma_out;
  93087. }
  93088. }
  93089. sqlite3_free(sqlite3_data_directory);
  93090. if( zRight[0] ){
  93091. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  93092. }else{
  93093. sqlite3_data_directory = 0;
  93094. }
  93095. #endif /* SQLITE_OMIT_WSD */
  93096. }
  93097. break;
  93098. }
  93099. #endif
  93100. #if SQLITE_ENABLE_LOCKING_STYLE
  93101. /*
  93102. ** PRAGMA [database.]lock_proxy_file
  93103. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  93104. **
  93105. ** Return or set the value of the lock_proxy_file flag. Changing
  93106. ** the value sets a specific file to be used for database access locks.
  93107. **
  93108. */
  93109. case PragTyp_LOCK_PROXY_FILE: {
  93110. if( !zRight ){
  93111. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  93112. char *proxy_file_path = NULL;
  93113. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  93114. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  93115. &proxy_file_path);
  93116. if( proxy_file_path ){
  93117. sqlite3VdbeSetNumCols(v, 1);
  93118. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  93119. "lock_proxy_file", SQLITE_STATIC);
  93120. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  93121. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93122. }
  93123. }else{
  93124. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  93125. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  93126. int res;
  93127. if( zRight[0] ){
  93128. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  93129. zRight);
  93130. } else {
  93131. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  93132. NULL);
  93133. }
  93134. if( res!=SQLITE_OK ){
  93135. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  93136. goto pragma_out;
  93137. }
  93138. }
  93139. break;
  93140. }
  93141. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  93142. /*
  93143. ** PRAGMA [database.]synchronous
  93144. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  93145. **
  93146. ** Return or set the local value of the synchronous flag. Changing
  93147. ** the local value does not make changes to the disk file and the
  93148. ** default value will be restored the next time the database is
  93149. ** opened.
  93150. */
  93151. case PragTyp_SYNCHRONOUS: {
  93152. if( !zRight ){
  93153. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  93154. }else{
  93155. if( !db->autoCommit ){
  93156. sqlite3ErrorMsg(pParse,
  93157. "Safety level may not be changed inside a transaction");
  93158. }else{
  93159. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  93160. setAllPagerFlags(db);
  93161. }
  93162. }
  93163. break;
  93164. }
  93165. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  93166. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  93167. case PragTyp_FLAG: {
  93168. if( zRight==0 ){
  93169. returnSingleInt(pParse, aPragmaNames[mid].zName,
  93170. (db->flags & aPragmaNames[mid].iArg)!=0 );
  93171. }else{
  93172. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  93173. if( db->autoCommit==0 ){
  93174. /* Foreign key support may not be enabled or disabled while not
  93175. ** in auto-commit mode. */
  93176. mask &= ~(SQLITE_ForeignKeys);
  93177. }
  93178. if( sqlite3GetBoolean(zRight, 0) ){
  93179. db->flags |= mask;
  93180. }else{
  93181. db->flags &= ~mask;
  93182. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  93183. }
  93184. /* Many of the flag-pragmas modify the code generated by the SQL
  93185. ** compiler (eg. count_changes). So add an opcode to expire all
  93186. ** compiled SQL statements after modifying a pragma value.
  93187. */
  93188. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  93189. setAllPagerFlags(db);
  93190. }
  93191. break;
  93192. }
  93193. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  93194. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  93195. /*
  93196. ** PRAGMA table_info(<table>)
  93197. **
  93198. ** Return a single row for each column of the named table. The columns of
  93199. ** the returned data set are:
  93200. **
  93201. ** cid: Column id (numbered from left to right, starting at 0)
  93202. ** name: Column name
  93203. ** type: Column declaration type.
  93204. ** notnull: True if 'NOT NULL' is part of column declaration
  93205. ** dflt_value: The default value for the column, if any.
  93206. */
  93207. case PragTyp_TABLE_INFO: if( zRight ){
  93208. Table *pTab;
  93209. pTab = sqlite3FindTable(db, zRight, zDb);
  93210. if( pTab ){
  93211. int i, k;
  93212. int nHidden = 0;
  93213. Column *pCol;
  93214. Index *pPk;
  93215. for(pPk=pTab->pIndex; pPk && pPk->autoIndex!=2; pPk=pPk->pNext){}
  93216. sqlite3VdbeSetNumCols(v, 6);
  93217. pParse->nMem = 6;
  93218. sqlite3CodeVerifySchema(pParse, iDb);
  93219. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  93220. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93221. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  93222. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  93223. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  93224. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  93225. sqlite3ViewGetColumnNames(pParse, pTab);
  93226. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  93227. if( IsHiddenColumn(pCol) ){
  93228. nHidden++;
  93229. continue;
  93230. }
  93231. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  93232. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  93233. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93234. pCol->zType ? pCol->zType : "", 0);
  93235. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  93236. if( pCol->zDflt ){
  93237. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  93238. }else{
  93239. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  93240. }
  93241. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  93242. k = 0;
  93243. }else if( pPk==0 ){
  93244. k = 1;
  93245. }else{
  93246. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  93247. }
  93248. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  93249. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  93250. }
  93251. }
  93252. }
  93253. break;
  93254. case PragTyp_STATS: {
  93255. Index *pIdx;
  93256. HashElem *i;
  93257. v = sqlite3GetVdbe(pParse);
  93258. sqlite3VdbeSetNumCols(v, 4);
  93259. pParse->nMem = 4;
  93260. sqlite3CodeVerifySchema(pParse, iDb);
  93261. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  93262. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  93263. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  93264. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  93265. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  93266. Table *pTab = sqliteHashData(i);
  93267. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  93268. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  93269. sqlite3VdbeAddOp2(v, OP_Integer,
  93270. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  93271. sqlite3VdbeAddOp2(v, OP_Integer, (int)pTab->nRowEst, 4);
  93272. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  93273. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93274. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  93275. sqlite3VdbeAddOp2(v, OP_Integer,
  93276. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  93277. sqlite3VdbeAddOp2(v, OP_Integer, (int)pIdx->aiRowEst[0], 4);
  93278. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  93279. }
  93280. }
  93281. }
  93282. break;
  93283. case PragTyp_INDEX_INFO: if( zRight ){
  93284. Index *pIdx;
  93285. Table *pTab;
  93286. pIdx = sqlite3FindIndex(db, zRight, zDb);
  93287. if( pIdx ){
  93288. int i;
  93289. pTab = pIdx->pTable;
  93290. sqlite3VdbeSetNumCols(v, 3);
  93291. pParse->nMem = 3;
  93292. sqlite3CodeVerifySchema(pParse, iDb);
  93293. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  93294. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  93295. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  93296. for(i=0; i<pIdx->nColumn; i++){
  93297. int cnum = pIdx->aiColumn[i];
  93298. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93299. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  93300. assert( pTab->nCol>cnum );
  93301. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  93302. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93303. }
  93304. }
  93305. }
  93306. break;
  93307. case PragTyp_INDEX_LIST: if( zRight ){
  93308. Index *pIdx;
  93309. Table *pTab;
  93310. int i;
  93311. pTab = sqlite3FindTable(db, zRight, zDb);
  93312. if( pTab ){
  93313. v = sqlite3GetVdbe(pParse);
  93314. sqlite3VdbeSetNumCols(v, 3);
  93315. pParse->nMem = 3;
  93316. sqlite3CodeVerifySchema(pParse, iDb);
  93317. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93318. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93319. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  93320. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  93321. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93322. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  93323. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
  93324. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93325. }
  93326. }
  93327. }
  93328. break;
  93329. case PragTyp_DATABASE_LIST: {
  93330. int i;
  93331. sqlite3VdbeSetNumCols(v, 3);
  93332. pParse->nMem = 3;
  93333. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93334. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93335. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  93336. for(i=0; i<db->nDb; i++){
  93337. if( db->aDb[i].pBt==0 ) continue;
  93338. assert( db->aDb[i].zName!=0 );
  93339. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93340. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  93341. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93342. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  93343. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93344. }
  93345. }
  93346. break;
  93347. case PragTyp_COLLATION_LIST: {
  93348. int i = 0;
  93349. HashElem *p;
  93350. sqlite3VdbeSetNumCols(v, 2);
  93351. pParse->nMem = 2;
  93352. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  93353. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  93354. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  93355. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  93356. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  93357. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  93358. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  93359. }
  93360. }
  93361. break;
  93362. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  93363. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93364. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  93365. FKey *pFK;
  93366. Table *pTab;
  93367. pTab = sqlite3FindTable(db, zRight, zDb);
  93368. if( pTab ){
  93369. v = sqlite3GetVdbe(pParse);
  93370. pFK = pTab->pFKey;
  93371. if( pFK ){
  93372. int i = 0;
  93373. sqlite3VdbeSetNumCols(v, 8);
  93374. pParse->nMem = 8;
  93375. sqlite3CodeVerifySchema(pParse, iDb);
  93376. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  93377. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  93378. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  93379. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  93380. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  93381. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  93382. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  93383. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  93384. while(pFK){
  93385. int j;
  93386. for(j=0; j<pFK->nCol; j++){
  93387. char *zCol = pFK->aCol[j].zCol;
  93388. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  93389. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  93390. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  93391. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  93392. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  93393. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  93394. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  93395. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  93396. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  93397. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  93398. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  93399. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  93400. }
  93401. ++i;
  93402. pFK = pFK->pNextFrom;
  93403. }
  93404. }
  93405. }
  93406. }
  93407. break;
  93408. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  93409. #ifndef SQLITE_OMIT_FOREIGN_KEY
  93410. #ifndef SQLITE_OMIT_TRIGGER
  93411. case PragTyp_FOREIGN_KEY_CHECK: {
  93412. FKey *pFK; /* A foreign key constraint */
  93413. Table *pTab; /* Child table contain "REFERENCES" keyword */
  93414. Table *pParent; /* Parent table that child points to */
  93415. Index *pIdx; /* Index in the parent table */
  93416. int i; /* Loop counter: Foreign key number for pTab */
  93417. int j; /* Loop counter: Field of the foreign key */
  93418. HashElem *k; /* Loop counter: Next table in schema */
  93419. int x; /* result variable */
  93420. int regResult; /* 3 registers to hold a result row */
  93421. int regKey; /* Register to hold key for checking the FK */
  93422. int regRow; /* Registers to hold a row from pTab */
  93423. int addrTop; /* Top of a loop checking foreign keys */
  93424. int addrOk; /* Jump here if the key is OK */
  93425. int *aiCols; /* child to parent column mapping */
  93426. regResult = pParse->nMem+1;
  93427. pParse->nMem += 4;
  93428. regKey = ++pParse->nMem;
  93429. regRow = ++pParse->nMem;
  93430. v = sqlite3GetVdbe(pParse);
  93431. sqlite3VdbeSetNumCols(v, 4);
  93432. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  93433. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  93434. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  93435. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  93436. sqlite3CodeVerifySchema(pParse, iDb);
  93437. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  93438. while( k ){
  93439. if( zRight ){
  93440. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  93441. k = 0;
  93442. }else{
  93443. pTab = (Table*)sqliteHashData(k);
  93444. k = sqliteHashNext(k);
  93445. }
  93446. if( pTab==0 || pTab->pFKey==0 ) continue;
  93447. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  93448. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  93449. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  93450. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  93451. P4_TRANSIENT);
  93452. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  93453. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  93454. if( pParent==0 ) continue;
  93455. pIdx = 0;
  93456. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  93457. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  93458. if( x==0 ){
  93459. if( pIdx==0 ){
  93460. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  93461. }else{
  93462. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  93463. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  93464. sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
  93465. }
  93466. }else{
  93467. k = 0;
  93468. break;
  93469. }
  93470. }
  93471. assert( pParse->nErr>0 || pFK==0 );
  93472. if( pFK ) break;
  93473. if( pParse->nTab<i ) pParse->nTab = i;
  93474. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0);
  93475. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  93476. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  93477. pIdx = 0;
  93478. aiCols = 0;
  93479. if( pParent ){
  93480. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  93481. assert( x==0 );
  93482. }
  93483. addrOk = sqlite3VdbeMakeLabel(v);
  93484. if( pParent && pIdx==0 ){
  93485. int iKey = pFK->aCol[0].iFrom;
  93486. assert( iKey>=0 && iKey<pTab->nCol );
  93487. if( iKey!=pTab->iPKey ){
  93488. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  93489. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  93490. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk);
  93491. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  93492. sqlite3VdbeCurrentAddr(v)+3);
  93493. }else{
  93494. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  93495. }
  93496. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow);
  93497. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  93498. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  93499. }else{
  93500. for(j=0; j<pFK->nCol; j++){
  93501. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  93502. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  93503. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk);
  93504. }
  93505. if( pParent ){
  93506. sqlite3VdbeAddOp3(v, OP_MakeRecord, regRow, pFK->nCol, regKey);
  93507. sqlite3VdbeChangeP4(v, -1,
  93508. sqlite3IndexAffinityStr(v,pIdx), P4_TRANSIENT);
  93509. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  93510. }
  93511. }
  93512. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  93513. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  93514. pFK->zTo, P4_TRANSIENT);
  93515. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  93516. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  93517. sqlite3VdbeResolveLabel(v, addrOk);
  93518. sqlite3DbFree(db, aiCols);
  93519. }
  93520. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1);
  93521. sqlite3VdbeJumpHere(v, addrTop);
  93522. }
  93523. }
  93524. break;
  93525. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  93526. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  93527. #ifndef NDEBUG
  93528. case PragTyp_PARSER_TRACE: {
  93529. if( zRight ){
  93530. if( sqlite3GetBoolean(zRight, 0) ){
  93531. sqlite3ParserTrace(stderr, "parser: ");
  93532. }else{
  93533. sqlite3ParserTrace(0, 0);
  93534. }
  93535. }
  93536. }
  93537. break;
  93538. #endif
  93539. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  93540. ** used will be case sensitive or not depending on the RHS.
  93541. */
  93542. case PragTyp_CASE_SENSITIVE_LIKE: {
  93543. if( zRight ){
  93544. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  93545. }
  93546. }
  93547. break;
  93548. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  93549. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  93550. #endif
  93551. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  93552. /* Pragma "quick_check" is reduced version of
  93553. ** integrity_check designed to detect most database corruption
  93554. ** without most of the overhead of a full integrity-check.
  93555. */
  93556. case PragTyp_INTEGRITY_CHECK: {
  93557. int i, j, addr, mxErr;
  93558. /* Code that appears at the end of the integrity check. If no error
  93559. ** messages have been generated, output OK. Otherwise output the
  93560. ** error message
  93561. */
  93562. static const VdbeOpList endCode[] = {
  93563. { OP_AddImm, 1, 0, 0}, /* 0 */
  93564. { OP_IfNeg, 1, 0, 0}, /* 1 */
  93565. { OP_String8, 0, 3, 0}, /* 2 */
  93566. { OP_ResultRow, 3, 1, 0},
  93567. };
  93568. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  93569. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  93570. ** then iDb is set to the index of the database identified by <db>.
  93571. ** In this case, the integrity of database iDb only is verified by
  93572. ** the VDBE created below.
  93573. **
  93574. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  93575. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  93576. ** to -1 here, to indicate that the VDBE should verify the integrity
  93577. ** of all attached databases. */
  93578. assert( iDb>=0 );
  93579. assert( iDb==0 || pId2->z );
  93580. if( pId2->z==0 ) iDb = -1;
  93581. /* Initialize the VDBE program */
  93582. pParse->nMem = 6;
  93583. sqlite3VdbeSetNumCols(v, 1);
  93584. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  93585. /* Set the maximum error count */
  93586. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  93587. if( zRight ){
  93588. sqlite3GetInt32(zRight, &mxErr);
  93589. if( mxErr<=0 ){
  93590. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  93591. }
  93592. }
  93593. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  93594. /* Do an integrity check on each database file */
  93595. for(i=0; i<db->nDb; i++){
  93596. HashElem *x;
  93597. Hash *pTbls;
  93598. int cnt = 0;
  93599. if( OMIT_TEMPDB && i==1 ) continue;
  93600. if( iDb>=0 && i!=iDb ) continue;
  93601. sqlite3CodeVerifySchema(pParse, i);
  93602. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  93603. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93604. sqlite3VdbeJumpHere(v, addr);
  93605. /* Do an integrity check of the B-Tree
  93606. **
  93607. ** Begin by filling registers 2, 3, ... with the root pages numbers
  93608. ** for all tables and indices in the database.
  93609. */
  93610. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  93611. pTbls = &db->aDb[i].pSchema->tblHash;
  93612. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  93613. Table *pTab = sqliteHashData(x);
  93614. Index *pIdx;
  93615. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  93616. cnt++;
  93617. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  93618. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  93619. cnt++;
  93620. }
  93621. }
  93622. /* Make sure sufficient number of registers have been allocated */
  93623. pParse->nMem = MAX( pParse->nMem, cnt+7 );
  93624. /* Do the b-tree integrity checks */
  93625. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  93626. sqlite3VdbeChangeP5(v, (u8)i);
  93627. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
  93628. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  93629. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  93630. P4_DYNAMIC);
  93631. sqlite3VdbeAddOp2(v, OP_Move, 2, 4);
  93632. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  93633. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  93634. sqlite3VdbeJumpHere(v, addr);
  93635. /* Make sure all the indices are constructed correctly.
  93636. */
  93637. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  93638. Table *pTab = sqliteHashData(x);
  93639. Index *pIdx;
  93640. int loopTop;
  93641. if( pTab->pIndex==0 ) continue;
  93642. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  93643. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93644. sqlite3VdbeJumpHere(v, addr);
  93645. sqlite3ExprCacheClear(pParse);
  93646. sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
  93647. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93648. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7+j); /* index entries counter */
  93649. }
  93650. pParse->nMem = MAX(pParse->nMem, 7+j);
  93651. loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0) + 1;
  93652. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93653. int jmp2, jmp3;
  93654. int r1;
  93655. static const VdbeOpList idxErr[] = {
  93656. { OP_AddImm, 1, -1, 0},
  93657. { OP_String8, 0, 3, 0}, /* 1 */
  93658. { OP_Rowid, 1, 4, 0},
  93659. { OP_String8, 0, 5, 0}, /* 3 */
  93660. { OP_String8, 0, 6, 0}, /* 4 */
  93661. { OP_Concat, 4, 3, 3},
  93662. { OP_Concat, 5, 3, 3},
  93663. { OP_Concat, 6, 3, 3},
  93664. { OP_ResultRow, 3, 1, 0},
  93665. { OP_IfPos, 1, 0, 0}, /* 9 */
  93666. { OP_Halt, 0, 0, 0},
  93667. };
  93668. r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0, &jmp3);
  93669. sqlite3VdbeAddOp2(v, OP_AddImm, 7+j, 1); /* increment entry count */
  93670. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
  93671. addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
  93672. sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
  93673. sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
  93674. sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_TRANSIENT);
  93675. sqlite3VdbeJumpHere(v, addr+9);
  93676. sqlite3VdbeJumpHere(v, jmp2);
  93677. sqlite3VdbeResolveLabel(v, jmp3);
  93678. }
  93679. sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop);
  93680. sqlite3VdbeJumpHere(v, loopTop-1);
  93681. #ifndef SQLITE_OMIT_BTREECOUNT
  93682. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  93683. "wrong # of entries in index ", P4_STATIC);
  93684. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  93685. addr = sqlite3VdbeCurrentAddr(v);
  93686. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2);
  93687. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  93688. sqlite3VdbeAddOp2(v, OP_Count, j+2, 3);
  93689. sqlite3VdbeAddOp3(v, OP_Eq, 7+j, addr+8, 3);
  93690. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  93691. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  93692. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  93693. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  93694. }
  93695. #endif /* SQLITE_OMIT_BTREECOUNT */
  93696. }
  93697. }
  93698. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
  93699. sqlite3VdbeChangeP2(v, addr, -mxErr);
  93700. sqlite3VdbeJumpHere(v, addr+1);
  93701. sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
  93702. }
  93703. break;
  93704. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  93705. #ifndef SQLITE_OMIT_UTF16
  93706. /*
  93707. ** PRAGMA encoding
  93708. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  93709. **
  93710. ** In its first form, this pragma returns the encoding of the main
  93711. ** database. If the database is not initialized, it is initialized now.
  93712. **
  93713. ** The second form of this pragma is a no-op if the main database file
  93714. ** has not already been initialized. In this case it sets the default
  93715. ** encoding that will be used for the main database file if a new file
  93716. ** is created. If an existing main database file is opened, then the
  93717. ** default text encoding for the existing database is used.
  93718. **
  93719. ** In all cases new databases created using the ATTACH command are
  93720. ** created to use the same default text encoding as the main database. If
  93721. ** the main database has not been initialized and/or created when ATTACH
  93722. ** is executed, this is done before the ATTACH operation.
  93723. **
  93724. ** In the second form this pragma sets the text encoding to be used in
  93725. ** new database files created using this database handle. It is only
  93726. ** useful if invoked immediately after the main database i
  93727. */
  93728. case PragTyp_ENCODING: {
  93729. static const struct EncName {
  93730. char *zName;
  93731. u8 enc;
  93732. } encnames[] = {
  93733. { "UTF8", SQLITE_UTF8 },
  93734. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  93735. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  93736. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  93737. { "UTF16le", SQLITE_UTF16LE },
  93738. { "UTF16be", SQLITE_UTF16BE },
  93739. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  93740. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  93741. { 0, 0 }
  93742. };
  93743. const struct EncName *pEnc;
  93744. if( !zRight ){ /* "PRAGMA encoding" */
  93745. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  93746. sqlite3VdbeSetNumCols(v, 1);
  93747. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  93748. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  93749. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  93750. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  93751. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  93752. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  93753. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93754. }else{ /* "PRAGMA encoding = XXX" */
  93755. /* Only change the value of sqlite.enc if the database handle is not
  93756. ** initialized. If the main database exists, the new sqlite.enc value
  93757. ** will be overwritten when the schema is next loaded. If it does not
  93758. ** already exists, it will be created to use the new encoding value.
  93759. */
  93760. if(
  93761. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  93762. DbHasProperty(db, 0, DB_Empty)
  93763. ){
  93764. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  93765. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  93766. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  93767. break;
  93768. }
  93769. }
  93770. if( !pEnc->zName ){
  93771. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  93772. }
  93773. }
  93774. }
  93775. }
  93776. break;
  93777. #endif /* SQLITE_OMIT_UTF16 */
  93778. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  93779. /*
  93780. ** PRAGMA [database.]schema_version
  93781. ** PRAGMA [database.]schema_version = <integer>
  93782. **
  93783. ** PRAGMA [database.]user_version
  93784. ** PRAGMA [database.]user_version = <integer>
  93785. **
  93786. ** PRAGMA [database.]freelist_count = <integer>
  93787. **
  93788. ** PRAGMA [database.]application_id
  93789. ** PRAGMA [database.]application_id = <integer>
  93790. **
  93791. ** The pragma's schema_version and user_version are used to set or get
  93792. ** the value of the schema-version and user-version, respectively. Both
  93793. ** the schema-version and the user-version are 32-bit signed integers
  93794. ** stored in the database header.
  93795. **
  93796. ** The schema-cookie is usually only manipulated internally by SQLite. It
  93797. ** is incremented by SQLite whenever the database schema is modified (by
  93798. ** creating or dropping a table or index). The schema version is used by
  93799. ** SQLite each time a query is executed to ensure that the internal cache
  93800. ** of the schema used when compiling the SQL query matches the schema of
  93801. ** the database against which the compiled query is actually executed.
  93802. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  93803. ** the schema-version is potentially dangerous and may lead to program
  93804. ** crashes or database corruption. Use with caution!
  93805. **
  93806. ** The user-version is not used internally by SQLite. It may be used by
  93807. ** applications for any purpose.
  93808. */
  93809. case PragTyp_HEADER_VALUE: {
  93810. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  93811. sqlite3VdbeUsesBtree(v, iDb);
  93812. switch( zLeft[0] ){
  93813. case 'a': case 'A':
  93814. iCookie = BTREE_APPLICATION_ID;
  93815. break;
  93816. case 'f': case 'F':
  93817. iCookie = BTREE_FREE_PAGE_COUNT;
  93818. break;
  93819. case 's': case 'S':
  93820. iCookie = BTREE_SCHEMA_VERSION;
  93821. break;
  93822. default:
  93823. iCookie = BTREE_USER_VERSION;
  93824. break;
  93825. }
  93826. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  93827. /* Write the specified cookie value */
  93828. static const VdbeOpList setCookie[] = {
  93829. { OP_Transaction, 0, 1, 0}, /* 0 */
  93830. { OP_Integer, 0, 1, 0}, /* 1 */
  93831. { OP_SetCookie, 0, 0, 1}, /* 2 */
  93832. };
  93833. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
  93834. sqlite3VdbeChangeP1(v, addr, iDb);
  93835. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  93836. sqlite3VdbeChangeP1(v, addr+2, iDb);
  93837. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  93838. }else{
  93839. /* Read the specified cookie value */
  93840. static const VdbeOpList readCookie[] = {
  93841. { OP_Transaction, 0, 0, 0}, /* 0 */
  93842. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  93843. { OP_ResultRow, 1, 1, 0}
  93844. };
  93845. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
  93846. sqlite3VdbeChangeP1(v, addr, iDb);
  93847. sqlite3VdbeChangeP1(v, addr+1, iDb);
  93848. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  93849. sqlite3VdbeSetNumCols(v, 1);
  93850. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  93851. }
  93852. }
  93853. break;
  93854. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  93855. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93856. /*
  93857. ** PRAGMA compile_options
  93858. **
  93859. ** Return the names of all compile-time options used in this build,
  93860. ** one option per row.
  93861. */
  93862. case PragTyp_COMPILE_OPTIONS: {
  93863. int i = 0;
  93864. const char *zOpt;
  93865. sqlite3VdbeSetNumCols(v, 1);
  93866. pParse->nMem = 1;
  93867. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  93868. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  93869. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  93870. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  93871. }
  93872. }
  93873. break;
  93874. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  93875. #ifndef SQLITE_OMIT_WAL
  93876. /*
  93877. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  93878. **
  93879. ** Checkpoint the database.
  93880. */
  93881. case PragTyp_WAL_CHECKPOINT: {
  93882. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  93883. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  93884. if( zRight ){
  93885. if( sqlite3StrICmp(zRight, "full")==0 ){
  93886. eMode = SQLITE_CHECKPOINT_FULL;
  93887. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  93888. eMode = SQLITE_CHECKPOINT_RESTART;
  93889. }
  93890. }
  93891. sqlite3VdbeSetNumCols(v, 3);
  93892. pParse->nMem = 3;
  93893. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  93894. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  93895. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  93896. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  93897. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  93898. }
  93899. break;
  93900. /*
  93901. ** PRAGMA wal_autocheckpoint
  93902. ** PRAGMA wal_autocheckpoint = N
  93903. **
  93904. ** Configure a database connection to automatically checkpoint a database
  93905. ** after accumulating N frames in the log. Or query for the current value
  93906. ** of N.
  93907. */
  93908. case PragTyp_WAL_AUTOCHECKPOINT: {
  93909. if( zRight ){
  93910. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  93911. }
  93912. returnSingleInt(pParse, "wal_autocheckpoint",
  93913. db->xWalCallback==sqlite3WalDefaultHook ?
  93914. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  93915. }
  93916. break;
  93917. #endif
  93918. /*
  93919. ** PRAGMA shrink_memory
  93920. **
  93921. ** This pragma attempts to free as much memory as possible from the
  93922. ** current database connection.
  93923. */
  93924. case PragTyp_SHRINK_MEMORY: {
  93925. sqlite3_db_release_memory(db);
  93926. break;
  93927. }
  93928. /*
  93929. ** PRAGMA busy_timeout
  93930. ** PRAGMA busy_timeout = N
  93931. **
  93932. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  93933. ** if one is set. If no busy handler or a different busy handler is set
  93934. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  93935. ** disables the timeout.
  93936. */
  93937. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  93938. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  93939. if( zRight ){
  93940. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  93941. }
  93942. returnSingleInt(pParse, "timeout", db->busyTimeout);
  93943. break;
  93944. }
  93945. /*
  93946. ** PRAGMA soft_heap_limit
  93947. ** PRAGMA soft_heap_limit = N
  93948. **
  93949. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  93950. ** use -1.
  93951. */
  93952. case PragTyp_SOFT_HEAP_LIMIT: {
  93953. sqlite3_int64 N;
  93954. if( zRight && sqlite3Atoi64(zRight, &N, 1000000, SQLITE_UTF8)==SQLITE_OK ){
  93955. sqlite3_soft_heap_limit64(N);
  93956. }
  93957. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  93958. break;
  93959. }
  93960. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  93961. /*
  93962. ** Report the current state of file logs for all databases
  93963. */
  93964. case PragTyp_LOCK_STATUS: {
  93965. static const char *const azLockName[] = {
  93966. "unlocked", "shared", "reserved", "pending", "exclusive"
  93967. };
  93968. int i;
  93969. sqlite3VdbeSetNumCols(v, 2);
  93970. pParse->nMem = 2;
  93971. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  93972. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  93973. for(i=0; i<db->nDb; i++){
  93974. Btree *pBt;
  93975. const char *zState = "unknown";
  93976. int j;
  93977. if( db->aDb[i].zName==0 ) continue;
  93978. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  93979. pBt = db->aDb[i].pBt;
  93980. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  93981. zState = "closed";
  93982. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  93983. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  93984. zState = azLockName[j];
  93985. }
  93986. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  93987. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  93988. }
  93989. break;
  93990. }
  93991. #endif
  93992. #ifdef SQLITE_HAS_CODEC
  93993. case PragTyp_KEY: {
  93994. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  93995. break;
  93996. }
  93997. case PragTyp_REKEY: {
  93998. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  93999. break;
  94000. }
  94001. case PragTyp_HEXKEY: {
  94002. if( zRight ){
  94003. u8 iByte;
  94004. int i;
  94005. char zKey[40];
  94006. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  94007. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  94008. if( (i&1)!=0 ) zKey[i/2] = iByte;
  94009. }
  94010. if( (zLeft[3] & 0xf)==0xb ){
  94011. sqlite3_key_v2(db, zDb, zKey, i/2);
  94012. }else{
  94013. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  94014. }
  94015. }
  94016. break;
  94017. }
  94018. #endif
  94019. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  94020. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  94021. #ifdef SQLITE_HAS_CODEC
  94022. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  94023. sqlite3_activate_see(&zRight[4]);
  94024. }
  94025. #endif
  94026. #ifdef SQLITE_ENABLE_CEROD
  94027. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  94028. sqlite3_activate_cerod(&zRight[6]);
  94029. }
  94030. #endif
  94031. }
  94032. break;
  94033. #endif
  94034. } /* End of the PRAGMA switch */
  94035. pragma_out:
  94036. sqlite3DbFree(db, zLeft);
  94037. sqlite3DbFree(db, zRight);
  94038. }
  94039. #endif /* SQLITE_OMIT_PRAGMA */
  94040. /************** End of pragma.c **********************************************/
  94041. /************** Begin file prepare.c *****************************************/
  94042. /*
  94043. ** 2005 May 25
  94044. **
  94045. ** The author disclaims copyright to this source code. In place of
  94046. ** a legal notice, here is a blessing:
  94047. **
  94048. ** May you do good and not evil.
  94049. ** May you find forgiveness for yourself and forgive others.
  94050. ** May you share freely, never taking more than you give.
  94051. **
  94052. *************************************************************************
  94053. ** This file contains the implementation of the sqlite3_prepare()
  94054. ** interface, and routines that contribute to loading the database schema
  94055. ** from disk.
  94056. */
  94057. /*
  94058. ** Fill the InitData structure with an error message that indicates
  94059. ** that the database is corrupt.
  94060. */
  94061. static void corruptSchema(
  94062. InitData *pData, /* Initialization context */
  94063. const char *zObj, /* Object being parsed at the point of error */
  94064. const char *zExtra /* Error information */
  94065. ){
  94066. sqlite3 *db = pData->db;
  94067. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  94068. if( zObj==0 ) zObj = "?";
  94069. sqlite3SetString(pData->pzErrMsg, db,
  94070. "malformed database schema (%s)", zObj);
  94071. if( zExtra ){
  94072. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  94073. "%s - %s", *pData->pzErrMsg, zExtra);
  94074. }
  94075. }
  94076. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  94077. }
  94078. /*
  94079. ** This is the callback routine for the code that initializes the
  94080. ** database. See sqlite3Init() below for additional information.
  94081. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  94082. **
  94083. ** Each callback contains the following information:
  94084. **
  94085. ** argv[0] = name of thing being created
  94086. ** argv[1] = root page number for table or index. 0 for trigger or view.
  94087. ** argv[2] = SQL text for the CREATE statement.
  94088. **
  94089. */
  94090. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  94091. InitData *pData = (InitData*)pInit;
  94092. sqlite3 *db = pData->db;
  94093. int iDb = pData->iDb;
  94094. assert( argc==3 );
  94095. UNUSED_PARAMETER2(NotUsed, argc);
  94096. assert( sqlite3_mutex_held(db->mutex) );
  94097. DbClearProperty(db, iDb, DB_Empty);
  94098. if( db->mallocFailed ){
  94099. corruptSchema(pData, argv[0], 0);
  94100. return 1;
  94101. }
  94102. assert( iDb>=0 && iDb<db->nDb );
  94103. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  94104. if( argv[1]==0 ){
  94105. corruptSchema(pData, argv[0], 0);
  94106. }else if( argv[2] && argv[2][0] ){
  94107. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  94108. ** But because db->init.busy is set to 1, no VDBE code is generated
  94109. ** or executed. All the parser does is build the internal data
  94110. ** structures that describe the table, index, or view.
  94111. */
  94112. int rc;
  94113. sqlite3_stmt *pStmt;
  94114. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  94115. assert( db->init.busy );
  94116. db->init.iDb = iDb;
  94117. db->init.newTnum = sqlite3Atoi(argv[1]);
  94118. db->init.orphanTrigger = 0;
  94119. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  94120. rc = db->errCode;
  94121. assert( (rc&0xFF)==(rcp&0xFF) );
  94122. db->init.iDb = 0;
  94123. if( SQLITE_OK!=rc ){
  94124. if( db->init.orphanTrigger ){
  94125. assert( iDb==1 );
  94126. }else{
  94127. pData->rc = rc;
  94128. if( rc==SQLITE_NOMEM ){
  94129. db->mallocFailed = 1;
  94130. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  94131. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  94132. }
  94133. }
  94134. }
  94135. sqlite3_finalize(pStmt);
  94136. }else if( argv[0]==0 ){
  94137. corruptSchema(pData, 0, 0);
  94138. }else{
  94139. /* If the SQL column is blank it means this is an index that
  94140. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  94141. ** constraint for a CREATE TABLE. The index should have already
  94142. ** been created when we processed the CREATE TABLE. All we have
  94143. ** to do here is record the root page number for that index.
  94144. */
  94145. Index *pIndex;
  94146. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  94147. if( pIndex==0 ){
  94148. /* This can occur if there exists an index on a TEMP table which
  94149. ** has the same name as another index on a permanent index. Since
  94150. ** the permanent table is hidden by the TEMP table, we can also
  94151. ** safely ignore the index on the permanent table.
  94152. */
  94153. /* Do Nothing */;
  94154. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  94155. corruptSchema(pData, argv[0], "invalid rootpage");
  94156. }
  94157. }
  94158. return 0;
  94159. }
  94160. /*
  94161. ** Attempt to read the database schema and initialize internal
  94162. ** data structures for a single database file. The index of the
  94163. ** database file is given by iDb. iDb==0 is used for the main
  94164. ** database. iDb==1 should never be used. iDb>=2 is used for
  94165. ** auxiliary databases. Return one of the SQLITE_ error codes to
  94166. ** indicate success or failure.
  94167. */
  94168. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  94169. int rc;
  94170. int i;
  94171. #ifndef SQLITE_OMIT_DEPRECATED
  94172. int size;
  94173. #endif
  94174. Table *pTab;
  94175. Db *pDb;
  94176. char const *azArg[4];
  94177. int meta[5];
  94178. InitData initData;
  94179. char const *zMasterSchema;
  94180. char const *zMasterName;
  94181. int openedTransaction = 0;
  94182. /*
  94183. ** The master database table has a structure like this
  94184. */
  94185. static const char master_schema[] =
  94186. "CREATE TABLE sqlite_master(\n"
  94187. " type text,\n"
  94188. " name text,\n"
  94189. " tbl_name text,\n"
  94190. " rootpage integer,\n"
  94191. " sql text\n"
  94192. ")"
  94193. ;
  94194. #ifndef SQLITE_OMIT_TEMPDB
  94195. static const char temp_master_schema[] =
  94196. "CREATE TEMP TABLE sqlite_temp_master(\n"
  94197. " type text,\n"
  94198. " name text,\n"
  94199. " tbl_name text,\n"
  94200. " rootpage integer,\n"
  94201. " sql text\n"
  94202. ")"
  94203. ;
  94204. #else
  94205. #define temp_master_schema 0
  94206. #endif
  94207. assert( iDb>=0 && iDb<db->nDb );
  94208. assert( db->aDb[iDb].pSchema );
  94209. assert( sqlite3_mutex_held(db->mutex) );
  94210. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  94211. /* zMasterSchema and zInitScript are set to point at the master schema
  94212. ** and initialisation script appropriate for the database being
  94213. ** initialized. zMasterName is the name of the master table.
  94214. */
  94215. if( !OMIT_TEMPDB && iDb==1 ){
  94216. zMasterSchema = temp_master_schema;
  94217. }else{
  94218. zMasterSchema = master_schema;
  94219. }
  94220. zMasterName = SCHEMA_TABLE(iDb);
  94221. /* Construct the schema tables. */
  94222. azArg[0] = zMasterName;
  94223. azArg[1] = "1";
  94224. azArg[2] = zMasterSchema;
  94225. azArg[3] = 0;
  94226. initData.db = db;
  94227. initData.iDb = iDb;
  94228. initData.rc = SQLITE_OK;
  94229. initData.pzErrMsg = pzErrMsg;
  94230. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  94231. if( initData.rc ){
  94232. rc = initData.rc;
  94233. goto error_out;
  94234. }
  94235. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  94236. if( ALWAYS(pTab) ){
  94237. pTab->tabFlags |= TF_Readonly;
  94238. }
  94239. /* Create a cursor to hold the database open
  94240. */
  94241. pDb = &db->aDb[iDb];
  94242. if( pDb->pBt==0 ){
  94243. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  94244. DbSetProperty(db, 1, DB_SchemaLoaded);
  94245. }
  94246. return SQLITE_OK;
  94247. }
  94248. /* If there is not already a read-only (or read-write) transaction opened
  94249. ** on the b-tree database, open one now. If a transaction is opened, it
  94250. ** will be closed before this function returns. */
  94251. sqlite3BtreeEnter(pDb->pBt);
  94252. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  94253. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  94254. if( rc!=SQLITE_OK ){
  94255. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  94256. goto initone_error_out;
  94257. }
  94258. openedTransaction = 1;
  94259. }
  94260. /* Get the database meta information.
  94261. **
  94262. ** Meta values are as follows:
  94263. ** meta[0] Schema cookie. Changes with each schema change.
  94264. ** meta[1] File format of schema layer.
  94265. ** meta[2] Size of the page cache.
  94266. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  94267. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  94268. ** meta[5] User version
  94269. ** meta[6] Incremental vacuum mode
  94270. ** meta[7] unused
  94271. ** meta[8] unused
  94272. ** meta[9] unused
  94273. **
  94274. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  94275. ** the possible values of meta[4].
  94276. */
  94277. for(i=0; i<ArraySize(meta); i++){
  94278. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  94279. }
  94280. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  94281. /* If opening a non-empty database, check the text encoding. For the
  94282. ** main database, set sqlite3.enc to the encoding of the main database.
  94283. ** For an attached db, it is an error if the encoding is not the same
  94284. ** as sqlite3.enc.
  94285. */
  94286. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  94287. if( iDb==0 ){
  94288. #ifndef SQLITE_OMIT_UTF16
  94289. u8 encoding;
  94290. /* If opening the main database, set ENC(db). */
  94291. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  94292. if( encoding==0 ) encoding = SQLITE_UTF8;
  94293. ENC(db) = encoding;
  94294. #else
  94295. ENC(db) = SQLITE_UTF8;
  94296. #endif
  94297. }else{
  94298. /* If opening an attached database, the encoding much match ENC(db) */
  94299. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  94300. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  94301. " text encoding as main database");
  94302. rc = SQLITE_ERROR;
  94303. goto initone_error_out;
  94304. }
  94305. }
  94306. }else{
  94307. DbSetProperty(db, iDb, DB_Empty);
  94308. }
  94309. pDb->pSchema->enc = ENC(db);
  94310. if( pDb->pSchema->cache_size==0 ){
  94311. #ifndef SQLITE_OMIT_DEPRECATED
  94312. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  94313. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  94314. pDb->pSchema->cache_size = size;
  94315. #else
  94316. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  94317. #endif
  94318. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  94319. }
  94320. /*
  94321. ** file_format==1 Version 3.0.0.
  94322. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  94323. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  94324. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  94325. */
  94326. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  94327. if( pDb->pSchema->file_format==0 ){
  94328. pDb->pSchema->file_format = 1;
  94329. }
  94330. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  94331. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  94332. rc = SQLITE_ERROR;
  94333. goto initone_error_out;
  94334. }
  94335. /* Ticket #2804: When we open a database in the newer file format,
  94336. ** clear the legacy_file_format pragma flag so that a VACUUM will
  94337. ** not downgrade the database and thus invalidate any descending
  94338. ** indices that the user might have created.
  94339. */
  94340. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  94341. db->flags &= ~SQLITE_LegacyFileFmt;
  94342. }
  94343. /* Read the schema information out of the schema tables
  94344. */
  94345. assert( db->init.busy );
  94346. {
  94347. char *zSql;
  94348. zSql = sqlite3MPrintf(db,
  94349. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  94350. db->aDb[iDb].zName, zMasterName);
  94351. #ifndef SQLITE_OMIT_AUTHORIZATION
  94352. {
  94353. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  94354. xAuth = db->xAuth;
  94355. db->xAuth = 0;
  94356. #endif
  94357. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  94358. #ifndef SQLITE_OMIT_AUTHORIZATION
  94359. db->xAuth = xAuth;
  94360. }
  94361. #endif
  94362. if( rc==SQLITE_OK ) rc = initData.rc;
  94363. sqlite3DbFree(db, zSql);
  94364. #ifndef SQLITE_OMIT_ANALYZE
  94365. if( rc==SQLITE_OK ){
  94366. sqlite3AnalysisLoad(db, iDb);
  94367. }
  94368. #endif
  94369. }
  94370. if( db->mallocFailed ){
  94371. rc = SQLITE_NOMEM;
  94372. sqlite3ResetAllSchemasOfConnection(db);
  94373. }
  94374. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  94375. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  94376. ** the schema loaded, even if errors occurred. In this situation the
  94377. ** current sqlite3_prepare() operation will fail, but the following one
  94378. ** will attempt to compile the supplied statement against whatever subset
  94379. ** of the schema was loaded before the error occurred. The primary
  94380. ** purpose of this is to allow access to the sqlite_master table
  94381. ** even when its contents have been corrupted.
  94382. */
  94383. DbSetProperty(db, iDb, DB_SchemaLoaded);
  94384. rc = SQLITE_OK;
  94385. }
  94386. /* Jump here for an error that occurs after successfully allocating
  94387. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  94388. ** before that point, jump to error_out.
  94389. */
  94390. initone_error_out:
  94391. if( openedTransaction ){
  94392. sqlite3BtreeCommit(pDb->pBt);
  94393. }
  94394. sqlite3BtreeLeave(pDb->pBt);
  94395. error_out:
  94396. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  94397. db->mallocFailed = 1;
  94398. }
  94399. return rc;
  94400. }
  94401. /*
  94402. ** Initialize all database files - the main database file, the file
  94403. ** used to store temporary tables, and any additional database files
  94404. ** created using ATTACH statements. Return a success code. If an
  94405. ** error occurs, write an error message into *pzErrMsg.
  94406. **
  94407. ** After a database is initialized, the DB_SchemaLoaded bit is set
  94408. ** bit is set in the flags field of the Db structure. If the database
  94409. ** file was of zero-length, then the DB_Empty flag is also set.
  94410. */
  94411. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  94412. int i, rc;
  94413. int commit_internal = !(db->flags&SQLITE_InternChanges);
  94414. assert( sqlite3_mutex_held(db->mutex) );
  94415. rc = SQLITE_OK;
  94416. db->init.busy = 1;
  94417. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  94418. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  94419. rc = sqlite3InitOne(db, i, pzErrMsg);
  94420. if( rc ){
  94421. sqlite3ResetOneSchema(db, i);
  94422. }
  94423. }
  94424. /* Once all the other databases have been initialized, load the schema
  94425. ** for the TEMP database. This is loaded last, as the TEMP database
  94426. ** schema may contain references to objects in other databases.
  94427. */
  94428. #ifndef SQLITE_OMIT_TEMPDB
  94429. if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
  94430. && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  94431. rc = sqlite3InitOne(db, 1, pzErrMsg);
  94432. if( rc ){
  94433. sqlite3ResetOneSchema(db, 1);
  94434. }
  94435. }
  94436. #endif
  94437. db->init.busy = 0;
  94438. if( rc==SQLITE_OK && commit_internal ){
  94439. sqlite3CommitInternalChanges(db);
  94440. }
  94441. return rc;
  94442. }
  94443. /*
  94444. ** This routine is a no-op if the database schema is already initialized.
  94445. ** Otherwise, the schema is loaded. An error code is returned.
  94446. */
  94447. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  94448. int rc = SQLITE_OK;
  94449. sqlite3 *db = pParse->db;
  94450. assert( sqlite3_mutex_held(db->mutex) );
  94451. if( !db->init.busy ){
  94452. rc = sqlite3Init(db, &pParse->zErrMsg);
  94453. }
  94454. if( rc!=SQLITE_OK ){
  94455. pParse->rc = rc;
  94456. pParse->nErr++;
  94457. }
  94458. return rc;
  94459. }
  94460. /*
  94461. ** Check schema cookies in all databases. If any cookie is out
  94462. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  94463. ** make no changes to pParse->rc.
  94464. */
  94465. static void schemaIsValid(Parse *pParse){
  94466. sqlite3 *db = pParse->db;
  94467. int iDb;
  94468. int rc;
  94469. int cookie;
  94470. assert( pParse->checkSchema );
  94471. assert( sqlite3_mutex_held(db->mutex) );
  94472. for(iDb=0; iDb<db->nDb; iDb++){
  94473. int openedTransaction = 0; /* True if a transaction is opened */
  94474. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  94475. if( pBt==0 ) continue;
  94476. /* If there is not already a read-only (or read-write) transaction opened
  94477. ** on the b-tree database, open one now. If a transaction is opened, it
  94478. ** will be closed immediately after reading the meta-value. */
  94479. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  94480. rc = sqlite3BtreeBeginTrans(pBt, 0);
  94481. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  94482. db->mallocFailed = 1;
  94483. }
  94484. if( rc!=SQLITE_OK ) return;
  94485. openedTransaction = 1;
  94486. }
  94487. /* Read the schema cookie from the database. If it does not match the
  94488. ** value stored as part of the in-memory schema representation,
  94489. ** set Parse.rc to SQLITE_SCHEMA. */
  94490. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  94491. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  94492. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  94493. sqlite3ResetOneSchema(db, iDb);
  94494. pParse->rc = SQLITE_SCHEMA;
  94495. }
  94496. /* Close the transaction, if one was opened. */
  94497. if( openedTransaction ){
  94498. sqlite3BtreeCommit(pBt);
  94499. }
  94500. }
  94501. }
  94502. /*
  94503. ** Convert a schema pointer into the iDb index that indicates
  94504. ** which database file in db->aDb[] the schema refers to.
  94505. **
  94506. ** If the same database is attached more than once, the first
  94507. ** attached database is returned.
  94508. */
  94509. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  94510. int i = -1000000;
  94511. /* If pSchema is NULL, then return -1000000. This happens when code in
  94512. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  94513. ** created by a sub-select). In this case the return value of this
  94514. ** function should never be used.
  94515. **
  94516. ** We return -1000000 instead of the more usual -1 simply because using
  94517. ** -1000000 as the incorrect index into db->aDb[] is much
  94518. ** more likely to cause a segfault than -1 (of course there are assert()
  94519. ** statements too, but it never hurts to play the odds).
  94520. */
  94521. assert( sqlite3_mutex_held(db->mutex) );
  94522. if( pSchema ){
  94523. for(i=0; ALWAYS(i<db->nDb); i++){
  94524. if( db->aDb[i].pSchema==pSchema ){
  94525. break;
  94526. }
  94527. }
  94528. assert( i>=0 && i<db->nDb );
  94529. }
  94530. return i;
  94531. }
  94532. /*
  94533. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  94534. */
  94535. static int sqlite3Prepare(
  94536. sqlite3 *db, /* Database handle. */
  94537. const char *zSql, /* UTF-8 encoded SQL statement. */
  94538. int nBytes, /* Length of zSql in bytes. */
  94539. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  94540. Vdbe *pReprepare, /* VM being reprepared */
  94541. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94542. const char **pzTail /* OUT: End of parsed string */
  94543. ){
  94544. Parse *pParse; /* Parsing context */
  94545. char *zErrMsg = 0; /* Error message */
  94546. int rc = SQLITE_OK; /* Result code */
  94547. int i; /* Loop counter */
  94548. /* Allocate the parsing context */
  94549. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  94550. if( pParse==0 ){
  94551. rc = SQLITE_NOMEM;
  94552. goto end_prepare;
  94553. }
  94554. pParse->pReprepare = pReprepare;
  94555. assert( ppStmt && *ppStmt==0 );
  94556. assert( !db->mallocFailed );
  94557. assert( sqlite3_mutex_held(db->mutex) );
  94558. /* Check to verify that it is possible to get a read lock on all
  94559. ** database schemas. The inability to get a read lock indicates that
  94560. ** some other database connection is holding a write-lock, which in
  94561. ** turn means that the other connection has made uncommitted changes
  94562. ** to the schema.
  94563. **
  94564. ** Were we to proceed and prepare the statement against the uncommitted
  94565. ** schema changes and if those schema changes are subsequently rolled
  94566. ** back and different changes are made in their place, then when this
  94567. ** prepared statement goes to run the schema cookie would fail to detect
  94568. ** the schema change. Disaster would follow.
  94569. **
  94570. ** This thread is currently holding mutexes on all Btrees (because
  94571. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  94572. ** is not possible for another thread to start a new schema change
  94573. ** while this routine is running. Hence, we do not need to hold
  94574. ** locks on the schema, we just need to make sure nobody else is
  94575. ** holding them.
  94576. **
  94577. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  94578. ** but it does *not* override schema lock detection, so this all still
  94579. ** works even if READ_UNCOMMITTED is set.
  94580. */
  94581. for(i=0; i<db->nDb; i++) {
  94582. Btree *pBt = db->aDb[i].pBt;
  94583. if( pBt ){
  94584. assert( sqlite3BtreeHoldsMutex(pBt) );
  94585. rc = sqlite3BtreeSchemaLocked(pBt);
  94586. if( rc ){
  94587. const char *zDb = db->aDb[i].zName;
  94588. sqlite3Error(db, rc, "database schema is locked: %s", zDb);
  94589. testcase( db->flags & SQLITE_ReadUncommitted );
  94590. goto end_prepare;
  94591. }
  94592. }
  94593. }
  94594. sqlite3VtabUnlockList(db);
  94595. pParse->db = db;
  94596. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  94597. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  94598. char *zSqlCopy;
  94599. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  94600. testcase( nBytes==mxLen );
  94601. testcase( nBytes==mxLen+1 );
  94602. if( nBytes>mxLen ){
  94603. sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
  94604. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  94605. goto end_prepare;
  94606. }
  94607. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  94608. if( zSqlCopy ){
  94609. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  94610. sqlite3DbFree(db, zSqlCopy);
  94611. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  94612. }else{
  94613. pParse->zTail = &zSql[nBytes];
  94614. }
  94615. }else{
  94616. sqlite3RunParser(pParse, zSql, &zErrMsg);
  94617. }
  94618. assert( 0==pParse->nQueryLoop );
  94619. if( db->mallocFailed ){
  94620. pParse->rc = SQLITE_NOMEM;
  94621. }
  94622. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  94623. if( pParse->checkSchema ){
  94624. schemaIsValid(pParse);
  94625. }
  94626. if( db->mallocFailed ){
  94627. pParse->rc = SQLITE_NOMEM;
  94628. }
  94629. if( pzTail ){
  94630. *pzTail = pParse->zTail;
  94631. }
  94632. rc = pParse->rc;
  94633. #ifndef SQLITE_OMIT_EXPLAIN
  94634. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  94635. static const char * const azColName[] = {
  94636. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  94637. "selectid", "order", "from", "detail"
  94638. };
  94639. int iFirst, mx;
  94640. if( pParse->explain==2 ){
  94641. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  94642. iFirst = 8;
  94643. mx = 12;
  94644. }else{
  94645. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  94646. iFirst = 0;
  94647. mx = 8;
  94648. }
  94649. for(i=iFirst; i<mx; i++){
  94650. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  94651. azColName[i], SQLITE_STATIC);
  94652. }
  94653. }
  94654. #endif
  94655. if( db->init.busy==0 ){
  94656. Vdbe *pVdbe = pParse->pVdbe;
  94657. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  94658. }
  94659. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  94660. sqlite3VdbeFinalize(pParse->pVdbe);
  94661. assert(!(*ppStmt));
  94662. }else{
  94663. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  94664. }
  94665. if( zErrMsg ){
  94666. sqlite3Error(db, rc, "%s", zErrMsg);
  94667. sqlite3DbFree(db, zErrMsg);
  94668. }else{
  94669. sqlite3Error(db, rc, 0);
  94670. }
  94671. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  94672. while( pParse->pTriggerPrg ){
  94673. TriggerPrg *pT = pParse->pTriggerPrg;
  94674. pParse->pTriggerPrg = pT->pNext;
  94675. sqlite3DbFree(db, pT);
  94676. }
  94677. end_prepare:
  94678. sqlite3StackFree(db, pParse);
  94679. rc = sqlite3ApiExit(db, rc);
  94680. assert( (rc&db->errMask)==rc );
  94681. return rc;
  94682. }
  94683. static int sqlite3LockAndPrepare(
  94684. sqlite3 *db, /* Database handle. */
  94685. const char *zSql, /* UTF-8 encoded SQL statement. */
  94686. int nBytes, /* Length of zSql in bytes. */
  94687. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  94688. Vdbe *pOld, /* VM being reprepared */
  94689. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94690. const char **pzTail /* OUT: End of parsed string */
  94691. ){
  94692. int rc;
  94693. assert( ppStmt!=0 );
  94694. *ppStmt = 0;
  94695. if( !sqlite3SafetyCheckOk(db) ){
  94696. return SQLITE_MISUSE_BKPT;
  94697. }
  94698. sqlite3_mutex_enter(db->mutex);
  94699. sqlite3BtreeEnterAll(db);
  94700. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  94701. if( rc==SQLITE_SCHEMA ){
  94702. sqlite3_finalize(*ppStmt);
  94703. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  94704. }
  94705. sqlite3BtreeLeaveAll(db);
  94706. sqlite3_mutex_leave(db->mutex);
  94707. assert( rc==SQLITE_OK || *ppStmt==0 );
  94708. return rc;
  94709. }
  94710. /*
  94711. ** Rerun the compilation of a statement after a schema change.
  94712. **
  94713. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  94714. ** if the statement cannot be recompiled because another connection has
  94715. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  94716. ** occurs, return SQLITE_SCHEMA.
  94717. */
  94718. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  94719. int rc;
  94720. sqlite3_stmt *pNew;
  94721. const char *zSql;
  94722. sqlite3 *db;
  94723. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  94724. zSql = sqlite3_sql((sqlite3_stmt *)p);
  94725. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  94726. db = sqlite3VdbeDb(p);
  94727. assert( sqlite3_mutex_held(db->mutex) );
  94728. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  94729. if( rc ){
  94730. if( rc==SQLITE_NOMEM ){
  94731. db->mallocFailed = 1;
  94732. }
  94733. assert( pNew==0 );
  94734. return rc;
  94735. }else{
  94736. assert( pNew!=0 );
  94737. }
  94738. sqlite3VdbeSwap((Vdbe*)pNew, p);
  94739. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  94740. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  94741. sqlite3VdbeFinalize((Vdbe*)pNew);
  94742. return SQLITE_OK;
  94743. }
  94744. /*
  94745. ** Two versions of the official API. Legacy and new use. In the legacy
  94746. ** version, the original SQL text is not saved in the prepared statement
  94747. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  94748. ** sqlite3_step(). In the new version, the original SQL text is retained
  94749. ** and the statement is automatically recompiled if an schema change
  94750. ** occurs.
  94751. */
  94752. SQLITE_API int sqlite3_prepare(
  94753. sqlite3 *db, /* Database handle. */
  94754. const char *zSql, /* UTF-8 encoded SQL statement. */
  94755. int nBytes, /* Length of zSql in bytes. */
  94756. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94757. const char **pzTail /* OUT: End of parsed string */
  94758. ){
  94759. int rc;
  94760. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  94761. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94762. return rc;
  94763. }
  94764. SQLITE_API int sqlite3_prepare_v2(
  94765. sqlite3 *db, /* Database handle. */
  94766. const char *zSql, /* UTF-8 encoded SQL statement. */
  94767. int nBytes, /* Length of zSql in bytes. */
  94768. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94769. const char **pzTail /* OUT: End of parsed string */
  94770. ){
  94771. int rc;
  94772. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  94773. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94774. return rc;
  94775. }
  94776. #ifndef SQLITE_OMIT_UTF16
  94777. /*
  94778. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  94779. */
  94780. static int sqlite3Prepare16(
  94781. sqlite3 *db, /* Database handle. */
  94782. const void *zSql, /* UTF-16 encoded SQL statement. */
  94783. int nBytes, /* Length of zSql in bytes. */
  94784. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  94785. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94786. const void **pzTail /* OUT: End of parsed string */
  94787. ){
  94788. /* This function currently works by first transforming the UTF-16
  94789. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  94790. ** tricky bit is figuring out the pointer to return in *pzTail.
  94791. */
  94792. char *zSql8;
  94793. const char *zTail8 = 0;
  94794. int rc = SQLITE_OK;
  94795. assert( ppStmt );
  94796. *ppStmt = 0;
  94797. if( !sqlite3SafetyCheckOk(db) ){
  94798. return SQLITE_MISUSE_BKPT;
  94799. }
  94800. if( nBytes>=0 ){
  94801. int sz;
  94802. const char *z = (const char*)zSql;
  94803. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  94804. nBytes = sz;
  94805. }
  94806. sqlite3_mutex_enter(db->mutex);
  94807. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  94808. if( zSql8 ){
  94809. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  94810. }
  94811. if( zTail8 && pzTail ){
  94812. /* If sqlite3_prepare returns a tail pointer, we calculate the
  94813. ** equivalent pointer into the UTF-16 string by counting the unicode
  94814. ** characters between zSql8 and zTail8, and then returning a pointer
  94815. ** the same number of characters into the UTF-16 string.
  94816. */
  94817. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  94818. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  94819. }
  94820. sqlite3DbFree(db, zSql8);
  94821. rc = sqlite3ApiExit(db, rc);
  94822. sqlite3_mutex_leave(db->mutex);
  94823. return rc;
  94824. }
  94825. /*
  94826. ** Two versions of the official API. Legacy and new use. In the legacy
  94827. ** version, the original SQL text is not saved in the prepared statement
  94828. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  94829. ** sqlite3_step(). In the new version, the original SQL text is retained
  94830. ** and the statement is automatically recompiled if an schema change
  94831. ** occurs.
  94832. */
  94833. SQLITE_API int sqlite3_prepare16(
  94834. sqlite3 *db, /* Database handle. */
  94835. const void *zSql, /* UTF-16 encoded SQL statement. */
  94836. int nBytes, /* Length of zSql in bytes. */
  94837. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94838. const void **pzTail /* OUT: End of parsed string */
  94839. ){
  94840. int rc;
  94841. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  94842. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94843. return rc;
  94844. }
  94845. SQLITE_API int sqlite3_prepare16_v2(
  94846. sqlite3 *db, /* Database handle. */
  94847. const void *zSql, /* UTF-16 encoded SQL statement. */
  94848. int nBytes, /* Length of zSql in bytes. */
  94849. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  94850. const void **pzTail /* OUT: End of parsed string */
  94851. ){
  94852. int rc;
  94853. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  94854. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  94855. return rc;
  94856. }
  94857. #endif /* SQLITE_OMIT_UTF16 */
  94858. /************** End of prepare.c *********************************************/
  94859. /************** Begin file select.c ******************************************/
  94860. /*
  94861. ** 2001 September 15
  94862. **
  94863. ** The author disclaims copyright to this source code. In place of
  94864. ** a legal notice, here is a blessing:
  94865. **
  94866. ** May you do good and not evil.
  94867. ** May you find forgiveness for yourself and forgive others.
  94868. ** May you share freely, never taking more than you give.
  94869. **
  94870. *************************************************************************
  94871. ** This file contains C code routines that are called by the parser
  94872. ** to handle SELECT statements in SQLite.
  94873. */
  94874. /*
  94875. ** Delete all the content of a Select structure but do not deallocate
  94876. ** the select structure itself.
  94877. */
  94878. static void clearSelect(sqlite3 *db, Select *p){
  94879. sqlite3ExprListDelete(db, p->pEList);
  94880. sqlite3SrcListDelete(db, p->pSrc);
  94881. sqlite3ExprDelete(db, p->pWhere);
  94882. sqlite3ExprListDelete(db, p->pGroupBy);
  94883. sqlite3ExprDelete(db, p->pHaving);
  94884. sqlite3ExprListDelete(db, p->pOrderBy);
  94885. sqlite3SelectDelete(db, p->pPrior);
  94886. sqlite3ExprDelete(db, p->pLimit);
  94887. sqlite3ExprDelete(db, p->pOffset);
  94888. }
  94889. /*
  94890. ** Initialize a SelectDest structure.
  94891. */
  94892. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  94893. pDest->eDest = (u8)eDest;
  94894. pDest->iSDParm = iParm;
  94895. pDest->affSdst = 0;
  94896. pDest->iSdst = 0;
  94897. pDest->nSdst = 0;
  94898. }
  94899. /*
  94900. ** Allocate a new Select structure and return a pointer to that
  94901. ** structure.
  94902. */
  94903. SQLITE_PRIVATE Select *sqlite3SelectNew(
  94904. Parse *pParse, /* Parsing context */
  94905. ExprList *pEList, /* which columns to include in the result */
  94906. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  94907. Expr *pWhere, /* the WHERE clause */
  94908. ExprList *pGroupBy, /* the GROUP BY clause */
  94909. Expr *pHaving, /* the HAVING clause */
  94910. ExprList *pOrderBy, /* the ORDER BY clause */
  94911. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  94912. Expr *pLimit, /* LIMIT value. NULL means not used */
  94913. Expr *pOffset /* OFFSET value. NULL means no offset */
  94914. ){
  94915. Select *pNew;
  94916. Select standin;
  94917. sqlite3 *db = pParse->db;
  94918. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  94919. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  94920. if( pNew==0 ){
  94921. assert( db->mallocFailed );
  94922. pNew = &standin;
  94923. memset(pNew, 0, sizeof(*pNew));
  94924. }
  94925. if( pEList==0 ){
  94926. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  94927. }
  94928. pNew->pEList = pEList;
  94929. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  94930. pNew->pSrc = pSrc;
  94931. pNew->pWhere = pWhere;
  94932. pNew->pGroupBy = pGroupBy;
  94933. pNew->pHaving = pHaving;
  94934. pNew->pOrderBy = pOrderBy;
  94935. pNew->selFlags = selFlags;
  94936. pNew->op = TK_SELECT;
  94937. pNew->pLimit = pLimit;
  94938. pNew->pOffset = pOffset;
  94939. assert( pOffset==0 || pLimit!=0 );
  94940. pNew->addrOpenEphm[0] = -1;
  94941. pNew->addrOpenEphm[1] = -1;
  94942. pNew->addrOpenEphm[2] = -1;
  94943. if( db->mallocFailed ) {
  94944. clearSelect(db, pNew);
  94945. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  94946. pNew = 0;
  94947. }else{
  94948. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  94949. }
  94950. assert( pNew!=&standin );
  94951. return pNew;
  94952. }
  94953. /*
  94954. ** Delete the given Select structure and all of its substructures.
  94955. */
  94956. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  94957. if( p ){
  94958. clearSelect(db, p);
  94959. sqlite3DbFree(db, p);
  94960. }
  94961. }
  94962. /*
  94963. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  94964. ** type of join. Return an integer constant that expresses that type
  94965. ** in terms of the following bit values:
  94966. **
  94967. ** JT_INNER
  94968. ** JT_CROSS
  94969. ** JT_OUTER
  94970. ** JT_NATURAL
  94971. ** JT_LEFT
  94972. ** JT_RIGHT
  94973. **
  94974. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  94975. **
  94976. ** If an illegal or unsupported join type is seen, then still return
  94977. ** a join type, but put an error in the pParse structure.
  94978. */
  94979. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  94980. int jointype = 0;
  94981. Token *apAll[3];
  94982. Token *p;
  94983. /* 0123456789 123456789 123456789 123 */
  94984. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  94985. static const struct {
  94986. u8 i; /* Beginning of keyword text in zKeyText[] */
  94987. u8 nChar; /* Length of the keyword in characters */
  94988. u8 code; /* Join type mask */
  94989. } aKeyword[] = {
  94990. /* natural */ { 0, 7, JT_NATURAL },
  94991. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  94992. /* outer */ { 10, 5, JT_OUTER },
  94993. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  94994. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  94995. /* inner */ { 23, 5, JT_INNER },
  94996. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  94997. };
  94998. int i, j;
  94999. apAll[0] = pA;
  95000. apAll[1] = pB;
  95001. apAll[2] = pC;
  95002. for(i=0; i<3 && apAll[i]; i++){
  95003. p = apAll[i];
  95004. for(j=0; j<ArraySize(aKeyword); j++){
  95005. if( p->n==aKeyword[j].nChar
  95006. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  95007. jointype |= aKeyword[j].code;
  95008. break;
  95009. }
  95010. }
  95011. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  95012. if( j>=ArraySize(aKeyword) ){
  95013. jointype |= JT_ERROR;
  95014. break;
  95015. }
  95016. }
  95017. if(
  95018. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  95019. (jointype & JT_ERROR)!=0
  95020. ){
  95021. const char *zSp = " ";
  95022. assert( pB!=0 );
  95023. if( pC==0 ){ zSp++; }
  95024. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  95025. "%T %T%s%T", pA, pB, zSp, pC);
  95026. jointype = JT_INNER;
  95027. }else if( (jointype & JT_OUTER)!=0
  95028. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  95029. sqlite3ErrorMsg(pParse,
  95030. "RIGHT and FULL OUTER JOINs are not currently supported");
  95031. jointype = JT_INNER;
  95032. }
  95033. return jointype;
  95034. }
  95035. /*
  95036. ** Return the index of a column in a table. Return -1 if the column
  95037. ** is not contained in the table.
  95038. */
  95039. static int columnIndex(Table *pTab, const char *zCol){
  95040. int i;
  95041. for(i=0; i<pTab->nCol; i++){
  95042. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  95043. }
  95044. return -1;
  95045. }
  95046. /*
  95047. ** Search the first N tables in pSrc, from left to right, looking for a
  95048. ** table that has a column named zCol.
  95049. **
  95050. ** When found, set *piTab and *piCol to the table index and column index
  95051. ** of the matching column and return TRUE.
  95052. **
  95053. ** If not found, return FALSE.
  95054. */
  95055. static int tableAndColumnIndex(
  95056. SrcList *pSrc, /* Array of tables to search */
  95057. int N, /* Number of tables in pSrc->a[] to search */
  95058. const char *zCol, /* Name of the column we are looking for */
  95059. int *piTab, /* Write index of pSrc->a[] here */
  95060. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  95061. ){
  95062. int i; /* For looping over tables in pSrc */
  95063. int iCol; /* Index of column matching zCol */
  95064. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  95065. for(i=0; i<N; i++){
  95066. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  95067. if( iCol>=0 ){
  95068. if( piTab ){
  95069. *piTab = i;
  95070. *piCol = iCol;
  95071. }
  95072. return 1;
  95073. }
  95074. }
  95075. return 0;
  95076. }
  95077. /*
  95078. ** This function is used to add terms implied by JOIN syntax to the
  95079. ** WHERE clause expression of a SELECT statement. The new term, which
  95080. ** is ANDed with the existing WHERE clause, is of the form:
  95081. **
  95082. ** (tab1.col1 = tab2.col2)
  95083. **
  95084. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  95085. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  95086. ** column iColRight of tab2.
  95087. */
  95088. static void addWhereTerm(
  95089. Parse *pParse, /* Parsing context */
  95090. SrcList *pSrc, /* List of tables in FROM clause */
  95091. int iLeft, /* Index of first table to join in pSrc */
  95092. int iColLeft, /* Index of column in first table */
  95093. int iRight, /* Index of second table in pSrc */
  95094. int iColRight, /* Index of column in second table */
  95095. int isOuterJoin, /* True if this is an OUTER join */
  95096. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  95097. ){
  95098. sqlite3 *db = pParse->db;
  95099. Expr *pE1;
  95100. Expr *pE2;
  95101. Expr *pEq;
  95102. assert( iLeft<iRight );
  95103. assert( pSrc->nSrc>iRight );
  95104. assert( pSrc->a[iLeft].pTab );
  95105. assert( pSrc->a[iRight].pTab );
  95106. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  95107. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  95108. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  95109. if( pEq && isOuterJoin ){
  95110. ExprSetProperty(pEq, EP_FromJoin);
  95111. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  95112. ExprSetVVAProperty(pEq, EP_NoReduce);
  95113. pEq->iRightJoinTable = (i16)pE2->iTable;
  95114. }
  95115. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  95116. }
  95117. /*
  95118. ** Set the EP_FromJoin property on all terms of the given expression.
  95119. ** And set the Expr.iRightJoinTable to iTable for every term in the
  95120. ** expression.
  95121. **
  95122. ** The EP_FromJoin property is used on terms of an expression to tell
  95123. ** the LEFT OUTER JOIN processing logic that this term is part of the
  95124. ** join restriction specified in the ON or USING clause and not a part
  95125. ** of the more general WHERE clause. These terms are moved over to the
  95126. ** WHERE clause during join processing but we need to remember that they
  95127. ** originated in the ON or USING clause.
  95128. **
  95129. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  95130. ** expression depends on table iRightJoinTable even if that table is not
  95131. ** explicitly mentioned in the expression. That information is needed
  95132. ** for cases like this:
  95133. **
  95134. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  95135. **
  95136. ** The where clause needs to defer the handling of the t1.x=5
  95137. ** term until after the t2 loop of the join. In that way, a
  95138. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  95139. ** defer the handling of t1.x=5, it will be processed immediately
  95140. ** after the t1 loop and rows with t1.x!=5 will never appear in
  95141. ** the output, which is incorrect.
  95142. */
  95143. static void setJoinExpr(Expr *p, int iTable){
  95144. while( p ){
  95145. ExprSetProperty(p, EP_FromJoin);
  95146. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  95147. ExprSetVVAProperty(p, EP_NoReduce);
  95148. p->iRightJoinTable = (i16)iTable;
  95149. setJoinExpr(p->pLeft, iTable);
  95150. p = p->pRight;
  95151. }
  95152. }
  95153. /*
  95154. ** This routine processes the join information for a SELECT statement.
  95155. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  95156. ** NATURAL joins also create extra WHERE clause terms.
  95157. **
  95158. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  95159. ** The left most table is the first entry in Select.pSrc. The right-most
  95160. ** table is the last entry. The join operator is held in the entry to
  95161. ** the left. Thus entry 0 contains the join operator for the join between
  95162. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  95163. ** also attached to the left entry.
  95164. **
  95165. ** This routine returns the number of errors encountered.
  95166. */
  95167. static int sqliteProcessJoin(Parse *pParse, Select *p){
  95168. SrcList *pSrc; /* All tables in the FROM clause */
  95169. int i, j; /* Loop counters */
  95170. struct SrcList_item *pLeft; /* Left table being joined */
  95171. struct SrcList_item *pRight; /* Right table being joined */
  95172. pSrc = p->pSrc;
  95173. pLeft = &pSrc->a[0];
  95174. pRight = &pLeft[1];
  95175. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  95176. Table *pLeftTab = pLeft->pTab;
  95177. Table *pRightTab = pRight->pTab;
  95178. int isOuter;
  95179. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  95180. isOuter = (pRight->jointype & JT_OUTER)!=0;
  95181. /* When the NATURAL keyword is present, add WHERE clause terms for
  95182. ** every column that the two tables have in common.
  95183. */
  95184. if( pRight->jointype & JT_NATURAL ){
  95185. if( pRight->pOn || pRight->pUsing ){
  95186. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  95187. "an ON or USING clause", 0);
  95188. return 1;
  95189. }
  95190. for(j=0; j<pRightTab->nCol; j++){
  95191. char *zName; /* Name of column in the right table */
  95192. int iLeft; /* Matching left table */
  95193. int iLeftCol; /* Matching column in the left table */
  95194. zName = pRightTab->aCol[j].zName;
  95195. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  95196. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  95197. isOuter, &p->pWhere);
  95198. }
  95199. }
  95200. }
  95201. /* Disallow both ON and USING clauses in the same join
  95202. */
  95203. if( pRight->pOn && pRight->pUsing ){
  95204. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  95205. "clauses in the same join");
  95206. return 1;
  95207. }
  95208. /* Add the ON clause to the end of the WHERE clause, connected by
  95209. ** an AND operator.
  95210. */
  95211. if( pRight->pOn ){
  95212. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  95213. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  95214. pRight->pOn = 0;
  95215. }
  95216. /* Create extra terms on the WHERE clause for each column named
  95217. ** in the USING clause. Example: If the two tables to be joined are
  95218. ** A and B and the USING clause names X, Y, and Z, then add this
  95219. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  95220. ** Report an error if any column mentioned in the USING clause is
  95221. ** not contained in both tables to be joined.
  95222. */
  95223. if( pRight->pUsing ){
  95224. IdList *pList = pRight->pUsing;
  95225. for(j=0; j<pList->nId; j++){
  95226. char *zName; /* Name of the term in the USING clause */
  95227. int iLeft; /* Table on the left with matching column name */
  95228. int iLeftCol; /* Column number of matching column on the left */
  95229. int iRightCol; /* Column number of matching column on the right */
  95230. zName = pList->a[j].zName;
  95231. iRightCol = columnIndex(pRightTab, zName);
  95232. if( iRightCol<0
  95233. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  95234. ){
  95235. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  95236. "not present in both tables", zName);
  95237. return 1;
  95238. }
  95239. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  95240. isOuter, &p->pWhere);
  95241. }
  95242. }
  95243. }
  95244. return 0;
  95245. }
  95246. /*
  95247. ** Insert code into "v" that will push the record on the top of the
  95248. ** stack into the sorter.
  95249. */
  95250. static void pushOntoSorter(
  95251. Parse *pParse, /* Parser context */
  95252. ExprList *pOrderBy, /* The ORDER BY clause */
  95253. Select *pSelect, /* The whole SELECT statement */
  95254. int regData /* Register holding data to be sorted */
  95255. ){
  95256. Vdbe *v = pParse->pVdbe;
  95257. int nExpr = pOrderBy->nExpr;
  95258. int regBase = sqlite3GetTempRange(pParse, nExpr+2);
  95259. int regRecord = sqlite3GetTempReg(pParse);
  95260. int op;
  95261. sqlite3ExprCacheClear(pParse);
  95262. sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
  95263. sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
  95264. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
  95265. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
  95266. if( pSelect->selFlags & SF_UseSorter ){
  95267. op = OP_SorterInsert;
  95268. }else{
  95269. op = OP_IdxInsert;
  95270. }
  95271. sqlite3VdbeAddOp2(v, op, pOrderBy->iECursor, regRecord);
  95272. sqlite3ReleaseTempReg(pParse, regRecord);
  95273. sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
  95274. if( pSelect->iLimit ){
  95275. int addr1, addr2;
  95276. int iLimit;
  95277. if( pSelect->iOffset ){
  95278. iLimit = pSelect->iOffset+1;
  95279. }else{
  95280. iLimit = pSelect->iLimit;
  95281. }
  95282. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
  95283. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  95284. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  95285. sqlite3VdbeJumpHere(v, addr1);
  95286. sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
  95287. sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
  95288. sqlite3VdbeJumpHere(v, addr2);
  95289. }
  95290. }
  95291. /*
  95292. ** Add code to implement the OFFSET
  95293. */
  95294. static void codeOffset(
  95295. Vdbe *v, /* Generate code into this VM */
  95296. Select *p, /* The SELECT statement being coded */
  95297. int iContinue /* Jump here to skip the current record */
  95298. ){
  95299. if( p->iOffset && iContinue!=0 ){
  95300. int addr;
  95301. sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
  95302. addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
  95303. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  95304. VdbeComment((v, "skip OFFSET records"));
  95305. sqlite3VdbeJumpHere(v, addr);
  95306. }
  95307. }
  95308. /*
  95309. ** Add code that will check to make sure the N registers starting at iMem
  95310. ** form a distinct entry. iTab is a sorting index that holds previously
  95311. ** seen combinations of the N values. A new entry is made in iTab
  95312. ** if the current N values are new.
  95313. **
  95314. ** A jump to addrRepeat is made and the N+1 values are popped from the
  95315. ** stack if the top N elements are not distinct.
  95316. */
  95317. static void codeDistinct(
  95318. Parse *pParse, /* Parsing and code generating context */
  95319. int iTab, /* A sorting index used to test for distinctness */
  95320. int addrRepeat, /* Jump to here if not distinct */
  95321. int N, /* Number of elements */
  95322. int iMem /* First element */
  95323. ){
  95324. Vdbe *v;
  95325. int r1;
  95326. v = pParse->pVdbe;
  95327. r1 = sqlite3GetTempReg(pParse);
  95328. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
  95329. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  95330. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  95331. sqlite3ReleaseTempReg(pParse, r1);
  95332. }
  95333. #ifndef SQLITE_OMIT_SUBQUERY
  95334. /*
  95335. ** Generate an error message when a SELECT is used within a subexpression
  95336. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  95337. ** column. We do this in a subroutine because the error used to occur
  95338. ** in multiple places. (The error only occurs in one place now, but we
  95339. ** retain the subroutine to minimize code disruption.)
  95340. */
  95341. static int checkForMultiColumnSelectError(
  95342. Parse *pParse, /* Parse context. */
  95343. SelectDest *pDest, /* Destination of SELECT results */
  95344. int nExpr /* Number of result columns returned by SELECT */
  95345. ){
  95346. int eDest = pDest->eDest;
  95347. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  95348. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  95349. "a SELECT that is part of an expression");
  95350. return 1;
  95351. }else{
  95352. return 0;
  95353. }
  95354. }
  95355. #endif
  95356. /*
  95357. ** An instance of the following object is used to record information about
  95358. ** how to process the DISTINCT keyword, to simplify passing that information
  95359. ** into the selectInnerLoop() routine.
  95360. */
  95361. typedef struct DistinctCtx DistinctCtx;
  95362. struct DistinctCtx {
  95363. u8 isTnct; /* True if the DISTINCT keyword is present */
  95364. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  95365. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  95366. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  95367. };
  95368. /*
  95369. ** This routine generates the code for the inside of the inner loop
  95370. ** of a SELECT.
  95371. **
  95372. ** If srcTab and nColumn are both zero, then the pEList expressions
  95373. ** are evaluated in order to get the data for this row. If nColumn>0
  95374. ** then data is pulled from srcTab and pEList is used only to get the
  95375. ** datatypes for each column.
  95376. */
  95377. static void selectInnerLoop(
  95378. Parse *pParse, /* The parser context */
  95379. Select *p, /* The complete select statement being coded */
  95380. ExprList *pEList, /* List of values being extracted */
  95381. int srcTab, /* Pull data from this table */
  95382. int nColumn, /* Number of columns in the source table */
  95383. ExprList *pOrderBy, /* If not NULL, sort results using this key */
  95384. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  95385. SelectDest *pDest, /* How to dispose of the results */
  95386. int iContinue, /* Jump here to continue with next row */
  95387. int iBreak /* Jump here to break out of the inner loop */
  95388. ){
  95389. Vdbe *v = pParse->pVdbe;
  95390. int i;
  95391. int hasDistinct; /* True if the DISTINCT keyword is present */
  95392. int regResult; /* Start of memory holding result set */
  95393. int eDest = pDest->eDest; /* How to dispose of results */
  95394. int iParm = pDest->iSDParm; /* First argument to disposal method */
  95395. int nResultCol; /* Number of result columns */
  95396. assert( v );
  95397. if( NEVER(v==0) ) return;
  95398. assert( pEList!=0 );
  95399. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  95400. if( pOrderBy==0 && !hasDistinct ){
  95401. codeOffset(v, p, iContinue);
  95402. }
  95403. /* Pull the requested columns.
  95404. */
  95405. if( nColumn>0 ){
  95406. nResultCol = nColumn;
  95407. }else{
  95408. nResultCol = pEList->nExpr;
  95409. }
  95410. if( pDest->iSdst==0 ){
  95411. pDest->iSdst = pParse->nMem+1;
  95412. pDest->nSdst = nResultCol;
  95413. pParse->nMem += nResultCol;
  95414. }else{
  95415. assert( pDest->nSdst==nResultCol );
  95416. }
  95417. regResult = pDest->iSdst;
  95418. if( nColumn>0 ){
  95419. for(i=0; i<nColumn; i++){
  95420. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  95421. }
  95422. }else if( eDest!=SRT_Exists ){
  95423. /* If the destination is an EXISTS(...) expression, the actual
  95424. ** values returned by the SELECT are not required.
  95425. */
  95426. sqlite3ExprCacheClear(pParse);
  95427. sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
  95428. }
  95429. nColumn = nResultCol;
  95430. /* If the DISTINCT keyword was present on the SELECT statement
  95431. ** and this row has been seen before, then do not make this row
  95432. ** part of the result.
  95433. */
  95434. if( hasDistinct ){
  95435. assert( pEList!=0 );
  95436. assert( pEList->nExpr==nColumn );
  95437. switch( pDistinct->eTnctType ){
  95438. case WHERE_DISTINCT_ORDERED: {
  95439. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  95440. int iJump; /* Jump destination */
  95441. int regPrev; /* Previous row content */
  95442. /* Allocate space for the previous row */
  95443. regPrev = pParse->nMem+1;
  95444. pParse->nMem += nColumn;
  95445. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  95446. ** sets the MEM_Cleared bit on the first register of the
  95447. ** previous value. This will cause the OP_Ne below to always
  95448. ** fail on the first iteration of the loop even if the first
  95449. ** row is all NULLs.
  95450. */
  95451. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  95452. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  95453. pOp->opcode = OP_Null;
  95454. pOp->p1 = 1;
  95455. pOp->p2 = regPrev;
  95456. iJump = sqlite3VdbeCurrentAddr(v) + nColumn;
  95457. for(i=0; i<nColumn; i++){
  95458. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  95459. if( i<nColumn-1 ){
  95460. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  95461. }else{
  95462. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  95463. }
  95464. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  95465. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  95466. }
  95467. assert( sqlite3VdbeCurrentAddr(v)==iJump );
  95468. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nColumn-1);
  95469. break;
  95470. }
  95471. case WHERE_DISTINCT_UNIQUE: {
  95472. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  95473. break;
  95474. }
  95475. default: {
  95476. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  95477. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nColumn, regResult);
  95478. break;
  95479. }
  95480. }
  95481. if( pOrderBy==0 ){
  95482. codeOffset(v, p, iContinue);
  95483. }
  95484. }
  95485. switch( eDest ){
  95486. /* In this mode, write each query result to the key of the temporary
  95487. ** table iParm.
  95488. */
  95489. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  95490. case SRT_Union: {
  95491. int r1;
  95492. r1 = sqlite3GetTempReg(pParse);
  95493. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95494. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  95495. sqlite3ReleaseTempReg(pParse, r1);
  95496. break;
  95497. }
  95498. /* Construct a record from the query result, but instead of
  95499. ** saving that record, use it as a key to delete elements from
  95500. ** the temporary table iParm.
  95501. */
  95502. case SRT_Except: {
  95503. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
  95504. break;
  95505. }
  95506. #endif
  95507. /* Store the result as data using a unique key.
  95508. */
  95509. case SRT_Table:
  95510. case SRT_EphemTab: {
  95511. int r1 = sqlite3GetTempReg(pParse);
  95512. testcase( eDest==SRT_Table );
  95513. testcase( eDest==SRT_EphemTab );
  95514. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95515. if( pOrderBy ){
  95516. pushOntoSorter(pParse, pOrderBy, p, r1);
  95517. }else{
  95518. int r2 = sqlite3GetTempReg(pParse);
  95519. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  95520. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  95521. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95522. sqlite3ReleaseTempReg(pParse, r2);
  95523. }
  95524. sqlite3ReleaseTempReg(pParse, r1);
  95525. break;
  95526. }
  95527. #ifndef SQLITE_OMIT_SUBQUERY
  95528. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  95529. ** then there should be a single item on the stack. Write this
  95530. ** item into the set table with bogus data.
  95531. */
  95532. case SRT_Set: {
  95533. assert( nColumn==1 );
  95534. pDest->affSdst =
  95535. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  95536. if( pOrderBy ){
  95537. /* At first glance you would think we could optimize out the
  95538. ** ORDER BY in this case since the order of entries in the set
  95539. ** does not matter. But there might be a LIMIT clause, in which
  95540. ** case the order does matter */
  95541. pushOntoSorter(pParse, pOrderBy, p, regResult);
  95542. }else{
  95543. int r1 = sqlite3GetTempReg(pParse);
  95544. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  95545. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  95546. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  95547. sqlite3ReleaseTempReg(pParse, r1);
  95548. }
  95549. break;
  95550. }
  95551. /* If any row exist in the result set, record that fact and abort.
  95552. */
  95553. case SRT_Exists: {
  95554. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  95555. /* The LIMIT clause will terminate the loop for us */
  95556. break;
  95557. }
  95558. /* If this is a scalar select that is part of an expression, then
  95559. ** store the results in the appropriate memory cell and break out
  95560. ** of the scan loop.
  95561. */
  95562. case SRT_Mem: {
  95563. assert( nColumn==1 );
  95564. if( pOrderBy ){
  95565. pushOntoSorter(pParse, pOrderBy, p, regResult);
  95566. }else{
  95567. sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
  95568. /* The LIMIT clause will jump out of the loop for us */
  95569. }
  95570. break;
  95571. }
  95572. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  95573. /* Send the data to the callback function or to a subroutine. In the
  95574. ** case of a subroutine, the subroutine itself is responsible for
  95575. ** popping the data from the stack.
  95576. */
  95577. case SRT_Coroutine:
  95578. case SRT_Output: {
  95579. testcase( eDest==SRT_Coroutine );
  95580. testcase( eDest==SRT_Output );
  95581. if( pOrderBy ){
  95582. int r1 = sqlite3GetTempReg(pParse);
  95583. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
  95584. pushOntoSorter(pParse, pOrderBy, p, r1);
  95585. sqlite3ReleaseTempReg(pParse, r1);
  95586. }else if( eDest==SRT_Coroutine ){
  95587. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  95588. }else{
  95589. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
  95590. sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
  95591. }
  95592. break;
  95593. }
  95594. #if !defined(SQLITE_OMIT_TRIGGER)
  95595. /* Discard the results. This is used for SELECT statements inside
  95596. ** the body of a TRIGGER. The purpose of such selects is to call
  95597. ** user-defined functions that have side effects. We do not care
  95598. ** about the actual results of the select.
  95599. */
  95600. default: {
  95601. assert( eDest==SRT_Discard );
  95602. break;
  95603. }
  95604. #endif
  95605. }
  95606. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  95607. ** there is a sorter, in which case the sorter has already limited
  95608. ** the output for us.
  95609. */
  95610. if( pOrderBy==0 && p->iLimit ){
  95611. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  95612. }
  95613. }
  95614. /*
  95615. ** Allocate a KeyInfo object sufficient for an index of N columns.
  95616. **
  95617. ** Actually, always allocate one extra column for the rowid at the end
  95618. ** of the index. So the KeyInfo returned will have space sufficient for
  95619. ** N+1 columns.
  95620. */
  95621. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N){
  95622. KeyInfo *p = sqlite3DbMallocZero(db,
  95623. sizeof(KeyInfo) + (N+1)*(sizeof(CollSeq*)+1));
  95624. if( p ){
  95625. p->aSortOrder = (u8*)&p->aColl[N+1];
  95626. p->nField = (u16)N;
  95627. p->enc = ENC(db);
  95628. p->db = db;
  95629. }
  95630. return p;
  95631. }
  95632. /*
  95633. ** Given an expression list, generate a KeyInfo structure that records
  95634. ** the collating sequence for each expression in that expression list.
  95635. **
  95636. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  95637. ** KeyInfo structure is appropriate for initializing a virtual index to
  95638. ** implement that clause. If the ExprList is the result set of a SELECT
  95639. ** then the KeyInfo structure is appropriate for initializing a virtual
  95640. ** index to implement a DISTINCT test.
  95641. **
  95642. ** Space to hold the KeyInfo structure is obtain from malloc. The calling
  95643. ** function is responsible for seeing that this structure is eventually
  95644. ** freed. Add the KeyInfo structure to the P4 field of an opcode using
  95645. ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
  95646. */
  95647. static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
  95648. int nExpr;
  95649. KeyInfo *pInfo;
  95650. struct ExprList_item *pItem;
  95651. sqlite3 *db = pParse->db;
  95652. int i;
  95653. nExpr = pList->nExpr;
  95654. pInfo = sqlite3KeyInfoAlloc(db, nExpr);
  95655. if( pInfo ){
  95656. for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
  95657. CollSeq *pColl;
  95658. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  95659. if( !pColl ) pColl = db->pDfltColl;
  95660. pInfo->aColl[i] = pColl;
  95661. pInfo->aSortOrder[i] = pItem->sortOrder;
  95662. }
  95663. }
  95664. return pInfo;
  95665. }
  95666. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  95667. /*
  95668. ** Name of the connection operator, used for error messages.
  95669. */
  95670. static const char *selectOpName(int id){
  95671. char *z;
  95672. switch( id ){
  95673. case TK_ALL: z = "UNION ALL"; break;
  95674. case TK_INTERSECT: z = "INTERSECT"; break;
  95675. case TK_EXCEPT: z = "EXCEPT"; break;
  95676. default: z = "UNION"; break;
  95677. }
  95678. return z;
  95679. }
  95680. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  95681. #ifndef SQLITE_OMIT_EXPLAIN
  95682. /*
  95683. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  95684. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  95685. ** where the caption is of the form:
  95686. **
  95687. ** "USE TEMP B-TREE FOR xxx"
  95688. **
  95689. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  95690. ** is determined by the zUsage argument.
  95691. */
  95692. static void explainTempTable(Parse *pParse, const char *zUsage){
  95693. if( pParse->explain==2 ){
  95694. Vdbe *v = pParse->pVdbe;
  95695. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  95696. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  95697. }
  95698. }
  95699. /*
  95700. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  95701. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  95702. ** in sqlite3Select() to assign values to structure member variables that
  95703. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  95704. ** code with #ifndef directives.
  95705. */
  95706. # define explainSetInteger(a, b) a = b
  95707. #else
  95708. /* No-op versions of the explainXXX() functions and macros. */
  95709. # define explainTempTable(y,z)
  95710. # define explainSetInteger(y,z)
  95711. #endif
  95712. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  95713. /*
  95714. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  95715. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  95716. ** where the caption is of one of the two forms:
  95717. **
  95718. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  95719. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  95720. **
  95721. ** where iSub1 and iSub2 are the integers passed as the corresponding
  95722. ** function parameters, and op is the text representation of the parameter
  95723. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  95724. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  95725. ** false, or the second form if it is true.
  95726. */
  95727. static void explainComposite(
  95728. Parse *pParse, /* Parse context */
  95729. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  95730. int iSub1, /* Subquery id 1 */
  95731. int iSub2, /* Subquery id 2 */
  95732. int bUseTmp /* True if a temp table was used */
  95733. ){
  95734. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  95735. if( pParse->explain==2 ){
  95736. Vdbe *v = pParse->pVdbe;
  95737. char *zMsg = sqlite3MPrintf(
  95738. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  95739. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  95740. );
  95741. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  95742. }
  95743. }
  95744. #else
  95745. /* No-op versions of the explainXXX() functions and macros. */
  95746. # define explainComposite(v,w,x,y,z)
  95747. #endif
  95748. /*
  95749. ** If the inner loop was generated using a non-null pOrderBy argument,
  95750. ** then the results were placed in a sorter. After the loop is terminated
  95751. ** we need to run the sorter and output the results. The following
  95752. ** routine generates the code needed to do that.
  95753. */
  95754. static void generateSortTail(
  95755. Parse *pParse, /* Parsing context */
  95756. Select *p, /* The SELECT statement */
  95757. Vdbe *v, /* Generate code into this VDBE */
  95758. int nColumn, /* Number of columns of data */
  95759. SelectDest *pDest /* Write the sorted results here */
  95760. ){
  95761. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  95762. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  95763. int addr;
  95764. int iTab;
  95765. int pseudoTab = 0;
  95766. ExprList *pOrderBy = p->pOrderBy;
  95767. int eDest = pDest->eDest;
  95768. int iParm = pDest->iSDParm;
  95769. int regRow;
  95770. int regRowid;
  95771. iTab = pOrderBy->iECursor;
  95772. regRow = sqlite3GetTempReg(pParse);
  95773. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  95774. pseudoTab = pParse->nTab++;
  95775. sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
  95776. regRowid = 0;
  95777. }else{
  95778. regRowid = sqlite3GetTempReg(pParse);
  95779. }
  95780. if( p->selFlags & SF_UseSorter ){
  95781. int regSortOut = ++pParse->nMem;
  95782. int ptab2 = pParse->nTab++;
  95783. sqlite3VdbeAddOp3(v, OP_OpenPseudo, ptab2, regSortOut, pOrderBy->nExpr+2);
  95784. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  95785. codeOffset(v, p, addrContinue);
  95786. sqlite3VdbeAddOp2(v, OP_SorterData, iTab, regSortOut);
  95787. sqlite3VdbeAddOp3(v, OP_Column, ptab2, pOrderBy->nExpr+1, regRow);
  95788. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  95789. }else{
  95790. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
  95791. codeOffset(v, p, addrContinue);
  95792. sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr+1, regRow);
  95793. }
  95794. switch( eDest ){
  95795. case SRT_Table:
  95796. case SRT_EphemTab: {
  95797. testcase( eDest==SRT_Table );
  95798. testcase( eDest==SRT_EphemTab );
  95799. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  95800. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  95801. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  95802. break;
  95803. }
  95804. #ifndef SQLITE_OMIT_SUBQUERY
  95805. case SRT_Set: {
  95806. assert( nColumn==1 );
  95807. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  95808. &pDest->affSdst, 1);
  95809. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  95810. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  95811. break;
  95812. }
  95813. case SRT_Mem: {
  95814. assert( nColumn==1 );
  95815. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  95816. /* The LIMIT clause will terminate the loop for us */
  95817. break;
  95818. }
  95819. #endif
  95820. default: {
  95821. int i;
  95822. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  95823. testcase( eDest==SRT_Output );
  95824. testcase( eDest==SRT_Coroutine );
  95825. for(i=0; i<nColumn; i++){
  95826. assert( regRow!=pDest->iSdst+i );
  95827. sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iSdst+i);
  95828. if( i==0 ){
  95829. sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  95830. }
  95831. }
  95832. if( eDest==SRT_Output ){
  95833. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  95834. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  95835. }else{
  95836. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  95837. }
  95838. break;
  95839. }
  95840. }
  95841. sqlite3ReleaseTempReg(pParse, regRow);
  95842. sqlite3ReleaseTempReg(pParse, regRowid);
  95843. /* The bottom of the loop
  95844. */
  95845. sqlite3VdbeResolveLabel(v, addrContinue);
  95846. if( p->selFlags & SF_UseSorter ){
  95847. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr);
  95848. }else{
  95849. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
  95850. }
  95851. sqlite3VdbeResolveLabel(v, addrBreak);
  95852. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  95853. sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
  95854. }
  95855. }
  95856. /*
  95857. ** Return a pointer to a string containing the 'declaration type' of the
  95858. ** expression pExpr. The string may be treated as static by the caller.
  95859. **
  95860. ** Also try to estimate the size of the returned value and return that
  95861. ** result in *pEstWidth.
  95862. **
  95863. ** The declaration type is the exact datatype definition extracted from the
  95864. ** original CREATE TABLE statement if the expression is a column. The
  95865. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  95866. ** is considered a column can be complex in the presence of subqueries. The
  95867. ** result-set expression in all of the following SELECT statements is
  95868. ** considered a column by this function.
  95869. **
  95870. ** SELECT col FROM tbl;
  95871. ** SELECT (SELECT col FROM tbl;
  95872. ** SELECT (SELECT col FROM tbl);
  95873. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  95874. **
  95875. ** The declaration type for any expression other than a column is NULL.
  95876. **
  95877. ** This routine has either 3 or 6 parameters depending on whether or not
  95878. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  95879. */
  95880. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  95881. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  95882. static const char *columnTypeImpl(
  95883. NameContext *pNC,
  95884. Expr *pExpr,
  95885. const char **pzOrigDb,
  95886. const char **pzOrigTab,
  95887. const char **pzOrigCol,
  95888. u8 *pEstWidth
  95889. ){
  95890. char const *zOrigDb = 0;
  95891. char const *zOrigTab = 0;
  95892. char const *zOrigCol = 0;
  95893. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  95894. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  95895. static const char *columnTypeImpl(
  95896. NameContext *pNC,
  95897. Expr *pExpr,
  95898. u8 *pEstWidth
  95899. ){
  95900. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  95901. char const *zType = 0;
  95902. int j;
  95903. u8 estWidth = 1;
  95904. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  95905. switch( pExpr->op ){
  95906. case TK_AGG_COLUMN:
  95907. case TK_COLUMN: {
  95908. /* The expression is a column. Locate the table the column is being
  95909. ** extracted from in NameContext.pSrcList. This table may be real
  95910. ** database table or a subquery.
  95911. */
  95912. Table *pTab = 0; /* Table structure column is extracted from */
  95913. Select *pS = 0; /* Select the column is extracted from */
  95914. int iCol = pExpr->iColumn; /* Index of column in pTab */
  95915. testcase( pExpr->op==TK_AGG_COLUMN );
  95916. testcase( pExpr->op==TK_COLUMN );
  95917. while( pNC && !pTab ){
  95918. SrcList *pTabList = pNC->pSrcList;
  95919. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  95920. if( j<pTabList->nSrc ){
  95921. pTab = pTabList->a[j].pTab;
  95922. pS = pTabList->a[j].pSelect;
  95923. }else{
  95924. pNC = pNC->pNext;
  95925. }
  95926. }
  95927. if( pTab==0 ){
  95928. /* At one time, code such as "SELECT new.x" within a trigger would
  95929. ** cause this condition to run. Since then, we have restructured how
  95930. ** trigger code is generated and so this condition is no longer
  95931. ** possible. However, it can still be true for statements like
  95932. ** the following:
  95933. **
  95934. ** CREATE TABLE t1(col INTEGER);
  95935. ** SELECT (SELECT t1.col) FROM FROM t1;
  95936. **
  95937. ** when columnType() is called on the expression "t1.col" in the
  95938. ** sub-select. In this case, set the column type to NULL, even
  95939. ** though it should really be "INTEGER".
  95940. **
  95941. ** This is not a problem, as the column type of "t1.col" is never
  95942. ** used. When columnType() is called on the expression
  95943. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  95944. ** branch below. */
  95945. break;
  95946. }
  95947. assert( pTab && pExpr->pTab==pTab );
  95948. if( pS ){
  95949. /* The "table" is actually a sub-select or a view in the FROM clause
  95950. ** of the SELECT statement. Return the declaration type and origin
  95951. ** data for the result-set column of the sub-select.
  95952. */
  95953. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  95954. /* If iCol is less than zero, then the expression requests the
  95955. ** rowid of the sub-select or view. This expression is legal (see
  95956. ** test case misc2.2.2) - it always evaluates to NULL.
  95957. */
  95958. NameContext sNC;
  95959. Expr *p = pS->pEList->a[iCol].pExpr;
  95960. sNC.pSrcList = pS->pSrc;
  95961. sNC.pNext = pNC;
  95962. sNC.pParse = pNC->pParse;
  95963. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  95964. }
  95965. }else if( ALWAYS(pTab->pSchema) ){
  95966. /* A real table */
  95967. assert( !pS );
  95968. if( iCol<0 ) iCol = pTab->iPKey;
  95969. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  95970. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  95971. if( iCol<0 ){
  95972. zType = "INTEGER";
  95973. zOrigCol = "rowid";
  95974. }else{
  95975. zType = pTab->aCol[iCol].zType;
  95976. zOrigCol = pTab->aCol[iCol].zName;
  95977. estWidth = pTab->aCol[iCol].szEst;
  95978. }
  95979. zOrigTab = pTab->zName;
  95980. if( pNC->pParse ){
  95981. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  95982. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  95983. }
  95984. #else
  95985. if( iCol<0 ){
  95986. zType = "INTEGER";
  95987. }else{
  95988. zType = pTab->aCol[iCol].zType;
  95989. estWidth = pTab->aCol[iCol].szEst;
  95990. }
  95991. #endif
  95992. }
  95993. break;
  95994. }
  95995. #ifndef SQLITE_OMIT_SUBQUERY
  95996. case TK_SELECT: {
  95997. /* The expression is a sub-select. Return the declaration type and
  95998. ** origin info for the single column in the result set of the SELECT
  95999. ** statement.
  96000. */
  96001. NameContext sNC;
  96002. Select *pS = pExpr->x.pSelect;
  96003. Expr *p = pS->pEList->a[0].pExpr;
  96004. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  96005. sNC.pSrcList = pS->pSrc;
  96006. sNC.pNext = pNC;
  96007. sNC.pParse = pNC->pParse;
  96008. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  96009. break;
  96010. }
  96011. #endif
  96012. }
  96013. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  96014. if( pzOrigDb ){
  96015. assert( pzOrigTab && pzOrigCol );
  96016. *pzOrigDb = zOrigDb;
  96017. *pzOrigTab = zOrigTab;
  96018. *pzOrigCol = zOrigCol;
  96019. }
  96020. #endif
  96021. if( pEstWidth ) *pEstWidth = estWidth;
  96022. return zType;
  96023. }
  96024. /*
  96025. ** Generate code that will tell the VDBE the declaration types of columns
  96026. ** in the result set.
  96027. */
  96028. static void generateColumnTypes(
  96029. Parse *pParse, /* Parser context */
  96030. SrcList *pTabList, /* List of tables */
  96031. ExprList *pEList /* Expressions defining the result set */
  96032. ){
  96033. #ifndef SQLITE_OMIT_DECLTYPE
  96034. Vdbe *v = pParse->pVdbe;
  96035. int i;
  96036. NameContext sNC;
  96037. sNC.pSrcList = pTabList;
  96038. sNC.pParse = pParse;
  96039. for(i=0; i<pEList->nExpr; i++){
  96040. Expr *p = pEList->a[i].pExpr;
  96041. const char *zType;
  96042. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  96043. const char *zOrigDb = 0;
  96044. const char *zOrigTab = 0;
  96045. const char *zOrigCol = 0;
  96046. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  96047. /* The vdbe must make its own copy of the column-type and other
  96048. ** column specific strings, in case the schema is reset before this
  96049. ** virtual machine is deleted.
  96050. */
  96051. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  96052. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  96053. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  96054. #else
  96055. zType = columnType(&sNC, p, 0, 0, 0, 0);
  96056. #endif
  96057. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  96058. }
  96059. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  96060. }
  96061. /*
  96062. ** Generate code that will tell the VDBE the names of columns
  96063. ** in the result set. This information is used to provide the
  96064. ** azCol[] values in the callback.
  96065. */
  96066. static void generateColumnNames(
  96067. Parse *pParse, /* Parser context */
  96068. SrcList *pTabList, /* List of tables */
  96069. ExprList *pEList /* Expressions defining the result set */
  96070. ){
  96071. Vdbe *v = pParse->pVdbe;
  96072. int i, j;
  96073. sqlite3 *db = pParse->db;
  96074. int fullNames, shortNames;
  96075. #ifndef SQLITE_OMIT_EXPLAIN
  96076. /* If this is an EXPLAIN, skip this step */
  96077. if( pParse->explain ){
  96078. return;
  96079. }
  96080. #endif
  96081. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  96082. pParse->colNamesSet = 1;
  96083. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  96084. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  96085. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  96086. for(i=0; i<pEList->nExpr; i++){
  96087. Expr *p;
  96088. p = pEList->a[i].pExpr;
  96089. if( NEVER(p==0) ) continue;
  96090. if( pEList->a[i].zName ){
  96091. char *zName = pEList->a[i].zName;
  96092. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  96093. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  96094. Table *pTab;
  96095. char *zCol;
  96096. int iCol = p->iColumn;
  96097. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  96098. if( pTabList->a[j].iCursor==p->iTable ) break;
  96099. }
  96100. assert( j<pTabList->nSrc );
  96101. pTab = pTabList->a[j].pTab;
  96102. if( iCol<0 ) iCol = pTab->iPKey;
  96103. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  96104. if( iCol<0 ){
  96105. zCol = "rowid";
  96106. }else{
  96107. zCol = pTab->aCol[iCol].zName;
  96108. }
  96109. if( !shortNames && !fullNames ){
  96110. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  96111. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  96112. }else if( fullNames ){
  96113. char *zName = 0;
  96114. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  96115. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  96116. }else{
  96117. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  96118. }
  96119. }else{
  96120. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  96121. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  96122. }
  96123. }
  96124. generateColumnTypes(pParse, pTabList, pEList);
  96125. }
  96126. /*
  96127. ** Given a an expression list (which is really the list of expressions
  96128. ** that form the result set of a SELECT statement) compute appropriate
  96129. ** column names for a table that would hold the expression list.
  96130. **
  96131. ** All column names will be unique.
  96132. **
  96133. ** Only the column names are computed. Column.zType, Column.zColl,
  96134. ** and other fields of Column are zeroed.
  96135. **
  96136. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  96137. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  96138. */
  96139. static int selectColumnsFromExprList(
  96140. Parse *pParse, /* Parsing context */
  96141. ExprList *pEList, /* Expr list from which to derive column names */
  96142. i16 *pnCol, /* Write the number of columns here */
  96143. Column **paCol /* Write the new column list here */
  96144. ){
  96145. sqlite3 *db = pParse->db; /* Database connection */
  96146. int i, j; /* Loop counters */
  96147. int cnt; /* Index added to make the name unique */
  96148. Column *aCol, *pCol; /* For looping over result columns */
  96149. int nCol; /* Number of columns in the result set */
  96150. Expr *p; /* Expression for a single result column */
  96151. char *zName; /* Column name */
  96152. int nName; /* Size of name in zName[] */
  96153. if( pEList ){
  96154. nCol = pEList->nExpr;
  96155. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  96156. testcase( aCol==0 );
  96157. }else{
  96158. nCol = 0;
  96159. aCol = 0;
  96160. }
  96161. *pnCol = nCol;
  96162. *paCol = aCol;
  96163. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  96164. /* Get an appropriate name for the column
  96165. */
  96166. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  96167. if( (zName = pEList->a[i].zName)!=0 ){
  96168. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  96169. zName = sqlite3DbStrDup(db, zName);
  96170. }else{
  96171. Expr *pColExpr = p; /* The expression that is the result column name */
  96172. Table *pTab; /* Table associated with this expression */
  96173. while( pColExpr->op==TK_DOT ){
  96174. pColExpr = pColExpr->pRight;
  96175. assert( pColExpr!=0 );
  96176. }
  96177. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  96178. /* For columns use the column name name */
  96179. int iCol = pColExpr->iColumn;
  96180. pTab = pColExpr->pTab;
  96181. if( iCol<0 ) iCol = pTab->iPKey;
  96182. zName = sqlite3MPrintf(db, "%s",
  96183. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  96184. }else if( pColExpr->op==TK_ID ){
  96185. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  96186. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  96187. }else{
  96188. /* Use the original text of the column expression as its name */
  96189. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  96190. }
  96191. }
  96192. if( db->mallocFailed ){
  96193. sqlite3DbFree(db, zName);
  96194. break;
  96195. }
  96196. /* Make sure the column name is unique. If the name is not unique,
  96197. ** append a integer to the name so that it becomes unique.
  96198. */
  96199. nName = sqlite3Strlen30(zName);
  96200. for(j=cnt=0; j<i; j++){
  96201. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  96202. char *zNewName;
  96203. int k;
  96204. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  96205. if( zName[k]==':' ) nName = k;
  96206. zName[nName] = 0;
  96207. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  96208. sqlite3DbFree(db, zName);
  96209. zName = zNewName;
  96210. j = -1;
  96211. if( zName==0 ) break;
  96212. }
  96213. }
  96214. pCol->zName = zName;
  96215. }
  96216. if( db->mallocFailed ){
  96217. for(j=0; j<i; j++){
  96218. sqlite3DbFree(db, aCol[j].zName);
  96219. }
  96220. sqlite3DbFree(db, aCol);
  96221. *paCol = 0;
  96222. *pnCol = 0;
  96223. return SQLITE_NOMEM;
  96224. }
  96225. return SQLITE_OK;
  96226. }
  96227. /*
  96228. ** Add type and collation information to a column list based on
  96229. ** a SELECT statement.
  96230. **
  96231. ** The column list presumably came from selectColumnNamesFromExprList().
  96232. ** The column list has only names, not types or collations. This
  96233. ** routine goes through and adds the types and collations.
  96234. **
  96235. ** This routine requires that all identifiers in the SELECT
  96236. ** statement be resolved.
  96237. */
  96238. static void selectAddColumnTypeAndCollation(
  96239. Parse *pParse, /* Parsing contexts */
  96240. Table *pTab, /* Add column type information to this table */
  96241. Select *pSelect /* SELECT used to determine types and collations */
  96242. ){
  96243. sqlite3 *db = pParse->db;
  96244. NameContext sNC;
  96245. Column *pCol;
  96246. CollSeq *pColl;
  96247. int i;
  96248. Expr *p;
  96249. struct ExprList_item *a;
  96250. u64 szAll = 0;
  96251. assert( pSelect!=0 );
  96252. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  96253. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  96254. if( db->mallocFailed ) return;
  96255. memset(&sNC, 0, sizeof(sNC));
  96256. sNC.pSrcList = pSelect->pSrc;
  96257. a = pSelect->pEList->a;
  96258. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  96259. p = a[i].pExpr;
  96260. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  96261. szAll += pCol->szEst;
  96262. pCol->affinity = sqlite3ExprAffinity(p);
  96263. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  96264. pColl = sqlite3ExprCollSeq(pParse, p);
  96265. if( pColl ){
  96266. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  96267. }
  96268. }
  96269. pTab->szTabRow = sqlite3LogEst(szAll*4);
  96270. }
  96271. /*
  96272. ** Given a SELECT statement, generate a Table structure that describes
  96273. ** the result set of that SELECT.
  96274. */
  96275. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  96276. Table *pTab;
  96277. sqlite3 *db = pParse->db;
  96278. int savedFlags;
  96279. savedFlags = db->flags;
  96280. db->flags &= ~SQLITE_FullColNames;
  96281. db->flags |= SQLITE_ShortColNames;
  96282. sqlite3SelectPrep(pParse, pSelect, 0);
  96283. if( pParse->nErr ) return 0;
  96284. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  96285. db->flags = savedFlags;
  96286. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  96287. if( pTab==0 ){
  96288. return 0;
  96289. }
  96290. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  96291. ** is disabled */
  96292. assert( db->lookaside.bEnabled==0 );
  96293. pTab->nRef = 1;
  96294. pTab->zName = 0;
  96295. pTab->nRowEst = 1048576;
  96296. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  96297. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  96298. pTab->iPKey = -1;
  96299. if( db->mallocFailed ){
  96300. sqlite3DeleteTable(db, pTab);
  96301. return 0;
  96302. }
  96303. return pTab;
  96304. }
  96305. /*
  96306. ** Get a VDBE for the given parser context. Create a new one if necessary.
  96307. ** If an error occurs, return NULL and leave a message in pParse.
  96308. */
  96309. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  96310. Vdbe *v = pParse->pVdbe;
  96311. if( v==0 ){
  96312. v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
  96313. #ifndef SQLITE_OMIT_TRACE
  96314. if( v ){
  96315. sqlite3VdbeAddOp0(v, OP_Trace);
  96316. }
  96317. #endif
  96318. }
  96319. return v;
  96320. }
  96321. /*
  96322. ** Compute the iLimit and iOffset fields of the SELECT based on the
  96323. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  96324. ** that appear in the original SQL statement after the LIMIT and OFFSET
  96325. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  96326. ** are the integer memory register numbers for counters used to compute
  96327. ** the limit and offset. If there is no limit and/or offset, then
  96328. ** iLimit and iOffset are negative.
  96329. **
  96330. ** This routine changes the values of iLimit and iOffset only if
  96331. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  96332. ** iOffset should have been preset to appropriate default values
  96333. ** (usually but not always -1) prior to calling this routine.
  96334. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  96335. ** redefined. The UNION ALL operator uses this property to force
  96336. ** the reuse of the same limit and offset registers across multiple
  96337. ** SELECT statements.
  96338. */
  96339. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  96340. Vdbe *v = 0;
  96341. int iLimit = 0;
  96342. int iOffset;
  96343. int addr1, n;
  96344. if( p->iLimit ) return;
  96345. /*
  96346. ** "LIMIT -1" always shows all rows. There is some
  96347. ** controversy about what the correct behavior should be.
  96348. ** The current implementation interprets "LIMIT 0" to mean
  96349. ** no rows.
  96350. */
  96351. sqlite3ExprCacheClear(pParse);
  96352. assert( p->pOffset==0 || p->pLimit!=0 );
  96353. if( p->pLimit ){
  96354. p->iLimit = iLimit = ++pParse->nMem;
  96355. v = sqlite3GetVdbe(pParse);
  96356. if( NEVER(v==0) ) return; /* VDBE should have already been allocated */
  96357. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  96358. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  96359. VdbeComment((v, "LIMIT counter"));
  96360. if( n==0 ){
  96361. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  96362. }else if( n>=0 && p->nSelectRow>(u64)n ){
  96363. p->nSelectRow = n;
  96364. }
  96365. }else{
  96366. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  96367. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
  96368. VdbeComment((v, "LIMIT counter"));
  96369. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
  96370. }
  96371. if( p->pOffset ){
  96372. p->iOffset = iOffset = ++pParse->nMem;
  96373. pParse->nMem++; /* Allocate an extra register for limit+offset */
  96374. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  96375. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
  96376. VdbeComment((v, "OFFSET counter"));
  96377. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
  96378. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  96379. sqlite3VdbeJumpHere(v, addr1);
  96380. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  96381. VdbeComment((v, "LIMIT+OFFSET"));
  96382. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
  96383. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  96384. sqlite3VdbeJumpHere(v, addr1);
  96385. }
  96386. }
  96387. }
  96388. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  96389. /*
  96390. ** Return the appropriate collating sequence for the iCol-th column of
  96391. ** the result set for the compound-select statement "p". Return NULL if
  96392. ** the column has no default collating sequence.
  96393. **
  96394. ** The collating sequence for the compound select is taken from the
  96395. ** left-most term of the select that has a collating sequence.
  96396. */
  96397. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  96398. CollSeq *pRet;
  96399. if( p->pPrior ){
  96400. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  96401. }else{
  96402. pRet = 0;
  96403. }
  96404. assert( iCol>=0 );
  96405. if( pRet==0 && iCol<p->pEList->nExpr ){
  96406. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  96407. }
  96408. return pRet;
  96409. }
  96410. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  96411. /* Forward reference */
  96412. static int multiSelectOrderBy(
  96413. Parse *pParse, /* Parsing context */
  96414. Select *p, /* The right-most of SELECTs to be coded */
  96415. SelectDest *pDest /* What to do with query results */
  96416. );
  96417. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  96418. /*
  96419. ** This routine is called to process a compound query form from
  96420. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  96421. ** INTERSECT
  96422. **
  96423. ** "p" points to the right-most of the two queries. the query on the
  96424. ** left is p->pPrior. The left query could also be a compound query
  96425. ** in which case this routine will be called recursively.
  96426. **
  96427. ** The results of the total query are to be written into a destination
  96428. ** of type eDest with parameter iParm.
  96429. **
  96430. ** Example 1: Consider a three-way compound SQL statement.
  96431. **
  96432. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  96433. **
  96434. ** This statement is parsed up as follows:
  96435. **
  96436. ** SELECT c FROM t3
  96437. ** |
  96438. ** `-----> SELECT b FROM t2
  96439. ** |
  96440. ** `------> SELECT a FROM t1
  96441. **
  96442. ** The arrows in the diagram above represent the Select.pPrior pointer.
  96443. ** So if this routine is called with p equal to the t3 query, then
  96444. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  96445. **
  96446. ** Notice that because of the way SQLite parses compound SELECTs, the
  96447. ** individual selects always group from left to right.
  96448. */
  96449. static int multiSelect(
  96450. Parse *pParse, /* Parsing context */
  96451. Select *p, /* The right-most of SELECTs to be coded */
  96452. SelectDest *pDest /* What to do with query results */
  96453. ){
  96454. int rc = SQLITE_OK; /* Success code from a subroutine */
  96455. Select *pPrior; /* Another SELECT immediately to our left */
  96456. Vdbe *v; /* Generate code to this VDBE */
  96457. SelectDest dest; /* Alternative data destination */
  96458. Select *pDelete = 0; /* Chain of simple selects to delete */
  96459. sqlite3 *db; /* Database connection */
  96460. #ifndef SQLITE_OMIT_EXPLAIN
  96461. int iSub1; /* EQP id of left-hand query */
  96462. int iSub2; /* EQP id of right-hand query */
  96463. #endif
  96464. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  96465. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  96466. */
  96467. assert( p && p->pPrior ); /* Calling function guarantees this much */
  96468. db = pParse->db;
  96469. pPrior = p->pPrior;
  96470. assert( pPrior->pRightmost!=pPrior );
  96471. assert( pPrior->pRightmost==p->pRightmost );
  96472. dest = *pDest;
  96473. if( pPrior->pOrderBy ){
  96474. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  96475. selectOpName(p->op));
  96476. rc = 1;
  96477. goto multi_select_end;
  96478. }
  96479. if( pPrior->pLimit ){
  96480. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  96481. selectOpName(p->op));
  96482. rc = 1;
  96483. goto multi_select_end;
  96484. }
  96485. v = sqlite3GetVdbe(pParse);
  96486. assert( v!=0 ); /* The VDBE already created by calling function */
  96487. /* Create the destination temporary table if necessary
  96488. */
  96489. if( dest.eDest==SRT_EphemTab ){
  96490. assert( p->pEList );
  96491. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  96492. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  96493. dest.eDest = SRT_Table;
  96494. }
  96495. /* Make sure all SELECTs in the statement have the same number of elements
  96496. ** in their result sets.
  96497. */
  96498. assert( p->pEList && pPrior->pEList );
  96499. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  96500. if( p->selFlags & SF_Values ){
  96501. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  96502. }else{
  96503. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  96504. " do not have the same number of result columns", selectOpName(p->op));
  96505. }
  96506. rc = 1;
  96507. goto multi_select_end;
  96508. }
  96509. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  96510. */
  96511. if( p->pOrderBy ){
  96512. return multiSelectOrderBy(pParse, p, pDest);
  96513. }
  96514. /* Generate code for the left and right SELECT statements.
  96515. */
  96516. switch( p->op ){
  96517. case TK_ALL: {
  96518. int addr = 0;
  96519. int nLimit;
  96520. assert( !pPrior->pLimit );
  96521. pPrior->iLimit = p->iLimit;
  96522. pPrior->iOffset = p->iOffset;
  96523. pPrior->pLimit = p->pLimit;
  96524. pPrior->pOffset = p->pOffset;
  96525. explainSetInteger(iSub1, pParse->iNextSelectId);
  96526. rc = sqlite3Select(pParse, pPrior, &dest);
  96527. p->pLimit = 0;
  96528. p->pOffset = 0;
  96529. if( rc ){
  96530. goto multi_select_end;
  96531. }
  96532. p->pPrior = 0;
  96533. p->iLimit = pPrior->iLimit;
  96534. p->iOffset = pPrior->iOffset;
  96535. if( p->iLimit ){
  96536. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
  96537. VdbeComment((v, "Jump ahead if LIMIT reached"));
  96538. }
  96539. explainSetInteger(iSub2, pParse->iNextSelectId);
  96540. rc = sqlite3Select(pParse, p, &dest);
  96541. testcase( rc!=SQLITE_OK );
  96542. pDelete = p->pPrior;
  96543. p->pPrior = pPrior;
  96544. p->nSelectRow += pPrior->nSelectRow;
  96545. if( pPrior->pLimit
  96546. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  96547. && nLimit>0 && p->nSelectRow > (u64)nLimit
  96548. ){
  96549. p->nSelectRow = nLimit;
  96550. }
  96551. if( addr ){
  96552. sqlite3VdbeJumpHere(v, addr);
  96553. }
  96554. break;
  96555. }
  96556. case TK_EXCEPT:
  96557. case TK_UNION: {
  96558. int unionTab; /* Cursor number of the temporary table holding result */
  96559. u8 op = 0; /* One of the SRT_ operations to apply to self */
  96560. int priorOp; /* The SRT_ operation to apply to prior selects */
  96561. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  96562. int addr;
  96563. SelectDest uniondest;
  96564. testcase( p->op==TK_EXCEPT );
  96565. testcase( p->op==TK_UNION );
  96566. priorOp = SRT_Union;
  96567. if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
  96568. /* We can reuse a temporary table generated by a SELECT to our
  96569. ** right.
  96570. */
  96571. assert( p->pRightmost!=p ); /* Can only happen for leftward elements
  96572. ** of a 3-way or more compound */
  96573. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  96574. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  96575. unionTab = dest.iSDParm;
  96576. }else{
  96577. /* We will need to create our own temporary table to hold the
  96578. ** intermediate results.
  96579. */
  96580. unionTab = pParse->nTab++;
  96581. assert( p->pOrderBy==0 );
  96582. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  96583. assert( p->addrOpenEphm[0] == -1 );
  96584. p->addrOpenEphm[0] = addr;
  96585. p->pRightmost->selFlags |= SF_UsesEphemeral;
  96586. assert( p->pEList );
  96587. }
  96588. /* Code the SELECT statements to our left
  96589. */
  96590. assert( !pPrior->pOrderBy );
  96591. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  96592. explainSetInteger(iSub1, pParse->iNextSelectId);
  96593. rc = sqlite3Select(pParse, pPrior, &uniondest);
  96594. if( rc ){
  96595. goto multi_select_end;
  96596. }
  96597. /* Code the current SELECT statement
  96598. */
  96599. if( p->op==TK_EXCEPT ){
  96600. op = SRT_Except;
  96601. }else{
  96602. assert( p->op==TK_UNION );
  96603. op = SRT_Union;
  96604. }
  96605. p->pPrior = 0;
  96606. pLimit = p->pLimit;
  96607. p->pLimit = 0;
  96608. pOffset = p->pOffset;
  96609. p->pOffset = 0;
  96610. uniondest.eDest = op;
  96611. explainSetInteger(iSub2, pParse->iNextSelectId);
  96612. rc = sqlite3Select(pParse, p, &uniondest);
  96613. testcase( rc!=SQLITE_OK );
  96614. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  96615. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  96616. sqlite3ExprListDelete(db, p->pOrderBy);
  96617. pDelete = p->pPrior;
  96618. p->pPrior = pPrior;
  96619. p->pOrderBy = 0;
  96620. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  96621. sqlite3ExprDelete(db, p->pLimit);
  96622. p->pLimit = pLimit;
  96623. p->pOffset = pOffset;
  96624. p->iLimit = 0;
  96625. p->iOffset = 0;
  96626. /* Convert the data in the temporary table into whatever form
  96627. ** it is that we currently need.
  96628. */
  96629. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  96630. if( dest.eDest!=priorOp ){
  96631. int iCont, iBreak, iStart;
  96632. assert( p->pEList );
  96633. if( dest.eDest==SRT_Output ){
  96634. Select *pFirst = p;
  96635. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  96636. generateColumnNames(pParse, 0, pFirst->pEList);
  96637. }
  96638. iBreak = sqlite3VdbeMakeLabel(v);
  96639. iCont = sqlite3VdbeMakeLabel(v);
  96640. computeLimitRegisters(pParse, p, iBreak);
  96641. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
  96642. iStart = sqlite3VdbeCurrentAddr(v);
  96643. selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  96644. 0, 0, &dest, iCont, iBreak);
  96645. sqlite3VdbeResolveLabel(v, iCont);
  96646. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
  96647. sqlite3VdbeResolveLabel(v, iBreak);
  96648. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  96649. }
  96650. break;
  96651. }
  96652. default: assert( p->op==TK_INTERSECT ); {
  96653. int tab1, tab2;
  96654. int iCont, iBreak, iStart;
  96655. Expr *pLimit, *pOffset;
  96656. int addr;
  96657. SelectDest intersectdest;
  96658. int r1;
  96659. /* INTERSECT is different from the others since it requires
  96660. ** two temporary tables. Hence it has its own case. Begin
  96661. ** by allocating the tables we will need.
  96662. */
  96663. tab1 = pParse->nTab++;
  96664. tab2 = pParse->nTab++;
  96665. assert( p->pOrderBy==0 );
  96666. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  96667. assert( p->addrOpenEphm[0] == -1 );
  96668. p->addrOpenEphm[0] = addr;
  96669. p->pRightmost->selFlags |= SF_UsesEphemeral;
  96670. assert( p->pEList );
  96671. /* Code the SELECTs to our left into temporary table "tab1".
  96672. */
  96673. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  96674. explainSetInteger(iSub1, pParse->iNextSelectId);
  96675. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  96676. if( rc ){
  96677. goto multi_select_end;
  96678. }
  96679. /* Code the current SELECT into temporary table "tab2"
  96680. */
  96681. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  96682. assert( p->addrOpenEphm[1] == -1 );
  96683. p->addrOpenEphm[1] = addr;
  96684. p->pPrior = 0;
  96685. pLimit = p->pLimit;
  96686. p->pLimit = 0;
  96687. pOffset = p->pOffset;
  96688. p->pOffset = 0;
  96689. intersectdest.iSDParm = tab2;
  96690. explainSetInteger(iSub2, pParse->iNextSelectId);
  96691. rc = sqlite3Select(pParse, p, &intersectdest);
  96692. testcase( rc!=SQLITE_OK );
  96693. pDelete = p->pPrior;
  96694. p->pPrior = pPrior;
  96695. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  96696. sqlite3ExprDelete(db, p->pLimit);
  96697. p->pLimit = pLimit;
  96698. p->pOffset = pOffset;
  96699. /* Generate code to take the intersection of the two temporary
  96700. ** tables.
  96701. */
  96702. assert( p->pEList );
  96703. if( dest.eDest==SRT_Output ){
  96704. Select *pFirst = p;
  96705. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  96706. generateColumnNames(pParse, 0, pFirst->pEList);
  96707. }
  96708. iBreak = sqlite3VdbeMakeLabel(v);
  96709. iCont = sqlite3VdbeMakeLabel(v);
  96710. computeLimitRegisters(pParse, p, iBreak);
  96711. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
  96712. r1 = sqlite3GetTempReg(pParse);
  96713. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  96714. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
  96715. sqlite3ReleaseTempReg(pParse, r1);
  96716. selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  96717. 0, 0, &dest, iCont, iBreak);
  96718. sqlite3VdbeResolveLabel(v, iCont);
  96719. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
  96720. sqlite3VdbeResolveLabel(v, iBreak);
  96721. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  96722. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  96723. break;
  96724. }
  96725. }
  96726. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  96727. /* Compute collating sequences used by
  96728. ** temporary tables needed to implement the compound select.
  96729. ** Attach the KeyInfo structure to all temporary tables.
  96730. **
  96731. ** This section is run by the right-most SELECT statement only.
  96732. ** SELECT statements to the left always skip this part. The right-most
  96733. ** SELECT might also skip this part if it has no ORDER BY clause and
  96734. ** no temp tables are required.
  96735. */
  96736. if( p->selFlags & SF_UsesEphemeral ){
  96737. int i; /* Loop counter */
  96738. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  96739. Select *pLoop; /* For looping through SELECT statements */
  96740. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  96741. int nCol; /* Number of columns in result set */
  96742. assert( p->pRightmost==p );
  96743. nCol = p->pEList->nExpr;
  96744. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol);
  96745. if( !pKeyInfo ){
  96746. rc = SQLITE_NOMEM;
  96747. goto multi_select_end;
  96748. }
  96749. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  96750. *apColl = multiSelectCollSeq(pParse, p, i);
  96751. if( 0==*apColl ){
  96752. *apColl = db->pDfltColl;
  96753. }
  96754. }
  96755. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  96756. for(i=0; i<2; i++){
  96757. int addr = pLoop->addrOpenEphm[i];
  96758. if( addr<0 ){
  96759. /* If [0] is unused then [1] is also unused. So we can
  96760. ** always safely abort as soon as the first unused slot is found */
  96761. assert( pLoop->addrOpenEphm[1]<0 );
  96762. break;
  96763. }
  96764. sqlite3VdbeChangeP2(v, addr, nCol);
  96765. sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
  96766. pLoop->addrOpenEphm[i] = -1;
  96767. }
  96768. }
  96769. sqlite3DbFree(db, pKeyInfo);
  96770. }
  96771. multi_select_end:
  96772. pDest->iSdst = dest.iSdst;
  96773. pDest->nSdst = dest.nSdst;
  96774. sqlite3SelectDelete(db, pDelete);
  96775. return rc;
  96776. }
  96777. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  96778. /*
  96779. ** Code an output subroutine for a coroutine implementation of a
  96780. ** SELECT statment.
  96781. **
  96782. ** The data to be output is contained in pIn->iSdst. There are
  96783. ** pIn->nSdst columns to be output. pDest is where the output should
  96784. ** be sent.
  96785. **
  96786. ** regReturn is the number of the register holding the subroutine
  96787. ** return address.
  96788. **
  96789. ** If regPrev>0 then it is the first register in a vector that
  96790. ** records the previous output. mem[regPrev] is a flag that is false
  96791. ** if there has been no previous output. If regPrev>0 then code is
  96792. ** generated to suppress duplicates. pKeyInfo is used for comparing
  96793. ** keys.
  96794. **
  96795. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  96796. ** iBreak.
  96797. */
  96798. static int generateOutputSubroutine(
  96799. Parse *pParse, /* Parsing context */
  96800. Select *p, /* The SELECT statement */
  96801. SelectDest *pIn, /* Coroutine supplying data */
  96802. SelectDest *pDest, /* Where to send the data */
  96803. int regReturn, /* The return address register */
  96804. int regPrev, /* Previous result register. No uniqueness if 0 */
  96805. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  96806. int p4type, /* The p4 type for pKeyInfo */
  96807. int iBreak /* Jump here if we hit the LIMIT */
  96808. ){
  96809. Vdbe *v = pParse->pVdbe;
  96810. int iContinue;
  96811. int addr;
  96812. addr = sqlite3VdbeCurrentAddr(v);
  96813. iContinue = sqlite3VdbeMakeLabel(v);
  96814. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  96815. */
  96816. if( regPrev ){
  96817. int j1, j2;
  96818. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
  96819. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  96820. (char*)pKeyInfo, p4type);
  96821. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
  96822. sqlite3VdbeJumpHere(v, j1);
  96823. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  96824. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  96825. }
  96826. if( pParse->db->mallocFailed ) return 0;
  96827. /* Suppress the first OFFSET entries if there is an OFFSET clause
  96828. */
  96829. codeOffset(v, p, iContinue);
  96830. switch( pDest->eDest ){
  96831. /* Store the result as data using a unique key.
  96832. */
  96833. case SRT_Table:
  96834. case SRT_EphemTab: {
  96835. int r1 = sqlite3GetTempReg(pParse);
  96836. int r2 = sqlite3GetTempReg(pParse);
  96837. testcase( pDest->eDest==SRT_Table );
  96838. testcase( pDest->eDest==SRT_EphemTab );
  96839. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  96840. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  96841. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  96842. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  96843. sqlite3ReleaseTempReg(pParse, r2);
  96844. sqlite3ReleaseTempReg(pParse, r1);
  96845. break;
  96846. }
  96847. #ifndef SQLITE_OMIT_SUBQUERY
  96848. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  96849. ** then there should be a single item on the stack. Write this
  96850. ** item into the set table with bogus data.
  96851. */
  96852. case SRT_Set: {
  96853. int r1;
  96854. assert( pIn->nSdst==1 );
  96855. pDest->affSdst =
  96856. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  96857. r1 = sqlite3GetTempReg(pParse);
  96858. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  96859. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  96860. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  96861. sqlite3ReleaseTempReg(pParse, r1);
  96862. break;
  96863. }
  96864. #if 0 /* Never occurs on an ORDER BY query */
  96865. /* If any row exist in the result set, record that fact and abort.
  96866. */
  96867. case SRT_Exists: {
  96868. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  96869. /* The LIMIT clause will terminate the loop for us */
  96870. break;
  96871. }
  96872. #endif
  96873. /* If this is a scalar select that is part of an expression, then
  96874. ** store the results in the appropriate memory cell and break out
  96875. ** of the scan loop.
  96876. */
  96877. case SRT_Mem: {
  96878. assert( pIn->nSdst==1 );
  96879. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  96880. /* The LIMIT clause will jump out of the loop for us */
  96881. break;
  96882. }
  96883. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  96884. /* The results are stored in a sequence of registers
  96885. ** starting at pDest->iSdst. Then the co-routine yields.
  96886. */
  96887. case SRT_Coroutine: {
  96888. if( pDest->iSdst==0 ){
  96889. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  96890. pDest->nSdst = pIn->nSdst;
  96891. }
  96892. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  96893. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  96894. break;
  96895. }
  96896. /* If none of the above, then the result destination must be
  96897. ** SRT_Output. This routine is never called with any other
  96898. ** destination other than the ones handled above or SRT_Output.
  96899. **
  96900. ** For SRT_Output, results are stored in a sequence of registers.
  96901. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  96902. ** return the next row of result.
  96903. */
  96904. default: {
  96905. assert( pDest->eDest==SRT_Output );
  96906. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  96907. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  96908. break;
  96909. }
  96910. }
  96911. /* Jump to the end of the loop if the LIMIT is reached.
  96912. */
  96913. if( p->iLimit ){
  96914. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
  96915. }
  96916. /* Generate the subroutine return
  96917. */
  96918. sqlite3VdbeResolveLabel(v, iContinue);
  96919. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  96920. return addr;
  96921. }
  96922. /*
  96923. ** Alternative compound select code generator for cases when there
  96924. ** is an ORDER BY clause.
  96925. **
  96926. ** We assume a query of the following form:
  96927. **
  96928. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  96929. **
  96930. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  96931. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  96932. ** co-routines. Then run the co-routines in parallel and merge the results
  96933. ** into the output. In addition to the two coroutines (called selectA and
  96934. ** selectB) there are 7 subroutines:
  96935. **
  96936. ** outA: Move the output of the selectA coroutine into the output
  96937. ** of the compound query.
  96938. **
  96939. ** outB: Move the output of the selectB coroutine into the output
  96940. ** of the compound query. (Only generated for UNION and
  96941. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  96942. ** appears only in B.)
  96943. **
  96944. ** AltB: Called when there is data from both coroutines and A<B.
  96945. **
  96946. ** AeqB: Called when there is data from both coroutines and A==B.
  96947. **
  96948. ** AgtB: Called when there is data from both coroutines and A>B.
  96949. **
  96950. ** EofA: Called when data is exhausted from selectA.
  96951. **
  96952. ** EofB: Called when data is exhausted from selectB.
  96953. **
  96954. ** The implementation of the latter five subroutines depend on which
  96955. ** <operator> is used:
  96956. **
  96957. **
  96958. ** UNION ALL UNION EXCEPT INTERSECT
  96959. ** ------------- ----------------- -------------- -----------------
  96960. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  96961. **
  96962. ** AeqB: outA, nextA nextA nextA outA, nextA
  96963. **
  96964. ** AgtB: outB, nextB outB, nextB nextB nextB
  96965. **
  96966. ** EofA: outB, nextB outB, nextB halt halt
  96967. **
  96968. ** EofB: outA, nextA outA, nextA outA, nextA halt
  96969. **
  96970. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  96971. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  96972. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  96973. ** following nextX causes a jump to the end of the select processing.
  96974. **
  96975. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  96976. ** within the output subroutine. The regPrev register set holds the previously
  96977. ** output value. A comparison is made against this value and the output
  96978. ** is skipped if the next results would be the same as the previous.
  96979. **
  96980. ** The implementation plan is to implement the two coroutines and seven
  96981. ** subroutines first, then put the control logic at the bottom. Like this:
  96982. **
  96983. ** goto Init
  96984. ** coA: coroutine for left query (A)
  96985. ** coB: coroutine for right query (B)
  96986. ** outA: output one row of A
  96987. ** outB: output one row of B (UNION and UNION ALL only)
  96988. ** EofA: ...
  96989. ** EofB: ...
  96990. ** AltB: ...
  96991. ** AeqB: ...
  96992. ** AgtB: ...
  96993. ** Init: initialize coroutine registers
  96994. ** yield coA
  96995. ** if eof(A) goto EofA
  96996. ** yield coB
  96997. ** if eof(B) goto EofB
  96998. ** Cmpr: Compare A, B
  96999. ** Jump AltB, AeqB, AgtB
  97000. ** End: ...
  97001. **
  97002. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  97003. ** actually called using Gosub and they do not Return. EofA and EofB loop
  97004. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  97005. ** and AgtB jump to either L2 or to one of EofA or EofB.
  97006. */
  97007. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  97008. static int multiSelectOrderBy(
  97009. Parse *pParse, /* Parsing context */
  97010. Select *p, /* The right-most of SELECTs to be coded */
  97011. SelectDest *pDest /* What to do with query results */
  97012. ){
  97013. int i, j; /* Loop counters */
  97014. Select *pPrior; /* Another SELECT immediately to our left */
  97015. Vdbe *v; /* Generate code to this VDBE */
  97016. SelectDest destA; /* Destination for coroutine A */
  97017. SelectDest destB; /* Destination for coroutine B */
  97018. int regAddrA; /* Address register for select-A coroutine */
  97019. int regEofA; /* Flag to indicate when select-A is complete */
  97020. int regAddrB; /* Address register for select-B coroutine */
  97021. int regEofB; /* Flag to indicate when select-B is complete */
  97022. int addrSelectA; /* Address of the select-A coroutine */
  97023. int addrSelectB; /* Address of the select-B coroutine */
  97024. int regOutA; /* Address register for the output-A subroutine */
  97025. int regOutB; /* Address register for the output-B subroutine */
  97026. int addrOutA; /* Address of the output-A subroutine */
  97027. int addrOutB = 0; /* Address of the output-B subroutine */
  97028. int addrEofA; /* Address of the select-A-exhausted subroutine */
  97029. int addrEofB; /* Address of the select-B-exhausted subroutine */
  97030. int addrAltB; /* Address of the A<B subroutine */
  97031. int addrAeqB; /* Address of the A==B subroutine */
  97032. int addrAgtB; /* Address of the A>B subroutine */
  97033. int regLimitA; /* Limit register for select-A */
  97034. int regLimitB; /* Limit register for select-A */
  97035. int regPrev; /* A range of registers to hold previous output */
  97036. int savedLimit; /* Saved value of p->iLimit */
  97037. int savedOffset; /* Saved value of p->iOffset */
  97038. int labelCmpr; /* Label for the start of the merge algorithm */
  97039. int labelEnd; /* Label for the end of the overall SELECT stmt */
  97040. int j1; /* Jump instructions that get retargetted */
  97041. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  97042. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  97043. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  97044. sqlite3 *db; /* Database connection */
  97045. ExprList *pOrderBy; /* The ORDER BY clause */
  97046. int nOrderBy; /* Number of terms in the ORDER BY clause */
  97047. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  97048. #ifndef SQLITE_OMIT_EXPLAIN
  97049. int iSub1; /* EQP id of left-hand query */
  97050. int iSub2; /* EQP id of right-hand query */
  97051. #endif
  97052. assert( p->pOrderBy!=0 );
  97053. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  97054. db = pParse->db;
  97055. v = pParse->pVdbe;
  97056. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  97057. labelEnd = sqlite3VdbeMakeLabel(v);
  97058. labelCmpr = sqlite3VdbeMakeLabel(v);
  97059. /* Patch up the ORDER BY clause
  97060. */
  97061. op = p->op;
  97062. pPrior = p->pPrior;
  97063. assert( pPrior->pOrderBy==0 );
  97064. pOrderBy = p->pOrderBy;
  97065. assert( pOrderBy );
  97066. nOrderBy = pOrderBy->nExpr;
  97067. /* For operators other than UNION ALL we have to make sure that
  97068. ** the ORDER BY clause covers every term of the result set. Add
  97069. ** terms to the ORDER BY clause as necessary.
  97070. */
  97071. if( op!=TK_ALL ){
  97072. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  97073. struct ExprList_item *pItem;
  97074. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  97075. assert( pItem->iOrderByCol>0 );
  97076. if( pItem->iOrderByCol==i ) break;
  97077. }
  97078. if( j==nOrderBy ){
  97079. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  97080. if( pNew==0 ) return SQLITE_NOMEM;
  97081. pNew->flags |= EP_IntValue;
  97082. pNew->u.iValue = i;
  97083. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  97084. if( pOrderBy ) pOrderBy->a[nOrderBy++].iOrderByCol = (u16)i;
  97085. }
  97086. }
  97087. }
  97088. /* Compute the comparison permutation and keyinfo that is used with
  97089. ** the permutation used to determine if the next
  97090. ** row of results comes from selectA or selectB. Also add explicit
  97091. ** collations to the ORDER BY clause terms so that when the subqueries
  97092. ** to the right and the left are evaluated, they use the correct
  97093. ** collation.
  97094. */
  97095. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  97096. if( aPermute ){
  97097. struct ExprList_item *pItem;
  97098. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  97099. assert( pItem->iOrderByCol>0 && pItem->iOrderByCol<=p->pEList->nExpr );
  97100. aPermute[i] = pItem->iOrderByCol - 1;
  97101. }
  97102. pKeyMerge = sqlite3KeyInfoAlloc(db, nOrderBy);
  97103. if( pKeyMerge ){
  97104. for(i=0; i<nOrderBy; i++){
  97105. CollSeq *pColl;
  97106. Expr *pTerm = pOrderBy->a[i].pExpr;
  97107. if( pTerm->flags & EP_Collate ){
  97108. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  97109. }else{
  97110. pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
  97111. if( pColl==0 ) pColl = db->pDfltColl;
  97112. pOrderBy->a[i].pExpr =
  97113. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  97114. }
  97115. pKeyMerge->aColl[i] = pColl;
  97116. pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  97117. }
  97118. }
  97119. }else{
  97120. pKeyMerge = 0;
  97121. }
  97122. /* Reattach the ORDER BY clause to the query.
  97123. */
  97124. p->pOrderBy = pOrderBy;
  97125. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  97126. /* Allocate a range of temporary registers and the KeyInfo needed
  97127. ** for the logic that removes duplicate result rows when the
  97128. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  97129. */
  97130. if( op==TK_ALL ){
  97131. regPrev = 0;
  97132. }else{
  97133. int nExpr = p->pEList->nExpr;
  97134. assert( nOrderBy>=nExpr || db->mallocFailed );
  97135. regPrev = pParse->nMem+1;
  97136. pParse->nMem += nExpr+1;
  97137. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  97138. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr);
  97139. if( pKeyDup ){
  97140. for(i=0; i<nExpr; i++){
  97141. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  97142. pKeyDup->aSortOrder[i] = 0;
  97143. }
  97144. }
  97145. }
  97146. /* Separate the left and the right query from one another
  97147. */
  97148. p->pPrior = 0;
  97149. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  97150. if( pPrior->pPrior==0 ){
  97151. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  97152. }
  97153. /* Compute the limit registers */
  97154. computeLimitRegisters(pParse, p, labelEnd);
  97155. if( p->iLimit && op==TK_ALL ){
  97156. regLimitA = ++pParse->nMem;
  97157. regLimitB = ++pParse->nMem;
  97158. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  97159. regLimitA);
  97160. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  97161. }else{
  97162. regLimitA = regLimitB = 0;
  97163. }
  97164. sqlite3ExprDelete(db, p->pLimit);
  97165. p->pLimit = 0;
  97166. sqlite3ExprDelete(db, p->pOffset);
  97167. p->pOffset = 0;
  97168. regAddrA = ++pParse->nMem;
  97169. regEofA = ++pParse->nMem;
  97170. regAddrB = ++pParse->nMem;
  97171. regEofB = ++pParse->nMem;
  97172. regOutA = ++pParse->nMem;
  97173. regOutB = ++pParse->nMem;
  97174. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  97175. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  97176. /* Jump past the various subroutines and coroutines to the main
  97177. ** merge loop
  97178. */
  97179. j1 = sqlite3VdbeAddOp0(v, OP_Goto);
  97180. addrSelectA = sqlite3VdbeCurrentAddr(v);
  97181. /* Generate a coroutine to evaluate the SELECT statement to the
  97182. ** left of the compound operator - the "A" select.
  97183. */
  97184. VdbeNoopComment((v, "Begin coroutine for left SELECT"));
  97185. pPrior->iLimit = regLimitA;
  97186. explainSetInteger(iSub1, pParse->iNextSelectId);
  97187. sqlite3Select(pParse, pPrior, &destA);
  97188. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
  97189. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97190. VdbeNoopComment((v, "End coroutine for left SELECT"));
  97191. /* Generate a coroutine to evaluate the SELECT statement on
  97192. ** the right - the "B" select
  97193. */
  97194. addrSelectB = sqlite3VdbeCurrentAddr(v);
  97195. VdbeNoopComment((v, "Begin coroutine for right SELECT"));
  97196. savedLimit = p->iLimit;
  97197. savedOffset = p->iOffset;
  97198. p->iLimit = regLimitB;
  97199. p->iOffset = 0;
  97200. explainSetInteger(iSub2, pParse->iNextSelectId);
  97201. sqlite3Select(pParse, p, &destB);
  97202. p->iLimit = savedLimit;
  97203. p->iOffset = savedOffset;
  97204. sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
  97205. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97206. VdbeNoopComment((v, "End coroutine for right SELECT"));
  97207. /* Generate a subroutine that outputs the current row of the A
  97208. ** select as the next output row of the compound select.
  97209. */
  97210. VdbeNoopComment((v, "Output routine for A"));
  97211. addrOutA = generateOutputSubroutine(pParse,
  97212. p, &destA, pDest, regOutA,
  97213. regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
  97214. /* Generate a subroutine that outputs the current row of the B
  97215. ** select as the next output row of the compound select.
  97216. */
  97217. if( op==TK_ALL || op==TK_UNION ){
  97218. VdbeNoopComment((v, "Output routine for B"));
  97219. addrOutB = generateOutputSubroutine(pParse,
  97220. p, &destB, pDest, regOutB,
  97221. regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
  97222. }
  97223. /* Generate a subroutine to run when the results from select A
  97224. ** are exhausted and only data in select B remains.
  97225. */
  97226. VdbeNoopComment((v, "eof-A subroutine"));
  97227. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  97228. addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
  97229. }else{
  97230. addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
  97231. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  97232. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97233. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  97234. p->nSelectRow += pPrior->nSelectRow;
  97235. }
  97236. /* Generate a subroutine to run when the results from select B
  97237. ** are exhausted and only data in select A remains.
  97238. */
  97239. if( op==TK_INTERSECT ){
  97240. addrEofB = addrEofA;
  97241. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  97242. }else{
  97243. VdbeNoopComment((v, "eof-B subroutine"));
  97244. addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
  97245. sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  97246. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97247. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  97248. }
  97249. /* Generate code to handle the case of A<B
  97250. */
  97251. VdbeNoopComment((v, "A-lt-B subroutine"));
  97252. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  97253. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97254. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97255. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97256. /* Generate code to handle the case of A==B
  97257. */
  97258. if( op==TK_ALL ){
  97259. addrAeqB = addrAltB;
  97260. }else if( op==TK_INTERSECT ){
  97261. addrAeqB = addrAltB;
  97262. addrAltB++;
  97263. }else{
  97264. VdbeNoopComment((v, "A-eq-B subroutine"));
  97265. addrAeqB =
  97266. sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
  97267. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97268. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97269. }
  97270. /* Generate code to handle the case of A>B
  97271. */
  97272. VdbeNoopComment((v, "A-gt-B subroutine"));
  97273. addrAgtB = sqlite3VdbeCurrentAddr(v);
  97274. if( op==TK_ALL || op==TK_UNION ){
  97275. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  97276. }
  97277. sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
  97278. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  97279. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  97280. /* This code runs once to initialize everything.
  97281. */
  97282. sqlite3VdbeJumpHere(v, j1);
  97283. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
  97284. sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
  97285. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
  97286. sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
  97287. sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
  97288. sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
  97289. /* Implement the main merge loop
  97290. */
  97291. sqlite3VdbeResolveLabel(v, labelCmpr);
  97292. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  97293. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  97294. (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
  97295. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  97296. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
  97297. /* Jump to the this point in order to terminate the query.
  97298. */
  97299. sqlite3VdbeResolveLabel(v, labelEnd);
  97300. /* Set the number of output columns
  97301. */
  97302. if( pDest->eDest==SRT_Output ){
  97303. Select *pFirst = pPrior;
  97304. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  97305. generateColumnNames(pParse, 0, pFirst->pEList);
  97306. }
  97307. /* Reassembly the compound query so that it will be freed correctly
  97308. ** by the calling function */
  97309. if( p->pPrior ){
  97310. sqlite3SelectDelete(db, p->pPrior);
  97311. }
  97312. p->pPrior = pPrior;
  97313. /*** TBD: Insert subroutine calls to close cursors on incomplete
  97314. **** subqueries ****/
  97315. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  97316. return SQLITE_OK;
  97317. }
  97318. #endif
  97319. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  97320. /* Forward Declarations */
  97321. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  97322. static void substSelect(sqlite3*, Select *, int, ExprList *);
  97323. /*
  97324. ** Scan through the expression pExpr. Replace every reference to
  97325. ** a column in table number iTable with a copy of the iColumn-th
  97326. ** entry in pEList. (But leave references to the ROWID column
  97327. ** unchanged.)
  97328. **
  97329. ** This routine is part of the flattening procedure. A subquery
  97330. ** whose result set is defined by pEList appears as entry in the
  97331. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  97332. ** FORM clause entry is iTable. This routine make the necessary
  97333. ** changes to pExpr so that it refers directly to the source table
  97334. ** of the subquery rather the result set of the subquery.
  97335. */
  97336. static Expr *substExpr(
  97337. sqlite3 *db, /* Report malloc errors to this connection */
  97338. Expr *pExpr, /* Expr in which substitution occurs */
  97339. int iTable, /* Table to be substituted */
  97340. ExprList *pEList /* Substitute expressions */
  97341. ){
  97342. if( pExpr==0 ) return 0;
  97343. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  97344. if( pExpr->iColumn<0 ){
  97345. pExpr->op = TK_NULL;
  97346. }else{
  97347. Expr *pNew;
  97348. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  97349. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  97350. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  97351. sqlite3ExprDelete(db, pExpr);
  97352. pExpr = pNew;
  97353. }
  97354. }else{
  97355. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  97356. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  97357. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  97358. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  97359. }else{
  97360. substExprList(db, pExpr->x.pList, iTable, pEList);
  97361. }
  97362. }
  97363. return pExpr;
  97364. }
  97365. static void substExprList(
  97366. sqlite3 *db, /* Report malloc errors here */
  97367. ExprList *pList, /* List to scan and in which to make substitutes */
  97368. int iTable, /* Table to be substituted */
  97369. ExprList *pEList /* Substitute values */
  97370. ){
  97371. int i;
  97372. if( pList==0 ) return;
  97373. for(i=0; i<pList->nExpr; i++){
  97374. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  97375. }
  97376. }
  97377. static void substSelect(
  97378. sqlite3 *db, /* Report malloc errors here */
  97379. Select *p, /* SELECT statement in which to make substitutions */
  97380. int iTable, /* Table to be replaced */
  97381. ExprList *pEList /* Substitute values */
  97382. ){
  97383. SrcList *pSrc;
  97384. struct SrcList_item *pItem;
  97385. int i;
  97386. if( !p ) return;
  97387. substExprList(db, p->pEList, iTable, pEList);
  97388. substExprList(db, p->pGroupBy, iTable, pEList);
  97389. substExprList(db, p->pOrderBy, iTable, pEList);
  97390. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  97391. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  97392. substSelect(db, p->pPrior, iTable, pEList);
  97393. pSrc = p->pSrc;
  97394. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  97395. if( ALWAYS(pSrc) ){
  97396. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  97397. substSelect(db, pItem->pSelect, iTable, pEList);
  97398. }
  97399. }
  97400. }
  97401. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  97402. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  97403. /*
  97404. ** This routine attempts to flatten subqueries as a performance optimization.
  97405. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  97406. **
  97407. ** To understand the concept of flattening, consider the following
  97408. ** query:
  97409. **
  97410. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  97411. **
  97412. ** The default way of implementing this query is to execute the
  97413. ** subquery first and store the results in a temporary table, then
  97414. ** run the outer query on that temporary table. This requires two
  97415. ** passes over the data. Furthermore, because the temporary table
  97416. ** has no indices, the WHERE clause on the outer query cannot be
  97417. ** optimized.
  97418. **
  97419. ** This routine attempts to rewrite queries such as the above into
  97420. ** a single flat select, like this:
  97421. **
  97422. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  97423. **
  97424. ** The code generated for this simpification gives the same result
  97425. ** but only has to scan the data once. And because indices might
  97426. ** exist on the table t1, a complete scan of the data might be
  97427. ** avoided.
  97428. **
  97429. ** Flattening is only attempted if all of the following are true:
  97430. **
  97431. ** (1) The subquery and the outer query do not both use aggregates.
  97432. **
  97433. ** (2) The subquery is not an aggregate or the outer query is not a join.
  97434. **
  97435. ** (3) The subquery is not the right operand of a left outer join
  97436. ** (Originally ticket #306. Strengthened by ticket #3300)
  97437. **
  97438. ** (4) The subquery is not DISTINCT.
  97439. **
  97440. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  97441. ** sub-queries that were excluded from this optimization. Restriction
  97442. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  97443. **
  97444. ** (6) The subquery does not use aggregates or the outer query is not
  97445. ** DISTINCT.
  97446. **
  97447. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  97448. ** A FROM clause, consider adding a FROM close with the special
  97449. ** table sqlite_once that consists of a single row containing a
  97450. ** single NULL.
  97451. **
  97452. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  97453. **
  97454. ** (9) The subquery does not use LIMIT or the outer query does not use
  97455. ** aggregates.
  97456. **
  97457. ** (10) The subquery does not use aggregates or the outer query does not
  97458. ** use LIMIT.
  97459. **
  97460. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  97461. **
  97462. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  97463. ** a separate restriction deriving from ticket #350.
  97464. **
  97465. ** (13) The subquery and outer query do not both use LIMIT.
  97466. **
  97467. ** (14) The subquery does not use OFFSET.
  97468. **
  97469. ** (15) The outer query is not part of a compound select or the
  97470. ** subquery does not have a LIMIT clause.
  97471. ** (See ticket #2339 and ticket [02a8e81d44]).
  97472. **
  97473. ** (16) The outer query is not an aggregate or the subquery does
  97474. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  97475. ** until we introduced the group_concat() function.
  97476. **
  97477. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  97478. ** compound clause made up entirely of non-aggregate queries, and
  97479. ** the parent query:
  97480. **
  97481. ** * is not itself part of a compound select,
  97482. ** * is not an aggregate or DISTINCT query, and
  97483. ** * is not a join
  97484. **
  97485. ** The parent and sub-query may contain WHERE clauses. Subject to
  97486. ** rules (11), (13) and (14), they may also contain ORDER BY,
  97487. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  97488. ** operator other than UNION ALL because all the other compound
  97489. ** operators have an implied DISTINCT which is disallowed by
  97490. ** restriction (4).
  97491. **
  97492. ** Also, each component of the sub-query must return the same number
  97493. ** of result columns. This is actually a requirement for any compound
  97494. ** SELECT statement, but all the code here does is make sure that no
  97495. ** such (illegal) sub-query is flattened. The caller will detect the
  97496. ** syntax error and return a detailed message.
  97497. **
  97498. ** (18) If the sub-query is a compound select, then all terms of the
  97499. ** ORDER by clause of the parent must be simple references to
  97500. ** columns of the sub-query.
  97501. **
  97502. ** (19) The subquery does not use LIMIT or the outer query does not
  97503. ** have a WHERE clause.
  97504. **
  97505. ** (20) If the sub-query is a compound select, then it must not use
  97506. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  97507. ** somewhat by saying that the terms of the ORDER BY clause must
  97508. ** appear as unmodified result columns in the outer query. But we
  97509. ** have other optimizations in mind to deal with that case.
  97510. **
  97511. ** (21) The subquery does not use LIMIT or the outer query is not
  97512. ** DISTINCT. (See ticket [752e1646fc]).
  97513. **
  97514. ** In this routine, the "p" parameter is a pointer to the outer query.
  97515. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  97516. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  97517. **
  97518. ** If flattening is not attempted, this routine is a no-op and returns 0.
  97519. ** If flattening is attempted this routine returns 1.
  97520. **
  97521. ** All of the expression analysis must occur on both the outer query and
  97522. ** the subquery before this routine runs.
  97523. */
  97524. static int flattenSubquery(
  97525. Parse *pParse, /* Parsing context */
  97526. Select *p, /* The parent or outer SELECT statement */
  97527. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  97528. int isAgg, /* True if outer SELECT uses aggregate functions */
  97529. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  97530. ){
  97531. const char *zSavedAuthContext = pParse->zAuthContext;
  97532. Select *pParent;
  97533. Select *pSub; /* The inner query or "subquery" */
  97534. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  97535. SrcList *pSrc; /* The FROM clause of the outer query */
  97536. SrcList *pSubSrc; /* The FROM clause of the subquery */
  97537. ExprList *pList; /* The result set of the outer query */
  97538. int iParent; /* VDBE cursor number of the pSub result set temp table */
  97539. int i; /* Loop counter */
  97540. Expr *pWhere; /* The WHERE clause */
  97541. struct SrcList_item *pSubitem; /* The subquery */
  97542. sqlite3 *db = pParse->db;
  97543. /* Check to see if flattening is permitted. Return 0 if not.
  97544. */
  97545. assert( p!=0 );
  97546. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  97547. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  97548. pSrc = p->pSrc;
  97549. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  97550. pSubitem = &pSrc->a[iFrom];
  97551. iParent = pSubitem->iCursor;
  97552. pSub = pSubitem->pSelect;
  97553. assert( pSub!=0 );
  97554. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  97555. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  97556. pSubSrc = pSub->pSrc;
  97557. assert( pSubSrc );
  97558. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  97559. ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
  97560. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  97561. ** became arbitrary expressions, we were forced to add restrictions (13)
  97562. ** and (14). */
  97563. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  97564. if( pSub->pOffset ) return 0; /* Restriction (14) */
  97565. if( p->pRightmost && pSub->pLimit ){
  97566. return 0; /* Restriction (15) */
  97567. }
  97568. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  97569. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  97570. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  97571. return 0; /* Restrictions (8)(9) */
  97572. }
  97573. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  97574. return 0; /* Restriction (6) */
  97575. }
  97576. if( p->pOrderBy && pSub->pOrderBy ){
  97577. return 0; /* Restriction (11) */
  97578. }
  97579. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  97580. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  97581. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  97582. return 0; /* Restriction (21) */
  97583. }
  97584. /* OBSOLETE COMMENT 1:
  97585. ** Restriction 3: If the subquery is a join, make sure the subquery is
  97586. ** not used as the right operand of an outer join. Examples of why this
  97587. ** is not allowed:
  97588. **
  97589. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  97590. **
  97591. ** If we flatten the above, we would get
  97592. **
  97593. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  97594. **
  97595. ** which is not at all the same thing.
  97596. **
  97597. ** OBSOLETE COMMENT 2:
  97598. ** Restriction 12: If the subquery is the right operand of a left outer
  97599. ** join, make sure the subquery has no WHERE clause.
  97600. ** An examples of why this is not allowed:
  97601. **
  97602. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  97603. **
  97604. ** If we flatten the above, we would get
  97605. **
  97606. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  97607. **
  97608. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  97609. ** effectively converts the OUTER JOIN into an INNER JOIN.
  97610. **
  97611. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  97612. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  97613. ** is fraught with danger. Best to avoid the whole thing. If the
  97614. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  97615. */
  97616. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  97617. return 0;
  97618. }
  97619. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  97620. ** use only the UNION ALL operator. And none of the simple select queries
  97621. ** that make up the compound SELECT are allowed to be aggregate or distinct
  97622. ** queries.
  97623. */
  97624. if( pSub->pPrior ){
  97625. if( pSub->pOrderBy ){
  97626. return 0; /* Restriction 20 */
  97627. }
  97628. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  97629. return 0;
  97630. }
  97631. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  97632. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  97633. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  97634. assert( pSub->pSrc!=0 );
  97635. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  97636. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  97637. || pSub1->pSrc->nSrc<1
  97638. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  97639. ){
  97640. return 0;
  97641. }
  97642. testcase( pSub1->pSrc->nSrc>1 );
  97643. }
  97644. /* Restriction 18. */
  97645. if( p->pOrderBy ){
  97646. int ii;
  97647. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  97648. if( p->pOrderBy->a[ii].iOrderByCol==0 ) return 0;
  97649. }
  97650. }
  97651. }
  97652. /***** If we reach this point, flattening is permitted. *****/
  97653. /* Authorize the subquery */
  97654. pParse->zAuthContext = pSubitem->zName;
  97655. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  97656. testcase( i==SQLITE_DENY );
  97657. pParse->zAuthContext = zSavedAuthContext;
  97658. /* If the sub-query is a compound SELECT statement, then (by restrictions
  97659. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  97660. ** be of the form:
  97661. **
  97662. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  97663. **
  97664. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  97665. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  97666. ** OFFSET clauses and joins them to the left-hand-side of the original
  97667. ** using UNION ALL operators. In this case N is the number of simple
  97668. ** select statements in the compound sub-query.
  97669. **
  97670. ** Example:
  97671. **
  97672. ** SELECT a+1 FROM (
  97673. ** SELECT x FROM tab
  97674. ** UNION ALL
  97675. ** SELECT y FROM tab
  97676. ** UNION ALL
  97677. ** SELECT abs(z*2) FROM tab2
  97678. ** ) WHERE a!=5 ORDER BY 1
  97679. **
  97680. ** Transformed into:
  97681. **
  97682. ** SELECT x+1 FROM tab WHERE x+1!=5
  97683. ** UNION ALL
  97684. ** SELECT y+1 FROM tab WHERE y+1!=5
  97685. ** UNION ALL
  97686. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  97687. ** ORDER BY 1
  97688. **
  97689. ** We call this the "compound-subquery flattening".
  97690. */
  97691. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  97692. Select *pNew;
  97693. ExprList *pOrderBy = p->pOrderBy;
  97694. Expr *pLimit = p->pLimit;
  97695. Expr *pOffset = p->pOffset;
  97696. Select *pPrior = p->pPrior;
  97697. p->pOrderBy = 0;
  97698. p->pSrc = 0;
  97699. p->pPrior = 0;
  97700. p->pLimit = 0;
  97701. p->pOffset = 0;
  97702. pNew = sqlite3SelectDup(db, p, 0);
  97703. p->pOffset = pOffset;
  97704. p->pLimit = pLimit;
  97705. p->pOrderBy = pOrderBy;
  97706. p->pSrc = pSrc;
  97707. p->op = TK_ALL;
  97708. p->pRightmost = 0;
  97709. if( pNew==0 ){
  97710. pNew = pPrior;
  97711. }else{
  97712. pNew->pPrior = pPrior;
  97713. pNew->pRightmost = 0;
  97714. }
  97715. p->pPrior = pNew;
  97716. if( db->mallocFailed ) return 1;
  97717. }
  97718. /* Begin flattening the iFrom-th entry of the FROM clause
  97719. ** in the outer query.
  97720. */
  97721. pSub = pSub1 = pSubitem->pSelect;
  97722. /* Delete the transient table structure associated with the
  97723. ** subquery
  97724. */
  97725. sqlite3DbFree(db, pSubitem->zDatabase);
  97726. sqlite3DbFree(db, pSubitem->zName);
  97727. sqlite3DbFree(db, pSubitem->zAlias);
  97728. pSubitem->zDatabase = 0;
  97729. pSubitem->zName = 0;
  97730. pSubitem->zAlias = 0;
  97731. pSubitem->pSelect = 0;
  97732. /* Defer deleting the Table object associated with the
  97733. ** subquery until code generation is
  97734. ** complete, since there may still exist Expr.pTab entries that
  97735. ** refer to the subquery even after flattening. Ticket #3346.
  97736. **
  97737. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  97738. */
  97739. if( ALWAYS(pSubitem->pTab!=0) ){
  97740. Table *pTabToDel = pSubitem->pTab;
  97741. if( pTabToDel->nRef==1 ){
  97742. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  97743. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  97744. pToplevel->pZombieTab = pTabToDel;
  97745. }else{
  97746. pTabToDel->nRef--;
  97747. }
  97748. pSubitem->pTab = 0;
  97749. }
  97750. /* The following loop runs once for each term in a compound-subquery
  97751. ** flattening (as described above). If we are doing a different kind
  97752. ** of flattening - a flattening other than a compound-subquery flattening -
  97753. ** then this loop only runs once.
  97754. **
  97755. ** This loop moves all of the FROM elements of the subquery into the
  97756. ** the FROM clause of the outer query. Before doing this, remember
  97757. ** the cursor number for the original outer query FROM element in
  97758. ** iParent. The iParent cursor will never be used. Subsequent code
  97759. ** will scan expressions looking for iParent references and replace
  97760. ** those references with expressions that resolve to the subquery FROM
  97761. ** elements we are now copying in.
  97762. */
  97763. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  97764. int nSubSrc;
  97765. u8 jointype = 0;
  97766. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  97767. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  97768. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  97769. if( pSrc ){
  97770. assert( pParent==p ); /* First time through the loop */
  97771. jointype = pSubitem->jointype;
  97772. }else{
  97773. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  97774. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  97775. if( pSrc==0 ){
  97776. assert( db->mallocFailed );
  97777. break;
  97778. }
  97779. }
  97780. /* The subquery uses a single slot of the FROM clause of the outer
  97781. ** query. If the subquery has more than one element in its FROM clause,
  97782. ** then expand the outer query to make space for it to hold all elements
  97783. ** of the subquery.
  97784. **
  97785. ** Example:
  97786. **
  97787. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  97788. **
  97789. ** The outer query has 3 slots in its FROM clause. One slot of the
  97790. ** outer query (the middle slot) is used by the subquery. The next
  97791. ** block of code will expand the out query to 4 slots. The middle
  97792. ** slot is expanded to two slots in order to make space for the
  97793. ** two elements in the FROM clause of the subquery.
  97794. */
  97795. if( nSubSrc>1 ){
  97796. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  97797. if( db->mallocFailed ){
  97798. break;
  97799. }
  97800. }
  97801. /* Transfer the FROM clause terms from the subquery into the
  97802. ** outer query.
  97803. */
  97804. for(i=0; i<nSubSrc; i++){
  97805. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  97806. pSrc->a[i+iFrom] = pSubSrc->a[i];
  97807. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  97808. }
  97809. pSrc->a[iFrom].jointype = jointype;
  97810. /* Now begin substituting subquery result set expressions for
  97811. ** references to the iParent in the outer query.
  97812. **
  97813. ** Example:
  97814. **
  97815. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  97816. ** \ \_____________ subquery __________/ /
  97817. ** \_____________________ outer query ______________________________/
  97818. **
  97819. ** We look at every expression in the outer query and every place we see
  97820. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  97821. */
  97822. pList = pParent->pEList;
  97823. for(i=0; i<pList->nExpr; i++){
  97824. if( pList->a[i].zName==0 ){
  97825. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  97826. sqlite3Dequote(zName);
  97827. pList->a[i].zName = zName;
  97828. }
  97829. }
  97830. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  97831. if( isAgg ){
  97832. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  97833. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  97834. }
  97835. if( pSub->pOrderBy ){
  97836. assert( pParent->pOrderBy==0 );
  97837. pParent->pOrderBy = pSub->pOrderBy;
  97838. pSub->pOrderBy = 0;
  97839. }else if( pParent->pOrderBy ){
  97840. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  97841. }
  97842. if( pSub->pWhere ){
  97843. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  97844. }else{
  97845. pWhere = 0;
  97846. }
  97847. if( subqueryIsAgg ){
  97848. assert( pParent->pHaving==0 );
  97849. pParent->pHaving = pParent->pWhere;
  97850. pParent->pWhere = pWhere;
  97851. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  97852. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  97853. sqlite3ExprDup(db, pSub->pHaving, 0));
  97854. assert( pParent->pGroupBy==0 );
  97855. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  97856. }else{
  97857. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  97858. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  97859. }
  97860. /* The flattened query is distinct if either the inner or the
  97861. ** outer query is distinct.
  97862. */
  97863. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  97864. /*
  97865. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  97866. **
  97867. ** One is tempted to try to add a and b to combine the limits. But this
  97868. ** does not work if either limit is negative.
  97869. */
  97870. if( pSub->pLimit ){
  97871. pParent->pLimit = pSub->pLimit;
  97872. pSub->pLimit = 0;
  97873. }
  97874. }
  97875. /* Finially, delete what is left of the subquery and return
  97876. ** success.
  97877. */
  97878. sqlite3SelectDelete(db, pSub1);
  97879. return 1;
  97880. }
  97881. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  97882. /*
  97883. ** Based on the contents of the AggInfo structure indicated by the first
  97884. ** argument, this function checks if the following are true:
  97885. **
  97886. ** * the query contains just a single aggregate function,
  97887. ** * the aggregate function is either min() or max(), and
  97888. ** * the argument to the aggregate function is a column value.
  97889. **
  97890. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  97891. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  97892. ** list of arguments passed to the aggregate before returning.
  97893. **
  97894. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  97895. ** WHERE_ORDERBY_NORMAL is returned.
  97896. */
  97897. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  97898. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  97899. *ppMinMax = 0;
  97900. if( pAggInfo->nFunc==1 ){
  97901. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  97902. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  97903. assert( pExpr->op==TK_AGG_FUNCTION );
  97904. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  97905. const char *zFunc = pExpr->u.zToken;
  97906. if( sqlite3StrICmp(zFunc, "min")==0 ){
  97907. eRet = WHERE_ORDERBY_MIN;
  97908. *ppMinMax = pEList;
  97909. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  97910. eRet = WHERE_ORDERBY_MAX;
  97911. *ppMinMax = pEList;
  97912. }
  97913. }
  97914. }
  97915. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  97916. return eRet;
  97917. }
  97918. /*
  97919. ** The select statement passed as the first argument is an aggregate query.
  97920. ** The second argment is the associated aggregate-info object. This
  97921. ** function tests if the SELECT is of the form:
  97922. **
  97923. ** SELECT count(*) FROM <tbl>
  97924. **
  97925. ** where table is a database table, not a sub-select or view. If the query
  97926. ** does match this pattern, then a pointer to the Table object representing
  97927. ** <tbl> is returned. Otherwise, 0 is returned.
  97928. */
  97929. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  97930. Table *pTab;
  97931. Expr *pExpr;
  97932. assert( !p->pGroupBy );
  97933. if( p->pWhere || p->pEList->nExpr!=1
  97934. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  97935. ){
  97936. return 0;
  97937. }
  97938. pTab = p->pSrc->a[0].pTab;
  97939. pExpr = p->pEList->a[0].pExpr;
  97940. assert( pTab && !pTab->pSelect && pExpr );
  97941. if( IsVirtual(pTab) ) return 0;
  97942. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  97943. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  97944. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  97945. if( pExpr->flags&EP_Distinct ) return 0;
  97946. return pTab;
  97947. }
  97948. /*
  97949. ** If the source-list item passed as an argument was augmented with an
  97950. ** INDEXED BY clause, then try to locate the specified index. If there
  97951. ** was such a clause and the named index cannot be found, return
  97952. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  97953. ** pFrom->pIndex and return SQLITE_OK.
  97954. */
  97955. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  97956. if( pFrom->pTab && pFrom->zIndex ){
  97957. Table *pTab = pFrom->pTab;
  97958. char *zIndex = pFrom->zIndex;
  97959. Index *pIdx;
  97960. for(pIdx=pTab->pIndex;
  97961. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  97962. pIdx=pIdx->pNext
  97963. );
  97964. if( !pIdx ){
  97965. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  97966. pParse->checkSchema = 1;
  97967. return SQLITE_ERROR;
  97968. }
  97969. pFrom->pIndex = pIdx;
  97970. }
  97971. return SQLITE_OK;
  97972. }
  97973. /*
  97974. ** Detect compound SELECT statements that use an ORDER BY clause with
  97975. ** an alternative collating sequence.
  97976. **
  97977. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  97978. **
  97979. ** These are rewritten as a subquery:
  97980. **
  97981. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  97982. ** ORDER BY ... COLLATE ...
  97983. **
  97984. ** This transformation is necessary because the multiSelectOrderBy() routine
  97985. ** above that generates the code for a compound SELECT with an ORDER BY clause
  97986. ** uses a merge algorithm that requires the same collating sequence on the
  97987. ** result columns as on the ORDER BY clause. See ticket
  97988. ** http://www.sqlite.org/src/info/6709574d2a
  97989. **
  97990. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  97991. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  97992. ** there are COLLATE terms in the ORDER BY.
  97993. */
  97994. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  97995. int i;
  97996. Select *pNew;
  97997. Select *pX;
  97998. sqlite3 *db;
  97999. struct ExprList_item *a;
  98000. SrcList *pNewSrc;
  98001. Parse *pParse;
  98002. Token dummy;
  98003. if( p->pPrior==0 ) return WRC_Continue;
  98004. if( p->pOrderBy==0 ) return WRC_Continue;
  98005. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  98006. if( pX==0 ) return WRC_Continue;
  98007. a = p->pOrderBy->a;
  98008. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  98009. if( a[i].pExpr->flags & EP_Collate ) break;
  98010. }
  98011. if( i<0 ) return WRC_Continue;
  98012. /* If we reach this point, that means the transformation is required. */
  98013. pParse = pWalker->pParse;
  98014. db = pParse->db;
  98015. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  98016. if( pNew==0 ) return WRC_Abort;
  98017. memset(&dummy, 0, sizeof(dummy));
  98018. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  98019. if( pNewSrc==0 ) return WRC_Abort;
  98020. *pNew = *p;
  98021. p->pSrc = pNewSrc;
  98022. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  98023. p->op = TK_SELECT;
  98024. p->pWhere = 0;
  98025. pNew->pGroupBy = 0;
  98026. pNew->pHaving = 0;
  98027. pNew->pOrderBy = 0;
  98028. p->pPrior = 0;
  98029. pNew->pLimit = 0;
  98030. pNew->pOffset = 0;
  98031. return WRC_Continue;
  98032. }
  98033. /*
  98034. ** This routine is a Walker callback for "expanding" a SELECT statement.
  98035. ** "Expanding" means to do the following:
  98036. **
  98037. ** (1) Make sure VDBE cursor numbers have been assigned to every
  98038. ** element of the FROM clause.
  98039. **
  98040. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  98041. ** defines FROM clause. When views appear in the FROM clause,
  98042. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  98043. ** that implements the view. A copy is made of the view's SELECT
  98044. ** statement so that we can freely modify or delete that statement
  98045. ** without worrying about messing up the presistent representation
  98046. ** of the view.
  98047. **
  98048. ** (3) Add terms to the WHERE clause to accomodate the NATURAL keyword
  98049. ** on joins and the ON and USING clause of joins.
  98050. **
  98051. ** (4) Scan the list of columns in the result set (pEList) looking
  98052. ** for instances of the "*" operator or the TABLE.* operator.
  98053. ** If found, expand each "*" to be every column in every table
  98054. ** and TABLE.* to be every column in TABLE.
  98055. **
  98056. */
  98057. static int selectExpander(Walker *pWalker, Select *p){
  98058. Parse *pParse = pWalker->pParse;
  98059. int i, j, k;
  98060. SrcList *pTabList;
  98061. ExprList *pEList;
  98062. struct SrcList_item *pFrom;
  98063. sqlite3 *db = pParse->db;
  98064. Expr *pE, *pRight, *pExpr;
  98065. u16 selFlags = p->selFlags;
  98066. p->selFlags |= SF_Expanded;
  98067. if( db->mallocFailed ){
  98068. return WRC_Abort;
  98069. }
  98070. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  98071. return WRC_Prune;
  98072. }
  98073. pTabList = p->pSrc;
  98074. pEList = p->pEList;
  98075. /* Make sure cursor numbers have been assigned to all entries in
  98076. ** the FROM clause of the SELECT statement.
  98077. */
  98078. sqlite3SrcListAssignCursors(pParse, pTabList);
  98079. /* Look up every table named in the FROM clause of the select. If
  98080. ** an entry of the FROM clause is a subquery instead of a table or view,
  98081. ** then create a transient table structure to describe the subquery.
  98082. */
  98083. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98084. Table *pTab;
  98085. if( pFrom->pTab!=0 ){
  98086. /* This statement has already been prepared. There is no need
  98087. ** to go further. */
  98088. assert( i==0 );
  98089. return WRC_Prune;
  98090. }
  98091. if( pFrom->zName==0 ){
  98092. #ifndef SQLITE_OMIT_SUBQUERY
  98093. Select *pSel = pFrom->pSelect;
  98094. /* A sub-query in the FROM clause of a SELECT */
  98095. assert( pSel!=0 );
  98096. assert( pFrom->pTab==0 );
  98097. sqlite3WalkSelect(pWalker, pSel);
  98098. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  98099. if( pTab==0 ) return WRC_Abort;
  98100. pTab->nRef = 1;
  98101. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  98102. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  98103. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  98104. pTab->iPKey = -1;
  98105. pTab->nRowEst = 1048576;
  98106. pTab->tabFlags |= TF_Ephemeral;
  98107. #endif
  98108. }else{
  98109. /* An ordinary table or view name in the FROM clause */
  98110. assert( pFrom->pTab==0 );
  98111. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  98112. if( pTab==0 ) return WRC_Abort;
  98113. if( pTab->nRef==0xffff ){
  98114. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  98115. pTab->zName);
  98116. pFrom->pTab = 0;
  98117. return WRC_Abort;
  98118. }
  98119. pTab->nRef++;
  98120. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  98121. if( pTab->pSelect || IsVirtual(pTab) ){
  98122. /* We reach here if the named table is a really a view */
  98123. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  98124. assert( pFrom->pSelect==0 );
  98125. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  98126. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  98127. }
  98128. #endif
  98129. }
  98130. /* Locate the index named by the INDEXED BY clause, if any. */
  98131. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  98132. return WRC_Abort;
  98133. }
  98134. }
  98135. /* Process NATURAL keywords, and ON and USING clauses of joins.
  98136. */
  98137. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  98138. return WRC_Abort;
  98139. }
  98140. /* For every "*" that occurs in the column list, insert the names of
  98141. ** all columns in all tables. And for every TABLE.* insert the names
  98142. ** of all columns in TABLE. The parser inserted a special expression
  98143. ** with the TK_ALL operator for each "*" that it found in the column list.
  98144. ** The following code just has to locate the TK_ALL expressions and expand
  98145. ** each one to the list of all columns in all tables.
  98146. **
  98147. ** The first loop just checks to see if there are any "*" operators
  98148. ** that need expanding.
  98149. */
  98150. for(k=0; k<pEList->nExpr; k++){
  98151. pE = pEList->a[k].pExpr;
  98152. if( pE->op==TK_ALL ) break;
  98153. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  98154. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  98155. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  98156. }
  98157. if( k<pEList->nExpr ){
  98158. /*
  98159. ** If we get here it means the result set contains one or more "*"
  98160. ** operators that need to be expanded. Loop through each expression
  98161. ** in the result set and expand them one by one.
  98162. */
  98163. struct ExprList_item *a = pEList->a;
  98164. ExprList *pNew = 0;
  98165. int flags = pParse->db->flags;
  98166. int longNames = (flags & SQLITE_FullColNames)!=0
  98167. && (flags & SQLITE_ShortColNames)==0;
  98168. /* When processing FROM-clause subqueries, it is always the case
  98169. ** that full_column_names=OFF and short_column_names=ON. The
  98170. ** sqlite3ResultSetOfSelect() routine makes it so. */
  98171. assert( (p->selFlags & SF_NestedFrom)==0
  98172. || ((flags & SQLITE_FullColNames)==0 &&
  98173. (flags & SQLITE_ShortColNames)!=0) );
  98174. for(k=0; k<pEList->nExpr; k++){
  98175. pE = a[k].pExpr;
  98176. pRight = pE->pRight;
  98177. assert( pE->op!=TK_DOT || pRight!=0 );
  98178. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  98179. /* This particular expression does not need to be expanded.
  98180. */
  98181. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  98182. if( pNew ){
  98183. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  98184. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  98185. a[k].zName = 0;
  98186. a[k].zSpan = 0;
  98187. }
  98188. a[k].pExpr = 0;
  98189. }else{
  98190. /* This expression is a "*" or a "TABLE.*" and needs to be
  98191. ** expanded. */
  98192. int tableSeen = 0; /* Set to 1 when TABLE matches */
  98193. char *zTName = 0; /* text of name of TABLE */
  98194. if( pE->op==TK_DOT ){
  98195. assert( pE->pLeft!=0 );
  98196. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  98197. zTName = pE->pLeft->u.zToken;
  98198. }
  98199. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98200. Table *pTab = pFrom->pTab;
  98201. Select *pSub = pFrom->pSelect;
  98202. char *zTabName = pFrom->zAlias;
  98203. const char *zSchemaName = 0;
  98204. int iDb;
  98205. if( zTabName==0 ){
  98206. zTabName = pTab->zName;
  98207. }
  98208. if( db->mallocFailed ) break;
  98209. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  98210. pSub = 0;
  98211. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  98212. continue;
  98213. }
  98214. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  98215. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  98216. }
  98217. for(j=0; j<pTab->nCol; j++){
  98218. char *zName = pTab->aCol[j].zName;
  98219. char *zColname; /* The computed column name */
  98220. char *zToFree; /* Malloced string that needs to be freed */
  98221. Token sColname; /* Computed column name as a token */
  98222. assert( zName );
  98223. if( zTName && pSub
  98224. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  98225. ){
  98226. continue;
  98227. }
  98228. /* If a column is marked as 'hidden' (currently only possible
  98229. ** for virtual tables), do not include it in the expanded
  98230. ** result-set list.
  98231. */
  98232. if( IsHiddenColumn(&pTab->aCol[j]) ){
  98233. assert(IsVirtual(pTab));
  98234. continue;
  98235. }
  98236. tableSeen = 1;
  98237. if( i>0 && zTName==0 ){
  98238. if( (pFrom->jointype & JT_NATURAL)!=0
  98239. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  98240. ){
  98241. /* In a NATURAL join, omit the join columns from the
  98242. ** table to the right of the join */
  98243. continue;
  98244. }
  98245. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  98246. /* In a join with a USING clause, omit columns in the
  98247. ** using clause from the table on the right. */
  98248. continue;
  98249. }
  98250. }
  98251. pRight = sqlite3Expr(db, TK_ID, zName);
  98252. zColname = zName;
  98253. zToFree = 0;
  98254. if( longNames || pTabList->nSrc>1 ){
  98255. Expr *pLeft;
  98256. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  98257. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  98258. if( zSchemaName ){
  98259. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  98260. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  98261. }
  98262. if( longNames ){
  98263. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  98264. zToFree = zColname;
  98265. }
  98266. }else{
  98267. pExpr = pRight;
  98268. }
  98269. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  98270. sColname.z = zColname;
  98271. sColname.n = sqlite3Strlen30(zColname);
  98272. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  98273. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  98274. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  98275. if( pSub ){
  98276. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  98277. testcase( pX->zSpan==0 );
  98278. }else{
  98279. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  98280. zSchemaName, zTabName, zColname);
  98281. testcase( pX->zSpan==0 );
  98282. }
  98283. pX->bSpanIsTab = 1;
  98284. }
  98285. sqlite3DbFree(db, zToFree);
  98286. }
  98287. }
  98288. if( !tableSeen ){
  98289. if( zTName ){
  98290. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  98291. }else{
  98292. sqlite3ErrorMsg(pParse, "no tables specified");
  98293. }
  98294. }
  98295. }
  98296. }
  98297. sqlite3ExprListDelete(db, pEList);
  98298. p->pEList = pNew;
  98299. }
  98300. #if SQLITE_MAX_COLUMN
  98301. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  98302. sqlite3ErrorMsg(pParse, "too many columns in result set");
  98303. }
  98304. #endif
  98305. return WRC_Continue;
  98306. }
  98307. /*
  98308. ** No-op routine for the parse-tree walker.
  98309. **
  98310. ** When this routine is the Walker.xExprCallback then expression trees
  98311. ** are walked without any actions being taken at each node. Presumably,
  98312. ** when this routine is used for Walker.xExprCallback then
  98313. ** Walker.xSelectCallback is set to do something useful for every
  98314. ** subquery in the parser tree.
  98315. */
  98316. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  98317. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  98318. return WRC_Continue;
  98319. }
  98320. /*
  98321. ** This routine "expands" a SELECT statement and all of its subqueries.
  98322. ** For additional information on what it means to "expand" a SELECT
  98323. ** statement, see the comment on the selectExpand worker callback above.
  98324. **
  98325. ** Expanding a SELECT statement is the first step in processing a
  98326. ** SELECT statement. The SELECT statement must be expanded before
  98327. ** name resolution is performed.
  98328. **
  98329. ** If anything goes wrong, an error message is written into pParse.
  98330. ** The calling function can detect the problem by looking at pParse->nErr
  98331. ** and/or pParse->db->mallocFailed.
  98332. */
  98333. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  98334. Walker w;
  98335. memset(&w, 0, sizeof(w));
  98336. w.xExprCallback = exprWalkNoop;
  98337. w.pParse = pParse;
  98338. if( pParse->hasCompound ){
  98339. w.xSelectCallback = convertCompoundSelectToSubquery;
  98340. sqlite3WalkSelect(&w, pSelect);
  98341. }
  98342. w.xSelectCallback = selectExpander;
  98343. sqlite3WalkSelect(&w, pSelect);
  98344. }
  98345. #ifndef SQLITE_OMIT_SUBQUERY
  98346. /*
  98347. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  98348. ** interface.
  98349. **
  98350. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  98351. ** information to the Table structure that represents the result set
  98352. ** of that subquery.
  98353. **
  98354. ** The Table structure that represents the result set was constructed
  98355. ** by selectExpander() but the type and collation information was omitted
  98356. ** at that point because identifiers had not yet been resolved. This
  98357. ** routine is called after identifier resolution.
  98358. */
  98359. static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  98360. Parse *pParse;
  98361. int i;
  98362. SrcList *pTabList;
  98363. struct SrcList_item *pFrom;
  98364. assert( p->selFlags & SF_Resolved );
  98365. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  98366. p->selFlags |= SF_HasTypeInfo;
  98367. pParse = pWalker->pParse;
  98368. pTabList = p->pSrc;
  98369. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  98370. Table *pTab = pFrom->pTab;
  98371. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  98372. /* A sub-query in the FROM clause of a SELECT */
  98373. Select *pSel = pFrom->pSelect;
  98374. assert( pSel );
  98375. while( pSel->pPrior ) pSel = pSel->pPrior;
  98376. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  98377. }
  98378. }
  98379. }
  98380. return WRC_Continue;
  98381. }
  98382. #endif
  98383. /*
  98384. ** This routine adds datatype and collating sequence information to
  98385. ** the Table structures of all FROM-clause subqueries in a
  98386. ** SELECT statement.
  98387. **
  98388. ** Use this routine after name resolution.
  98389. */
  98390. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  98391. #ifndef SQLITE_OMIT_SUBQUERY
  98392. Walker w;
  98393. memset(&w, 0, sizeof(w));
  98394. w.xSelectCallback = selectAddSubqueryTypeInfo;
  98395. w.xExprCallback = exprWalkNoop;
  98396. w.pParse = pParse;
  98397. w.bSelectDepthFirst = 1;
  98398. sqlite3WalkSelect(&w, pSelect);
  98399. #endif
  98400. }
  98401. /*
  98402. ** This routine sets up a SELECT statement for processing. The
  98403. ** following is accomplished:
  98404. **
  98405. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  98406. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  98407. ** * ON and USING clauses are shifted into WHERE statements
  98408. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  98409. ** * Identifiers in expression are matched to tables.
  98410. **
  98411. ** This routine acts recursively on all subqueries within the SELECT.
  98412. */
  98413. SQLITE_PRIVATE void sqlite3SelectPrep(
  98414. Parse *pParse, /* The parser context */
  98415. Select *p, /* The SELECT statement being coded. */
  98416. NameContext *pOuterNC /* Name context for container */
  98417. ){
  98418. sqlite3 *db;
  98419. if( NEVER(p==0) ) return;
  98420. db = pParse->db;
  98421. if( db->mallocFailed ) return;
  98422. if( p->selFlags & SF_HasTypeInfo ) return;
  98423. sqlite3SelectExpand(pParse, p);
  98424. if( pParse->nErr || db->mallocFailed ) return;
  98425. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  98426. if( pParse->nErr || db->mallocFailed ) return;
  98427. sqlite3SelectAddTypeInfo(pParse, p);
  98428. }
  98429. /*
  98430. ** Reset the aggregate accumulator.
  98431. **
  98432. ** The aggregate accumulator is a set of memory cells that hold
  98433. ** intermediate results while calculating an aggregate. This
  98434. ** routine generates code that stores NULLs in all of those memory
  98435. ** cells.
  98436. */
  98437. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  98438. Vdbe *v = pParse->pVdbe;
  98439. int i;
  98440. struct AggInfo_func *pFunc;
  98441. if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
  98442. return;
  98443. }
  98444. for(i=0; i<pAggInfo->nColumn; i++){
  98445. sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
  98446. }
  98447. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  98448. sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
  98449. if( pFunc->iDistinct>=0 ){
  98450. Expr *pE = pFunc->pExpr;
  98451. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  98452. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  98453. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  98454. "argument");
  98455. pFunc->iDistinct = -1;
  98456. }else{
  98457. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
  98458. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  98459. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  98460. }
  98461. }
  98462. }
  98463. }
  98464. /*
  98465. ** Invoke the OP_AggFinalize opcode for every aggregate function
  98466. ** in the AggInfo structure.
  98467. */
  98468. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  98469. Vdbe *v = pParse->pVdbe;
  98470. int i;
  98471. struct AggInfo_func *pF;
  98472. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  98473. ExprList *pList = pF->pExpr->x.pList;
  98474. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  98475. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  98476. (void*)pF->pFunc, P4_FUNCDEF);
  98477. }
  98478. }
  98479. /*
  98480. ** Update the accumulator memory cells for an aggregate based on
  98481. ** the current cursor position.
  98482. */
  98483. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  98484. Vdbe *v = pParse->pVdbe;
  98485. int i;
  98486. int regHit = 0;
  98487. int addrHitTest = 0;
  98488. struct AggInfo_func *pF;
  98489. struct AggInfo_col *pC;
  98490. pAggInfo->directMode = 1;
  98491. sqlite3ExprCacheClear(pParse);
  98492. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  98493. int nArg;
  98494. int addrNext = 0;
  98495. int regAgg;
  98496. ExprList *pList = pF->pExpr->x.pList;
  98497. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  98498. if( pList ){
  98499. nArg = pList->nExpr;
  98500. regAgg = sqlite3GetTempRange(pParse, nArg);
  98501. sqlite3ExprCodeExprList(pParse, pList, regAgg, 1);
  98502. }else{
  98503. nArg = 0;
  98504. regAgg = 0;
  98505. }
  98506. if( pF->iDistinct>=0 ){
  98507. addrNext = sqlite3VdbeMakeLabel(v);
  98508. assert( nArg==1 );
  98509. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  98510. }
  98511. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  98512. CollSeq *pColl = 0;
  98513. struct ExprList_item *pItem;
  98514. int j;
  98515. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  98516. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  98517. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  98518. }
  98519. if( !pColl ){
  98520. pColl = pParse->db->pDfltColl;
  98521. }
  98522. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  98523. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  98524. }
  98525. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  98526. (void*)pF->pFunc, P4_FUNCDEF);
  98527. sqlite3VdbeChangeP5(v, (u8)nArg);
  98528. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  98529. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  98530. if( addrNext ){
  98531. sqlite3VdbeResolveLabel(v, addrNext);
  98532. sqlite3ExprCacheClear(pParse);
  98533. }
  98534. }
  98535. /* Before populating the accumulator registers, clear the column cache.
  98536. ** Otherwise, if any of the required column values are already present
  98537. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  98538. ** to pC->iMem. But by the time the value is used, the original register
  98539. ** may have been used, invalidating the underlying buffer holding the
  98540. ** text or blob value. See ticket [883034dcb5].
  98541. **
  98542. ** Another solution would be to change the OP_SCopy used to copy cached
  98543. ** values to an OP_Copy.
  98544. */
  98545. if( regHit ){
  98546. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit);
  98547. }
  98548. sqlite3ExprCacheClear(pParse);
  98549. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  98550. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  98551. }
  98552. pAggInfo->directMode = 0;
  98553. sqlite3ExprCacheClear(pParse);
  98554. if( addrHitTest ){
  98555. sqlite3VdbeJumpHere(v, addrHitTest);
  98556. }
  98557. }
  98558. /*
  98559. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  98560. ** count(*) query ("SELECT count(*) FROM pTab").
  98561. */
  98562. #ifndef SQLITE_OMIT_EXPLAIN
  98563. static void explainSimpleCount(
  98564. Parse *pParse, /* Parse context */
  98565. Table *pTab, /* Table being queried */
  98566. Index *pIdx /* Index used to optimize scan, or NULL */
  98567. ){
  98568. if( pParse->explain==2 ){
  98569. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  98570. pTab->zName,
  98571. pIdx ? " USING COVERING INDEX " : "",
  98572. pIdx ? pIdx->zName : ""
  98573. );
  98574. sqlite3VdbeAddOp4(
  98575. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  98576. );
  98577. }
  98578. }
  98579. #else
  98580. # define explainSimpleCount(a,b,c)
  98581. #endif
  98582. /*
  98583. ** Generate code for the SELECT statement given in the p argument.
  98584. **
  98585. ** The results are distributed in various ways depending on the
  98586. ** contents of the SelectDest structure pointed to by argument pDest
  98587. ** as follows:
  98588. **
  98589. ** pDest->eDest Result
  98590. ** ------------ -------------------------------------------
  98591. ** SRT_Output Generate a row of output (using the OP_ResultRow
  98592. ** opcode) for each row in the result set.
  98593. **
  98594. ** SRT_Mem Only valid if the result is a single column.
  98595. ** Store the first column of the first result row
  98596. ** in register pDest->iSDParm then abandon the rest
  98597. ** of the query. This destination implies "LIMIT 1".
  98598. **
  98599. ** SRT_Set The result must be a single column. Store each
  98600. ** row of result as the key in table pDest->iSDParm.
  98601. ** Apply the affinity pDest->affSdst before storing
  98602. ** results. Used to implement "IN (SELECT ...)".
  98603. **
  98604. ** SRT_Union Store results as a key in a temporary table
  98605. ** identified by pDest->iSDParm.
  98606. **
  98607. ** SRT_Except Remove results from the temporary table pDest->iSDParm.
  98608. **
  98609. ** SRT_Table Store results in temporary table pDest->iSDParm.
  98610. ** This is like SRT_EphemTab except that the table
  98611. ** is assumed to already be open.
  98612. **
  98613. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  98614. ** the result there. The cursor is left open after
  98615. ** returning. This is like SRT_Table except that
  98616. ** this destination uses OP_OpenEphemeral to create
  98617. ** the table first.
  98618. **
  98619. ** SRT_Coroutine Generate a co-routine that returns a new row of
  98620. ** results each time it is invoked. The entry point
  98621. ** of the co-routine is stored in register pDest->iSDParm.
  98622. **
  98623. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  98624. ** set is not empty.
  98625. **
  98626. ** SRT_Discard Throw the results away. This is used by SELECT
  98627. ** statements within triggers whose only purpose is
  98628. ** the side-effects of functions.
  98629. **
  98630. ** This routine returns the number of errors. If any errors are
  98631. ** encountered, then an appropriate error message is left in
  98632. ** pParse->zErrMsg.
  98633. **
  98634. ** This routine does NOT free the Select structure passed in. The
  98635. ** calling function needs to do that.
  98636. */
  98637. SQLITE_PRIVATE int sqlite3Select(
  98638. Parse *pParse, /* The parser context */
  98639. Select *p, /* The SELECT statement being coded. */
  98640. SelectDest *pDest /* What to do with the query results */
  98641. ){
  98642. int i, j; /* Loop counters */
  98643. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  98644. Vdbe *v; /* The virtual machine under construction */
  98645. int isAgg; /* True for select lists like "count(*)" */
  98646. ExprList *pEList; /* List of columns to extract. */
  98647. SrcList *pTabList; /* List of tables to select from */
  98648. Expr *pWhere; /* The WHERE clause. May be NULL */
  98649. ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  98650. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  98651. Expr *pHaving; /* The HAVING clause. May be NULL */
  98652. int rc = 1; /* Value to return from this function */
  98653. int addrSortIndex; /* Address of an OP_OpenEphemeral instruction */
  98654. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  98655. AggInfo sAggInfo; /* Information used by aggregate queries */
  98656. int iEnd; /* Address of the end of the query */
  98657. sqlite3 *db; /* The database connection */
  98658. #ifndef SQLITE_OMIT_EXPLAIN
  98659. int iRestoreSelectId = pParse->iSelectId;
  98660. pParse->iSelectId = pParse->iNextSelectId++;
  98661. #endif
  98662. db = pParse->db;
  98663. if( p==0 || db->mallocFailed || pParse->nErr ){
  98664. return 1;
  98665. }
  98666. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  98667. memset(&sAggInfo, 0, sizeof(sAggInfo));
  98668. if( IgnorableOrderby(pDest) ){
  98669. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  98670. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
  98671. /* If ORDER BY makes no difference in the output then neither does
  98672. ** DISTINCT so it can be removed too. */
  98673. sqlite3ExprListDelete(db, p->pOrderBy);
  98674. p->pOrderBy = 0;
  98675. p->selFlags &= ~SF_Distinct;
  98676. }
  98677. sqlite3SelectPrep(pParse, p, 0);
  98678. pOrderBy = p->pOrderBy;
  98679. pTabList = p->pSrc;
  98680. pEList = p->pEList;
  98681. if( pParse->nErr || db->mallocFailed ){
  98682. goto select_end;
  98683. }
  98684. isAgg = (p->selFlags & SF_Aggregate)!=0;
  98685. assert( pEList!=0 );
  98686. /* Begin generating code.
  98687. */
  98688. v = sqlite3GetVdbe(pParse);
  98689. if( v==0 ) goto select_end;
  98690. /* If writing to memory or generating a set
  98691. ** only a single column may be output.
  98692. */
  98693. #ifndef SQLITE_OMIT_SUBQUERY
  98694. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  98695. goto select_end;
  98696. }
  98697. #endif
  98698. /* Generate code for all sub-queries in the FROM clause
  98699. */
  98700. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  98701. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  98702. struct SrcList_item *pItem = &pTabList->a[i];
  98703. SelectDest dest;
  98704. Select *pSub = pItem->pSelect;
  98705. int isAggSub;
  98706. if( pSub==0 ) continue;
  98707. /* Sometimes the code for a subquery will be generated more than
  98708. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  98709. ** for example. In that case, do not regenerate the code to manifest
  98710. ** a view or the co-routine to implement a view. The first instance
  98711. ** is sufficient, though the subroutine to manifest the view does need
  98712. ** to be invoked again. */
  98713. if( pItem->addrFillSub ){
  98714. if( pItem->viaCoroutine==0 ){
  98715. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  98716. }
  98717. continue;
  98718. }
  98719. /* Increment Parse.nHeight by the height of the largest expression
  98720. ** tree referred to by this, the parent select. The child select
  98721. ** may contain expression trees of at most
  98722. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  98723. ** more conservative than necessary, but much easier than enforcing
  98724. ** an exact limit.
  98725. */
  98726. pParse->nHeight += sqlite3SelectExprHeight(p);
  98727. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  98728. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  98729. /* This subquery can be absorbed into its parent. */
  98730. if( isAggSub ){
  98731. isAgg = 1;
  98732. p->selFlags |= SF_Aggregate;
  98733. }
  98734. i = -1;
  98735. }else if( pTabList->nSrc==1 && (p->selFlags & SF_Materialize)==0
  98736. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  98737. ){
  98738. /* Implement a co-routine that will return a single row of the result
  98739. ** set on each invocation.
  98740. */
  98741. int addrTop;
  98742. int addrEof;
  98743. pItem->regReturn = ++pParse->nMem;
  98744. addrEof = ++pParse->nMem;
  98745. /* Before coding the OP_Goto to jump to the start of the main routine,
  98746. ** ensure that the jump to the verify-schema routine has already
  98747. ** been coded. Otherwise, the verify-schema would likely be coded as
  98748. ** part of the co-routine. If the main routine then accessed the
  98749. ** database before invoking the co-routine for the first time (for
  98750. ** example to initialize a LIMIT register from a sub-select), it would
  98751. ** be doing so without having verified the schema version and obtained
  98752. ** the required db locks. See ticket d6b36be38. */
  98753. sqlite3CodeVerifySchema(pParse, -1);
  98754. sqlite3VdbeAddOp0(v, OP_Goto);
  98755. addrTop = sqlite3VdbeAddOp1(v, OP_OpenPseudo, pItem->iCursor);
  98756. sqlite3VdbeChangeP5(v, 1);
  98757. VdbeComment((v, "coroutine for %s", pItem->pTab->zName));
  98758. pItem->addrFillSub = addrTop;
  98759. sqlite3VdbeAddOp2(v, OP_Integer, 0, addrEof);
  98760. sqlite3VdbeChangeP5(v, 1);
  98761. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  98762. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  98763. sqlite3Select(pParse, pSub, &dest);
  98764. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  98765. pItem->viaCoroutine = 1;
  98766. sqlite3VdbeChangeP2(v, addrTop, dest.iSdst);
  98767. sqlite3VdbeChangeP3(v, addrTop, dest.nSdst);
  98768. sqlite3VdbeAddOp2(v, OP_Integer, 1, addrEof);
  98769. sqlite3VdbeAddOp1(v, OP_Yield, pItem->regReturn);
  98770. VdbeComment((v, "end %s", pItem->pTab->zName));
  98771. sqlite3VdbeJumpHere(v, addrTop-1);
  98772. sqlite3ClearTempRegCache(pParse);
  98773. }else{
  98774. /* Generate a subroutine that will fill an ephemeral table with
  98775. ** the content of this subquery. pItem->addrFillSub will point
  98776. ** to the address of the generated subroutine. pItem->regReturn
  98777. ** is a register allocated to hold the subroutine return address
  98778. */
  98779. int topAddr;
  98780. int onceAddr = 0;
  98781. int retAddr;
  98782. assert( pItem->addrFillSub==0 );
  98783. pItem->regReturn = ++pParse->nMem;
  98784. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  98785. pItem->addrFillSub = topAddr+1;
  98786. VdbeNoopComment((v, "materialize %s", pItem->pTab->zName));
  98787. if( pItem->isCorrelated==0 ){
  98788. /* If the subquery is not correlated and if we are not inside of
  98789. ** a trigger, then we only need to compute the value of the subquery
  98790. ** once. */
  98791. onceAddr = sqlite3CodeOnce(pParse);
  98792. }
  98793. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  98794. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  98795. sqlite3Select(pParse, pSub, &dest);
  98796. pItem->pTab->nRowEst = (unsigned)pSub->nSelectRow;
  98797. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  98798. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  98799. VdbeComment((v, "end %s", pItem->pTab->zName));
  98800. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  98801. sqlite3ClearTempRegCache(pParse);
  98802. }
  98803. if( /*pParse->nErr ||*/ db->mallocFailed ){
  98804. goto select_end;
  98805. }
  98806. pParse->nHeight -= sqlite3SelectExprHeight(p);
  98807. pTabList = p->pSrc;
  98808. if( !IgnorableOrderby(pDest) ){
  98809. pOrderBy = p->pOrderBy;
  98810. }
  98811. }
  98812. pEList = p->pEList;
  98813. #endif
  98814. pWhere = p->pWhere;
  98815. pGroupBy = p->pGroupBy;
  98816. pHaving = p->pHaving;
  98817. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  98818. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98819. /* If there is are a sequence of queries, do the earlier ones first.
  98820. */
  98821. if( p->pPrior ){
  98822. if( p->pRightmost==0 ){
  98823. Select *pLoop, *pRight = 0;
  98824. int cnt = 0;
  98825. int mxSelect;
  98826. for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
  98827. pLoop->pRightmost = p;
  98828. pLoop->pNext = pRight;
  98829. pRight = pLoop;
  98830. }
  98831. mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  98832. if( mxSelect && cnt>mxSelect ){
  98833. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  98834. goto select_end;
  98835. }
  98836. }
  98837. rc = multiSelect(pParse, p, pDest);
  98838. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  98839. return rc;
  98840. }
  98841. #endif
  98842. /* If there is both a GROUP BY and an ORDER BY clause and they are
  98843. ** identical, then disable the ORDER BY clause since the GROUP BY
  98844. ** will cause elements to come out in the correct order. This is
  98845. ** an optimization - the correct answer should result regardless.
  98846. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER
  98847. ** to disable this optimization for testing purposes.
  98848. */
  98849. if( sqlite3ExprListCompare(p->pGroupBy, pOrderBy, -1)==0
  98850. && OptimizationEnabled(db, SQLITE_GroupByOrder) ){
  98851. pOrderBy = 0;
  98852. }
  98853. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  98854. ** if the select-list is the same as the ORDER BY list, then this query
  98855. ** can be rewritten as a GROUP BY. In other words, this:
  98856. **
  98857. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  98858. **
  98859. ** is transformed to:
  98860. **
  98861. ** SELECT xyz FROM ... GROUP BY xyz
  98862. **
  98863. ** The second form is preferred as a single index (or temp-table) may be
  98864. ** used for both the ORDER BY and DISTINCT processing. As originally
  98865. ** written the query must use a temp-table for at least one of the ORDER
  98866. ** BY and DISTINCT, and an index or separate temp-table for the other.
  98867. */
  98868. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  98869. && sqlite3ExprListCompare(pOrderBy, p->pEList, -1)==0
  98870. ){
  98871. p->selFlags &= ~SF_Distinct;
  98872. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  98873. pGroupBy = p->pGroupBy;
  98874. pOrderBy = 0;
  98875. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  98876. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  98877. ** original setting of the SF_Distinct flag, not the current setting */
  98878. assert( sDistinct.isTnct );
  98879. }
  98880. /* If there is an ORDER BY clause, then this sorting
  98881. ** index might end up being unused if the data can be
  98882. ** extracted in pre-sorted order. If that is the case, then the
  98883. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  98884. ** we figure out that the sorting index is not needed. The addrSortIndex
  98885. ** variable is used to facilitate that change.
  98886. */
  98887. if( pOrderBy ){
  98888. KeyInfo *pKeyInfo;
  98889. pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
  98890. pOrderBy->iECursor = pParse->nTab++;
  98891. p->addrOpenEphm[2] = addrSortIndex =
  98892. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  98893. pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
  98894. (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  98895. }else{
  98896. addrSortIndex = -1;
  98897. }
  98898. /* If the output is destined for a temporary table, open that table.
  98899. */
  98900. if( pDest->eDest==SRT_EphemTab ){
  98901. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  98902. }
  98903. /* Set the limiter.
  98904. */
  98905. iEnd = sqlite3VdbeMakeLabel(v);
  98906. p->nSelectRow = LARGEST_INT64;
  98907. computeLimitRegisters(pParse, p, iEnd);
  98908. if( p->iLimit==0 && addrSortIndex>=0 ){
  98909. sqlite3VdbeGetOp(v, addrSortIndex)->opcode = OP_SorterOpen;
  98910. p->selFlags |= SF_UseSorter;
  98911. }
  98912. /* Open a virtual index to use for the distinct set.
  98913. */
  98914. if( p->selFlags & SF_Distinct ){
  98915. sDistinct.tabTnct = pParse->nTab++;
  98916. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  98917. sDistinct.tabTnct, 0, 0,
  98918. (char*)keyInfoFromExprList(pParse, p->pEList),
  98919. P4_KEYINFO_HANDOFF);
  98920. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  98921. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  98922. }else{
  98923. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  98924. }
  98925. if( !isAgg && pGroupBy==0 ){
  98926. /* No aggregate functions and no GROUP BY clause */
  98927. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  98928. /* Begin the database scan. */
  98929. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pOrderBy, p->pEList,
  98930. wctrlFlags, 0);
  98931. if( pWInfo==0 ) goto select_end;
  98932. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  98933. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  98934. }
  98935. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  98936. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  98937. }
  98938. if( pOrderBy && sqlite3WhereIsOrdered(pWInfo) ) pOrderBy = 0;
  98939. /* If sorting index that was created by a prior OP_OpenEphemeral
  98940. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  98941. ** into an OP_Noop.
  98942. */
  98943. if( addrSortIndex>=0 && pOrderBy==0 ){
  98944. sqlite3VdbeChangeToNoop(v, addrSortIndex);
  98945. p->addrOpenEphm[2] = -1;
  98946. }
  98947. /* Use the standard inner loop. */
  98948. selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, &sDistinct, pDest,
  98949. sqlite3WhereContinueLabel(pWInfo),
  98950. sqlite3WhereBreakLabel(pWInfo));
  98951. /* End the database scan loop.
  98952. */
  98953. sqlite3WhereEnd(pWInfo);
  98954. }else{
  98955. /* This case when there exist aggregate functions or a GROUP BY clause
  98956. ** or both */
  98957. NameContext sNC; /* Name context for processing aggregate information */
  98958. int iAMem; /* First Mem address for storing current GROUP BY */
  98959. int iBMem; /* First Mem address for previous GROUP BY */
  98960. int iUseFlag; /* Mem address holding flag indicating that at least
  98961. ** one row of the input to the aggregator has been
  98962. ** processed */
  98963. int iAbortFlag; /* Mem address which causes query abort if positive */
  98964. int groupBySort; /* Rows come from source in GROUP BY order */
  98965. int addrEnd; /* End of processing for this SELECT */
  98966. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  98967. int sortOut = 0; /* Output register from the sorter */
  98968. /* Remove any and all aliases between the result set and the
  98969. ** GROUP BY clause.
  98970. */
  98971. if( pGroupBy ){
  98972. int k; /* Loop counter */
  98973. struct ExprList_item *pItem; /* For looping over expression in a list */
  98974. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  98975. pItem->iAlias = 0;
  98976. }
  98977. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  98978. pItem->iAlias = 0;
  98979. }
  98980. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  98981. }else{
  98982. p->nSelectRow = 1;
  98983. }
  98984. /* Create a label to jump to when we want to abort the query */
  98985. addrEnd = sqlite3VdbeMakeLabel(v);
  98986. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  98987. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  98988. ** SELECT statement.
  98989. */
  98990. memset(&sNC, 0, sizeof(sNC));
  98991. sNC.pParse = pParse;
  98992. sNC.pSrcList = pTabList;
  98993. sNC.pAggInfo = &sAggInfo;
  98994. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
  98995. sAggInfo.pGroupBy = pGroupBy;
  98996. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  98997. sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
  98998. if( pHaving ){
  98999. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  99000. }
  99001. sAggInfo.nAccumulator = sAggInfo.nColumn;
  99002. for(i=0; i<sAggInfo.nFunc; i++){
  99003. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  99004. sNC.ncFlags |= NC_InAggFunc;
  99005. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  99006. sNC.ncFlags &= ~NC_InAggFunc;
  99007. }
  99008. if( db->mallocFailed ) goto select_end;
  99009. /* Processing for aggregates with GROUP BY is very different and
  99010. ** much more complex than aggregates without a GROUP BY.
  99011. */
  99012. if( pGroupBy ){
  99013. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  99014. int j1; /* A-vs-B comparision jump */
  99015. int addrOutputRow; /* Start of subroutine that outputs a result row */
  99016. int regOutputRow; /* Return address register for output subroutine */
  99017. int addrSetAbort; /* Set the abort flag and return */
  99018. int addrTopOfLoop; /* Top of the input loop */
  99019. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  99020. int addrReset; /* Subroutine for resetting the accumulator */
  99021. int regReset; /* Return address register for reset subroutine */
  99022. /* If there is a GROUP BY clause we might need a sorting index to
  99023. ** implement it. Allocate that sorting index now. If it turns out
  99024. ** that we do not need it after all, the OP_SorterOpen instruction
  99025. ** will be converted into a Noop.
  99026. */
  99027. sAggInfo.sortingIdx = pParse->nTab++;
  99028. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
  99029. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  99030. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  99031. 0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
  99032. /* Initialize memory locations used by GROUP BY aggregate processing
  99033. */
  99034. iUseFlag = ++pParse->nMem;
  99035. iAbortFlag = ++pParse->nMem;
  99036. regOutputRow = ++pParse->nMem;
  99037. addrOutputRow = sqlite3VdbeMakeLabel(v);
  99038. regReset = ++pParse->nMem;
  99039. addrReset = sqlite3VdbeMakeLabel(v);
  99040. iAMem = pParse->nMem + 1;
  99041. pParse->nMem += pGroupBy->nExpr;
  99042. iBMem = pParse->nMem + 1;
  99043. pParse->nMem += pGroupBy->nExpr;
  99044. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  99045. VdbeComment((v, "clear abort flag"));
  99046. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  99047. VdbeComment((v, "indicate accumulator empty"));
  99048. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  99049. /* Begin a loop that will extract all source rows in GROUP BY order.
  99050. ** This might involve two separate loops with an OP_Sort in between, or
  99051. ** it might be a single loop that uses an index to extract information
  99052. ** in the right order to begin with.
  99053. */
  99054. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  99055. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  99056. WHERE_GROUPBY, 0);
  99057. if( pWInfo==0 ) goto select_end;
  99058. if( sqlite3WhereIsOrdered(pWInfo) ){
  99059. /* The optimizer is able to deliver rows in group by order so
  99060. ** we do not have to sort. The OP_OpenEphemeral table will be
  99061. ** cancelled later because we still need to use the pKeyInfo
  99062. */
  99063. groupBySort = 0;
  99064. }else{
  99065. /* Rows are coming out in undetermined order. We have to push
  99066. ** each row into a sorting index, terminate the first loop,
  99067. ** then loop over the sorting index in order to get the output
  99068. ** in sorted order
  99069. */
  99070. int regBase;
  99071. int regRecord;
  99072. int nCol;
  99073. int nGroupBy;
  99074. explainTempTable(pParse,
  99075. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  99076. "DISTINCT" : "GROUP BY");
  99077. groupBySort = 1;
  99078. nGroupBy = pGroupBy->nExpr;
  99079. nCol = nGroupBy + 1;
  99080. j = nGroupBy+1;
  99081. for(i=0; i<sAggInfo.nColumn; i++){
  99082. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  99083. nCol++;
  99084. j++;
  99085. }
  99086. }
  99087. regBase = sqlite3GetTempRange(pParse, nCol);
  99088. sqlite3ExprCacheClear(pParse);
  99089. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  99090. sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
  99091. j = nGroupBy+1;
  99092. for(i=0; i<sAggInfo.nColumn; i++){
  99093. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  99094. if( pCol->iSorterColumn>=j ){
  99095. int r1 = j + regBase;
  99096. int r2;
  99097. r2 = sqlite3ExprCodeGetColumn(pParse,
  99098. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  99099. if( r1!=r2 ){
  99100. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  99101. }
  99102. j++;
  99103. }
  99104. }
  99105. regRecord = sqlite3GetTempReg(pParse);
  99106. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  99107. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  99108. sqlite3ReleaseTempReg(pParse, regRecord);
  99109. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  99110. sqlite3WhereEnd(pWInfo);
  99111. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  99112. sortOut = sqlite3GetTempReg(pParse);
  99113. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  99114. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  99115. VdbeComment((v, "GROUP BY sort"));
  99116. sAggInfo.useSortingIdx = 1;
  99117. sqlite3ExprCacheClear(pParse);
  99118. }
  99119. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  99120. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  99121. ** Then compare the current GROUP BY terms against the GROUP BY terms
  99122. ** from the previous row currently stored in a0, a1, a2...
  99123. */
  99124. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  99125. sqlite3ExprCacheClear(pParse);
  99126. if( groupBySort ){
  99127. sqlite3VdbeAddOp2(v, OP_SorterData, sAggInfo.sortingIdx, sortOut);
  99128. }
  99129. for(j=0; j<pGroupBy->nExpr; j++){
  99130. if( groupBySort ){
  99131. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  99132. if( j==0 ) sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
  99133. }else{
  99134. sAggInfo.directMode = 1;
  99135. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  99136. }
  99137. }
  99138. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  99139. (char*)pKeyInfo, P4_KEYINFO);
  99140. j1 = sqlite3VdbeCurrentAddr(v);
  99141. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
  99142. /* Generate code that runs whenever the GROUP BY changes.
  99143. ** Changes in the GROUP BY are detected by the previous code
  99144. ** block. If there were no changes, this block is skipped.
  99145. **
  99146. ** This code copies current group by terms in b0,b1,b2,...
  99147. ** over to a0,a1,a2. It then calls the output subroutine
  99148. ** and resets the aggregate accumulator registers in preparation
  99149. ** for the next GROUP BY batch.
  99150. */
  99151. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  99152. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  99153. VdbeComment((v, "output one row"));
  99154. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
  99155. VdbeComment((v, "check abort flag"));
  99156. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  99157. VdbeComment((v, "reset accumulator"));
  99158. /* Update the aggregate accumulators based on the content of
  99159. ** the current row
  99160. */
  99161. sqlite3VdbeJumpHere(v, j1);
  99162. updateAccumulator(pParse, &sAggInfo);
  99163. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  99164. VdbeComment((v, "indicate data in accumulator"));
  99165. /* End of the loop
  99166. */
  99167. if( groupBySort ){
  99168. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  99169. }else{
  99170. sqlite3WhereEnd(pWInfo);
  99171. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  99172. }
  99173. /* Output the final row of result
  99174. */
  99175. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  99176. VdbeComment((v, "output final row"));
  99177. /* Jump over the subroutines
  99178. */
  99179. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  99180. /* Generate a subroutine that outputs a single row of the result
  99181. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  99182. ** is less than or equal to zero, the subroutine is a no-op. If
  99183. ** the processing calls for the query to abort, this subroutine
  99184. ** increments the iAbortFlag memory location before returning in
  99185. ** order to signal the caller to abort.
  99186. */
  99187. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  99188. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  99189. VdbeComment((v, "set abort flag"));
  99190. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99191. sqlite3VdbeResolveLabel(v, addrOutputRow);
  99192. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  99193. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
  99194. VdbeComment((v, "Groupby result generator entry point"));
  99195. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99196. finalizeAggFunctions(pParse, &sAggInfo);
  99197. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  99198. selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
  99199. &sDistinct, pDest,
  99200. addrOutputRow+1, addrSetAbort);
  99201. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  99202. VdbeComment((v, "end groupby result generator"));
  99203. /* Generate a subroutine that will reset the group-by accumulator
  99204. */
  99205. sqlite3VdbeResolveLabel(v, addrReset);
  99206. resetAccumulator(pParse, &sAggInfo);
  99207. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  99208. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  99209. else {
  99210. ExprList *pDel = 0;
  99211. #ifndef SQLITE_OMIT_BTREECOUNT
  99212. Table *pTab;
  99213. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  99214. /* If isSimpleCount() returns a pointer to a Table structure, then
  99215. ** the SQL statement is of the form:
  99216. **
  99217. ** SELECT count(*) FROM <tbl>
  99218. **
  99219. ** where the Table structure returned represents table <tbl>.
  99220. **
  99221. ** This statement is so common that it is optimized specially. The
  99222. ** OP_Count instruction is executed either on the intkey table that
  99223. ** contains the data for table <tbl> or on one of its indexes. It
  99224. ** is better to execute the op on an index, as indexes are almost
  99225. ** always spread across less pages than their corresponding tables.
  99226. */
  99227. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  99228. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  99229. Index *pIdx; /* Iterator variable */
  99230. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  99231. Index *pBest = 0; /* Best index found so far */
  99232. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  99233. sqlite3CodeVerifySchema(pParse, iDb);
  99234. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  99235. /* Search for the index that has the lowest scan cost.
  99236. **
  99237. ** (2011-04-15) Do not do a full scan of an unordered index.
  99238. **
  99239. ** (2013-10-03) Do not count the entires in a partial index.
  99240. **
  99241. ** In practice the KeyInfo structure will not be used. It is only
  99242. ** passed to keep OP_OpenRead happy.
  99243. */
  99244. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  99245. if( pIdx->bUnordered==0
  99246. && pIdx->szIdxRow<pTab->szTabRow
  99247. && pIdx->pPartIdxWhere==0
  99248. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  99249. ){
  99250. pBest = pIdx;
  99251. }
  99252. }
  99253. if( pBest ){
  99254. iRoot = pBest->tnum;
  99255. pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
  99256. }
  99257. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  99258. sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
  99259. if( pKeyInfo ){
  99260. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
  99261. }
  99262. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  99263. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  99264. explainSimpleCount(pParse, pTab, pBest);
  99265. }else
  99266. #endif /* SQLITE_OMIT_BTREECOUNT */
  99267. {
  99268. /* Check if the query is of one of the following forms:
  99269. **
  99270. ** SELECT min(x) FROM ...
  99271. ** SELECT max(x) FROM ...
  99272. **
  99273. ** If it is, then ask the code in where.c to attempt to sort results
  99274. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  99275. ** If where.c is able to produce results sorted in this order, then
  99276. ** add vdbe code to break out of the processing loop after the
  99277. ** first iteration (since the first iteration of the loop is
  99278. ** guaranteed to operate on the row with the minimum or maximum
  99279. ** value of x, the only row required).
  99280. **
  99281. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  99282. ** modify behavior as follows:
  99283. **
  99284. ** + If the query is a "SELECT min(x)", then the loop coded by
  99285. ** where.c should not iterate over any values with a NULL value
  99286. ** for x.
  99287. **
  99288. ** + The optimizer code in where.c (the thing that decides which
  99289. ** index or indices to use) should place a different priority on
  99290. ** satisfying the 'ORDER BY' clause than it does in other cases.
  99291. ** Refer to code and comments in where.c for details.
  99292. */
  99293. ExprList *pMinMax = 0;
  99294. u8 flag = WHERE_ORDERBY_NORMAL;
  99295. assert( p->pGroupBy==0 );
  99296. assert( flag==0 );
  99297. if( p->pHaving==0 ){
  99298. flag = minMaxQuery(&sAggInfo, &pMinMax);
  99299. }
  99300. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  99301. if( flag ){
  99302. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  99303. pDel = pMinMax;
  99304. if( pMinMax && !db->mallocFailed ){
  99305. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  99306. pMinMax->a[0].pExpr->op = TK_COLUMN;
  99307. }
  99308. }
  99309. /* This case runs if the aggregate has no GROUP BY clause. The
  99310. ** processing is much simpler since there is only a single row
  99311. ** of output.
  99312. */
  99313. resetAccumulator(pParse, &sAggInfo);
  99314. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  99315. if( pWInfo==0 ){
  99316. sqlite3ExprListDelete(db, pDel);
  99317. goto select_end;
  99318. }
  99319. updateAccumulator(pParse, &sAggInfo);
  99320. assert( pMinMax==0 || pMinMax->nExpr==1 );
  99321. if( sqlite3WhereIsOrdered(pWInfo) ){
  99322. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  99323. VdbeComment((v, "%s() by index",
  99324. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  99325. }
  99326. sqlite3WhereEnd(pWInfo);
  99327. finalizeAggFunctions(pParse, &sAggInfo);
  99328. }
  99329. pOrderBy = 0;
  99330. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  99331. selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, 0,
  99332. pDest, addrEnd, addrEnd);
  99333. sqlite3ExprListDelete(db, pDel);
  99334. }
  99335. sqlite3VdbeResolveLabel(v, addrEnd);
  99336. } /* endif aggregate query */
  99337. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  99338. explainTempTable(pParse, "DISTINCT");
  99339. }
  99340. /* If there is an ORDER BY clause, then we need to sort the results
  99341. ** and send them to the callback one by one.
  99342. */
  99343. if( pOrderBy ){
  99344. explainTempTable(pParse, "ORDER BY");
  99345. generateSortTail(pParse, p, v, pEList->nExpr, pDest);
  99346. }
  99347. /* Jump here to skip this query
  99348. */
  99349. sqlite3VdbeResolveLabel(v, iEnd);
  99350. /* The SELECT was successfully coded. Set the return code to 0
  99351. ** to indicate no errors.
  99352. */
  99353. rc = 0;
  99354. /* Control jumps to here if an error is encountered above, or upon
  99355. ** successful coding of the SELECT.
  99356. */
  99357. select_end:
  99358. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  99359. /* Identify column names if results of the SELECT are to be output.
  99360. */
  99361. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  99362. generateColumnNames(pParse, pTabList, pEList);
  99363. }
  99364. sqlite3DbFree(db, sAggInfo.aCol);
  99365. sqlite3DbFree(db, sAggInfo.aFunc);
  99366. return rc;
  99367. }
  99368. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  99369. /*
  99370. ** Generate a human-readable description of a the Select object.
  99371. */
  99372. static void explainOneSelect(Vdbe *pVdbe, Select *p){
  99373. sqlite3ExplainPrintf(pVdbe, "SELECT ");
  99374. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  99375. if( p->selFlags & SF_Distinct ){
  99376. sqlite3ExplainPrintf(pVdbe, "DISTINCT ");
  99377. }
  99378. if( p->selFlags & SF_Aggregate ){
  99379. sqlite3ExplainPrintf(pVdbe, "agg_flag ");
  99380. }
  99381. sqlite3ExplainNL(pVdbe);
  99382. sqlite3ExplainPrintf(pVdbe, " ");
  99383. }
  99384. sqlite3ExplainExprList(pVdbe, p->pEList);
  99385. sqlite3ExplainNL(pVdbe);
  99386. if( p->pSrc && p->pSrc->nSrc ){
  99387. int i;
  99388. sqlite3ExplainPrintf(pVdbe, "FROM ");
  99389. sqlite3ExplainPush(pVdbe);
  99390. for(i=0; i<p->pSrc->nSrc; i++){
  99391. struct SrcList_item *pItem = &p->pSrc->a[i];
  99392. sqlite3ExplainPrintf(pVdbe, "{%d,*} = ", pItem->iCursor);
  99393. if( pItem->pSelect ){
  99394. sqlite3ExplainSelect(pVdbe, pItem->pSelect);
  99395. if( pItem->pTab ){
  99396. sqlite3ExplainPrintf(pVdbe, " (tabname=%s)", pItem->pTab->zName);
  99397. }
  99398. }else if( pItem->zName ){
  99399. sqlite3ExplainPrintf(pVdbe, "%s", pItem->zName);
  99400. }
  99401. if( pItem->zAlias ){
  99402. sqlite3ExplainPrintf(pVdbe, " (AS %s)", pItem->zAlias);
  99403. }
  99404. if( pItem->jointype & JT_LEFT ){
  99405. sqlite3ExplainPrintf(pVdbe, " LEFT-JOIN");
  99406. }
  99407. sqlite3ExplainNL(pVdbe);
  99408. }
  99409. sqlite3ExplainPop(pVdbe);
  99410. }
  99411. if( p->pWhere ){
  99412. sqlite3ExplainPrintf(pVdbe, "WHERE ");
  99413. sqlite3ExplainExpr(pVdbe, p->pWhere);
  99414. sqlite3ExplainNL(pVdbe);
  99415. }
  99416. if( p->pGroupBy ){
  99417. sqlite3ExplainPrintf(pVdbe, "GROUPBY ");
  99418. sqlite3ExplainExprList(pVdbe, p->pGroupBy);
  99419. sqlite3ExplainNL(pVdbe);
  99420. }
  99421. if( p->pHaving ){
  99422. sqlite3ExplainPrintf(pVdbe, "HAVING ");
  99423. sqlite3ExplainExpr(pVdbe, p->pHaving);
  99424. sqlite3ExplainNL(pVdbe);
  99425. }
  99426. if( p->pOrderBy ){
  99427. sqlite3ExplainPrintf(pVdbe, "ORDERBY ");
  99428. sqlite3ExplainExprList(pVdbe, p->pOrderBy);
  99429. sqlite3ExplainNL(pVdbe);
  99430. }
  99431. if( p->pLimit ){
  99432. sqlite3ExplainPrintf(pVdbe, "LIMIT ");
  99433. sqlite3ExplainExpr(pVdbe, p->pLimit);
  99434. sqlite3ExplainNL(pVdbe);
  99435. }
  99436. if( p->pOffset ){
  99437. sqlite3ExplainPrintf(pVdbe, "OFFSET ");
  99438. sqlite3ExplainExpr(pVdbe, p->pOffset);
  99439. sqlite3ExplainNL(pVdbe);
  99440. }
  99441. }
  99442. SQLITE_PRIVATE void sqlite3ExplainSelect(Vdbe *pVdbe, Select *p){
  99443. if( p==0 ){
  99444. sqlite3ExplainPrintf(pVdbe, "(null-select)");
  99445. return;
  99446. }
  99447. while( p->pPrior ){
  99448. p->pPrior->pNext = p;
  99449. p = p->pPrior;
  99450. }
  99451. sqlite3ExplainPush(pVdbe);
  99452. while( p ){
  99453. explainOneSelect(pVdbe, p);
  99454. p = p->pNext;
  99455. if( p==0 ) break;
  99456. sqlite3ExplainNL(pVdbe);
  99457. sqlite3ExplainPrintf(pVdbe, "%s\n", selectOpName(p->op));
  99458. }
  99459. sqlite3ExplainPrintf(pVdbe, "END");
  99460. sqlite3ExplainPop(pVdbe);
  99461. }
  99462. /* End of the structure debug printing code
  99463. *****************************************************************************/
  99464. #endif /* defined(SQLITE_ENABLE_TREE_EXPLAIN) */
  99465. /************** End of select.c **********************************************/
  99466. /************** Begin file table.c *******************************************/
  99467. /*
  99468. ** 2001 September 15
  99469. **
  99470. ** The author disclaims copyright to this source code. In place of
  99471. ** a legal notice, here is a blessing:
  99472. **
  99473. ** May you do good and not evil.
  99474. ** May you find forgiveness for yourself and forgive others.
  99475. ** May you share freely, never taking more than you give.
  99476. **
  99477. *************************************************************************
  99478. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  99479. ** interface routines. These are just wrappers around the main
  99480. ** interface routine of sqlite3_exec().
  99481. **
  99482. ** These routines are in a separate files so that they will not be linked
  99483. ** if they are not used.
  99484. */
  99485. /* #include <stdlib.h> */
  99486. /* #include <string.h> */
  99487. #ifndef SQLITE_OMIT_GET_TABLE
  99488. /*
  99489. ** This structure is used to pass data from sqlite3_get_table() through
  99490. ** to the callback function is uses to build the result.
  99491. */
  99492. typedef struct TabResult {
  99493. char **azResult; /* Accumulated output */
  99494. char *zErrMsg; /* Error message text, if an error occurs */
  99495. int nAlloc; /* Slots allocated for azResult[] */
  99496. int nRow; /* Number of rows in the result */
  99497. int nColumn; /* Number of columns in the result */
  99498. int nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  99499. int rc; /* Return code from sqlite3_exec() */
  99500. } TabResult;
  99501. /*
  99502. ** This routine is called once for each row in the result table. Its job
  99503. ** is to fill in the TabResult structure appropriately, allocating new
  99504. ** memory as necessary.
  99505. */
  99506. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  99507. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  99508. int need; /* Slots needed in p->azResult[] */
  99509. int i; /* Loop counter */
  99510. char *z; /* A single column of result */
  99511. /* Make sure there is enough space in p->azResult to hold everything
  99512. ** we need to remember from this invocation of the callback.
  99513. */
  99514. if( p->nRow==0 && argv!=0 ){
  99515. need = nCol*2;
  99516. }else{
  99517. need = nCol;
  99518. }
  99519. if( p->nData + need > p->nAlloc ){
  99520. char **azNew;
  99521. p->nAlloc = p->nAlloc*2 + need;
  99522. azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
  99523. if( azNew==0 ) goto malloc_failed;
  99524. p->azResult = azNew;
  99525. }
  99526. /* If this is the first row, then generate an extra row containing
  99527. ** the names of all columns.
  99528. */
  99529. if( p->nRow==0 ){
  99530. p->nColumn = nCol;
  99531. for(i=0; i<nCol; i++){
  99532. z = sqlite3_mprintf("%s", colv[i]);
  99533. if( z==0 ) goto malloc_failed;
  99534. p->azResult[p->nData++] = z;
  99535. }
  99536. }else if( p->nColumn!=nCol ){
  99537. sqlite3_free(p->zErrMsg);
  99538. p->zErrMsg = sqlite3_mprintf(
  99539. "sqlite3_get_table() called with two or more incompatible queries"
  99540. );
  99541. p->rc = SQLITE_ERROR;
  99542. return 1;
  99543. }
  99544. /* Copy over the row data
  99545. */
  99546. if( argv!=0 ){
  99547. for(i=0; i<nCol; i++){
  99548. if( argv[i]==0 ){
  99549. z = 0;
  99550. }else{
  99551. int n = sqlite3Strlen30(argv[i])+1;
  99552. z = sqlite3_malloc( n );
  99553. if( z==0 ) goto malloc_failed;
  99554. memcpy(z, argv[i], n);
  99555. }
  99556. p->azResult[p->nData++] = z;
  99557. }
  99558. p->nRow++;
  99559. }
  99560. return 0;
  99561. malloc_failed:
  99562. p->rc = SQLITE_NOMEM;
  99563. return 1;
  99564. }
  99565. /*
  99566. ** Query the database. But instead of invoking a callback for each row,
  99567. ** malloc() for space to hold the result and return the entire results
  99568. ** at the conclusion of the call.
  99569. **
  99570. ** The result that is written to ***pazResult is held in memory obtained
  99571. ** from malloc(). But the caller cannot free this memory directly.
  99572. ** Instead, the entire table should be passed to sqlite3_free_table() when
  99573. ** the calling procedure is finished using it.
  99574. */
  99575. SQLITE_API int sqlite3_get_table(
  99576. sqlite3 *db, /* The database on which the SQL executes */
  99577. const char *zSql, /* The SQL to be executed */
  99578. char ***pazResult, /* Write the result table here */
  99579. int *pnRow, /* Write the number of rows in the result here */
  99580. int *pnColumn, /* Write the number of columns of result here */
  99581. char **pzErrMsg /* Write error messages here */
  99582. ){
  99583. int rc;
  99584. TabResult res;
  99585. *pazResult = 0;
  99586. if( pnColumn ) *pnColumn = 0;
  99587. if( pnRow ) *pnRow = 0;
  99588. if( pzErrMsg ) *pzErrMsg = 0;
  99589. res.zErrMsg = 0;
  99590. res.nRow = 0;
  99591. res.nColumn = 0;
  99592. res.nData = 1;
  99593. res.nAlloc = 20;
  99594. res.rc = SQLITE_OK;
  99595. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  99596. if( res.azResult==0 ){
  99597. db->errCode = SQLITE_NOMEM;
  99598. return SQLITE_NOMEM;
  99599. }
  99600. res.azResult[0] = 0;
  99601. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  99602. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  99603. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  99604. if( (rc&0xff)==SQLITE_ABORT ){
  99605. sqlite3_free_table(&res.azResult[1]);
  99606. if( res.zErrMsg ){
  99607. if( pzErrMsg ){
  99608. sqlite3_free(*pzErrMsg);
  99609. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  99610. }
  99611. sqlite3_free(res.zErrMsg);
  99612. }
  99613. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  99614. return res.rc;
  99615. }
  99616. sqlite3_free(res.zErrMsg);
  99617. if( rc!=SQLITE_OK ){
  99618. sqlite3_free_table(&res.azResult[1]);
  99619. return rc;
  99620. }
  99621. if( res.nAlloc>res.nData ){
  99622. char **azNew;
  99623. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  99624. if( azNew==0 ){
  99625. sqlite3_free_table(&res.azResult[1]);
  99626. db->errCode = SQLITE_NOMEM;
  99627. return SQLITE_NOMEM;
  99628. }
  99629. res.azResult = azNew;
  99630. }
  99631. *pazResult = &res.azResult[1];
  99632. if( pnColumn ) *pnColumn = res.nColumn;
  99633. if( pnRow ) *pnRow = res.nRow;
  99634. return rc;
  99635. }
  99636. /*
  99637. ** This routine frees the space the sqlite3_get_table() malloced.
  99638. */
  99639. SQLITE_API void sqlite3_free_table(
  99640. char **azResult /* Result returned from from sqlite3_get_table() */
  99641. ){
  99642. if( azResult ){
  99643. int i, n;
  99644. azResult--;
  99645. assert( azResult!=0 );
  99646. n = SQLITE_PTR_TO_INT(azResult[0]);
  99647. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  99648. sqlite3_free(azResult);
  99649. }
  99650. }
  99651. #endif /* SQLITE_OMIT_GET_TABLE */
  99652. /************** End of table.c ***********************************************/
  99653. /************** Begin file trigger.c *****************************************/
  99654. /*
  99655. **
  99656. ** The author disclaims copyright to this source code. In place of
  99657. ** a legal notice, here is a blessing:
  99658. **
  99659. ** May you do good and not evil.
  99660. ** May you find forgiveness for yourself and forgive others.
  99661. ** May you share freely, never taking more than you give.
  99662. **
  99663. *************************************************************************
  99664. ** This file contains the implementation for TRIGGERs
  99665. */
  99666. #ifndef SQLITE_OMIT_TRIGGER
  99667. /*
  99668. ** Delete a linked list of TriggerStep structures.
  99669. */
  99670. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  99671. while( pTriggerStep ){
  99672. TriggerStep * pTmp = pTriggerStep;
  99673. pTriggerStep = pTriggerStep->pNext;
  99674. sqlite3ExprDelete(db, pTmp->pWhere);
  99675. sqlite3ExprListDelete(db, pTmp->pExprList);
  99676. sqlite3SelectDelete(db, pTmp->pSelect);
  99677. sqlite3IdListDelete(db, pTmp->pIdList);
  99678. sqlite3DbFree(db, pTmp);
  99679. }
  99680. }
  99681. /*
  99682. ** Given table pTab, return a list of all the triggers attached to
  99683. ** the table. The list is connected by Trigger.pNext pointers.
  99684. **
  99685. ** All of the triggers on pTab that are in the same database as pTab
  99686. ** are already attached to pTab->pTrigger. But there might be additional
  99687. ** triggers on pTab in the TEMP schema. This routine prepends all
  99688. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  99689. ** and returns the combined list.
  99690. **
  99691. ** To state it another way: This routine returns a list of all triggers
  99692. ** that fire off of pTab. The list will include any TEMP triggers on
  99693. ** pTab as well as the triggers lised in pTab->pTrigger.
  99694. */
  99695. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  99696. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  99697. Trigger *pList = 0; /* List of triggers to return */
  99698. if( pParse->disableTriggers ){
  99699. return 0;
  99700. }
  99701. if( pTmpSchema!=pTab->pSchema ){
  99702. HashElem *p;
  99703. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  99704. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  99705. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  99706. if( pTrig->pTabSchema==pTab->pSchema
  99707. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  99708. ){
  99709. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  99710. pList = pTrig;
  99711. }
  99712. }
  99713. }
  99714. return (pList ? pList : pTab->pTrigger);
  99715. }
  99716. /*
  99717. ** This is called by the parser when it sees a CREATE TRIGGER statement
  99718. ** up to the point of the BEGIN before the trigger actions. A Trigger
  99719. ** structure is generated based on the information available and stored
  99720. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  99721. ** sqlite3FinishTrigger() function is called to complete the trigger
  99722. ** construction process.
  99723. */
  99724. SQLITE_PRIVATE void sqlite3BeginTrigger(
  99725. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  99726. Token *pName1, /* The name of the trigger */
  99727. Token *pName2, /* The name of the trigger */
  99728. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  99729. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  99730. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  99731. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  99732. Expr *pWhen, /* WHEN clause */
  99733. int isTemp, /* True if the TEMPORARY keyword is present */
  99734. int noErr /* Suppress errors if the trigger already exists */
  99735. ){
  99736. Trigger *pTrigger = 0; /* The new trigger */
  99737. Table *pTab; /* Table that the trigger fires off of */
  99738. char *zName = 0; /* Name of the trigger */
  99739. sqlite3 *db = pParse->db; /* The database connection */
  99740. int iDb; /* The database to store the trigger in */
  99741. Token *pName; /* The unqualified db name */
  99742. DbFixer sFix; /* State vector for the DB fixer */
  99743. int iTabDb; /* Index of the database holding pTab */
  99744. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  99745. assert( pName2!=0 );
  99746. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  99747. assert( op>0 && op<0xff );
  99748. if( isTemp ){
  99749. /* If TEMP was specified, then the trigger name may not be qualified. */
  99750. if( pName2->n>0 ){
  99751. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  99752. goto trigger_cleanup;
  99753. }
  99754. iDb = 1;
  99755. pName = pName1;
  99756. }else{
  99757. /* Figure out the db that the trigger will be created in */
  99758. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  99759. if( iDb<0 ){
  99760. goto trigger_cleanup;
  99761. }
  99762. }
  99763. if( !pTableName || db->mallocFailed ){
  99764. goto trigger_cleanup;
  99765. }
  99766. /* A long-standing parser bug is that this syntax was allowed:
  99767. **
  99768. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  99769. ** ^^^^^^^^
  99770. **
  99771. ** To maintain backwards compatibility, ignore the database
  99772. ** name on pTableName if we are reparsing our of SQLITE_MASTER.
  99773. */
  99774. if( db->init.busy && iDb!=1 ){
  99775. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  99776. pTableName->a[0].zDatabase = 0;
  99777. }
  99778. /* If the trigger name was unqualified, and the table is a temp table,
  99779. ** then set iDb to 1 to create the trigger in the temporary database.
  99780. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  99781. ** exist, the error is caught by the block below.
  99782. */
  99783. pTab = sqlite3SrcListLookup(pParse, pTableName);
  99784. if( db->init.busy==0 && pName2->n==0 && pTab
  99785. && pTab->pSchema==db->aDb[1].pSchema ){
  99786. iDb = 1;
  99787. }
  99788. /* Ensure the table name matches database name and that the table exists */
  99789. if( db->mallocFailed ) goto trigger_cleanup;
  99790. assert( pTableName->nSrc==1 );
  99791. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  99792. if( sqlite3FixSrcList(&sFix, pTableName) ){
  99793. goto trigger_cleanup;
  99794. }
  99795. pTab = sqlite3SrcListLookup(pParse, pTableName);
  99796. if( !pTab ){
  99797. /* The table does not exist. */
  99798. if( db->init.iDb==1 ){
  99799. /* Ticket #3810.
  99800. ** Normally, whenever a table is dropped, all associated triggers are
  99801. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  99802. ** and the table is dropped by a different database connection, the
  99803. ** trigger is not visible to the database connection that does the
  99804. ** drop so the trigger cannot be dropped. This results in an
  99805. ** "orphaned trigger" - a trigger whose associated table is missing.
  99806. */
  99807. db->init.orphanTrigger = 1;
  99808. }
  99809. goto trigger_cleanup;
  99810. }
  99811. if( IsVirtual(pTab) ){
  99812. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  99813. goto trigger_cleanup;
  99814. }
  99815. /* Check that the trigger name is not reserved and that no trigger of the
  99816. ** specified name exists */
  99817. zName = sqlite3NameFromToken(db, pName);
  99818. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  99819. goto trigger_cleanup;
  99820. }
  99821. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99822. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
  99823. zName, sqlite3Strlen30(zName)) ){
  99824. if( !noErr ){
  99825. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  99826. }else{
  99827. assert( !db->init.busy );
  99828. sqlite3CodeVerifySchema(pParse, iDb);
  99829. }
  99830. goto trigger_cleanup;
  99831. }
  99832. /* Do not create a trigger on a system table */
  99833. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  99834. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  99835. pParse->nErr++;
  99836. goto trigger_cleanup;
  99837. }
  99838. /* INSTEAD of triggers are only for views and views only support INSTEAD
  99839. ** of triggers.
  99840. */
  99841. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  99842. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  99843. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  99844. goto trigger_cleanup;
  99845. }
  99846. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  99847. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  99848. " trigger on table: %S", pTableName, 0);
  99849. goto trigger_cleanup;
  99850. }
  99851. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  99852. #ifndef SQLITE_OMIT_AUTHORIZATION
  99853. {
  99854. int code = SQLITE_CREATE_TRIGGER;
  99855. const char *zDb = db->aDb[iTabDb].zName;
  99856. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  99857. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  99858. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  99859. goto trigger_cleanup;
  99860. }
  99861. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  99862. goto trigger_cleanup;
  99863. }
  99864. }
  99865. #endif
  99866. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  99867. ** cannot appear on views. So we might as well translate every
  99868. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  99869. ** elsewhere.
  99870. */
  99871. if (tr_tm == TK_INSTEAD){
  99872. tr_tm = TK_BEFORE;
  99873. }
  99874. /* Build the Trigger object */
  99875. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  99876. if( pTrigger==0 ) goto trigger_cleanup;
  99877. pTrigger->zName = zName;
  99878. zName = 0;
  99879. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  99880. pTrigger->pSchema = db->aDb[iDb].pSchema;
  99881. pTrigger->pTabSchema = pTab->pSchema;
  99882. pTrigger->op = (u8)op;
  99883. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  99884. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  99885. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  99886. assert( pParse->pNewTrigger==0 );
  99887. pParse->pNewTrigger = pTrigger;
  99888. trigger_cleanup:
  99889. sqlite3DbFree(db, zName);
  99890. sqlite3SrcListDelete(db, pTableName);
  99891. sqlite3IdListDelete(db, pColumns);
  99892. sqlite3ExprDelete(db, pWhen);
  99893. if( !pParse->pNewTrigger ){
  99894. sqlite3DeleteTrigger(db, pTrigger);
  99895. }else{
  99896. assert( pParse->pNewTrigger==pTrigger );
  99897. }
  99898. }
  99899. /*
  99900. ** This routine is called after all of the trigger actions have been parsed
  99901. ** in order to complete the process of building the trigger.
  99902. */
  99903. SQLITE_PRIVATE void sqlite3FinishTrigger(
  99904. Parse *pParse, /* Parser context */
  99905. TriggerStep *pStepList, /* The triggered program */
  99906. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  99907. ){
  99908. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  99909. char *zName; /* Name of trigger */
  99910. sqlite3 *db = pParse->db; /* The database */
  99911. DbFixer sFix; /* Fixer object */
  99912. int iDb; /* Database containing the trigger */
  99913. Token nameToken; /* Trigger name for error reporting */
  99914. pParse->pNewTrigger = 0;
  99915. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  99916. zName = pTrig->zName;
  99917. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  99918. pTrig->step_list = pStepList;
  99919. while( pStepList ){
  99920. pStepList->pTrig = pTrig;
  99921. pStepList = pStepList->pNext;
  99922. }
  99923. nameToken.z = pTrig->zName;
  99924. nameToken.n = sqlite3Strlen30(nameToken.z);
  99925. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  99926. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  99927. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  99928. ){
  99929. goto triggerfinish_cleanup;
  99930. }
  99931. /* if we are not initializing,
  99932. ** build the sqlite_master entry
  99933. */
  99934. if( !db->init.busy ){
  99935. Vdbe *v;
  99936. char *z;
  99937. /* Make an entry in the sqlite_master table */
  99938. v = sqlite3GetVdbe(pParse);
  99939. if( v==0 ) goto triggerfinish_cleanup;
  99940. sqlite3BeginWriteOperation(pParse, 0, iDb);
  99941. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  99942. sqlite3NestedParse(pParse,
  99943. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  99944. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  99945. pTrig->table, z);
  99946. sqlite3DbFree(db, z);
  99947. sqlite3ChangeCookie(pParse, iDb);
  99948. sqlite3VdbeAddParseSchemaOp(v, iDb,
  99949. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  99950. }
  99951. if( db->init.busy ){
  99952. Trigger *pLink = pTrig;
  99953. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  99954. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  99955. pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
  99956. if( pTrig ){
  99957. db->mallocFailed = 1;
  99958. }else if( pLink->pSchema==pLink->pTabSchema ){
  99959. Table *pTab;
  99960. int n = sqlite3Strlen30(pLink->table);
  99961. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
  99962. assert( pTab!=0 );
  99963. pLink->pNext = pTab->pTrigger;
  99964. pTab->pTrigger = pLink;
  99965. }
  99966. }
  99967. triggerfinish_cleanup:
  99968. sqlite3DeleteTrigger(db, pTrig);
  99969. assert( !pParse->pNewTrigger );
  99970. sqlite3DeleteTriggerStep(db, pStepList);
  99971. }
  99972. /*
  99973. ** Turn a SELECT statement (that the pSelect parameter points to) into
  99974. ** a trigger step. Return a pointer to a TriggerStep structure.
  99975. **
  99976. ** The parser calls this routine when it finds a SELECT statement in
  99977. ** body of a TRIGGER.
  99978. */
  99979. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  99980. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  99981. if( pTriggerStep==0 ) {
  99982. sqlite3SelectDelete(db, pSelect);
  99983. return 0;
  99984. }
  99985. pTriggerStep->op = TK_SELECT;
  99986. pTriggerStep->pSelect = pSelect;
  99987. pTriggerStep->orconf = OE_Default;
  99988. return pTriggerStep;
  99989. }
  99990. /*
  99991. ** Allocate space to hold a new trigger step. The allocated space
  99992. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  99993. **
  99994. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  99995. */
  99996. static TriggerStep *triggerStepAllocate(
  99997. sqlite3 *db, /* Database connection */
  99998. u8 op, /* Trigger opcode */
  99999. Token *pName /* The target name */
  100000. ){
  100001. TriggerStep *pTriggerStep;
  100002. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  100003. if( pTriggerStep ){
  100004. char *z = (char*)&pTriggerStep[1];
  100005. memcpy(z, pName->z, pName->n);
  100006. pTriggerStep->target.z = z;
  100007. pTriggerStep->target.n = pName->n;
  100008. pTriggerStep->op = op;
  100009. }
  100010. return pTriggerStep;
  100011. }
  100012. /*
  100013. ** Build a trigger step out of an INSERT statement. Return a pointer
  100014. ** to the new trigger step.
  100015. **
  100016. ** The parser calls this routine when it sees an INSERT inside the
  100017. ** body of a trigger.
  100018. */
  100019. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  100020. sqlite3 *db, /* The database connection */
  100021. Token *pTableName, /* Name of the table into which we insert */
  100022. IdList *pColumn, /* List of columns in pTableName to insert into */
  100023. ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  100024. Select *pSelect, /* A SELECT statement that supplies values */
  100025. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  100026. ){
  100027. TriggerStep *pTriggerStep;
  100028. assert(pEList == 0 || pSelect == 0);
  100029. assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
  100030. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  100031. if( pTriggerStep ){
  100032. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  100033. pTriggerStep->pIdList = pColumn;
  100034. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  100035. pTriggerStep->orconf = orconf;
  100036. }else{
  100037. sqlite3IdListDelete(db, pColumn);
  100038. }
  100039. sqlite3ExprListDelete(db, pEList);
  100040. sqlite3SelectDelete(db, pSelect);
  100041. return pTriggerStep;
  100042. }
  100043. /*
  100044. ** Construct a trigger step that implements an UPDATE statement and return
  100045. ** a pointer to that trigger step. The parser calls this routine when it
  100046. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  100047. */
  100048. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  100049. sqlite3 *db, /* The database connection */
  100050. Token *pTableName, /* Name of the table to be updated */
  100051. ExprList *pEList, /* The SET clause: list of column and new values */
  100052. Expr *pWhere, /* The WHERE clause */
  100053. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  100054. ){
  100055. TriggerStep *pTriggerStep;
  100056. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  100057. if( pTriggerStep ){
  100058. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  100059. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  100060. pTriggerStep->orconf = orconf;
  100061. }
  100062. sqlite3ExprListDelete(db, pEList);
  100063. sqlite3ExprDelete(db, pWhere);
  100064. return pTriggerStep;
  100065. }
  100066. /*
  100067. ** Construct a trigger step that implements a DELETE statement and return
  100068. ** a pointer to that trigger step. The parser calls this routine when it
  100069. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  100070. */
  100071. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  100072. sqlite3 *db, /* Database connection */
  100073. Token *pTableName, /* The table from which rows are deleted */
  100074. Expr *pWhere /* The WHERE clause */
  100075. ){
  100076. TriggerStep *pTriggerStep;
  100077. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  100078. if( pTriggerStep ){
  100079. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  100080. pTriggerStep->orconf = OE_Default;
  100081. }
  100082. sqlite3ExprDelete(db, pWhere);
  100083. return pTriggerStep;
  100084. }
  100085. /*
  100086. ** Recursively delete a Trigger structure
  100087. */
  100088. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  100089. if( pTrigger==0 ) return;
  100090. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  100091. sqlite3DbFree(db, pTrigger->zName);
  100092. sqlite3DbFree(db, pTrigger->table);
  100093. sqlite3ExprDelete(db, pTrigger->pWhen);
  100094. sqlite3IdListDelete(db, pTrigger->pColumns);
  100095. sqlite3DbFree(db, pTrigger);
  100096. }
  100097. /*
  100098. ** This function is called to drop a trigger from the database schema.
  100099. **
  100100. ** This may be called directly from the parser and therefore identifies
  100101. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  100102. ** same job as this routine except it takes a pointer to the trigger
  100103. ** instead of the trigger name.
  100104. **/
  100105. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  100106. Trigger *pTrigger = 0;
  100107. int i;
  100108. const char *zDb;
  100109. const char *zName;
  100110. int nName;
  100111. sqlite3 *db = pParse->db;
  100112. if( db->mallocFailed ) goto drop_trigger_cleanup;
  100113. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  100114. goto drop_trigger_cleanup;
  100115. }
  100116. assert( pName->nSrc==1 );
  100117. zDb = pName->a[0].zDatabase;
  100118. zName = pName->a[0].zName;
  100119. nName = sqlite3Strlen30(zName);
  100120. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  100121. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  100122. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  100123. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  100124. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  100125. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
  100126. if( pTrigger ) break;
  100127. }
  100128. if( !pTrigger ){
  100129. if( !noErr ){
  100130. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  100131. }else{
  100132. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  100133. }
  100134. pParse->checkSchema = 1;
  100135. goto drop_trigger_cleanup;
  100136. }
  100137. sqlite3DropTriggerPtr(pParse, pTrigger);
  100138. drop_trigger_cleanup:
  100139. sqlite3SrcListDelete(db, pName);
  100140. }
  100141. /*
  100142. ** Return a pointer to the Table structure for the table that a trigger
  100143. ** is set on.
  100144. */
  100145. static Table *tableOfTrigger(Trigger *pTrigger){
  100146. int n = sqlite3Strlen30(pTrigger->table);
  100147. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
  100148. }
  100149. /*
  100150. ** Drop a trigger given a pointer to that trigger.
  100151. */
  100152. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  100153. Table *pTable;
  100154. Vdbe *v;
  100155. sqlite3 *db = pParse->db;
  100156. int iDb;
  100157. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  100158. assert( iDb>=0 && iDb<db->nDb );
  100159. pTable = tableOfTrigger(pTrigger);
  100160. assert( pTable );
  100161. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  100162. #ifndef SQLITE_OMIT_AUTHORIZATION
  100163. {
  100164. int code = SQLITE_DROP_TRIGGER;
  100165. const char *zDb = db->aDb[iDb].zName;
  100166. const char *zTab = SCHEMA_TABLE(iDb);
  100167. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  100168. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  100169. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  100170. return;
  100171. }
  100172. }
  100173. #endif
  100174. /* Generate code to destroy the database record of the trigger.
  100175. */
  100176. assert( pTable!=0 );
  100177. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  100178. int base;
  100179. static const VdbeOpList dropTrigger[] = {
  100180. { OP_Rewind, 0, ADDR(9), 0},
  100181. { OP_String8, 0, 1, 0}, /* 1 */
  100182. { OP_Column, 0, 1, 2},
  100183. { OP_Ne, 2, ADDR(8), 1},
  100184. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  100185. { OP_Column, 0, 0, 2},
  100186. { OP_Ne, 2, ADDR(8), 1},
  100187. { OP_Delete, 0, 0, 0},
  100188. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  100189. };
  100190. sqlite3BeginWriteOperation(pParse, 0, iDb);
  100191. sqlite3OpenMasterTable(pParse, iDb);
  100192. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  100193. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  100194. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  100195. sqlite3ChangeCookie(pParse, iDb);
  100196. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  100197. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  100198. if( pParse->nMem<3 ){
  100199. pParse->nMem = 3;
  100200. }
  100201. }
  100202. }
  100203. /*
  100204. ** Remove a trigger from the hash tables of the sqlite* pointer.
  100205. */
  100206. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  100207. Trigger *pTrigger;
  100208. Hash *pHash;
  100209. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  100210. pHash = &(db->aDb[iDb].pSchema->trigHash);
  100211. pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
  100212. if( ALWAYS(pTrigger) ){
  100213. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  100214. Table *pTab = tableOfTrigger(pTrigger);
  100215. Trigger **pp;
  100216. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  100217. *pp = (*pp)->pNext;
  100218. }
  100219. sqlite3DeleteTrigger(db, pTrigger);
  100220. db->flags |= SQLITE_InternChanges;
  100221. }
  100222. }
  100223. /*
  100224. ** pEList is the SET clause of an UPDATE statement. Each entry
  100225. ** in pEList is of the format <id>=<expr>. If any of the entries
  100226. ** in pEList have an <id> which matches an identifier in pIdList,
  100227. ** then return TRUE. If pIdList==NULL, then it is considered a
  100228. ** wildcard that matches anything. Likewise if pEList==NULL then
  100229. ** it matches anything so always return true. Return false only
  100230. ** if there is no match.
  100231. */
  100232. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  100233. int e;
  100234. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  100235. for(e=0; e<pEList->nExpr; e++){
  100236. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  100237. }
  100238. return 0;
  100239. }
  100240. /*
  100241. ** Return a list of all triggers on table pTab if there exists at least
  100242. ** one trigger that must be fired when an operation of type 'op' is
  100243. ** performed on the table, and, if that operation is an UPDATE, if at
  100244. ** least one of the columns in pChanges is being modified.
  100245. */
  100246. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  100247. Parse *pParse, /* Parse context */
  100248. Table *pTab, /* The table the contains the triggers */
  100249. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  100250. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  100251. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100252. ){
  100253. int mask = 0;
  100254. Trigger *pList = 0;
  100255. Trigger *p;
  100256. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  100257. pList = sqlite3TriggerList(pParse, pTab);
  100258. }
  100259. assert( pList==0 || IsVirtual(pTab)==0 );
  100260. for(p=pList; p; p=p->pNext){
  100261. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  100262. mask |= p->tr_tm;
  100263. }
  100264. }
  100265. if( pMask ){
  100266. *pMask = mask;
  100267. }
  100268. return (mask ? pList : 0);
  100269. }
  100270. /*
  100271. ** Convert the pStep->target token into a SrcList and return a pointer
  100272. ** to that SrcList.
  100273. **
  100274. ** This routine adds a specific database name, if needed, to the target when
  100275. ** forming the SrcList. This prevents a trigger in one database from
  100276. ** referring to a target in another database. An exception is when the
  100277. ** trigger is in TEMP in which case it can refer to any other database it
  100278. ** wants.
  100279. */
  100280. static SrcList *targetSrcList(
  100281. Parse *pParse, /* The parsing context */
  100282. TriggerStep *pStep /* The trigger containing the target token */
  100283. ){
  100284. int iDb; /* Index of the database to use */
  100285. SrcList *pSrc; /* SrcList to be returned */
  100286. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  100287. if( pSrc ){
  100288. assert( pSrc->nSrc>0 );
  100289. assert( pSrc->a!=0 );
  100290. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  100291. if( iDb==0 || iDb>=2 ){
  100292. sqlite3 *db = pParse->db;
  100293. assert( iDb<pParse->db->nDb );
  100294. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  100295. }
  100296. }
  100297. return pSrc;
  100298. }
  100299. /*
  100300. ** Generate VDBE code for the statements inside the body of a single
  100301. ** trigger.
  100302. */
  100303. static int codeTriggerProgram(
  100304. Parse *pParse, /* The parser context */
  100305. TriggerStep *pStepList, /* List of statements inside the trigger body */
  100306. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  100307. ){
  100308. TriggerStep *pStep;
  100309. Vdbe *v = pParse->pVdbe;
  100310. sqlite3 *db = pParse->db;
  100311. assert( pParse->pTriggerTab && pParse->pToplevel );
  100312. assert( pStepList );
  100313. assert( v!=0 );
  100314. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  100315. /* Figure out the ON CONFLICT policy that will be used for this step
  100316. ** of the trigger program. If the statement that caused this trigger
  100317. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  100318. ** the ON CONFLICT policy that was specified as part of the trigger
  100319. ** step statement. Example:
  100320. **
  100321. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  100322. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  100323. ** END;
  100324. **
  100325. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  100326. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  100327. */
  100328. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  100329. /* Clear the cookieGoto flag. When coding triggers, the cookieGoto
  100330. ** variable is used as a flag to indicate to sqlite3ExprCodeConstants()
  100331. ** that it is not safe to refactor constants (this happens after the
  100332. ** start of the first loop in the SQL statement is coded - at that
  100333. ** point code may be conditionally executed, so it is no longer safe to
  100334. ** initialize constant register values). */
  100335. assert( pParse->cookieGoto==0 || pParse->cookieGoto==-1 );
  100336. pParse->cookieGoto = 0;
  100337. switch( pStep->op ){
  100338. case TK_UPDATE: {
  100339. sqlite3Update(pParse,
  100340. targetSrcList(pParse, pStep),
  100341. sqlite3ExprListDup(db, pStep->pExprList, 0),
  100342. sqlite3ExprDup(db, pStep->pWhere, 0),
  100343. pParse->eOrconf
  100344. );
  100345. break;
  100346. }
  100347. case TK_INSERT: {
  100348. sqlite3Insert(pParse,
  100349. targetSrcList(pParse, pStep),
  100350. sqlite3ExprListDup(db, pStep->pExprList, 0),
  100351. sqlite3SelectDup(db, pStep->pSelect, 0),
  100352. sqlite3IdListDup(db, pStep->pIdList),
  100353. pParse->eOrconf
  100354. );
  100355. break;
  100356. }
  100357. case TK_DELETE: {
  100358. sqlite3DeleteFrom(pParse,
  100359. targetSrcList(pParse, pStep),
  100360. sqlite3ExprDup(db, pStep->pWhere, 0)
  100361. );
  100362. break;
  100363. }
  100364. default: assert( pStep->op==TK_SELECT ); {
  100365. SelectDest sDest;
  100366. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  100367. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  100368. sqlite3Select(pParse, pSelect, &sDest);
  100369. sqlite3SelectDelete(db, pSelect);
  100370. break;
  100371. }
  100372. }
  100373. if( pStep->op!=TK_SELECT ){
  100374. sqlite3VdbeAddOp0(v, OP_ResetCount);
  100375. }
  100376. }
  100377. return 0;
  100378. }
  100379. #ifdef SQLITE_DEBUG
  100380. /*
  100381. ** This function is used to add VdbeComment() annotations to a VDBE
  100382. ** program. It is not used in production code, only for debugging.
  100383. */
  100384. static const char *onErrorText(int onError){
  100385. switch( onError ){
  100386. case OE_Abort: return "abort";
  100387. case OE_Rollback: return "rollback";
  100388. case OE_Fail: return "fail";
  100389. case OE_Replace: return "replace";
  100390. case OE_Ignore: return "ignore";
  100391. case OE_Default: return "default";
  100392. }
  100393. return "n/a";
  100394. }
  100395. #endif
  100396. /*
  100397. ** Parse context structure pFrom has just been used to create a sub-vdbe
  100398. ** (trigger program). If an error has occurred, transfer error information
  100399. ** from pFrom to pTo.
  100400. */
  100401. static void transferParseError(Parse *pTo, Parse *pFrom){
  100402. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  100403. assert( pTo->zErrMsg==0 || pTo->nErr );
  100404. if( pTo->nErr==0 ){
  100405. pTo->zErrMsg = pFrom->zErrMsg;
  100406. pTo->nErr = pFrom->nErr;
  100407. }else{
  100408. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  100409. }
  100410. }
  100411. /*
  100412. ** Create and populate a new TriggerPrg object with a sub-program
  100413. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  100414. */
  100415. static TriggerPrg *codeRowTrigger(
  100416. Parse *pParse, /* Current parse context */
  100417. Trigger *pTrigger, /* Trigger to code */
  100418. Table *pTab, /* The table pTrigger is attached to */
  100419. int orconf /* ON CONFLICT policy to code trigger program with */
  100420. ){
  100421. Parse *pTop = sqlite3ParseToplevel(pParse);
  100422. sqlite3 *db = pParse->db; /* Database handle */
  100423. TriggerPrg *pPrg; /* Value to return */
  100424. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  100425. Vdbe *v; /* Temporary VM */
  100426. NameContext sNC; /* Name context for sub-vdbe */
  100427. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  100428. Parse *pSubParse; /* Parse context for sub-vdbe */
  100429. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  100430. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  100431. assert( pTop->pVdbe );
  100432. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  100433. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  100434. ** list of the top-level Parse object sooner rather than later. */
  100435. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  100436. if( !pPrg ) return 0;
  100437. pPrg->pNext = pTop->pTriggerPrg;
  100438. pTop->pTriggerPrg = pPrg;
  100439. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  100440. if( !pProgram ) return 0;
  100441. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  100442. pPrg->pTrigger = pTrigger;
  100443. pPrg->orconf = orconf;
  100444. pPrg->aColmask[0] = 0xffffffff;
  100445. pPrg->aColmask[1] = 0xffffffff;
  100446. /* Allocate and populate a new Parse context to use for coding the
  100447. ** trigger sub-program. */
  100448. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  100449. if( !pSubParse ) return 0;
  100450. memset(&sNC, 0, sizeof(sNC));
  100451. sNC.pParse = pSubParse;
  100452. pSubParse->db = db;
  100453. pSubParse->pTriggerTab = pTab;
  100454. pSubParse->pToplevel = pTop;
  100455. pSubParse->zAuthContext = pTrigger->zName;
  100456. pSubParse->eTriggerOp = pTrigger->op;
  100457. pSubParse->nQueryLoop = pParse->nQueryLoop;
  100458. v = sqlite3GetVdbe(pSubParse);
  100459. if( v ){
  100460. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  100461. pTrigger->zName, onErrorText(orconf),
  100462. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  100463. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  100464. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  100465. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  100466. pTab->zName
  100467. ));
  100468. #ifndef SQLITE_OMIT_TRACE
  100469. sqlite3VdbeChangeP4(v, -1,
  100470. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  100471. );
  100472. #endif
  100473. /* If one was specified, code the WHEN clause. If it evaluates to false
  100474. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  100475. ** OP_Halt inserted at the end of the program. */
  100476. if( pTrigger->pWhen ){
  100477. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  100478. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  100479. && db->mallocFailed==0
  100480. ){
  100481. iEndTrigger = sqlite3VdbeMakeLabel(v);
  100482. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  100483. }
  100484. sqlite3ExprDelete(db, pWhen);
  100485. }
  100486. /* Code the trigger program into the sub-vdbe. */
  100487. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  100488. /* Insert an OP_Halt at the end of the sub-program. */
  100489. if( iEndTrigger ){
  100490. sqlite3VdbeResolveLabel(v, iEndTrigger);
  100491. }
  100492. sqlite3VdbeAddOp0(v, OP_Halt);
  100493. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  100494. transferParseError(pParse, pSubParse);
  100495. if( db->mallocFailed==0 ){
  100496. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  100497. }
  100498. pProgram->nMem = pSubParse->nMem;
  100499. pProgram->nCsr = pSubParse->nTab;
  100500. pProgram->nOnce = pSubParse->nOnce;
  100501. pProgram->token = (void *)pTrigger;
  100502. pPrg->aColmask[0] = pSubParse->oldmask;
  100503. pPrg->aColmask[1] = pSubParse->newmask;
  100504. sqlite3VdbeDelete(v);
  100505. }
  100506. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  100507. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  100508. sqlite3StackFree(db, pSubParse);
  100509. return pPrg;
  100510. }
  100511. /*
  100512. ** Return a pointer to a TriggerPrg object containing the sub-program for
  100513. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  100514. ** TriggerPrg object exists, a new object is allocated and populated before
  100515. ** being returned.
  100516. */
  100517. static TriggerPrg *getRowTrigger(
  100518. Parse *pParse, /* Current parse context */
  100519. Trigger *pTrigger, /* Trigger to code */
  100520. Table *pTab, /* The table trigger pTrigger is attached to */
  100521. int orconf /* ON CONFLICT algorithm. */
  100522. ){
  100523. Parse *pRoot = sqlite3ParseToplevel(pParse);
  100524. TriggerPrg *pPrg;
  100525. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  100526. /* It may be that this trigger has already been coded (or is in the
  100527. ** process of being coded). If this is the case, then an entry with
  100528. ** a matching TriggerPrg.pTrigger field will be present somewhere
  100529. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  100530. for(pPrg=pRoot->pTriggerPrg;
  100531. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  100532. pPrg=pPrg->pNext
  100533. );
  100534. /* If an existing TriggerPrg could not be located, create a new one. */
  100535. if( !pPrg ){
  100536. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  100537. }
  100538. return pPrg;
  100539. }
  100540. /*
  100541. ** Generate code for the trigger program associated with trigger p on
  100542. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  100543. ** function are the same as those described in the header function for
  100544. ** sqlite3CodeRowTrigger()
  100545. */
  100546. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  100547. Parse *pParse, /* Parse context */
  100548. Trigger *p, /* Trigger to code */
  100549. Table *pTab, /* The table to code triggers from */
  100550. int reg, /* Reg array containing OLD.* and NEW.* values */
  100551. int orconf, /* ON CONFLICT policy */
  100552. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  100553. ){
  100554. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  100555. TriggerPrg *pPrg;
  100556. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  100557. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  100558. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  100559. ** is a pointer to the sub-vdbe containing the trigger program. */
  100560. if( pPrg ){
  100561. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  100562. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  100563. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  100564. VdbeComment(
  100565. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  100566. /* Set the P5 operand of the OP_Program instruction to non-zero if
  100567. ** recursive invocation of this trigger program is disallowed. Recursive
  100568. ** invocation is disallowed if (a) the sub-program is really a trigger,
  100569. ** not a foreign key action, and (b) the flag to enable recursive triggers
  100570. ** is clear. */
  100571. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  100572. }
  100573. }
  100574. /*
  100575. ** This is called to code the required FOR EACH ROW triggers for an operation
  100576. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  100577. ** is given by the op parameter. The tr_tm parameter determines whether the
  100578. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  100579. ** parameter pChanges is passed the list of columns being modified.
  100580. **
  100581. ** If there are no triggers that fire at the specified time for the specified
  100582. ** operation on pTab, this function is a no-op.
  100583. **
  100584. ** The reg argument is the address of the first in an array of registers
  100585. ** that contain the values substituted for the new.* and old.* references
  100586. ** in the trigger program. If N is the number of columns in table pTab
  100587. ** (a copy of pTab->nCol), then registers are populated as follows:
  100588. **
  100589. ** Register Contains
  100590. ** ------------------------------------------------------
  100591. ** reg+0 OLD.rowid
  100592. ** reg+1 OLD.* value of left-most column of pTab
  100593. ** ... ...
  100594. ** reg+N OLD.* value of right-most column of pTab
  100595. ** reg+N+1 NEW.rowid
  100596. ** reg+N+2 OLD.* value of left-most column of pTab
  100597. ** ... ...
  100598. ** reg+N+N+1 NEW.* value of right-most column of pTab
  100599. **
  100600. ** For ON DELETE triggers, the registers containing the NEW.* values will
  100601. ** never be accessed by the trigger program, so they are not allocated or
  100602. ** populated by the caller (there is no data to populate them with anyway).
  100603. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  100604. ** are never accessed, and so are not allocated by the caller. So, for an
  100605. ** ON INSERT trigger, the value passed to this function as parameter reg
  100606. ** is not a readable register, although registers (reg+N) through
  100607. ** (reg+N+N+1) are.
  100608. **
  100609. ** Parameter orconf is the default conflict resolution algorithm for the
  100610. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  100611. ** is the instruction that control should jump to if a trigger program
  100612. ** raises an IGNORE exception.
  100613. */
  100614. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  100615. Parse *pParse, /* Parse context */
  100616. Trigger *pTrigger, /* List of triggers on table pTab */
  100617. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  100618. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  100619. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  100620. Table *pTab, /* The table to code triggers from */
  100621. int reg, /* The first in an array of registers (see above) */
  100622. int orconf, /* ON CONFLICT policy */
  100623. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  100624. ){
  100625. Trigger *p; /* Used to iterate through pTrigger list */
  100626. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  100627. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  100628. assert( (op==TK_UPDATE)==(pChanges!=0) );
  100629. for(p=pTrigger; p; p=p->pNext){
  100630. /* Sanity checking: The schema for the trigger and for the table are
  100631. ** always defined. The trigger must be in the same schema as the table
  100632. ** or else it must be a TEMP trigger. */
  100633. assert( p->pSchema!=0 );
  100634. assert( p->pTabSchema!=0 );
  100635. assert( p->pSchema==p->pTabSchema
  100636. || p->pSchema==pParse->db->aDb[1].pSchema );
  100637. /* Determine whether we should code this trigger */
  100638. if( p->op==op
  100639. && p->tr_tm==tr_tm
  100640. && checkColumnOverlap(p->pColumns, pChanges)
  100641. ){
  100642. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  100643. }
  100644. }
  100645. }
  100646. /*
  100647. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  100648. ** This function returns a 32-bit bitmask indicating which columns of the
  100649. ** old.* or new.* tables actually are used by triggers. This information
  100650. ** may be used by the caller, for example, to avoid having to load the entire
  100651. ** old.* record into memory when executing an UPDATE or DELETE command.
  100652. **
  100653. ** Bit 0 of the returned mask is set if the left-most column of the
  100654. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  100655. ** the second leftmost column value is required, and so on. If there
  100656. ** are more than 32 columns in the table, and at least one of the columns
  100657. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  100658. **
  100659. ** It is not possible to determine if the old.rowid or new.rowid column is
  100660. ** accessed by triggers. The caller must always assume that it is.
  100661. **
  100662. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  100663. ** applies to the old.* table. If 1, the new.* table.
  100664. **
  100665. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  100666. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  100667. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  100668. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  100669. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  100670. */
  100671. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  100672. Parse *pParse, /* Parse context */
  100673. Trigger *pTrigger, /* List of triggers on table pTab */
  100674. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  100675. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  100676. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100677. Table *pTab, /* The table to code triggers from */
  100678. int orconf /* Default ON CONFLICT policy for trigger steps */
  100679. ){
  100680. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  100681. u32 mask = 0;
  100682. Trigger *p;
  100683. assert( isNew==1 || isNew==0 );
  100684. for(p=pTrigger; p; p=p->pNext){
  100685. if( p->op==op && (tr_tm&p->tr_tm)
  100686. && checkColumnOverlap(p->pColumns,pChanges)
  100687. ){
  100688. TriggerPrg *pPrg;
  100689. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  100690. if( pPrg ){
  100691. mask |= pPrg->aColmask[isNew];
  100692. }
  100693. }
  100694. }
  100695. return mask;
  100696. }
  100697. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  100698. /************** End of trigger.c *********************************************/
  100699. /************** Begin file update.c ******************************************/
  100700. /*
  100701. ** 2001 September 15
  100702. **
  100703. ** The author disclaims copyright to this source code. In place of
  100704. ** a legal notice, here is a blessing:
  100705. **
  100706. ** May you do good and not evil.
  100707. ** May you find forgiveness for yourself and forgive others.
  100708. ** May you share freely, never taking more than you give.
  100709. **
  100710. *************************************************************************
  100711. ** This file contains C code routines that are called by the parser
  100712. ** to handle UPDATE statements.
  100713. */
  100714. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100715. /* Forward declaration */
  100716. static void updateVirtualTable(
  100717. Parse *pParse, /* The parsing context */
  100718. SrcList *pSrc, /* The virtual table to be modified */
  100719. Table *pTab, /* The virtual table */
  100720. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  100721. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  100722. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  100723. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  100724. int onError /* ON CONFLICT strategy */
  100725. );
  100726. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  100727. /*
  100728. ** The most recently coded instruction was an OP_Column to retrieve the
  100729. ** i-th column of table pTab. This routine sets the P4 parameter of the
  100730. ** OP_Column to the default value, if any.
  100731. **
  100732. ** The default value of a column is specified by a DEFAULT clause in the
  100733. ** column definition. This was either supplied by the user when the table
  100734. ** was created, or added later to the table definition by an ALTER TABLE
  100735. ** command. If the latter, then the row-records in the table btree on disk
  100736. ** may not contain a value for the column and the default value, taken
  100737. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  100738. ** If the former, then all row-records are guaranteed to include a value
  100739. ** for the column and the P4 value is not required.
  100740. **
  100741. ** Column definitions created by an ALTER TABLE command may only have
  100742. ** literal default values specified: a number, null or a string. (If a more
  100743. ** complicated default expression value was provided, it is evaluated
  100744. ** when the ALTER TABLE is executed and one of the literal values written
  100745. ** into the sqlite_master table.)
  100746. **
  100747. ** Therefore, the P4 parameter is only required if the default value for
  100748. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  100749. ** function is capable of transforming these types of expressions into
  100750. ** sqlite3_value objects.
  100751. **
  100752. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  100753. ** on register iReg. This is used when an equivalent integer value is
  100754. ** stored in place of an 8-byte floating point value in order to save
  100755. ** space.
  100756. */
  100757. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  100758. assert( pTab!=0 );
  100759. if( !pTab->pSelect ){
  100760. sqlite3_value *pValue = 0;
  100761. u8 enc = ENC(sqlite3VdbeDb(v));
  100762. Column *pCol = &pTab->aCol[i];
  100763. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  100764. assert( i<pTab->nCol );
  100765. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  100766. pCol->affinity, &pValue);
  100767. if( pValue ){
  100768. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  100769. }
  100770. #ifndef SQLITE_OMIT_FLOATING_POINT
  100771. if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  100772. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  100773. }
  100774. #endif
  100775. }
  100776. }
  100777. /*
  100778. ** Process an UPDATE statement.
  100779. **
  100780. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  100781. ** \_______/ \________/ \______/ \________________/
  100782. * onError pTabList pChanges pWhere
  100783. */
  100784. SQLITE_PRIVATE void sqlite3Update(
  100785. Parse *pParse, /* The parser context */
  100786. SrcList *pTabList, /* The table in which we should change things */
  100787. ExprList *pChanges, /* Things to be changed */
  100788. Expr *pWhere, /* The WHERE clause. May be null */
  100789. int onError /* How to handle constraint errors */
  100790. ){
  100791. int i, j; /* Loop counters */
  100792. Table *pTab; /* The table to be updated */
  100793. int addr = 0; /* VDBE instruction address of the start of the loop */
  100794. WhereInfo *pWInfo; /* Information about the WHERE clause */
  100795. Vdbe *v; /* The virtual database engine */
  100796. Index *pIdx; /* For looping over indices */
  100797. int nIdx; /* Number of indices that need updating */
  100798. int iCur; /* VDBE Cursor number of pTab */
  100799. sqlite3 *db; /* The database structure */
  100800. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  100801. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  100802. ** an expression for the i-th column of the table.
  100803. ** aXRef[i]==-1 if the i-th column is not changed. */
  100804. int chngRowid; /* True if the record number is being changed */
  100805. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  100806. int openAll = 0; /* True if all indices need to be opened */
  100807. AuthContext sContext; /* The authorization context */
  100808. NameContext sNC; /* The name-context to resolve expressions in */
  100809. int iDb; /* Database containing the table being updated */
  100810. int okOnePass; /* True for one-pass algorithm without the FIFO */
  100811. int hasFK; /* True if foreign key processing is required */
  100812. #ifndef SQLITE_OMIT_TRIGGER
  100813. int isView; /* True when updating a view (INSTEAD OF trigger) */
  100814. Trigger *pTrigger; /* List of triggers on pTab, if required */
  100815. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  100816. #endif
  100817. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  100818. /* Register Allocations */
  100819. int regRowCount = 0; /* A count of rows changed */
  100820. int regOldRowid; /* The old rowid */
  100821. int regNewRowid; /* The new rowid */
  100822. int regNew; /* Content of the NEW.* table in triggers */
  100823. int regOld = 0; /* Content of OLD.* table in triggers */
  100824. int regRowSet = 0; /* Rowset of rows to be updated */
  100825. memset(&sContext, 0, sizeof(sContext));
  100826. db = pParse->db;
  100827. if( pParse->nErr || db->mallocFailed ){
  100828. goto update_cleanup;
  100829. }
  100830. assert( pTabList->nSrc==1 );
  100831. /* Locate the table which we want to update.
  100832. */
  100833. pTab = sqlite3SrcListLookup(pParse, pTabList);
  100834. if( pTab==0 ) goto update_cleanup;
  100835. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  100836. /* Figure out if we have any triggers and if the table being
  100837. ** updated is a view.
  100838. */
  100839. #ifndef SQLITE_OMIT_TRIGGER
  100840. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  100841. isView = pTab->pSelect!=0;
  100842. assert( pTrigger || tmask==0 );
  100843. #else
  100844. # define pTrigger 0
  100845. # define isView 0
  100846. # define tmask 0
  100847. #endif
  100848. #ifdef SQLITE_OMIT_VIEW
  100849. # undef isView
  100850. # define isView 0
  100851. #endif
  100852. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  100853. goto update_cleanup;
  100854. }
  100855. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  100856. goto update_cleanup;
  100857. }
  100858. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
  100859. if( aXRef==0 ) goto update_cleanup;
  100860. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  100861. /* Allocate a cursors for the main database table and for all indices.
  100862. ** The index cursors might not be used, but if they are used they
  100863. ** need to occur right after the database cursor. So go ahead and
  100864. ** allocate enough space, just in case.
  100865. */
  100866. pTabList->a[0].iCursor = iCur = pParse->nTab++;
  100867. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  100868. pParse->nTab++;
  100869. }
  100870. /* Initialize the name-context */
  100871. memset(&sNC, 0, sizeof(sNC));
  100872. sNC.pParse = pParse;
  100873. sNC.pSrcList = pTabList;
  100874. /* Resolve the column names in all the expressions of the
  100875. ** of the UPDATE statement. Also find the column index
  100876. ** for each column to be updated in the pChanges array. For each
  100877. ** column to be updated, make sure we have authorization to change
  100878. ** that column.
  100879. */
  100880. chngRowid = 0;
  100881. for(i=0; i<pChanges->nExpr; i++){
  100882. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  100883. goto update_cleanup;
  100884. }
  100885. for(j=0; j<pTab->nCol; j++){
  100886. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  100887. if( j==pTab->iPKey ){
  100888. chngRowid = 1;
  100889. pRowidExpr = pChanges->a[i].pExpr;
  100890. }
  100891. aXRef[j] = i;
  100892. break;
  100893. }
  100894. }
  100895. if( j>=pTab->nCol ){
  100896. if( sqlite3IsRowid(pChanges->a[i].zName) ){
  100897. j = -1;
  100898. chngRowid = 1;
  100899. pRowidExpr = pChanges->a[i].pExpr;
  100900. }else{
  100901. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  100902. pParse->checkSchema = 1;
  100903. goto update_cleanup;
  100904. }
  100905. }
  100906. #ifndef SQLITE_OMIT_AUTHORIZATION
  100907. {
  100908. int rc;
  100909. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  100910. j<0 ? "ROWID" : pTab->aCol[j].zName,
  100911. db->aDb[iDb].zName);
  100912. if( rc==SQLITE_DENY ){
  100913. goto update_cleanup;
  100914. }else if( rc==SQLITE_IGNORE ){
  100915. aXRef[j] = -1;
  100916. }
  100917. }
  100918. #endif
  100919. }
  100920. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
  100921. /* Allocate memory for the array aRegIdx[]. There is one entry in the
  100922. ** array for each index associated with table being updated. Fill in
  100923. ** the value with a register number for indices that are to be used
  100924. ** and with zero for unused indices.
  100925. */
  100926. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  100927. if( nIdx>0 ){
  100928. aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
  100929. if( aRegIdx==0 ) goto update_cleanup;
  100930. }
  100931. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  100932. int reg;
  100933. if( hasFK || chngRowid || pIdx->pPartIdxWhere ){
  100934. reg = ++pParse->nMem;
  100935. }else{
  100936. reg = 0;
  100937. for(i=0; i<pIdx->nColumn; i++){
  100938. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  100939. reg = ++pParse->nMem;
  100940. break;
  100941. }
  100942. }
  100943. }
  100944. aRegIdx[j] = reg;
  100945. }
  100946. /* Begin generating code. */
  100947. v = sqlite3GetVdbe(pParse);
  100948. if( v==0 ) goto update_cleanup;
  100949. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  100950. sqlite3BeginWriteOperation(pParse, 1, iDb);
  100951. #ifndef SQLITE_OMIT_VIRTUALTABLE
  100952. /* Virtual tables must be handled separately */
  100953. if( IsVirtual(pTab) ){
  100954. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  100955. pWhere, onError);
  100956. pWhere = 0;
  100957. pTabList = 0;
  100958. goto update_cleanup;
  100959. }
  100960. #endif
  100961. /* Allocate required registers. */
  100962. regRowSet = ++pParse->nMem;
  100963. regOldRowid = regNewRowid = ++pParse->nMem;
  100964. if( pTrigger || hasFK ){
  100965. regOld = pParse->nMem + 1;
  100966. pParse->nMem += pTab->nCol;
  100967. }
  100968. if( chngRowid || pTrigger || hasFK ){
  100969. regNewRowid = ++pParse->nMem;
  100970. }
  100971. regNew = pParse->nMem + 1;
  100972. pParse->nMem += pTab->nCol;
  100973. /* Start the view context. */
  100974. if( isView ){
  100975. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  100976. }
  100977. /* If we are trying to update a view, realize that view into
  100978. ** a ephemeral table.
  100979. */
  100980. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  100981. if( isView ){
  100982. sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
  100983. }
  100984. #endif
  100985. /* Resolve the column names in all the expressions in the
  100986. ** WHERE clause.
  100987. */
  100988. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  100989. goto update_cleanup;
  100990. }
  100991. /* Begin the database scan
  100992. */
  100993. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  100994. pWInfo = sqlite3WhereBegin(
  100995. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, 0
  100996. );
  100997. if( pWInfo==0 ) goto update_cleanup;
  100998. okOnePass = sqlite3WhereOkOnePass(pWInfo);
  100999. /* Remember the rowid of every item to be updated.
  101000. */
  101001. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
  101002. if( !okOnePass ){
  101003. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  101004. }
  101005. /* End the database scan loop.
  101006. */
  101007. sqlite3WhereEnd(pWInfo);
  101008. /* Initialize the count of updated rows
  101009. */
  101010. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  101011. regRowCount = ++pParse->nMem;
  101012. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  101013. }
  101014. if( !isView ){
  101015. /*
  101016. ** Open every index that needs updating. Note that if any
  101017. ** index could potentially invoke a REPLACE conflict resolution
  101018. ** action, then we need to open all indices because we might need
  101019. ** to be deleting some records.
  101020. */
  101021. if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite);
  101022. if( onError==OE_Replace ){
  101023. openAll = 1;
  101024. }else{
  101025. openAll = 0;
  101026. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  101027. if( pIdx->onError==OE_Replace ){
  101028. openAll = 1;
  101029. break;
  101030. }
  101031. }
  101032. }
  101033. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  101034. assert( aRegIdx );
  101035. if( openAll || aRegIdx[i]>0 ){
  101036. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
  101037. sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
  101038. (char*)pKey, P4_KEYINFO_HANDOFF);
  101039. assert( pParse->nTab>iCur+i+1 );
  101040. }
  101041. }
  101042. }
  101043. /* Top of the update loop */
  101044. if( okOnePass ){
  101045. int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
  101046. addr = sqlite3VdbeAddOp0(v, OP_Goto);
  101047. sqlite3VdbeJumpHere(v, a1);
  101048. }else{
  101049. addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
  101050. }
  101051. /* Make cursor iCur point to the record that is being updated. If
  101052. ** this record does not exist for some reason (deleted by a trigger,
  101053. ** for example, then jump to the next iteration of the RowSet loop. */
  101054. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  101055. /* If the record number will change, set register regNewRowid to
  101056. ** contain the new value. If the record number is not being modified,
  101057. ** then regNewRowid is the same register as regOldRowid, which is
  101058. ** already populated. */
  101059. assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
  101060. if( chngRowid ){
  101061. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  101062. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
  101063. }
  101064. /* If there are triggers on this table, populate an array of registers
  101065. ** with the required old.* column data. */
  101066. if( hasFK || pTrigger ){
  101067. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  101068. oldmask |= sqlite3TriggerColmask(pParse,
  101069. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  101070. );
  101071. for(i=0; i<pTab->nCol; i++){
  101072. if( aXRef[i]<0 || oldmask==0xffffffff || (i<32 && (oldmask & (1<<i))) ){
  101073. sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, i, regOld+i);
  101074. }else{
  101075. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  101076. }
  101077. }
  101078. if( chngRowid==0 ){
  101079. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  101080. }
  101081. }
  101082. /* Populate the array of registers beginning at regNew with the new
  101083. ** row data. This array is used to check constaints, create the new
  101084. ** table and index records, and as the values for any new.* references
  101085. ** made by triggers.
  101086. **
  101087. ** If there are one or more BEFORE triggers, then do not populate the
  101088. ** registers associated with columns that are (a) not modified by
  101089. ** this UPDATE statement and (b) not accessed by new.* references. The
  101090. ** values for registers not modified by the UPDATE must be reloaded from
  101091. ** the database after the BEFORE triggers are fired anyway (as the trigger
  101092. ** may have modified them). So not loading those that are not going to
  101093. ** be used eliminates some redundant opcodes.
  101094. */
  101095. newmask = sqlite3TriggerColmask(
  101096. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  101097. );
  101098. sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);
  101099. for(i=0; i<pTab->nCol; i++){
  101100. if( i==pTab->iPKey ){
  101101. /*sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);*/
  101102. }else{
  101103. j = aXRef[i];
  101104. if( j>=0 ){
  101105. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  101106. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
  101107. /* This branch loads the value of a column that will not be changed
  101108. ** into a register. This is done if there are no BEFORE triggers, or
  101109. ** if there are one or more BEFORE triggers that use this value via
  101110. ** a new.* reference in a trigger program.
  101111. */
  101112. testcase( i==31 );
  101113. testcase( i==32 );
  101114. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  101115. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  101116. }
  101117. }
  101118. }
  101119. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  101120. ** verified. One could argue that this is wrong.
  101121. */
  101122. if( tmask&TRIGGER_BEFORE ){
  101123. sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
  101124. sqlite3TableAffinityStr(v, pTab);
  101125. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  101126. TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
  101127. /* The row-trigger may have deleted the row being updated. In this
  101128. ** case, jump to the next row. No updates or AFTER triggers are
  101129. ** required. This behavior - what happens when the row being updated
  101130. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  101131. ** documentation.
  101132. */
  101133. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
  101134. /* If it did not delete it, the row-trigger may still have modified
  101135. ** some of the columns of the row being updated. Load the values for
  101136. ** all columns not modified by the update statement into their
  101137. ** registers in case this has happened.
  101138. */
  101139. for(i=0; i<pTab->nCol; i++){
  101140. if( aXRef[i]<0 && i!=pTab->iPKey ){
  101141. sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
  101142. sqlite3ColumnDefault(v, pTab, i, regNew+i);
  101143. }
  101144. }
  101145. }
  101146. if( !isView ){
  101147. int j1; /* Address of jump instruction */
  101148. /* Do constraint checks. */
  101149. sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
  101150. aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
  101151. /* Do FK constraint checks. */
  101152. if( hasFK ){
  101153. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngRowid);
  101154. }
  101155. /* Delete the index entries associated with the current record. */
  101156. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
  101157. sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
  101158. /* If changing the record number, delete the old record. */
  101159. if( hasFK || chngRowid ){
  101160. sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
  101161. }
  101162. sqlite3VdbeJumpHere(v, j1);
  101163. if( hasFK ){
  101164. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngRowid);
  101165. }
  101166. /* Insert the new index entries and the new record. */
  101167. sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
  101168. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  101169. ** handle rows (possibly in other tables) that refer via a foreign key
  101170. ** to the row just updated. */
  101171. if( hasFK ){
  101172. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngRowid);
  101173. }
  101174. }
  101175. /* Increment the row counter
  101176. */
  101177. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  101178. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  101179. }
  101180. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  101181. TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
  101182. /* Repeat the above with the next record to be updated, until
  101183. ** all record selected by the WHERE clause have been updated.
  101184. */
  101185. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
  101186. sqlite3VdbeJumpHere(v, addr);
  101187. /* Close all tables */
  101188. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  101189. assert( aRegIdx );
  101190. if( openAll || aRegIdx[i]>0 ){
  101191. sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
  101192. }
  101193. }
  101194. sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
  101195. /* Update the sqlite_sequence table by storing the content of the
  101196. ** maximum rowid counter values recorded while inserting into
  101197. ** autoincrement tables.
  101198. */
  101199. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  101200. sqlite3AutoincrementEnd(pParse);
  101201. }
  101202. /*
  101203. ** Return the number of rows that were changed. If this routine is
  101204. ** generating code because of a call to sqlite3NestedParse(), do not
  101205. ** invoke the callback function.
  101206. */
  101207. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  101208. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  101209. sqlite3VdbeSetNumCols(v, 1);
  101210. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  101211. }
  101212. update_cleanup:
  101213. sqlite3AuthContextPop(&sContext);
  101214. sqlite3DbFree(db, aRegIdx);
  101215. sqlite3DbFree(db, aXRef);
  101216. sqlite3SrcListDelete(db, pTabList);
  101217. sqlite3ExprListDelete(db, pChanges);
  101218. sqlite3ExprDelete(db, pWhere);
  101219. return;
  101220. }
  101221. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  101222. ** thely may interfere with compilation of other functions in this file
  101223. ** (or in another file, if this file becomes part of the amalgamation). */
  101224. #ifdef isView
  101225. #undef isView
  101226. #endif
  101227. #ifdef pTrigger
  101228. #undef pTrigger
  101229. #endif
  101230. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101231. /*
  101232. ** Generate code for an UPDATE of a virtual table.
  101233. **
  101234. ** The strategy is that we create an ephemerial table that contains
  101235. ** for each row to be changed:
  101236. **
  101237. ** (A) The original rowid of that row.
  101238. ** (B) The revised rowid for the row. (note1)
  101239. ** (C) The content of every column in the row.
  101240. **
  101241. ** Then we loop over this ephemeral table and for each row in
  101242. ** the ephermeral table call VUpdate.
  101243. **
  101244. ** When finished, drop the ephemeral table.
  101245. **
  101246. ** (note1) Actually, if we know in advance that (A) is always the same
  101247. ** as (B) we only store (A), then duplicate (A) when pulling
  101248. ** it out of the ephemeral table before calling VUpdate.
  101249. */
  101250. static void updateVirtualTable(
  101251. Parse *pParse, /* The parsing context */
  101252. SrcList *pSrc, /* The virtual table to be modified */
  101253. Table *pTab, /* The virtual table */
  101254. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  101255. Expr *pRowid, /* Expression used to recompute the rowid */
  101256. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  101257. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  101258. int onError /* ON CONFLICT strategy */
  101259. ){
  101260. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  101261. ExprList *pEList = 0; /* The result set of the SELECT statement */
  101262. Select *pSelect = 0; /* The SELECT statement */
  101263. Expr *pExpr; /* Temporary expression */
  101264. int ephemTab; /* Table holding the result of the SELECT */
  101265. int i; /* Loop counter */
  101266. int addr; /* Address of top of loop */
  101267. int iReg; /* First register in set passed to OP_VUpdate */
  101268. sqlite3 *db = pParse->db; /* Database connection */
  101269. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  101270. SelectDest dest;
  101271. /* Construct the SELECT statement that will find the new values for
  101272. ** all updated rows.
  101273. */
  101274. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  101275. if( pRowid ){
  101276. pEList = sqlite3ExprListAppend(pParse, pEList,
  101277. sqlite3ExprDup(db, pRowid, 0));
  101278. }
  101279. assert( pTab->iPKey<0 );
  101280. for(i=0; i<pTab->nCol; i++){
  101281. if( aXRef[i]>=0 ){
  101282. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  101283. }else{
  101284. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  101285. }
  101286. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  101287. }
  101288. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  101289. /* Create the ephemeral table into which the update results will
  101290. ** be stored.
  101291. */
  101292. assert( v );
  101293. ephemTab = pParse->nTab++;
  101294. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  101295. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  101296. /* fill the ephemeral table
  101297. */
  101298. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  101299. sqlite3Select(pParse, pSelect, &dest);
  101300. /* Generate code to scan the ephemeral table and call VUpdate. */
  101301. iReg = ++pParse->nMem;
  101302. pParse->nMem += pTab->nCol+1;
  101303. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
  101304. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  101305. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  101306. for(i=0; i<pTab->nCol; i++){
  101307. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  101308. }
  101309. sqlite3VtabMakeWritable(pParse, pTab);
  101310. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  101311. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  101312. sqlite3MayAbort(pParse);
  101313. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
  101314. sqlite3VdbeJumpHere(v, addr);
  101315. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  101316. /* Cleanup */
  101317. sqlite3SelectDelete(db, pSelect);
  101318. }
  101319. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  101320. /************** End of update.c **********************************************/
  101321. /************** Begin file vacuum.c ******************************************/
  101322. /*
  101323. ** 2003 April 6
  101324. **
  101325. ** The author disclaims copyright to this source code. In place of
  101326. ** a legal notice, here is a blessing:
  101327. **
  101328. ** May you do good and not evil.
  101329. ** May you find forgiveness for yourself and forgive others.
  101330. ** May you share freely, never taking more than you give.
  101331. **
  101332. *************************************************************************
  101333. ** This file contains code used to implement the VACUUM command.
  101334. **
  101335. ** Most of the code in this file may be omitted by defining the
  101336. ** SQLITE_OMIT_VACUUM macro.
  101337. */
  101338. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  101339. /*
  101340. ** Finalize a prepared statement. If there was an error, store the
  101341. ** text of the error message in *pzErrMsg. Return the result code.
  101342. */
  101343. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  101344. int rc;
  101345. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  101346. if( rc ){
  101347. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  101348. }
  101349. return rc;
  101350. }
  101351. /*
  101352. ** Execute zSql on database db. Return an error code.
  101353. */
  101354. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  101355. sqlite3_stmt *pStmt;
  101356. VVA_ONLY( int rc; )
  101357. if( !zSql ){
  101358. return SQLITE_NOMEM;
  101359. }
  101360. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  101361. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  101362. return sqlite3_errcode(db);
  101363. }
  101364. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  101365. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  101366. return vacuumFinalize(db, pStmt, pzErrMsg);
  101367. }
  101368. /*
  101369. ** Execute zSql on database db. The statement returns exactly
  101370. ** one column. Execute this as SQL on the same database.
  101371. */
  101372. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  101373. sqlite3_stmt *pStmt;
  101374. int rc;
  101375. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  101376. if( rc!=SQLITE_OK ) return rc;
  101377. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  101378. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  101379. if( rc!=SQLITE_OK ){
  101380. vacuumFinalize(db, pStmt, pzErrMsg);
  101381. return rc;
  101382. }
  101383. }
  101384. return vacuumFinalize(db, pStmt, pzErrMsg);
  101385. }
  101386. /*
  101387. ** The VACUUM command is used to clean up the database,
  101388. ** collapse free space, etc. It is modelled after the VACUUM command
  101389. ** in PostgreSQL. The VACUUM command works as follows:
  101390. **
  101391. ** (1) Create a new transient database file
  101392. ** (2) Copy all content from the database being vacuumed into
  101393. ** the new transient database file
  101394. ** (3) Copy content from the transient database back into the
  101395. ** original database.
  101396. **
  101397. ** The transient database requires temporary disk space approximately
  101398. ** equal to the size of the original database. The copy operation of
  101399. ** step (3) requires additional temporary disk space approximately equal
  101400. ** to the size of the original database for the rollback journal.
  101401. ** Hence, temporary disk space that is approximately 2x the size of the
  101402. ** orginal database is required. Every page of the database is written
  101403. ** approximately 3 times: Once for step (2) and twice for step (3).
  101404. ** Two writes per page are required in step (3) because the original
  101405. ** database content must be written into the rollback journal prior to
  101406. ** overwriting the database with the vacuumed content.
  101407. **
  101408. ** Only 1x temporary space and only 1x writes would be required if
  101409. ** the copy of step (3) were replace by deleting the original database
  101410. ** and renaming the transient database as the original. But that will
  101411. ** not work if other processes are attached to the original database.
  101412. ** And a power loss in between deleting the original and renaming the
  101413. ** transient would cause the database file to appear to be deleted
  101414. ** following reboot.
  101415. */
  101416. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  101417. Vdbe *v = sqlite3GetVdbe(pParse);
  101418. if( v ){
  101419. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  101420. sqlite3VdbeUsesBtree(v, 0);
  101421. }
  101422. return;
  101423. }
  101424. /*
  101425. ** This routine implements the OP_Vacuum opcode of the VDBE.
  101426. */
  101427. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  101428. int rc = SQLITE_OK; /* Return code from service routines */
  101429. Btree *pMain; /* The database being vacuumed */
  101430. Btree *pTemp; /* The temporary database we vacuum into */
  101431. char *zSql = 0; /* SQL statements */
  101432. int saved_flags; /* Saved value of the db->flags */
  101433. int saved_nChange; /* Saved value of db->nChange */
  101434. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  101435. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  101436. Db *pDb = 0; /* Database to detach at end of vacuum */
  101437. int isMemDb; /* True if vacuuming a :memory: database */
  101438. int nRes; /* Bytes of reserved space at the end of each page */
  101439. int nDb; /* Number of attached databases */
  101440. if( !db->autoCommit ){
  101441. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  101442. return SQLITE_ERROR;
  101443. }
  101444. if( db->nVdbeActive>1 ){
  101445. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  101446. return SQLITE_ERROR;
  101447. }
  101448. /* Save the current value of the database flags so that it can be
  101449. ** restored before returning. Then set the writable-schema flag, and
  101450. ** disable CHECK and foreign key constraints. */
  101451. saved_flags = db->flags;
  101452. saved_nChange = db->nChange;
  101453. saved_nTotalChange = db->nTotalChange;
  101454. saved_xTrace = db->xTrace;
  101455. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  101456. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  101457. db->xTrace = 0;
  101458. pMain = db->aDb[0].pBt;
  101459. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  101460. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  101461. ** can be set to 'off' for this file, as it is not recovered if a crash
  101462. ** occurs anyway. The integrity of the database is maintained by a
  101463. ** (possibly synchronous) transaction opened on the main database before
  101464. ** sqlite3BtreeCopyFile() is called.
  101465. **
  101466. ** An optimisation would be to use a non-journaled pager.
  101467. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  101468. ** that actually made the VACUUM run slower. Very little journalling
  101469. ** actually occurs when doing a vacuum since the vacuum_db is initially
  101470. ** empty. Only the journal header is written. Apparently it takes more
  101471. ** time to parse and run the PRAGMA to turn journalling off than it does
  101472. ** to write the journal header file.
  101473. */
  101474. nDb = db->nDb;
  101475. if( sqlite3TempInMemory(db) ){
  101476. zSql = "ATTACH ':memory:' AS vacuum_db;";
  101477. }else{
  101478. zSql = "ATTACH '' AS vacuum_db;";
  101479. }
  101480. rc = execSql(db, pzErrMsg, zSql);
  101481. if( db->nDb>nDb ){
  101482. pDb = &db->aDb[db->nDb-1];
  101483. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  101484. }
  101485. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101486. pTemp = db->aDb[db->nDb-1].pBt;
  101487. /* The call to execSql() to attach the temp database has left the file
  101488. ** locked (as there was more than one active statement when the transaction
  101489. ** to read the schema was concluded. Unlock it here so that this doesn't
  101490. ** cause problems for the call to BtreeSetPageSize() below. */
  101491. sqlite3BtreeCommit(pTemp);
  101492. nRes = sqlite3BtreeGetReserve(pMain);
  101493. /* A VACUUM cannot change the pagesize of an encrypted database. */
  101494. #ifdef SQLITE_HAS_CODEC
  101495. if( db->nextPagesize ){
  101496. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  101497. int nKey;
  101498. char *zKey;
  101499. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  101500. if( nKey ) db->nextPagesize = 0;
  101501. }
  101502. #endif
  101503. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  101504. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101505. /* Begin a transaction and take an exclusive lock on the main database
  101506. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  101507. ** to ensure that we do not try to change the page-size on a WAL database.
  101508. */
  101509. rc = execSql(db, pzErrMsg, "BEGIN;");
  101510. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101511. rc = sqlite3BtreeBeginTrans(pMain, 2);
  101512. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101513. /* Do not attempt to change the page size for a WAL database */
  101514. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  101515. ==PAGER_JOURNALMODE_WAL ){
  101516. db->nextPagesize = 0;
  101517. }
  101518. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  101519. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  101520. || NEVER(db->mallocFailed)
  101521. ){
  101522. rc = SQLITE_NOMEM;
  101523. goto end_of_vacuum;
  101524. }
  101525. #ifndef SQLITE_OMIT_AUTOVACUUM
  101526. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  101527. sqlite3BtreeGetAutoVacuum(pMain));
  101528. #endif
  101529. /* Query the schema of the main database. Create a mirror schema
  101530. ** in the temporary database.
  101531. */
  101532. rc = execExecSql(db, pzErrMsg,
  101533. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  101534. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  101535. " AND rootpage>0"
  101536. );
  101537. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101538. rc = execExecSql(db, pzErrMsg,
  101539. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  101540. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  101541. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101542. rc = execExecSql(db, pzErrMsg,
  101543. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  101544. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  101545. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101546. /* Loop through the tables in the main database. For each, do
  101547. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  101548. ** the contents to the temporary database.
  101549. */
  101550. rc = execExecSql(db, pzErrMsg,
  101551. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  101552. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  101553. "FROM main.sqlite_master "
  101554. "WHERE type = 'table' AND name!='sqlite_sequence' "
  101555. " AND rootpage>0"
  101556. );
  101557. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101558. /* Copy over the sequence table
  101559. */
  101560. rc = execExecSql(db, pzErrMsg,
  101561. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  101562. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  101563. );
  101564. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101565. rc = execExecSql(db, pzErrMsg,
  101566. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  101567. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  101568. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  101569. );
  101570. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101571. /* Copy the triggers, views, and virtual tables from the main database
  101572. ** over to the temporary database. None of these objects has any
  101573. ** associated storage, so all we have to do is copy their entries
  101574. ** from the SQLITE_MASTER table.
  101575. */
  101576. rc = execSql(db, pzErrMsg,
  101577. "INSERT INTO vacuum_db.sqlite_master "
  101578. " SELECT type, name, tbl_name, rootpage, sql"
  101579. " FROM main.sqlite_master"
  101580. " WHERE type='view' OR type='trigger'"
  101581. " OR (type='table' AND rootpage=0)"
  101582. );
  101583. if( rc ) goto end_of_vacuum;
  101584. /* At this point, there is a write transaction open on both the
  101585. ** vacuum database and the main database. Assuming no error occurs,
  101586. ** both transactions are closed by this block - the main database
  101587. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  101588. ** call to sqlite3BtreeCommit().
  101589. */
  101590. {
  101591. u32 meta;
  101592. int i;
  101593. /* This array determines which meta meta values are preserved in the
  101594. ** vacuum. Even entries are the meta value number and odd entries
  101595. ** are an increment to apply to the meta value after the vacuum.
  101596. ** The increment is used to increase the schema cookie so that other
  101597. ** connections to the same database will know to reread the schema.
  101598. */
  101599. static const unsigned char aCopy[] = {
  101600. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  101601. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  101602. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  101603. BTREE_USER_VERSION, 0, /* Preserve the user version */
  101604. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  101605. };
  101606. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  101607. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  101608. /* Copy Btree meta values */
  101609. for(i=0; i<ArraySize(aCopy); i+=2){
  101610. /* GetMeta() and UpdateMeta() cannot fail in this context because
  101611. ** we already have page 1 loaded into cache and marked dirty. */
  101612. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  101613. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  101614. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  101615. }
  101616. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  101617. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101618. rc = sqlite3BtreeCommit(pTemp);
  101619. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  101620. #ifndef SQLITE_OMIT_AUTOVACUUM
  101621. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  101622. #endif
  101623. }
  101624. assert( rc==SQLITE_OK );
  101625. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  101626. end_of_vacuum:
  101627. /* Restore the original value of db->flags */
  101628. db->flags = saved_flags;
  101629. db->nChange = saved_nChange;
  101630. db->nTotalChange = saved_nTotalChange;
  101631. db->xTrace = saved_xTrace;
  101632. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  101633. /* Currently there is an SQL level transaction open on the vacuum
  101634. ** database. No locks are held on any other files (since the main file
  101635. ** was committed at the btree level). So it safe to end the transaction
  101636. ** by manually setting the autoCommit flag to true and detaching the
  101637. ** vacuum database. The vacuum_db journal file is deleted when the pager
  101638. ** is closed by the DETACH.
  101639. */
  101640. db->autoCommit = 1;
  101641. if( pDb ){
  101642. sqlite3BtreeClose(pDb->pBt);
  101643. pDb->pBt = 0;
  101644. pDb->pSchema = 0;
  101645. }
  101646. /* This both clears the schemas and reduces the size of the db->aDb[]
  101647. ** array. */
  101648. sqlite3ResetAllSchemasOfConnection(db);
  101649. return rc;
  101650. }
  101651. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  101652. /************** End of vacuum.c **********************************************/
  101653. /************** Begin file vtab.c ********************************************/
  101654. /*
  101655. ** 2006 June 10
  101656. **
  101657. ** The author disclaims copyright to this source code. In place of
  101658. ** a legal notice, here is a blessing:
  101659. **
  101660. ** May you do good and not evil.
  101661. ** May you find forgiveness for yourself and forgive others.
  101662. ** May you share freely, never taking more than you give.
  101663. **
  101664. *************************************************************************
  101665. ** This file contains code used to help implement virtual tables.
  101666. */
  101667. #ifndef SQLITE_OMIT_VIRTUALTABLE
  101668. /*
  101669. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  101670. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  101671. ** this struct allocated on the stack. It is used by the implementation of
  101672. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  101673. ** are invoked only from within xCreate and xConnect methods.
  101674. */
  101675. struct VtabCtx {
  101676. VTable *pVTable; /* The virtual table being constructed */
  101677. Table *pTab; /* The Table object to which the virtual table belongs */
  101678. };
  101679. /*
  101680. ** The actual function that does the work of creating a new module.
  101681. ** This function implements the sqlite3_create_module() and
  101682. ** sqlite3_create_module_v2() interfaces.
  101683. */
  101684. static int createModule(
  101685. sqlite3 *db, /* Database in which module is registered */
  101686. const char *zName, /* Name assigned to this module */
  101687. const sqlite3_module *pModule, /* The definition of the module */
  101688. void *pAux, /* Context pointer for xCreate/xConnect */
  101689. void (*xDestroy)(void *) /* Module destructor function */
  101690. ){
  101691. int rc = SQLITE_OK;
  101692. int nName;
  101693. sqlite3_mutex_enter(db->mutex);
  101694. nName = sqlite3Strlen30(zName);
  101695. if( sqlite3HashFind(&db->aModule, zName, nName) ){
  101696. rc = SQLITE_MISUSE_BKPT;
  101697. }else{
  101698. Module *pMod;
  101699. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  101700. if( pMod ){
  101701. Module *pDel;
  101702. char *zCopy = (char *)(&pMod[1]);
  101703. memcpy(zCopy, zName, nName+1);
  101704. pMod->zName = zCopy;
  101705. pMod->pModule = pModule;
  101706. pMod->pAux = pAux;
  101707. pMod->xDestroy = xDestroy;
  101708. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,nName,(void*)pMod);
  101709. assert( pDel==0 || pDel==pMod );
  101710. if( pDel ){
  101711. db->mallocFailed = 1;
  101712. sqlite3DbFree(db, pDel);
  101713. }
  101714. }
  101715. }
  101716. rc = sqlite3ApiExit(db, rc);
  101717. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  101718. sqlite3_mutex_leave(db->mutex);
  101719. return rc;
  101720. }
  101721. /*
  101722. ** External API function used to create a new virtual-table module.
  101723. */
  101724. SQLITE_API int sqlite3_create_module(
  101725. sqlite3 *db, /* Database in which module is registered */
  101726. const char *zName, /* Name assigned to this module */
  101727. const sqlite3_module *pModule, /* The definition of the module */
  101728. void *pAux /* Context pointer for xCreate/xConnect */
  101729. ){
  101730. return createModule(db, zName, pModule, pAux, 0);
  101731. }
  101732. /*
  101733. ** External API function used to create a new virtual-table module.
  101734. */
  101735. SQLITE_API int sqlite3_create_module_v2(
  101736. sqlite3 *db, /* Database in which module is registered */
  101737. const char *zName, /* Name assigned to this module */
  101738. const sqlite3_module *pModule, /* The definition of the module */
  101739. void *pAux, /* Context pointer for xCreate/xConnect */
  101740. void (*xDestroy)(void *) /* Module destructor function */
  101741. ){
  101742. return createModule(db, zName, pModule, pAux, xDestroy);
  101743. }
  101744. /*
  101745. ** Lock the virtual table so that it cannot be disconnected.
  101746. ** Locks nest. Every lock should have a corresponding unlock.
  101747. ** If an unlock is omitted, resources leaks will occur.
  101748. **
  101749. ** If a disconnect is attempted while a virtual table is locked,
  101750. ** the disconnect is deferred until all locks have been removed.
  101751. */
  101752. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  101753. pVTab->nRef++;
  101754. }
  101755. /*
  101756. ** pTab is a pointer to a Table structure representing a virtual-table.
  101757. ** Return a pointer to the VTable object used by connection db to access
  101758. ** this virtual-table, if one has been created, or NULL otherwise.
  101759. */
  101760. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  101761. VTable *pVtab;
  101762. assert( IsVirtual(pTab) );
  101763. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  101764. return pVtab;
  101765. }
  101766. /*
  101767. ** Decrement the ref-count on a virtual table object. When the ref-count
  101768. ** reaches zero, call the xDisconnect() method to delete the object.
  101769. */
  101770. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  101771. sqlite3 *db = pVTab->db;
  101772. assert( db );
  101773. assert( pVTab->nRef>0 );
  101774. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  101775. pVTab->nRef--;
  101776. if( pVTab->nRef==0 ){
  101777. sqlite3_vtab *p = pVTab->pVtab;
  101778. if( p ){
  101779. p->pModule->xDisconnect(p);
  101780. }
  101781. sqlite3DbFree(db, pVTab);
  101782. }
  101783. }
  101784. /*
  101785. ** Table p is a virtual table. This function moves all elements in the
  101786. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  101787. ** database connections to be disconnected at the next opportunity.
  101788. ** Except, if argument db is not NULL, then the entry associated with
  101789. ** connection db is left in the p->pVTable list.
  101790. */
  101791. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  101792. VTable *pRet = 0;
  101793. VTable *pVTable = p->pVTable;
  101794. p->pVTable = 0;
  101795. /* Assert that the mutex (if any) associated with the BtShared database
  101796. ** that contains table p is held by the caller. See header comments
  101797. ** above function sqlite3VtabUnlockList() for an explanation of why
  101798. ** this makes it safe to access the sqlite3.pDisconnect list of any
  101799. ** database connection that may have an entry in the p->pVTable list.
  101800. */
  101801. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  101802. while( pVTable ){
  101803. sqlite3 *db2 = pVTable->db;
  101804. VTable *pNext = pVTable->pNext;
  101805. assert( db2 );
  101806. if( db2==db ){
  101807. pRet = pVTable;
  101808. p->pVTable = pRet;
  101809. pRet->pNext = 0;
  101810. }else{
  101811. pVTable->pNext = db2->pDisconnect;
  101812. db2->pDisconnect = pVTable;
  101813. }
  101814. pVTable = pNext;
  101815. }
  101816. assert( !db || pRet );
  101817. return pRet;
  101818. }
  101819. /*
  101820. ** Table *p is a virtual table. This function removes the VTable object
  101821. ** for table *p associated with database connection db from the linked
  101822. ** list in p->pVTab. It also decrements the VTable ref count. This is
  101823. ** used when closing database connection db to free all of its VTable
  101824. ** objects without disturbing the rest of the Schema object (which may
  101825. ** be being used by other shared-cache connections).
  101826. */
  101827. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  101828. VTable **ppVTab;
  101829. assert( IsVirtual(p) );
  101830. assert( sqlite3BtreeHoldsAllMutexes(db) );
  101831. assert( sqlite3_mutex_held(db->mutex) );
  101832. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  101833. if( (*ppVTab)->db==db ){
  101834. VTable *pVTab = *ppVTab;
  101835. *ppVTab = pVTab->pNext;
  101836. sqlite3VtabUnlock(pVTab);
  101837. break;
  101838. }
  101839. }
  101840. }
  101841. /*
  101842. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  101843. **
  101844. ** This function may only be called when the mutexes associated with all
  101845. ** shared b-tree databases opened using connection db are held by the
  101846. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  101847. ** sqlite3.pDisconnect list is accessed only as follows:
  101848. **
  101849. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  101850. ** associated with the database handle itself must be held.
  101851. **
  101852. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  101853. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  101854. ** associated with the database the virtual table is stored in is held
  101855. ** or, if the virtual table is stored in a non-sharable database, then
  101856. ** the database handle mutex is held.
  101857. **
  101858. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  101859. ** by multiple threads. It is thread-safe.
  101860. */
  101861. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  101862. VTable *p = db->pDisconnect;
  101863. db->pDisconnect = 0;
  101864. assert( sqlite3BtreeHoldsAllMutexes(db) );
  101865. assert( sqlite3_mutex_held(db->mutex) );
  101866. if( p ){
  101867. sqlite3ExpirePreparedStatements(db);
  101868. do {
  101869. VTable *pNext = p->pNext;
  101870. sqlite3VtabUnlock(p);
  101871. p = pNext;
  101872. }while( p );
  101873. }
  101874. }
  101875. /*
  101876. ** Clear any and all virtual-table information from the Table record.
  101877. ** This routine is called, for example, just before deleting the Table
  101878. ** record.
  101879. **
  101880. ** Since it is a virtual-table, the Table structure contains a pointer
  101881. ** to the head of a linked list of VTable structures. Each VTable
  101882. ** structure is associated with a single sqlite3* user of the schema.
  101883. ** The reference count of the VTable structure associated with database
  101884. ** connection db is decremented immediately (which may lead to the
  101885. ** structure being xDisconnected and free). Any other VTable structures
  101886. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  101887. ** database connection.
  101888. */
  101889. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  101890. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  101891. if( p->azModuleArg ){
  101892. int i;
  101893. for(i=0; i<p->nModuleArg; i++){
  101894. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  101895. }
  101896. sqlite3DbFree(db, p->azModuleArg);
  101897. }
  101898. }
  101899. /*
  101900. ** Add a new module argument to pTable->azModuleArg[].
  101901. ** The string is not copied - the pointer is stored. The
  101902. ** string will be freed automatically when the table is
  101903. ** deleted.
  101904. */
  101905. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  101906. int i = pTable->nModuleArg++;
  101907. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  101908. char **azModuleArg;
  101909. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  101910. if( azModuleArg==0 ){
  101911. int j;
  101912. for(j=0; j<i; j++){
  101913. sqlite3DbFree(db, pTable->azModuleArg[j]);
  101914. }
  101915. sqlite3DbFree(db, zArg);
  101916. sqlite3DbFree(db, pTable->azModuleArg);
  101917. pTable->nModuleArg = 0;
  101918. }else{
  101919. azModuleArg[i] = zArg;
  101920. azModuleArg[i+1] = 0;
  101921. }
  101922. pTable->azModuleArg = azModuleArg;
  101923. }
  101924. /*
  101925. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  101926. ** statement. The module name has been parsed, but the optional list
  101927. ** of parameters that follow the module name are still pending.
  101928. */
  101929. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  101930. Parse *pParse, /* Parsing context */
  101931. Token *pName1, /* Name of new table, or database name */
  101932. Token *pName2, /* Name of new table or NULL */
  101933. Token *pModuleName, /* Name of the module for the virtual table */
  101934. int ifNotExists /* No error if the table already exists */
  101935. ){
  101936. int iDb; /* The database the table is being created in */
  101937. Table *pTable; /* The new virtual table */
  101938. sqlite3 *db; /* Database connection */
  101939. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  101940. pTable = pParse->pNewTable;
  101941. if( pTable==0 ) return;
  101942. assert( 0==pTable->pIndex );
  101943. db = pParse->db;
  101944. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  101945. assert( iDb>=0 );
  101946. pTable->tabFlags |= TF_Virtual;
  101947. pTable->nModuleArg = 0;
  101948. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  101949. addModuleArgument(db, pTable, 0);
  101950. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  101951. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  101952. #ifndef SQLITE_OMIT_AUTHORIZATION
  101953. /* Creating a virtual table invokes the authorization callback twice.
  101954. ** The first invocation, to obtain permission to INSERT a row into the
  101955. ** sqlite_master table, has already been made by sqlite3StartTable().
  101956. ** The second call, to obtain permission to create the table, is made now.
  101957. */
  101958. if( pTable->azModuleArg ){
  101959. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  101960. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  101961. }
  101962. #endif
  101963. }
  101964. /*
  101965. ** This routine takes the module argument that has been accumulating
  101966. ** in pParse->zArg[] and appends it to the list of arguments on the
  101967. ** virtual table currently under construction in pParse->pTable.
  101968. */
  101969. static void addArgumentToVtab(Parse *pParse){
  101970. if( pParse->sArg.z && pParse->pNewTable ){
  101971. const char *z = (const char*)pParse->sArg.z;
  101972. int n = pParse->sArg.n;
  101973. sqlite3 *db = pParse->db;
  101974. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  101975. }
  101976. }
  101977. /*
  101978. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  101979. ** has been completely parsed.
  101980. */
  101981. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  101982. Table *pTab = pParse->pNewTable; /* The table being constructed */
  101983. sqlite3 *db = pParse->db; /* The database connection */
  101984. if( pTab==0 ) return;
  101985. addArgumentToVtab(pParse);
  101986. pParse->sArg.z = 0;
  101987. if( pTab->nModuleArg<1 ) return;
  101988. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  101989. ** first time (in other words if the virtual table is actually being
  101990. ** created now instead of just being read out of sqlite_master) then
  101991. ** do additional initialization work and store the statement text
  101992. ** in the sqlite_master table.
  101993. */
  101994. if( !db->init.busy ){
  101995. char *zStmt;
  101996. char *zWhere;
  101997. int iDb;
  101998. Vdbe *v;
  101999. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  102000. if( pEnd ){
  102001. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  102002. }
  102003. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  102004. /* A slot for the record has already been allocated in the
  102005. ** SQLITE_MASTER table. We just need to update that slot with all
  102006. ** the information we've collected.
  102007. **
  102008. ** The VM register number pParse->regRowid holds the rowid of an
  102009. ** entry in the sqlite_master table tht was created for this vtab
  102010. ** by sqlite3StartTable().
  102011. */
  102012. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102013. sqlite3NestedParse(pParse,
  102014. "UPDATE %Q.%s "
  102015. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  102016. "WHERE rowid=#%d",
  102017. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  102018. pTab->zName,
  102019. pTab->zName,
  102020. zStmt,
  102021. pParse->regRowid
  102022. );
  102023. sqlite3DbFree(db, zStmt);
  102024. v = sqlite3GetVdbe(pParse);
  102025. sqlite3ChangeCookie(pParse, iDb);
  102026. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  102027. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  102028. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  102029. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  102030. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  102031. }
  102032. /* If we are rereading the sqlite_master table create the in-memory
  102033. ** record of the table. The xConnect() method is not called until
  102034. ** the first time the virtual table is used in an SQL statement. This
  102035. ** allows a schema that contains virtual tables to be loaded before
  102036. ** the required virtual table implementations are registered. */
  102037. else {
  102038. Table *pOld;
  102039. Schema *pSchema = pTab->pSchema;
  102040. const char *zName = pTab->zName;
  102041. int nName = sqlite3Strlen30(zName);
  102042. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  102043. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
  102044. if( pOld ){
  102045. db->mallocFailed = 1;
  102046. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  102047. return;
  102048. }
  102049. pParse->pNewTable = 0;
  102050. }
  102051. }
  102052. /*
  102053. ** The parser calls this routine when it sees the first token
  102054. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  102055. */
  102056. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  102057. addArgumentToVtab(pParse);
  102058. pParse->sArg.z = 0;
  102059. pParse->sArg.n = 0;
  102060. }
  102061. /*
  102062. ** The parser calls this routine for each token after the first token
  102063. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  102064. */
  102065. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  102066. Token *pArg = &pParse->sArg;
  102067. if( pArg->z==0 ){
  102068. pArg->z = p->z;
  102069. pArg->n = p->n;
  102070. }else{
  102071. assert(pArg->z < p->z);
  102072. pArg->n = (int)(&p->z[p->n] - pArg->z);
  102073. }
  102074. }
  102075. /*
  102076. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  102077. ** pointer to the function to invoke is passed as the fourth parameter
  102078. ** to this procedure.
  102079. */
  102080. static int vtabCallConstructor(
  102081. sqlite3 *db,
  102082. Table *pTab,
  102083. Module *pMod,
  102084. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  102085. char **pzErr
  102086. ){
  102087. VtabCtx sCtx, *pPriorCtx;
  102088. VTable *pVTable;
  102089. int rc;
  102090. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  102091. int nArg = pTab->nModuleArg;
  102092. char *zErr = 0;
  102093. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  102094. int iDb;
  102095. if( !zModuleName ){
  102096. return SQLITE_NOMEM;
  102097. }
  102098. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  102099. if( !pVTable ){
  102100. sqlite3DbFree(db, zModuleName);
  102101. return SQLITE_NOMEM;
  102102. }
  102103. pVTable->db = db;
  102104. pVTable->pMod = pMod;
  102105. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102106. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  102107. /* Invoke the virtual table constructor */
  102108. assert( &db->pVtabCtx );
  102109. assert( xConstruct );
  102110. sCtx.pTab = pTab;
  102111. sCtx.pVTable = pVTable;
  102112. pPriorCtx = db->pVtabCtx;
  102113. db->pVtabCtx = &sCtx;
  102114. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  102115. db->pVtabCtx = pPriorCtx;
  102116. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  102117. if( SQLITE_OK!=rc ){
  102118. if( zErr==0 ){
  102119. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  102120. }else {
  102121. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  102122. sqlite3_free(zErr);
  102123. }
  102124. sqlite3DbFree(db, pVTable);
  102125. }else if( ALWAYS(pVTable->pVtab) ){
  102126. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  102127. ** the sqlite3_vtab object if successful. */
  102128. pVTable->pVtab->pModule = pMod->pModule;
  102129. pVTable->nRef = 1;
  102130. if( sCtx.pTab ){
  102131. const char *zFormat = "vtable constructor did not declare schema: %s";
  102132. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  102133. sqlite3VtabUnlock(pVTable);
  102134. rc = SQLITE_ERROR;
  102135. }else{
  102136. int iCol;
  102137. /* If everything went according to plan, link the new VTable structure
  102138. ** into the linked list headed by pTab->pVTable. Then loop through the
  102139. ** columns of the table to see if any of them contain the token "hidden".
  102140. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  102141. ** the type string. */
  102142. pVTable->pNext = pTab->pVTable;
  102143. pTab->pVTable = pVTable;
  102144. for(iCol=0; iCol<pTab->nCol; iCol++){
  102145. char *zType = pTab->aCol[iCol].zType;
  102146. int nType;
  102147. int i = 0;
  102148. if( !zType ) continue;
  102149. nType = sqlite3Strlen30(zType);
  102150. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  102151. for(i=0; i<nType; i++){
  102152. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  102153. && (zType[i+7]=='\0' || zType[i+7]==' ')
  102154. ){
  102155. i++;
  102156. break;
  102157. }
  102158. }
  102159. }
  102160. if( i<nType ){
  102161. int j;
  102162. int nDel = 6 + (zType[i+6] ? 1 : 0);
  102163. for(j=i; (j+nDel)<=nType; j++){
  102164. zType[j] = zType[j+nDel];
  102165. }
  102166. if( zType[i]=='\0' && i>0 ){
  102167. assert(zType[i-1]==' ');
  102168. zType[i-1] = '\0';
  102169. }
  102170. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  102171. }
  102172. }
  102173. }
  102174. }
  102175. sqlite3DbFree(db, zModuleName);
  102176. return rc;
  102177. }
  102178. /*
  102179. ** This function is invoked by the parser to call the xConnect() method
  102180. ** of the virtual table pTab. If an error occurs, an error code is returned
  102181. ** and an error left in pParse.
  102182. **
  102183. ** This call is a no-op if table pTab is not a virtual table.
  102184. */
  102185. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  102186. sqlite3 *db = pParse->db;
  102187. const char *zMod;
  102188. Module *pMod;
  102189. int rc;
  102190. assert( pTab );
  102191. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  102192. return SQLITE_OK;
  102193. }
  102194. /* Locate the required virtual table module */
  102195. zMod = pTab->azModuleArg[0];
  102196. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  102197. if( !pMod ){
  102198. const char *zModule = pTab->azModuleArg[0];
  102199. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  102200. rc = SQLITE_ERROR;
  102201. }else{
  102202. char *zErr = 0;
  102203. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  102204. if( rc!=SQLITE_OK ){
  102205. sqlite3ErrorMsg(pParse, "%s", zErr);
  102206. }
  102207. sqlite3DbFree(db, zErr);
  102208. }
  102209. return rc;
  102210. }
  102211. /*
  102212. ** Grow the db->aVTrans[] array so that there is room for at least one
  102213. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  102214. */
  102215. static int growVTrans(sqlite3 *db){
  102216. const int ARRAY_INCR = 5;
  102217. /* Grow the sqlite3.aVTrans array if required */
  102218. if( (db->nVTrans%ARRAY_INCR)==0 ){
  102219. VTable **aVTrans;
  102220. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  102221. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  102222. if( !aVTrans ){
  102223. return SQLITE_NOMEM;
  102224. }
  102225. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  102226. db->aVTrans = aVTrans;
  102227. }
  102228. return SQLITE_OK;
  102229. }
  102230. /*
  102231. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  102232. ** have already been reserved using growVTrans().
  102233. */
  102234. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  102235. /* Add pVtab to the end of sqlite3.aVTrans */
  102236. db->aVTrans[db->nVTrans++] = pVTab;
  102237. sqlite3VtabLock(pVTab);
  102238. }
  102239. /*
  102240. ** This function is invoked by the vdbe to call the xCreate method
  102241. ** of the virtual table named zTab in database iDb.
  102242. **
  102243. ** If an error occurs, *pzErr is set to point an an English language
  102244. ** description of the error and an SQLITE_XXX error code is returned.
  102245. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  102246. */
  102247. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  102248. int rc = SQLITE_OK;
  102249. Table *pTab;
  102250. Module *pMod;
  102251. const char *zMod;
  102252. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  102253. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  102254. /* Locate the required virtual table module */
  102255. zMod = pTab->azModuleArg[0];
  102256. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
  102257. /* If the module has been registered and includes a Create method,
  102258. ** invoke it now. If the module has not been registered, return an
  102259. ** error. Otherwise, do nothing.
  102260. */
  102261. if( !pMod ){
  102262. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  102263. rc = SQLITE_ERROR;
  102264. }else{
  102265. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  102266. }
  102267. /* Justification of ALWAYS(): The xConstructor method is required to
  102268. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  102269. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  102270. rc = growVTrans(db);
  102271. if( rc==SQLITE_OK ){
  102272. addToVTrans(db, sqlite3GetVTable(db, pTab));
  102273. }
  102274. }
  102275. return rc;
  102276. }
  102277. /*
  102278. ** This function is used to set the schema of a virtual table. It is only
  102279. ** valid to call this function from within the xCreate() or xConnect() of a
  102280. ** virtual table module.
  102281. */
  102282. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  102283. Parse *pParse;
  102284. int rc = SQLITE_OK;
  102285. Table *pTab;
  102286. char *zErr = 0;
  102287. sqlite3_mutex_enter(db->mutex);
  102288. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  102289. sqlite3Error(db, SQLITE_MISUSE, 0);
  102290. sqlite3_mutex_leave(db->mutex);
  102291. return SQLITE_MISUSE_BKPT;
  102292. }
  102293. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  102294. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  102295. if( pParse==0 ){
  102296. rc = SQLITE_NOMEM;
  102297. }else{
  102298. pParse->declareVtab = 1;
  102299. pParse->db = db;
  102300. pParse->nQueryLoop = 1;
  102301. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  102302. && pParse->pNewTable
  102303. && !db->mallocFailed
  102304. && !pParse->pNewTable->pSelect
  102305. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  102306. ){
  102307. if( !pTab->aCol ){
  102308. pTab->aCol = pParse->pNewTable->aCol;
  102309. pTab->nCol = pParse->pNewTable->nCol;
  102310. pParse->pNewTable->nCol = 0;
  102311. pParse->pNewTable->aCol = 0;
  102312. }
  102313. db->pVtabCtx->pTab = 0;
  102314. }else{
  102315. sqlite3Error(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  102316. sqlite3DbFree(db, zErr);
  102317. rc = SQLITE_ERROR;
  102318. }
  102319. pParse->declareVtab = 0;
  102320. if( pParse->pVdbe ){
  102321. sqlite3VdbeFinalize(pParse->pVdbe);
  102322. }
  102323. sqlite3DeleteTable(db, pParse->pNewTable);
  102324. sqlite3StackFree(db, pParse);
  102325. }
  102326. assert( (rc&0xff)==rc );
  102327. rc = sqlite3ApiExit(db, rc);
  102328. sqlite3_mutex_leave(db->mutex);
  102329. return rc;
  102330. }
  102331. /*
  102332. ** This function is invoked by the vdbe to call the xDestroy method
  102333. ** of the virtual table named zTab in database iDb. This occurs
  102334. ** when a DROP TABLE is mentioned.
  102335. **
  102336. ** This call is a no-op if zTab is not a virtual table.
  102337. */
  102338. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  102339. int rc = SQLITE_OK;
  102340. Table *pTab;
  102341. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  102342. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  102343. VTable *p = vtabDisconnectAll(db, pTab);
  102344. assert( rc==SQLITE_OK );
  102345. rc = p->pMod->pModule->xDestroy(p->pVtab);
  102346. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  102347. if( rc==SQLITE_OK ){
  102348. assert( pTab->pVTable==p && p->pNext==0 );
  102349. p->pVtab = 0;
  102350. pTab->pVTable = 0;
  102351. sqlite3VtabUnlock(p);
  102352. }
  102353. }
  102354. return rc;
  102355. }
  102356. /*
  102357. ** This function invokes either the xRollback or xCommit method
  102358. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  102359. ** called is identified by the second argument, "offset", which is
  102360. ** the offset of the method to call in the sqlite3_module structure.
  102361. **
  102362. ** The array is cleared after invoking the callbacks.
  102363. */
  102364. static void callFinaliser(sqlite3 *db, int offset){
  102365. int i;
  102366. if( db->aVTrans ){
  102367. for(i=0; i<db->nVTrans; i++){
  102368. VTable *pVTab = db->aVTrans[i];
  102369. sqlite3_vtab *p = pVTab->pVtab;
  102370. if( p ){
  102371. int (*x)(sqlite3_vtab *);
  102372. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  102373. if( x ) x(p);
  102374. }
  102375. pVTab->iSavepoint = 0;
  102376. sqlite3VtabUnlock(pVTab);
  102377. }
  102378. sqlite3DbFree(db, db->aVTrans);
  102379. db->nVTrans = 0;
  102380. db->aVTrans = 0;
  102381. }
  102382. }
  102383. /*
  102384. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  102385. ** array. Return the error code for the first error that occurs, or
  102386. ** SQLITE_OK if all xSync operations are successful.
  102387. **
  102388. ** If an error message is available, leave it in p->zErrMsg.
  102389. */
  102390. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  102391. int i;
  102392. int rc = SQLITE_OK;
  102393. VTable **aVTrans = db->aVTrans;
  102394. db->aVTrans = 0;
  102395. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  102396. int (*x)(sqlite3_vtab *);
  102397. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  102398. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  102399. rc = x(pVtab);
  102400. sqlite3VtabImportErrmsg(p, pVtab);
  102401. }
  102402. }
  102403. db->aVTrans = aVTrans;
  102404. return rc;
  102405. }
  102406. /*
  102407. ** Invoke the xRollback method of all virtual tables in the
  102408. ** sqlite3.aVTrans array. Then clear the array itself.
  102409. */
  102410. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  102411. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  102412. return SQLITE_OK;
  102413. }
  102414. /*
  102415. ** Invoke the xCommit method of all virtual tables in the
  102416. ** sqlite3.aVTrans array. Then clear the array itself.
  102417. */
  102418. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  102419. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  102420. return SQLITE_OK;
  102421. }
  102422. /*
  102423. ** If the virtual table pVtab supports the transaction interface
  102424. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  102425. ** not currently open, invoke the xBegin method now.
  102426. **
  102427. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  102428. ** in the sqlite3.aVTrans array.
  102429. */
  102430. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  102431. int rc = SQLITE_OK;
  102432. const sqlite3_module *pModule;
  102433. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  102434. ** than zero, then this function is being called from within a
  102435. ** virtual module xSync() callback. It is illegal to write to
  102436. ** virtual module tables in this case, so return SQLITE_LOCKED.
  102437. */
  102438. if( sqlite3VtabInSync(db) ){
  102439. return SQLITE_LOCKED;
  102440. }
  102441. if( !pVTab ){
  102442. return SQLITE_OK;
  102443. }
  102444. pModule = pVTab->pVtab->pModule;
  102445. if( pModule->xBegin ){
  102446. int i;
  102447. /* If pVtab is already in the aVTrans array, return early */
  102448. for(i=0; i<db->nVTrans; i++){
  102449. if( db->aVTrans[i]==pVTab ){
  102450. return SQLITE_OK;
  102451. }
  102452. }
  102453. /* Invoke the xBegin method. If successful, add the vtab to the
  102454. ** sqlite3.aVTrans[] array. */
  102455. rc = growVTrans(db);
  102456. if( rc==SQLITE_OK ){
  102457. rc = pModule->xBegin(pVTab->pVtab);
  102458. if( rc==SQLITE_OK ){
  102459. addToVTrans(db, pVTab);
  102460. }
  102461. }
  102462. }
  102463. return rc;
  102464. }
  102465. /*
  102466. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  102467. ** virtual tables that currently have an open transaction. Pass iSavepoint
  102468. ** as the second argument to the virtual table method invoked.
  102469. **
  102470. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  102471. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  102472. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  102473. ** an open transaction is invoked.
  102474. **
  102475. ** If any virtual table method returns an error code other than SQLITE_OK,
  102476. ** processing is abandoned and the error returned to the caller of this
  102477. ** function immediately. If all calls to virtual table methods are successful,
  102478. ** SQLITE_OK is returned.
  102479. */
  102480. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  102481. int rc = SQLITE_OK;
  102482. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  102483. assert( iSavepoint>=0 );
  102484. if( db->aVTrans ){
  102485. int i;
  102486. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  102487. VTable *pVTab = db->aVTrans[i];
  102488. const sqlite3_module *pMod = pVTab->pMod->pModule;
  102489. if( pVTab->pVtab && pMod->iVersion>=2 ){
  102490. int (*xMethod)(sqlite3_vtab *, int);
  102491. switch( op ){
  102492. case SAVEPOINT_BEGIN:
  102493. xMethod = pMod->xSavepoint;
  102494. pVTab->iSavepoint = iSavepoint+1;
  102495. break;
  102496. case SAVEPOINT_ROLLBACK:
  102497. xMethod = pMod->xRollbackTo;
  102498. break;
  102499. default:
  102500. xMethod = pMod->xRelease;
  102501. break;
  102502. }
  102503. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  102504. rc = xMethod(pVTab->pVtab, iSavepoint);
  102505. }
  102506. }
  102507. }
  102508. }
  102509. return rc;
  102510. }
  102511. /*
  102512. ** The first parameter (pDef) is a function implementation. The
  102513. ** second parameter (pExpr) is the first argument to this function.
  102514. ** If pExpr is a column in a virtual table, then let the virtual
  102515. ** table implementation have an opportunity to overload the function.
  102516. **
  102517. ** This routine is used to allow virtual table implementations to
  102518. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  102519. **
  102520. ** Return either the pDef argument (indicating no change) or a
  102521. ** new FuncDef structure that is marked as ephemeral using the
  102522. ** SQLITE_FUNC_EPHEM flag.
  102523. */
  102524. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  102525. sqlite3 *db, /* Database connection for reporting malloc problems */
  102526. FuncDef *pDef, /* Function to possibly overload */
  102527. int nArg, /* Number of arguments to the function */
  102528. Expr *pExpr /* First argument to the function */
  102529. ){
  102530. Table *pTab;
  102531. sqlite3_vtab *pVtab;
  102532. sqlite3_module *pMod;
  102533. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  102534. void *pArg = 0;
  102535. FuncDef *pNew;
  102536. int rc = 0;
  102537. char *zLowerName;
  102538. unsigned char *z;
  102539. /* Check to see the left operand is a column in a virtual table */
  102540. if( NEVER(pExpr==0) ) return pDef;
  102541. if( pExpr->op!=TK_COLUMN ) return pDef;
  102542. pTab = pExpr->pTab;
  102543. if( NEVER(pTab==0) ) return pDef;
  102544. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  102545. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  102546. assert( pVtab!=0 );
  102547. assert( pVtab->pModule!=0 );
  102548. pMod = (sqlite3_module *)pVtab->pModule;
  102549. if( pMod->xFindFunction==0 ) return pDef;
  102550. /* Call the xFindFunction method on the virtual table implementation
  102551. ** to see if the implementation wants to overload this function
  102552. */
  102553. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  102554. if( zLowerName ){
  102555. for(z=(unsigned char*)zLowerName; *z; z++){
  102556. *z = sqlite3UpperToLower[*z];
  102557. }
  102558. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  102559. sqlite3DbFree(db, zLowerName);
  102560. }
  102561. if( rc==0 ){
  102562. return pDef;
  102563. }
  102564. /* Create a new ephemeral function definition for the overloaded
  102565. ** function */
  102566. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  102567. + sqlite3Strlen30(pDef->zName) + 1);
  102568. if( pNew==0 ){
  102569. return pDef;
  102570. }
  102571. *pNew = *pDef;
  102572. pNew->zName = (char *)&pNew[1];
  102573. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  102574. pNew->xFunc = xFunc;
  102575. pNew->pUserData = pArg;
  102576. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  102577. return pNew;
  102578. }
  102579. /*
  102580. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  102581. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  102582. ** array if it is missing. If pTab is already in the array, this routine
  102583. ** is a no-op.
  102584. */
  102585. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  102586. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  102587. int i, n;
  102588. Table **apVtabLock;
  102589. assert( IsVirtual(pTab) );
  102590. for(i=0; i<pToplevel->nVtabLock; i++){
  102591. if( pTab==pToplevel->apVtabLock[i] ) return;
  102592. }
  102593. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  102594. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  102595. if( apVtabLock ){
  102596. pToplevel->apVtabLock = apVtabLock;
  102597. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  102598. }else{
  102599. pToplevel->db->mallocFailed = 1;
  102600. }
  102601. }
  102602. /*
  102603. ** Return the ON CONFLICT resolution mode in effect for the virtual
  102604. ** table update operation currently in progress.
  102605. **
  102606. ** The results of this routine are undefined unless it is called from
  102607. ** within an xUpdate method.
  102608. */
  102609. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  102610. static const unsigned char aMap[] = {
  102611. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  102612. };
  102613. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  102614. assert( OE_Ignore==4 && OE_Replace==5 );
  102615. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  102616. return (int)aMap[db->vtabOnConflict-1];
  102617. }
  102618. /*
  102619. ** Call from within the xCreate() or xConnect() methods to provide
  102620. ** the SQLite core with additional information about the behavior
  102621. ** of the virtual table being implemented.
  102622. */
  102623. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  102624. va_list ap;
  102625. int rc = SQLITE_OK;
  102626. sqlite3_mutex_enter(db->mutex);
  102627. va_start(ap, op);
  102628. switch( op ){
  102629. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  102630. VtabCtx *p = db->pVtabCtx;
  102631. if( !p ){
  102632. rc = SQLITE_MISUSE_BKPT;
  102633. }else{
  102634. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  102635. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  102636. }
  102637. break;
  102638. }
  102639. default:
  102640. rc = SQLITE_MISUSE_BKPT;
  102641. break;
  102642. }
  102643. va_end(ap);
  102644. if( rc!=SQLITE_OK ) sqlite3Error(db, rc, 0);
  102645. sqlite3_mutex_leave(db->mutex);
  102646. return rc;
  102647. }
  102648. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  102649. /************** End of vtab.c ************************************************/
  102650. /************** Begin file where.c *******************************************/
  102651. /*
  102652. ** 2001 September 15
  102653. **
  102654. ** The author disclaims copyright to this source code. In place of
  102655. ** a legal notice, here is a blessing:
  102656. **
  102657. ** May you do good and not evil.
  102658. ** May you find forgiveness for yourself and forgive others.
  102659. ** May you share freely, never taking more than you give.
  102660. **
  102661. *************************************************************************
  102662. ** This module contains C code that generates VDBE code used to process
  102663. ** the WHERE clause of SQL statements. This module is responsible for
  102664. ** generating the code that loops through a table looking for applicable
  102665. ** rows. Indices are selected and used to speed the search when doing
  102666. ** so is applicable. Because this module is responsible for selecting
  102667. ** indices, you might also think of this module as the "query optimizer".
  102668. */
  102669. /*
  102670. ** Trace output macros
  102671. */
  102672. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  102673. /***/ int sqlite3WhereTrace = 0;
  102674. #endif
  102675. #if defined(SQLITE_DEBUG) \
  102676. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  102677. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  102678. # define WHERETRACE_ENABLED 1
  102679. #else
  102680. # define WHERETRACE(K,X)
  102681. #endif
  102682. /* Forward references
  102683. */
  102684. typedef struct WhereClause WhereClause;
  102685. typedef struct WhereMaskSet WhereMaskSet;
  102686. typedef struct WhereOrInfo WhereOrInfo;
  102687. typedef struct WhereAndInfo WhereAndInfo;
  102688. typedef struct WhereLevel WhereLevel;
  102689. typedef struct WhereLoop WhereLoop;
  102690. typedef struct WherePath WherePath;
  102691. typedef struct WhereTerm WhereTerm;
  102692. typedef struct WhereLoopBuilder WhereLoopBuilder;
  102693. typedef struct WhereScan WhereScan;
  102694. typedef struct WhereOrCost WhereOrCost;
  102695. typedef struct WhereOrSet WhereOrSet;
  102696. /*
  102697. ** This object contains information needed to implement a single nested
  102698. ** loop in WHERE clause.
  102699. **
  102700. ** Contrast this object with WhereLoop. This object describes the
  102701. ** implementation of the loop. WhereLoop describes the algorithm.
  102702. ** This object contains a pointer to the WhereLoop algorithm as one of
  102703. ** its elements.
  102704. **
  102705. ** The WhereInfo object contains a single instance of this object for
  102706. ** each term in the FROM clause (which is to say, for each of the
  102707. ** nested loops as implemented). The order of WhereLevel objects determines
  102708. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  102709. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  102710. */
  102711. struct WhereLevel {
  102712. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  102713. int iTabCur; /* The VDBE cursor used to access the table */
  102714. int iIdxCur; /* The VDBE cursor used to access pIdx */
  102715. int addrBrk; /* Jump here to break out of the loop */
  102716. int addrNxt; /* Jump here to start the next IN combination */
  102717. int addrCont; /* Jump here to continue with the next loop cycle */
  102718. int addrFirst; /* First instruction of interior of the loop */
  102719. int addrBody; /* Beginning of the body of this loop */
  102720. u8 iFrom; /* Which entry in the FROM clause */
  102721. u8 op, p5; /* Opcode and P5 of the opcode that ends the loop */
  102722. int p1, p2; /* Operands of the opcode used to ends the loop */
  102723. union { /* Information that depends on pWLoop->wsFlags */
  102724. struct {
  102725. int nIn; /* Number of entries in aInLoop[] */
  102726. struct InLoop {
  102727. int iCur; /* The VDBE cursor used by this IN operator */
  102728. int addrInTop; /* Top of the IN loop */
  102729. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  102730. } *aInLoop; /* Information about each nested IN operator */
  102731. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  102732. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  102733. } u;
  102734. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  102735. Bitmask notReady; /* FROM entries not usable at this level */
  102736. };
  102737. /*
  102738. ** Each instance of this object represents an algorithm for evaluating one
  102739. ** term of a join. Every term of the FROM clause will have at least
  102740. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  102741. ** prevent a query solution - which is an error) and many terms of the
  102742. ** FROM clause will have multiple WhereLoop objects, each describing a
  102743. ** potential way of implementing that FROM-clause term, together with
  102744. ** dependencies and cost estimates for using the chosen algorithm.
  102745. **
  102746. ** Query planning consists of building up a collection of these WhereLoop
  102747. ** objects, then computing a particular sequence of WhereLoop objects, with
  102748. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  102749. ** and that minimize the overall cost.
  102750. */
  102751. struct WhereLoop {
  102752. Bitmask prereq; /* Bitmask of other loops that must run first */
  102753. Bitmask maskSelf; /* Bitmask identifying table iTab */
  102754. #ifdef SQLITE_DEBUG
  102755. char cId; /* Symbolic ID of this loop for debugging use */
  102756. #endif
  102757. u8 iTab; /* Position in FROM clause of table for this loop */
  102758. u8 iSortIdx; /* Sorting index number. 0==None */
  102759. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  102760. LogEst rRun; /* Cost of running each loop */
  102761. LogEst nOut; /* Estimated number of output rows */
  102762. union {
  102763. struct { /* Information for internal btree tables */
  102764. int nEq; /* Number of equality constraints */
  102765. Index *pIndex; /* Index used, or NULL */
  102766. } btree;
  102767. struct { /* Information for virtual tables */
  102768. int idxNum; /* Index number */
  102769. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  102770. u8 isOrdered; /* True if satisfies ORDER BY */
  102771. u16 omitMask; /* Terms that may be omitted */
  102772. char *idxStr; /* Index identifier string */
  102773. } vtab;
  102774. } u;
  102775. u32 wsFlags; /* WHERE_* flags describing the plan */
  102776. u16 nLTerm; /* Number of entries in aLTerm[] */
  102777. /**** whereLoopXfer() copies fields above ***********************/
  102778. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  102779. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  102780. WhereTerm **aLTerm; /* WhereTerms used */
  102781. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  102782. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  102783. };
  102784. /* This object holds the prerequisites and the cost of running a
  102785. ** subquery on one operand of an OR operator in the WHERE clause.
  102786. ** See WhereOrSet for additional information
  102787. */
  102788. struct WhereOrCost {
  102789. Bitmask prereq; /* Prerequisites */
  102790. LogEst rRun; /* Cost of running this subquery */
  102791. LogEst nOut; /* Number of outputs for this subquery */
  102792. };
  102793. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  102794. ** correspond to the subquery(s) of OR-clause processing. Only the
  102795. ** best N_OR_COST elements are retained.
  102796. */
  102797. #define N_OR_COST 3
  102798. struct WhereOrSet {
  102799. u16 n; /* Number of valid a[] entries */
  102800. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  102801. };
  102802. /* Forward declaration of methods */
  102803. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  102804. /*
  102805. ** Each instance of this object holds a sequence of WhereLoop objects
  102806. ** that implement some or all of a query plan.
  102807. **
  102808. ** Think of each WhereLoop object as a node in a graph with arcs
  102809. ** showing dependencies and costs for travelling between nodes. (That is
  102810. ** not a completely accurate description because WhereLoop costs are a
  102811. ** vector, not a scalar, and because dependencies are many-to-one, not
  102812. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  102813. ** Then a WherePath object is a path through the graph that visits some
  102814. ** or all of the WhereLoop objects once.
  102815. **
  102816. ** The "solver" works by creating the N best WherePath objects of length
  102817. ** 1. Then using those as a basis to compute the N best WherePath objects
  102818. ** of length 2. And so forth until the length of WherePaths equals the
  102819. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  102820. ** at the end is the choosen query plan.
  102821. */
  102822. struct WherePath {
  102823. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  102824. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  102825. LogEst nRow; /* Estimated number of rows generated by this path */
  102826. LogEst rCost; /* Total cost of this path */
  102827. u8 isOrdered; /* True if this path satisfies ORDER BY */
  102828. u8 isOrderedValid; /* True if the isOrdered field is valid */
  102829. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  102830. };
  102831. /*
  102832. ** The query generator uses an array of instances of this structure to
  102833. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  102834. ** clause subexpression is separated from the others by AND operators,
  102835. ** usually, or sometimes subexpressions separated by OR.
  102836. **
  102837. ** All WhereTerms are collected into a single WhereClause structure.
  102838. ** The following identity holds:
  102839. **
  102840. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  102841. **
  102842. ** When a term is of the form:
  102843. **
  102844. ** X <op> <expr>
  102845. **
  102846. ** where X is a column name and <op> is one of certain operators,
  102847. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  102848. ** cursor number and column number for X. WhereTerm.eOperator records
  102849. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  102850. ** use of a bitmask encoding for the operator allows us to search
  102851. ** quickly for terms that match any of several different operators.
  102852. **
  102853. ** A WhereTerm might also be two or more subterms connected by OR:
  102854. **
  102855. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  102856. **
  102857. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  102858. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  102859. ** is collected about the OR clause.
  102860. **
  102861. ** If a term in the WHERE clause does not match either of the two previous
  102862. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  102863. ** to the original subexpression content and wtFlags is set up appropriately
  102864. ** but no other fields in the WhereTerm object are meaningful.
  102865. **
  102866. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  102867. ** but they do so indirectly. A single WhereMaskSet structure translates
  102868. ** cursor number into bits and the translated bit is stored in the prereq
  102869. ** fields. The translation is used in order to maximize the number of
  102870. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  102871. ** spread out over the non-negative integers. For example, the cursor
  102872. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  102873. ** translates these sparse cursor numbers into consecutive integers
  102874. ** beginning with 0 in order to make the best possible use of the available
  102875. ** bits in the Bitmask. So, in the example above, the cursor numbers
  102876. ** would be mapped into integers 0 through 7.
  102877. **
  102878. ** The number of terms in a join is limited by the number of bits
  102879. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  102880. ** is only able to process joins with 64 or fewer tables.
  102881. */
  102882. struct WhereTerm {
  102883. Expr *pExpr; /* Pointer to the subexpression that is this term */
  102884. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  102885. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  102886. union {
  102887. int leftColumn; /* Column number of X in "X <op> <expr>" */
  102888. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  102889. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  102890. } u;
  102891. LogEst truthProb; /* Probability of truth for this expression */
  102892. u16 eOperator; /* A WO_xx value describing <op> */
  102893. u8 wtFlags; /* TERM_xxx bit flags. See below */
  102894. u8 nChild; /* Number of children that must disable us */
  102895. WhereClause *pWC; /* The clause this term is part of */
  102896. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  102897. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  102898. };
  102899. /*
  102900. ** Allowed values of WhereTerm.wtFlags
  102901. */
  102902. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  102903. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  102904. #define TERM_CODED 0x04 /* This term is already coded */
  102905. #define TERM_COPIED 0x08 /* Has a child */
  102906. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  102907. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  102908. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  102909. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  102910. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  102911. #else
  102912. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  102913. #endif
  102914. /*
  102915. ** An instance of the WhereScan object is used as an iterator for locating
  102916. ** terms in the WHERE clause that are useful to the query planner.
  102917. */
  102918. struct WhereScan {
  102919. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  102920. WhereClause *pWC; /* WhereClause currently being scanned */
  102921. char *zCollName; /* Required collating sequence, if not NULL */
  102922. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  102923. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  102924. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  102925. u32 opMask; /* Acceptable operators */
  102926. int k; /* Resume scanning at this->pWC->a[this->k] */
  102927. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  102928. };
  102929. /*
  102930. ** An instance of the following structure holds all information about a
  102931. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  102932. **
  102933. ** Explanation of pOuter: For a WHERE clause of the form
  102934. **
  102935. ** a AND ((b AND c) OR (d AND e)) AND f
  102936. **
  102937. ** There are separate WhereClause objects for the whole clause and for
  102938. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  102939. ** subclauses points to the WhereClause object for the whole clause.
  102940. */
  102941. struct WhereClause {
  102942. WhereInfo *pWInfo; /* WHERE clause processing context */
  102943. WhereClause *pOuter; /* Outer conjunction */
  102944. u8 op; /* Split operator. TK_AND or TK_OR */
  102945. int nTerm; /* Number of terms */
  102946. int nSlot; /* Number of entries in a[] */
  102947. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  102948. #if defined(SQLITE_SMALL_STACK)
  102949. WhereTerm aStatic[1]; /* Initial static space for a[] */
  102950. #else
  102951. WhereTerm aStatic[8]; /* Initial static space for a[] */
  102952. #endif
  102953. };
  102954. /*
  102955. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  102956. ** a dynamically allocated instance of the following structure.
  102957. */
  102958. struct WhereOrInfo {
  102959. WhereClause wc; /* Decomposition into subterms */
  102960. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  102961. };
  102962. /*
  102963. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  102964. ** a dynamically allocated instance of the following structure.
  102965. */
  102966. struct WhereAndInfo {
  102967. WhereClause wc; /* The subexpression broken out */
  102968. };
  102969. /*
  102970. ** An instance of the following structure keeps track of a mapping
  102971. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  102972. **
  102973. ** The VDBE cursor numbers are small integers contained in
  102974. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  102975. ** clause, the cursor numbers might not begin with 0 and they might
  102976. ** contain gaps in the numbering sequence. But we want to make maximum
  102977. ** use of the bits in our bitmasks. This structure provides a mapping
  102978. ** from the sparse cursor numbers into consecutive integers beginning
  102979. ** with 0.
  102980. **
  102981. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  102982. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  102983. **
  102984. ** For example, if the WHERE clause expression used these VDBE
  102985. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  102986. ** would map those cursor numbers into bits 0 through 5.
  102987. **
  102988. ** Note that the mapping is not necessarily ordered. In the example
  102989. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  102990. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  102991. ** does not really matter. What is important is that sparse cursor
  102992. ** numbers all get mapped into bit numbers that begin with 0 and contain
  102993. ** no gaps.
  102994. */
  102995. struct WhereMaskSet {
  102996. int n; /* Number of assigned cursor values */
  102997. int ix[BMS]; /* Cursor assigned to each bit */
  102998. };
  102999. /*
  103000. ** This object is a convenience wrapper holding all information needed
  103001. ** to construct WhereLoop objects for a particular query.
  103002. */
  103003. struct WhereLoopBuilder {
  103004. WhereInfo *pWInfo; /* Information about this WHERE */
  103005. WhereClause *pWC; /* WHERE clause terms */
  103006. ExprList *pOrderBy; /* ORDER BY clause */
  103007. WhereLoop *pNew; /* Template WhereLoop */
  103008. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  103009. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  103010. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  103011. int nRecValid; /* Number of valid fields currently in pRec */
  103012. #endif
  103013. };
  103014. /*
  103015. ** The WHERE clause processing routine has two halves. The
  103016. ** first part does the start of the WHERE loop and the second
  103017. ** half does the tail of the WHERE loop. An instance of
  103018. ** this structure is returned by the first half and passed
  103019. ** into the second half to give some continuity.
  103020. **
  103021. ** An instance of this object holds the complete state of the query
  103022. ** planner.
  103023. */
  103024. struct WhereInfo {
  103025. Parse *pParse; /* Parsing and code generating context */
  103026. SrcList *pTabList; /* List of tables in the join */
  103027. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  103028. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  103029. WhereLoop *pLoops; /* List of all WhereLoop objects */
  103030. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  103031. LogEst nRowOut; /* Estimated number of output rows */
  103032. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  103033. u8 bOBSat; /* ORDER BY satisfied by indices */
  103034. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  103035. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  103036. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  103037. u8 nLevel; /* Number of nested loop */
  103038. int iTop; /* The very beginning of the WHERE loop */
  103039. int iContinue; /* Jump here to continue with next record */
  103040. int iBreak; /* Jump here to break out of the loop */
  103041. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  103042. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  103043. WhereClause sWC; /* Decomposition of the WHERE clause */
  103044. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  103045. };
  103046. /*
  103047. ** Bitmasks for the operators on WhereTerm objects. These are all
  103048. ** operators that are of interest to the query planner. An
  103049. ** OR-ed combination of these values can be used when searching for
  103050. ** particular WhereTerms within a WhereClause.
  103051. */
  103052. #define WO_IN 0x001
  103053. #define WO_EQ 0x002
  103054. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  103055. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  103056. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  103057. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  103058. #define WO_MATCH 0x040
  103059. #define WO_ISNULL 0x080
  103060. #define WO_OR 0x100 /* Two or more OR-connected terms */
  103061. #define WO_AND 0x200 /* Two or more AND-connected terms */
  103062. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  103063. #define WO_NOOP 0x800 /* This term does not restrict search space */
  103064. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  103065. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  103066. /*
  103067. ** These are definitions of bits in the WhereLoop.wsFlags field.
  103068. ** The particular combination of bits in each WhereLoop help to
  103069. ** determine the algorithm that WhereLoop represents.
  103070. */
  103071. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  103072. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  103073. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  103074. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  103075. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  103076. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  103077. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  103078. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  103079. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  103080. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  103081. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  103082. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  103083. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  103084. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  103085. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  103086. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  103087. /*
  103088. ** Return the estimated number of output rows from a WHERE clause
  103089. */
  103090. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  103091. return sqlite3LogEstToInt(pWInfo->nRowOut);
  103092. }
  103093. /*
  103094. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  103095. ** WHERE clause returns outputs for DISTINCT processing.
  103096. */
  103097. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  103098. return pWInfo->eDistinct;
  103099. }
  103100. /*
  103101. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  103102. ** Return FALSE if the output needs to be sorted.
  103103. */
  103104. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  103105. return pWInfo->bOBSat!=0;
  103106. }
  103107. /*
  103108. ** Return the VDBE address or label to jump to in order to continue
  103109. ** immediately with the next row of a WHERE clause.
  103110. */
  103111. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  103112. return pWInfo->iContinue;
  103113. }
  103114. /*
  103115. ** Return the VDBE address or label to jump to in order to break
  103116. ** out of a WHERE loop.
  103117. */
  103118. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  103119. return pWInfo->iBreak;
  103120. }
  103121. /*
  103122. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  103123. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  103124. ** UPDATE or DELETE might change subsequent WHERE clause results.
  103125. */
  103126. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo){
  103127. return pWInfo->okOnePass;
  103128. }
  103129. /*
  103130. ** Move the content of pSrc into pDest
  103131. */
  103132. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  103133. pDest->n = pSrc->n;
  103134. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  103135. }
  103136. /*
  103137. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  103138. **
  103139. ** The new entry might overwrite an existing entry, or it might be
  103140. ** appended, or it might be discarded. Do whatever is the right thing
  103141. ** so that pSet keeps the N_OR_COST best entries seen so far.
  103142. */
  103143. static int whereOrInsert(
  103144. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  103145. Bitmask prereq, /* Prerequisites of the new entry */
  103146. LogEst rRun, /* Run-cost of the new entry */
  103147. LogEst nOut /* Number of outputs for the new entry */
  103148. ){
  103149. u16 i;
  103150. WhereOrCost *p;
  103151. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  103152. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  103153. goto whereOrInsert_done;
  103154. }
  103155. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  103156. return 0;
  103157. }
  103158. }
  103159. if( pSet->n<N_OR_COST ){
  103160. p = &pSet->a[pSet->n++];
  103161. p->nOut = nOut;
  103162. }else{
  103163. p = pSet->a;
  103164. for(i=1; i<pSet->n; i++){
  103165. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  103166. }
  103167. if( p->rRun<=rRun ) return 0;
  103168. }
  103169. whereOrInsert_done:
  103170. p->prereq = prereq;
  103171. p->rRun = rRun;
  103172. if( p->nOut>nOut ) p->nOut = nOut;
  103173. return 1;
  103174. }
  103175. /*
  103176. ** Initialize a preallocated WhereClause structure.
  103177. */
  103178. static void whereClauseInit(
  103179. WhereClause *pWC, /* The WhereClause to be initialized */
  103180. WhereInfo *pWInfo /* The WHERE processing context */
  103181. ){
  103182. pWC->pWInfo = pWInfo;
  103183. pWC->pOuter = 0;
  103184. pWC->nTerm = 0;
  103185. pWC->nSlot = ArraySize(pWC->aStatic);
  103186. pWC->a = pWC->aStatic;
  103187. }
  103188. /* Forward reference */
  103189. static void whereClauseClear(WhereClause*);
  103190. /*
  103191. ** Deallocate all memory associated with a WhereOrInfo object.
  103192. */
  103193. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  103194. whereClauseClear(&p->wc);
  103195. sqlite3DbFree(db, p);
  103196. }
  103197. /*
  103198. ** Deallocate all memory associated with a WhereAndInfo object.
  103199. */
  103200. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  103201. whereClauseClear(&p->wc);
  103202. sqlite3DbFree(db, p);
  103203. }
  103204. /*
  103205. ** Deallocate a WhereClause structure. The WhereClause structure
  103206. ** itself is not freed. This routine is the inverse of whereClauseInit().
  103207. */
  103208. static void whereClauseClear(WhereClause *pWC){
  103209. int i;
  103210. WhereTerm *a;
  103211. sqlite3 *db = pWC->pWInfo->pParse->db;
  103212. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  103213. if( a->wtFlags & TERM_DYNAMIC ){
  103214. sqlite3ExprDelete(db, a->pExpr);
  103215. }
  103216. if( a->wtFlags & TERM_ORINFO ){
  103217. whereOrInfoDelete(db, a->u.pOrInfo);
  103218. }else if( a->wtFlags & TERM_ANDINFO ){
  103219. whereAndInfoDelete(db, a->u.pAndInfo);
  103220. }
  103221. }
  103222. if( pWC->a!=pWC->aStatic ){
  103223. sqlite3DbFree(db, pWC->a);
  103224. }
  103225. }
  103226. /*
  103227. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  103228. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  103229. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  103230. ** 0 is returned if the new WhereTerm could not be added due to a memory
  103231. ** allocation error. The memory allocation failure will be recorded in
  103232. ** the db->mallocFailed flag so that higher-level functions can detect it.
  103233. **
  103234. ** This routine will increase the size of the pWC->a[] array as necessary.
  103235. **
  103236. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  103237. ** for freeing the expression p is assumed by the WhereClause object pWC.
  103238. ** This is true even if this routine fails to allocate a new WhereTerm.
  103239. **
  103240. ** WARNING: This routine might reallocate the space used to store
  103241. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  103242. ** calling this routine. Such pointers may be reinitialized by referencing
  103243. ** the pWC->a[] array.
  103244. */
  103245. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  103246. WhereTerm *pTerm;
  103247. int idx;
  103248. testcase( wtFlags & TERM_VIRTUAL );
  103249. if( pWC->nTerm>=pWC->nSlot ){
  103250. WhereTerm *pOld = pWC->a;
  103251. sqlite3 *db = pWC->pWInfo->pParse->db;
  103252. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  103253. if( pWC->a==0 ){
  103254. if( wtFlags & TERM_DYNAMIC ){
  103255. sqlite3ExprDelete(db, p);
  103256. }
  103257. pWC->a = pOld;
  103258. return 0;
  103259. }
  103260. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  103261. if( pOld!=pWC->aStatic ){
  103262. sqlite3DbFree(db, pOld);
  103263. }
  103264. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  103265. }
  103266. pTerm = &pWC->a[idx = pWC->nTerm++];
  103267. if( p && ExprHasProperty(p, EP_Unlikely) ){
  103268. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  103269. }else{
  103270. pTerm->truthProb = -1;
  103271. }
  103272. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  103273. pTerm->wtFlags = wtFlags;
  103274. pTerm->pWC = pWC;
  103275. pTerm->iParent = -1;
  103276. return idx;
  103277. }
  103278. /*
  103279. ** This routine identifies subexpressions in the WHERE clause where
  103280. ** each subexpression is separated by the AND operator or some other
  103281. ** operator specified in the op parameter. The WhereClause structure
  103282. ** is filled with pointers to subexpressions. For example:
  103283. **
  103284. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  103285. ** \________/ \_______________/ \________________/
  103286. ** slot[0] slot[1] slot[2]
  103287. **
  103288. ** The original WHERE clause in pExpr is unaltered. All this routine
  103289. ** does is make slot[] entries point to substructure within pExpr.
  103290. **
  103291. ** In the previous sentence and in the diagram, "slot[]" refers to
  103292. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  103293. ** all terms of the WHERE clause.
  103294. */
  103295. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  103296. pWC->op = op;
  103297. if( pExpr==0 ) return;
  103298. if( pExpr->op!=op ){
  103299. whereClauseInsert(pWC, pExpr, 0);
  103300. }else{
  103301. whereSplit(pWC, pExpr->pLeft, op);
  103302. whereSplit(pWC, pExpr->pRight, op);
  103303. }
  103304. }
  103305. /*
  103306. ** Initialize a WhereMaskSet object
  103307. */
  103308. #define initMaskSet(P) (P)->n=0
  103309. /*
  103310. ** Return the bitmask for the given cursor number. Return 0 if
  103311. ** iCursor is not in the set.
  103312. */
  103313. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  103314. int i;
  103315. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  103316. for(i=0; i<pMaskSet->n; i++){
  103317. if( pMaskSet->ix[i]==iCursor ){
  103318. return MASKBIT(i);
  103319. }
  103320. }
  103321. return 0;
  103322. }
  103323. /*
  103324. ** Create a new mask for cursor iCursor.
  103325. **
  103326. ** There is one cursor per table in the FROM clause. The number of
  103327. ** tables in the FROM clause is limited by a test early in the
  103328. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  103329. ** array will never overflow.
  103330. */
  103331. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  103332. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  103333. pMaskSet->ix[pMaskSet->n++] = iCursor;
  103334. }
  103335. /*
  103336. ** These routines walk (recursively) an expression tree and generate
  103337. ** a bitmask indicating which tables are used in that expression
  103338. ** tree.
  103339. */
  103340. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  103341. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  103342. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  103343. Bitmask mask = 0;
  103344. if( p==0 ) return 0;
  103345. if( p->op==TK_COLUMN ){
  103346. mask = getMask(pMaskSet, p->iTable);
  103347. return mask;
  103348. }
  103349. mask = exprTableUsage(pMaskSet, p->pRight);
  103350. mask |= exprTableUsage(pMaskSet, p->pLeft);
  103351. if( ExprHasProperty(p, EP_xIsSelect) ){
  103352. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  103353. }else{
  103354. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  103355. }
  103356. return mask;
  103357. }
  103358. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  103359. int i;
  103360. Bitmask mask = 0;
  103361. if( pList ){
  103362. for(i=0; i<pList->nExpr; i++){
  103363. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  103364. }
  103365. }
  103366. return mask;
  103367. }
  103368. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  103369. Bitmask mask = 0;
  103370. while( pS ){
  103371. SrcList *pSrc = pS->pSrc;
  103372. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  103373. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  103374. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  103375. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  103376. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  103377. if( ALWAYS(pSrc!=0) ){
  103378. int i;
  103379. for(i=0; i<pSrc->nSrc; i++){
  103380. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  103381. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  103382. }
  103383. }
  103384. pS = pS->pPrior;
  103385. }
  103386. return mask;
  103387. }
  103388. /*
  103389. ** Return TRUE if the given operator is one of the operators that is
  103390. ** allowed for an indexable WHERE clause term. The allowed operators are
  103391. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  103392. */
  103393. static int allowedOp(int op){
  103394. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  103395. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  103396. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  103397. assert( TK_GE==TK_EQ+4 );
  103398. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  103399. }
  103400. /*
  103401. ** Swap two objects of type TYPE.
  103402. */
  103403. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  103404. /*
  103405. ** Commute a comparison operator. Expressions of the form "X op Y"
  103406. ** are converted into "Y op X".
  103407. **
  103408. ** If left/right precedence rules come into play when determining the
  103409. ** collating sequence, then COLLATE operators are adjusted to ensure
  103410. ** that the collating sequence does not change. For example:
  103411. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  103412. ** the left hand side of a comparison overrides any collation sequence
  103413. ** attached to the right. For the same reason the EP_Collate flag
  103414. ** is not commuted.
  103415. */
  103416. static void exprCommute(Parse *pParse, Expr *pExpr){
  103417. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  103418. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  103419. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  103420. if( expRight==expLeft ){
  103421. /* Either X and Y both have COLLATE operator or neither do */
  103422. if( expRight ){
  103423. /* Both X and Y have COLLATE operators. Make sure X is always
  103424. ** used by clearing the EP_Collate flag from Y. */
  103425. pExpr->pRight->flags &= ~EP_Collate;
  103426. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  103427. /* Neither X nor Y have COLLATE operators, but X has a non-default
  103428. ** collating sequence. So add the EP_Collate marker on X to cause
  103429. ** it to be searched first. */
  103430. pExpr->pLeft->flags |= EP_Collate;
  103431. }
  103432. }
  103433. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  103434. if( pExpr->op>=TK_GT ){
  103435. assert( TK_LT==TK_GT+2 );
  103436. assert( TK_GE==TK_LE+2 );
  103437. assert( TK_GT>TK_EQ );
  103438. assert( TK_GT<TK_LE );
  103439. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  103440. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  103441. }
  103442. }
  103443. /*
  103444. ** Translate from TK_xx operator to WO_xx bitmask.
  103445. */
  103446. static u16 operatorMask(int op){
  103447. u16 c;
  103448. assert( allowedOp(op) );
  103449. if( op==TK_IN ){
  103450. c = WO_IN;
  103451. }else if( op==TK_ISNULL ){
  103452. c = WO_ISNULL;
  103453. }else{
  103454. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  103455. c = (u16)(WO_EQ<<(op-TK_EQ));
  103456. }
  103457. assert( op!=TK_ISNULL || c==WO_ISNULL );
  103458. assert( op!=TK_IN || c==WO_IN );
  103459. assert( op!=TK_EQ || c==WO_EQ );
  103460. assert( op!=TK_LT || c==WO_LT );
  103461. assert( op!=TK_LE || c==WO_LE );
  103462. assert( op!=TK_GT || c==WO_GT );
  103463. assert( op!=TK_GE || c==WO_GE );
  103464. return c;
  103465. }
  103466. /*
  103467. ** Advance to the next WhereTerm that matches according to the criteria
  103468. ** established when the pScan object was initialized by whereScanInit().
  103469. ** Return NULL if there are no more matching WhereTerms.
  103470. */
  103471. static WhereTerm *whereScanNext(WhereScan *pScan){
  103472. int iCur; /* The cursor on the LHS of the term */
  103473. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  103474. Expr *pX; /* An expression being tested */
  103475. WhereClause *pWC; /* Shorthand for pScan->pWC */
  103476. WhereTerm *pTerm; /* The term being tested */
  103477. int k = pScan->k; /* Where to start scanning */
  103478. while( pScan->iEquiv<=pScan->nEquiv ){
  103479. iCur = pScan->aEquiv[pScan->iEquiv-2];
  103480. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  103481. while( (pWC = pScan->pWC)!=0 ){
  103482. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  103483. if( pTerm->leftCursor==iCur && pTerm->u.leftColumn==iColumn ){
  103484. if( (pTerm->eOperator & WO_EQUIV)!=0
  103485. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  103486. ){
  103487. int j;
  103488. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  103489. assert( pX->op==TK_COLUMN );
  103490. for(j=0; j<pScan->nEquiv; j+=2){
  103491. if( pScan->aEquiv[j]==pX->iTable
  103492. && pScan->aEquiv[j+1]==pX->iColumn ){
  103493. break;
  103494. }
  103495. }
  103496. if( j==pScan->nEquiv ){
  103497. pScan->aEquiv[j] = pX->iTable;
  103498. pScan->aEquiv[j+1] = pX->iColumn;
  103499. pScan->nEquiv += 2;
  103500. }
  103501. }
  103502. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  103503. /* Verify the affinity and collating sequence match */
  103504. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  103505. CollSeq *pColl;
  103506. Parse *pParse = pWC->pWInfo->pParse;
  103507. pX = pTerm->pExpr;
  103508. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  103509. continue;
  103510. }
  103511. assert(pX->pLeft);
  103512. pColl = sqlite3BinaryCompareCollSeq(pParse,
  103513. pX->pLeft, pX->pRight);
  103514. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  103515. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  103516. continue;
  103517. }
  103518. }
  103519. if( (pTerm->eOperator & WO_EQ)!=0
  103520. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  103521. && pX->iTable==pScan->aEquiv[0]
  103522. && pX->iColumn==pScan->aEquiv[1]
  103523. ){
  103524. continue;
  103525. }
  103526. pScan->k = k+1;
  103527. return pTerm;
  103528. }
  103529. }
  103530. }
  103531. pScan->pWC = pScan->pWC->pOuter;
  103532. k = 0;
  103533. }
  103534. pScan->pWC = pScan->pOrigWC;
  103535. k = 0;
  103536. pScan->iEquiv += 2;
  103537. }
  103538. return 0;
  103539. }
  103540. /*
  103541. ** Initialize a WHERE clause scanner object. Return a pointer to the
  103542. ** first match. Return NULL if there are no matches.
  103543. **
  103544. ** The scanner will be searching the WHERE clause pWC. It will look
  103545. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  103546. ** iCur. The <op> must be one of the operators described by opMask.
  103547. **
  103548. ** If the search is for X and the WHERE clause contains terms of the
  103549. ** form X=Y then this routine might also return terms of the form
  103550. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  103551. ** but is enough to handle most commonly occurring SQL statements.
  103552. **
  103553. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  103554. ** index pIdx.
  103555. */
  103556. static WhereTerm *whereScanInit(
  103557. WhereScan *pScan, /* The WhereScan object being initialized */
  103558. WhereClause *pWC, /* The WHERE clause to be scanned */
  103559. int iCur, /* Cursor to scan for */
  103560. int iColumn, /* Column to scan for */
  103561. u32 opMask, /* Operator(s) to scan for */
  103562. Index *pIdx /* Must be compatible with this index */
  103563. ){
  103564. int j;
  103565. /* memset(pScan, 0, sizeof(*pScan)); */
  103566. pScan->pOrigWC = pWC;
  103567. pScan->pWC = pWC;
  103568. if( pIdx && iColumn>=0 ){
  103569. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  103570. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  103571. if( NEVER(j>=pIdx->nColumn) ) return 0;
  103572. }
  103573. pScan->zCollName = pIdx->azColl[j];
  103574. }else{
  103575. pScan->idxaff = 0;
  103576. pScan->zCollName = 0;
  103577. }
  103578. pScan->opMask = opMask;
  103579. pScan->k = 0;
  103580. pScan->aEquiv[0] = iCur;
  103581. pScan->aEquiv[1] = iColumn;
  103582. pScan->nEquiv = 2;
  103583. pScan->iEquiv = 2;
  103584. return whereScanNext(pScan);
  103585. }
  103586. /*
  103587. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  103588. ** where X is a reference to the iColumn of table iCur and <op> is one of
  103589. ** the WO_xx operator codes specified by the op parameter.
  103590. ** Return a pointer to the term. Return 0 if not found.
  103591. **
  103592. ** The term returned might by Y=<expr> if there is another constraint in
  103593. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  103594. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  103595. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  103596. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  103597. ** and the second is for the column number. There are 22 slots in aEquiv[]
  103598. ** so that means we can look for X plus up to 10 other equivalent values.
  103599. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  103600. ** and ... and A9=A10 and A10=<expr>.
  103601. **
  103602. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  103603. ** then try for the one with no dependencies on <expr> - in other words where
  103604. ** <expr> is a constant expression of some kind. Only return entries of
  103605. ** the form "X <op> Y" where Y is a column in another table if no terms of
  103606. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  103607. ** exist, try to return a term that does not use WO_EQUIV.
  103608. */
  103609. static WhereTerm *findTerm(
  103610. WhereClause *pWC, /* The WHERE clause to be searched */
  103611. int iCur, /* Cursor number of LHS */
  103612. int iColumn, /* Column number of LHS */
  103613. Bitmask notReady, /* RHS must not overlap with this mask */
  103614. u32 op, /* Mask of WO_xx values describing operator */
  103615. Index *pIdx /* Must be compatible with this index, if not NULL */
  103616. ){
  103617. WhereTerm *pResult = 0;
  103618. WhereTerm *p;
  103619. WhereScan scan;
  103620. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  103621. while( p ){
  103622. if( (p->prereqRight & notReady)==0 ){
  103623. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  103624. return p;
  103625. }
  103626. if( pResult==0 ) pResult = p;
  103627. }
  103628. p = whereScanNext(&scan);
  103629. }
  103630. return pResult;
  103631. }
  103632. /* Forward reference */
  103633. static void exprAnalyze(SrcList*, WhereClause*, int);
  103634. /*
  103635. ** Call exprAnalyze on all terms in a WHERE clause.
  103636. */
  103637. static void exprAnalyzeAll(
  103638. SrcList *pTabList, /* the FROM clause */
  103639. WhereClause *pWC /* the WHERE clause to be analyzed */
  103640. ){
  103641. int i;
  103642. for(i=pWC->nTerm-1; i>=0; i--){
  103643. exprAnalyze(pTabList, pWC, i);
  103644. }
  103645. }
  103646. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  103647. /*
  103648. ** Check to see if the given expression is a LIKE or GLOB operator that
  103649. ** can be optimized using inequality constraints. Return TRUE if it is
  103650. ** so and false if not.
  103651. **
  103652. ** In order for the operator to be optimizible, the RHS must be a string
  103653. ** literal that does not begin with a wildcard.
  103654. */
  103655. static int isLikeOrGlob(
  103656. Parse *pParse, /* Parsing and code generating context */
  103657. Expr *pExpr, /* Test this expression */
  103658. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  103659. int *pisComplete, /* True if the only wildcard is % in the last character */
  103660. int *pnoCase /* True if uppercase is equivalent to lowercase */
  103661. ){
  103662. const char *z = 0; /* String on RHS of LIKE operator */
  103663. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  103664. ExprList *pList; /* List of operands to the LIKE operator */
  103665. int c; /* One character in z[] */
  103666. int cnt; /* Number of non-wildcard prefix characters */
  103667. char wc[3]; /* Wildcard characters */
  103668. sqlite3 *db = pParse->db; /* Database connection */
  103669. sqlite3_value *pVal = 0;
  103670. int op; /* Opcode of pRight */
  103671. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  103672. return 0;
  103673. }
  103674. #ifdef SQLITE_EBCDIC
  103675. if( *pnoCase ) return 0;
  103676. #endif
  103677. pList = pExpr->x.pList;
  103678. pLeft = pList->a[1].pExpr;
  103679. if( pLeft->op!=TK_COLUMN
  103680. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  103681. || IsVirtual(pLeft->pTab)
  103682. ){
  103683. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  103684. ** be the name of an indexed column with TEXT affinity. */
  103685. return 0;
  103686. }
  103687. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  103688. pRight = pList->a[0].pExpr;
  103689. op = pRight->op;
  103690. if( op==TK_REGISTER ){
  103691. op = pRight->op2;
  103692. }
  103693. if( op==TK_VARIABLE ){
  103694. Vdbe *pReprepare = pParse->pReprepare;
  103695. int iCol = pRight->iColumn;
  103696. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  103697. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  103698. z = (char *)sqlite3_value_text(pVal);
  103699. }
  103700. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  103701. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  103702. }else if( op==TK_STRING ){
  103703. z = pRight->u.zToken;
  103704. }
  103705. if( z ){
  103706. cnt = 0;
  103707. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  103708. cnt++;
  103709. }
  103710. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  103711. Expr *pPrefix;
  103712. *pisComplete = c==wc[0] && z[cnt+1]==0;
  103713. pPrefix = sqlite3Expr(db, TK_STRING, z);
  103714. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  103715. *ppPrefix = pPrefix;
  103716. if( op==TK_VARIABLE ){
  103717. Vdbe *v = pParse->pVdbe;
  103718. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  103719. if( *pisComplete && pRight->u.zToken[1] ){
  103720. /* If the rhs of the LIKE expression is a variable, and the current
  103721. ** value of the variable means there is no need to invoke the LIKE
  103722. ** function, then no OP_Variable will be added to the program.
  103723. ** This causes problems for the sqlite3_bind_parameter_name()
  103724. ** API. To workaround them, add a dummy OP_Variable here.
  103725. */
  103726. int r1 = sqlite3GetTempReg(pParse);
  103727. sqlite3ExprCodeTarget(pParse, pRight, r1);
  103728. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  103729. sqlite3ReleaseTempReg(pParse, r1);
  103730. }
  103731. }
  103732. }else{
  103733. z = 0;
  103734. }
  103735. }
  103736. sqlite3ValueFree(pVal);
  103737. return (z!=0);
  103738. }
  103739. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  103740. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103741. /*
  103742. ** Check to see if the given expression is of the form
  103743. **
  103744. ** column MATCH expr
  103745. **
  103746. ** If it is then return TRUE. If not, return FALSE.
  103747. */
  103748. static int isMatchOfColumn(
  103749. Expr *pExpr /* Test this expression */
  103750. ){
  103751. ExprList *pList;
  103752. if( pExpr->op!=TK_FUNCTION ){
  103753. return 0;
  103754. }
  103755. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  103756. return 0;
  103757. }
  103758. pList = pExpr->x.pList;
  103759. if( pList->nExpr!=2 ){
  103760. return 0;
  103761. }
  103762. if( pList->a[1].pExpr->op != TK_COLUMN ){
  103763. return 0;
  103764. }
  103765. return 1;
  103766. }
  103767. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  103768. /*
  103769. ** If the pBase expression originated in the ON or USING clause of
  103770. ** a join, then transfer the appropriate markings over to derived.
  103771. */
  103772. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  103773. if( pDerived ){
  103774. pDerived->flags |= pBase->flags & EP_FromJoin;
  103775. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  103776. }
  103777. }
  103778. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  103779. /*
  103780. ** Analyze a term that consists of two or more OR-connected
  103781. ** subterms. So in:
  103782. **
  103783. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  103784. ** ^^^^^^^^^^^^^^^^^^^^
  103785. **
  103786. ** This routine analyzes terms such as the middle term in the above example.
  103787. ** A WhereOrTerm object is computed and attached to the term under
  103788. ** analysis, regardless of the outcome of the analysis. Hence:
  103789. **
  103790. ** WhereTerm.wtFlags |= TERM_ORINFO
  103791. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  103792. **
  103793. ** The term being analyzed must have two or more of OR-connected subterms.
  103794. ** A single subterm might be a set of AND-connected sub-subterms.
  103795. ** Examples of terms under analysis:
  103796. **
  103797. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  103798. ** (B) x=expr1 OR expr2=x OR x=expr3
  103799. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  103800. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  103801. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  103802. **
  103803. ** CASE 1:
  103804. **
  103805. ** If all subterms are of the form T.C=expr for some single column of C and
  103806. ** a single table T (as shown in example B above) then create a new virtual
  103807. ** term that is an equivalent IN expression. In other words, if the term
  103808. ** being analyzed is:
  103809. **
  103810. ** x = expr1 OR expr2 = x OR x = expr3
  103811. **
  103812. ** then create a new virtual term like this:
  103813. **
  103814. ** x IN (expr1,expr2,expr3)
  103815. **
  103816. ** CASE 2:
  103817. **
  103818. ** If all subterms are indexable by a single table T, then set
  103819. **
  103820. ** WhereTerm.eOperator = WO_OR
  103821. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  103822. **
  103823. ** A subterm is "indexable" if it is of the form
  103824. ** "T.C <op> <expr>" where C is any column of table T and
  103825. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  103826. ** A subterm is also indexable if it is an AND of two or more
  103827. ** subsubterms at least one of which is indexable. Indexable AND
  103828. ** subterms have their eOperator set to WO_AND and they have
  103829. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  103830. **
  103831. ** From another point of view, "indexable" means that the subterm could
  103832. ** potentially be used with an index if an appropriate index exists.
  103833. ** This analysis does not consider whether or not the index exists; that
  103834. ** is decided elsewhere. This analysis only looks at whether subterms
  103835. ** appropriate for indexing exist.
  103836. **
  103837. ** All examples A through E above satisfy case 2. But if a term
  103838. ** also statisfies case 1 (such as B) we know that the optimizer will
  103839. ** always prefer case 1, so in that case we pretend that case 2 is not
  103840. ** satisfied.
  103841. **
  103842. ** It might be the case that multiple tables are indexable. For example,
  103843. ** (E) above is indexable on tables P, Q, and R.
  103844. **
  103845. ** Terms that satisfy case 2 are candidates for lookup by using
  103846. ** separate indices to find rowids for each subterm and composing
  103847. ** the union of all rowids using a RowSet object. This is similar
  103848. ** to "bitmap indices" in other database engines.
  103849. **
  103850. ** OTHERWISE:
  103851. **
  103852. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  103853. ** zero. This term is not useful for search.
  103854. */
  103855. static void exprAnalyzeOrTerm(
  103856. SrcList *pSrc, /* the FROM clause */
  103857. WhereClause *pWC, /* the complete WHERE clause */
  103858. int idxTerm /* Index of the OR-term to be analyzed */
  103859. ){
  103860. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  103861. Parse *pParse = pWInfo->pParse; /* Parser context */
  103862. sqlite3 *db = pParse->db; /* Database connection */
  103863. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  103864. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  103865. int i; /* Loop counters */
  103866. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  103867. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  103868. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  103869. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  103870. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  103871. /*
  103872. ** Break the OR clause into its separate subterms. The subterms are
  103873. ** stored in a WhereClause structure containing within the WhereOrInfo
  103874. ** object that is attached to the original OR clause term.
  103875. */
  103876. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  103877. assert( pExpr->op==TK_OR );
  103878. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  103879. if( pOrInfo==0 ) return;
  103880. pTerm->wtFlags |= TERM_ORINFO;
  103881. pOrWc = &pOrInfo->wc;
  103882. whereClauseInit(pOrWc, pWInfo);
  103883. whereSplit(pOrWc, pExpr, TK_OR);
  103884. exprAnalyzeAll(pSrc, pOrWc);
  103885. if( db->mallocFailed ) return;
  103886. assert( pOrWc->nTerm>=2 );
  103887. /*
  103888. ** Compute the set of tables that might satisfy cases 1 or 2.
  103889. */
  103890. indexable = ~(Bitmask)0;
  103891. chngToIN = ~(Bitmask)0;
  103892. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  103893. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  103894. WhereAndInfo *pAndInfo;
  103895. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  103896. chngToIN = 0;
  103897. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  103898. if( pAndInfo ){
  103899. WhereClause *pAndWC;
  103900. WhereTerm *pAndTerm;
  103901. int j;
  103902. Bitmask b = 0;
  103903. pOrTerm->u.pAndInfo = pAndInfo;
  103904. pOrTerm->wtFlags |= TERM_ANDINFO;
  103905. pOrTerm->eOperator = WO_AND;
  103906. pAndWC = &pAndInfo->wc;
  103907. whereClauseInit(pAndWC, pWC->pWInfo);
  103908. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  103909. exprAnalyzeAll(pSrc, pAndWC);
  103910. pAndWC->pOuter = pWC;
  103911. testcase( db->mallocFailed );
  103912. if( !db->mallocFailed ){
  103913. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  103914. assert( pAndTerm->pExpr );
  103915. if( allowedOp(pAndTerm->pExpr->op) ){
  103916. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  103917. }
  103918. }
  103919. }
  103920. indexable &= b;
  103921. }
  103922. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  103923. /* Skip this term for now. We revisit it when we process the
  103924. ** corresponding TERM_VIRTUAL term */
  103925. }else{
  103926. Bitmask b;
  103927. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  103928. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  103929. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  103930. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  103931. }
  103932. indexable &= b;
  103933. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  103934. chngToIN = 0;
  103935. }else{
  103936. chngToIN &= b;
  103937. }
  103938. }
  103939. }
  103940. /*
  103941. ** Record the set of tables that satisfy case 2. The set might be
  103942. ** empty.
  103943. */
  103944. pOrInfo->indexable = indexable;
  103945. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  103946. /*
  103947. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  103948. ** we have to do some additional checking to see if case 1 really
  103949. ** is satisfied.
  103950. **
  103951. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  103952. ** that there is no possibility of transforming the OR clause into an
  103953. ** IN operator because one or more terms in the OR clause contain
  103954. ** something other than == on a column in the single table. The 1-bit
  103955. ** case means that every term of the OR clause is of the form
  103956. ** "table.column=expr" for some single table. The one bit that is set
  103957. ** will correspond to the common table. We still need to check to make
  103958. ** sure the same column is used on all terms. The 2-bit case is when
  103959. ** the all terms are of the form "table1.column=table2.column". It
  103960. ** might be possible to form an IN operator with either table1.column
  103961. ** or table2.column as the LHS if either is common to every term of
  103962. ** the OR clause.
  103963. **
  103964. ** Note that terms of the form "table.column1=table.column2" (the
  103965. ** same table on both sizes of the ==) cannot be optimized.
  103966. */
  103967. if( chngToIN ){
  103968. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  103969. int iColumn = -1; /* Column index on lhs of IN operator */
  103970. int iCursor = -1; /* Table cursor common to all terms */
  103971. int j = 0; /* Loop counter */
  103972. /* Search for a table and column that appears on one side or the
  103973. ** other of the == operator in every subterm. That table and column
  103974. ** will be recorded in iCursor and iColumn. There might not be any
  103975. ** such table and column. Set okToChngToIN if an appropriate table
  103976. ** and column is found but leave okToChngToIN false if not found.
  103977. */
  103978. for(j=0; j<2 && !okToChngToIN; j++){
  103979. pOrTerm = pOrWc->a;
  103980. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  103981. assert( pOrTerm->eOperator & WO_EQ );
  103982. pOrTerm->wtFlags &= ~TERM_OR_OK;
  103983. if( pOrTerm->leftCursor==iCursor ){
  103984. /* This is the 2-bit case and we are on the second iteration and
  103985. ** current term is from the first iteration. So skip this term. */
  103986. assert( j==1 );
  103987. continue;
  103988. }
  103989. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  103990. /* This term must be of the form t1.a==t2.b where t2 is in the
  103991. ** chngToIN set but t1 is not. This term will be either preceeded
  103992. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  103993. ** and use its inversion. */
  103994. testcase( pOrTerm->wtFlags & TERM_COPIED );
  103995. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  103996. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  103997. continue;
  103998. }
  103999. iColumn = pOrTerm->u.leftColumn;
  104000. iCursor = pOrTerm->leftCursor;
  104001. break;
  104002. }
  104003. if( i<0 ){
  104004. /* No candidate table+column was found. This can only occur
  104005. ** on the second iteration */
  104006. assert( j==1 );
  104007. assert( IsPowerOfTwo(chngToIN) );
  104008. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  104009. break;
  104010. }
  104011. testcase( j==1 );
  104012. /* We have found a candidate table and column. Check to see if that
  104013. ** table and column is common to every term in the OR clause */
  104014. okToChngToIN = 1;
  104015. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  104016. assert( pOrTerm->eOperator & WO_EQ );
  104017. if( pOrTerm->leftCursor!=iCursor ){
  104018. pOrTerm->wtFlags &= ~TERM_OR_OK;
  104019. }else if( pOrTerm->u.leftColumn!=iColumn ){
  104020. okToChngToIN = 0;
  104021. }else{
  104022. int affLeft, affRight;
  104023. /* If the right-hand side is also a column, then the affinities
  104024. ** of both right and left sides must be such that no type
  104025. ** conversions are required on the right. (Ticket #2249)
  104026. */
  104027. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  104028. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  104029. if( affRight!=0 && affRight!=affLeft ){
  104030. okToChngToIN = 0;
  104031. }else{
  104032. pOrTerm->wtFlags |= TERM_OR_OK;
  104033. }
  104034. }
  104035. }
  104036. }
  104037. /* At this point, okToChngToIN is true if original pTerm satisfies
  104038. ** case 1. In that case, construct a new virtual term that is
  104039. ** pTerm converted into an IN operator.
  104040. */
  104041. if( okToChngToIN ){
  104042. Expr *pDup; /* A transient duplicate expression */
  104043. ExprList *pList = 0; /* The RHS of the IN operator */
  104044. Expr *pLeft = 0; /* The LHS of the IN operator */
  104045. Expr *pNew; /* The complete IN operator */
  104046. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  104047. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  104048. assert( pOrTerm->eOperator & WO_EQ );
  104049. assert( pOrTerm->leftCursor==iCursor );
  104050. assert( pOrTerm->u.leftColumn==iColumn );
  104051. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  104052. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  104053. pLeft = pOrTerm->pExpr->pLeft;
  104054. }
  104055. assert( pLeft!=0 );
  104056. pDup = sqlite3ExprDup(db, pLeft, 0);
  104057. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  104058. if( pNew ){
  104059. int idxNew;
  104060. transferJoinMarkings(pNew, pExpr);
  104061. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  104062. pNew->x.pList = pList;
  104063. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  104064. testcase( idxNew==0 );
  104065. exprAnalyze(pSrc, pWC, idxNew);
  104066. pTerm = &pWC->a[idxTerm];
  104067. pWC->a[idxNew].iParent = idxTerm;
  104068. pTerm->nChild = 1;
  104069. }else{
  104070. sqlite3ExprListDelete(db, pList);
  104071. }
  104072. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  104073. }
  104074. }
  104075. }
  104076. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  104077. /*
  104078. ** The input to this routine is an WhereTerm structure with only the
  104079. ** "pExpr" field filled in. The job of this routine is to analyze the
  104080. ** subexpression and populate all the other fields of the WhereTerm
  104081. ** structure.
  104082. **
  104083. ** If the expression is of the form "<expr> <op> X" it gets commuted
  104084. ** to the standard form of "X <op> <expr>".
  104085. **
  104086. ** If the expression is of the form "X <op> Y" where both X and Y are
  104087. ** columns, then the original expression is unchanged and a new virtual
  104088. ** term of the form "Y <op> X" is added to the WHERE clause and
  104089. ** analyzed separately. The original term is marked with TERM_COPIED
  104090. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  104091. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  104092. ** is a commuted copy of a prior term.) The original term has nChild=1
  104093. ** and the copy has idxParent set to the index of the original term.
  104094. */
  104095. static void exprAnalyze(
  104096. SrcList *pSrc, /* the FROM clause */
  104097. WhereClause *pWC, /* the WHERE clause */
  104098. int idxTerm /* Index of the term to be analyzed */
  104099. ){
  104100. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  104101. WhereTerm *pTerm; /* The term to be analyzed */
  104102. WhereMaskSet *pMaskSet; /* Set of table index masks */
  104103. Expr *pExpr; /* The expression to be analyzed */
  104104. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  104105. Bitmask prereqAll; /* Prerequesites of pExpr */
  104106. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  104107. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  104108. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  104109. int noCase = 0; /* LIKE/GLOB distinguishes case */
  104110. int op; /* Top-level operator. pExpr->op */
  104111. Parse *pParse = pWInfo->pParse; /* Parsing context */
  104112. sqlite3 *db = pParse->db; /* Database connection */
  104113. if( db->mallocFailed ){
  104114. return;
  104115. }
  104116. pTerm = &pWC->a[idxTerm];
  104117. pMaskSet = &pWInfo->sMaskSet;
  104118. pExpr = pTerm->pExpr;
  104119. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  104120. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  104121. op = pExpr->op;
  104122. if( op==TK_IN ){
  104123. assert( pExpr->pRight==0 );
  104124. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  104125. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  104126. }else{
  104127. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  104128. }
  104129. }else if( op==TK_ISNULL ){
  104130. pTerm->prereqRight = 0;
  104131. }else{
  104132. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  104133. }
  104134. prereqAll = exprTableUsage(pMaskSet, pExpr);
  104135. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  104136. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  104137. prereqAll |= x;
  104138. extraRight = x-1; /* ON clause terms may not be used with an index
  104139. ** on left table of a LEFT JOIN. Ticket #3015 */
  104140. }
  104141. pTerm->prereqAll = prereqAll;
  104142. pTerm->leftCursor = -1;
  104143. pTerm->iParent = -1;
  104144. pTerm->eOperator = 0;
  104145. if( allowedOp(op) ){
  104146. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  104147. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  104148. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  104149. if( pLeft->op==TK_COLUMN ){
  104150. pTerm->leftCursor = pLeft->iTable;
  104151. pTerm->u.leftColumn = pLeft->iColumn;
  104152. pTerm->eOperator = operatorMask(op) & opMask;
  104153. }
  104154. if( pRight && pRight->op==TK_COLUMN ){
  104155. WhereTerm *pNew;
  104156. Expr *pDup;
  104157. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  104158. if( pTerm->leftCursor>=0 ){
  104159. int idxNew;
  104160. pDup = sqlite3ExprDup(db, pExpr, 0);
  104161. if( db->mallocFailed ){
  104162. sqlite3ExprDelete(db, pDup);
  104163. return;
  104164. }
  104165. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  104166. if( idxNew==0 ) return;
  104167. pNew = &pWC->a[idxNew];
  104168. pNew->iParent = idxTerm;
  104169. pTerm = &pWC->a[idxTerm];
  104170. pTerm->nChild = 1;
  104171. pTerm->wtFlags |= TERM_COPIED;
  104172. if( pExpr->op==TK_EQ
  104173. && !ExprHasProperty(pExpr, EP_FromJoin)
  104174. && OptimizationEnabled(db, SQLITE_Transitive)
  104175. ){
  104176. pTerm->eOperator |= WO_EQUIV;
  104177. eExtraOp = WO_EQUIV;
  104178. }
  104179. }else{
  104180. pDup = pExpr;
  104181. pNew = pTerm;
  104182. }
  104183. exprCommute(pParse, pDup);
  104184. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  104185. pNew->leftCursor = pLeft->iTable;
  104186. pNew->u.leftColumn = pLeft->iColumn;
  104187. testcase( (prereqLeft | extraRight) != prereqLeft );
  104188. pNew->prereqRight = prereqLeft | extraRight;
  104189. pNew->prereqAll = prereqAll;
  104190. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  104191. }
  104192. }
  104193. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  104194. /* If a term is the BETWEEN operator, create two new virtual terms
  104195. ** that define the range that the BETWEEN implements. For example:
  104196. **
  104197. ** a BETWEEN b AND c
  104198. **
  104199. ** is converted into:
  104200. **
  104201. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  104202. **
  104203. ** The two new terms are added onto the end of the WhereClause object.
  104204. ** The new terms are "dynamic" and are children of the original BETWEEN
  104205. ** term. That means that if the BETWEEN term is coded, the children are
  104206. ** skipped. Or, if the children are satisfied by an index, the original
  104207. ** BETWEEN term is skipped.
  104208. */
  104209. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  104210. ExprList *pList = pExpr->x.pList;
  104211. int i;
  104212. static const u8 ops[] = {TK_GE, TK_LE};
  104213. assert( pList!=0 );
  104214. assert( pList->nExpr==2 );
  104215. for(i=0; i<2; i++){
  104216. Expr *pNewExpr;
  104217. int idxNew;
  104218. pNewExpr = sqlite3PExpr(pParse, ops[i],
  104219. sqlite3ExprDup(db, pExpr->pLeft, 0),
  104220. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  104221. transferJoinMarkings(pNewExpr, pExpr);
  104222. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  104223. testcase( idxNew==0 );
  104224. exprAnalyze(pSrc, pWC, idxNew);
  104225. pTerm = &pWC->a[idxTerm];
  104226. pWC->a[idxNew].iParent = idxTerm;
  104227. }
  104228. pTerm->nChild = 2;
  104229. }
  104230. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  104231. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  104232. /* Analyze a term that is composed of two or more subterms connected by
  104233. ** an OR operator.
  104234. */
  104235. else if( pExpr->op==TK_OR ){
  104236. assert( pWC->op==TK_AND );
  104237. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  104238. pTerm = &pWC->a[idxTerm];
  104239. }
  104240. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  104241. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  104242. /* Add constraints to reduce the search space on a LIKE or GLOB
  104243. ** operator.
  104244. **
  104245. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  104246. **
  104247. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  104248. **
  104249. ** The last character of the prefix "abc" is incremented to form the
  104250. ** termination condition "abd".
  104251. */
  104252. if( pWC->op==TK_AND
  104253. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  104254. ){
  104255. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  104256. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  104257. Expr *pNewExpr1;
  104258. Expr *pNewExpr2;
  104259. int idxNew1;
  104260. int idxNew2;
  104261. Token sCollSeqName; /* Name of collating sequence */
  104262. pLeft = pExpr->x.pList->a[1].pExpr;
  104263. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  104264. if( !db->mallocFailed ){
  104265. u8 c, *pC; /* Last character before the first wildcard */
  104266. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  104267. c = *pC;
  104268. if( noCase ){
  104269. /* The point is to increment the last character before the first
  104270. ** wildcard. But if we increment '@', that will push it into the
  104271. ** alphabetic range where case conversions will mess up the
  104272. ** inequality. To avoid this, make sure to also run the full
  104273. ** LIKE on all candidate expressions by clearing the isComplete flag
  104274. */
  104275. if( c=='A'-1 ) isComplete = 0;
  104276. c = sqlite3UpperToLower[c];
  104277. }
  104278. *pC = c + 1;
  104279. }
  104280. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  104281. sCollSeqName.n = 6;
  104282. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  104283. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  104284. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  104285. pStr1, 0);
  104286. transferJoinMarkings(pNewExpr1, pExpr);
  104287. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  104288. testcase( idxNew1==0 );
  104289. exprAnalyze(pSrc, pWC, idxNew1);
  104290. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  104291. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  104292. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  104293. pStr2, 0);
  104294. transferJoinMarkings(pNewExpr2, pExpr);
  104295. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  104296. testcase( idxNew2==0 );
  104297. exprAnalyze(pSrc, pWC, idxNew2);
  104298. pTerm = &pWC->a[idxTerm];
  104299. if( isComplete ){
  104300. pWC->a[idxNew1].iParent = idxTerm;
  104301. pWC->a[idxNew2].iParent = idxTerm;
  104302. pTerm->nChild = 2;
  104303. }
  104304. }
  104305. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  104306. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104307. /* Add a WO_MATCH auxiliary term to the constraint set if the
  104308. ** current expression is of the form: column MATCH expr.
  104309. ** This information is used by the xBestIndex methods of
  104310. ** virtual tables. The native query optimizer does not attempt
  104311. ** to do anything with MATCH functions.
  104312. */
  104313. if( isMatchOfColumn(pExpr) ){
  104314. int idxNew;
  104315. Expr *pRight, *pLeft;
  104316. WhereTerm *pNewTerm;
  104317. Bitmask prereqColumn, prereqExpr;
  104318. pRight = pExpr->x.pList->a[0].pExpr;
  104319. pLeft = pExpr->x.pList->a[1].pExpr;
  104320. prereqExpr = exprTableUsage(pMaskSet, pRight);
  104321. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  104322. if( (prereqExpr & prereqColumn)==0 ){
  104323. Expr *pNewExpr;
  104324. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  104325. 0, sqlite3ExprDup(db, pRight, 0), 0);
  104326. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  104327. testcase( idxNew==0 );
  104328. pNewTerm = &pWC->a[idxNew];
  104329. pNewTerm->prereqRight = prereqExpr;
  104330. pNewTerm->leftCursor = pLeft->iTable;
  104331. pNewTerm->u.leftColumn = pLeft->iColumn;
  104332. pNewTerm->eOperator = WO_MATCH;
  104333. pNewTerm->iParent = idxTerm;
  104334. pTerm = &pWC->a[idxTerm];
  104335. pTerm->nChild = 1;
  104336. pTerm->wtFlags |= TERM_COPIED;
  104337. pNewTerm->prereqAll = pTerm->prereqAll;
  104338. }
  104339. }
  104340. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104341. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104342. /* When sqlite_stat3 histogram data is available an operator of the
  104343. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  104344. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  104345. ** virtual term of that form.
  104346. **
  104347. ** Note that the virtual term must be tagged with TERM_VNULL. This
  104348. ** TERM_VNULL tag will suppress the not-null check at the beginning
  104349. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  104350. ** the start of the loop will prevent any results from being returned.
  104351. */
  104352. if( pExpr->op==TK_NOTNULL
  104353. && pExpr->pLeft->op==TK_COLUMN
  104354. && pExpr->pLeft->iColumn>=0
  104355. && OptimizationEnabled(db, SQLITE_Stat3)
  104356. ){
  104357. Expr *pNewExpr;
  104358. Expr *pLeft = pExpr->pLeft;
  104359. int idxNew;
  104360. WhereTerm *pNewTerm;
  104361. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  104362. sqlite3ExprDup(db, pLeft, 0),
  104363. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  104364. idxNew = whereClauseInsert(pWC, pNewExpr,
  104365. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  104366. if( idxNew ){
  104367. pNewTerm = &pWC->a[idxNew];
  104368. pNewTerm->prereqRight = 0;
  104369. pNewTerm->leftCursor = pLeft->iTable;
  104370. pNewTerm->u.leftColumn = pLeft->iColumn;
  104371. pNewTerm->eOperator = WO_GT;
  104372. pNewTerm->iParent = idxTerm;
  104373. pTerm = &pWC->a[idxTerm];
  104374. pTerm->nChild = 1;
  104375. pTerm->wtFlags |= TERM_COPIED;
  104376. pNewTerm->prereqAll = pTerm->prereqAll;
  104377. }
  104378. }
  104379. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  104380. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  104381. ** an index for tables to the left of the join.
  104382. */
  104383. pTerm->prereqRight |= extraRight;
  104384. }
  104385. /*
  104386. ** This function searches pList for a entry that matches the iCol-th column
  104387. ** of index pIdx.
  104388. **
  104389. ** If such an expression is found, its index in pList->a[] is returned. If
  104390. ** no expression is found, -1 is returned.
  104391. */
  104392. static int findIndexCol(
  104393. Parse *pParse, /* Parse context */
  104394. ExprList *pList, /* Expression list to search */
  104395. int iBase, /* Cursor for table associated with pIdx */
  104396. Index *pIdx, /* Index to match column of */
  104397. int iCol /* Column of index to match */
  104398. ){
  104399. int i;
  104400. const char *zColl = pIdx->azColl[iCol];
  104401. for(i=0; i<pList->nExpr; i++){
  104402. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  104403. if( p->op==TK_COLUMN
  104404. && p->iColumn==pIdx->aiColumn[iCol]
  104405. && p->iTable==iBase
  104406. ){
  104407. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  104408. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  104409. return i;
  104410. }
  104411. }
  104412. }
  104413. return -1;
  104414. }
  104415. /*
  104416. ** Return true if the DISTINCT expression-list passed as the third argument
  104417. ** is redundant.
  104418. **
  104419. ** A DISTINCT list is redundant if the database contains some subset of
  104420. ** columns that are unique and non-null.
  104421. */
  104422. static int isDistinctRedundant(
  104423. Parse *pParse, /* Parsing context */
  104424. SrcList *pTabList, /* The FROM clause */
  104425. WhereClause *pWC, /* The WHERE clause */
  104426. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  104427. ){
  104428. Table *pTab;
  104429. Index *pIdx;
  104430. int i;
  104431. int iBase;
  104432. /* If there is more than one table or sub-select in the FROM clause of
  104433. ** this query, then it will not be possible to show that the DISTINCT
  104434. ** clause is redundant. */
  104435. if( pTabList->nSrc!=1 ) return 0;
  104436. iBase = pTabList->a[0].iCursor;
  104437. pTab = pTabList->a[0].pTab;
  104438. /* If any of the expressions is an IPK column on table iBase, then return
  104439. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  104440. ** current SELECT is a correlated sub-query.
  104441. */
  104442. for(i=0; i<pDistinct->nExpr; i++){
  104443. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  104444. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  104445. }
  104446. /* Loop through all indices on the table, checking each to see if it makes
  104447. ** the DISTINCT qualifier redundant. It does so if:
  104448. **
  104449. ** 1. The index is itself UNIQUE, and
  104450. **
  104451. ** 2. All of the columns in the index are either part of the pDistinct
  104452. ** list, or else the WHERE clause contains a term of the form "col=X",
  104453. ** where X is a constant value. The collation sequences of the
  104454. ** comparison and select-list expressions must match those of the index.
  104455. **
  104456. ** 3. All of those index columns for which the WHERE clause does not
  104457. ** contain a "col=X" term are subject to a NOT NULL constraint.
  104458. */
  104459. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104460. if( pIdx->onError==OE_None ) continue;
  104461. for(i=0; i<pIdx->nColumn; i++){
  104462. int iCol = pIdx->aiColumn[i];
  104463. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  104464. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  104465. if( iIdxCol<0 || pTab->aCol[pIdx->aiColumn[i]].notNull==0 ){
  104466. break;
  104467. }
  104468. }
  104469. }
  104470. if( i==pIdx->nColumn ){
  104471. /* This index implies that the DISTINCT qualifier is redundant. */
  104472. return 1;
  104473. }
  104474. }
  104475. return 0;
  104476. }
  104477. /*
  104478. ** Estimate the logarithm of the input value to base 2.
  104479. */
  104480. static LogEst estLog(LogEst N){
  104481. LogEst x = sqlite3LogEst(N);
  104482. return x>33 ? x - 33 : 0;
  104483. }
  104484. /*
  104485. ** Two routines for printing the content of an sqlite3_index_info
  104486. ** structure. Used for testing and debugging only. If neither
  104487. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  104488. ** are no-ops.
  104489. */
  104490. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  104491. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  104492. int i;
  104493. if( !sqlite3WhereTrace ) return;
  104494. for(i=0; i<p->nConstraint; i++){
  104495. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  104496. i,
  104497. p->aConstraint[i].iColumn,
  104498. p->aConstraint[i].iTermOffset,
  104499. p->aConstraint[i].op,
  104500. p->aConstraint[i].usable);
  104501. }
  104502. for(i=0; i<p->nOrderBy; i++){
  104503. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  104504. i,
  104505. p->aOrderBy[i].iColumn,
  104506. p->aOrderBy[i].desc);
  104507. }
  104508. }
  104509. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  104510. int i;
  104511. if( !sqlite3WhereTrace ) return;
  104512. for(i=0; i<p->nConstraint; i++){
  104513. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  104514. i,
  104515. p->aConstraintUsage[i].argvIndex,
  104516. p->aConstraintUsage[i].omit);
  104517. }
  104518. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  104519. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  104520. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  104521. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  104522. }
  104523. #else
  104524. #define TRACE_IDX_INPUTS(A)
  104525. #define TRACE_IDX_OUTPUTS(A)
  104526. #endif
  104527. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  104528. /*
  104529. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  104530. ** could be used with an index to access pSrc, assuming an appropriate
  104531. ** index existed.
  104532. */
  104533. static int termCanDriveIndex(
  104534. WhereTerm *pTerm, /* WHERE clause term to check */
  104535. struct SrcList_item *pSrc, /* Table we are trying to access */
  104536. Bitmask notReady /* Tables in outer loops of the join */
  104537. ){
  104538. char aff;
  104539. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  104540. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  104541. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  104542. if( pTerm->u.leftColumn<0 ) return 0;
  104543. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  104544. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  104545. return 1;
  104546. }
  104547. #endif
  104548. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  104549. /*
  104550. ** Generate code to construct the Index object for an automatic index
  104551. ** and to set up the WhereLevel object pLevel so that the code generator
  104552. ** makes use of the automatic index.
  104553. */
  104554. static void constructAutomaticIndex(
  104555. Parse *pParse, /* The parsing context */
  104556. WhereClause *pWC, /* The WHERE clause */
  104557. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  104558. Bitmask notReady, /* Mask of cursors that are not available */
  104559. WhereLevel *pLevel /* Write new index here */
  104560. ){
  104561. int nColumn; /* Number of columns in the constructed index */
  104562. WhereTerm *pTerm; /* A single term of the WHERE clause */
  104563. WhereTerm *pWCEnd; /* End of pWC->a[] */
  104564. int nByte; /* Byte of memory needed for pIdx */
  104565. Index *pIdx; /* Object describing the transient index */
  104566. Vdbe *v; /* Prepared statement under construction */
  104567. int addrInit; /* Address of the initialization bypass jump */
  104568. Table *pTable; /* The table being indexed */
  104569. KeyInfo *pKeyinfo; /* Key information for the index */
  104570. int addrTop; /* Top of the index fill loop */
  104571. int regRecord; /* Register holding an index record */
  104572. int n; /* Column counter */
  104573. int i; /* Loop counter */
  104574. int mxBitCol; /* Maximum column in pSrc->colUsed */
  104575. CollSeq *pColl; /* Collating sequence to on a column */
  104576. WhereLoop *pLoop; /* The Loop object */
  104577. Bitmask idxCols; /* Bitmap of columns used for indexing */
  104578. Bitmask extraCols; /* Bitmap of additional columns */
  104579. u8 sentWarning = 0; /* True if a warnning has been issued */
  104580. /* Generate code to skip over the creation and initialization of the
  104581. ** transient index on 2nd and subsequent iterations of the loop. */
  104582. v = pParse->pVdbe;
  104583. assert( v!=0 );
  104584. addrInit = sqlite3CodeOnce(pParse);
  104585. /* Count the number of columns that will be added to the index
  104586. ** and used to match WHERE clause constraints */
  104587. nColumn = 0;
  104588. pTable = pSrc->pTab;
  104589. pWCEnd = &pWC->a[pWC->nTerm];
  104590. pLoop = pLevel->pWLoop;
  104591. idxCols = 0;
  104592. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  104593. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  104594. int iCol = pTerm->u.leftColumn;
  104595. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  104596. testcase( iCol==BMS );
  104597. testcase( iCol==BMS-1 );
  104598. if( !sentWarning ){
  104599. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  104600. "automatic index on %s(%s)", pTable->zName,
  104601. pTable->aCol[iCol].zName);
  104602. sentWarning = 1;
  104603. }
  104604. if( (idxCols & cMask)==0 ){
  104605. if( whereLoopResize(pParse->db, pLoop, nColumn+1) ) return;
  104606. pLoop->aLTerm[nColumn++] = pTerm;
  104607. idxCols |= cMask;
  104608. }
  104609. }
  104610. }
  104611. assert( nColumn>0 );
  104612. pLoop->u.btree.nEq = pLoop->nLTerm = nColumn;
  104613. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  104614. | WHERE_AUTO_INDEX;
  104615. /* Count the number of additional columns needed to create a
  104616. ** covering index. A "covering index" is an index that contains all
  104617. ** columns that are needed by the query. With a covering index, the
  104618. ** original table never needs to be accessed. Automatic indices must
  104619. ** be a covering index because the index will not be updated if the
  104620. ** original table changes and the index and table cannot both be used
  104621. ** if they go out of sync.
  104622. */
  104623. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  104624. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  104625. testcase( pTable->nCol==BMS-1 );
  104626. testcase( pTable->nCol==BMS-2 );
  104627. for(i=0; i<mxBitCol; i++){
  104628. if( extraCols & MASKBIT(i) ) nColumn++;
  104629. }
  104630. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  104631. nColumn += pTable->nCol - BMS + 1;
  104632. }
  104633. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  104634. /* Construct the Index object to describe this index */
  104635. nByte = sizeof(Index);
  104636. nByte += nColumn*sizeof(int); /* Index.aiColumn */
  104637. nByte += nColumn*sizeof(char*); /* Index.azColl */
  104638. nByte += nColumn; /* Index.aSortOrder */
  104639. pIdx = sqlite3DbMallocZero(pParse->db, nByte);
  104640. if( pIdx==0 ) return;
  104641. pLoop->u.btree.pIndex = pIdx;
  104642. pIdx->azColl = (char**)&pIdx[1];
  104643. pIdx->aiColumn = (int*)&pIdx->azColl[nColumn];
  104644. pIdx->aSortOrder = (u8*)&pIdx->aiColumn[nColumn];
  104645. pIdx->zName = "auto-index";
  104646. pIdx->nColumn = nColumn;
  104647. pIdx->pTable = pTable;
  104648. n = 0;
  104649. idxCols = 0;
  104650. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  104651. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  104652. int iCol = pTerm->u.leftColumn;
  104653. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  104654. testcase( iCol==BMS-1 );
  104655. testcase( iCol==BMS );
  104656. if( (idxCols & cMask)==0 ){
  104657. Expr *pX = pTerm->pExpr;
  104658. idxCols |= cMask;
  104659. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  104660. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  104661. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  104662. n++;
  104663. }
  104664. }
  104665. }
  104666. assert( (u32)n==pLoop->u.btree.nEq );
  104667. /* Add additional columns needed to make the automatic index into
  104668. ** a covering index */
  104669. for(i=0; i<mxBitCol; i++){
  104670. if( extraCols & MASKBIT(i) ){
  104671. pIdx->aiColumn[n] = i;
  104672. pIdx->azColl[n] = "BINARY";
  104673. n++;
  104674. }
  104675. }
  104676. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  104677. for(i=BMS-1; i<pTable->nCol; i++){
  104678. pIdx->aiColumn[n] = i;
  104679. pIdx->azColl[n] = "BINARY";
  104680. n++;
  104681. }
  104682. }
  104683. assert( n==nColumn );
  104684. /* Create the automatic index */
  104685. pKeyinfo = sqlite3IndexKeyinfo(pParse, pIdx);
  104686. assert( pLevel->iIdxCur>=0 );
  104687. pLevel->iIdxCur = pParse->nTab++;
  104688. sqlite3VdbeAddOp4(v, OP_OpenAutoindex, pLevel->iIdxCur, nColumn+1, 0,
  104689. (char*)pKeyinfo, P4_KEYINFO_HANDOFF);
  104690. VdbeComment((v, "for %s", pTable->zName));
  104691. /* Fill the automatic index with content */
  104692. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
  104693. regRecord = sqlite3GetTempReg(pParse);
  104694. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 1, 0);
  104695. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  104696. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  104697. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
  104698. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  104699. sqlite3VdbeJumpHere(v, addrTop);
  104700. sqlite3ReleaseTempReg(pParse, regRecord);
  104701. /* Jump here when skipping the initialization */
  104702. sqlite3VdbeJumpHere(v, addrInit);
  104703. }
  104704. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  104705. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104706. /*
  104707. ** Allocate and populate an sqlite3_index_info structure. It is the
  104708. ** responsibility of the caller to eventually release the structure
  104709. ** by passing the pointer returned by this function to sqlite3_free().
  104710. */
  104711. static sqlite3_index_info *allocateIndexInfo(
  104712. Parse *pParse,
  104713. WhereClause *pWC,
  104714. struct SrcList_item *pSrc,
  104715. ExprList *pOrderBy
  104716. ){
  104717. int i, j;
  104718. int nTerm;
  104719. struct sqlite3_index_constraint *pIdxCons;
  104720. struct sqlite3_index_orderby *pIdxOrderBy;
  104721. struct sqlite3_index_constraint_usage *pUsage;
  104722. WhereTerm *pTerm;
  104723. int nOrderBy;
  104724. sqlite3_index_info *pIdxInfo;
  104725. /* Count the number of possible WHERE clause constraints referring
  104726. ** to this virtual table */
  104727. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  104728. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  104729. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  104730. testcase( pTerm->eOperator & WO_IN );
  104731. testcase( pTerm->eOperator & WO_ISNULL );
  104732. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  104733. if( pTerm->wtFlags & TERM_VNULL ) continue;
  104734. nTerm++;
  104735. }
  104736. /* If the ORDER BY clause contains only columns in the current
  104737. ** virtual table then allocate space for the aOrderBy part of
  104738. ** the sqlite3_index_info structure.
  104739. */
  104740. nOrderBy = 0;
  104741. if( pOrderBy ){
  104742. int n = pOrderBy->nExpr;
  104743. for(i=0; i<n; i++){
  104744. Expr *pExpr = pOrderBy->a[i].pExpr;
  104745. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  104746. }
  104747. if( i==n){
  104748. nOrderBy = n;
  104749. }
  104750. }
  104751. /* Allocate the sqlite3_index_info structure
  104752. */
  104753. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  104754. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  104755. + sizeof(*pIdxOrderBy)*nOrderBy );
  104756. if( pIdxInfo==0 ){
  104757. sqlite3ErrorMsg(pParse, "out of memory");
  104758. return 0;
  104759. }
  104760. /* Initialize the structure. The sqlite3_index_info structure contains
  104761. ** many fields that are declared "const" to prevent xBestIndex from
  104762. ** changing them. We have to do some funky casting in order to
  104763. ** initialize those fields.
  104764. */
  104765. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  104766. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  104767. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  104768. *(int*)&pIdxInfo->nConstraint = nTerm;
  104769. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  104770. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  104771. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  104772. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  104773. pUsage;
  104774. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  104775. u8 op;
  104776. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  104777. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  104778. testcase( pTerm->eOperator & WO_IN );
  104779. testcase( pTerm->eOperator & WO_ISNULL );
  104780. if( pTerm->eOperator & (WO_ISNULL) ) continue;
  104781. if( pTerm->wtFlags & TERM_VNULL ) continue;
  104782. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  104783. pIdxCons[j].iTermOffset = i;
  104784. op = (u8)pTerm->eOperator & WO_ALL;
  104785. if( op==WO_IN ) op = WO_EQ;
  104786. pIdxCons[j].op = op;
  104787. /* The direct assignment in the previous line is possible only because
  104788. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  104789. ** following asserts verify this fact. */
  104790. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  104791. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  104792. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  104793. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  104794. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  104795. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  104796. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  104797. j++;
  104798. }
  104799. for(i=0; i<nOrderBy; i++){
  104800. Expr *pExpr = pOrderBy->a[i].pExpr;
  104801. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  104802. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  104803. }
  104804. return pIdxInfo;
  104805. }
  104806. /*
  104807. ** The table object reference passed as the second argument to this function
  104808. ** must represent a virtual table. This function invokes the xBestIndex()
  104809. ** method of the virtual table with the sqlite3_index_info object that
  104810. ** comes in as the 3rd argument to this function.
  104811. **
  104812. ** If an error occurs, pParse is populated with an error message and a
  104813. ** non-zero value is returned. Otherwise, 0 is returned and the output
  104814. ** part of the sqlite3_index_info structure is left populated.
  104815. **
  104816. ** Whether or not an error is returned, it is the responsibility of the
  104817. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  104818. ** that this is required.
  104819. */
  104820. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  104821. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  104822. int i;
  104823. int rc;
  104824. TRACE_IDX_INPUTS(p);
  104825. rc = pVtab->pModule->xBestIndex(pVtab, p);
  104826. TRACE_IDX_OUTPUTS(p);
  104827. if( rc!=SQLITE_OK ){
  104828. if( rc==SQLITE_NOMEM ){
  104829. pParse->db->mallocFailed = 1;
  104830. }else if( !pVtab->zErrMsg ){
  104831. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  104832. }else{
  104833. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  104834. }
  104835. }
  104836. sqlite3_free(pVtab->zErrMsg);
  104837. pVtab->zErrMsg = 0;
  104838. for(i=0; i<p->nConstraint; i++){
  104839. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  104840. sqlite3ErrorMsg(pParse,
  104841. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  104842. }
  104843. }
  104844. return pParse->nErr;
  104845. }
  104846. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  104847. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104848. /*
  104849. ** Estimate the location of a particular key among all keys in an
  104850. ** index. Store the results in aStat as follows:
  104851. **
  104852. ** aStat[0] Est. number of rows less than pVal
  104853. ** aStat[1] Est. number of rows equal to pVal
  104854. **
  104855. ** Return SQLITE_OK on success.
  104856. */
  104857. static void whereKeyStats(
  104858. Parse *pParse, /* Database connection */
  104859. Index *pIdx, /* Index to consider domain of */
  104860. UnpackedRecord *pRec, /* Vector of values to consider */
  104861. int roundUp, /* Round up if true. Round down if false */
  104862. tRowcnt *aStat /* OUT: stats written here */
  104863. ){
  104864. IndexSample *aSample = pIdx->aSample;
  104865. int iCol; /* Index of required stats in anEq[] etc. */
  104866. int iMin = 0; /* Smallest sample not yet tested */
  104867. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  104868. int iTest; /* Next sample to test */
  104869. int res; /* Result of comparison operation */
  104870. #ifndef SQLITE_DEBUG
  104871. UNUSED_PARAMETER( pParse );
  104872. #endif
  104873. assert( pRec!=0 || pParse->db->mallocFailed );
  104874. if( pRec==0 ) return;
  104875. iCol = pRec->nField - 1;
  104876. assert( pIdx->nSample>0 );
  104877. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  104878. do{
  104879. iTest = (iMin+i)/2;
  104880. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  104881. if( res<0 ){
  104882. iMin = iTest+1;
  104883. }else{
  104884. i = iTest;
  104885. }
  104886. }while( res && iMin<i );
  104887. #ifdef SQLITE_DEBUG
  104888. /* The following assert statements check that the binary search code
  104889. ** above found the right answer. This block serves no purpose other
  104890. ** than to invoke the asserts. */
  104891. if( res==0 ){
  104892. /* If (res==0) is true, then sample $i must be equal to pRec */
  104893. assert( i<pIdx->nSample );
  104894. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  104895. || pParse->db->mallocFailed );
  104896. }else{
  104897. /* Otherwise, pRec must be smaller than sample $i and larger than
  104898. ** sample ($i-1). */
  104899. assert( i==pIdx->nSample
  104900. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  104901. || pParse->db->mallocFailed );
  104902. assert( i==0
  104903. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  104904. || pParse->db->mallocFailed );
  104905. }
  104906. #endif /* ifdef SQLITE_DEBUG */
  104907. /* At this point, aSample[i] is the first sample that is greater than
  104908. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  104909. ** than pVal. If aSample[i]==pVal, then res==0.
  104910. */
  104911. if( res==0 ){
  104912. aStat[0] = aSample[i].anLt[iCol];
  104913. aStat[1] = aSample[i].anEq[iCol];
  104914. }else{
  104915. tRowcnt iLower, iUpper, iGap;
  104916. if( i==0 ){
  104917. iLower = 0;
  104918. iUpper = aSample[0].anLt[iCol];
  104919. }else{
  104920. iUpper = i>=pIdx->nSample ? pIdx->aiRowEst[0] : aSample[i].anLt[iCol];
  104921. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  104922. }
  104923. aStat[1] = (pIdx->nColumn>iCol ? pIdx->aAvgEq[iCol] : 1);
  104924. if( iLower>=iUpper ){
  104925. iGap = 0;
  104926. }else{
  104927. iGap = iUpper - iLower;
  104928. }
  104929. if( roundUp ){
  104930. iGap = (iGap*2)/3;
  104931. }else{
  104932. iGap = iGap/3;
  104933. }
  104934. aStat[0] = iLower + iGap;
  104935. }
  104936. }
  104937. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  104938. /*
  104939. ** This function is used to estimate the number of rows that will be visited
  104940. ** by scanning an index for a range of values. The range may have an upper
  104941. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  104942. ** and lower bounds are represented by pLower and pUpper respectively. For
  104943. ** example, assuming that index p is on t1(a):
  104944. **
  104945. ** ... FROM t1 WHERE a > ? AND a < ? ...
  104946. ** |_____| |_____|
  104947. ** | |
  104948. ** pLower pUpper
  104949. **
  104950. ** If either of the upper or lower bound is not present, then NULL is passed in
  104951. ** place of the corresponding WhereTerm.
  104952. **
  104953. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  104954. ** column subject to the range constraint. Or, equivalently, the number of
  104955. ** equality constraints optimized by the proposed index scan. For example,
  104956. ** assuming index p is on t1(a, b), and the SQL query is:
  104957. **
  104958. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  104959. **
  104960. ** then nEq is set to 1 (as the range restricted column, b, is the second
  104961. ** left-most column of the index). Or, if the query is:
  104962. **
  104963. ** ... FROM t1 WHERE a > ? AND a < ? ...
  104964. **
  104965. ** then nEq is set to 0.
  104966. **
  104967. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  104968. ** number of rows that the index scan is expected to visit without
  104969. ** considering the range constraints. If nEq is 0, this is the number of
  104970. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  104971. ** to account for the range contraints pLower and pUpper.
  104972. **
  104973. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  104974. ** used, each range inequality reduces the search space by a factor of 4.
  104975. ** Hence a pair of constraints (x>? AND x<?) reduces the expected number of
  104976. ** rows visited by a factor of 16.
  104977. */
  104978. static int whereRangeScanEst(
  104979. Parse *pParse, /* Parsing & code generating context */
  104980. WhereLoopBuilder *pBuilder,
  104981. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  104982. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  104983. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  104984. ){
  104985. int rc = SQLITE_OK;
  104986. int nOut = pLoop->nOut;
  104987. LogEst nNew;
  104988. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  104989. Index *p = pLoop->u.btree.pIndex;
  104990. int nEq = pLoop->u.btree.nEq;
  104991. if( p->nSample>0
  104992. && nEq==pBuilder->nRecValid
  104993. && nEq<p->nSampleCol
  104994. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  104995. ){
  104996. UnpackedRecord *pRec = pBuilder->pRec;
  104997. tRowcnt a[2];
  104998. u8 aff;
  104999. /* Variable iLower will be set to the estimate of the number of rows in
  105000. ** the index that are less than the lower bound of the range query. The
  105001. ** lower bound being the concatenation of $P and $L, where $P is the
  105002. ** key-prefix formed by the nEq values matched against the nEq left-most
  105003. ** columns of the index, and $L is the value in pLower.
  105004. **
  105005. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  105006. ** is not a simple variable or literal value), the lower bound of the
  105007. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  105008. ** if $L is available, whereKeyStats() is called for both ($P) and
  105009. ** ($P:$L) and the larger of the two returned values used.
  105010. **
  105011. ** Similarly, iUpper is to be set to the estimate of the number of rows
  105012. ** less than the upper bound of the range query. Where the upper bound
  105013. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  105014. ** of iUpper are requested of whereKeyStats() and the smaller used.
  105015. */
  105016. tRowcnt iLower;
  105017. tRowcnt iUpper;
  105018. if( nEq==p->nColumn ){
  105019. aff = SQLITE_AFF_INTEGER;
  105020. }else{
  105021. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  105022. }
  105023. /* Determine iLower and iUpper using ($P) only. */
  105024. if( nEq==0 ){
  105025. iLower = 0;
  105026. iUpper = p->aiRowEst[0];
  105027. }else{
  105028. /* Note: this call could be optimized away - since the same values must
  105029. ** have been requested when testing key $P in whereEqualScanEst(). */
  105030. whereKeyStats(pParse, p, pRec, 0, a);
  105031. iLower = a[0];
  105032. iUpper = a[0] + a[1];
  105033. }
  105034. /* If possible, improve on the iLower estimate using ($P:$L). */
  105035. if( pLower ){
  105036. int bOk; /* True if value is extracted from pExpr */
  105037. Expr *pExpr = pLower->pExpr->pRight;
  105038. assert( (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  105039. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  105040. if( rc==SQLITE_OK && bOk ){
  105041. tRowcnt iNew;
  105042. whereKeyStats(pParse, p, pRec, 0, a);
  105043. iNew = a[0] + ((pLower->eOperator & WO_GT) ? a[1] : 0);
  105044. if( iNew>iLower ) iLower = iNew;
  105045. nOut--;
  105046. }
  105047. }
  105048. /* If possible, improve on the iUpper estimate using ($P:$U). */
  105049. if( pUpper ){
  105050. int bOk; /* True if value is extracted from pExpr */
  105051. Expr *pExpr = pUpper->pExpr->pRight;
  105052. assert( (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  105053. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  105054. if( rc==SQLITE_OK && bOk ){
  105055. tRowcnt iNew;
  105056. whereKeyStats(pParse, p, pRec, 1, a);
  105057. iNew = a[0] + ((pUpper->eOperator & WO_LE) ? a[1] : 0);
  105058. if( iNew<iUpper ) iUpper = iNew;
  105059. nOut--;
  105060. }
  105061. }
  105062. pBuilder->pRec = pRec;
  105063. if( rc==SQLITE_OK ){
  105064. if( iUpper>iLower ){
  105065. nNew = sqlite3LogEst(iUpper - iLower);
  105066. }else{
  105067. nNew = 10; assert( 10==sqlite3LogEst(2) );
  105068. }
  105069. if( nNew<nOut ){
  105070. nOut = nNew;
  105071. }
  105072. pLoop->nOut = (LogEst)nOut;
  105073. WHERETRACE(0x100, ("range scan regions: %u..%u est=%d\n",
  105074. (u32)iLower, (u32)iUpper, nOut));
  105075. return SQLITE_OK;
  105076. }
  105077. }
  105078. #else
  105079. UNUSED_PARAMETER(pParse);
  105080. UNUSED_PARAMETER(pBuilder);
  105081. #endif
  105082. assert( pLower || pUpper );
  105083. /* TUNING: Each inequality constraint reduces the search space 4-fold.
  105084. ** A BETWEEN operator, therefore, reduces the search space 16-fold */
  105085. nNew = nOut;
  105086. if( pLower && (pLower->wtFlags & TERM_VNULL)==0 ){
  105087. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  105088. nOut--;
  105089. }
  105090. if( pUpper ){
  105091. nNew -= 20; assert( 20==sqlite3LogEst(4) );
  105092. nOut--;
  105093. }
  105094. if( nNew<10 ) nNew = 10;
  105095. if( nNew<nOut ) nOut = nNew;
  105096. pLoop->nOut = (LogEst)nOut;
  105097. return rc;
  105098. }
  105099. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  105100. /*
  105101. ** Estimate the number of rows that will be returned based on
  105102. ** an equality constraint x=VALUE and where that VALUE occurs in
  105103. ** the histogram data. This only works when x is the left-most
  105104. ** column of an index and sqlite_stat3 histogram data is available
  105105. ** for that index. When pExpr==NULL that means the constraint is
  105106. ** "x IS NULL" instead of "x=VALUE".
  105107. **
  105108. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  105109. ** If unable to make an estimate, leave *pnRow unchanged and return
  105110. ** non-zero.
  105111. **
  105112. ** This routine can fail if it is unable to load a collating sequence
  105113. ** required for string comparison, or if unable to allocate memory
  105114. ** for a UTF conversion required for comparison. The error is stored
  105115. ** in the pParse structure.
  105116. */
  105117. static int whereEqualScanEst(
  105118. Parse *pParse, /* Parsing & code generating context */
  105119. WhereLoopBuilder *pBuilder,
  105120. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  105121. tRowcnt *pnRow /* Write the revised row estimate here */
  105122. ){
  105123. Index *p = pBuilder->pNew->u.btree.pIndex;
  105124. int nEq = pBuilder->pNew->u.btree.nEq;
  105125. UnpackedRecord *pRec = pBuilder->pRec;
  105126. u8 aff; /* Column affinity */
  105127. int rc; /* Subfunction return code */
  105128. tRowcnt a[2]; /* Statistics */
  105129. int bOk;
  105130. assert( nEq>=1 );
  105131. assert( nEq<=(p->nColumn+1) );
  105132. assert( p->aSample!=0 );
  105133. assert( p->nSample>0 );
  105134. assert( pBuilder->nRecValid<nEq );
  105135. /* If values are not available for all fields of the index to the left
  105136. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  105137. if( pBuilder->nRecValid<(nEq-1) ){
  105138. return SQLITE_NOTFOUND;
  105139. }
  105140. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  105141. ** below would return the same value. */
  105142. if( nEq>p->nColumn ){
  105143. *pnRow = 1;
  105144. return SQLITE_OK;
  105145. }
  105146. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  105147. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  105148. pBuilder->pRec = pRec;
  105149. if( rc!=SQLITE_OK ) return rc;
  105150. if( bOk==0 ) return SQLITE_NOTFOUND;
  105151. pBuilder->nRecValid = nEq;
  105152. whereKeyStats(pParse, p, pRec, 0, a);
  105153. WHERETRACE(0x100,("equality scan regions: %d\n", (int)a[1]));
  105154. *pnRow = a[1];
  105155. return rc;
  105156. }
  105157. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  105158. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  105159. /*
  105160. ** Estimate the number of rows that will be returned based on
  105161. ** an IN constraint where the right-hand side of the IN operator
  105162. ** is a list of values. Example:
  105163. **
  105164. ** WHERE x IN (1,2,3,4)
  105165. **
  105166. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  105167. ** If unable to make an estimate, leave *pnRow unchanged and return
  105168. ** non-zero.
  105169. **
  105170. ** This routine can fail if it is unable to load a collating sequence
  105171. ** required for string comparison, or if unable to allocate memory
  105172. ** for a UTF conversion required for comparison. The error is stored
  105173. ** in the pParse structure.
  105174. */
  105175. static int whereInScanEst(
  105176. Parse *pParse, /* Parsing & code generating context */
  105177. WhereLoopBuilder *pBuilder,
  105178. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  105179. tRowcnt *pnRow /* Write the revised row estimate here */
  105180. ){
  105181. Index *p = pBuilder->pNew->u.btree.pIndex;
  105182. int nRecValid = pBuilder->nRecValid;
  105183. int rc = SQLITE_OK; /* Subfunction return code */
  105184. tRowcnt nEst; /* Number of rows for a single term */
  105185. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  105186. int i; /* Loop counter */
  105187. assert( p->aSample!=0 );
  105188. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  105189. nEst = p->aiRowEst[0];
  105190. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  105191. nRowEst += nEst;
  105192. pBuilder->nRecValid = nRecValid;
  105193. }
  105194. if( rc==SQLITE_OK ){
  105195. if( nRowEst > p->aiRowEst[0] ) nRowEst = p->aiRowEst[0];
  105196. *pnRow = nRowEst;
  105197. WHERETRACE(0x100,("IN row estimate: est=%g\n", nRowEst));
  105198. }
  105199. assert( pBuilder->nRecValid==nRecValid );
  105200. return rc;
  105201. }
  105202. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  105203. /*
  105204. ** Disable a term in the WHERE clause. Except, do not disable the term
  105205. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  105206. ** or USING clause of that join.
  105207. **
  105208. ** Consider the term t2.z='ok' in the following queries:
  105209. **
  105210. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  105211. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  105212. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  105213. **
  105214. ** The t2.z='ok' is disabled in the in (2) because it originates
  105215. ** in the ON clause. The term is disabled in (3) because it is not part
  105216. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  105217. **
  105218. ** Disabling a term causes that term to not be tested in the inner loop
  105219. ** of the join. Disabling is an optimization. When terms are satisfied
  105220. ** by indices, we disable them to prevent redundant tests in the inner
  105221. ** loop. We would get the correct results if nothing were ever disabled,
  105222. ** but joins might run a little slower. The trick is to disable as much
  105223. ** as we can without disabling too much. If we disabled in (1), we'd get
  105224. ** the wrong answer. See ticket #813.
  105225. */
  105226. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  105227. if( pTerm
  105228. && (pTerm->wtFlags & TERM_CODED)==0
  105229. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  105230. && (pLevel->notReady & pTerm->prereqAll)==0
  105231. ){
  105232. pTerm->wtFlags |= TERM_CODED;
  105233. if( pTerm->iParent>=0 ){
  105234. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  105235. if( (--pOther->nChild)==0 ){
  105236. disableTerm(pLevel, pOther);
  105237. }
  105238. }
  105239. }
  105240. }
  105241. /*
  105242. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  105243. ** to the n registers starting at base.
  105244. **
  105245. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  105246. ** beginning and end of zAff are ignored. If all entries in zAff are
  105247. ** SQLITE_AFF_NONE, then no code gets generated.
  105248. **
  105249. ** This routine makes its own copy of zAff so that the caller is free
  105250. ** to modify zAff after this routine returns.
  105251. */
  105252. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  105253. Vdbe *v = pParse->pVdbe;
  105254. if( zAff==0 ){
  105255. assert( pParse->db->mallocFailed );
  105256. return;
  105257. }
  105258. assert( v!=0 );
  105259. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  105260. ** and end of the affinity string.
  105261. */
  105262. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  105263. n--;
  105264. base++;
  105265. zAff++;
  105266. }
  105267. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  105268. n--;
  105269. }
  105270. /* Code the OP_Affinity opcode if there is anything left to do. */
  105271. if( n>0 ){
  105272. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  105273. sqlite3VdbeChangeP4(v, -1, zAff, n);
  105274. sqlite3ExprCacheAffinityChange(pParse, base, n);
  105275. }
  105276. }
  105277. /*
  105278. ** Generate code for a single equality term of the WHERE clause. An equality
  105279. ** term can be either X=expr or X IN (...). pTerm is the term to be
  105280. ** coded.
  105281. **
  105282. ** The current value for the constraint is left in register iReg.
  105283. **
  105284. ** For a constraint of the form X=expr, the expression is evaluated and its
  105285. ** result is left on the stack. For constraints of the form X IN (...)
  105286. ** this routine sets up a loop that will iterate over all values of X.
  105287. */
  105288. static int codeEqualityTerm(
  105289. Parse *pParse, /* The parsing context */
  105290. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  105291. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  105292. int iEq, /* Index of the equality term within this level */
  105293. int bRev, /* True for reverse-order IN operations */
  105294. int iTarget /* Attempt to leave results in this register */
  105295. ){
  105296. Expr *pX = pTerm->pExpr;
  105297. Vdbe *v = pParse->pVdbe;
  105298. int iReg; /* Register holding results */
  105299. assert( iTarget>0 );
  105300. if( pX->op==TK_EQ ){
  105301. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  105302. }else if( pX->op==TK_ISNULL ){
  105303. iReg = iTarget;
  105304. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  105305. #ifndef SQLITE_OMIT_SUBQUERY
  105306. }else{
  105307. int eType;
  105308. int iTab;
  105309. struct InLoop *pIn;
  105310. WhereLoop *pLoop = pLevel->pWLoop;
  105311. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  105312. && pLoop->u.btree.pIndex!=0
  105313. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  105314. ){
  105315. testcase( iEq==0 );
  105316. testcase( bRev );
  105317. bRev = !bRev;
  105318. }
  105319. assert( pX->op==TK_IN );
  105320. iReg = iTarget;
  105321. eType = sqlite3FindInIndex(pParse, pX, 0);
  105322. if( eType==IN_INDEX_INDEX_DESC ){
  105323. testcase( bRev );
  105324. bRev = !bRev;
  105325. }
  105326. iTab = pX->iTable;
  105327. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  105328. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  105329. pLoop->wsFlags |= WHERE_IN_ABLE;
  105330. if( pLevel->u.in.nIn==0 ){
  105331. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  105332. }
  105333. pLevel->u.in.nIn++;
  105334. pLevel->u.in.aInLoop =
  105335. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  105336. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  105337. pIn = pLevel->u.in.aInLoop;
  105338. if( pIn ){
  105339. pIn += pLevel->u.in.nIn - 1;
  105340. pIn->iCur = iTab;
  105341. if( eType==IN_INDEX_ROWID ){
  105342. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  105343. }else{
  105344. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  105345. }
  105346. pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
  105347. sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
  105348. }else{
  105349. pLevel->u.in.nIn = 0;
  105350. }
  105351. #endif
  105352. }
  105353. disableTerm(pLevel, pTerm);
  105354. return iReg;
  105355. }
  105356. /*
  105357. ** Generate code that will evaluate all == and IN constraints for an
  105358. ** index.
  105359. **
  105360. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  105361. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  105362. ** The index has as many as three equality constraints, but in this
  105363. ** example, the third "c" value is an inequality. So only two
  105364. ** constraints are coded. This routine will generate code to evaluate
  105365. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  105366. ** in consecutive registers and the index of the first register is returned.
  105367. **
  105368. ** In the example above nEq==2. But this subroutine works for any value
  105369. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  105370. ** The only thing it does is allocate the pLevel->iMem memory cell and
  105371. ** compute the affinity string.
  105372. **
  105373. ** This routine always allocates at least one memory cell and returns
  105374. ** the index of that memory cell. The code that
  105375. ** calls this routine will use that memory cell to store the termination
  105376. ** key value of the loop. If one or more IN operators appear, then
  105377. ** this routine allocates an additional nEq memory cells for internal
  105378. ** use.
  105379. **
  105380. ** Before returning, *pzAff is set to point to a buffer containing a
  105381. ** copy of the column affinity string of the index allocated using
  105382. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  105383. ** with equality constraints that use NONE affinity are set to
  105384. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  105385. **
  105386. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  105387. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  105388. **
  105389. ** In the example above, the index on t1(a) has TEXT affinity. But since
  105390. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  105391. ** no conversion should be attempted before using a t2.b value as part of
  105392. ** a key to search the index. Hence the first byte in the returned affinity
  105393. ** string in this example would be set to SQLITE_AFF_NONE.
  105394. */
  105395. static int codeAllEqualityTerms(
  105396. Parse *pParse, /* Parsing context */
  105397. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  105398. int bRev, /* Reverse the order of IN operators */
  105399. int nExtraReg, /* Number of extra registers to allocate */
  105400. char **pzAff /* OUT: Set to point to affinity string */
  105401. ){
  105402. int nEq; /* The number of == or IN constraints to code */
  105403. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  105404. Index *pIdx; /* The index being used for this loop */
  105405. WhereTerm *pTerm; /* A single constraint term */
  105406. WhereLoop *pLoop; /* The WhereLoop object */
  105407. int j; /* Loop counter */
  105408. int regBase; /* Base register */
  105409. int nReg; /* Number of registers to allocate */
  105410. char *zAff; /* Affinity string to return */
  105411. /* This module is only called on query plans that use an index. */
  105412. pLoop = pLevel->pWLoop;
  105413. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  105414. nEq = pLoop->u.btree.nEq;
  105415. pIdx = pLoop->u.btree.pIndex;
  105416. assert( pIdx!=0 );
  105417. /* Figure out how many memory cells we will need then allocate them.
  105418. */
  105419. regBase = pParse->nMem + 1;
  105420. nReg = pLoop->u.btree.nEq + nExtraReg;
  105421. pParse->nMem += nReg;
  105422. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  105423. if( !zAff ){
  105424. pParse->db->mallocFailed = 1;
  105425. }
  105426. /* Evaluate the equality constraints
  105427. */
  105428. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  105429. for(j=0; j<nEq; j++){
  105430. int r1;
  105431. pTerm = pLoop->aLTerm[j];
  105432. assert( pTerm!=0 );
  105433. /* The following true for indices with redundant columns.
  105434. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  105435. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  105436. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  105437. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  105438. if( r1!=regBase+j ){
  105439. if( nReg==1 ){
  105440. sqlite3ReleaseTempReg(pParse, regBase);
  105441. regBase = r1;
  105442. }else{
  105443. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  105444. }
  105445. }
  105446. testcase( pTerm->eOperator & WO_ISNULL );
  105447. testcase( pTerm->eOperator & WO_IN );
  105448. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  105449. Expr *pRight = pTerm->pExpr->pRight;
  105450. sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
  105451. if( zAff ){
  105452. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  105453. zAff[j] = SQLITE_AFF_NONE;
  105454. }
  105455. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  105456. zAff[j] = SQLITE_AFF_NONE;
  105457. }
  105458. }
  105459. }
  105460. }
  105461. *pzAff = zAff;
  105462. return regBase;
  105463. }
  105464. #ifndef SQLITE_OMIT_EXPLAIN
  105465. /*
  105466. ** This routine is a helper for explainIndexRange() below
  105467. **
  105468. ** pStr holds the text of an expression that we are building up one term
  105469. ** at a time. This routine adds a new term to the end of the expression.
  105470. ** Terms are separated by AND so add the "AND" text for second and subsequent
  105471. ** terms only.
  105472. */
  105473. static void explainAppendTerm(
  105474. StrAccum *pStr, /* The text expression being built */
  105475. int iTerm, /* Index of this term. First is zero */
  105476. const char *zColumn, /* Name of the column */
  105477. const char *zOp /* Name of the operator */
  105478. ){
  105479. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  105480. sqlite3StrAccumAppend(pStr, zColumn, -1);
  105481. sqlite3StrAccumAppend(pStr, zOp, 1);
  105482. sqlite3StrAccumAppend(pStr, "?", 1);
  105483. }
  105484. /*
  105485. ** Argument pLevel describes a strategy for scanning table pTab. This
  105486. ** function returns a pointer to a string buffer containing a description
  105487. ** of the subset of table rows scanned by the strategy in the form of an
  105488. ** SQL expression. Or, if all rows are scanned, NULL is returned.
  105489. **
  105490. ** For example, if the query:
  105491. **
  105492. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  105493. **
  105494. ** is run and there is an index on (a, b), then this function returns a
  105495. ** string similar to:
  105496. **
  105497. ** "a=? AND b>?"
  105498. **
  105499. ** The returned pointer points to memory obtained from sqlite3DbMalloc().
  105500. ** It is the responsibility of the caller to free the buffer when it is
  105501. ** no longer required.
  105502. */
  105503. static char *explainIndexRange(sqlite3 *db, WhereLoop *pLoop, Table *pTab){
  105504. Index *pIndex = pLoop->u.btree.pIndex;
  105505. int nEq = pLoop->u.btree.nEq;
  105506. int i, j;
  105507. Column *aCol = pTab->aCol;
  105508. int *aiColumn = pIndex->aiColumn;
  105509. StrAccum txt;
  105510. if( nEq==0 && (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ){
  105511. return 0;
  105512. }
  105513. sqlite3StrAccumInit(&txt, 0, 0, SQLITE_MAX_LENGTH);
  105514. txt.db = db;
  105515. sqlite3StrAccumAppend(&txt, " (", 2);
  105516. for(i=0; i<nEq; i++){
  105517. char *z = (i==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[i]].zName;
  105518. explainAppendTerm(&txt, i, z, "=");
  105519. }
  105520. j = i;
  105521. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  105522. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  105523. explainAppendTerm(&txt, i++, z, ">");
  105524. }
  105525. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  105526. char *z = (j==pIndex->nColumn ) ? "rowid" : aCol[aiColumn[j]].zName;
  105527. explainAppendTerm(&txt, i, z, "<");
  105528. }
  105529. sqlite3StrAccumAppend(&txt, ")", 1);
  105530. return sqlite3StrAccumFinish(&txt);
  105531. }
  105532. /*
  105533. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  105534. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  105535. ** record is added to the output to describe the table scan strategy in
  105536. ** pLevel.
  105537. */
  105538. static void explainOneScan(
  105539. Parse *pParse, /* Parse context */
  105540. SrcList *pTabList, /* Table list this loop refers to */
  105541. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  105542. int iLevel, /* Value for "level" column of output */
  105543. int iFrom, /* Value for "from" column of output */
  105544. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  105545. ){
  105546. if( pParse->explain==2 ){
  105547. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  105548. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  105549. sqlite3 *db = pParse->db; /* Database handle */
  105550. char *zMsg; /* Text to add to EQP output */
  105551. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  105552. int isSearch; /* True for a SEARCH. False for SCAN. */
  105553. WhereLoop *pLoop; /* The controlling WhereLoop object */
  105554. u32 flags; /* Flags that describe this loop */
  105555. pLoop = pLevel->pWLoop;
  105556. flags = pLoop->wsFlags;
  105557. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  105558. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  105559. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  105560. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  105561. zMsg = sqlite3MPrintf(db, "%s", isSearch?"SEARCH":"SCAN");
  105562. if( pItem->pSelect ){
  105563. zMsg = sqlite3MAppendf(db, zMsg, "%s SUBQUERY %d", zMsg,pItem->iSelectId);
  105564. }else{
  105565. zMsg = sqlite3MAppendf(db, zMsg, "%s TABLE %s", zMsg, pItem->zName);
  105566. }
  105567. if( pItem->zAlias ){
  105568. zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
  105569. }
  105570. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0
  105571. && ALWAYS(pLoop->u.btree.pIndex!=0)
  105572. ){
  105573. char *zWhere = explainIndexRange(db, pLoop, pItem->pTab);
  105574. zMsg = sqlite3MAppendf(db, zMsg,
  105575. ((flags & WHERE_AUTO_INDEX) ?
  105576. "%s USING AUTOMATIC %sINDEX%.0s%s" :
  105577. "%s USING %sINDEX %s%s"),
  105578. zMsg, ((flags & WHERE_IDX_ONLY) ? "COVERING " : ""),
  105579. pLoop->u.btree.pIndex->zName, zWhere);
  105580. sqlite3DbFree(db, zWhere);
  105581. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  105582. zMsg = sqlite3MAppendf(db, zMsg, "%s USING INTEGER PRIMARY KEY", zMsg);
  105583. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  105584. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid=?)", zMsg);
  105585. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  105586. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>? AND rowid<?)", zMsg);
  105587. }else if( flags&WHERE_BTM_LIMIT ){
  105588. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid>?)", zMsg);
  105589. }else if( ALWAYS(flags&WHERE_TOP_LIMIT) ){
  105590. zMsg = sqlite3MAppendf(db, zMsg, "%s (rowid<?)", zMsg);
  105591. }
  105592. }
  105593. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105594. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  105595. zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
  105596. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  105597. }
  105598. #endif
  105599. zMsg = sqlite3MAppendf(db, zMsg, "%s", zMsg);
  105600. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  105601. }
  105602. }
  105603. #else
  105604. # define explainOneScan(u,v,w,x,y,z)
  105605. #endif /* SQLITE_OMIT_EXPLAIN */
  105606. /*
  105607. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  105608. ** implementation described by pWInfo.
  105609. */
  105610. static Bitmask codeOneLoopStart(
  105611. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  105612. int iLevel, /* Which level of pWInfo->a[] should be coded */
  105613. Bitmask notReady /* Which tables are currently available */
  105614. ){
  105615. int j, k; /* Loop counters */
  105616. int iCur; /* The VDBE cursor for the table */
  105617. int addrNxt; /* Where to jump to continue with the next IN case */
  105618. int omitTable; /* True if we use the index only */
  105619. int bRev; /* True if we need to scan in reverse order */
  105620. WhereLevel *pLevel; /* The where level to be coded */
  105621. WhereLoop *pLoop; /* The WhereLoop object being coded */
  105622. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  105623. WhereTerm *pTerm; /* A WHERE clause term */
  105624. Parse *pParse; /* Parsing context */
  105625. sqlite3 *db; /* Database connection */
  105626. Vdbe *v; /* The prepared stmt under constructions */
  105627. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  105628. int addrBrk; /* Jump here to break out of the loop */
  105629. int addrCont; /* Jump here to continue with next cycle */
  105630. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  105631. int iReleaseReg = 0; /* Temp register to free before returning */
  105632. pParse = pWInfo->pParse;
  105633. v = pParse->pVdbe;
  105634. pWC = &pWInfo->sWC;
  105635. db = pParse->db;
  105636. pLevel = &pWInfo->a[iLevel];
  105637. pLoop = pLevel->pWLoop;
  105638. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  105639. iCur = pTabItem->iCursor;
  105640. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  105641. bRev = (pWInfo->revMask>>iLevel)&1;
  105642. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  105643. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  105644. VdbeNoopComment((v, "Begin Join Loop %d", iLevel));
  105645. /* Create labels for the "break" and "continue" instructions
  105646. ** for the current loop. Jump to addrBrk to break out of a loop.
  105647. ** Jump to cont to go immediately to the next iteration of the
  105648. ** loop.
  105649. **
  105650. ** When there is an IN operator, we also have a "addrNxt" label that
  105651. ** means to continue with the next IN value combination. When
  105652. ** there are no IN operators in the constraints, the "addrNxt" label
  105653. ** is the same as "addrBrk".
  105654. */
  105655. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  105656. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  105657. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  105658. ** initialize a memory cell that records if this table matches any
  105659. ** row of the left table of the join.
  105660. */
  105661. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  105662. pLevel->iLeftJoin = ++pParse->nMem;
  105663. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  105664. VdbeComment((v, "init LEFT JOIN no-match flag"));
  105665. }
  105666. /* Special case of a FROM clause subquery implemented as a co-routine */
  105667. if( pTabItem->viaCoroutine ){
  105668. int regYield = pTabItem->regReturn;
  105669. sqlite3VdbeAddOp2(v, OP_Integer, pTabItem->addrFillSub-1, regYield);
  105670. pLevel->p2 = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
  105671. VdbeComment((v, "next row of co-routine %s", pTabItem->pTab->zName));
  105672. sqlite3VdbeAddOp2(v, OP_If, regYield+1, addrBrk);
  105673. pLevel->op = OP_Goto;
  105674. }else
  105675. #ifndef SQLITE_OMIT_VIRTUALTABLE
  105676. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  105677. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  105678. ** to access the data.
  105679. */
  105680. int iReg; /* P3 Value for OP_VFilter */
  105681. int addrNotFound;
  105682. int nConstraint = pLoop->nLTerm;
  105683. sqlite3ExprCachePush(pParse);
  105684. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  105685. addrNotFound = pLevel->addrBrk;
  105686. for(j=0; j<nConstraint; j++){
  105687. int iTarget = iReg+j+2;
  105688. pTerm = pLoop->aLTerm[j];
  105689. if( pTerm==0 ) continue;
  105690. if( pTerm->eOperator & WO_IN ){
  105691. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  105692. addrNotFound = pLevel->addrNxt;
  105693. }else{
  105694. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  105695. }
  105696. }
  105697. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  105698. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  105699. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  105700. pLoop->u.vtab.idxStr,
  105701. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  105702. pLoop->u.vtab.needFree = 0;
  105703. for(j=0; j<nConstraint && j<16; j++){
  105704. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  105705. disableTerm(pLevel, pLoop->aLTerm[j]);
  105706. }
  105707. }
  105708. pLevel->op = OP_VNext;
  105709. pLevel->p1 = iCur;
  105710. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  105711. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  105712. sqlite3ExprCachePop(pParse, 1);
  105713. }else
  105714. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  105715. if( (pLoop->wsFlags & WHERE_IPK)!=0
  105716. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  105717. ){
  105718. /* Case 2: We can directly reference a single row using an
  105719. ** equality comparison against the ROWID field. Or
  105720. ** we reference multiple rows using a "rowid IN (...)"
  105721. ** construct.
  105722. */
  105723. assert( pLoop->u.btree.nEq==1 );
  105724. iReleaseReg = sqlite3GetTempReg(pParse);
  105725. pTerm = pLoop->aLTerm[0];
  105726. assert( pTerm!=0 );
  105727. assert( pTerm->pExpr!=0 );
  105728. assert( omitTable==0 );
  105729. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  105730. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  105731. addrNxt = pLevel->addrNxt;
  105732. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
  105733. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  105734. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  105735. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  105736. VdbeComment((v, "pk"));
  105737. pLevel->op = OP_Noop;
  105738. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  105739. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  105740. ){
  105741. /* Case 3: We have an inequality comparison against the ROWID field.
  105742. */
  105743. int testOp = OP_Noop;
  105744. int start;
  105745. int memEndValue = 0;
  105746. WhereTerm *pStart, *pEnd;
  105747. assert( omitTable==0 );
  105748. j = 0;
  105749. pStart = pEnd = 0;
  105750. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  105751. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  105752. assert( pStart!=0 || pEnd!=0 );
  105753. if( bRev ){
  105754. pTerm = pStart;
  105755. pStart = pEnd;
  105756. pEnd = pTerm;
  105757. }
  105758. if( pStart ){
  105759. Expr *pX; /* The expression that defines the start bound */
  105760. int r1, rTemp; /* Registers for holding the start boundary */
  105761. /* The following constant maps TK_xx codes into corresponding
  105762. ** seek opcodes. It depends on a particular ordering of TK_xx
  105763. */
  105764. const u8 aMoveOp[] = {
  105765. /* TK_GT */ OP_SeekGt,
  105766. /* TK_LE */ OP_SeekLe,
  105767. /* TK_LT */ OP_SeekLt,
  105768. /* TK_GE */ OP_SeekGe
  105769. };
  105770. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  105771. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  105772. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  105773. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  105774. testcase( pStart->wtFlags & TERM_VIRTUAL );
  105775. pX = pStart->pExpr;
  105776. assert( pX!=0 );
  105777. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  105778. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  105779. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  105780. VdbeComment((v, "pk"));
  105781. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  105782. sqlite3ReleaseTempReg(pParse, rTemp);
  105783. disableTerm(pLevel, pStart);
  105784. }else{
  105785. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  105786. }
  105787. if( pEnd ){
  105788. Expr *pX;
  105789. pX = pEnd->pExpr;
  105790. assert( pX!=0 );
  105791. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  105792. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  105793. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  105794. memEndValue = ++pParse->nMem;
  105795. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  105796. if( pX->op==TK_LT || pX->op==TK_GT ){
  105797. testOp = bRev ? OP_Le : OP_Ge;
  105798. }else{
  105799. testOp = bRev ? OP_Lt : OP_Gt;
  105800. }
  105801. disableTerm(pLevel, pEnd);
  105802. }
  105803. start = sqlite3VdbeCurrentAddr(v);
  105804. pLevel->op = bRev ? OP_Prev : OP_Next;
  105805. pLevel->p1 = iCur;
  105806. pLevel->p2 = start;
  105807. assert( pLevel->p5==0 );
  105808. if( testOp!=OP_Noop ){
  105809. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  105810. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  105811. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  105812. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  105813. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  105814. }
  105815. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  105816. /* Case 4: A scan using an index.
  105817. **
  105818. ** The WHERE clause may contain zero or more equality
  105819. ** terms ("==" or "IN" operators) that refer to the N
  105820. ** left-most columns of the index. It may also contain
  105821. ** inequality constraints (>, <, >= or <=) on the indexed
  105822. ** column that immediately follows the N equalities. Only
  105823. ** the right-most column can be an inequality - the rest must
  105824. ** use the "==" and "IN" operators. For example, if the
  105825. ** index is on (x,y,z), then the following clauses are all
  105826. ** optimized:
  105827. **
  105828. ** x=5
  105829. ** x=5 AND y=10
  105830. ** x=5 AND y<10
  105831. ** x=5 AND y>5 AND y<10
  105832. ** x=5 AND y=5 AND z<=10
  105833. **
  105834. ** The z<10 term of the following cannot be used, only
  105835. ** the x=5 term:
  105836. **
  105837. ** x=5 AND z<10
  105838. **
  105839. ** N may be zero if there are inequality constraints.
  105840. ** If there are no inequality constraints, then N is at
  105841. ** least one.
  105842. **
  105843. ** This case is also used when there are no WHERE clause
  105844. ** constraints but an index is selected anyway, in order
  105845. ** to force the output order to conform to an ORDER BY.
  105846. */
  105847. static const u8 aStartOp[] = {
  105848. 0,
  105849. 0,
  105850. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  105851. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  105852. OP_SeekGt, /* 4: (start_constraints && !startEq && !bRev) */
  105853. OP_SeekLt, /* 5: (start_constraints && !startEq && bRev) */
  105854. OP_SeekGe, /* 6: (start_constraints && startEq && !bRev) */
  105855. OP_SeekLe /* 7: (start_constraints && startEq && bRev) */
  105856. };
  105857. static const u8 aEndOp[] = {
  105858. OP_Noop, /* 0: (!end_constraints) */
  105859. OP_IdxGE, /* 1: (end_constraints && !bRev) */
  105860. OP_IdxLT /* 2: (end_constraints && bRev) */
  105861. };
  105862. int nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  105863. int isMinQuery = 0; /* If this is an optimized SELECT min(x).. */
  105864. int regBase; /* Base register holding constraint values */
  105865. int r1; /* Temp register */
  105866. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  105867. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  105868. int startEq; /* True if range start uses ==, >= or <= */
  105869. int endEq; /* True if range end uses ==, >= or <= */
  105870. int start_constraints; /* Start of range is constrained */
  105871. int nConstraint; /* Number of constraint terms */
  105872. Index *pIdx; /* The index we will be using */
  105873. int iIdxCur; /* The VDBE cursor for the index */
  105874. int nExtraReg = 0; /* Number of extra registers needed */
  105875. int op; /* Instruction opcode */
  105876. char *zStartAff; /* Affinity for start of range constraint */
  105877. char *zEndAff; /* Affinity for end of range constraint */
  105878. pIdx = pLoop->u.btree.pIndex;
  105879. iIdxCur = pLevel->iIdxCur;
  105880. /* If this loop satisfies a sort order (pOrderBy) request that
  105881. ** was passed to this function to implement a "SELECT min(x) ..."
  105882. ** query, then the caller will only allow the loop to run for
  105883. ** a single iteration. This means that the first row returned
  105884. ** should not have a NULL value stored in 'x'. If column 'x' is
  105885. ** the first one after the nEq equality constraints in the index,
  105886. ** this requires some special handling.
  105887. */
  105888. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  105889. && (pWInfo->bOBSat!=0)
  105890. && (pIdx->nColumn>nEq)
  105891. ){
  105892. /* assert( pOrderBy->nExpr==1 ); */
  105893. /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
  105894. isMinQuery = 1;
  105895. nExtraReg = 1;
  105896. }
  105897. /* Find any inequality constraint terms for the start and end
  105898. ** of the range.
  105899. */
  105900. j = nEq;
  105901. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  105902. pRangeStart = pLoop->aLTerm[j++];
  105903. nExtraReg = 1;
  105904. }
  105905. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  105906. pRangeEnd = pLoop->aLTerm[j++];
  105907. nExtraReg = 1;
  105908. }
  105909. /* Generate code to evaluate all constraint terms using == or IN
  105910. ** and store the values of those terms in an array of registers
  105911. ** starting at regBase.
  105912. */
  105913. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  105914. zEndAff = sqlite3DbStrDup(db, zStartAff);
  105915. addrNxt = pLevel->addrNxt;
  105916. /* If we are doing a reverse order scan on an ascending index, or
  105917. ** a forward order scan on a descending index, interchange the
  105918. ** start and end terms (pRangeStart and pRangeEnd).
  105919. */
  105920. if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  105921. || (bRev && pIdx->nColumn==nEq)
  105922. ){
  105923. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  105924. }
  105925. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  105926. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  105927. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  105928. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  105929. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  105930. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  105931. start_constraints = pRangeStart || nEq>0;
  105932. /* Seek the index cursor to the start of the range. */
  105933. nConstraint = nEq;
  105934. if( pRangeStart ){
  105935. Expr *pRight = pRangeStart->pExpr->pRight;
  105936. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  105937. if( (pRangeStart->wtFlags & TERM_VNULL)==0 ){
  105938. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  105939. }
  105940. if( zStartAff ){
  105941. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  105942. /* Since the comparison is to be performed with no conversions
  105943. ** applied to the operands, set the affinity to apply to pRight to
  105944. ** SQLITE_AFF_NONE. */
  105945. zStartAff[nEq] = SQLITE_AFF_NONE;
  105946. }
  105947. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  105948. zStartAff[nEq] = SQLITE_AFF_NONE;
  105949. }
  105950. }
  105951. nConstraint++;
  105952. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  105953. }else if( isMinQuery ){
  105954. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  105955. nConstraint++;
  105956. startEq = 0;
  105957. start_constraints = 1;
  105958. }
  105959. codeApplyAffinity(pParse, regBase, nConstraint, zStartAff);
  105960. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  105961. assert( op!=0 );
  105962. testcase( op==OP_Rewind );
  105963. testcase( op==OP_Last );
  105964. testcase( op==OP_SeekGt );
  105965. testcase( op==OP_SeekGe );
  105966. testcase( op==OP_SeekLe );
  105967. testcase( op==OP_SeekLt );
  105968. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  105969. /* Load the value for the inequality constraint at the end of the
  105970. ** range (if any).
  105971. */
  105972. nConstraint = nEq;
  105973. if( pRangeEnd ){
  105974. Expr *pRight = pRangeEnd->pExpr->pRight;
  105975. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  105976. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  105977. if( (pRangeEnd->wtFlags & TERM_VNULL)==0 ){
  105978. sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
  105979. }
  105980. if( zEndAff ){
  105981. if( sqlite3CompareAffinity(pRight, zEndAff[nEq])==SQLITE_AFF_NONE){
  105982. /* Since the comparison is to be performed with no conversions
  105983. ** applied to the operands, set the affinity to apply to pRight to
  105984. ** SQLITE_AFF_NONE. */
  105985. zEndAff[nEq] = SQLITE_AFF_NONE;
  105986. }
  105987. if( sqlite3ExprNeedsNoAffinityChange(pRight, zEndAff[nEq]) ){
  105988. zEndAff[nEq] = SQLITE_AFF_NONE;
  105989. }
  105990. }
  105991. codeApplyAffinity(pParse, regBase, nEq+1, zEndAff);
  105992. nConstraint++;
  105993. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  105994. }
  105995. sqlite3DbFree(db, zStartAff);
  105996. sqlite3DbFree(db, zEndAff);
  105997. /* Top of the loop body */
  105998. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  105999. /* Check if the index cursor is past the end of the range. */
  106000. op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
  106001. testcase( op==OP_Noop );
  106002. testcase( op==OP_IdxGE );
  106003. testcase( op==OP_IdxLT );
  106004. if( op!=OP_Noop ){
  106005. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  106006. sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
  106007. }
  106008. /* If there are inequality constraints, check that the value
  106009. ** of the table column that the inequality contrains is not NULL.
  106010. ** If it is, jump to the next iteration of the loop.
  106011. */
  106012. r1 = sqlite3GetTempReg(pParse);
  106013. testcase( pLoop->wsFlags & WHERE_BTM_LIMIT );
  106014. testcase( pLoop->wsFlags & WHERE_TOP_LIMIT );
  106015. if( (pLoop->wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0 ){
  106016. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
  106017. sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
  106018. }
  106019. sqlite3ReleaseTempReg(pParse, r1);
  106020. /* Seek the table cursor, if required */
  106021. disableTerm(pLevel, pRangeStart);
  106022. disableTerm(pLevel, pRangeEnd);
  106023. if( !omitTable ){
  106024. iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
  106025. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  106026. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  106027. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  106028. }
  106029. /* Record the instruction used to terminate the loop. Disable
  106030. ** WHERE clause terms made redundant by the index range scan.
  106031. */
  106032. if( pLoop->wsFlags & WHERE_ONEROW ){
  106033. pLevel->op = OP_Noop;
  106034. }else if( bRev ){
  106035. pLevel->op = OP_Prev;
  106036. }else{
  106037. pLevel->op = OP_Next;
  106038. }
  106039. pLevel->p1 = iIdxCur;
  106040. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  106041. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  106042. }else{
  106043. assert( pLevel->p5==0 );
  106044. }
  106045. }else
  106046. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  106047. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  106048. /* Case 5: Two or more separately indexed terms connected by OR
  106049. **
  106050. ** Example:
  106051. **
  106052. ** CREATE TABLE t1(a,b,c,d);
  106053. ** CREATE INDEX i1 ON t1(a);
  106054. ** CREATE INDEX i2 ON t1(b);
  106055. ** CREATE INDEX i3 ON t1(c);
  106056. **
  106057. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  106058. **
  106059. ** In the example, there are three indexed terms connected by OR.
  106060. ** The top of the loop looks like this:
  106061. **
  106062. ** Null 1 # Zero the rowset in reg 1
  106063. **
  106064. ** Then, for each indexed term, the following. The arguments to
  106065. ** RowSetTest are such that the rowid of the current row is inserted
  106066. ** into the RowSet. If it is already present, control skips the
  106067. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  106068. **
  106069. ** sqlite3WhereBegin(<term>)
  106070. ** RowSetTest # Insert rowid into rowset
  106071. ** Gosub 2 A
  106072. ** sqlite3WhereEnd()
  106073. **
  106074. ** Following the above, code to terminate the loop. Label A, the target
  106075. ** of the Gosub above, jumps to the instruction right after the Goto.
  106076. **
  106077. ** Null 1 # Zero the rowset in reg 1
  106078. ** Goto B # The loop is finished.
  106079. **
  106080. ** A: <loop body> # Return data, whatever.
  106081. **
  106082. ** Return 2 # Jump back to the Gosub
  106083. **
  106084. ** B: <after the loop>
  106085. **
  106086. */
  106087. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  106088. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  106089. Index *pCov = 0; /* Potential covering index (or NULL) */
  106090. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  106091. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  106092. int regRowset = 0; /* Register for RowSet object */
  106093. int regRowid = 0; /* Register holding rowid */
  106094. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  106095. int iRetInit; /* Address of regReturn init */
  106096. int untestedTerms = 0; /* Some terms not completely tested */
  106097. int ii; /* Loop counter */
  106098. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  106099. pTerm = pLoop->aLTerm[0];
  106100. assert( pTerm!=0 );
  106101. assert( pTerm->eOperator & WO_OR );
  106102. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  106103. pOrWc = &pTerm->u.pOrInfo->wc;
  106104. pLevel->op = OP_Return;
  106105. pLevel->p1 = regReturn;
  106106. /* Set up a new SrcList in pOrTab containing the table being scanned
  106107. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  106108. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  106109. */
  106110. if( pWInfo->nLevel>1 ){
  106111. int nNotReady; /* The number of notReady tables */
  106112. struct SrcList_item *origSrc; /* Original list of tables */
  106113. nNotReady = pWInfo->nLevel - iLevel - 1;
  106114. pOrTab = sqlite3StackAllocRaw(db,
  106115. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  106116. if( pOrTab==0 ) return notReady;
  106117. pOrTab->nAlloc = (u8)(nNotReady + 1);
  106118. pOrTab->nSrc = pOrTab->nAlloc;
  106119. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  106120. origSrc = pWInfo->pTabList->a;
  106121. for(k=1; k<=nNotReady; k++){
  106122. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  106123. }
  106124. }else{
  106125. pOrTab = pWInfo->pTabList;
  106126. }
  106127. /* Initialize the rowset register to contain NULL. An SQL NULL is
  106128. ** equivalent to an empty rowset.
  106129. **
  106130. ** Also initialize regReturn to contain the address of the instruction
  106131. ** immediately following the OP_Return at the bottom of the loop. This
  106132. ** is required in a few obscure LEFT JOIN cases where control jumps
  106133. ** over the top of the loop into the body of it. In this case the
  106134. ** correct response for the end-of-loop code (the OP_Return) is to
  106135. ** fall through to the next instruction, just as an OP_Next does if
  106136. ** called on an uninitialized cursor.
  106137. */
  106138. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  106139. regRowset = ++pParse->nMem;
  106140. regRowid = ++pParse->nMem;
  106141. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  106142. }
  106143. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  106144. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  106145. ** Then for every term xN, evaluate as the subexpression: xN AND z
  106146. ** That way, terms in y that are factored into the disjunction will
  106147. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  106148. **
  106149. ** Actually, each subexpression is converted to "xN AND w" where w is
  106150. ** the "interesting" terms of z - terms that did not originate in the
  106151. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  106152. ** indices.
  106153. **
  106154. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  106155. ** is not contained in the ON clause of a LEFT JOIN.
  106156. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  106157. */
  106158. if( pWC->nTerm>1 ){
  106159. int iTerm;
  106160. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  106161. Expr *pExpr = pWC->a[iTerm].pExpr;
  106162. if( &pWC->a[iTerm] == pTerm ) continue;
  106163. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  106164. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO) ) continue;
  106165. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  106166. pExpr = sqlite3ExprDup(db, pExpr, 0);
  106167. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  106168. }
  106169. if( pAndExpr ){
  106170. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  106171. }
  106172. }
  106173. for(ii=0; ii<pOrWc->nTerm; ii++){
  106174. WhereTerm *pOrTerm = &pOrWc->a[ii];
  106175. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  106176. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  106177. Expr *pOrExpr = pOrTerm->pExpr;
  106178. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  106179. pAndExpr->pLeft = pOrExpr;
  106180. pOrExpr = pAndExpr;
  106181. }
  106182. /* Loop through table entries that match term pOrTerm. */
  106183. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  106184. WHERE_OMIT_OPEN_CLOSE | WHERE_AND_ONLY |
  106185. WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY, iCovCur);
  106186. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  106187. if( pSubWInfo ){
  106188. WhereLoop *pSubLoop;
  106189. explainOneScan(
  106190. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  106191. );
  106192. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  106193. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  106194. int r;
  106195. r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur,
  106196. regRowid, 0);
  106197. sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
  106198. sqlite3VdbeCurrentAddr(v)+2, r, iSet);
  106199. }
  106200. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  106201. /* The pSubWInfo->untestedTerms flag means that this OR term
  106202. ** contained one or more AND term from a notReady table. The
  106203. ** terms from the notReady table could not be tested and will
  106204. ** need to be tested later.
  106205. */
  106206. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  106207. /* If all of the OR-connected terms are optimized using the same
  106208. ** index, and the index is opened using the same cursor number
  106209. ** by each call to sqlite3WhereBegin() made by this loop, it may
  106210. ** be possible to use that index as a covering index.
  106211. **
  106212. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  106213. ** uses an index, and this is either the first OR-connected term
  106214. ** processed or the index is the same as that used by all previous
  106215. ** terms, set pCov to the candidate covering index. Otherwise, set
  106216. ** pCov to NULL to indicate that no candidate covering index will
  106217. ** be available.
  106218. */
  106219. pSubLoop = pSubWInfo->a[0].pWLoop;
  106220. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  106221. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  106222. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  106223. ){
  106224. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  106225. pCov = pSubLoop->u.btree.pIndex;
  106226. }else{
  106227. pCov = 0;
  106228. }
  106229. /* Finish the loop through table entries that match term pOrTerm. */
  106230. sqlite3WhereEnd(pSubWInfo);
  106231. }
  106232. }
  106233. }
  106234. pLevel->u.pCovidx = pCov;
  106235. if( pCov ) pLevel->iIdxCur = iCovCur;
  106236. if( pAndExpr ){
  106237. pAndExpr->pLeft = 0;
  106238. sqlite3ExprDelete(db, pAndExpr);
  106239. }
  106240. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  106241. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  106242. sqlite3VdbeResolveLabel(v, iLoopBody);
  106243. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  106244. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  106245. }else
  106246. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  106247. {
  106248. /* Case 6: There is no usable index. We must do a complete
  106249. ** scan of the entire table.
  106250. */
  106251. static const u8 aStep[] = { OP_Next, OP_Prev };
  106252. static const u8 aStart[] = { OP_Rewind, OP_Last };
  106253. assert( bRev==0 || bRev==1 );
  106254. pLevel->op = aStep[bRev];
  106255. pLevel->p1 = iCur;
  106256. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  106257. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  106258. }
  106259. /* Insert code to test every subexpression that can be completely
  106260. ** computed using the current set of tables.
  106261. */
  106262. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  106263. Expr *pE;
  106264. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  106265. testcase( pTerm->wtFlags & TERM_CODED );
  106266. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106267. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  106268. testcase( pWInfo->untestedTerms==0
  106269. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  106270. pWInfo->untestedTerms = 1;
  106271. continue;
  106272. }
  106273. pE = pTerm->pExpr;
  106274. assert( pE!=0 );
  106275. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  106276. continue;
  106277. }
  106278. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  106279. pTerm->wtFlags |= TERM_CODED;
  106280. }
  106281. /* Insert code to test for implied constraints based on transitivity
  106282. ** of the "==" operator.
  106283. **
  106284. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  106285. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  106286. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  106287. ** the implied "t1.a=123" constraint.
  106288. */
  106289. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  106290. Expr *pE, *pEAlt;
  106291. WhereTerm *pAlt;
  106292. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106293. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  106294. if( pTerm->leftCursor!=iCur ) continue;
  106295. if( pLevel->iLeftJoin ) continue;
  106296. pE = pTerm->pExpr;
  106297. assert( !ExprHasProperty(pE, EP_FromJoin) );
  106298. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  106299. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  106300. if( pAlt==0 ) continue;
  106301. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  106302. testcase( pAlt->eOperator & WO_EQ );
  106303. testcase( pAlt->eOperator & WO_IN );
  106304. VdbeNoopComment((v, "begin transitive constraint"));
  106305. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  106306. if( pEAlt ){
  106307. *pEAlt = *pAlt->pExpr;
  106308. pEAlt->pLeft = pE->pLeft;
  106309. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  106310. sqlite3StackFree(db, pEAlt);
  106311. }
  106312. }
  106313. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  106314. ** at least one row of the right table has matched the left table.
  106315. */
  106316. if( pLevel->iLeftJoin ){
  106317. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  106318. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  106319. VdbeComment((v, "record LEFT JOIN hit"));
  106320. sqlite3ExprCacheClear(pParse);
  106321. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  106322. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  106323. testcase( pTerm->wtFlags & TERM_CODED );
  106324. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  106325. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  106326. assert( pWInfo->untestedTerms );
  106327. continue;
  106328. }
  106329. assert( pTerm->pExpr );
  106330. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  106331. pTerm->wtFlags |= TERM_CODED;
  106332. }
  106333. }
  106334. sqlite3ReleaseTempReg(pParse, iReleaseReg);
  106335. return pLevel->notReady;
  106336. }
  106337. #ifdef WHERETRACE_ENABLED
  106338. /*
  106339. ** Print a WhereLoop object for debugging purposes
  106340. */
  106341. static void whereLoopPrint(WhereLoop *p, SrcList *pTabList){
  106342. int nb = 1+(pTabList->nSrc+7)/8;
  106343. struct SrcList_item *pItem = pTabList->a + p->iTab;
  106344. Table *pTab = pItem->pTab;
  106345. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  106346. p->iTab, nb, p->maskSelf, nb, p->prereq);
  106347. sqlite3DebugPrintf(" %12s",
  106348. pItem->zAlias ? pItem->zAlias : pTab->zName);
  106349. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  106350. if( p->u.btree.pIndex ){
  106351. const char *zName = p->u.btree.pIndex->zName;
  106352. if( zName==0 ) zName = "ipk";
  106353. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  106354. int i = sqlite3Strlen30(zName) - 1;
  106355. while( zName[i]!='_' ) i--;
  106356. zName += i;
  106357. }
  106358. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  106359. }else{
  106360. sqlite3DebugPrintf("%20s","");
  106361. }
  106362. }else{
  106363. char *z;
  106364. if( p->u.vtab.idxStr ){
  106365. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  106366. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  106367. }else{
  106368. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  106369. }
  106370. sqlite3DebugPrintf(" %-19s", z);
  106371. sqlite3_free(z);
  106372. }
  106373. sqlite3DebugPrintf(" f %04x N %d", p->wsFlags, p->nLTerm);
  106374. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  106375. }
  106376. #endif
  106377. /*
  106378. ** Convert bulk memory into a valid WhereLoop that can be passed
  106379. ** to whereLoopClear harmlessly.
  106380. */
  106381. static void whereLoopInit(WhereLoop *p){
  106382. p->aLTerm = p->aLTermSpace;
  106383. p->nLTerm = 0;
  106384. p->nLSlot = ArraySize(p->aLTermSpace);
  106385. p->wsFlags = 0;
  106386. }
  106387. /*
  106388. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  106389. */
  106390. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  106391. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  106392. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  106393. sqlite3_free(p->u.vtab.idxStr);
  106394. p->u.vtab.needFree = 0;
  106395. p->u.vtab.idxStr = 0;
  106396. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  106397. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  106398. sqlite3DbFree(db, p->u.btree.pIndex);
  106399. p->u.btree.pIndex = 0;
  106400. }
  106401. }
  106402. }
  106403. /*
  106404. ** Deallocate internal memory used by a WhereLoop object
  106405. */
  106406. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  106407. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  106408. whereLoopClearUnion(db, p);
  106409. whereLoopInit(p);
  106410. }
  106411. /*
  106412. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  106413. */
  106414. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  106415. WhereTerm **paNew;
  106416. if( p->nLSlot>=n ) return SQLITE_OK;
  106417. n = (n+7)&~7;
  106418. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  106419. if( paNew==0 ) return SQLITE_NOMEM;
  106420. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  106421. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  106422. p->aLTerm = paNew;
  106423. p->nLSlot = n;
  106424. return SQLITE_OK;
  106425. }
  106426. /*
  106427. ** Transfer content from the second pLoop into the first.
  106428. */
  106429. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  106430. whereLoopClearUnion(db, pTo);
  106431. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  106432. memset(&pTo->u, 0, sizeof(pTo->u));
  106433. return SQLITE_NOMEM;
  106434. }
  106435. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  106436. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  106437. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  106438. pFrom->u.vtab.needFree = 0;
  106439. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  106440. pFrom->u.btree.pIndex = 0;
  106441. }
  106442. return SQLITE_OK;
  106443. }
  106444. /*
  106445. ** Delete a WhereLoop object
  106446. */
  106447. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  106448. whereLoopClear(db, p);
  106449. sqlite3DbFree(db, p);
  106450. }
  106451. /*
  106452. ** Free a WhereInfo structure
  106453. */
  106454. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  106455. if( ALWAYS(pWInfo) ){
  106456. whereClauseClear(&pWInfo->sWC);
  106457. while( pWInfo->pLoops ){
  106458. WhereLoop *p = pWInfo->pLoops;
  106459. pWInfo->pLoops = p->pNextLoop;
  106460. whereLoopDelete(db, p);
  106461. }
  106462. sqlite3DbFree(db, pWInfo);
  106463. }
  106464. }
  106465. /*
  106466. ** Insert or replace a WhereLoop entry using the template supplied.
  106467. **
  106468. ** An existing WhereLoop entry might be overwritten if the new template
  106469. ** is better and has fewer dependencies. Or the template will be ignored
  106470. ** and no insert will occur if an existing WhereLoop is faster and has
  106471. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  106472. ** added based on the template.
  106473. **
  106474. ** If pBuilder->pOrSet is not NULL then we only care about only the
  106475. ** prerequisites and rRun and nOut costs of the N best loops. That
  106476. ** information is gathered in the pBuilder->pOrSet object. This special
  106477. ** processing mode is used only for OR clause processing.
  106478. **
  106479. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  106480. ** still might overwrite similar loops with the new template if the
  106481. ** template is better. Loops may be overwritten if the following
  106482. ** conditions are met:
  106483. **
  106484. ** (1) They have the same iTab.
  106485. ** (2) They have the same iSortIdx.
  106486. ** (3) The template has same or fewer dependencies than the current loop
  106487. ** (4) The template has the same or lower cost than the current loop
  106488. ** (5) The template uses more terms of the same index but has no additional
  106489. ** dependencies
  106490. */
  106491. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  106492. WhereLoop **ppPrev, *p, *pNext = 0;
  106493. WhereInfo *pWInfo = pBuilder->pWInfo;
  106494. sqlite3 *db = pWInfo->pParse->db;
  106495. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  106496. ** and prereqs.
  106497. */
  106498. if( pBuilder->pOrSet!=0 ){
  106499. #if WHERETRACE_ENABLED
  106500. u16 n = pBuilder->pOrSet->n;
  106501. int x =
  106502. #endif
  106503. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  106504. pTemplate->nOut);
  106505. #if WHERETRACE_ENABLED
  106506. if( sqlite3WhereTrace & 0x8 ){
  106507. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  106508. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106509. }
  106510. #endif
  106511. return SQLITE_OK;
  106512. }
  106513. /* Search for an existing WhereLoop to overwrite, or which takes
  106514. ** priority over pTemplate.
  106515. */
  106516. for(ppPrev=&pWInfo->pLoops, p=*ppPrev; p; ppPrev=&p->pNextLoop, p=*ppPrev){
  106517. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  106518. /* If either the iTab or iSortIdx values for two WhereLoop are different
  106519. ** then those WhereLoops need to be considered separately. Neither is
  106520. ** a candidate to replace the other. */
  106521. continue;
  106522. }
  106523. /* In the current implementation, the rSetup value is either zero
  106524. ** or the cost of building an automatic index (NlogN) and the NlogN
  106525. ** is the same for compatible WhereLoops. */
  106526. assert( p->rSetup==0 || pTemplate->rSetup==0
  106527. || p->rSetup==pTemplate->rSetup );
  106528. /* whereLoopAddBtree() always generates and inserts the automatic index
  106529. ** case first. Hence compatible candidate WhereLoops never have a larger
  106530. ** rSetup. Call this SETUP-INVARIANT */
  106531. assert( p->rSetup>=pTemplate->rSetup );
  106532. if( (p->prereq & pTemplate->prereq)==p->prereq
  106533. && p->rSetup<=pTemplate->rSetup
  106534. && p->rRun<=pTemplate->rRun
  106535. && p->nOut<=pTemplate->nOut
  106536. ){
  106537. /* This branch taken when p is equal or better than pTemplate in
  106538. ** all of (1) dependencies (2) setup-cost, (3) run-cost, and
  106539. ** (4) number of output rows. */
  106540. assert( p->rSetup==pTemplate->rSetup );
  106541. if( p->prereq==pTemplate->prereq
  106542. && p->nLTerm<pTemplate->nLTerm
  106543. && (p->wsFlags & pTemplate->wsFlags & WHERE_INDEXED)!=0
  106544. && (p->u.btree.pIndex==pTemplate->u.btree.pIndex
  106545. || pTemplate->rRun+p->nLTerm<=p->rRun+pTemplate->nLTerm)
  106546. ){
  106547. /* Overwrite an existing WhereLoop with an similar one that uses
  106548. ** more terms of the index */
  106549. pNext = p->pNextLoop;
  106550. break;
  106551. }else{
  106552. /* pTemplate is not helpful.
  106553. ** Return without changing or adding anything */
  106554. goto whereLoopInsert_noop;
  106555. }
  106556. }
  106557. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq
  106558. && p->rRun>=pTemplate->rRun
  106559. && p->nOut>=pTemplate->nOut
  106560. ){
  106561. /* Overwrite an existing WhereLoop with a better one: one that is
  106562. ** better at one of (1) dependencies, (2) setup-cost, (3) run-cost
  106563. ** or (4) number of output rows, and is no worse in any of those
  106564. ** categories. */
  106565. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  106566. pNext = p->pNextLoop;
  106567. break;
  106568. }
  106569. }
  106570. /* If we reach this point it means that either p[] should be overwritten
  106571. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  106572. ** WhereLoop and insert it.
  106573. */
  106574. #if WHERETRACE_ENABLED
  106575. if( sqlite3WhereTrace & 0x8 ){
  106576. if( p!=0 ){
  106577. sqlite3DebugPrintf("ins-del: ");
  106578. whereLoopPrint(p, pWInfo->pTabList);
  106579. }
  106580. sqlite3DebugPrintf("ins-new: ");
  106581. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106582. }
  106583. #endif
  106584. if( p==0 ){
  106585. p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  106586. if( p==0 ) return SQLITE_NOMEM;
  106587. whereLoopInit(p);
  106588. }
  106589. whereLoopXfer(db, p, pTemplate);
  106590. p->pNextLoop = pNext;
  106591. *ppPrev = p;
  106592. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  106593. Index *pIndex = p->u.btree.pIndex;
  106594. if( pIndex && pIndex->tnum==0 ){
  106595. p->u.btree.pIndex = 0;
  106596. }
  106597. }
  106598. return SQLITE_OK;
  106599. /* Jump here if the insert is a no-op */
  106600. whereLoopInsert_noop:
  106601. #if WHERETRACE_ENABLED
  106602. if( sqlite3WhereTrace & 0x8 ){
  106603. sqlite3DebugPrintf("ins-noop: ");
  106604. whereLoopPrint(pTemplate, pWInfo->pTabList);
  106605. }
  106606. #endif
  106607. return SQLITE_OK;
  106608. }
  106609. /*
  106610. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  106611. ** WHERE clause that reference the loop but which are not used by an
  106612. ** index.
  106613. **
  106614. ** In the current implementation, the first extra WHERE clause term reduces
  106615. ** the number of output rows by a factor of 10 and each additional term
  106616. ** reduces the number of output rows by sqrt(2).
  106617. */
  106618. static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop){
  106619. WhereTerm *pTerm, *pX;
  106620. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  106621. int i, j;
  106622. if( !OptimizationEnabled(pWC->pWInfo->pParse->db, SQLITE_AdjustOutEst) ){
  106623. return;
  106624. }
  106625. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  106626. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  106627. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  106628. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  106629. for(j=pLoop->nLTerm-1; j>=0; j--){
  106630. pX = pLoop->aLTerm[j];
  106631. if( pX==pTerm ) break;
  106632. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  106633. }
  106634. if( j<0 ) pLoop->nOut += pTerm->truthProb;
  106635. }
  106636. }
  106637. /*
  106638. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the index pIndex.
  106639. ** Try to match one more.
  106640. **
  106641. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  106642. ** INTEGER PRIMARY KEY.
  106643. */
  106644. static int whereLoopAddBtreeIndex(
  106645. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  106646. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  106647. Index *pProbe, /* An index on pSrc */
  106648. LogEst nInMul /* log(Number of iterations due to IN) */
  106649. ){
  106650. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  106651. Parse *pParse = pWInfo->pParse; /* Parsing context */
  106652. sqlite3 *db = pParse->db; /* Database connection malloc context */
  106653. WhereLoop *pNew; /* Template WhereLoop under construction */
  106654. WhereTerm *pTerm; /* A WhereTerm under consideration */
  106655. int opMask; /* Valid operators for constraints */
  106656. WhereScan scan; /* Iterator for WHERE terms */
  106657. Bitmask saved_prereq; /* Original value of pNew->prereq */
  106658. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  106659. int saved_nEq; /* Original value of pNew->u.btree.nEq */
  106660. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  106661. LogEst saved_nOut; /* Original value of pNew->nOut */
  106662. int iCol; /* Index of the column in the table */
  106663. int rc = SQLITE_OK; /* Return code */
  106664. LogEst nRowEst; /* Estimated index selectivity */
  106665. LogEst rLogSize; /* Logarithm of table size */
  106666. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  106667. pNew = pBuilder->pNew;
  106668. if( db->mallocFailed ) return SQLITE_NOMEM;
  106669. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  106670. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  106671. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  106672. opMask = WO_LT|WO_LE;
  106673. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  106674. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  106675. }else{
  106676. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  106677. }
  106678. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  106679. assert( pNew->u.btree.nEq<=pProbe->nColumn );
  106680. if( pNew->u.btree.nEq < pProbe->nColumn ){
  106681. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  106682. nRowEst = sqlite3LogEst(pProbe->aiRowEst[pNew->u.btree.nEq+1]);
  106683. if( nRowEst==0 && pProbe->onError==OE_None ) nRowEst = 1;
  106684. }else{
  106685. iCol = -1;
  106686. nRowEst = 0;
  106687. }
  106688. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  106689. opMask, pProbe);
  106690. saved_nEq = pNew->u.btree.nEq;
  106691. saved_nLTerm = pNew->nLTerm;
  106692. saved_wsFlags = pNew->wsFlags;
  106693. saved_prereq = pNew->prereq;
  106694. saved_nOut = pNew->nOut;
  106695. pNew->rSetup = 0;
  106696. rLogSize = estLog(sqlite3LogEst(pProbe->aiRowEst[0]));
  106697. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  106698. int nIn = 0;
  106699. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106700. int nRecValid = pBuilder->nRecValid;
  106701. #endif
  106702. if( (pTerm->eOperator==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  106703. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  106704. ){
  106705. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  106706. }
  106707. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  106708. assert( pNew->nOut==saved_nOut );
  106709. pNew->wsFlags = saved_wsFlags;
  106710. pNew->u.btree.nEq = saved_nEq;
  106711. pNew->nLTerm = saved_nLTerm;
  106712. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  106713. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  106714. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  106715. pNew->rRun = rLogSize; /* Baseline cost is log2(N). Adjustments below */
  106716. if( pTerm->eOperator & WO_IN ){
  106717. Expr *pExpr = pTerm->pExpr;
  106718. pNew->wsFlags |= WHERE_COLUMN_IN;
  106719. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  106720. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  106721. nIn = 46; assert( 46==sqlite3LogEst(25) );
  106722. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  106723. /* "x IN (value, value, ...)" */
  106724. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  106725. }
  106726. pNew->rRun += nIn;
  106727. pNew->u.btree.nEq++;
  106728. pNew->nOut = nRowEst + nInMul + nIn;
  106729. }else if( pTerm->eOperator & (WO_EQ) ){
  106730. assert( (pNew->wsFlags & (WHERE_COLUMN_NULL|WHERE_COLUMN_IN))!=0
  106731. || nInMul==0 );
  106732. pNew->wsFlags |= WHERE_COLUMN_EQ;
  106733. if( iCol<0
  106734. || (pProbe->onError!=OE_None && nInMul==0
  106735. && pNew->u.btree.nEq==pProbe->nColumn-1)
  106736. ){
  106737. assert( (pNew->wsFlags & WHERE_COLUMN_IN)==0 || iCol<0 );
  106738. pNew->wsFlags |= WHERE_ONEROW;
  106739. }
  106740. pNew->u.btree.nEq++;
  106741. pNew->nOut = nRowEst + nInMul;
  106742. }else if( pTerm->eOperator & (WO_ISNULL) ){
  106743. pNew->wsFlags |= WHERE_COLUMN_NULL;
  106744. pNew->u.btree.nEq++;
  106745. /* TUNING: IS NULL selects 2 rows */
  106746. nIn = 10; assert( 10==sqlite3LogEst(2) );
  106747. pNew->nOut = nRowEst + nInMul + nIn;
  106748. }else if( pTerm->eOperator & (WO_GT|WO_GE) ){
  106749. testcase( pTerm->eOperator & WO_GT );
  106750. testcase( pTerm->eOperator & WO_GE );
  106751. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  106752. pBtm = pTerm;
  106753. pTop = 0;
  106754. }else{
  106755. assert( pTerm->eOperator & (WO_LT|WO_LE) );
  106756. testcase( pTerm->eOperator & WO_LT );
  106757. testcase( pTerm->eOperator & WO_LE );
  106758. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  106759. pTop = pTerm;
  106760. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  106761. pNew->aLTerm[pNew->nLTerm-2] : 0;
  106762. }
  106763. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  106764. /* Adjust nOut and rRun for STAT3 range values */
  106765. assert( pNew->nOut==saved_nOut );
  106766. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  106767. }
  106768. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106769. if( nInMul==0
  106770. && pProbe->nSample
  106771. && pNew->u.btree.nEq<=pProbe->nSampleCol
  106772. && OptimizationEnabled(db, SQLITE_Stat3)
  106773. ){
  106774. Expr *pExpr = pTerm->pExpr;
  106775. tRowcnt nOut = 0;
  106776. if( (pTerm->eOperator & (WO_EQ|WO_ISNULL))!=0 ){
  106777. testcase( pTerm->eOperator & WO_EQ );
  106778. testcase( pTerm->eOperator & WO_ISNULL );
  106779. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  106780. }else if( (pTerm->eOperator & WO_IN)
  106781. && !ExprHasProperty(pExpr, EP_xIsSelect) ){
  106782. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  106783. }
  106784. assert( nOut==0 || rc==SQLITE_OK );
  106785. if( nOut ){
  106786. pNew->nOut = sqlite3LogEst(nOut);
  106787. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  106788. }
  106789. }
  106790. #endif
  106791. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  106792. /* Each row involves a step of the index, then a binary search of
  106793. ** the main table */
  106794. pNew->rRun = sqlite3LogEstAdd(pNew->rRun,rLogSize>27 ? rLogSize-17 : 10);
  106795. }
  106796. /* Step cost for each output row */
  106797. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut);
  106798. whereLoopOutputAdjust(pBuilder->pWC, pNew);
  106799. rc = whereLoopInsert(pBuilder, pNew);
  106800. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  106801. && pNew->u.btree.nEq<(pProbe->nColumn + (pProbe->zName!=0))
  106802. ){
  106803. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  106804. }
  106805. pNew->nOut = saved_nOut;
  106806. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106807. pBuilder->nRecValid = nRecValid;
  106808. #endif
  106809. }
  106810. pNew->prereq = saved_prereq;
  106811. pNew->u.btree.nEq = saved_nEq;
  106812. pNew->wsFlags = saved_wsFlags;
  106813. pNew->nOut = saved_nOut;
  106814. pNew->nLTerm = saved_nLTerm;
  106815. return rc;
  106816. }
  106817. /*
  106818. ** Return True if it is possible that pIndex might be useful in
  106819. ** implementing the ORDER BY clause in pBuilder.
  106820. **
  106821. ** Return False if pBuilder does not contain an ORDER BY clause or
  106822. ** if there is no way for pIndex to be useful in implementing that
  106823. ** ORDER BY clause.
  106824. */
  106825. static int indexMightHelpWithOrderBy(
  106826. WhereLoopBuilder *pBuilder,
  106827. Index *pIndex,
  106828. int iCursor
  106829. ){
  106830. ExprList *pOB;
  106831. int ii, jj;
  106832. if( pIndex->bUnordered ) return 0;
  106833. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  106834. for(ii=0; ii<pOB->nExpr; ii++){
  106835. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  106836. if( pExpr->op!=TK_COLUMN ) return 0;
  106837. if( pExpr->iTable==iCursor ){
  106838. for(jj=0; jj<pIndex->nColumn; jj++){
  106839. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  106840. }
  106841. }
  106842. }
  106843. return 0;
  106844. }
  106845. /*
  106846. ** Return a bitmask where 1s indicate that the corresponding column of
  106847. ** the table is used by an index. Only the first 63 columns are considered.
  106848. */
  106849. static Bitmask columnsInIndex(Index *pIdx){
  106850. Bitmask m = 0;
  106851. int j;
  106852. for(j=pIdx->nColumn-1; j>=0; j--){
  106853. int x = pIdx->aiColumn[j];
  106854. assert( x>=0 );
  106855. testcase( x==BMS-1 );
  106856. testcase( x==BMS-2 );
  106857. if( x<BMS-1 ) m |= MASKBIT(x);
  106858. }
  106859. return m;
  106860. }
  106861. /* Check to see if a partial index with pPartIndexWhere can be used
  106862. ** in the current query. Return true if it can be and false if not.
  106863. */
  106864. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  106865. int i;
  106866. WhereTerm *pTerm;
  106867. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  106868. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  106869. }
  106870. return 0;
  106871. }
  106872. /*
  106873. ** Add all WhereLoop objects for a single table of the join where the table
  106874. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  106875. ** a b-tree table, not a virtual table.
  106876. */
  106877. static int whereLoopAddBtree(
  106878. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  106879. Bitmask mExtra /* Extra prerequesites for using this table */
  106880. ){
  106881. WhereInfo *pWInfo; /* WHERE analysis context */
  106882. Index *pProbe; /* An index we are evaluating */
  106883. Index sPk; /* A fake index object for the primary key */
  106884. tRowcnt aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
  106885. int aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  106886. SrcList *pTabList; /* The FROM clause */
  106887. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  106888. WhereLoop *pNew; /* Template WhereLoop object */
  106889. int rc = SQLITE_OK; /* Return code */
  106890. int iSortIdx = 1; /* Index number */
  106891. int b; /* A boolean value */
  106892. LogEst rSize; /* number of rows in the table */
  106893. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  106894. WhereClause *pWC; /* The parsed WHERE clause */
  106895. Table *pTab; /* Table being queried */
  106896. pNew = pBuilder->pNew;
  106897. pWInfo = pBuilder->pWInfo;
  106898. pTabList = pWInfo->pTabList;
  106899. pSrc = pTabList->a + pNew->iTab;
  106900. pTab = pSrc->pTab;
  106901. pWC = pBuilder->pWC;
  106902. assert( !IsVirtual(pSrc->pTab) );
  106903. if( pSrc->pIndex ){
  106904. /* An INDEXED BY clause specifies a particular index to use */
  106905. pProbe = pSrc->pIndex;
  106906. }else{
  106907. /* There is no INDEXED BY clause. Create a fake Index object in local
  106908. ** variable sPk to represent the rowid primary key index. Make this
  106909. ** fake index the first in a chain of Index objects with all of the real
  106910. ** indices to follow */
  106911. Index *pFirst; /* First of real indices on the table */
  106912. memset(&sPk, 0, sizeof(Index));
  106913. sPk.nColumn = 1;
  106914. sPk.aiColumn = &aiColumnPk;
  106915. sPk.aiRowEst = aiRowEstPk;
  106916. sPk.onError = OE_Replace;
  106917. sPk.pTable = pTab;
  106918. aiRowEstPk[0] = pTab->nRowEst;
  106919. aiRowEstPk[1] = 1;
  106920. pFirst = pSrc->pTab->pIndex;
  106921. if( pSrc->notIndexed==0 ){
  106922. /* The real indices of the table are only considered if the
  106923. ** NOT INDEXED qualifier is omitted from the FROM clause */
  106924. sPk.pNext = pFirst;
  106925. }
  106926. pProbe = &sPk;
  106927. }
  106928. rSize = sqlite3LogEst(pTab->nRowEst);
  106929. rLogSize = estLog(rSize);
  106930. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  106931. /* Automatic indexes */
  106932. if( !pBuilder->pOrSet
  106933. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  106934. && pSrc->pIndex==0
  106935. && !pSrc->viaCoroutine
  106936. && !pSrc->notIndexed
  106937. && !pSrc->isCorrelated
  106938. ){
  106939. /* Generate auto-index WhereLoops */
  106940. WhereTerm *pTerm;
  106941. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  106942. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  106943. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  106944. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  106945. pNew->u.btree.nEq = 1;
  106946. pNew->u.btree.pIndex = 0;
  106947. pNew->nLTerm = 1;
  106948. pNew->aLTerm[0] = pTerm;
  106949. /* TUNING: One-time cost for computing the automatic index is
  106950. ** approximately 7*N*log2(N) where N is the number of rows in
  106951. ** the table being indexed. */
  106952. pNew->rSetup = rLogSize + rSize + 28; assert( 28==sqlite3LogEst(7) );
  106953. /* TUNING: Each index lookup yields 20 rows in the table. This
  106954. ** is more than the usual guess of 10 rows, since we have no way
  106955. ** of knowning how selective the index will ultimately be. It would
  106956. ** not be unreasonable to make this value much larger. */
  106957. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  106958. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  106959. pNew->wsFlags = WHERE_AUTO_INDEX;
  106960. pNew->prereq = mExtra | pTerm->prereqRight;
  106961. rc = whereLoopInsert(pBuilder, pNew);
  106962. }
  106963. }
  106964. }
  106965. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  106966. /* Loop over all indices
  106967. */
  106968. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  106969. if( pProbe->pPartIdxWhere!=0
  106970. && !whereUsablePartialIndex(pNew->iTab, pWC, pProbe->pPartIdxWhere) ){
  106971. continue; /* Partial index inappropriate for this query */
  106972. }
  106973. pNew->u.btree.nEq = 0;
  106974. pNew->nLTerm = 0;
  106975. pNew->iSortIdx = 0;
  106976. pNew->rSetup = 0;
  106977. pNew->prereq = mExtra;
  106978. pNew->nOut = rSize;
  106979. pNew->u.btree.pIndex = pProbe;
  106980. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  106981. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  106982. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  106983. if( pProbe->tnum<=0 ){
  106984. /* Integer primary key index */
  106985. pNew->wsFlags = WHERE_IPK;
  106986. /* Full table scan */
  106987. pNew->iSortIdx = b ? iSortIdx : 0;
  106988. /* TUNING: Cost of full table scan is 3*(N + log2(N)).
  106989. ** + The extra 3 factor is to encourage the use of indexed lookups
  106990. ** over full scans. FIXME */
  106991. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 16;
  106992. whereLoopOutputAdjust(pWC, pNew);
  106993. rc = whereLoopInsert(pBuilder, pNew);
  106994. pNew->nOut = rSize;
  106995. if( rc ) break;
  106996. }else{
  106997. Bitmask m = pSrc->colUsed & ~columnsInIndex(pProbe);
  106998. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  106999. /* Full scan via index */
  107000. if( b
  107001. || ( m==0
  107002. && pProbe->bUnordered==0
  107003. && pProbe->szIdxRow<pTab->szTabRow
  107004. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  107005. && sqlite3GlobalConfig.bUseCis
  107006. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  107007. )
  107008. ){
  107009. pNew->iSortIdx = b ? iSortIdx : 0;
  107010. if( m==0 ){
  107011. /* TUNING: Cost of a covering index scan is K*(N + log2(N)).
  107012. ** + The extra factor K of between 1.1 and 3.0 that depends
  107013. ** on the relative sizes of the table and the index. K
  107014. ** is smaller for smaller indices, thus favoring them.
  107015. */
  107016. pNew->rRun = sqlite3LogEstAdd(rSize,rLogSize) + 1 +
  107017. (15*pProbe->szIdxRow)/pTab->szTabRow;
  107018. }else{
  107019. assert( b!=0 );
  107020. /* TUNING: Cost of scanning a non-covering index is (N+1)*log2(N)
  107021. ** which we will simplify to just N*log2(N) */
  107022. pNew->rRun = rSize + rLogSize;
  107023. }
  107024. whereLoopOutputAdjust(pWC, pNew);
  107025. rc = whereLoopInsert(pBuilder, pNew);
  107026. pNew->nOut = rSize;
  107027. if( rc ) break;
  107028. }
  107029. }
  107030. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  107031. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  107032. sqlite3Stat4ProbeFree(pBuilder->pRec);
  107033. pBuilder->nRecValid = 0;
  107034. pBuilder->pRec = 0;
  107035. #endif
  107036. /* If there was an INDEXED BY clause, then only that one index is
  107037. ** considered. */
  107038. if( pSrc->pIndex ) break;
  107039. }
  107040. return rc;
  107041. }
  107042. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107043. /*
  107044. ** Add all WhereLoop objects for a table of the join identified by
  107045. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  107046. */
  107047. static int whereLoopAddVirtual(
  107048. WhereLoopBuilder *pBuilder /* WHERE clause information */
  107049. ){
  107050. WhereInfo *pWInfo; /* WHERE analysis context */
  107051. Parse *pParse; /* The parsing context */
  107052. WhereClause *pWC; /* The WHERE clause */
  107053. struct SrcList_item *pSrc; /* The FROM clause term to search */
  107054. Table *pTab;
  107055. sqlite3 *db;
  107056. sqlite3_index_info *pIdxInfo;
  107057. struct sqlite3_index_constraint *pIdxCons;
  107058. struct sqlite3_index_constraint_usage *pUsage;
  107059. WhereTerm *pTerm;
  107060. int i, j;
  107061. int iTerm, mxTerm;
  107062. int nConstraint;
  107063. int seenIn = 0; /* True if an IN operator is seen */
  107064. int seenVar = 0; /* True if a non-constant constraint is seen */
  107065. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  107066. WhereLoop *pNew;
  107067. int rc = SQLITE_OK;
  107068. pWInfo = pBuilder->pWInfo;
  107069. pParse = pWInfo->pParse;
  107070. db = pParse->db;
  107071. pWC = pBuilder->pWC;
  107072. pNew = pBuilder->pNew;
  107073. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  107074. pTab = pSrc->pTab;
  107075. assert( IsVirtual(pTab) );
  107076. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  107077. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  107078. pNew->prereq = 0;
  107079. pNew->rSetup = 0;
  107080. pNew->wsFlags = WHERE_VIRTUALTABLE;
  107081. pNew->nLTerm = 0;
  107082. pNew->u.vtab.needFree = 0;
  107083. pUsage = pIdxInfo->aConstraintUsage;
  107084. nConstraint = pIdxInfo->nConstraint;
  107085. if( whereLoopResize(db, pNew, nConstraint) ){
  107086. sqlite3DbFree(db, pIdxInfo);
  107087. return SQLITE_NOMEM;
  107088. }
  107089. for(iPhase=0; iPhase<=3; iPhase++){
  107090. if( !seenIn && (iPhase&1)!=0 ){
  107091. iPhase++;
  107092. if( iPhase>3 ) break;
  107093. }
  107094. if( !seenVar && iPhase>1 ) break;
  107095. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  107096. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  107097. j = pIdxCons->iTermOffset;
  107098. pTerm = &pWC->a[j];
  107099. switch( iPhase ){
  107100. case 0: /* Constants without IN operator */
  107101. pIdxCons->usable = 0;
  107102. if( (pTerm->eOperator & WO_IN)!=0 ){
  107103. seenIn = 1;
  107104. }
  107105. if( pTerm->prereqRight!=0 ){
  107106. seenVar = 1;
  107107. }else if( (pTerm->eOperator & WO_IN)==0 ){
  107108. pIdxCons->usable = 1;
  107109. }
  107110. break;
  107111. case 1: /* Constants with IN operators */
  107112. assert( seenIn );
  107113. pIdxCons->usable = (pTerm->prereqRight==0);
  107114. break;
  107115. case 2: /* Variables without IN */
  107116. assert( seenVar );
  107117. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  107118. break;
  107119. default: /* Variables with IN */
  107120. assert( seenVar && seenIn );
  107121. pIdxCons->usable = 1;
  107122. break;
  107123. }
  107124. }
  107125. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  107126. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  107127. pIdxInfo->idxStr = 0;
  107128. pIdxInfo->idxNum = 0;
  107129. pIdxInfo->needToFreeIdxStr = 0;
  107130. pIdxInfo->orderByConsumed = 0;
  107131. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  107132. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  107133. if( rc ) goto whereLoopAddVtab_exit;
  107134. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  107135. pNew->prereq = 0;
  107136. mxTerm = -1;
  107137. assert( pNew->nLSlot>=nConstraint );
  107138. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  107139. pNew->u.vtab.omitMask = 0;
  107140. for(i=0; i<nConstraint; i++, pIdxCons++){
  107141. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  107142. j = pIdxCons->iTermOffset;
  107143. if( iTerm>=nConstraint
  107144. || j<0
  107145. || j>=pWC->nTerm
  107146. || pNew->aLTerm[iTerm]!=0
  107147. ){
  107148. rc = SQLITE_ERROR;
  107149. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  107150. goto whereLoopAddVtab_exit;
  107151. }
  107152. testcase( iTerm==nConstraint-1 );
  107153. testcase( j==0 );
  107154. testcase( j==pWC->nTerm-1 );
  107155. pTerm = &pWC->a[j];
  107156. pNew->prereq |= pTerm->prereqRight;
  107157. assert( iTerm<pNew->nLSlot );
  107158. pNew->aLTerm[iTerm] = pTerm;
  107159. if( iTerm>mxTerm ) mxTerm = iTerm;
  107160. testcase( iTerm==15 );
  107161. testcase( iTerm==16 );
  107162. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  107163. if( (pTerm->eOperator & WO_IN)!=0 ){
  107164. if( pUsage[i].omit==0 ){
  107165. /* Do not attempt to use an IN constraint if the virtual table
  107166. ** says that the equivalent EQ constraint cannot be safely omitted.
  107167. ** If we do attempt to use such a constraint, some rows might be
  107168. ** repeated in the output. */
  107169. break;
  107170. }
  107171. /* A virtual table that is constrained by an IN clause may not
  107172. ** consume the ORDER BY clause because (1) the order of IN terms
  107173. ** is not necessarily related to the order of output terms and
  107174. ** (2) Multiple outputs from a single IN value will not merge
  107175. ** together. */
  107176. pIdxInfo->orderByConsumed = 0;
  107177. }
  107178. }
  107179. }
  107180. if( i>=nConstraint ){
  107181. pNew->nLTerm = mxTerm+1;
  107182. assert( pNew->nLTerm<=pNew->nLSlot );
  107183. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  107184. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  107185. pIdxInfo->needToFreeIdxStr = 0;
  107186. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  107187. pNew->u.vtab.isOrdered = (u8)((pIdxInfo->nOrderBy!=0)
  107188. && pIdxInfo->orderByConsumed);
  107189. pNew->rSetup = 0;
  107190. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  107191. /* TUNING: Every virtual table query returns 25 rows */
  107192. pNew->nOut = 46; assert( 46==sqlite3LogEst(25) );
  107193. whereLoopInsert(pBuilder, pNew);
  107194. if( pNew->u.vtab.needFree ){
  107195. sqlite3_free(pNew->u.vtab.idxStr);
  107196. pNew->u.vtab.needFree = 0;
  107197. }
  107198. }
  107199. }
  107200. whereLoopAddVtab_exit:
  107201. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  107202. sqlite3DbFree(db, pIdxInfo);
  107203. return rc;
  107204. }
  107205. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107206. /*
  107207. ** Add WhereLoop entries to handle OR terms. This works for either
  107208. ** btrees or virtual tables.
  107209. */
  107210. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  107211. WhereInfo *pWInfo = pBuilder->pWInfo;
  107212. WhereClause *pWC;
  107213. WhereLoop *pNew;
  107214. WhereTerm *pTerm, *pWCEnd;
  107215. int rc = SQLITE_OK;
  107216. int iCur;
  107217. WhereClause tempWC;
  107218. WhereLoopBuilder sSubBuild;
  107219. WhereOrSet sSum, sCur, sPrev;
  107220. struct SrcList_item *pItem;
  107221. pWC = pBuilder->pWC;
  107222. if( pWInfo->wctrlFlags & WHERE_AND_ONLY ) return SQLITE_OK;
  107223. pWCEnd = pWC->a + pWC->nTerm;
  107224. pNew = pBuilder->pNew;
  107225. memset(&sSum, 0, sizeof(sSum));
  107226. pItem = pWInfo->pTabList->a + pNew->iTab;
  107227. iCur = pItem->iCursor;
  107228. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  107229. if( (pTerm->eOperator & WO_OR)!=0
  107230. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  107231. ){
  107232. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  107233. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  107234. WhereTerm *pOrTerm;
  107235. int once = 1;
  107236. int i, j;
  107237. sSubBuild = *pBuilder;
  107238. sSubBuild.pOrderBy = 0;
  107239. sSubBuild.pOrSet = &sCur;
  107240. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  107241. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  107242. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  107243. }else if( pOrTerm->leftCursor==iCur ){
  107244. tempWC.pWInfo = pWC->pWInfo;
  107245. tempWC.pOuter = pWC;
  107246. tempWC.op = TK_AND;
  107247. tempWC.nTerm = 1;
  107248. tempWC.a = pOrTerm;
  107249. sSubBuild.pWC = &tempWC;
  107250. }else{
  107251. continue;
  107252. }
  107253. sCur.n = 0;
  107254. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107255. if( IsVirtual(pItem->pTab) ){
  107256. rc = whereLoopAddVirtual(&sSubBuild);
  107257. for(i=0; i<sCur.n; i++) sCur.a[i].prereq |= mExtra;
  107258. }else
  107259. #endif
  107260. {
  107261. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  107262. }
  107263. assert( rc==SQLITE_OK || sCur.n==0 );
  107264. if( sCur.n==0 ){
  107265. sSum.n = 0;
  107266. break;
  107267. }else if( once ){
  107268. whereOrMove(&sSum, &sCur);
  107269. once = 0;
  107270. }else{
  107271. whereOrMove(&sPrev, &sSum);
  107272. sSum.n = 0;
  107273. for(i=0; i<sPrev.n; i++){
  107274. for(j=0; j<sCur.n; j++){
  107275. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  107276. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  107277. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  107278. }
  107279. }
  107280. }
  107281. }
  107282. pNew->nLTerm = 1;
  107283. pNew->aLTerm[0] = pTerm;
  107284. pNew->wsFlags = WHERE_MULTI_OR;
  107285. pNew->rSetup = 0;
  107286. pNew->iSortIdx = 0;
  107287. memset(&pNew->u, 0, sizeof(pNew->u));
  107288. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  107289. /* TUNING: Multiple by 3.5 for the secondary table lookup */
  107290. pNew->rRun = sSum.a[i].rRun + 18;
  107291. pNew->nOut = sSum.a[i].nOut;
  107292. pNew->prereq = sSum.a[i].prereq;
  107293. rc = whereLoopInsert(pBuilder, pNew);
  107294. }
  107295. }
  107296. }
  107297. return rc;
  107298. }
  107299. /*
  107300. ** Add all WhereLoop objects for all tables
  107301. */
  107302. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  107303. WhereInfo *pWInfo = pBuilder->pWInfo;
  107304. Bitmask mExtra = 0;
  107305. Bitmask mPrior = 0;
  107306. int iTab;
  107307. SrcList *pTabList = pWInfo->pTabList;
  107308. struct SrcList_item *pItem;
  107309. sqlite3 *db = pWInfo->pParse->db;
  107310. int nTabList = pWInfo->nLevel;
  107311. int rc = SQLITE_OK;
  107312. u8 priorJoinType = 0;
  107313. WhereLoop *pNew;
  107314. /* Loop over the tables in the join, from left to right */
  107315. pNew = pBuilder->pNew;
  107316. whereLoopInit(pNew);
  107317. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  107318. pNew->iTab = iTab;
  107319. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  107320. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  107321. mExtra = mPrior;
  107322. }
  107323. priorJoinType = pItem->jointype;
  107324. if( IsVirtual(pItem->pTab) ){
  107325. rc = whereLoopAddVirtual(pBuilder);
  107326. }else{
  107327. rc = whereLoopAddBtree(pBuilder, mExtra);
  107328. }
  107329. if( rc==SQLITE_OK ){
  107330. rc = whereLoopAddOr(pBuilder, mExtra);
  107331. }
  107332. mPrior |= pNew->maskSelf;
  107333. if( rc || db->mallocFailed ) break;
  107334. }
  107335. whereLoopClear(db, pNew);
  107336. return rc;
  107337. }
  107338. /*
  107339. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  107340. ** parameters) to see if it outputs rows in the requested ORDER BY
  107341. ** (or GROUP BY) without requiring a separate sort operation. Return:
  107342. **
  107343. ** 0: ORDER BY is not satisfied. Sorting required
  107344. ** 1: ORDER BY is satisfied. Omit sorting
  107345. ** -1: Unknown at this time
  107346. **
  107347. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  107348. ** strict. With GROUP BY and DISTINCT the only requirement is that
  107349. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  107350. ** and DISTINT do not require rows to appear in any particular order as long
  107351. ** as equivelent rows are grouped together. Thus for GROUP BY and DISTINCT
  107352. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  107353. ** pOrderBy terms must be matched in strict left-to-right order.
  107354. */
  107355. static int wherePathSatisfiesOrderBy(
  107356. WhereInfo *pWInfo, /* The WHERE clause */
  107357. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  107358. WherePath *pPath, /* The WherePath to check */
  107359. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  107360. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  107361. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  107362. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  107363. ){
  107364. u8 revSet; /* True if rev is known */
  107365. u8 rev; /* Composite sort order */
  107366. u8 revIdx; /* Index sort order */
  107367. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  107368. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  107369. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  107370. u16 nColumn; /* Number of columns in pIndex */
  107371. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  107372. int iLoop; /* Index of WhereLoop in pPath being processed */
  107373. int i, j; /* Loop counters */
  107374. int iCur; /* Cursor number for current WhereLoop */
  107375. int iColumn; /* A column number within table iCur */
  107376. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  107377. WhereTerm *pTerm; /* A single term of the WHERE clause */
  107378. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  107379. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  107380. Index *pIndex; /* The index associated with pLoop */
  107381. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  107382. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  107383. Bitmask obDone; /* Mask of all ORDER BY terms */
  107384. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  107385. Bitmask ready; /* Mask of inner loops */
  107386. /*
  107387. ** We say the WhereLoop is "one-row" if it generates no more than one
  107388. ** row of output. A WhereLoop is one-row if all of the following are true:
  107389. ** (a) All index columns match with WHERE_COLUMN_EQ.
  107390. ** (b) The index is unique
  107391. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  107392. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  107393. **
  107394. ** We say the WhereLoop is "order-distinct" if the set of columns from
  107395. ** that WhereLoop that are in the ORDER BY clause are different for every
  107396. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  107397. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  107398. ** is not order-distinct. To be order-distinct is not quite the same as being
  107399. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  107400. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  107401. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  107402. **
  107403. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  107404. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  107405. ** automatically order-distinct.
  107406. */
  107407. assert( pOrderBy!=0 );
  107408. /* Sortability of virtual tables is determined by the xBestIndex method
  107409. ** of the virtual table itself */
  107410. if( pLast->wsFlags & WHERE_VIRTUALTABLE ){
  107411. testcase( nLoop>0 ); /* True when outer loops are one-row and match
  107412. ** no ORDER BY terms */
  107413. return pLast->u.vtab.isOrdered;
  107414. }
  107415. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  107416. nOrderBy = pOrderBy->nExpr;
  107417. testcase( nOrderBy==BMS-1 );
  107418. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  107419. isOrderDistinct = 1;
  107420. obDone = MASKBIT(nOrderBy)-1;
  107421. orderDistinctMask = 0;
  107422. ready = 0;
  107423. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  107424. if( iLoop>0 ) ready |= pLoop->maskSelf;
  107425. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  107426. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  107427. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  107428. /* Mark off any ORDER BY term X that is a column in the table of
  107429. ** the current loop for which there is term in the WHERE
  107430. ** clause of the form X IS NULL or X=? that reference only outer
  107431. ** loops.
  107432. */
  107433. for(i=0; i<nOrderBy; i++){
  107434. if( MASKBIT(i) & obSat ) continue;
  107435. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  107436. if( pOBExpr->op!=TK_COLUMN ) continue;
  107437. if( pOBExpr->iTable!=iCur ) continue;
  107438. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  107439. ~ready, WO_EQ|WO_ISNULL, 0);
  107440. if( pTerm==0 ) continue;
  107441. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  107442. const char *z1, *z2;
  107443. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  107444. if( !pColl ) pColl = db->pDfltColl;
  107445. z1 = pColl->zName;
  107446. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  107447. if( !pColl ) pColl = db->pDfltColl;
  107448. z2 = pColl->zName;
  107449. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  107450. }
  107451. obSat |= MASKBIT(i);
  107452. }
  107453. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  107454. if( pLoop->wsFlags & WHERE_IPK ){
  107455. pIndex = 0;
  107456. nColumn = 0;
  107457. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  107458. return 0;
  107459. }else{
  107460. nColumn = pIndex->nColumn;
  107461. isOrderDistinct = pIndex->onError!=OE_None;
  107462. }
  107463. /* Loop through all columns of the index and deal with the ones
  107464. ** that are not constrained by == or IN.
  107465. */
  107466. rev = revSet = 0;
  107467. distinctColumns = 0;
  107468. for(j=0; j<=nColumn; j++){
  107469. u8 bOnce; /* True to run the ORDER BY search loop */
  107470. /* Skip over == and IS NULL terms */
  107471. if( j<pLoop->u.btree.nEq
  107472. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  107473. ){
  107474. if( i & WO_ISNULL ){
  107475. testcase( isOrderDistinct );
  107476. isOrderDistinct = 0;
  107477. }
  107478. continue;
  107479. }
  107480. /* Get the column number in the table (iColumn) and sort order
  107481. ** (revIdx) for the j-th column of the index.
  107482. */
  107483. if( j<nColumn ){
  107484. /* Normal index columns */
  107485. iColumn = pIndex->aiColumn[j];
  107486. revIdx = pIndex->aSortOrder[j];
  107487. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  107488. }else{
  107489. /* The ROWID column at the end */
  107490. assert( j==nColumn );
  107491. iColumn = -1;
  107492. revIdx = 0;
  107493. }
  107494. /* An unconstrained column that might be NULL means that this
  107495. ** WhereLoop is not well-ordered
  107496. */
  107497. if( isOrderDistinct
  107498. && iColumn>=0
  107499. && j>=pLoop->u.btree.nEq
  107500. && pIndex->pTable->aCol[iColumn].notNull==0
  107501. ){
  107502. isOrderDistinct = 0;
  107503. }
  107504. /* Find the ORDER BY term that corresponds to the j-th column
  107505. ** of the index and and mark that ORDER BY term off
  107506. */
  107507. bOnce = 1;
  107508. isMatch = 0;
  107509. for(i=0; bOnce && i<nOrderBy; i++){
  107510. if( MASKBIT(i) & obSat ) continue;
  107511. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  107512. testcase( wctrlFlags & WHERE_GROUPBY );
  107513. testcase( wctrlFlags & WHERE_DISTINCTBY );
  107514. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  107515. if( pOBExpr->op!=TK_COLUMN ) continue;
  107516. if( pOBExpr->iTable!=iCur ) continue;
  107517. if( pOBExpr->iColumn!=iColumn ) continue;
  107518. if( iColumn>=0 ){
  107519. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  107520. if( !pColl ) pColl = db->pDfltColl;
  107521. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  107522. }
  107523. isMatch = 1;
  107524. break;
  107525. }
  107526. if( isMatch ){
  107527. if( iColumn<0 ){
  107528. testcase( distinctColumns==0 );
  107529. distinctColumns = 1;
  107530. }
  107531. obSat |= MASKBIT(i);
  107532. if( (pWInfo->wctrlFlags & WHERE_GROUPBY)==0 ){
  107533. /* Make sure the sort order is compatible in an ORDER BY clause.
  107534. ** Sort order is irrelevant for a GROUP BY clause. */
  107535. if( revSet ){
  107536. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) return 0;
  107537. }else{
  107538. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  107539. if( rev ) *pRevMask |= MASKBIT(iLoop);
  107540. revSet = 1;
  107541. }
  107542. }
  107543. }else{
  107544. /* No match found */
  107545. if( j==0 || j<nColumn ){
  107546. testcase( isOrderDistinct!=0 );
  107547. isOrderDistinct = 0;
  107548. }
  107549. break;
  107550. }
  107551. } /* end Loop over all index columns */
  107552. if( distinctColumns ){
  107553. testcase( isOrderDistinct==0 );
  107554. isOrderDistinct = 1;
  107555. }
  107556. } /* end-if not one-row */
  107557. /* Mark off any other ORDER BY terms that reference pLoop */
  107558. if( isOrderDistinct ){
  107559. orderDistinctMask |= pLoop->maskSelf;
  107560. for(i=0; i<nOrderBy; i++){
  107561. Expr *p;
  107562. if( MASKBIT(i) & obSat ) continue;
  107563. p = pOrderBy->a[i].pExpr;
  107564. if( (exprTableUsage(&pWInfo->sMaskSet, p)&~orderDistinctMask)==0 ){
  107565. obSat |= MASKBIT(i);
  107566. }
  107567. }
  107568. }
  107569. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  107570. if( obSat==obDone ) return 1;
  107571. if( !isOrderDistinct ) return 0;
  107572. return -1;
  107573. }
  107574. #ifdef WHERETRACE_ENABLED
  107575. /* For debugging use only: */
  107576. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  107577. static char zName[65];
  107578. int i;
  107579. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  107580. if( pLast ) zName[i++] = pLast->cId;
  107581. zName[i] = 0;
  107582. return zName;
  107583. }
  107584. #endif
  107585. /*
  107586. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  107587. ** attempts to find the lowest cost path that visits each WhereLoop
  107588. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  107589. **
  107590. ** Assume that the total number of output rows that will need to be sorted
  107591. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  107592. ** costs if nRowEst==0.
  107593. **
  107594. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  107595. ** error occurs.
  107596. */
  107597. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  107598. int mxChoice; /* Maximum number of simultaneous paths tracked */
  107599. int nLoop; /* Number of terms in the join */
  107600. Parse *pParse; /* Parsing context */
  107601. sqlite3 *db; /* The database connection */
  107602. int iLoop; /* Loop counter over the terms of the join */
  107603. int ii, jj; /* Loop counters */
  107604. int mxI = 0; /* Index of next entry to replace */
  107605. LogEst rCost; /* Cost of a path */
  107606. LogEst nOut; /* Number of outputs */
  107607. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  107608. LogEst mxOut = 0; /* Maximum nOut value on the set of paths */
  107609. LogEst rSortCost; /* Cost to do a sort */
  107610. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  107611. WherePath *aFrom; /* All nFrom paths at the previous level */
  107612. WherePath *aTo; /* The nTo best paths at the current level */
  107613. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  107614. WherePath *pTo; /* An element of aTo[] that we are working on */
  107615. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  107616. WhereLoop **pX; /* Used to divy up the pSpace memory */
  107617. char *pSpace; /* Temporary memory used by this routine */
  107618. pParse = pWInfo->pParse;
  107619. db = pParse->db;
  107620. nLoop = pWInfo->nLevel;
  107621. /* TUNING: For simple queries, only the best path is tracked.
  107622. ** For 2-way joins, the 5 best paths are followed.
  107623. ** For joins of 3 or more tables, track the 10 best paths */
  107624. mxChoice = (nLoop==1) ? 1 : (nLoop==2 ? 5 : 10);
  107625. assert( nLoop<=pWInfo->pTabList->nSrc );
  107626. WHERETRACE(0x002, ("---- begin solver\n"));
  107627. /* Allocate and initialize space for aTo and aFrom */
  107628. ii = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  107629. pSpace = sqlite3DbMallocRaw(db, ii);
  107630. if( pSpace==0 ) return SQLITE_NOMEM;
  107631. aTo = (WherePath*)pSpace;
  107632. aFrom = aTo+mxChoice;
  107633. memset(aFrom, 0, sizeof(aFrom[0]));
  107634. pX = (WhereLoop**)(aFrom+mxChoice);
  107635. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  107636. pFrom->aLoop = pX;
  107637. }
  107638. /* Seed the search with a single WherePath containing zero WhereLoops.
  107639. **
  107640. ** TUNING: Do not let the number of iterations go above 25. If the cost
  107641. ** of computing an automatic index is not paid back within the first 25
  107642. ** rows, then do not use the automatic index. */
  107643. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  107644. nFrom = 1;
  107645. /* Precompute the cost of sorting the final result set, if the caller
  107646. ** to sqlite3WhereBegin() was concerned about sorting */
  107647. rSortCost = 0;
  107648. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  107649. aFrom[0].isOrderedValid = 1;
  107650. }else{
  107651. /* TUNING: Estimated cost of sorting is 48*N*log2(N) where N is the
  107652. ** number of output rows. The 48 is the expected size of a row to sort.
  107653. ** FIXME: compute a better estimate of the 48 multiplier based on the
  107654. ** result set expressions. */
  107655. rSortCost = nRowEst + estLog(nRowEst);
  107656. WHERETRACE(0x002,("---- sort cost=%-3d\n", rSortCost));
  107657. }
  107658. /* Compute successively longer WherePaths using the previous generation
  107659. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  107660. ** best paths at each generation */
  107661. for(iLoop=0; iLoop<nLoop; iLoop++){
  107662. nTo = 0;
  107663. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  107664. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  107665. Bitmask maskNew;
  107666. Bitmask revMask = 0;
  107667. u8 isOrderedValid = pFrom->isOrderedValid;
  107668. u8 isOrdered = pFrom->isOrdered;
  107669. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  107670. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  107671. /* At this point, pWLoop is a candidate to be the next loop.
  107672. ** Compute its cost */
  107673. rCost = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  107674. rCost = sqlite3LogEstAdd(rCost, pFrom->rCost);
  107675. nOut = pFrom->nRow + pWLoop->nOut;
  107676. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  107677. if( !isOrderedValid ){
  107678. switch( wherePathSatisfiesOrderBy(pWInfo,
  107679. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  107680. iLoop, pWLoop, &revMask) ){
  107681. case 1: /* Yes. pFrom+pWLoop does satisfy the ORDER BY clause */
  107682. isOrdered = 1;
  107683. isOrderedValid = 1;
  107684. break;
  107685. case 0: /* No. pFrom+pWLoop will require a separate sort */
  107686. isOrdered = 0;
  107687. isOrderedValid = 1;
  107688. rCost = sqlite3LogEstAdd(rCost, rSortCost);
  107689. break;
  107690. default: /* Cannot tell yet. Try again on the next iteration */
  107691. break;
  107692. }
  107693. }else{
  107694. revMask = pFrom->revLoop;
  107695. }
  107696. /* Check to see if pWLoop should be added to the mxChoice best so far */
  107697. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  107698. if( pTo->maskLoop==maskNew
  107699. && pTo->isOrderedValid==isOrderedValid
  107700. && ((pTo->rCost<=rCost && pTo->nRow<=nOut) ||
  107701. (pTo->rCost>=rCost && pTo->nRow>=nOut))
  107702. ){
  107703. testcase( jj==nTo-1 );
  107704. break;
  107705. }
  107706. }
  107707. if( jj>=nTo ){
  107708. if( nTo>=mxChoice && rCost>=mxCost ){
  107709. #ifdef WHERETRACE_ENABLED
  107710. if( sqlite3WhereTrace&0x4 ){
  107711. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  107712. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107713. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107714. }
  107715. #endif
  107716. continue;
  107717. }
  107718. /* Add a new Path to the aTo[] set */
  107719. if( nTo<mxChoice ){
  107720. /* Increase the size of the aTo set by one */
  107721. jj = nTo++;
  107722. }else{
  107723. /* New path replaces the prior worst to keep count below mxChoice */
  107724. jj = mxI;
  107725. }
  107726. pTo = &aTo[jj];
  107727. #ifdef WHERETRACE_ENABLED
  107728. if( sqlite3WhereTrace&0x4 ){
  107729. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  107730. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107731. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107732. }
  107733. #endif
  107734. }else{
  107735. if( pTo->rCost<=rCost && pTo->nRow<=nOut ){
  107736. #ifdef WHERETRACE_ENABLED
  107737. if( sqlite3WhereTrace&0x4 ){
  107738. sqlite3DebugPrintf(
  107739. "Skip %s cost=%-3d,%3d order=%c",
  107740. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107741. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107742. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  107743. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107744. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107745. }
  107746. #endif
  107747. testcase( pTo->rCost==rCost );
  107748. continue;
  107749. }
  107750. testcase( pTo->rCost==rCost+1 );
  107751. /* A new and better score for a previously created equivalent path */
  107752. #ifdef WHERETRACE_ENABLED
  107753. if( sqlite3WhereTrace&0x4 ){
  107754. sqlite3DebugPrintf(
  107755. "Update %s cost=%-3d,%3d order=%c",
  107756. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  107757. isOrderedValid ? (isOrdered ? 'Y' : 'N') : '?');
  107758. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  107759. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107760. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107761. }
  107762. #endif
  107763. }
  107764. /* pWLoop is a winner. Add it to the set of best so far */
  107765. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  107766. pTo->revLoop = revMask;
  107767. pTo->nRow = nOut;
  107768. pTo->rCost = rCost;
  107769. pTo->isOrderedValid = isOrderedValid;
  107770. pTo->isOrdered = isOrdered;
  107771. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  107772. pTo->aLoop[iLoop] = pWLoop;
  107773. if( nTo>=mxChoice ){
  107774. mxI = 0;
  107775. mxCost = aTo[0].rCost;
  107776. mxOut = aTo[0].nRow;
  107777. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  107778. if( pTo->rCost>mxCost || (pTo->rCost==mxCost && pTo->nRow>mxOut) ){
  107779. mxCost = pTo->rCost;
  107780. mxOut = pTo->nRow;
  107781. mxI = jj;
  107782. }
  107783. }
  107784. }
  107785. }
  107786. }
  107787. #ifdef WHERETRACE_ENABLED
  107788. if( sqlite3WhereTrace>=2 ){
  107789. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  107790. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  107791. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  107792. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  107793. pTo->isOrderedValid ? (pTo->isOrdered ? 'Y' : 'N') : '?');
  107794. if( pTo->isOrderedValid && pTo->isOrdered ){
  107795. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  107796. }else{
  107797. sqlite3DebugPrintf("\n");
  107798. }
  107799. }
  107800. }
  107801. #endif
  107802. /* Swap the roles of aFrom and aTo for the next generation */
  107803. pFrom = aTo;
  107804. aTo = aFrom;
  107805. aFrom = pFrom;
  107806. nFrom = nTo;
  107807. }
  107808. if( nFrom==0 ){
  107809. sqlite3ErrorMsg(pParse, "no query solution");
  107810. sqlite3DbFree(db, pSpace);
  107811. return SQLITE_ERROR;
  107812. }
  107813. /* Find the lowest cost path. pFrom will be left pointing to that path */
  107814. pFrom = aFrom;
  107815. for(ii=1; ii<nFrom; ii++){
  107816. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  107817. }
  107818. assert( pWInfo->nLevel==nLoop );
  107819. /* Load the lowest cost path into pWInfo */
  107820. for(iLoop=0; iLoop<nLoop; iLoop++){
  107821. WhereLevel *pLevel = pWInfo->a + iLoop;
  107822. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  107823. pLevel->iFrom = pWLoop->iTab;
  107824. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  107825. }
  107826. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  107827. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  107828. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  107829. && nRowEst
  107830. ){
  107831. Bitmask notUsed;
  107832. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  107833. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  107834. if( rc==1 ) pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  107835. }
  107836. if( pFrom->isOrdered ){
  107837. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  107838. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  107839. }else{
  107840. pWInfo->bOBSat = 1;
  107841. pWInfo->revMask = pFrom->revLoop;
  107842. }
  107843. }
  107844. pWInfo->nRowOut = pFrom->nRow;
  107845. /* Free temporary memory and return success */
  107846. sqlite3DbFree(db, pSpace);
  107847. return SQLITE_OK;
  107848. }
  107849. /*
  107850. ** Most queries use only a single table (they are not joins) and have
  107851. ** simple == constraints against indexed fields. This routine attempts
  107852. ** to plan those simple cases using much less ceremony than the
  107853. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  107854. ** times for the common case.
  107855. **
  107856. ** Return non-zero on success, if this query can be handled by this
  107857. ** no-frills query planner. Return zero if this query needs the
  107858. ** general-purpose query planner.
  107859. */
  107860. static int whereShortCut(WhereLoopBuilder *pBuilder){
  107861. WhereInfo *pWInfo;
  107862. struct SrcList_item *pItem;
  107863. WhereClause *pWC;
  107864. WhereTerm *pTerm;
  107865. WhereLoop *pLoop;
  107866. int iCur;
  107867. int j;
  107868. Table *pTab;
  107869. Index *pIdx;
  107870. pWInfo = pBuilder->pWInfo;
  107871. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  107872. assert( pWInfo->pTabList->nSrc>=1 );
  107873. pItem = pWInfo->pTabList->a;
  107874. pTab = pItem->pTab;
  107875. if( IsVirtual(pTab) ) return 0;
  107876. if( pItem->zIndex ) return 0;
  107877. iCur = pItem->iCursor;
  107878. pWC = &pWInfo->sWC;
  107879. pLoop = pBuilder->pNew;
  107880. pLoop->wsFlags = 0;
  107881. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  107882. if( pTerm ){
  107883. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  107884. pLoop->aLTerm[0] = pTerm;
  107885. pLoop->nLTerm = 1;
  107886. pLoop->u.btree.nEq = 1;
  107887. /* TUNING: Cost of a rowid lookup is 10 */
  107888. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  107889. }else{
  107890. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107891. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  107892. assert( ArraySize(pLoop->aLTermSpace)==4 );
  107893. if( pIdx->onError==OE_None
  107894. || pIdx->pPartIdxWhere!=0
  107895. || pIdx->nColumn>ArraySize(pLoop->aLTermSpace)
  107896. ) continue;
  107897. for(j=0; j<pIdx->nColumn; j++){
  107898. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  107899. if( pTerm==0 ) break;
  107900. pLoop->aLTerm[j] = pTerm;
  107901. }
  107902. if( j!=pIdx->nColumn ) continue;
  107903. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  107904. if( (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  107905. pLoop->wsFlags |= WHERE_IDX_ONLY;
  107906. }
  107907. pLoop->nLTerm = j;
  107908. pLoop->u.btree.nEq = j;
  107909. pLoop->u.btree.pIndex = pIdx;
  107910. /* TUNING: Cost of a unique index lookup is 15 */
  107911. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  107912. break;
  107913. }
  107914. }
  107915. if( pLoop->wsFlags ){
  107916. pLoop->nOut = (LogEst)1;
  107917. pWInfo->a[0].pWLoop = pLoop;
  107918. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  107919. pWInfo->a[0].iTabCur = iCur;
  107920. pWInfo->nRowOut = 1;
  107921. if( pWInfo->pOrderBy ) pWInfo->bOBSat = 1;
  107922. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  107923. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  107924. }
  107925. #ifdef SQLITE_DEBUG
  107926. pLoop->cId = '0';
  107927. #endif
  107928. return 1;
  107929. }
  107930. return 0;
  107931. }
  107932. /*
  107933. ** Generate the beginning of the loop used for WHERE clause processing.
  107934. ** The return value is a pointer to an opaque structure that contains
  107935. ** information needed to terminate the loop. Later, the calling routine
  107936. ** should invoke sqlite3WhereEnd() with the return value of this function
  107937. ** in order to complete the WHERE clause processing.
  107938. **
  107939. ** If an error occurs, this routine returns NULL.
  107940. **
  107941. ** The basic idea is to do a nested loop, one loop for each table in
  107942. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  107943. ** same as a SELECT with only a single table in the FROM clause.) For
  107944. ** example, if the SQL is this:
  107945. **
  107946. ** SELECT * FROM t1, t2, t3 WHERE ...;
  107947. **
  107948. ** Then the code generated is conceptually like the following:
  107949. **
  107950. ** foreach row1 in t1 do \ Code generated
  107951. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  107952. ** foreach row3 in t3 do /
  107953. ** ...
  107954. ** end \ Code generated
  107955. ** end |-- by sqlite3WhereEnd()
  107956. ** end /
  107957. **
  107958. ** Note that the loops might not be nested in the order in which they
  107959. ** appear in the FROM clause if a different order is better able to make
  107960. ** use of indices. Note also that when the IN operator appears in
  107961. ** the WHERE clause, it might result in additional nested loops for
  107962. ** scanning through all values on the right-hand side of the IN.
  107963. **
  107964. ** There are Btree cursors associated with each table. t1 uses cursor
  107965. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  107966. ** And so forth. This routine generates code to open those VDBE cursors
  107967. ** and sqlite3WhereEnd() generates the code to close them.
  107968. **
  107969. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  107970. ** in pTabList pointing at their appropriate entries. The [...] code
  107971. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  107972. ** data from the various tables of the loop.
  107973. **
  107974. ** If the WHERE clause is empty, the foreach loops must each scan their
  107975. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  107976. ** the tables have indices and there are terms in the WHERE clause that
  107977. ** refer to those indices, a complete table scan can be avoided and the
  107978. ** code will run much faster. Most of the work of this routine is checking
  107979. ** to see if there are indices that can be used to speed up the loop.
  107980. **
  107981. ** Terms of the WHERE clause are also used to limit which rows actually
  107982. ** make it to the "..." in the middle of the loop. After each "foreach",
  107983. ** terms of the WHERE clause that use only terms in that loop and outer
  107984. ** loops are evaluated and if false a jump is made around all subsequent
  107985. ** inner loops (or around the "..." if the test occurs within the inner-
  107986. ** most loop)
  107987. **
  107988. ** OUTER JOINS
  107989. **
  107990. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  107991. **
  107992. ** foreach row1 in t1 do
  107993. ** flag = 0
  107994. ** foreach row2 in t2 do
  107995. ** start:
  107996. ** ...
  107997. ** flag = 1
  107998. ** end
  107999. ** if flag==0 then
  108000. ** move the row2 cursor to a null row
  108001. ** goto start
  108002. ** fi
  108003. ** end
  108004. **
  108005. ** ORDER BY CLAUSE PROCESSING
  108006. **
  108007. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  108008. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  108009. ** if there is one. If there is no ORDER BY clause or if this routine
  108010. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  108011. */
  108012. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  108013. Parse *pParse, /* The parser context */
  108014. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  108015. Expr *pWhere, /* The WHERE clause */
  108016. ExprList *pOrderBy, /* An ORDER BY clause, or NULL */
  108017. ExprList *pResultSet, /* Result set of the query */
  108018. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  108019. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  108020. ){
  108021. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  108022. int nTabList; /* Number of elements in pTabList */
  108023. WhereInfo *pWInfo; /* Will become the return value of this function */
  108024. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  108025. Bitmask notReady; /* Cursors that are not yet positioned */
  108026. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  108027. WhereMaskSet *pMaskSet; /* The expression mask set */
  108028. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  108029. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  108030. int ii; /* Loop counter */
  108031. sqlite3 *db; /* Database connection */
  108032. int rc; /* Return code */
  108033. /* Variable initialization */
  108034. db = pParse->db;
  108035. memset(&sWLB, 0, sizeof(sWLB));
  108036. sWLB.pOrderBy = pOrderBy;
  108037. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  108038. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  108039. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  108040. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  108041. }
  108042. /* The number of tables in the FROM clause is limited by the number of
  108043. ** bits in a Bitmask
  108044. */
  108045. testcase( pTabList->nSrc==BMS );
  108046. if( pTabList->nSrc>BMS ){
  108047. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  108048. return 0;
  108049. }
  108050. /* This function normally generates a nested loop for all tables in
  108051. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  108052. ** only generate code for the first table in pTabList and assume that
  108053. ** any cursors associated with subsequent tables are uninitialized.
  108054. */
  108055. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  108056. /* Allocate and initialize the WhereInfo structure that will become the
  108057. ** return value. A single allocation is used to store the WhereInfo
  108058. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  108059. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  108060. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  108061. ** some architectures. Hence the ROUND8() below.
  108062. */
  108063. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  108064. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  108065. if( db->mallocFailed ){
  108066. sqlite3DbFree(db, pWInfo);
  108067. pWInfo = 0;
  108068. goto whereBeginError;
  108069. }
  108070. pWInfo->nLevel = nTabList;
  108071. pWInfo->pParse = pParse;
  108072. pWInfo->pTabList = pTabList;
  108073. pWInfo->pOrderBy = pOrderBy;
  108074. pWInfo->pResultSet = pResultSet;
  108075. pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
  108076. pWInfo->wctrlFlags = wctrlFlags;
  108077. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  108078. pMaskSet = &pWInfo->sMaskSet;
  108079. sWLB.pWInfo = pWInfo;
  108080. sWLB.pWC = &pWInfo->sWC;
  108081. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  108082. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  108083. whereLoopInit(sWLB.pNew);
  108084. #ifdef SQLITE_DEBUG
  108085. sWLB.pNew->cId = '*';
  108086. #endif
  108087. /* Split the WHERE clause into separate subexpressions where each
  108088. ** subexpression is separated by an AND operator.
  108089. */
  108090. initMaskSet(pMaskSet);
  108091. whereClauseInit(&pWInfo->sWC, pWInfo);
  108092. sqlite3ExprCodeConstants(pParse, pWhere);
  108093. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  108094. sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
  108095. /* Special case: a WHERE clause that is constant. Evaluate the
  108096. ** expression and either jump over all of the code or fall thru.
  108097. */
  108098. if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
  108099. sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
  108100. pWhere = 0;
  108101. }
  108102. /* Special case: No FROM clause
  108103. */
  108104. if( nTabList==0 ){
  108105. if( pOrderBy ) pWInfo->bOBSat = 1;
  108106. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  108107. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  108108. }
  108109. }
  108110. /* Assign a bit from the bitmask to every term in the FROM clause.
  108111. **
  108112. ** When assigning bitmask values to FROM clause cursors, it must be
  108113. ** the case that if X is the bitmask for the N-th FROM clause term then
  108114. ** the bitmask for all FROM clause terms to the left of the N-th term
  108115. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  108116. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  108117. ** of the join. Subtracting one from the right table bitmask gives a
  108118. ** bitmask for all tables to the left of the join. Knowing the bitmask
  108119. ** for all tables to the left of a left join is important. Ticket #3015.
  108120. **
  108121. ** Note that bitmasks are created for all pTabList->nSrc tables in
  108122. ** pTabList, not just the first nTabList tables. nTabList is normally
  108123. ** equal to pTabList->nSrc but might be shortened to 1 if the
  108124. ** WHERE_ONETABLE_ONLY flag is set.
  108125. */
  108126. for(ii=0; ii<pTabList->nSrc; ii++){
  108127. createMask(pMaskSet, pTabList->a[ii].iCursor);
  108128. }
  108129. #ifndef NDEBUG
  108130. {
  108131. Bitmask toTheLeft = 0;
  108132. for(ii=0; ii<pTabList->nSrc; ii++){
  108133. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  108134. assert( (m-1)==toTheLeft );
  108135. toTheLeft |= m;
  108136. }
  108137. }
  108138. #endif
  108139. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  108140. ** add new virtual terms onto the end of the WHERE clause. We do not
  108141. ** want to analyze these virtual terms, so start analyzing at the end
  108142. ** and work forward so that the added virtual terms are never processed.
  108143. */
  108144. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  108145. if( db->mallocFailed ){
  108146. goto whereBeginError;
  108147. }
  108148. /* If the ORDER BY (or GROUP BY) clause contains references to general
  108149. ** expressions, then we won't be able to satisfy it using indices, so
  108150. ** go ahead and disable it now.
  108151. */
  108152. if( pOrderBy && (wctrlFlags & WHERE_WANT_DISTINCT)!=0 ){
  108153. for(ii=0; ii<pOrderBy->nExpr; ii++){
  108154. Expr *pExpr = sqlite3ExprSkipCollate(pOrderBy->a[ii].pExpr);
  108155. if( pExpr->op!=TK_COLUMN ){
  108156. pWInfo->pOrderBy = pOrderBy = 0;
  108157. break;
  108158. }else if( pExpr->iColumn<0 ){
  108159. break;
  108160. }
  108161. }
  108162. }
  108163. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  108164. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  108165. /* The DISTINCT marking is pointless. Ignore it. */
  108166. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  108167. }else if( pOrderBy==0 ){
  108168. /* Try to ORDER BY the result set to make distinct processing easier */
  108169. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  108170. pWInfo->pOrderBy = pResultSet;
  108171. }
  108172. }
  108173. /* Construct the WhereLoop objects */
  108174. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  108175. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  108176. rc = whereLoopAddAll(&sWLB);
  108177. if( rc ) goto whereBeginError;
  108178. /* Display all of the WhereLoop objects if wheretrace is enabled */
  108179. #ifdef WHERETRACE_ENABLED
  108180. if( sqlite3WhereTrace ){
  108181. WhereLoop *p;
  108182. int i;
  108183. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  108184. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  108185. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  108186. p->cId = zLabel[i%sizeof(zLabel)];
  108187. whereLoopPrint(p, pTabList);
  108188. }
  108189. }
  108190. #endif
  108191. wherePathSolver(pWInfo, 0);
  108192. if( db->mallocFailed ) goto whereBeginError;
  108193. if( pWInfo->pOrderBy ){
  108194. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  108195. if( db->mallocFailed ) goto whereBeginError;
  108196. }
  108197. }
  108198. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  108199. pWInfo->revMask = (Bitmask)(-1);
  108200. }
  108201. if( pParse->nErr || NEVER(db->mallocFailed) ){
  108202. goto whereBeginError;
  108203. }
  108204. #ifdef WHERETRACE_ENABLED
  108205. if( sqlite3WhereTrace ){
  108206. int ii;
  108207. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  108208. if( pWInfo->bOBSat ){
  108209. sqlite3DebugPrintf(" ORDERBY=0x%llx", pWInfo->revMask);
  108210. }
  108211. switch( pWInfo->eDistinct ){
  108212. case WHERE_DISTINCT_UNIQUE: {
  108213. sqlite3DebugPrintf(" DISTINCT=unique");
  108214. break;
  108215. }
  108216. case WHERE_DISTINCT_ORDERED: {
  108217. sqlite3DebugPrintf(" DISTINCT=ordered");
  108218. break;
  108219. }
  108220. case WHERE_DISTINCT_UNORDERED: {
  108221. sqlite3DebugPrintf(" DISTINCT=unordered");
  108222. break;
  108223. }
  108224. }
  108225. sqlite3DebugPrintf("\n");
  108226. for(ii=0; ii<pWInfo->nLevel; ii++){
  108227. whereLoopPrint(pWInfo->a[ii].pWLoop, pTabList);
  108228. }
  108229. }
  108230. #endif
  108231. /* Attempt to omit tables from the join that do not effect the result */
  108232. if( pWInfo->nLevel>=2
  108233. && pResultSet!=0
  108234. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  108235. ){
  108236. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  108237. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  108238. while( pWInfo->nLevel>=2 ){
  108239. WhereTerm *pTerm, *pEnd;
  108240. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  108241. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  108242. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  108243. && (pLoop->wsFlags & WHERE_ONEROW)==0
  108244. ){
  108245. break;
  108246. }
  108247. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  108248. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  108249. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  108250. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  108251. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  108252. ){
  108253. break;
  108254. }
  108255. }
  108256. if( pTerm<pEnd ) break;
  108257. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  108258. pWInfo->nLevel--;
  108259. nTabList--;
  108260. }
  108261. }
  108262. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  108263. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  108264. /* If the caller is an UPDATE or DELETE statement that is requesting
  108265. ** to use a one-pass algorithm, determine if this is appropriate.
  108266. ** The one-pass algorithm only works if the WHERE clause constrains
  108267. ** the statement to update a single row.
  108268. */
  108269. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  108270. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  108271. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  108272. pWInfo->okOnePass = 1;
  108273. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  108274. }
  108275. /* Open all tables in the pTabList and any indices selected for
  108276. ** searching those tables.
  108277. */
  108278. notReady = ~(Bitmask)0;
  108279. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  108280. Table *pTab; /* Table to open */
  108281. int iDb; /* Index of database containing table/index */
  108282. struct SrcList_item *pTabItem;
  108283. pTabItem = &pTabList->a[pLevel->iFrom];
  108284. pTab = pTabItem->pTab;
  108285. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  108286. pLoop = pLevel->pWLoop;
  108287. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  108288. /* Do nothing */
  108289. }else
  108290. #ifndef SQLITE_OMIT_VIRTUALTABLE
  108291. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  108292. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  108293. int iCur = pTabItem->iCursor;
  108294. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  108295. }else if( IsVirtual(pTab) ){
  108296. /* noop */
  108297. }else
  108298. #endif
  108299. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  108300. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  108301. int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
  108302. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  108303. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  108304. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  108305. if( !pWInfo->okOnePass && pTab->nCol<BMS ){
  108306. Bitmask b = pTabItem->colUsed;
  108307. int n = 0;
  108308. for(; b; b=b>>1, n++){}
  108309. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  108310. SQLITE_INT_TO_PTR(n), P4_INT32);
  108311. assert( n<=pTab->nCol );
  108312. }
  108313. }else{
  108314. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  108315. }
  108316. if( pLoop->wsFlags & WHERE_INDEXED ){
  108317. Index *pIx = pLoop->u.btree.pIndex;
  108318. KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
  108319. /* FIXME: As an optimization use pTabItem->iCursor if WHERE_IDX_ONLY */
  108320. int iIndexCur = pLevel->iIdxCur = iIdxCur ? iIdxCur : pParse->nTab++;
  108321. assert( pIx->pSchema==pTab->pSchema );
  108322. assert( iIndexCur>=0 );
  108323. sqlite3VdbeAddOp4(v, OP_OpenRead, iIndexCur, pIx->tnum, iDb,
  108324. (char*)pKey, P4_KEYINFO_HANDOFF);
  108325. VdbeComment((v, "%s", pIx->zName));
  108326. }
  108327. sqlite3CodeVerifySchema(pParse, iDb);
  108328. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  108329. }
  108330. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  108331. if( db->mallocFailed ) goto whereBeginError;
  108332. /* Generate the code to do the search. Each iteration of the for
  108333. ** loop below generates code for a single nested loop of the VM
  108334. ** program.
  108335. */
  108336. notReady = ~(Bitmask)0;
  108337. for(ii=0; ii<nTabList; ii++){
  108338. pLevel = &pWInfo->a[ii];
  108339. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  108340. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  108341. constructAutomaticIndex(pParse, &pWInfo->sWC,
  108342. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  108343. if( db->mallocFailed ) goto whereBeginError;
  108344. }
  108345. #endif
  108346. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  108347. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  108348. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  108349. pWInfo->iContinue = pLevel->addrCont;
  108350. }
  108351. /* Done. */
  108352. return pWInfo;
  108353. /* Jump here if malloc fails */
  108354. whereBeginError:
  108355. if( pWInfo ){
  108356. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  108357. whereInfoFree(db, pWInfo);
  108358. }
  108359. return 0;
  108360. }
  108361. /*
  108362. ** Generate the end of the WHERE loop. See comments on
  108363. ** sqlite3WhereBegin() for additional information.
  108364. */
  108365. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  108366. Parse *pParse = pWInfo->pParse;
  108367. Vdbe *v = pParse->pVdbe;
  108368. int i;
  108369. WhereLevel *pLevel;
  108370. WhereLoop *pLoop;
  108371. SrcList *pTabList = pWInfo->pTabList;
  108372. sqlite3 *db = pParse->db;
  108373. /* Generate loop termination code.
  108374. */
  108375. sqlite3ExprCacheClear(pParse);
  108376. for(i=pWInfo->nLevel-1; i>=0; i--){
  108377. pLevel = &pWInfo->a[i];
  108378. pLoop = pLevel->pWLoop;
  108379. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  108380. if( pLevel->op!=OP_Noop ){
  108381. sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
  108382. sqlite3VdbeChangeP5(v, pLevel->p5);
  108383. }
  108384. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  108385. struct InLoop *pIn;
  108386. int j;
  108387. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  108388. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  108389. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  108390. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  108391. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  108392. }
  108393. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  108394. }
  108395. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  108396. if( pLevel->iLeftJoin ){
  108397. int addr;
  108398. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
  108399. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  108400. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  108401. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  108402. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  108403. }
  108404. if( pLoop->wsFlags & WHERE_INDEXED ){
  108405. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  108406. }
  108407. if( pLevel->op==OP_Return ){
  108408. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  108409. }else{
  108410. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  108411. }
  108412. sqlite3VdbeJumpHere(v, addr);
  108413. }
  108414. }
  108415. /* The "break" point is here, just past the end of the outer loop.
  108416. ** Set it.
  108417. */
  108418. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  108419. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  108420. */
  108421. assert( pWInfo->nLevel<=pTabList->nSrc );
  108422. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  108423. Index *pIdx = 0;
  108424. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  108425. Table *pTab = pTabItem->pTab;
  108426. assert( pTab!=0 );
  108427. pLoop = pLevel->pWLoop;
  108428. if( (pTab->tabFlags & TF_Ephemeral)==0
  108429. && pTab->pSelect==0
  108430. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  108431. ){
  108432. int ws = pLoop->wsFlags;
  108433. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  108434. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  108435. }
  108436. if( (ws & WHERE_INDEXED)!=0 && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 ){
  108437. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  108438. }
  108439. }
  108440. /* If this scan uses an index, make VDBE code substitutions to read data
  108441. ** from the index instead of from the table where possible. In some cases
  108442. ** this optimization prevents the table from ever being read, which can
  108443. ** yield a significant performance boost.
  108444. **
  108445. ** Calls to the code generator in between sqlite3WhereBegin and
  108446. ** sqlite3WhereEnd will have created code that references the table
  108447. ** directly. This loop scans all that code looking for opcodes
  108448. ** that reference the table and converts them into opcodes that
  108449. ** reference the index.
  108450. */
  108451. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  108452. pIdx = pLoop->u.btree.pIndex;
  108453. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  108454. pIdx = pLevel->u.pCovidx;
  108455. }
  108456. if( pIdx && !db->mallocFailed ){
  108457. int k, j, last;
  108458. VdbeOp *pOp;
  108459. last = sqlite3VdbeCurrentAddr(v);
  108460. k = pLevel->addrBody;
  108461. pOp = sqlite3VdbeGetOp(v, k);
  108462. for(; k<last; k++, pOp++){
  108463. if( pOp->p1!=pLevel->iTabCur ) continue;
  108464. if( pOp->opcode==OP_Column ){
  108465. for(j=0; j<pIdx->nColumn; j++){
  108466. if( pOp->p2==pIdx->aiColumn[j] ){
  108467. pOp->p2 = j;
  108468. pOp->p1 = pLevel->iIdxCur;
  108469. break;
  108470. }
  108471. }
  108472. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || j<pIdx->nColumn );
  108473. }else if( pOp->opcode==OP_Rowid ){
  108474. pOp->p1 = pLevel->iIdxCur;
  108475. pOp->opcode = OP_IdxRowid;
  108476. }
  108477. }
  108478. }
  108479. }
  108480. /* Final cleanup
  108481. */
  108482. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  108483. whereInfoFree(db, pWInfo);
  108484. return;
  108485. }
  108486. /************** End of where.c ***********************************************/
  108487. /************** Begin file parse.c *******************************************/
  108488. /* Driver template for the LEMON parser generator.
  108489. ** The author disclaims copyright to this source code.
  108490. **
  108491. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  108492. ** The only modifications are the addition of a couple of NEVER()
  108493. ** macros to disable tests that are needed in the case of a general
  108494. ** LALR(1) grammar but which are always false in the
  108495. ** specific grammar used by SQLite.
  108496. */
  108497. /* First off, code is included that follows the "include" declaration
  108498. ** in the input grammar file. */
  108499. /* #include <stdio.h> */
  108500. /*
  108501. ** Disable all error recovery processing in the parser push-down
  108502. ** automaton.
  108503. */
  108504. #define YYNOERRORRECOVERY 1
  108505. /*
  108506. ** Make yytestcase() the same as testcase()
  108507. */
  108508. #define yytestcase(X) testcase(X)
  108509. /*
  108510. ** An instance of this structure holds information about the
  108511. ** LIMIT clause of a SELECT statement.
  108512. */
  108513. struct LimitVal {
  108514. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  108515. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  108516. };
  108517. /*
  108518. ** An instance of this structure is used to store the LIKE,
  108519. ** GLOB, NOT LIKE, and NOT GLOB operators.
  108520. */
  108521. struct LikeOp {
  108522. Token eOperator; /* "like" or "glob" or "regexp" */
  108523. int bNot; /* True if the NOT keyword is present */
  108524. };
  108525. /*
  108526. ** An instance of the following structure describes the event of a
  108527. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  108528. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  108529. **
  108530. ** UPDATE ON (a,b,c)
  108531. **
  108532. ** Then the "b" IdList records the list "a,b,c".
  108533. */
  108534. struct TrigEvent { int a; IdList * b; };
  108535. /*
  108536. ** An instance of this structure holds the ATTACH key and the key type.
  108537. */
  108538. struct AttachKey { int type; Token key; };
  108539. /*
  108540. ** One or more VALUES claues
  108541. */
  108542. struct ValueList {
  108543. ExprList *pList;
  108544. Select *pSelect;
  108545. };
  108546. /* This is a utility routine used to set the ExprSpan.zStart and
  108547. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  108548. ** range of text beginning with pStart and going to the end of pEnd.
  108549. */
  108550. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  108551. pOut->zStart = pStart->z;
  108552. pOut->zEnd = &pEnd->z[pEnd->n];
  108553. }
  108554. /* Construct a new Expr object from a single identifier. Use the
  108555. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  108556. ** that created the expression.
  108557. */
  108558. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  108559. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  108560. pOut->zStart = pValue->z;
  108561. pOut->zEnd = &pValue->z[pValue->n];
  108562. }
  108563. /* This routine constructs a binary expression node out of two ExprSpan
  108564. ** objects and uses the result to populate a new ExprSpan object.
  108565. */
  108566. static void spanBinaryExpr(
  108567. ExprSpan *pOut, /* Write the result here */
  108568. Parse *pParse, /* The parsing context. Errors accumulate here */
  108569. int op, /* The binary operation */
  108570. ExprSpan *pLeft, /* The left operand */
  108571. ExprSpan *pRight /* The right operand */
  108572. ){
  108573. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  108574. pOut->zStart = pLeft->zStart;
  108575. pOut->zEnd = pRight->zEnd;
  108576. }
  108577. /* Construct an expression node for a unary postfix operator
  108578. */
  108579. static void spanUnaryPostfix(
  108580. ExprSpan *pOut, /* Write the new expression node here */
  108581. Parse *pParse, /* Parsing context to record errors */
  108582. int op, /* The operator */
  108583. ExprSpan *pOperand, /* The operand */
  108584. Token *pPostOp /* The operand token for setting the span */
  108585. ){
  108586. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  108587. pOut->zStart = pOperand->zStart;
  108588. pOut->zEnd = &pPostOp->z[pPostOp->n];
  108589. }
  108590. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  108591. ** unary TK_ISNULL or TK_NOTNULL expression. */
  108592. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  108593. sqlite3 *db = pParse->db;
  108594. if( db->mallocFailed==0 && pY->op==TK_NULL ){
  108595. pA->op = (u8)op;
  108596. sqlite3ExprDelete(db, pA->pRight);
  108597. pA->pRight = 0;
  108598. }
  108599. }
  108600. /* Construct an expression node for a unary prefix operator
  108601. */
  108602. static void spanUnaryPrefix(
  108603. ExprSpan *pOut, /* Write the new expression node here */
  108604. Parse *pParse, /* Parsing context to record errors */
  108605. int op, /* The operator */
  108606. ExprSpan *pOperand, /* The operand */
  108607. Token *pPreOp /* The operand token for setting the span */
  108608. ){
  108609. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  108610. pOut->zStart = pPreOp->z;
  108611. pOut->zEnd = pOperand->zEnd;
  108612. }
  108613. /* Next is all token values, in a form suitable for use by makeheaders.
  108614. ** This section will be null unless lemon is run with the -m switch.
  108615. */
  108616. /*
  108617. ** These constants (all generated automatically by the parser generator)
  108618. ** specify the various kinds of tokens (terminals) that the parser
  108619. ** understands.
  108620. **
  108621. ** Each symbol here is a terminal symbol in the grammar.
  108622. */
  108623. /* Make sure the INTERFACE macro is defined.
  108624. */
  108625. #ifndef INTERFACE
  108626. # define INTERFACE 1
  108627. #endif
  108628. /* The next thing included is series of defines which control
  108629. ** various aspects of the generated parser.
  108630. ** YYCODETYPE is the data type used for storing terminal
  108631. ** and nonterminal numbers. "unsigned char" is
  108632. ** used if there are fewer than 250 terminals
  108633. ** and nonterminals. "int" is used otherwise.
  108634. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  108635. ** to no legal terminal or nonterminal number. This
  108636. ** number is used to fill in empty slots of the hash
  108637. ** table.
  108638. ** YYFALLBACK If defined, this indicates that one or more tokens
  108639. ** have fall-back values which should be used if the
  108640. ** original value of the token will not parse.
  108641. ** YYACTIONTYPE is the data type used for storing terminal
  108642. ** and nonterminal numbers. "unsigned char" is
  108643. ** used if there are fewer than 250 rules and
  108644. ** states combined. "int" is used otherwise.
  108645. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  108646. ** directly to the parser from the tokenizer.
  108647. ** YYMINORTYPE is the data type used for all minor tokens.
  108648. ** This is typically a union of many types, one of
  108649. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  108650. ** for base tokens is called "yy0".
  108651. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  108652. ** zero the stack is dynamically sized using realloc()
  108653. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  108654. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  108655. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  108656. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  108657. ** YYNSTATE the combined number of states.
  108658. ** YYNRULE the number of rules in the grammar
  108659. ** YYERRORSYMBOL is the code number of the error symbol. If not
  108660. ** defined, then do no error processing.
  108661. */
  108662. #define YYCODETYPE unsigned char
  108663. #define YYNOCODE 251
  108664. #define YYACTIONTYPE unsigned short int
  108665. #define YYWILDCARD 67
  108666. #define sqlite3ParserTOKENTYPE Token
  108667. typedef union {
  108668. int yyinit;
  108669. sqlite3ParserTOKENTYPE yy0;
  108670. struct LimitVal yy64;
  108671. Expr* yy122;
  108672. Select* yy159;
  108673. IdList* yy180;
  108674. struct {int value; int mask;} yy207;
  108675. u8 yy258;
  108676. u16 yy305;
  108677. struct LikeOp yy318;
  108678. TriggerStep* yy327;
  108679. ExprSpan yy342;
  108680. SrcList* yy347;
  108681. int yy392;
  108682. struct TrigEvent yy410;
  108683. ExprList* yy442;
  108684. struct ValueList yy487;
  108685. } YYMINORTYPE;
  108686. #ifndef YYSTACKDEPTH
  108687. #define YYSTACKDEPTH 100
  108688. #endif
  108689. #define sqlite3ParserARG_SDECL Parse *pParse;
  108690. #define sqlite3ParserARG_PDECL ,Parse *pParse
  108691. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  108692. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  108693. #define YYNSTATE 628
  108694. #define YYNRULE 327
  108695. #define YYFALLBACK 1
  108696. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  108697. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  108698. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  108699. /* The yyzerominor constant is used to initialize instances of
  108700. ** YYMINORTYPE objects to zero. */
  108701. static const YYMINORTYPE yyzerominor = { 0 };
  108702. /* Define the yytestcase() macro to be a no-op if is not already defined
  108703. ** otherwise.
  108704. **
  108705. ** Applications can choose to define yytestcase() in the %include section
  108706. ** to a macro that can assist in verifying code coverage. For production
  108707. ** code the yytestcase() macro should be turned off. But it is useful
  108708. ** for testing.
  108709. */
  108710. #ifndef yytestcase
  108711. # define yytestcase(X)
  108712. #endif
  108713. /* Next are the tables used to determine what action to take based on the
  108714. ** current state and lookahead token. These tables are used to implement
  108715. ** functions that take a state number and lookahead value and return an
  108716. ** action integer.
  108717. **
  108718. ** Suppose the action integer is N. Then the action is determined as
  108719. ** follows
  108720. **
  108721. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  108722. ** token onto the stack and goto state N.
  108723. **
  108724. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  108725. **
  108726. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  108727. **
  108728. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  108729. **
  108730. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  108731. ** slots in the yy_action[] table.
  108732. **
  108733. ** The action table is constructed as a single large table named yy_action[].
  108734. ** Given state S and lookahead X, the action is computed as
  108735. **
  108736. ** yy_action[ yy_shift_ofst[S] + X ]
  108737. **
  108738. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  108739. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  108740. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  108741. ** and that yy_default[S] should be used instead.
  108742. **
  108743. ** The formula above is for computing the action when the lookahead is
  108744. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  108745. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  108746. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  108747. ** YY_SHIFT_USE_DFLT.
  108748. **
  108749. ** The following are the tables generated in this section:
  108750. **
  108751. ** yy_action[] A single table containing all actions.
  108752. ** yy_lookahead[] A table containing the lookahead for each entry in
  108753. ** yy_action. Used to detect hash collisions.
  108754. ** yy_shift_ofst[] For each state, the offset into yy_action for
  108755. ** shifting terminals.
  108756. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  108757. ** shifting non-terminals after a reduce.
  108758. ** yy_default[] Default action for each state.
  108759. */
  108760. #define YY_ACTTAB_COUNT (1564)
  108761. static const YYACTIONTYPE yy_action[] = {
  108762. /* 0 */ 310, 956, 184, 418, 2, 171, 625, 595, 56, 56,
  108763. /* 10 */ 56, 56, 49, 54, 54, 54, 54, 53, 53, 52,
  108764. /* 20 */ 52, 52, 51, 233, 621, 620, 299, 621, 620, 234,
  108765. /* 30 */ 588, 582, 56, 56, 56, 56, 19, 54, 54, 54,
  108766. /* 40 */ 54, 53, 53, 52, 52, 52, 51, 233, 606, 57,
  108767. /* 50 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108768. /* 60 */ 56, 56, 542, 54, 54, 54, 54, 53, 53, 52,
  108769. /* 70 */ 52, 52, 51, 233, 310, 595, 326, 196, 195, 194,
  108770. /* 80 */ 33, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108771. /* 90 */ 51, 233, 618, 617, 165, 618, 617, 381, 378, 377,
  108772. /* 100 */ 408, 533, 577, 577, 588, 582, 304, 423, 376, 59,
  108773. /* 110 */ 53, 53, 52, 52, 52, 51, 233, 50, 47, 146,
  108774. /* 120 */ 575, 546, 65, 57, 58, 48, 580, 579, 581, 581,
  108775. /* 130 */ 55, 55, 56, 56, 56, 56, 213, 54, 54, 54,
  108776. /* 140 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 223,
  108777. /* 150 */ 540, 421, 170, 176, 138, 281, 384, 276, 383, 168,
  108778. /* 160 */ 490, 552, 410, 669, 621, 620, 272, 439, 410, 439,
  108779. /* 170 */ 551, 605, 67, 483, 508, 619, 600, 413, 588, 582,
  108780. /* 180 */ 601, 484, 619, 413, 619, 599, 91, 440, 441, 440,
  108781. /* 190 */ 336, 599, 73, 670, 222, 267, 481, 57, 58, 48,
  108782. /* 200 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108783. /* 210 */ 671, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108784. /* 220 */ 51, 233, 310, 280, 232, 231, 1, 132, 200, 386,
  108785. /* 230 */ 621, 620, 618, 617, 279, 436, 290, 564, 175, 263,
  108786. /* 240 */ 410, 265, 438, 498, 437, 166, 442, 569, 337, 569,
  108787. /* 250 */ 201, 538, 588, 582, 600, 413, 165, 595, 601, 381,
  108788. /* 260 */ 378, 377, 598, 599, 92, 524, 619, 570, 570, 593,
  108789. /* 270 */ 376, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  108790. /* 280 */ 56, 56, 56, 56, 598, 54, 54, 54, 54, 53,
  108791. /* 290 */ 53, 52, 52, 52, 51, 233, 310, 464, 618, 617,
  108792. /* 300 */ 591, 591, 591, 174, 273, 397, 410, 273, 410, 549,
  108793. /* 310 */ 398, 621, 620, 68, 327, 621, 620, 621, 620, 619,
  108794. /* 320 */ 547, 413, 619, 413, 472, 595, 588, 582, 473, 599,
  108795. /* 330 */ 92, 599, 92, 52, 52, 52, 51, 233, 514, 513,
  108796. /* 340 */ 206, 323, 364, 465, 221, 57, 58, 48, 580, 579,
  108797. /* 350 */ 581, 581, 55, 55, 56, 56, 56, 56, 530, 54,
  108798. /* 360 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108799. /* 370 */ 310, 397, 410, 397, 598, 373, 387, 531, 348, 618,
  108800. /* 380 */ 617, 576, 202, 618, 617, 618, 617, 413, 621, 620,
  108801. /* 390 */ 145, 255, 347, 254, 578, 599, 74, 352, 45, 490,
  108802. /* 400 */ 588, 582, 235, 189, 465, 545, 167, 297, 187, 470,
  108803. /* 410 */ 480, 67, 62, 39, 619, 547, 598, 346, 574, 57,
  108804. /* 420 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108805. /* 430 */ 56, 56, 6, 54, 54, 54, 54, 53, 53, 52,
  108806. /* 440 */ 52, 52, 51, 233, 310, 563, 559, 408, 529, 577,
  108807. /* 450 */ 577, 345, 255, 347, 254, 182, 618, 617, 504, 505,
  108808. /* 460 */ 315, 410, 558, 235, 166, 272, 410, 353, 565, 181,
  108809. /* 470 */ 408, 547, 577, 577, 588, 582, 413, 538, 557, 562,
  108810. /* 480 */ 518, 413, 619, 249, 599, 16, 7, 36, 468, 599,
  108811. /* 490 */ 92, 517, 619, 57, 58, 48, 580, 579, 581, 581,
  108812. /* 500 */ 55, 55, 56, 56, 56, 56, 542, 54, 54, 54,
  108813. /* 510 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 328,
  108814. /* 520 */ 573, 572, 526, 559, 561, 395, 872, 246, 410, 248,
  108815. /* 530 */ 171, 393, 595, 219, 408, 410, 577, 577, 503, 558,
  108816. /* 540 */ 365, 145, 511, 413, 408, 229, 577, 577, 588, 582,
  108817. /* 550 */ 413, 599, 92, 382, 270, 557, 166, 401, 599, 69,
  108818. /* 560 */ 502, 420, 946, 199, 946, 198, 547, 57, 58, 48,
  108819. /* 570 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108820. /* 580 */ 569, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108821. /* 590 */ 51, 233, 310, 318, 420, 945, 509, 945, 309, 598,
  108822. /* 600 */ 595, 566, 491, 212, 173, 247, 424, 616, 615, 614,
  108823. /* 610 */ 324, 197, 143, 406, 573, 572, 490, 66, 50, 47,
  108824. /* 620 */ 146, 595, 588, 582, 232, 231, 560, 428, 67, 556,
  108825. /* 630 */ 15, 619, 186, 544, 304, 422, 35, 206, 433, 424,
  108826. /* 640 */ 553, 57, 58, 48, 580, 579, 581, 581, 55, 55,
  108827. /* 650 */ 56, 56, 56, 56, 205, 54, 54, 54, 54, 53,
  108828. /* 660 */ 53, 52, 52, 52, 51, 233, 310, 570, 570, 261,
  108829. /* 670 */ 269, 598, 12, 374, 569, 166, 410, 314, 410, 421,
  108830. /* 680 */ 410, 474, 474, 366, 619, 50, 47, 146, 598, 595,
  108831. /* 690 */ 256, 413, 166, 413, 352, 413, 588, 582, 32, 599,
  108832. /* 700 */ 94, 599, 97, 599, 95, 628, 626, 330, 142, 50,
  108833. /* 710 */ 47, 146, 334, 350, 359, 57, 58, 48, 580, 579,
  108834. /* 720 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  108835. /* 730 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108836. /* 740 */ 310, 410, 389, 413, 410, 22, 566, 405, 212, 363,
  108837. /* 750 */ 390, 599, 104, 360, 410, 156, 413, 410, 604, 413,
  108838. /* 760 */ 538, 332, 570, 570, 599, 103, 494, 599, 105, 413,
  108839. /* 770 */ 588, 582, 413, 261, 550, 619, 11, 599, 106, 522,
  108840. /* 780 */ 599, 133, 169, 458, 457, 170, 35, 602, 619, 57,
  108841. /* 790 */ 58, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108842. /* 800 */ 56, 56, 410, 54, 54, 54, 54, 53, 53, 52,
  108843. /* 810 */ 52, 52, 51, 233, 310, 410, 260, 413, 410, 50,
  108844. /* 820 */ 47, 146, 358, 319, 356, 599, 134, 528, 353, 338,
  108845. /* 830 */ 413, 410, 357, 413, 358, 410, 358, 619, 599, 98,
  108846. /* 840 */ 129, 599, 102, 619, 588, 582, 413, 21, 235, 619,
  108847. /* 850 */ 413, 619, 211, 143, 599, 101, 30, 167, 599, 93,
  108848. /* 860 */ 351, 536, 203, 57, 58, 48, 580, 579, 581, 581,
  108849. /* 870 */ 55, 55, 56, 56, 56, 56, 410, 54, 54, 54,
  108850. /* 880 */ 54, 53, 53, 52, 52, 52, 51, 233, 310, 410,
  108851. /* 890 */ 527, 413, 410, 426, 215, 306, 598, 552, 141, 599,
  108852. /* 900 */ 100, 40, 410, 38, 413, 410, 551, 413, 410, 228,
  108853. /* 910 */ 220, 315, 599, 77, 501, 599, 96, 413, 588, 582,
  108854. /* 920 */ 413, 339, 253, 413, 218, 599, 137, 380, 599, 136,
  108855. /* 930 */ 28, 599, 135, 271, 716, 210, 482, 57, 58, 48,
  108856. /* 940 */ 580, 579, 581, 581, 55, 55, 56, 56, 56, 56,
  108857. /* 950 */ 410, 54, 54, 54, 54, 53, 53, 52, 52, 52,
  108858. /* 960 */ 51, 233, 310, 410, 273, 413, 410, 316, 147, 598,
  108859. /* 970 */ 273, 627, 2, 599, 76, 209, 410, 127, 413, 619,
  108860. /* 980 */ 126, 413, 410, 622, 235, 619, 599, 90, 375, 599,
  108861. /* 990 */ 89, 413, 588, 582, 27, 261, 351, 413, 619, 599,
  108862. /* 1000 */ 75, 322, 542, 542, 125, 599, 88, 321, 279, 598,
  108863. /* 1010 */ 619, 57, 46, 48, 580, 579, 581, 581, 55, 55,
  108864. /* 1020 */ 56, 56, 56, 56, 410, 54, 54, 54, 54, 53,
  108865. /* 1030 */ 53, 52, 52, 52, 51, 233, 310, 410, 451, 413,
  108866. /* 1040 */ 164, 285, 283, 273, 610, 425, 305, 599, 87, 371,
  108867. /* 1050 */ 410, 478, 413, 410, 609, 410, 608, 603, 619, 619,
  108868. /* 1060 */ 599, 99, 587, 586, 122, 413, 588, 582, 413, 619,
  108869. /* 1070 */ 413, 619, 619, 599, 86, 367, 599, 17, 599, 85,
  108870. /* 1080 */ 320, 185, 520, 519, 584, 583, 58, 48, 580, 579,
  108871. /* 1090 */ 581, 581, 55, 55, 56, 56, 56, 56, 410, 54,
  108872. /* 1100 */ 54, 54, 54, 53, 53, 52, 52, 52, 51, 233,
  108873. /* 1110 */ 310, 585, 410, 413, 410, 261, 261, 261, 409, 592,
  108874. /* 1120 */ 475, 599, 84, 170, 410, 467, 519, 413, 121, 413,
  108875. /* 1130 */ 619, 619, 619, 619, 619, 599, 83, 599, 72, 413,
  108876. /* 1140 */ 588, 582, 51, 233, 626, 330, 471, 599, 71, 258,
  108877. /* 1150 */ 159, 120, 14, 463, 157, 158, 117, 261, 449, 448,
  108878. /* 1160 */ 447, 48, 580, 579, 581, 581, 55, 55, 56, 56,
  108879. /* 1170 */ 56, 56, 619, 54, 54, 54, 54, 53, 53, 52,
  108880. /* 1180 */ 52, 52, 51, 233, 44, 404, 261, 3, 410, 460,
  108881. /* 1190 */ 261, 414, 620, 118, 399, 10, 25, 24, 555, 349,
  108882. /* 1200 */ 217, 619, 407, 413, 410, 619, 4, 44, 404, 619,
  108883. /* 1210 */ 3, 599, 82, 619, 414, 620, 456, 543, 115, 413,
  108884. /* 1220 */ 539, 402, 537, 275, 507, 407, 251, 599, 81, 216,
  108885. /* 1230 */ 274, 564, 619, 243, 454, 619, 154, 619, 619, 619,
  108886. /* 1240 */ 450, 417, 624, 110, 402, 619, 410, 236, 64, 123,
  108887. /* 1250 */ 488, 41, 42, 532, 564, 204, 410, 268, 43, 412,
  108888. /* 1260 */ 411, 413, 266, 593, 108, 619, 107, 435, 333, 599,
  108889. /* 1270 */ 80, 413, 619, 264, 41, 42, 444, 619, 410, 599,
  108890. /* 1280 */ 70, 43, 412, 411, 434, 262, 593, 149, 619, 598,
  108891. /* 1290 */ 257, 237, 188, 413, 591, 591, 591, 590, 589, 13,
  108892. /* 1300 */ 619, 599, 18, 329, 235, 619, 44, 404, 361, 3,
  108893. /* 1310 */ 419, 462, 340, 414, 620, 227, 124, 591, 591, 591,
  108894. /* 1320 */ 590, 589, 13, 619, 407, 410, 619, 410, 139, 34,
  108895. /* 1330 */ 404, 388, 3, 148, 623, 313, 414, 620, 312, 331,
  108896. /* 1340 */ 413, 461, 413, 402, 180, 354, 413, 407, 599, 79,
  108897. /* 1350 */ 599, 78, 250, 564, 599, 9, 619, 613, 612, 611,
  108898. /* 1360 */ 619, 8, 453, 443, 242, 416, 402, 619, 239, 235,
  108899. /* 1370 */ 179, 238, 429, 41, 42, 289, 564, 619, 619, 619,
  108900. /* 1380 */ 43, 412, 411, 619, 144, 593, 619, 619, 177, 61,
  108901. /* 1390 */ 619, 597, 392, 621, 620, 288, 41, 42, 415, 619,
  108902. /* 1400 */ 294, 30, 394, 43, 412, 411, 293, 619, 593, 31,
  108903. /* 1410 */ 619, 396, 292, 60, 230, 37, 591, 591, 591, 590,
  108904. /* 1420 */ 589, 13, 214, 554, 183, 291, 172, 302, 301, 300,
  108905. /* 1430 */ 178, 298, 596, 564, 452, 29, 286, 391, 541, 591,
  108906. /* 1440 */ 591, 591, 590, 589, 13, 284, 521, 535, 150, 534,
  108907. /* 1450 */ 241, 282, 385, 192, 191, 325, 516, 515, 277, 240,
  108908. /* 1460 */ 511, 524, 308, 512, 128, 593, 510, 225, 226, 487,
  108909. /* 1470 */ 486, 224, 152, 492, 465, 307, 485, 163, 153, 372,
  108910. /* 1480 */ 479, 151, 162, 259, 370, 161, 368, 208, 476, 477,
  108911. /* 1490 */ 26, 160, 469, 466, 362, 140, 591, 591, 591, 116,
  108912. /* 1500 */ 119, 455, 344, 155, 114, 343, 113, 112, 446, 111,
  108913. /* 1510 */ 131, 109, 432, 317, 130, 431, 23, 20, 430, 427,
  108914. /* 1520 */ 190, 63, 255, 342, 244, 607, 295, 287, 311, 594,
  108915. /* 1530 */ 278, 508, 496, 235, 493, 571, 497, 568, 495, 403,
  108916. /* 1540 */ 459, 379, 355, 245, 193, 303, 567, 296, 341, 5,
  108917. /* 1550 */ 445, 548, 506, 207, 525, 500, 335, 489, 252, 369,
  108918. /* 1560 */ 400, 499, 523, 233,
  108919. };
  108920. static const YYCODETYPE yy_lookahead[] = {
  108921. /* 0 */ 19, 142, 143, 144, 145, 24, 1, 26, 77, 78,
  108922. /* 10 */ 79, 80, 81, 82, 83, 84, 85, 86, 87, 88,
  108923. /* 20 */ 89, 90, 91, 92, 26, 27, 15, 26, 27, 197,
  108924. /* 30 */ 49, 50, 77, 78, 79, 80, 204, 82, 83, 84,
  108925. /* 40 */ 85, 86, 87, 88, 89, 90, 91, 92, 23, 68,
  108926. /* 50 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  108927. /* 60 */ 79, 80, 166, 82, 83, 84, 85, 86, 87, 88,
  108928. /* 70 */ 89, 90, 91, 92, 19, 94, 19, 105, 106, 107,
  108929. /* 80 */ 25, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108930. /* 90 */ 91, 92, 94, 95, 96, 94, 95, 99, 100, 101,
  108931. /* 100 */ 112, 205, 114, 115, 49, 50, 22, 23, 110, 54,
  108932. /* 110 */ 86, 87, 88, 89, 90, 91, 92, 221, 222, 223,
  108933. /* 120 */ 23, 120, 25, 68, 69, 70, 71, 72, 73, 74,
  108934. /* 130 */ 75, 76, 77, 78, 79, 80, 22, 82, 83, 84,
  108935. /* 140 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 92,
  108936. /* 150 */ 23, 67, 25, 96, 97, 98, 99, 100, 101, 102,
  108937. /* 160 */ 150, 32, 150, 118, 26, 27, 109, 150, 150, 150,
  108938. /* 170 */ 41, 161, 162, 180, 181, 165, 113, 165, 49, 50,
  108939. /* 180 */ 117, 188, 165, 165, 165, 173, 174, 170, 171, 170,
  108940. /* 190 */ 171, 173, 174, 118, 184, 16, 186, 68, 69, 70,
  108941. /* 200 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  108942. /* 210 */ 118, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108943. /* 220 */ 91, 92, 19, 98, 86, 87, 22, 24, 160, 88,
  108944. /* 230 */ 26, 27, 94, 95, 109, 97, 224, 66, 118, 60,
  108945. /* 240 */ 150, 62, 104, 23, 106, 25, 229, 230, 229, 230,
  108946. /* 250 */ 160, 150, 49, 50, 113, 165, 96, 26, 117, 99,
  108947. /* 260 */ 100, 101, 194, 173, 174, 94, 165, 129, 130, 98,
  108948. /* 270 */ 110, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  108949. /* 280 */ 77, 78, 79, 80, 194, 82, 83, 84, 85, 86,
  108950. /* 290 */ 87, 88, 89, 90, 91, 92, 19, 11, 94, 95,
  108951. /* 300 */ 129, 130, 131, 118, 150, 215, 150, 150, 150, 25,
  108952. /* 310 */ 220, 26, 27, 22, 213, 26, 27, 26, 27, 165,
  108953. /* 320 */ 25, 165, 165, 165, 30, 94, 49, 50, 34, 173,
  108954. /* 330 */ 174, 173, 174, 88, 89, 90, 91, 92, 7, 8,
  108955. /* 340 */ 160, 187, 48, 57, 187, 68, 69, 70, 71, 72,
  108956. /* 350 */ 73, 74, 75, 76, 77, 78, 79, 80, 23, 82,
  108957. /* 360 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  108958. /* 370 */ 19, 215, 150, 215, 194, 19, 220, 88, 220, 94,
  108959. /* 380 */ 95, 23, 160, 94, 95, 94, 95, 165, 26, 27,
  108960. /* 390 */ 95, 105, 106, 107, 113, 173, 174, 217, 22, 150,
  108961. /* 400 */ 49, 50, 116, 119, 57, 120, 50, 158, 22, 21,
  108962. /* 410 */ 161, 162, 232, 136, 165, 120, 194, 237, 23, 68,
  108963. /* 420 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  108964. /* 430 */ 79, 80, 22, 82, 83, 84, 85, 86, 87, 88,
  108965. /* 440 */ 89, 90, 91, 92, 19, 23, 12, 112, 23, 114,
  108966. /* 450 */ 115, 63, 105, 106, 107, 23, 94, 95, 97, 98,
  108967. /* 460 */ 104, 150, 28, 116, 25, 109, 150, 150, 23, 23,
  108968. /* 470 */ 112, 25, 114, 115, 49, 50, 165, 150, 44, 11,
  108969. /* 480 */ 46, 165, 165, 16, 173, 174, 76, 136, 100, 173,
  108970. /* 490 */ 174, 57, 165, 68, 69, 70, 71, 72, 73, 74,
  108971. /* 500 */ 75, 76, 77, 78, 79, 80, 166, 82, 83, 84,
  108972. /* 510 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 169,
  108973. /* 520 */ 170, 171, 23, 12, 23, 214, 138, 60, 150, 62,
  108974. /* 530 */ 24, 215, 26, 216, 112, 150, 114, 115, 36, 28,
  108975. /* 540 */ 213, 95, 103, 165, 112, 205, 114, 115, 49, 50,
  108976. /* 550 */ 165, 173, 174, 51, 23, 44, 25, 46, 173, 174,
  108977. /* 560 */ 58, 22, 23, 22, 25, 160, 120, 68, 69, 70,
  108978. /* 570 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  108979. /* 580 */ 230, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  108980. /* 590 */ 91, 92, 19, 215, 22, 23, 23, 25, 163, 194,
  108981. /* 600 */ 94, 166, 167, 168, 25, 138, 67, 7, 8, 9,
  108982. /* 610 */ 108, 206, 207, 169, 170, 171, 150, 22, 221, 222,
  108983. /* 620 */ 223, 26, 49, 50, 86, 87, 23, 161, 162, 23,
  108984. /* 630 */ 22, 165, 24, 120, 22, 23, 25, 160, 241, 67,
  108985. /* 640 */ 176, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  108986. /* 650 */ 77, 78, 79, 80, 160, 82, 83, 84, 85, 86,
  108987. /* 660 */ 87, 88, 89, 90, 91, 92, 19, 129, 130, 150,
  108988. /* 670 */ 23, 194, 35, 23, 230, 25, 150, 155, 150, 67,
  108989. /* 680 */ 150, 105, 106, 107, 165, 221, 222, 223, 194, 94,
  108990. /* 690 */ 23, 165, 25, 165, 217, 165, 49, 50, 25, 173,
  108991. /* 700 */ 174, 173, 174, 173, 174, 0, 1, 2, 118, 221,
  108992. /* 710 */ 222, 223, 193, 219, 237, 68, 69, 70, 71, 72,
  108993. /* 720 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  108994. /* 730 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  108995. /* 740 */ 19, 150, 19, 165, 150, 24, 166, 167, 168, 227,
  108996. /* 750 */ 27, 173, 174, 231, 150, 25, 165, 150, 172, 165,
  108997. /* 760 */ 150, 242, 129, 130, 173, 174, 180, 173, 174, 165,
  108998. /* 770 */ 49, 50, 165, 150, 176, 165, 35, 173, 174, 165,
  108999. /* 780 */ 173, 174, 35, 23, 23, 25, 25, 173, 165, 68,
  109000. /* 790 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  109001. /* 800 */ 79, 80, 150, 82, 83, 84, 85, 86, 87, 88,
  109002. /* 810 */ 89, 90, 91, 92, 19, 150, 193, 165, 150, 221,
  109003. /* 820 */ 222, 223, 150, 213, 19, 173, 174, 23, 150, 97,
  109004. /* 830 */ 165, 150, 27, 165, 150, 150, 150, 165, 173, 174,
  109005. /* 840 */ 22, 173, 174, 165, 49, 50, 165, 52, 116, 165,
  109006. /* 850 */ 165, 165, 206, 207, 173, 174, 126, 50, 173, 174,
  109007. /* 860 */ 128, 27, 160, 68, 69, 70, 71, 72, 73, 74,
  109008. /* 870 */ 75, 76, 77, 78, 79, 80, 150, 82, 83, 84,
  109009. /* 880 */ 85, 86, 87, 88, 89, 90, 91, 92, 19, 150,
  109010. /* 890 */ 23, 165, 150, 23, 216, 25, 194, 32, 39, 173,
  109011. /* 900 */ 174, 135, 150, 137, 165, 150, 41, 165, 150, 52,
  109012. /* 910 */ 238, 104, 173, 174, 29, 173, 174, 165, 49, 50,
  109013. /* 920 */ 165, 219, 238, 165, 238, 173, 174, 52, 173, 174,
  109014. /* 930 */ 22, 173, 174, 23, 23, 160, 25, 68, 69, 70,
  109015. /* 940 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  109016. /* 950 */ 150, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  109017. /* 960 */ 91, 92, 19, 150, 150, 165, 150, 245, 246, 194,
  109018. /* 970 */ 150, 144, 145, 173, 174, 160, 150, 22, 165, 165,
  109019. /* 980 */ 22, 165, 150, 150, 116, 165, 173, 174, 52, 173,
  109020. /* 990 */ 174, 165, 49, 50, 22, 150, 128, 165, 165, 173,
  109021. /* 1000 */ 174, 187, 166, 166, 22, 173, 174, 187, 109, 194,
  109022. /* 1010 */ 165, 68, 69, 70, 71, 72, 73, 74, 75, 76,
  109023. /* 1020 */ 77, 78, 79, 80, 150, 82, 83, 84, 85, 86,
  109024. /* 1030 */ 87, 88, 89, 90, 91, 92, 19, 150, 193, 165,
  109025. /* 1040 */ 102, 205, 205, 150, 150, 247, 248, 173, 174, 19,
  109026. /* 1050 */ 150, 20, 165, 150, 150, 150, 150, 150, 165, 165,
  109027. /* 1060 */ 173, 174, 49, 50, 104, 165, 49, 50, 165, 165,
  109028. /* 1070 */ 165, 165, 165, 173, 174, 43, 173, 174, 173, 174,
  109029. /* 1080 */ 187, 24, 190, 191, 71, 72, 69, 70, 71, 72,
  109030. /* 1090 */ 73, 74, 75, 76, 77, 78, 79, 80, 150, 82,
  109031. /* 1100 */ 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
  109032. /* 1110 */ 19, 98, 150, 165, 150, 150, 150, 150, 150, 150,
  109033. /* 1120 */ 59, 173, 174, 25, 150, 190, 191, 165, 53, 165,
  109034. /* 1130 */ 165, 165, 165, 165, 165, 173, 174, 173, 174, 165,
  109035. /* 1140 */ 49, 50, 91, 92, 1, 2, 53, 173, 174, 138,
  109036. /* 1150 */ 104, 22, 5, 1, 35, 118, 127, 150, 193, 193,
  109037. /* 1160 */ 193, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  109038. /* 1170 */ 79, 80, 165, 82, 83, 84, 85, 86, 87, 88,
  109039. /* 1180 */ 89, 90, 91, 92, 19, 20, 150, 22, 150, 27,
  109040. /* 1190 */ 150, 26, 27, 108, 150, 22, 76, 76, 150, 25,
  109041. /* 1200 */ 193, 165, 37, 165, 150, 165, 22, 19, 20, 165,
  109042. /* 1210 */ 22, 173, 174, 165, 26, 27, 23, 150, 119, 165,
  109043. /* 1220 */ 150, 56, 150, 150, 150, 37, 16, 173, 174, 193,
  109044. /* 1230 */ 150, 66, 165, 193, 1, 165, 121, 165, 165, 165,
  109045. /* 1240 */ 20, 146, 147, 119, 56, 165, 150, 152, 16, 154,
  109046. /* 1250 */ 150, 86, 87, 88, 66, 160, 150, 150, 93, 94,
  109047. /* 1260 */ 95, 165, 150, 98, 108, 165, 127, 23, 65, 173,
  109048. /* 1270 */ 174, 165, 165, 150, 86, 87, 128, 165, 150, 173,
  109049. /* 1280 */ 174, 93, 94, 95, 23, 150, 98, 15, 165, 194,
  109050. /* 1290 */ 150, 140, 22, 165, 129, 130, 131, 132, 133, 134,
  109051. /* 1300 */ 165, 173, 174, 3, 116, 165, 19, 20, 150, 22,
  109052. /* 1310 */ 4, 150, 217, 26, 27, 179, 179, 129, 130, 131,
  109053. /* 1320 */ 132, 133, 134, 165, 37, 150, 165, 150, 164, 19,
  109054. /* 1330 */ 20, 150, 22, 246, 149, 249, 26, 27, 249, 244,
  109055. /* 1340 */ 165, 150, 165, 56, 6, 150, 165, 37, 173, 174,
  109056. /* 1350 */ 173, 174, 150, 66, 173, 174, 165, 149, 149, 13,
  109057. /* 1360 */ 165, 25, 150, 150, 150, 149, 56, 165, 150, 116,
  109058. /* 1370 */ 151, 150, 150, 86, 87, 150, 66, 165, 165, 165,
  109059. /* 1380 */ 93, 94, 95, 165, 150, 98, 165, 165, 151, 22,
  109060. /* 1390 */ 165, 194, 150, 26, 27, 150, 86, 87, 159, 165,
  109061. /* 1400 */ 199, 126, 123, 93, 94, 95, 200, 165, 98, 124,
  109062. /* 1410 */ 165, 122, 201, 125, 225, 135, 129, 130, 131, 132,
  109063. /* 1420 */ 133, 134, 5, 157, 157, 202, 118, 10, 11, 12,
  109064. /* 1430 */ 13, 14, 203, 66, 17, 104, 210, 121, 211, 129,
  109065. /* 1440 */ 130, 131, 132, 133, 134, 210, 175, 211, 31, 211,
  109066. /* 1450 */ 33, 210, 104, 86, 87, 47, 175, 183, 175, 42,
  109067. /* 1460 */ 103, 94, 178, 177, 22, 98, 175, 92, 228, 175,
  109068. /* 1470 */ 175, 228, 55, 183, 57, 178, 175, 156, 61, 18,
  109069. /* 1480 */ 157, 64, 156, 235, 157, 156, 45, 157, 236, 157,
  109070. /* 1490 */ 135, 156, 199, 189, 157, 68, 129, 130, 131, 22,
  109071. /* 1500 */ 189, 199, 157, 156, 192, 18, 192, 192, 199, 192,
  109072. /* 1510 */ 218, 189, 40, 157, 218, 157, 240, 240, 157, 38,
  109073. /* 1520 */ 196, 243, 105, 106, 107, 153, 198, 209, 111, 166,
  109074. /* 1530 */ 176, 181, 166, 116, 166, 230, 176, 230, 176, 226,
  109075. /* 1540 */ 199, 177, 239, 209, 185, 148, 166, 195, 209, 196,
  109076. /* 1550 */ 199, 208, 182, 233, 173, 182, 139, 186, 239, 234,
  109077. /* 1560 */ 191, 182, 173, 92,
  109078. };
  109079. #define YY_SHIFT_USE_DFLT (-70)
  109080. #define YY_SHIFT_COUNT (417)
  109081. #define YY_SHIFT_MIN (-69)
  109082. #define YY_SHIFT_MAX (1487)
  109083. static const short yy_shift_ofst[] = {
  109084. /* 0 */ 1143, 1188, 1417, 1188, 1287, 1287, 138, 138, -2, -19,
  109085. /* 10 */ 1287, 1287, 1287, 1287, 347, 362, 129, 129, 795, 1165,
  109086. /* 20 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109087. /* 30 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109088. /* 40 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1310, 1287,
  109089. /* 50 */ 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287, 1287,
  109090. /* 60 */ 1287, 1287, 286, 362, 362, 538, 538, 231, 1253, 55,
  109091. /* 70 */ 721, 647, 573, 499, 425, 351, 277, 203, 869, 869,
  109092. /* 80 */ 869, 869, 869, 869, 869, 869, 869, 869, 869, 869,
  109093. /* 90 */ 869, 869, 869, 943, 869, 1017, 1091, 1091, -69, -45,
  109094. /* 100 */ -45, -45, -45, -45, -1, 24, 245, 362, 362, 362,
  109095. /* 110 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109096. /* 120 */ 362, 362, 362, 388, 356, 362, 362, 362, 362, 362,
  109097. /* 130 */ 732, 868, 231, 1051, 1471, -70, -70, -70, 1367, 57,
  109098. /* 140 */ 434, 434, 289, 291, 285, 1, 204, 572, 539, 362,
  109099. /* 150 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109100. /* 160 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109101. /* 170 */ 362, 362, 362, 362, 362, 362, 362, 362, 362, 362,
  109102. /* 180 */ 362, 506, 506, 506, 705, 1253, 1253, 1253, -70, -70,
  109103. /* 190 */ -70, 171, 171, 160, 502, 502, 502, 446, 432, 511,
  109104. /* 200 */ 422, 358, 335, -12, -12, -12, -12, 576, 294, -12,
  109105. /* 210 */ -12, 295, 595, 141, 600, 730, 723, 723, 805, 730,
  109106. /* 220 */ 805, 439, 911, 231, 865, 231, 865, 807, 865, 723,
  109107. /* 230 */ 766, 633, 633, 231, 284, 63, 608, 1481, 1308, 1308,
  109108. /* 240 */ 1472, 1472, 1308, 1477, 1427, 1275, 1487, 1487, 1487, 1487,
  109109. /* 250 */ 1308, 1461, 1275, 1477, 1427, 1427, 1275, 1308, 1461, 1355,
  109110. /* 260 */ 1441, 1308, 1308, 1461, 1308, 1461, 1308, 1461, 1442, 1348,
  109111. /* 270 */ 1348, 1348, 1408, 1375, 1375, 1442, 1348, 1357, 1348, 1408,
  109112. /* 280 */ 1348, 1348, 1316, 1331, 1316, 1331, 1316, 1331, 1308, 1308,
  109113. /* 290 */ 1280, 1288, 1289, 1285, 1279, 1275, 1253, 1336, 1346, 1346,
  109114. /* 300 */ 1338, 1338, 1338, 1338, -70, -70, -70, -70, -70, -70,
  109115. /* 310 */ 1013, 467, 612, 84, 179, -28, 870, 410, 761, 760,
  109116. /* 320 */ 667, 650, 531, 220, 361, 331, 125, 127, 97, 1306,
  109117. /* 330 */ 1300, 1270, 1151, 1272, 1203, 1232, 1261, 1244, 1148, 1174,
  109118. /* 340 */ 1139, 1156, 1124, 1220, 1115, 1210, 1233, 1099, 1193, 1184,
  109119. /* 350 */ 1174, 1173, 1029, 1121, 1120, 1085, 1162, 1119, 1037, 1152,
  109120. /* 360 */ 1147, 1129, 1046, 1011, 1093, 1098, 1075, 1061, 1032, 960,
  109121. /* 370 */ 1057, 1031, 1030, 899, 938, 982, 936, 972, 958, 910,
  109122. /* 380 */ 955, 875, 885, 908, 857, 859, 867, 804, 590, 834,
  109123. /* 390 */ 747, 818, 513, 611, 741, 673, 637, 611, 606, 603,
  109124. /* 400 */ 579, 501, 541, 468, 386, 445, 395, 376, 281, 185,
  109125. /* 410 */ 120, 92, 75, 45, 114, 25, 11, 5,
  109126. };
  109127. #define YY_REDUCE_USE_DFLT (-169)
  109128. #define YY_REDUCE_COUNT (309)
  109129. #define YY_REDUCE_MIN (-168)
  109130. #define YY_REDUCE_MAX (1397)
  109131. static const short yy_reduce_ofst[] = {
  109132. /* 0 */ -141, 90, 1095, 222, 158, 156, 19, 17, 10, -104,
  109133. /* 10 */ 378, 316, 311, 12, 180, 249, 598, 464, 397, 1181,
  109134. /* 20 */ 1177, 1175, 1128, 1106, 1096, 1054, 1038, 974, 964, 962,
  109135. /* 30 */ 948, 905, 903, 900, 887, 874, 832, 826, 816, 813,
  109136. /* 40 */ 800, 758, 755, 752, 742, 739, 726, 685, 681, 668,
  109137. /* 50 */ 665, 652, 607, 604, 594, 591, 578, 530, 528, 526,
  109138. /* 60 */ 385, 18, 477, 466, 519, 444, 350, 435, 405, 488,
  109139. /* 70 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109140. /* 80 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109141. /* 90 */ 488, 488, 488, 488, 488, 488, 488, 488, 488, 488,
  109142. /* 100 */ 488, 488, 488, 488, 488, 488, 488, 1040, 678, 1036,
  109143. /* 110 */ 1007, 967, 966, 965, 845, 686, 610, 684, 317, 672,
  109144. /* 120 */ 893, 327, 623, 522, -7, 820, 814, 157, 154, 101,
  109145. /* 130 */ 702, 494, 580, 488, 488, 488, 488, 488, 614, 586,
  109146. /* 140 */ 935, 892, 968, 1245, 1242, 1234, 1225, 798, 798, 1222,
  109147. /* 150 */ 1221, 1218, 1214, 1213, 1212, 1202, 1195, 1191, 1161, 1158,
  109148. /* 160 */ 1140, 1135, 1123, 1112, 1107, 1100, 1080, 1074, 1073, 1072,
  109149. /* 170 */ 1070, 1067, 1048, 1044, 969, 968, 907, 906, 904, 894,
  109150. /* 180 */ 833, 837, 836, 340, 827, 815, 775, 68, 722, 646,
  109151. /* 190 */ -168, 1389, 1381, 1371, 1379, 1373, 1370, 1343, 1352, 1369,
  109152. /* 200 */ 1352, 1352, 1352, 1352, 1352, 1352, 1352, 1325, 1320, 1352,
  109153. /* 210 */ 1352, 1343, 1380, 1353, 1397, 1351, 1339, 1334, 1319, 1341,
  109154. /* 220 */ 1303, 1364, 1359, 1368, 1362, 1366, 1360, 1350, 1354, 1318,
  109155. /* 230 */ 1313, 1307, 1305, 1363, 1328, 1324, 1372, 1278, 1361, 1358,
  109156. /* 240 */ 1277, 1276, 1356, 1296, 1322, 1309, 1317, 1315, 1314, 1312,
  109157. /* 250 */ 1345, 1347, 1302, 1292, 1311, 1304, 1293, 1337, 1335, 1252,
  109158. /* 260 */ 1248, 1332, 1330, 1329, 1327, 1326, 1323, 1321, 1297, 1301,
  109159. /* 270 */ 1295, 1294, 1290, 1243, 1240, 1284, 1291, 1286, 1283, 1274,
  109160. /* 280 */ 1281, 1271, 1238, 1241, 1236, 1235, 1227, 1226, 1267, 1266,
  109161. /* 290 */ 1189, 1229, 1223, 1211, 1206, 1201, 1197, 1239, 1237, 1219,
  109162. /* 300 */ 1216, 1209, 1208, 1185, 1089, 1086, 1087, 1137, 1136, 1164,
  109163. };
  109164. static const YYACTIONTYPE yy_default[] = {
  109165. /* 0 */ 633, 867, 955, 955, 867, 867, 955, 955, 955, 757,
  109166. /* 10 */ 955, 955, 955, 865, 955, 955, 785, 785, 929, 955,
  109167. /* 20 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109168. /* 30 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109169. /* 40 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109170. /* 50 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109171. /* 60 */ 955, 955, 955, 955, 955, 955, 955, 672, 761, 791,
  109172. /* 70 */ 955, 955, 955, 955, 955, 955, 955, 955, 928, 930,
  109173. /* 80 */ 799, 798, 908, 772, 796, 789, 793, 868, 861, 862,
  109174. /* 90 */ 860, 864, 869, 955, 792, 828, 845, 827, 839, 844,
  109175. /* 100 */ 851, 843, 840, 830, 829, 831, 832, 955, 955, 955,
  109176. /* 110 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109177. /* 120 */ 955, 955, 955, 659, 726, 955, 955, 955, 955, 955,
  109178. /* 130 */ 955, 955, 955, 833, 834, 848, 847, 846, 955, 664,
  109179. /* 140 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109180. /* 150 */ 935, 933, 955, 880, 955, 955, 955, 955, 955, 955,
  109181. /* 160 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109182. /* 170 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109183. /* 180 */ 639, 757, 757, 757, 633, 955, 955, 955, 947, 761,
  109184. /* 190 */ 751, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109185. /* 200 */ 955, 955, 955, 801, 740, 918, 920, 955, 901, 738,
  109186. /* 210 */ 661, 759, 674, 749, 641, 795, 774, 774, 913, 795,
  109187. /* 220 */ 913, 697, 720, 955, 785, 955, 785, 694, 785, 774,
  109188. /* 230 */ 863, 955, 955, 955, 758, 749, 955, 940, 765, 765,
  109189. /* 240 */ 932, 932, 765, 807, 730, 795, 737, 737, 737, 737,
  109190. /* 250 */ 765, 656, 795, 807, 730, 730, 795, 765, 656, 907,
  109191. /* 260 */ 905, 765, 765, 656, 765, 656, 765, 656, 873, 728,
  109192. /* 270 */ 728, 728, 712, 877, 877, 873, 728, 697, 728, 712,
  109193. /* 280 */ 728, 728, 778, 773, 778, 773, 778, 773, 765, 765,
  109194. /* 290 */ 955, 790, 779, 788, 786, 795, 955, 715, 649, 649,
  109195. /* 300 */ 638, 638, 638, 638, 952, 952, 947, 699, 699, 682,
  109196. /* 310 */ 955, 955, 955, 955, 955, 955, 955, 882, 955, 955,
  109197. /* 320 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109198. /* 330 */ 634, 942, 955, 955, 939, 955, 955, 955, 955, 800,
  109199. /* 340 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109200. /* 350 */ 917, 955, 955, 955, 955, 955, 955, 955, 911, 955,
  109201. /* 360 */ 955, 955, 955, 955, 955, 904, 903, 955, 955, 955,
  109202. /* 370 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109203. /* 380 */ 955, 955, 955, 955, 955, 955, 955, 955, 955, 955,
  109204. /* 390 */ 955, 955, 955, 787, 955, 780, 955, 866, 955, 955,
  109205. /* 400 */ 955, 955, 955, 955, 955, 955, 955, 955, 743, 816,
  109206. /* 410 */ 955, 815, 819, 814, 666, 955, 647, 955, 630, 635,
  109207. /* 420 */ 951, 954, 953, 950, 949, 948, 943, 941, 938, 937,
  109208. /* 430 */ 936, 934, 931, 927, 886, 884, 891, 890, 889, 888,
  109209. /* 440 */ 887, 885, 883, 881, 802, 797, 794, 926, 879, 739,
  109210. /* 450 */ 736, 735, 655, 944, 910, 919, 806, 805, 808, 916,
  109211. /* 460 */ 915, 914, 912, 909, 896, 804, 803, 731, 871, 870,
  109212. /* 470 */ 658, 900, 899, 898, 902, 906, 897, 767, 657, 654,
  109213. /* 480 */ 663, 718, 719, 727, 725, 724, 723, 722, 721, 717,
  109214. /* 490 */ 665, 673, 711, 696, 695, 876, 878, 875, 874, 704,
  109215. /* 500 */ 703, 709, 708, 707, 706, 705, 702, 701, 700, 693,
  109216. /* 510 */ 692, 698, 691, 714, 713, 710, 690, 734, 733, 732,
  109217. /* 520 */ 729, 689, 688, 687, 819, 686, 685, 825, 824, 812,
  109218. /* 530 */ 855, 754, 753, 752, 764, 763, 776, 775, 810, 809,
  109219. /* 540 */ 777, 762, 756, 755, 771, 770, 769, 768, 760, 750,
  109220. /* 550 */ 782, 784, 783, 781, 857, 766, 854, 925, 924, 923,
  109221. /* 560 */ 922, 921, 859, 858, 826, 823, 677, 678, 894, 893,
  109222. /* 570 */ 895, 892, 680, 679, 676, 675, 856, 745, 744, 852,
  109223. /* 580 */ 849, 841, 837, 853, 850, 842, 838, 836, 835, 821,
  109224. /* 590 */ 820, 818, 817, 813, 822, 668, 746, 742, 741, 811,
  109225. /* 600 */ 748, 747, 684, 683, 681, 662, 660, 653, 651, 650,
  109226. /* 610 */ 652, 648, 646, 645, 644, 643, 642, 671, 670, 669,
  109227. /* 620 */ 667, 666, 640, 637, 636, 632, 631, 629,
  109228. };
  109229. /* The next table maps tokens into fallback tokens. If a construct
  109230. ** like the following:
  109231. **
  109232. ** %fallback ID X Y Z.
  109233. **
  109234. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  109235. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  109236. ** but it does not parse, the type of the token is changed to ID and
  109237. ** the parse is retried before an error is thrown.
  109238. */
  109239. #ifdef YYFALLBACK
  109240. static const YYCODETYPE yyFallback[] = {
  109241. 0, /* $ => nothing */
  109242. 0, /* SEMI => nothing */
  109243. 26, /* EXPLAIN => ID */
  109244. 26, /* QUERY => ID */
  109245. 26, /* PLAN => ID */
  109246. 26, /* BEGIN => ID */
  109247. 0, /* TRANSACTION => nothing */
  109248. 26, /* DEFERRED => ID */
  109249. 26, /* IMMEDIATE => ID */
  109250. 26, /* EXCLUSIVE => ID */
  109251. 0, /* COMMIT => nothing */
  109252. 26, /* END => ID */
  109253. 26, /* ROLLBACK => ID */
  109254. 26, /* SAVEPOINT => ID */
  109255. 26, /* RELEASE => ID */
  109256. 0, /* TO => nothing */
  109257. 0, /* TABLE => nothing */
  109258. 0, /* CREATE => nothing */
  109259. 26, /* IF => ID */
  109260. 0, /* NOT => nothing */
  109261. 0, /* EXISTS => nothing */
  109262. 26, /* TEMP => ID */
  109263. 0, /* LP => nothing */
  109264. 0, /* RP => nothing */
  109265. 0, /* AS => nothing */
  109266. 0, /* COMMA => nothing */
  109267. 0, /* ID => nothing */
  109268. 0, /* INDEXED => nothing */
  109269. 26, /* ABORT => ID */
  109270. 26, /* ACTION => ID */
  109271. 26, /* AFTER => ID */
  109272. 26, /* ANALYZE => ID */
  109273. 26, /* ASC => ID */
  109274. 26, /* ATTACH => ID */
  109275. 26, /* BEFORE => ID */
  109276. 26, /* BY => ID */
  109277. 26, /* CASCADE => ID */
  109278. 26, /* CAST => ID */
  109279. 26, /* COLUMNKW => ID */
  109280. 26, /* CONFLICT => ID */
  109281. 26, /* DATABASE => ID */
  109282. 26, /* DESC => ID */
  109283. 26, /* DETACH => ID */
  109284. 26, /* EACH => ID */
  109285. 26, /* FAIL => ID */
  109286. 26, /* FOR => ID */
  109287. 26, /* IGNORE => ID */
  109288. 26, /* INITIALLY => ID */
  109289. 26, /* INSTEAD => ID */
  109290. 26, /* LIKE_KW => ID */
  109291. 26, /* MATCH => ID */
  109292. 26, /* NO => ID */
  109293. 26, /* KEY => ID */
  109294. 26, /* OF => ID */
  109295. 26, /* OFFSET => ID */
  109296. 26, /* PRAGMA => ID */
  109297. 26, /* RAISE => ID */
  109298. 26, /* REPLACE => ID */
  109299. 26, /* RESTRICT => ID */
  109300. 26, /* ROW => ID */
  109301. 26, /* TRIGGER => ID */
  109302. 26, /* VACUUM => ID */
  109303. 26, /* VIEW => ID */
  109304. 26, /* VIRTUAL => ID */
  109305. 26, /* REINDEX => ID */
  109306. 26, /* RENAME => ID */
  109307. 26, /* CTIME_KW => ID */
  109308. };
  109309. #endif /* YYFALLBACK */
  109310. /* The following structure represents a single element of the
  109311. ** parser's stack. Information stored includes:
  109312. **
  109313. ** + The state number for the parser at this level of the stack.
  109314. **
  109315. ** + The value of the token stored at this level of the stack.
  109316. ** (In other words, the "major" token.)
  109317. **
  109318. ** + The semantic value stored at this level of the stack. This is
  109319. ** the information used by the action routines in the grammar.
  109320. ** It is sometimes called the "minor" token.
  109321. */
  109322. struct yyStackEntry {
  109323. YYACTIONTYPE stateno; /* The state-number */
  109324. YYCODETYPE major; /* The major token value. This is the code
  109325. ** number for the token at this stack level */
  109326. YYMINORTYPE minor; /* The user-supplied minor token value. This
  109327. ** is the value of the token */
  109328. };
  109329. typedef struct yyStackEntry yyStackEntry;
  109330. /* The state of the parser is completely contained in an instance of
  109331. ** the following structure */
  109332. struct yyParser {
  109333. int yyidx; /* Index of top element in stack */
  109334. #ifdef YYTRACKMAXSTACKDEPTH
  109335. int yyidxMax; /* Maximum value of yyidx */
  109336. #endif
  109337. int yyerrcnt; /* Shifts left before out of the error */
  109338. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  109339. #if YYSTACKDEPTH<=0
  109340. int yystksz; /* Current side of the stack */
  109341. yyStackEntry *yystack; /* The parser's stack */
  109342. #else
  109343. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  109344. #endif
  109345. };
  109346. typedef struct yyParser yyParser;
  109347. #ifndef NDEBUG
  109348. /* #include <stdio.h> */
  109349. static FILE *yyTraceFILE = 0;
  109350. static char *yyTracePrompt = 0;
  109351. #endif /* NDEBUG */
  109352. #ifndef NDEBUG
  109353. /*
  109354. ** Turn parser tracing on by giving a stream to which to write the trace
  109355. ** and a prompt to preface each trace message. Tracing is turned off
  109356. ** by making either argument NULL
  109357. **
  109358. ** Inputs:
  109359. ** <ul>
  109360. ** <li> A FILE* to which trace output should be written.
  109361. ** If NULL, then tracing is turned off.
  109362. ** <li> A prefix string written at the beginning of every
  109363. ** line of trace output. If NULL, then tracing is
  109364. ** turned off.
  109365. ** </ul>
  109366. **
  109367. ** Outputs:
  109368. ** None.
  109369. */
  109370. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  109371. yyTraceFILE = TraceFILE;
  109372. yyTracePrompt = zTracePrompt;
  109373. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  109374. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  109375. }
  109376. #endif /* NDEBUG */
  109377. #ifndef NDEBUG
  109378. /* For tracing shifts, the names of all terminals and nonterminals
  109379. ** are required. The following table supplies these names */
  109380. static const char *const yyTokenName[] = {
  109381. "$", "SEMI", "EXPLAIN", "QUERY",
  109382. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  109383. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  109384. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  109385. "TABLE", "CREATE", "IF", "NOT",
  109386. "EXISTS", "TEMP", "LP", "RP",
  109387. "AS", "COMMA", "ID", "INDEXED",
  109388. "ABORT", "ACTION", "AFTER", "ANALYZE",
  109389. "ASC", "ATTACH", "BEFORE", "BY",
  109390. "CASCADE", "CAST", "COLUMNKW", "CONFLICT",
  109391. "DATABASE", "DESC", "DETACH", "EACH",
  109392. "FAIL", "FOR", "IGNORE", "INITIALLY",
  109393. "INSTEAD", "LIKE_KW", "MATCH", "NO",
  109394. "KEY", "OF", "OFFSET", "PRAGMA",
  109395. "RAISE", "REPLACE", "RESTRICT", "ROW",
  109396. "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
  109397. "REINDEX", "RENAME", "CTIME_KW", "ANY",
  109398. "OR", "AND", "IS", "BETWEEN",
  109399. "IN", "ISNULL", "NOTNULL", "NE",
  109400. "EQ", "GT", "LE", "LT",
  109401. "GE", "ESCAPE", "BITAND", "BITOR",
  109402. "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  109403. "STAR", "SLASH", "REM", "CONCAT",
  109404. "COLLATE", "BITNOT", "STRING", "JOIN_KW",
  109405. "CONSTRAINT", "DEFAULT", "NULL", "PRIMARY",
  109406. "UNIQUE", "CHECK", "REFERENCES", "AUTOINCR",
  109407. "ON", "INSERT", "DELETE", "UPDATE",
  109408. "SET", "DEFERRABLE", "FOREIGN", "DROP",
  109409. "UNION", "ALL", "EXCEPT", "INTERSECT",
  109410. "SELECT", "DISTINCT", "DOT", "FROM",
  109411. "JOIN", "USING", "ORDER", "GROUP",
  109412. "HAVING", "LIMIT", "WHERE", "INTO",
  109413. "VALUES", "INTEGER", "FLOAT", "BLOB",
  109414. "REGISTER", "VARIABLE", "CASE", "WHEN",
  109415. "THEN", "ELSE", "INDEX", "ALTER",
  109416. "ADD", "error", "input", "cmdlist",
  109417. "ecmd", "explain", "cmdx", "cmd",
  109418. "transtype", "trans_opt", "nm", "savepoint_opt",
  109419. "create_table", "create_table_args", "createkw", "temp",
  109420. "ifnotexists", "dbnm", "columnlist", "conslist_opt",
  109421. "select", "column", "columnid", "type",
  109422. "carglist", "id", "ids", "typetoken",
  109423. "typename", "signed", "plus_num", "minus_num",
  109424. "ccons", "term", "expr", "onconf",
  109425. "sortorder", "autoinc", "idxlist_opt", "refargs",
  109426. "defer_subclause", "refarg", "refact", "init_deferred_pred_opt",
  109427. "conslist", "tconscomma", "tcons", "idxlist",
  109428. "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
  109429. "ifexists", "fullname", "oneselect", "multiselect_op",
  109430. "distinct", "selcollist", "from", "where_opt",
  109431. "groupby_opt", "having_opt", "orderby_opt", "limit_opt",
  109432. "sclp", "as", "seltablist", "stl_prefix",
  109433. "joinop", "indexed_opt", "on_opt", "using_opt",
  109434. "joinop2", "inscollist", "sortlist", "nexprlist",
  109435. "setlist", "insert_cmd", "inscollist_opt", "valuelist",
  109436. "exprlist", "likeop", "between_op", "in_op",
  109437. "case_operand", "case_exprlist", "case_else", "uniqueflag",
  109438. "collate", "nmnum", "number", "trigger_decl",
  109439. "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  109440. "when_clause", "trigger_cmd", "trnm", "tridxby",
  109441. "database_kw_opt", "key_opt", "add_column_fullname", "kwcolumn_opt",
  109442. "create_vtab", "vtabarglist", "vtabarg", "vtabargtoken",
  109443. "lp", "anylist",
  109444. };
  109445. #endif /* NDEBUG */
  109446. #ifndef NDEBUG
  109447. /* For tracing reduce actions, the names of all rules are required.
  109448. */
  109449. static const char *const yyRuleName[] = {
  109450. /* 0 */ "input ::= cmdlist",
  109451. /* 1 */ "cmdlist ::= cmdlist ecmd",
  109452. /* 2 */ "cmdlist ::= ecmd",
  109453. /* 3 */ "ecmd ::= SEMI",
  109454. /* 4 */ "ecmd ::= explain cmdx SEMI",
  109455. /* 5 */ "explain ::=",
  109456. /* 6 */ "explain ::= EXPLAIN",
  109457. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  109458. /* 8 */ "cmdx ::= cmd",
  109459. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  109460. /* 10 */ "trans_opt ::=",
  109461. /* 11 */ "trans_opt ::= TRANSACTION",
  109462. /* 12 */ "trans_opt ::= TRANSACTION nm",
  109463. /* 13 */ "transtype ::=",
  109464. /* 14 */ "transtype ::= DEFERRED",
  109465. /* 15 */ "transtype ::= IMMEDIATE",
  109466. /* 16 */ "transtype ::= EXCLUSIVE",
  109467. /* 17 */ "cmd ::= COMMIT trans_opt",
  109468. /* 18 */ "cmd ::= END trans_opt",
  109469. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  109470. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  109471. /* 21 */ "savepoint_opt ::=",
  109472. /* 22 */ "cmd ::= SAVEPOINT nm",
  109473. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  109474. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  109475. /* 25 */ "cmd ::= create_table create_table_args",
  109476. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  109477. /* 27 */ "createkw ::= CREATE",
  109478. /* 28 */ "ifnotexists ::=",
  109479. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  109480. /* 30 */ "temp ::= TEMP",
  109481. /* 31 */ "temp ::=",
  109482. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP",
  109483. /* 33 */ "create_table_args ::= AS select",
  109484. /* 34 */ "columnlist ::= columnlist COMMA column",
  109485. /* 35 */ "columnlist ::= column",
  109486. /* 36 */ "column ::= columnid type carglist",
  109487. /* 37 */ "columnid ::= nm",
  109488. /* 38 */ "id ::= ID",
  109489. /* 39 */ "id ::= INDEXED",
  109490. /* 40 */ "ids ::= ID|STRING",
  109491. /* 41 */ "nm ::= id",
  109492. /* 42 */ "nm ::= STRING",
  109493. /* 43 */ "nm ::= JOIN_KW",
  109494. /* 44 */ "type ::=",
  109495. /* 45 */ "type ::= typetoken",
  109496. /* 46 */ "typetoken ::= typename",
  109497. /* 47 */ "typetoken ::= typename LP signed RP",
  109498. /* 48 */ "typetoken ::= typename LP signed COMMA signed RP",
  109499. /* 49 */ "typename ::= ids",
  109500. /* 50 */ "typename ::= typename ids",
  109501. /* 51 */ "signed ::= plus_num",
  109502. /* 52 */ "signed ::= minus_num",
  109503. /* 53 */ "carglist ::= carglist ccons",
  109504. /* 54 */ "carglist ::=",
  109505. /* 55 */ "ccons ::= CONSTRAINT nm",
  109506. /* 56 */ "ccons ::= DEFAULT term",
  109507. /* 57 */ "ccons ::= DEFAULT LP expr RP",
  109508. /* 58 */ "ccons ::= DEFAULT PLUS term",
  109509. /* 59 */ "ccons ::= DEFAULT MINUS term",
  109510. /* 60 */ "ccons ::= DEFAULT id",
  109511. /* 61 */ "ccons ::= NULL onconf",
  109512. /* 62 */ "ccons ::= NOT NULL onconf",
  109513. /* 63 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  109514. /* 64 */ "ccons ::= UNIQUE onconf",
  109515. /* 65 */ "ccons ::= CHECK LP expr RP",
  109516. /* 66 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  109517. /* 67 */ "ccons ::= defer_subclause",
  109518. /* 68 */ "ccons ::= COLLATE ids",
  109519. /* 69 */ "autoinc ::=",
  109520. /* 70 */ "autoinc ::= AUTOINCR",
  109521. /* 71 */ "refargs ::=",
  109522. /* 72 */ "refargs ::= refargs refarg",
  109523. /* 73 */ "refarg ::= MATCH nm",
  109524. /* 74 */ "refarg ::= ON INSERT refact",
  109525. /* 75 */ "refarg ::= ON DELETE refact",
  109526. /* 76 */ "refarg ::= ON UPDATE refact",
  109527. /* 77 */ "refact ::= SET NULL",
  109528. /* 78 */ "refact ::= SET DEFAULT",
  109529. /* 79 */ "refact ::= CASCADE",
  109530. /* 80 */ "refact ::= RESTRICT",
  109531. /* 81 */ "refact ::= NO ACTION",
  109532. /* 82 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  109533. /* 83 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  109534. /* 84 */ "init_deferred_pred_opt ::=",
  109535. /* 85 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  109536. /* 86 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  109537. /* 87 */ "conslist_opt ::=",
  109538. /* 88 */ "conslist_opt ::= COMMA conslist",
  109539. /* 89 */ "conslist ::= conslist tconscomma tcons",
  109540. /* 90 */ "conslist ::= tcons",
  109541. /* 91 */ "tconscomma ::= COMMA",
  109542. /* 92 */ "tconscomma ::=",
  109543. /* 93 */ "tcons ::= CONSTRAINT nm",
  109544. /* 94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  109545. /* 95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  109546. /* 96 */ "tcons ::= CHECK LP expr RP onconf",
  109547. /* 97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  109548. /* 98 */ "defer_subclause_opt ::=",
  109549. /* 99 */ "defer_subclause_opt ::= defer_subclause",
  109550. /* 100 */ "onconf ::=",
  109551. /* 101 */ "onconf ::= ON CONFLICT resolvetype",
  109552. /* 102 */ "orconf ::=",
  109553. /* 103 */ "orconf ::= OR resolvetype",
  109554. /* 104 */ "resolvetype ::= raisetype",
  109555. /* 105 */ "resolvetype ::= IGNORE",
  109556. /* 106 */ "resolvetype ::= REPLACE",
  109557. /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
  109558. /* 108 */ "ifexists ::= IF EXISTS",
  109559. /* 109 */ "ifexists ::=",
  109560. /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  109561. /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
  109562. /* 112 */ "cmd ::= select",
  109563. /* 113 */ "select ::= oneselect",
  109564. /* 114 */ "select ::= select multiselect_op oneselect",
  109565. /* 115 */ "multiselect_op ::= UNION",
  109566. /* 116 */ "multiselect_op ::= UNION ALL",
  109567. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  109568. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  109569. /* 119 */ "distinct ::= DISTINCT",
  109570. /* 120 */ "distinct ::= ALL",
  109571. /* 121 */ "distinct ::=",
  109572. /* 122 */ "sclp ::= selcollist COMMA",
  109573. /* 123 */ "sclp ::=",
  109574. /* 124 */ "selcollist ::= sclp expr as",
  109575. /* 125 */ "selcollist ::= sclp STAR",
  109576. /* 126 */ "selcollist ::= sclp nm DOT STAR",
  109577. /* 127 */ "as ::= AS nm",
  109578. /* 128 */ "as ::= ids",
  109579. /* 129 */ "as ::=",
  109580. /* 130 */ "from ::=",
  109581. /* 131 */ "from ::= FROM seltablist",
  109582. /* 132 */ "stl_prefix ::= seltablist joinop",
  109583. /* 133 */ "stl_prefix ::=",
  109584. /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  109585. /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  109586. /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  109587. /* 137 */ "dbnm ::=",
  109588. /* 138 */ "dbnm ::= DOT nm",
  109589. /* 139 */ "fullname ::= nm dbnm",
  109590. /* 140 */ "joinop ::= COMMA|JOIN",
  109591. /* 141 */ "joinop ::= JOIN_KW JOIN",
  109592. /* 142 */ "joinop ::= JOIN_KW nm JOIN",
  109593. /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
  109594. /* 144 */ "on_opt ::= ON expr",
  109595. /* 145 */ "on_opt ::=",
  109596. /* 146 */ "indexed_opt ::=",
  109597. /* 147 */ "indexed_opt ::= INDEXED BY nm",
  109598. /* 148 */ "indexed_opt ::= NOT INDEXED",
  109599. /* 149 */ "using_opt ::= USING LP inscollist RP",
  109600. /* 150 */ "using_opt ::=",
  109601. /* 151 */ "orderby_opt ::=",
  109602. /* 152 */ "orderby_opt ::= ORDER BY sortlist",
  109603. /* 153 */ "sortlist ::= sortlist COMMA expr sortorder",
  109604. /* 154 */ "sortlist ::= expr sortorder",
  109605. /* 155 */ "sortorder ::= ASC",
  109606. /* 156 */ "sortorder ::= DESC",
  109607. /* 157 */ "sortorder ::=",
  109608. /* 158 */ "groupby_opt ::=",
  109609. /* 159 */ "groupby_opt ::= GROUP BY nexprlist",
  109610. /* 160 */ "having_opt ::=",
  109611. /* 161 */ "having_opt ::= HAVING expr",
  109612. /* 162 */ "limit_opt ::=",
  109613. /* 163 */ "limit_opt ::= LIMIT expr",
  109614. /* 164 */ "limit_opt ::= LIMIT expr OFFSET expr",
  109615. /* 165 */ "limit_opt ::= LIMIT expr COMMA expr",
  109616. /* 166 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
  109617. /* 167 */ "where_opt ::=",
  109618. /* 168 */ "where_opt ::= WHERE expr",
  109619. /* 169 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
  109620. /* 170 */ "setlist ::= setlist COMMA nm EQ expr",
  109621. /* 171 */ "setlist ::= nm EQ expr",
  109622. /* 172 */ "cmd ::= insert_cmd INTO fullname inscollist_opt valuelist",
  109623. /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
  109624. /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  109625. /* 175 */ "insert_cmd ::= INSERT orconf",
  109626. /* 176 */ "insert_cmd ::= REPLACE",
  109627. /* 177 */ "valuelist ::= VALUES LP nexprlist RP",
  109628. /* 178 */ "valuelist ::= valuelist COMMA LP exprlist RP",
  109629. /* 179 */ "inscollist_opt ::=",
  109630. /* 180 */ "inscollist_opt ::= LP inscollist RP",
  109631. /* 181 */ "inscollist ::= inscollist COMMA nm",
  109632. /* 182 */ "inscollist ::= nm",
  109633. /* 183 */ "expr ::= term",
  109634. /* 184 */ "expr ::= LP expr RP",
  109635. /* 185 */ "term ::= NULL",
  109636. /* 186 */ "expr ::= id",
  109637. /* 187 */ "expr ::= JOIN_KW",
  109638. /* 188 */ "expr ::= nm DOT nm",
  109639. /* 189 */ "expr ::= nm DOT nm DOT nm",
  109640. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  109641. /* 191 */ "term ::= STRING",
  109642. /* 192 */ "expr ::= REGISTER",
  109643. /* 193 */ "expr ::= VARIABLE",
  109644. /* 194 */ "expr ::= expr COLLATE ids",
  109645. /* 195 */ "expr ::= CAST LP expr AS typetoken RP",
  109646. /* 196 */ "expr ::= ID LP distinct exprlist RP",
  109647. /* 197 */ "expr ::= ID LP STAR RP",
  109648. /* 198 */ "term ::= CTIME_KW",
  109649. /* 199 */ "expr ::= expr AND expr",
  109650. /* 200 */ "expr ::= expr OR expr",
  109651. /* 201 */ "expr ::= expr LT|GT|GE|LE expr",
  109652. /* 202 */ "expr ::= expr EQ|NE expr",
  109653. /* 203 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  109654. /* 204 */ "expr ::= expr PLUS|MINUS expr",
  109655. /* 205 */ "expr ::= expr STAR|SLASH|REM expr",
  109656. /* 206 */ "expr ::= expr CONCAT expr",
  109657. /* 207 */ "likeop ::= LIKE_KW",
  109658. /* 208 */ "likeop ::= NOT LIKE_KW",
  109659. /* 209 */ "likeop ::= MATCH",
  109660. /* 210 */ "likeop ::= NOT MATCH",
  109661. /* 211 */ "expr ::= expr likeop expr",
  109662. /* 212 */ "expr ::= expr likeop expr ESCAPE expr",
  109663. /* 213 */ "expr ::= expr ISNULL|NOTNULL",
  109664. /* 214 */ "expr ::= expr NOT NULL",
  109665. /* 215 */ "expr ::= expr IS expr",
  109666. /* 216 */ "expr ::= expr IS NOT expr",
  109667. /* 217 */ "expr ::= NOT expr",
  109668. /* 218 */ "expr ::= BITNOT expr",
  109669. /* 219 */ "expr ::= MINUS expr",
  109670. /* 220 */ "expr ::= PLUS expr",
  109671. /* 221 */ "between_op ::= BETWEEN",
  109672. /* 222 */ "between_op ::= NOT BETWEEN",
  109673. /* 223 */ "expr ::= expr between_op expr AND expr",
  109674. /* 224 */ "in_op ::= IN",
  109675. /* 225 */ "in_op ::= NOT IN",
  109676. /* 226 */ "expr ::= expr in_op LP exprlist RP",
  109677. /* 227 */ "expr ::= LP select RP",
  109678. /* 228 */ "expr ::= expr in_op LP select RP",
  109679. /* 229 */ "expr ::= expr in_op nm dbnm",
  109680. /* 230 */ "expr ::= EXISTS LP select RP",
  109681. /* 231 */ "expr ::= CASE case_operand case_exprlist case_else END",
  109682. /* 232 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  109683. /* 233 */ "case_exprlist ::= WHEN expr THEN expr",
  109684. /* 234 */ "case_else ::= ELSE expr",
  109685. /* 235 */ "case_else ::=",
  109686. /* 236 */ "case_operand ::= expr",
  109687. /* 237 */ "case_operand ::=",
  109688. /* 238 */ "exprlist ::= nexprlist",
  109689. /* 239 */ "exprlist ::=",
  109690. /* 240 */ "nexprlist ::= nexprlist COMMA expr",
  109691. /* 241 */ "nexprlist ::= expr",
  109692. /* 242 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  109693. /* 243 */ "uniqueflag ::= UNIQUE",
  109694. /* 244 */ "uniqueflag ::=",
  109695. /* 245 */ "idxlist_opt ::=",
  109696. /* 246 */ "idxlist_opt ::= LP idxlist RP",
  109697. /* 247 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  109698. /* 248 */ "idxlist ::= nm collate sortorder",
  109699. /* 249 */ "collate ::=",
  109700. /* 250 */ "collate ::= COLLATE ids",
  109701. /* 251 */ "cmd ::= DROP INDEX ifexists fullname",
  109702. /* 252 */ "cmd ::= VACUUM",
  109703. /* 253 */ "cmd ::= VACUUM nm",
  109704. /* 254 */ "cmd ::= PRAGMA nm dbnm",
  109705. /* 255 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  109706. /* 256 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  109707. /* 257 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  109708. /* 258 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  109709. /* 259 */ "nmnum ::= plus_num",
  109710. /* 260 */ "nmnum ::= nm",
  109711. /* 261 */ "nmnum ::= ON",
  109712. /* 262 */ "nmnum ::= DELETE",
  109713. /* 263 */ "nmnum ::= DEFAULT",
  109714. /* 264 */ "plus_num ::= PLUS number",
  109715. /* 265 */ "plus_num ::= number",
  109716. /* 266 */ "minus_num ::= MINUS number",
  109717. /* 267 */ "number ::= INTEGER|FLOAT",
  109718. /* 268 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  109719. /* 269 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  109720. /* 270 */ "trigger_time ::= BEFORE",
  109721. /* 271 */ "trigger_time ::= AFTER",
  109722. /* 272 */ "trigger_time ::= INSTEAD OF",
  109723. /* 273 */ "trigger_time ::=",
  109724. /* 274 */ "trigger_event ::= DELETE|INSERT",
  109725. /* 275 */ "trigger_event ::= UPDATE",
  109726. /* 276 */ "trigger_event ::= UPDATE OF inscollist",
  109727. /* 277 */ "foreach_clause ::=",
  109728. /* 278 */ "foreach_clause ::= FOR EACH ROW",
  109729. /* 279 */ "when_clause ::=",
  109730. /* 280 */ "when_clause ::= WHEN expr",
  109731. /* 281 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  109732. /* 282 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  109733. /* 283 */ "trnm ::= nm",
  109734. /* 284 */ "trnm ::= nm DOT nm",
  109735. /* 285 */ "tridxby ::=",
  109736. /* 286 */ "tridxby ::= INDEXED BY nm",
  109737. /* 287 */ "tridxby ::= NOT INDEXED",
  109738. /* 288 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  109739. /* 289 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist",
  109740. /* 290 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  109741. /* 291 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  109742. /* 292 */ "trigger_cmd ::= select",
  109743. /* 293 */ "expr ::= RAISE LP IGNORE RP",
  109744. /* 294 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  109745. /* 295 */ "raisetype ::= ROLLBACK",
  109746. /* 296 */ "raisetype ::= ABORT",
  109747. /* 297 */ "raisetype ::= FAIL",
  109748. /* 298 */ "cmd ::= DROP TRIGGER ifexists fullname",
  109749. /* 299 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  109750. /* 300 */ "cmd ::= DETACH database_kw_opt expr",
  109751. /* 301 */ "key_opt ::=",
  109752. /* 302 */ "key_opt ::= KEY expr",
  109753. /* 303 */ "database_kw_opt ::= DATABASE",
  109754. /* 304 */ "database_kw_opt ::=",
  109755. /* 305 */ "cmd ::= REINDEX",
  109756. /* 306 */ "cmd ::= REINDEX nm dbnm",
  109757. /* 307 */ "cmd ::= ANALYZE",
  109758. /* 308 */ "cmd ::= ANALYZE nm dbnm",
  109759. /* 309 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  109760. /* 310 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  109761. /* 311 */ "add_column_fullname ::= fullname",
  109762. /* 312 */ "kwcolumn_opt ::=",
  109763. /* 313 */ "kwcolumn_opt ::= COLUMNKW",
  109764. /* 314 */ "cmd ::= create_vtab",
  109765. /* 315 */ "cmd ::= create_vtab LP vtabarglist RP",
  109766. /* 316 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  109767. /* 317 */ "vtabarglist ::= vtabarg",
  109768. /* 318 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  109769. /* 319 */ "vtabarg ::=",
  109770. /* 320 */ "vtabarg ::= vtabarg vtabargtoken",
  109771. /* 321 */ "vtabargtoken ::= ANY",
  109772. /* 322 */ "vtabargtoken ::= lp anylist RP",
  109773. /* 323 */ "lp ::= LP",
  109774. /* 324 */ "anylist ::=",
  109775. /* 325 */ "anylist ::= anylist LP anylist RP",
  109776. /* 326 */ "anylist ::= anylist ANY",
  109777. };
  109778. #endif /* NDEBUG */
  109779. #if YYSTACKDEPTH<=0
  109780. /*
  109781. ** Try to increase the size of the parser stack.
  109782. */
  109783. static void yyGrowStack(yyParser *p){
  109784. int newSize;
  109785. yyStackEntry *pNew;
  109786. newSize = p->yystksz*2 + 100;
  109787. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  109788. if( pNew ){
  109789. p->yystack = pNew;
  109790. p->yystksz = newSize;
  109791. #ifndef NDEBUG
  109792. if( yyTraceFILE ){
  109793. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  109794. yyTracePrompt, p->yystksz);
  109795. }
  109796. #endif
  109797. }
  109798. }
  109799. #endif
  109800. /*
  109801. ** This function allocates a new parser.
  109802. ** The only argument is a pointer to a function which works like
  109803. ** malloc.
  109804. **
  109805. ** Inputs:
  109806. ** A pointer to the function used to allocate memory.
  109807. **
  109808. ** Outputs:
  109809. ** A pointer to a parser. This pointer is used in subsequent calls
  109810. ** to sqlite3Parser and sqlite3ParserFree.
  109811. */
  109812. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
  109813. yyParser *pParser;
  109814. pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  109815. if( pParser ){
  109816. pParser->yyidx = -1;
  109817. #ifdef YYTRACKMAXSTACKDEPTH
  109818. pParser->yyidxMax = 0;
  109819. #endif
  109820. #if YYSTACKDEPTH<=0
  109821. pParser->yystack = NULL;
  109822. pParser->yystksz = 0;
  109823. yyGrowStack(pParser);
  109824. #endif
  109825. }
  109826. return pParser;
  109827. }
  109828. /* The following function deletes the value associated with a
  109829. ** symbol. The symbol can be either a terminal or nonterminal.
  109830. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  109831. ** the value.
  109832. */
  109833. static void yy_destructor(
  109834. yyParser *yypParser, /* The parser */
  109835. YYCODETYPE yymajor, /* Type code for object to destroy */
  109836. YYMINORTYPE *yypminor /* The object to be destroyed */
  109837. ){
  109838. sqlite3ParserARG_FETCH;
  109839. switch( yymajor ){
  109840. /* Here is inserted the actions which take place when a
  109841. ** terminal or non-terminal is destroyed. This can happen
  109842. ** when the symbol is popped from the stack during a
  109843. ** reduce or during error processing or when a parser is
  109844. ** being destroyed before it is finished parsing.
  109845. **
  109846. ** Note: during a reduce, the only symbols destroyed are those
  109847. ** which appear on the RHS of the rule, but which are not used
  109848. ** inside the C code.
  109849. */
  109850. case 160: /* select */
  109851. case 194: /* oneselect */
  109852. {
  109853. sqlite3SelectDelete(pParse->db, (yypminor->yy159));
  109854. }
  109855. break;
  109856. case 173: /* term */
  109857. case 174: /* expr */
  109858. {
  109859. sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
  109860. }
  109861. break;
  109862. case 178: /* idxlist_opt */
  109863. case 187: /* idxlist */
  109864. case 197: /* selcollist */
  109865. case 200: /* groupby_opt */
  109866. case 202: /* orderby_opt */
  109867. case 204: /* sclp */
  109868. case 214: /* sortlist */
  109869. case 215: /* nexprlist */
  109870. case 216: /* setlist */
  109871. case 220: /* exprlist */
  109872. case 225: /* case_exprlist */
  109873. {
  109874. sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
  109875. }
  109876. break;
  109877. case 193: /* fullname */
  109878. case 198: /* from */
  109879. case 206: /* seltablist */
  109880. case 207: /* stl_prefix */
  109881. {
  109882. sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
  109883. }
  109884. break;
  109885. case 199: /* where_opt */
  109886. case 201: /* having_opt */
  109887. case 210: /* on_opt */
  109888. case 224: /* case_operand */
  109889. case 226: /* case_else */
  109890. case 236: /* when_clause */
  109891. case 241: /* key_opt */
  109892. {
  109893. sqlite3ExprDelete(pParse->db, (yypminor->yy122));
  109894. }
  109895. break;
  109896. case 211: /* using_opt */
  109897. case 213: /* inscollist */
  109898. case 218: /* inscollist_opt */
  109899. {
  109900. sqlite3IdListDelete(pParse->db, (yypminor->yy180));
  109901. }
  109902. break;
  109903. case 219: /* valuelist */
  109904. {
  109905. sqlite3ExprListDelete(pParse->db, (yypminor->yy487).pList);
  109906. sqlite3SelectDelete(pParse->db, (yypminor->yy487).pSelect);
  109907. }
  109908. break;
  109909. case 232: /* trigger_cmd_list */
  109910. case 237: /* trigger_cmd */
  109911. {
  109912. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
  109913. }
  109914. break;
  109915. case 234: /* trigger_event */
  109916. {
  109917. sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
  109918. }
  109919. break;
  109920. default: break; /* If no destructor action specified: do nothing */
  109921. }
  109922. }
  109923. /*
  109924. ** Pop the parser's stack once.
  109925. **
  109926. ** If there is a destructor routine associated with the token which
  109927. ** is popped from the stack, then call it.
  109928. **
  109929. ** Return the major token number for the symbol popped.
  109930. */
  109931. static int yy_pop_parser_stack(yyParser *pParser){
  109932. YYCODETYPE yymajor;
  109933. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  109934. /* There is no mechanism by which the parser stack can be popped below
  109935. ** empty in SQLite. */
  109936. if( NEVER(pParser->yyidx<0) ) return 0;
  109937. #ifndef NDEBUG
  109938. if( yyTraceFILE && pParser->yyidx>=0 ){
  109939. fprintf(yyTraceFILE,"%sPopping %s\n",
  109940. yyTracePrompt,
  109941. yyTokenName[yytos->major]);
  109942. }
  109943. #endif
  109944. yymajor = yytos->major;
  109945. yy_destructor(pParser, yymajor, &yytos->minor);
  109946. pParser->yyidx--;
  109947. return yymajor;
  109948. }
  109949. /*
  109950. ** Deallocate and destroy a parser. Destructors are all called for
  109951. ** all stack elements before shutting the parser down.
  109952. **
  109953. ** Inputs:
  109954. ** <ul>
  109955. ** <li> A pointer to the parser. This should be a pointer
  109956. ** obtained from sqlite3ParserAlloc.
  109957. ** <li> A pointer to a function used to reclaim memory obtained
  109958. ** from malloc.
  109959. ** </ul>
  109960. */
  109961. SQLITE_PRIVATE void sqlite3ParserFree(
  109962. void *p, /* The parser to be deleted */
  109963. void (*freeProc)(void*) /* Function used to reclaim memory */
  109964. ){
  109965. yyParser *pParser = (yyParser*)p;
  109966. /* In SQLite, we never try to destroy a parser that was not successfully
  109967. ** created in the first place. */
  109968. if( NEVER(pParser==0) ) return;
  109969. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  109970. #if YYSTACKDEPTH<=0
  109971. free(pParser->yystack);
  109972. #endif
  109973. (*freeProc)((void*)pParser);
  109974. }
  109975. /*
  109976. ** Return the peak depth of the stack for a parser.
  109977. */
  109978. #ifdef YYTRACKMAXSTACKDEPTH
  109979. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  109980. yyParser *pParser = (yyParser*)p;
  109981. return pParser->yyidxMax;
  109982. }
  109983. #endif
  109984. /*
  109985. ** Find the appropriate action for a parser given the terminal
  109986. ** look-ahead token iLookAhead.
  109987. **
  109988. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  109989. ** independent of the look-ahead. If it is, return the action, otherwise
  109990. ** return YY_NO_ACTION.
  109991. */
  109992. static int yy_find_shift_action(
  109993. yyParser *pParser, /* The parser */
  109994. YYCODETYPE iLookAhead /* The look-ahead token */
  109995. ){
  109996. int i;
  109997. int stateno = pParser->yystack[pParser->yyidx].stateno;
  109998. if( stateno>YY_SHIFT_COUNT
  109999. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  110000. return yy_default[stateno];
  110001. }
  110002. assert( iLookAhead!=YYNOCODE );
  110003. i += iLookAhead;
  110004. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  110005. if( iLookAhead>0 ){
  110006. #ifdef YYFALLBACK
  110007. YYCODETYPE iFallback; /* Fallback token */
  110008. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  110009. && (iFallback = yyFallback[iLookAhead])!=0 ){
  110010. #ifndef NDEBUG
  110011. if( yyTraceFILE ){
  110012. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  110013. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  110014. }
  110015. #endif
  110016. return yy_find_shift_action(pParser, iFallback);
  110017. }
  110018. #endif
  110019. #ifdef YYWILDCARD
  110020. {
  110021. int j = i - iLookAhead + YYWILDCARD;
  110022. if(
  110023. #if YY_SHIFT_MIN+YYWILDCARD<0
  110024. j>=0 &&
  110025. #endif
  110026. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  110027. j<YY_ACTTAB_COUNT &&
  110028. #endif
  110029. yy_lookahead[j]==YYWILDCARD
  110030. ){
  110031. #ifndef NDEBUG
  110032. if( yyTraceFILE ){
  110033. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  110034. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  110035. }
  110036. #endif /* NDEBUG */
  110037. return yy_action[j];
  110038. }
  110039. }
  110040. #endif /* YYWILDCARD */
  110041. }
  110042. return yy_default[stateno];
  110043. }else{
  110044. return yy_action[i];
  110045. }
  110046. }
  110047. /*
  110048. ** Find the appropriate action for a parser given the non-terminal
  110049. ** look-ahead token iLookAhead.
  110050. **
  110051. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  110052. ** independent of the look-ahead. If it is, return the action, otherwise
  110053. ** return YY_NO_ACTION.
  110054. */
  110055. static int yy_find_reduce_action(
  110056. int stateno, /* Current state number */
  110057. YYCODETYPE iLookAhead /* The look-ahead token */
  110058. ){
  110059. int i;
  110060. #ifdef YYERRORSYMBOL
  110061. if( stateno>YY_REDUCE_COUNT ){
  110062. return yy_default[stateno];
  110063. }
  110064. #else
  110065. assert( stateno<=YY_REDUCE_COUNT );
  110066. #endif
  110067. i = yy_reduce_ofst[stateno];
  110068. assert( i!=YY_REDUCE_USE_DFLT );
  110069. assert( iLookAhead!=YYNOCODE );
  110070. i += iLookAhead;
  110071. #ifdef YYERRORSYMBOL
  110072. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  110073. return yy_default[stateno];
  110074. }
  110075. #else
  110076. assert( i>=0 && i<YY_ACTTAB_COUNT );
  110077. assert( yy_lookahead[i]==iLookAhead );
  110078. #endif
  110079. return yy_action[i];
  110080. }
  110081. /*
  110082. ** The following routine is called if the stack overflows.
  110083. */
  110084. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  110085. sqlite3ParserARG_FETCH;
  110086. yypParser->yyidx--;
  110087. #ifndef NDEBUG
  110088. if( yyTraceFILE ){
  110089. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  110090. }
  110091. #endif
  110092. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  110093. /* Here code is inserted which will execute if the parser
  110094. ** stack every overflows */
  110095. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  110096. sqlite3ErrorMsg(pParse, "parser stack overflow");
  110097. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  110098. }
  110099. /*
  110100. ** Perform a shift action.
  110101. */
  110102. static void yy_shift(
  110103. yyParser *yypParser, /* The parser to be shifted */
  110104. int yyNewState, /* The new state to shift in */
  110105. int yyMajor, /* The major token to shift in */
  110106. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  110107. ){
  110108. yyStackEntry *yytos;
  110109. yypParser->yyidx++;
  110110. #ifdef YYTRACKMAXSTACKDEPTH
  110111. if( yypParser->yyidx>yypParser->yyidxMax ){
  110112. yypParser->yyidxMax = yypParser->yyidx;
  110113. }
  110114. #endif
  110115. #if YYSTACKDEPTH>0
  110116. if( yypParser->yyidx>=YYSTACKDEPTH ){
  110117. yyStackOverflow(yypParser, yypMinor);
  110118. return;
  110119. }
  110120. #else
  110121. if( yypParser->yyidx>=yypParser->yystksz ){
  110122. yyGrowStack(yypParser);
  110123. if( yypParser->yyidx>=yypParser->yystksz ){
  110124. yyStackOverflow(yypParser, yypMinor);
  110125. return;
  110126. }
  110127. }
  110128. #endif
  110129. yytos = &yypParser->yystack[yypParser->yyidx];
  110130. yytos->stateno = (YYACTIONTYPE)yyNewState;
  110131. yytos->major = (YYCODETYPE)yyMajor;
  110132. yytos->minor = *yypMinor;
  110133. #ifndef NDEBUG
  110134. if( yyTraceFILE && yypParser->yyidx>0 ){
  110135. int i;
  110136. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  110137. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  110138. for(i=1; i<=yypParser->yyidx; i++)
  110139. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  110140. fprintf(yyTraceFILE,"\n");
  110141. }
  110142. #endif
  110143. }
  110144. /* The following table contains information about every rule that
  110145. ** is used during the reduce.
  110146. */
  110147. static const struct {
  110148. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  110149. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  110150. } yyRuleInfo[] = {
  110151. { 142, 1 },
  110152. { 143, 2 },
  110153. { 143, 1 },
  110154. { 144, 1 },
  110155. { 144, 3 },
  110156. { 145, 0 },
  110157. { 145, 1 },
  110158. { 145, 3 },
  110159. { 146, 1 },
  110160. { 147, 3 },
  110161. { 149, 0 },
  110162. { 149, 1 },
  110163. { 149, 2 },
  110164. { 148, 0 },
  110165. { 148, 1 },
  110166. { 148, 1 },
  110167. { 148, 1 },
  110168. { 147, 2 },
  110169. { 147, 2 },
  110170. { 147, 2 },
  110171. { 151, 1 },
  110172. { 151, 0 },
  110173. { 147, 2 },
  110174. { 147, 3 },
  110175. { 147, 5 },
  110176. { 147, 2 },
  110177. { 152, 6 },
  110178. { 154, 1 },
  110179. { 156, 0 },
  110180. { 156, 3 },
  110181. { 155, 1 },
  110182. { 155, 0 },
  110183. { 153, 4 },
  110184. { 153, 2 },
  110185. { 158, 3 },
  110186. { 158, 1 },
  110187. { 161, 3 },
  110188. { 162, 1 },
  110189. { 165, 1 },
  110190. { 165, 1 },
  110191. { 166, 1 },
  110192. { 150, 1 },
  110193. { 150, 1 },
  110194. { 150, 1 },
  110195. { 163, 0 },
  110196. { 163, 1 },
  110197. { 167, 1 },
  110198. { 167, 4 },
  110199. { 167, 6 },
  110200. { 168, 1 },
  110201. { 168, 2 },
  110202. { 169, 1 },
  110203. { 169, 1 },
  110204. { 164, 2 },
  110205. { 164, 0 },
  110206. { 172, 2 },
  110207. { 172, 2 },
  110208. { 172, 4 },
  110209. { 172, 3 },
  110210. { 172, 3 },
  110211. { 172, 2 },
  110212. { 172, 2 },
  110213. { 172, 3 },
  110214. { 172, 5 },
  110215. { 172, 2 },
  110216. { 172, 4 },
  110217. { 172, 4 },
  110218. { 172, 1 },
  110219. { 172, 2 },
  110220. { 177, 0 },
  110221. { 177, 1 },
  110222. { 179, 0 },
  110223. { 179, 2 },
  110224. { 181, 2 },
  110225. { 181, 3 },
  110226. { 181, 3 },
  110227. { 181, 3 },
  110228. { 182, 2 },
  110229. { 182, 2 },
  110230. { 182, 1 },
  110231. { 182, 1 },
  110232. { 182, 2 },
  110233. { 180, 3 },
  110234. { 180, 2 },
  110235. { 183, 0 },
  110236. { 183, 2 },
  110237. { 183, 2 },
  110238. { 159, 0 },
  110239. { 159, 2 },
  110240. { 184, 3 },
  110241. { 184, 1 },
  110242. { 185, 1 },
  110243. { 185, 0 },
  110244. { 186, 2 },
  110245. { 186, 7 },
  110246. { 186, 5 },
  110247. { 186, 5 },
  110248. { 186, 10 },
  110249. { 188, 0 },
  110250. { 188, 1 },
  110251. { 175, 0 },
  110252. { 175, 3 },
  110253. { 189, 0 },
  110254. { 189, 2 },
  110255. { 190, 1 },
  110256. { 190, 1 },
  110257. { 190, 1 },
  110258. { 147, 4 },
  110259. { 192, 2 },
  110260. { 192, 0 },
  110261. { 147, 8 },
  110262. { 147, 4 },
  110263. { 147, 1 },
  110264. { 160, 1 },
  110265. { 160, 3 },
  110266. { 195, 1 },
  110267. { 195, 2 },
  110268. { 195, 1 },
  110269. { 194, 9 },
  110270. { 196, 1 },
  110271. { 196, 1 },
  110272. { 196, 0 },
  110273. { 204, 2 },
  110274. { 204, 0 },
  110275. { 197, 3 },
  110276. { 197, 2 },
  110277. { 197, 4 },
  110278. { 205, 2 },
  110279. { 205, 1 },
  110280. { 205, 0 },
  110281. { 198, 0 },
  110282. { 198, 2 },
  110283. { 207, 2 },
  110284. { 207, 0 },
  110285. { 206, 7 },
  110286. { 206, 7 },
  110287. { 206, 7 },
  110288. { 157, 0 },
  110289. { 157, 2 },
  110290. { 193, 2 },
  110291. { 208, 1 },
  110292. { 208, 2 },
  110293. { 208, 3 },
  110294. { 208, 4 },
  110295. { 210, 2 },
  110296. { 210, 0 },
  110297. { 209, 0 },
  110298. { 209, 3 },
  110299. { 209, 2 },
  110300. { 211, 4 },
  110301. { 211, 0 },
  110302. { 202, 0 },
  110303. { 202, 3 },
  110304. { 214, 4 },
  110305. { 214, 2 },
  110306. { 176, 1 },
  110307. { 176, 1 },
  110308. { 176, 0 },
  110309. { 200, 0 },
  110310. { 200, 3 },
  110311. { 201, 0 },
  110312. { 201, 2 },
  110313. { 203, 0 },
  110314. { 203, 2 },
  110315. { 203, 4 },
  110316. { 203, 4 },
  110317. { 147, 5 },
  110318. { 199, 0 },
  110319. { 199, 2 },
  110320. { 147, 7 },
  110321. { 216, 5 },
  110322. { 216, 3 },
  110323. { 147, 5 },
  110324. { 147, 5 },
  110325. { 147, 6 },
  110326. { 217, 2 },
  110327. { 217, 1 },
  110328. { 219, 4 },
  110329. { 219, 5 },
  110330. { 218, 0 },
  110331. { 218, 3 },
  110332. { 213, 3 },
  110333. { 213, 1 },
  110334. { 174, 1 },
  110335. { 174, 3 },
  110336. { 173, 1 },
  110337. { 174, 1 },
  110338. { 174, 1 },
  110339. { 174, 3 },
  110340. { 174, 5 },
  110341. { 173, 1 },
  110342. { 173, 1 },
  110343. { 174, 1 },
  110344. { 174, 1 },
  110345. { 174, 3 },
  110346. { 174, 6 },
  110347. { 174, 5 },
  110348. { 174, 4 },
  110349. { 173, 1 },
  110350. { 174, 3 },
  110351. { 174, 3 },
  110352. { 174, 3 },
  110353. { 174, 3 },
  110354. { 174, 3 },
  110355. { 174, 3 },
  110356. { 174, 3 },
  110357. { 174, 3 },
  110358. { 221, 1 },
  110359. { 221, 2 },
  110360. { 221, 1 },
  110361. { 221, 2 },
  110362. { 174, 3 },
  110363. { 174, 5 },
  110364. { 174, 2 },
  110365. { 174, 3 },
  110366. { 174, 3 },
  110367. { 174, 4 },
  110368. { 174, 2 },
  110369. { 174, 2 },
  110370. { 174, 2 },
  110371. { 174, 2 },
  110372. { 222, 1 },
  110373. { 222, 2 },
  110374. { 174, 5 },
  110375. { 223, 1 },
  110376. { 223, 2 },
  110377. { 174, 5 },
  110378. { 174, 3 },
  110379. { 174, 5 },
  110380. { 174, 4 },
  110381. { 174, 4 },
  110382. { 174, 5 },
  110383. { 225, 5 },
  110384. { 225, 4 },
  110385. { 226, 2 },
  110386. { 226, 0 },
  110387. { 224, 1 },
  110388. { 224, 0 },
  110389. { 220, 1 },
  110390. { 220, 0 },
  110391. { 215, 3 },
  110392. { 215, 1 },
  110393. { 147, 12 },
  110394. { 227, 1 },
  110395. { 227, 0 },
  110396. { 178, 0 },
  110397. { 178, 3 },
  110398. { 187, 5 },
  110399. { 187, 3 },
  110400. { 228, 0 },
  110401. { 228, 2 },
  110402. { 147, 4 },
  110403. { 147, 1 },
  110404. { 147, 2 },
  110405. { 147, 3 },
  110406. { 147, 5 },
  110407. { 147, 6 },
  110408. { 147, 5 },
  110409. { 147, 6 },
  110410. { 229, 1 },
  110411. { 229, 1 },
  110412. { 229, 1 },
  110413. { 229, 1 },
  110414. { 229, 1 },
  110415. { 170, 2 },
  110416. { 170, 1 },
  110417. { 171, 2 },
  110418. { 230, 1 },
  110419. { 147, 5 },
  110420. { 231, 11 },
  110421. { 233, 1 },
  110422. { 233, 1 },
  110423. { 233, 2 },
  110424. { 233, 0 },
  110425. { 234, 1 },
  110426. { 234, 1 },
  110427. { 234, 3 },
  110428. { 235, 0 },
  110429. { 235, 3 },
  110430. { 236, 0 },
  110431. { 236, 2 },
  110432. { 232, 3 },
  110433. { 232, 2 },
  110434. { 238, 1 },
  110435. { 238, 3 },
  110436. { 239, 0 },
  110437. { 239, 3 },
  110438. { 239, 2 },
  110439. { 237, 7 },
  110440. { 237, 5 },
  110441. { 237, 5 },
  110442. { 237, 5 },
  110443. { 237, 1 },
  110444. { 174, 4 },
  110445. { 174, 6 },
  110446. { 191, 1 },
  110447. { 191, 1 },
  110448. { 191, 1 },
  110449. { 147, 4 },
  110450. { 147, 6 },
  110451. { 147, 3 },
  110452. { 241, 0 },
  110453. { 241, 2 },
  110454. { 240, 1 },
  110455. { 240, 0 },
  110456. { 147, 1 },
  110457. { 147, 3 },
  110458. { 147, 1 },
  110459. { 147, 3 },
  110460. { 147, 6 },
  110461. { 147, 6 },
  110462. { 242, 1 },
  110463. { 243, 0 },
  110464. { 243, 1 },
  110465. { 147, 1 },
  110466. { 147, 4 },
  110467. { 244, 8 },
  110468. { 245, 1 },
  110469. { 245, 3 },
  110470. { 246, 0 },
  110471. { 246, 2 },
  110472. { 247, 1 },
  110473. { 247, 3 },
  110474. { 248, 1 },
  110475. { 249, 0 },
  110476. { 249, 4 },
  110477. { 249, 2 },
  110478. };
  110479. static void yy_accept(yyParser*); /* Forward Declaration */
  110480. /*
  110481. ** Perform a reduce action and the shift that must immediately
  110482. ** follow the reduce.
  110483. */
  110484. static void yy_reduce(
  110485. yyParser *yypParser, /* The parser */
  110486. int yyruleno /* Number of the rule by which to reduce */
  110487. ){
  110488. int yygoto; /* The next state */
  110489. int yyact; /* The next action */
  110490. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  110491. yyStackEntry *yymsp; /* The top of the parser's stack */
  110492. int yysize; /* Amount to pop the stack */
  110493. sqlite3ParserARG_FETCH;
  110494. yymsp = &yypParser->yystack[yypParser->yyidx];
  110495. #ifndef NDEBUG
  110496. if( yyTraceFILE && yyruleno>=0
  110497. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  110498. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  110499. yyRuleName[yyruleno]);
  110500. }
  110501. #endif /* NDEBUG */
  110502. /* Silence complaints from purify about yygotominor being uninitialized
  110503. ** in some cases when it is copied into the stack after the following
  110504. ** switch. yygotominor is uninitialized when a rule reduces that does
  110505. ** not set the value of its left-hand side nonterminal. Leaving the
  110506. ** value of the nonterminal uninitialized is utterly harmless as long
  110507. ** as the value is never used. So really the only thing this code
  110508. ** accomplishes is to quieten purify.
  110509. **
  110510. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  110511. ** without this code, their parser segfaults. I'm not sure what there
  110512. ** parser is doing to make this happen. This is the second bug report
  110513. ** from wireshark this week. Clearly they are stressing Lemon in ways
  110514. ** that it has not been previously stressed... (SQLite ticket #2172)
  110515. */
  110516. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  110517. yygotominor = yyzerominor;
  110518. switch( yyruleno ){
  110519. /* Beginning here are the reduction cases. A typical example
  110520. ** follows:
  110521. ** case 0:
  110522. ** #line <lineno> <grammarfile>
  110523. ** { ... } // User supplied code
  110524. ** #line <lineno> <thisfile>
  110525. ** break;
  110526. */
  110527. case 5: /* explain ::= */
  110528. { sqlite3BeginParse(pParse, 0); }
  110529. break;
  110530. case 6: /* explain ::= EXPLAIN */
  110531. { sqlite3BeginParse(pParse, 1); }
  110532. break;
  110533. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  110534. { sqlite3BeginParse(pParse, 2); }
  110535. break;
  110536. case 8: /* cmdx ::= cmd */
  110537. { sqlite3FinishCoding(pParse); }
  110538. break;
  110539. case 9: /* cmd ::= BEGIN transtype trans_opt */
  110540. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
  110541. break;
  110542. case 13: /* transtype ::= */
  110543. {yygotominor.yy392 = TK_DEFERRED;}
  110544. break;
  110545. case 14: /* transtype ::= DEFERRED */
  110546. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  110547. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  110548. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  110549. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  110550. {yygotominor.yy392 = yymsp[0].major;}
  110551. break;
  110552. case 17: /* cmd ::= COMMIT trans_opt */
  110553. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  110554. {sqlite3CommitTransaction(pParse);}
  110555. break;
  110556. case 19: /* cmd ::= ROLLBACK trans_opt */
  110557. {sqlite3RollbackTransaction(pParse);}
  110558. break;
  110559. case 22: /* cmd ::= SAVEPOINT nm */
  110560. {
  110561. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  110562. }
  110563. break;
  110564. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  110565. {
  110566. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  110567. }
  110568. break;
  110569. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  110570. {
  110571. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  110572. }
  110573. break;
  110574. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  110575. {
  110576. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
  110577. }
  110578. break;
  110579. case 27: /* createkw ::= CREATE */
  110580. {
  110581. pParse->db->lookaside.bEnabled = 0;
  110582. yygotominor.yy0 = yymsp[0].minor.yy0;
  110583. }
  110584. break;
  110585. case 28: /* ifnotexists ::= */
  110586. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  110587. case 69: /* autoinc ::= */ yytestcase(yyruleno==69);
  110588. case 82: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==82);
  110589. case 84: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==84);
  110590. case 86: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==86);
  110591. case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
  110592. case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
  110593. case 221: /* between_op ::= BETWEEN */ yytestcase(yyruleno==221);
  110594. case 224: /* in_op ::= IN */ yytestcase(yyruleno==224);
  110595. {yygotominor.yy392 = 0;}
  110596. break;
  110597. case 29: /* ifnotexists ::= IF NOT EXISTS */
  110598. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  110599. case 70: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==70);
  110600. case 85: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==85);
  110601. case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
  110602. case 222: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==222);
  110603. case 225: /* in_op ::= NOT IN */ yytestcase(yyruleno==225);
  110604. {yygotominor.yy392 = 1;}
  110605. break;
  110606. case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
  110607. {
  110608. sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
  110609. }
  110610. break;
  110611. case 33: /* create_table_args ::= AS select */
  110612. {
  110613. sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy159);
  110614. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  110615. }
  110616. break;
  110617. case 36: /* column ::= columnid type carglist */
  110618. {
  110619. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  110620. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  110621. }
  110622. break;
  110623. case 37: /* columnid ::= nm */
  110624. {
  110625. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  110626. yygotominor.yy0 = yymsp[0].minor.yy0;
  110627. pParse->constraintName.n = 0;
  110628. }
  110629. break;
  110630. case 38: /* id ::= ID */
  110631. case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
  110632. case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
  110633. case 41: /* nm ::= id */ yytestcase(yyruleno==41);
  110634. case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
  110635. case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
  110636. case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
  110637. case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
  110638. case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
  110639. case 128: /* as ::= ids */ yytestcase(yyruleno==128);
  110640. case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
  110641. case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
  110642. case 250: /* collate ::= COLLATE ids */ yytestcase(yyruleno==250);
  110643. case 259: /* nmnum ::= plus_num */ yytestcase(yyruleno==259);
  110644. case 260: /* nmnum ::= nm */ yytestcase(yyruleno==260);
  110645. case 261: /* nmnum ::= ON */ yytestcase(yyruleno==261);
  110646. case 262: /* nmnum ::= DELETE */ yytestcase(yyruleno==262);
  110647. case 263: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==263);
  110648. case 264: /* plus_num ::= PLUS number */ yytestcase(yyruleno==264);
  110649. case 265: /* plus_num ::= number */ yytestcase(yyruleno==265);
  110650. case 266: /* minus_num ::= MINUS number */ yytestcase(yyruleno==266);
  110651. case 267: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==267);
  110652. case 283: /* trnm ::= nm */ yytestcase(yyruleno==283);
  110653. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  110654. break;
  110655. case 45: /* type ::= typetoken */
  110656. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  110657. break;
  110658. case 47: /* typetoken ::= typename LP signed RP */
  110659. {
  110660. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  110661. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  110662. }
  110663. break;
  110664. case 48: /* typetoken ::= typename LP signed COMMA signed RP */
  110665. {
  110666. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  110667. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  110668. }
  110669. break;
  110670. case 50: /* typename ::= typename ids */
  110671. {yygotominor.yy0.z=yymsp[-1].minor.yy0.z; yygotominor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
  110672. break;
  110673. case 55: /* ccons ::= CONSTRAINT nm */
  110674. case 93: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
  110675. {pParse->constraintName = yymsp[0].minor.yy0;}
  110676. break;
  110677. case 56: /* ccons ::= DEFAULT term */
  110678. case 58: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==58);
  110679. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
  110680. break;
  110681. case 57: /* ccons ::= DEFAULT LP expr RP */
  110682. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
  110683. break;
  110684. case 59: /* ccons ::= DEFAULT MINUS term */
  110685. {
  110686. ExprSpan v;
  110687. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
  110688. v.zStart = yymsp[-1].minor.yy0.z;
  110689. v.zEnd = yymsp[0].minor.yy342.zEnd;
  110690. sqlite3AddDefaultValue(pParse,&v);
  110691. }
  110692. break;
  110693. case 60: /* ccons ::= DEFAULT id */
  110694. {
  110695. ExprSpan v;
  110696. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  110697. sqlite3AddDefaultValue(pParse,&v);
  110698. }
  110699. break;
  110700. case 62: /* ccons ::= NOT NULL onconf */
  110701. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
  110702. break;
  110703. case 63: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  110704. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
  110705. break;
  110706. case 64: /* ccons ::= UNIQUE onconf */
  110707. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
  110708. break;
  110709. case 65: /* ccons ::= CHECK LP expr RP */
  110710. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
  110711. break;
  110712. case 66: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  110713. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
  110714. break;
  110715. case 67: /* ccons ::= defer_subclause */
  110716. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
  110717. break;
  110718. case 68: /* ccons ::= COLLATE ids */
  110719. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  110720. break;
  110721. case 71: /* refargs ::= */
  110722. { yygotominor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
  110723. break;
  110724. case 72: /* refargs ::= refargs refarg */
  110725. { yygotominor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
  110726. break;
  110727. case 73: /* refarg ::= MATCH nm */
  110728. case 74: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==74);
  110729. { yygotominor.yy207.value = 0; yygotominor.yy207.mask = 0x000000; }
  110730. break;
  110731. case 75: /* refarg ::= ON DELETE refact */
  110732. { yygotominor.yy207.value = yymsp[0].minor.yy392; yygotominor.yy207.mask = 0x0000ff; }
  110733. break;
  110734. case 76: /* refarg ::= ON UPDATE refact */
  110735. { yygotominor.yy207.value = yymsp[0].minor.yy392<<8; yygotominor.yy207.mask = 0x00ff00; }
  110736. break;
  110737. case 77: /* refact ::= SET NULL */
  110738. { yygotominor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
  110739. break;
  110740. case 78: /* refact ::= SET DEFAULT */
  110741. { yygotominor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
  110742. break;
  110743. case 79: /* refact ::= CASCADE */
  110744. { yygotominor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
  110745. break;
  110746. case 80: /* refact ::= RESTRICT */
  110747. { yygotominor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
  110748. break;
  110749. case 81: /* refact ::= NO ACTION */
  110750. { yygotominor.yy392 = OE_None; /* EV: R-33326-45252 */}
  110751. break;
  110752. case 83: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  110753. case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
  110754. case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
  110755. case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
  110756. {yygotominor.yy392 = yymsp[0].minor.yy392;}
  110757. break;
  110758. case 87: /* conslist_opt ::= */
  110759. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  110760. break;
  110761. case 88: /* conslist_opt ::= COMMA conslist */
  110762. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  110763. break;
  110764. case 91: /* tconscomma ::= COMMA */
  110765. {pParse->constraintName.n = 0;}
  110766. break;
  110767. case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  110768. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
  110769. break;
  110770. case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
  110771. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
  110772. break;
  110773. case 96: /* tcons ::= CHECK LP expr RP onconf */
  110774. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
  110775. break;
  110776. case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  110777. {
  110778. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
  110779. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
  110780. }
  110781. break;
  110782. case 100: /* onconf ::= */
  110783. {yygotominor.yy392 = OE_Default;}
  110784. break;
  110785. case 102: /* orconf ::= */
  110786. {yygotominor.yy258 = OE_Default;}
  110787. break;
  110788. case 103: /* orconf ::= OR resolvetype */
  110789. {yygotominor.yy258 = (u8)yymsp[0].minor.yy392;}
  110790. break;
  110791. case 105: /* resolvetype ::= IGNORE */
  110792. {yygotominor.yy392 = OE_Ignore;}
  110793. break;
  110794. case 106: /* resolvetype ::= REPLACE */
  110795. {yygotominor.yy392 = OE_Replace;}
  110796. break;
  110797. case 107: /* cmd ::= DROP TABLE ifexists fullname */
  110798. {
  110799. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
  110800. }
  110801. break;
  110802. case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  110803. {
  110804. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy159, yymsp[-6].minor.yy392, yymsp[-4].minor.yy392);
  110805. }
  110806. break;
  110807. case 111: /* cmd ::= DROP VIEW ifexists fullname */
  110808. {
  110809. sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
  110810. }
  110811. break;
  110812. case 112: /* cmd ::= select */
  110813. {
  110814. SelectDest dest = {SRT_Output, 0, 0, 0, 0};
  110815. sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
  110816. sqlite3ExplainBegin(pParse->pVdbe);
  110817. sqlite3ExplainSelect(pParse->pVdbe, yymsp[0].minor.yy159);
  110818. sqlite3ExplainFinish(pParse->pVdbe);
  110819. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
  110820. }
  110821. break;
  110822. case 113: /* select ::= oneselect */
  110823. {yygotominor.yy159 = yymsp[0].minor.yy159;}
  110824. break;
  110825. case 114: /* select ::= select multiselect_op oneselect */
  110826. {
  110827. if( yymsp[0].minor.yy159 ){
  110828. yymsp[0].minor.yy159->op = (u8)yymsp[-1].minor.yy392;
  110829. yymsp[0].minor.yy159->pPrior = yymsp[-2].minor.yy159;
  110830. if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
  110831. }else{
  110832. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy159);
  110833. }
  110834. yygotominor.yy159 = yymsp[0].minor.yy159;
  110835. }
  110836. break;
  110837. case 116: /* multiselect_op ::= UNION ALL */
  110838. {yygotominor.yy392 = TK_ALL;}
  110839. break;
  110840. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  110841. {
  110842. yygotominor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy305,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
  110843. }
  110844. break;
  110845. case 119: /* distinct ::= DISTINCT */
  110846. {yygotominor.yy305 = SF_Distinct;}
  110847. break;
  110848. case 120: /* distinct ::= ALL */
  110849. case 121: /* distinct ::= */ yytestcase(yyruleno==121);
  110850. {yygotominor.yy305 = 0;}
  110851. break;
  110852. case 122: /* sclp ::= selcollist COMMA */
  110853. case 246: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==246);
  110854. {yygotominor.yy442 = yymsp[-1].minor.yy442;}
  110855. break;
  110856. case 123: /* sclp ::= */
  110857. case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
  110858. case 158: /* groupby_opt ::= */ yytestcase(yyruleno==158);
  110859. case 239: /* exprlist ::= */ yytestcase(yyruleno==239);
  110860. case 245: /* idxlist_opt ::= */ yytestcase(yyruleno==245);
  110861. {yygotominor.yy442 = 0;}
  110862. break;
  110863. case 124: /* selcollist ::= sclp expr as */
  110864. {
  110865. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
  110866. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[0].minor.yy0, 1);
  110867. sqlite3ExprListSetSpan(pParse,yygotominor.yy442,&yymsp[-1].minor.yy342);
  110868. }
  110869. break;
  110870. case 125: /* selcollist ::= sclp STAR */
  110871. {
  110872. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  110873. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
  110874. }
  110875. break;
  110876. case 126: /* selcollist ::= sclp nm DOT STAR */
  110877. {
  110878. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  110879. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  110880. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  110881. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
  110882. }
  110883. break;
  110884. case 129: /* as ::= */
  110885. {yygotominor.yy0.n = 0;}
  110886. break;
  110887. case 130: /* from ::= */
  110888. {yygotominor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy347));}
  110889. break;
  110890. case 131: /* from ::= FROM seltablist */
  110891. {
  110892. yygotominor.yy347 = yymsp[0].minor.yy347;
  110893. sqlite3SrcListShiftJoinType(yygotominor.yy347);
  110894. }
  110895. break;
  110896. case 132: /* stl_prefix ::= seltablist joinop */
  110897. {
  110898. yygotominor.yy347 = yymsp[-1].minor.yy347;
  110899. if( ALWAYS(yygotominor.yy347 && yygotominor.yy347->nSrc>0) ) yygotominor.yy347->a[yygotominor.yy347->nSrc-1].jointype = (u8)yymsp[0].minor.yy392;
  110900. }
  110901. break;
  110902. case 133: /* stl_prefix ::= */
  110903. {yygotominor.yy347 = 0;}
  110904. break;
  110905. case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  110906. {
  110907. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110908. sqlite3SrcListIndexedBy(pParse, yygotominor.yy347, &yymsp[-2].minor.yy0);
  110909. }
  110910. break;
  110911. case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  110912. {
  110913. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110914. }
  110915. break;
  110916. case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  110917. {
  110918. if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
  110919. yygotominor.yy347 = yymsp[-4].minor.yy347;
  110920. }else if( yymsp[-4].minor.yy347->nSrc==1 ){
  110921. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110922. if( yygotominor.yy347 ){
  110923. struct SrcList_item *pNew = &yygotominor.yy347->a[yygotominor.yy347->nSrc-1];
  110924. struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
  110925. pNew->zName = pOld->zName;
  110926. pNew->zDatabase = pOld->zDatabase;
  110927. pNew->pSelect = pOld->pSelect;
  110928. pOld->zName = pOld->zDatabase = 0;
  110929. pOld->pSelect = 0;
  110930. }
  110931. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
  110932. }else{
  110933. Select *pSubquery;
  110934. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
  110935. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
  110936. yygotominor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
  110937. }
  110938. }
  110939. break;
  110940. case 137: /* dbnm ::= */
  110941. case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
  110942. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  110943. break;
  110944. case 139: /* fullname ::= nm dbnm */
  110945. {yygotominor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  110946. break;
  110947. case 140: /* joinop ::= COMMA|JOIN */
  110948. { yygotominor.yy392 = JT_INNER; }
  110949. break;
  110950. case 141: /* joinop ::= JOIN_KW JOIN */
  110951. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  110952. break;
  110953. case 142: /* joinop ::= JOIN_KW nm JOIN */
  110954. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  110955. break;
  110956. case 143: /* joinop ::= JOIN_KW nm nm JOIN */
  110957. { yygotominor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  110958. break;
  110959. case 144: /* on_opt ::= ON expr */
  110960. case 161: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==161);
  110961. case 168: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==168);
  110962. case 234: /* case_else ::= ELSE expr */ yytestcase(yyruleno==234);
  110963. case 236: /* case_operand ::= expr */ yytestcase(yyruleno==236);
  110964. {yygotominor.yy122 = yymsp[0].minor.yy342.pExpr;}
  110965. break;
  110966. case 145: /* on_opt ::= */
  110967. case 160: /* having_opt ::= */ yytestcase(yyruleno==160);
  110968. case 167: /* where_opt ::= */ yytestcase(yyruleno==167);
  110969. case 235: /* case_else ::= */ yytestcase(yyruleno==235);
  110970. case 237: /* case_operand ::= */ yytestcase(yyruleno==237);
  110971. {yygotominor.yy122 = 0;}
  110972. break;
  110973. case 148: /* indexed_opt ::= NOT INDEXED */
  110974. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  110975. break;
  110976. case 149: /* using_opt ::= USING LP inscollist RP */
  110977. case 180: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==180);
  110978. {yygotominor.yy180 = yymsp[-1].minor.yy180;}
  110979. break;
  110980. case 150: /* using_opt ::= */
  110981. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  110982. {yygotominor.yy180 = 0;}
  110983. break;
  110984. case 152: /* orderby_opt ::= ORDER BY sortlist */
  110985. case 159: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==159);
  110986. case 238: /* exprlist ::= nexprlist */ yytestcase(yyruleno==238);
  110987. {yygotominor.yy442 = yymsp[0].minor.yy442;}
  110988. break;
  110989. case 153: /* sortlist ::= sortlist COMMA expr sortorder */
  110990. {
  110991. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
  110992. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  110993. }
  110994. break;
  110995. case 154: /* sortlist ::= expr sortorder */
  110996. {
  110997. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr);
  110998. if( yygotominor.yy442 && ALWAYS(yygotominor.yy442->a) ) yygotominor.yy442->a[0].sortOrder = (u8)yymsp[0].minor.yy392;
  110999. }
  111000. break;
  111001. case 155: /* sortorder ::= ASC */
  111002. case 157: /* sortorder ::= */ yytestcase(yyruleno==157);
  111003. {yygotominor.yy392 = SQLITE_SO_ASC;}
  111004. break;
  111005. case 156: /* sortorder ::= DESC */
  111006. {yygotominor.yy392 = SQLITE_SO_DESC;}
  111007. break;
  111008. case 162: /* limit_opt ::= */
  111009. {yygotominor.yy64.pLimit = 0; yygotominor.yy64.pOffset = 0;}
  111010. break;
  111011. case 163: /* limit_opt ::= LIMIT expr */
  111012. {yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yygotominor.yy64.pOffset = 0;}
  111013. break;
  111014. case 164: /* limit_opt ::= LIMIT expr OFFSET expr */
  111015. {yygotominor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
  111016. break;
  111017. case 165: /* limit_opt ::= LIMIT expr COMMA expr */
  111018. {yygotominor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yygotominor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
  111019. break;
  111020. case 166: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
  111021. {
  111022. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
  111023. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
  111024. }
  111025. break;
  111026. case 169: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
  111027. {
  111028. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
  111029. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
  111030. sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy258);
  111031. }
  111032. break;
  111033. case 170: /* setlist ::= setlist COMMA nm EQ expr */
  111034. {
  111035. yygotominor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
  111036. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111037. }
  111038. break;
  111039. case 171: /* setlist ::= nm EQ expr */
  111040. {
  111041. yygotominor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
  111042. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111043. }
  111044. break;
  111045. case 172: /* cmd ::= insert_cmd INTO fullname inscollist_opt valuelist */
  111046. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  111047. break;
  111048. case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
  111049. {sqlite3Insert(pParse, yymsp[-2].minor.yy347, 0, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy258);}
  111050. break;
  111051. case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  111052. {sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy258);}
  111053. break;
  111054. case 175: /* insert_cmd ::= INSERT orconf */
  111055. {yygotominor.yy258 = yymsp[0].minor.yy258;}
  111056. break;
  111057. case 176: /* insert_cmd ::= REPLACE */
  111058. {yygotominor.yy258 = OE_Replace;}
  111059. break;
  111060. case 177: /* valuelist ::= VALUES LP nexprlist RP */
  111061. {
  111062. yygotominor.yy487.pList = yymsp[-1].minor.yy442;
  111063. yygotominor.yy487.pSelect = 0;
  111064. }
  111065. break;
  111066. case 178: /* valuelist ::= valuelist COMMA LP exprlist RP */
  111067. {
  111068. Select *pRight = sqlite3SelectNew(pParse, yymsp[-1].minor.yy442, 0, 0, 0, 0, 0, 0, 0, 0);
  111069. if( yymsp[-4].minor.yy487.pList ){
  111070. yymsp[-4].minor.yy487.pSelect = sqlite3SelectNew(pParse, yymsp[-4].minor.yy487.pList, 0, 0, 0, 0, 0, 0, 0, 0);
  111071. yymsp[-4].minor.yy487.pList = 0;
  111072. }
  111073. yygotominor.yy487.pList = 0;
  111074. if( yymsp[-4].minor.yy487.pSelect==0 || pRight==0 ){
  111075. sqlite3SelectDelete(pParse->db, pRight);
  111076. sqlite3SelectDelete(pParse->db, yymsp[-4].minor.yy487.pSelect);
  111077. yygotominor.yy487.pSelect = 0;
  111078. }else{
  111079. pRight->op = TK_ALL;
  111080. pRight->pPrior = yymsp[-4].minor.yy487.pSelect;
  111081. pRight->selFlags |= SF_Values;
  111082. pRight->pPrior->selFlags |= SF_Values;
  111083. yygotominor.yy487.pSelect = pRight;
  111084. }
  111085. }
  111086. break;
  111087. case 181: /* inscollist ::= inscollist COMMA nm */
  111088. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
  111089. break;
  111090. case 182: /* inscollist ::= nm */
  111091. {yygotominor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  111092. break;
  111093. case 183: /* expr ::= term */
  111094. {yygotominor.yy342 = yymsp[0].minor.yy342;}
  111095. break;
  111096. case 184: /* expr ::= LP expr RP */
  111097. {yygotominor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr; spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  111098. break;
  111099. case 185: /* term ::= NULL */
  111100. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  111101. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  111102. {spanExpr(&yygotominor.yy342, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  111103. break;
  111104. case 186: /* expr ::= id */
  111105. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  111106. {spanExpr(&yygotominor.yy342, pParse, TK_ID, &yymsp[0].minor.yy0);}
  111107. break;
  111108. case 188: /* expr ::= nm DOT nm */
  111109. {
  111110. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  111111. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  111112. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  111113. spanSet(&yygotominor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  111114. }
  111115. break;
  111116. case 189: /* expr ::= nm DOT nm DOT nm */
  111117. {
  111118. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  111119. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  111120. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  111121. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  111122. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  111123. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  111124. }
  111125. break;
  111126. case 192: /* expr ::= REGISTER */
  111127. {
  111128. /* When doing a nested parse, one can include terms in an expression
  111129. ** that look like this: #1 #2 ... These terms refer to registers
  111130. ** in the virtual machine. #N is the N-th register. */
  111131. if( pParse->nested==0 ){
  111132. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  111133. yygotominor.yy342.pExpr = 0;
  111134. }else{
  111135. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  111136. if( yygotominor.yy342.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy342.pExpr->iTable);
  111137. }
  111138. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111139. }
  111140. break;
  111141. case 193: /* expr ::= VARIABLE */
  111142. {
  111143. spanExpr(&yygotominor.yy342, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  111144. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy342.pExpr);
  111145. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111146. }
  111147. break;
  111148. case 194: /* expr ::= expr COLLATE ids */
  111149. {
  111150. yygotominor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0);
  111151. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  111152. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111153. }
  111154. break;
  111155. case 195: /* expr ::= CAST LP expr AS typetoken RP */
  111156. {
  111157. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
  111158. spanSet(&yygotominor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  111159. }
  111160. break;
  111161. case 196: /* expr ::= ID LP distinct exprlist RP */
  111162. {
  111163. if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  111164. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  111165. }
  111166. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
  111167. spanSet(&yygotominor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  111168. if( yymsp[-2].minor.yy305 && yygotominor.yy342.pExpr ){
  111169. yygotominor.yy342.pExpr->flags |= EP_Distinct;
  111170. }
  111171. }
  111172. break;
  111173. case 197: /* expr ::= ID LP STAR RP */
  111174. {
  111175. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  111176. spanSet(&yygotominor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  111177. }
  111178. break;
  111179. case 198: /* term ::= CTIME_KW */
  111180. {
  111181. /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
  111182. ** treated as functions that return constants */
  111183. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
  111184. if( yygotominor.yy342.pExpr ){
  111185. yygotominor.yy342.pExpr->op = TK_CONST_FUNC;
  111186. }
  111187. spanSet(&yygotominor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  111188. }
  111189. break;
  111190. case 199: /* expr ::= expr AND expr */
  111191. case 200: /* expr ::= expr OR expr */ yytestcase(yyruleno==200);
  111192. case 201: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==201);
  111193. case 202: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==202);
  111194. case 203: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==203);
  111195. case 204: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==204);
  111196. case 205: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==205);
  111197. case 206: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==206);
  111198. {spanBinaryExpr(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
  111199. break;
  111200. case 207: /* likeop ::= LIKE_KW */
  111201. case 209: /* likeop ::= MATCH */ yytestcase(yyruleno==209);
  111202. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 0;}
  111203. break;
  111204. case 208: /* likeop ::= NOT LIKE_KW */
  111205. case 210: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==210);
  111206. {yygotominor.yy318.eOperator = yymsp[0].minor.yy0; yygotominor.yy318.bNot = 1;}
  111207. break;
  111208. case 211: /* expr ::= expr likeop expr */
  111209. {
  111210. ExprList *pList;
  111211. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
  111212. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
  111213. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
  111214. if( yymsp[-1].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111215. yygotominor.yy342.zStart = yymsp[-2].minor.yy342.zStart;
  111216. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111217. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  111218. }
  111219. break;
  111220. case 212: /* expr ::= expr likeop expr ESCAPE expr */
  111221. {
  111222. ExprList *pList;
  111223. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111224. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
  111225. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  111226. yygotominor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
  111227. if( yymsp[-3].minor.yy318.bNot ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111228. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111229. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111230. if( yygotominor.yy342.pExpr ) yygotominor.yy342.pExpr->flags |= EP_InfixFunc;
  111231. }
  111232. break;
  111233. case 213: /* expr ::= expr ISNULL|NOTNULL */
  111234. {spanUnaryPostfix(&yygotominor.yy342,pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
  111235. break;
  111236. case 214: /* expr ::= expr NOT NULL */
  111237. {spanUnaryPostfix(&yygotominor.yy342,pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
  111238. break;
  111239. case 215: /* expr ::= expr IS expr */
  111240. {
  111241. spanBinaryExpr(&yygotominor.yy342,pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
  111242. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_ISNULL);
  111243. }
  111244. break;
  111245. case 216: /* expr ::= expr IS NOT expr */
  111246. {
  111247. spanBinaryExpr(&yygotominor.yy342,pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
  111248. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yygotominor.yy342.pExpr, TK_NOTNULL);
  111249. }
  111250. break;
  111251. case 217: /* expr ::= NOT expr */
  111252. case 218: /* expr ::= BITNOT expr */ yytestcase(yyruleno==218);
  111253. {spanUnaryPrefix(&yygotominor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111254. break;
  111255. case 219: /* expr ::= MINUS expr */
  111256. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111257. break;
  111258. case 220: /* expr ::= PLUS expr */
  111259. {spanUnaryPrefix(&yygotominor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);}
  111260. break;
  111261. case 223: /* expr ::= expr between_op expr AND expr */
  111262. {
  111263. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111264. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
  111265. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111266. if( yygotominor.yy342.pExpr ){
  111267. yygotominor.yy342.pExpr->x.pList = pList;
  111268. }else{
  111269. sqlite3ExprListDelete(pParse->db, pList);
  111270. }
  111271. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111272. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111273. yygotominor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
  111274. }
  111275. break;
  111276. case 226: /* expr ::= expr in_op LP exprlist RP */
  111277. {
  111278. if( yymsp[-1].minor.yy442==0 ){
  111279. /* Expressions of the form
  111280. **
  111281. ** expr1 IN ()
  111282. ** expr1 NOT IN ()
  111283. **
  111284. ** simplify to constants 0 (false) and 1 (true), respectively,
  111285. ** regardless of the value of expr1.
  111286. */
  111287. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
  111288. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
  111289. }else{
  111290. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111291. if( yygotominor.yy342.pExpr ){
  111292. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
  111293. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111294. }else{
  111295. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
  111296. }
  111297. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111298. }
  111299. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111300. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111301. }
  111302. break;
  111303. case 227: /* expr ::= LP select RP */
  111304. {
  111305. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  111306. if( yygotominor.yy342.pExpr ){
  111307. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  111308. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111309. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111310. }else{
  111311. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111312. }
  111313. yygotominor.yy342.zStart = yymsp[-2].minor.yy0.z;
  111314. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111315. }
  111316. break;
  111317. case 228: /* expr ::= expr in_op LP select RP */
  111318. {
  111319. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
  111320. if( yygotominor.yy342.pExpr ){
  111321. yygotominor.yy342.pExpr->x.pSelect = yymsp[-1].minor.yy159;
  111322. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111323. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111324. }else{
  111325. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111326. }
  111327. if( yymsp[-3].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111328. yygotominor.yy342.zStart = yymsp[-4].minor.yy342.zStart;
  111329. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111330. }
  111331. break;
  111332. case 229: /* expr ::= expr in_op nm dbnm */
  111333. {
  111334. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  111335. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
  111336. if( yygotominor.yy342.pExpr ){
  111337. yygotominor.yy342.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  111338. ExprSetProperty(yygotominor.yy342.pExpr, EP_xIsSelect);
  111339. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111340. }else{
  111341. sqlite3SrcListDelete(pParse->db, pSrc);
  111342. }
  111343. if( yymsp[-2].minor.yy392 ) yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy342.pExpr, 0, 0);
  111344. yygotominor.yy342.zStart = yymsp[-3].minor.yy342.zStart;
  111345. yygotominor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
  111346. }
  111347. break;
  111348. case 230: /* expr ::= EXISTS LP select RP */
  111349. {
  111350. Expr *p = yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  111351. if( p ){
  111352. p->x.pSelect = yymsp[-1].minor.yy159;
  111353. ExprSetProperty(p, EP_xIsSelect);
  111354. sqlite3ExprSetHeight(pParse, p);
  111355. }else{
  111356. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy159);
  111357. }
  111358. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  111359. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111360. }
  111361. break;
  111362. case 231: /* expr ::= CASE case_operand case_exprlist case_else END */
  111363. {
  111364. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
  111365. if( yygotominor.yy342.pExpr ){
  111366. yygotominor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
  111367. sqlite3ExprSetHeight(pParse, yygotominor.yy342.pExpr);
  111368. }else{
  111369. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
  111370. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
  111371. }
  111372. yygotominor.yy342.zStart = yymsp[-4].minor.yy0.z;
  111373. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111374. }
  111375. break;
  111376. case 232: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  111377. {
  111378. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
  111379. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  111380. }
  111381. break;
  111382. case 233: /* case_exprlist ::= WHEN expr THEN expr */
  111383. {
  111384. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
  111385. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yygotominor.yy442, yymsp[0].minor.yy342.pExpr);
  111386. }
  111387. break;
  111388. case 240: /* nexprlist ::= nexprlist COMMA expr */
  111389. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
  111390. break;
  111391. case 241: /* nexprlist ::= expr */
  111392. {yygotominor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr);}
  111393. break;
  111394. case 242: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  111395. {
  111396. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  111397. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
  111398. &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
  111399. }
  111400. break;
  111401. case 243: /* uniqueflag ::= UNIQUE */
  111402. case 296: /* raisetype ::= ABORT */ yytestcase(yyruleno==296);
  111403. {yygotominor.yy392 = OE_Abort;}
  111404. break;
  111405. case 244: /* uniqueflag ::= */
  111406. {yygotominor.yy392 = OE_None;}
  111407. break;
  111408. case 247: /* idxlist ::= idxlist COMMA nm collate sortorder */
  111409. {
  111410. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  111411. yygotominor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, p);
  111412. sqlite3ExprListSetName(pParse,yygotominor.yy442,&yymsp[-2].minor.yy0,1);
  111413. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  111414. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  111415. }
  111416. break;
  111417. case 248: /* idxlist ::= nm collate sortorder */
  111418. {
  111419. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  111420. yygotominor.yy442 = sqlite3ExprListAppend(pParse,0, p);
  111421. sqlite3ExprListSetName(pParse, yygotominor.yy442, &yymsp[-2].minor.yy0, 1);
  111422. sqlite3ExprListCheckLength(pParse, yygotominor.yy442, "index");
  111423. if( yygotominor.yy442 ) yygotominor.yy442->a[yygotominor.yy442->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy392;
  111424. }
  111425. break;
  111426. case 249: /* collate ::= */
  111427. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  111428. break;
  111429. case 251: /* cmd ::= DROP INDEX ifexists fullname */
  111430. {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
  111431. break;
  111432. case 252: /* cmd ::= VACUUM */
  111433. case 253: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==253);
  111434. {sqlite3Vacuum(pParse);}
  111435. break;
  111436. case 254: /* cmd ::= PRAGMA nm dbnm */
  111437. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  111438. break;
  111439. case 255: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  111440. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  111441. break;
  111442. case 256: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  111443. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  111444. break;
  111445. case 257: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  111446. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  111447. break;
  111448. case 258: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  111449. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  111450. break;
  111451. case 268: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  111452. {
  111453. Token all;
  111454. all.z = yymsp[-3].minor.yy0.z;
  111455. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  111456. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
  111457. }
  111458. break;
  111459. case 269: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  111460. {
  111461. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
  111462. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  111463. }
  111464. break;
  111465. case 270: /* trigger_time ::= BEFORE */
  111466. case 273: /* trigger_time ::= */ yytestcase(yyruleno==273);
  111467. { yygotominor.yy392 = TK_BEFORE; }
  111468. break;
  111469. case 271: /* trigger_time ::= AFTER */
  111470. { yygotominor.yy392 = TK_AFTER; }
  111471. break;
  111472. case 272: /* trigger_time ::= INSTEAD OF */
  111473. { yygotominor.yy392 = TK_INSTEAD;}
  111474. break;
  111475. case 274: /* trigger_event ::= DELETE|INSERT */
  111476. case 275: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==275);
  111477. {yygotominor.yy410.a = yymsp[0].major; yygotominor.yy410.b = 0;}
  111478. break;
  111479. case 276: /* trigger_event ::= UPDATE OF inscollist */
  111480. {yygotominor.yy410.a = TK_UPDATE; yygotominor.yy410.b = yymsp[0].minor.yy180;}
  111481. break;
  111482. case 279: /* when_clause ::= */
  111483. case 301: /* key_opt ::= */ yytestcase(yyruleno==301);
  111484. { yygotominor.yy122 = 0; }
  111485. break;
  111486. case 280: /* when_clause ::= WHEN expr */
  111487. case 302: /* key_opt ::= KEY expr */ yytestcase(yyruleno==302);
  111488. { yygotominor.yy122 = yymsp[0].minor.yy342.pExpr; }
  111489. break;
  111490. case 281: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  111491. {
  111492. assert( yymsp[-2].minor.yy327!=0 );
  111493. yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
  111494. yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
  111495. yygotominor.yy327 = yymsp[-2].minor.yy327;
  111496. }
  111497. break;
  111498. case 282: /* trigger_cmd_list ::= trigger_cmd SEMI */
  111499. {
  111500. assert( yymsp[-1].minor.yy327!=0 );
  111501. yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
  111502. yygotominor.yy327 = yymsp[-1].minor.yy327;
  111503. }
  111504. break;
  111505. case 284: /* trnm ::= nm DOT nm */
  111506. {
  111507. yygotominor.yy0 = yymsp[0].minor.yy0;
  111508. sqlite3ErrorMsg(pParse,
  111509. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  111510. "statements within triggers");
  111511. }
  111512. break;
  111513. case 286: /* tridxby ::= INDEXED BY nm */
  111514. {
  111515. sqlite3ErrorMsg(pParse,
  111516. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  111517. "within triggers");
  111518. }
  111519. break;
  111520. case 287: /* tridxby ::= NOT INDEXED */
  111521. {
  111522. sqlite3ErrorMsg(pParse,
  111523. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  111524. "within triggers");
  111525. }
  111526. break;
  111527. case 288: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  111528. { yygotominor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy258); }
  111529. break;
  111530. case 289: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt valuelist */
  111531. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy487.pList, yymsp[0].minor.yy487.pSelect, yymsp[-4].minor.yy258);}
  111532. break;
  111533. case 290: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  111534. {yygotominor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, 0, yymsp[0].minor.yy159, yymsp[-4].minor.yy258);}
  111535. break;
  111536. case 291: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  111537. {yygotominor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
  111538. break;
  111539. case 292: /* trigger_cmd ::= select */
  111540. {yygotominor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); }
  111541. break;
  111542. case 293: /* expr ::= RAISE LP IGNORE RP */
  111543. {
  111544. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  111545. if( yygotominor.yy342.pExpr ){
  111546. yygotominor.yy342.pExpr->affinity = OE_Ignore;
  111547. }
  111548. yygotominor.yy342.zStart = yymsp[-3].minor.yy0.z;
  111549. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111550. }
  111551. break;
  111552. case 294: /* expr ::= RAISE LP raisetype COMMA nm RP */
  111553. {
  111554. yygotominor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  111555. if( yygotominor.yy342.pExpr ) {
  111556. yygotominor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
  111557. }
  111558. yygotominor.yy342.zStart = yymsp[-5].minor.yy0.z;
  111559. yygotominor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  111560. }
  111561. break;
  111562. case 295: /* raisetype ::= ROLLBACK */
  111563. {yygotominor.yy392 = OE_Rollback;}
  111564. break;
  111565. case 297: /* raisetype ::= FAIL */
  111566. {yygotominor.yy392 = OE_Fail;}
  111567. break;
  111568. case 298: /* cmd ::= DROP TRIGGER ifexists fullname */
  111569. {
  111570. sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
  111571. }
  111572. break;
  111573. case 299: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  111574. {
  111575. sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
  111576. }
  111577. break;
  111578. case 300: /* cmd ::= DETACH database_kw_opt expr */
  111579. {
  111580. sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
  111581. }
  111582. break;
  111583. case 305: /* cmd ::= REINDEX */
  111584. {sqlite3Reindex(pParse, 0, 0);}
  111585. break;
  111586. case 306: /* cmd ::= REINDEX nm dbnm */
  111587. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  111588. break;
  111589. case 307: /* cmd ::= ANALYZE */
  111590. {sqlite3Analyze(pParse, 0, 0);}
  111591. break;
  111592. case 308: /* cmd ::= ANALYZE nm dbnm */
  111593. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  111594. break;
  111595. case 309: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  111596. {
  111597. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
  111598. }
  111599. break;
  111600. case 310: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  111601. {
  111602. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  111603. }
  111604. break;
  111605. case 311: /* add_column_fullname ::= fullname */
  111606. {
  111607. pParse->db->lookaside.bEnabled = 0;
  111608. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
  111609. }
  111610. break;
  111611. case 314: /* cmd ::= create_vtab */
  111612. {sqlite3VtabFinishParse(pParse,0);}
  111613. break;
  111614. case 315: /* cmd ::= create_vtab LP vtabarglist RP */
  111615. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  111616. break;
  111617. case 316: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  111618. {
  111619. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
  111620. }
  111621. break;
  111622. case 319: /* vtabarg ::= */
  111623. {sqlite3VtabArgInit(pParse);}
  111624. break;
  111625. case 321: /* vtabargtoken ::= ANY */
  111626. case 322: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==322);
  111627. case 323: /* lp ::= LP */ yytestcase(yyruleno==323);
  111628. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  111629. break;
  111630. default:
  111631. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  111632. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  111633. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  111634. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  111635. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  111636. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  111637. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  111638. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  111639. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  111640. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  111641. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  111642. /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
  111643. /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
  111644. /* (44) type ::= */ yytestcase(yyruleno==44);
  111645. /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
  111646. /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
  111647. /* (53) carglist ::= carglist ccons */ yytestcase(yyruleno==53);
  111648. /* (54) carglist ::= */ yytestcase(yyruleno==54);
  111649. /* (61) ccons ::= NULL onconf */ yytestcase(yyruleno==61);
  111650. /* (89) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==89);
  111651. /* (90) conslist ::= tcons */ yytestcase(yyruleno==90);
  111652. /* (92) tconscomma ::= */ yytestcase(yyruleno==92);
  111653. /* (277) foreach_clause ::= */ yytestcase(yyruleno==277);
  111654. /* (278) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==278);
  111655. /* (285) tridxby ::= */ yytestcase(yyruleno==285);
  111656. /* (303) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==303);
  111657. /* (304) database_kw_opt ::= */ yytestcase(yyruleno==304);
  111658. /* (312) kwcolumn_opt ::= */ yytestcase(yyruleno==312);
  111659. /* (313) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==313);
  111660. /* (317) vtabarglist ::= vtabarg */ yytestcase(yyruleno==317);
  111661. /* (318) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==318);
  111662. /* (320) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==320);
  111663. /* (324) anylist ::= */ yytestcase(yyruleno==324);
  111664. /* (325) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==325);
  111665. /* (326) anylist ::= anylist ANY */ yytestcase(yyruleno==326);
  111666. break;
  111667. };
  111668. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  111669. yygoto = yyRuleInfo[yyruleno].lhs;
  111670. yysize = yyRuleInfo[yyruleno].nrhs;
  111671. yypParser->yyidx -= yysize;
  111672. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  111673. if( yyact < YYNSTATE ){
  111674. #ifdef NDEBUG
  111675. /* If we are not debugging and the reduce action popped at least
  111676. ** one element off the stack, then we can push the new element back
  111677. ** onto the stack here, and skip the stack overflow test in yy_shift().
  111678. ** That gives a significant speed improvement. */
  111679. if( yysize ){
  111680. yypParser->yyidx++;
  111681. yymsp -= yysize-1;
  111682. yymsp->stateno = (YYACTIONTYPE)yyact;
  111683. yymsp->major = (YYCODETYPE)yygoto;
  111684. yymsp->minor = yygotominor;
  111685. }else
  111686. #endif
  111687. {
  111688. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  111689. }
  111690. }else{
  111691. assert( yyact == YYNSTATE + YYNRULE + 1 );
  111692. yy_accept(yypParser);
  111693. }
  111694. }
  111695. /*
  111696. ** The following code executes when the parse fails
  111697. */
  111698. #ifndef YYNOERRORRECOVERY
  111699. static void yy_parse_failed(
  111700. yyParser *yypParser /* The parser */
  111701. ){
  111702. sqlite3ParserARG_FETCH;
  111703. #ifndef NDEBUG
  111704. if( yyTraceFILE ){
  111705. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  111706. }
  111707. #endif
  111708. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  111709. /* Here code is inserted which will be executed whenever the
  111710. ** parser fails */
  111711. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111712. }
  111713. #endif /* YYNOERRORRECOVERY */
  111714. /*
  111715. ** The following code executes when a syntax error first occurs.
  111716. */
  111717. static void yy_syntax_error(
  111718. yyParser *yypParser, /* The parser */
  111719. int yymajor, /* The major type of the error token */
  111720. YYMINORTYPE yyminor /* The minor type of the error token */
  111721. ){
  111722. sqlite3ParserARG_FETCH;
  111723. #define TOKEN (yyminor.yy0)
  111724. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  111725. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  111726. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  111727. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111728. }
  111729. /*
  111730. ** The following is executed when the parser accepts
  111731. */
  111732. static void yy_accept(
  111733. yyParser *yypParser /* The parser */
  111734. ){
  111735. sqlite3ParserARG_FETCH;
  111736. #ifndef NDEBUG
  111737. if( yyTraceFILE ){
  111738. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  111739. }
  111740. #endif
  111741. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  111742. /* Here code is inserted which will be executed whenever the
  111743. ** parser accepts */
  111744. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  111745. }
  111746. /* The main parser program.
  111747. ** The first argument is a pointer to a structure obtained from
  111748. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  111749. ** The second argument is the major token number. The third is
  111750. ** the minor token. The fourth optional argument is whatever the
  111751. ** user wants (and specified in the grammar) and is available for
  111752. ** use by the action routines.
  111753. **
  111754. ** Inputs:
  111755. ** <ul>
  111756. ** <li> A pointer to the parser (an opaque structure.)
  111757. ** <li> The major token number.
  111758. ** <li> The minor token number.
  111759. ** <li> An option argument of a grammar-specified type.
  111760. ** </ul>
  111761. **
  111762. ** Outputs:
  111763. ** None.
  111764. */
  111765. SQLITE_PRIVATE void sqlite3Parser(
  111766. void *yyp, /* The parser */
  111767. int yymajor, /* The major token code number */
  111768. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  111769. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  111770. ){
  111771. YYMINORTYPE yyminorunion;
  111772. int yyact; /* The parser action. */
  111773. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  111774. int yyendofinput; /* True if we are at the end of input */
  111775. #endif
  111776. #ifdef YYERRORSYMBOL
  111777. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  111778. #endif
  111779. yyParser *yypParser; /* The parser */
  111780. /* (re)initialize the parser, if necessary */
  111781. yypParser = (yyParser*)yyp;
  111782. if( yypParser->yyidx<0 ){
  111783. #if YYSTACKDEPTH<=0
  111784. if( yypParser->yystksz <=0 ){
  111785. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  111786. yyminorunion = yyzerominor;
  111787. yyStackOverflow(yypParser, &yyminorunion);
  111788. return;
  111789. }
  111790. #endif
  111791. yypParser->yyidx = 0;
  111792. yypParser->yyerrcnt = -1;
  111793. yypParser->yystack[0].stateno = 0;
  111794. yypParser->yystack[0].major = 0;
  111795. }
  111796. yyminorunion.yy0 = yyminor;
  111797. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  111798. yyendofinput = (yymajor==0);
  111799. #endif
  111800. sqlite3ParserARG_STORE;
  111801. #ifndef NDEBUG
  111802. if( yyTraceFILE ){
  111803. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  111804. }
  111805. #endif
  111806. do{
  111807. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  111808. if( yyact<YYNSTATE ){
  111809. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  111810. yypParser->yyerrcnt--;
  111811. yymajor = YYNOCODE;
  111812. }else if( yyact < YYNSTATE + YYNRULE ){
  111813. yy_reduce(yypParser,yyact-YYNSTATE);
  111814. }else{
  111815. assert( yyact == YY_ERROR_ACTION );
  111816. #ifdef YYERRORSYMBOL
  111817. int yymx;
  111818. #endif
  111819. #ifndef NDEBUG
  111820. if( yyTraceFILE ){
  111821. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  111822. }
  111823. #endif
  111824. #ifdef YYERRORSYMBOL
  111825. /* A syntax error has occurred.
  111826. ** The response to an error depends upon whether or not the
  111827. ** grammar defines an error token "ERROR".
  111828. **
  111829. ** This is what we do if the grammar does define ERROR:
  111830. **
  111831. ** * Call the %syntax_error function.
  111832. **
  111833. ** * Begin popping the stack until we enter a state where
  111834. ** it is legal to shift the error symbol, then shift
  111835. ** the error symbol.
  111836. **
  111837. ** * Set the error count to three.
  111838. **
  111839. ** * Begin accepting and shifting new tokens. No new error
  111840. ** processing will occur until three tokens have been
  111841. ** shifted successfully.
  111842. **
  111843. */
  111844. if( yypParser->yyerrcnt<0 ){
  111845. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111846. }
  111847. yymx = yypParser->yystack[yypParser->yyidx].major;
  111848. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  111849. #ifndef NDEBUG
  111850. if( yyTraceFILE ){
  111851. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  111852. yyTracePrompt,yyTokenName[yymajor]);
  111853. }
  111854. #endif
  111855. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  111856. yymajor = YYNOCODE;
  111857. }else{
  111858. while(
  111859. yypParser->yyidx >= 0 &&
  111860. yymx != YYERRORSYMBOL &&
  111861. (yyact = yy_find_reduce_action(
  111862. yypParser->yystack[yypParser->yyidx].stateno,
  111863. YYERRORSYMBOL)) >= YYNSTATE
  111864. ){
  111865. yy_pop_parser_stack(yypParser);
  111866. }
  111867. if( yypParser->yyidx < 0 || yymajor==0 ){
  111868. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111869. yy_parse_failed(yypParser);
  111870. yymajor = YYNOCODE;
  111871. }else if( yymx!=YYERRORSYMBOL ){
  111872. YYMINORTYPE u2;
  111873. u2.YYERRSYMDT = 0;
  111874. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  111875. }
  111876. }
  111877. yypParser->yyerrcnt = 3;
  111878. yyerrorhit = 1;
  111879. #elif defined(YYNOERRORRECOVERY)
  111880. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  111881. ** do any kind of error recovery. Instead, simply invoke the syntax
  111882. ** error routine and continue going as if nothing had happened.
  111883. **
  111884. ** Applications can set this macro (for example inside %include) if
  111885. ** they intend to abandon the parse upon the first syntax error seen.
  111886. */
  111887. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111888. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111889. yymajor = YYNOCODE;
  111890. #else /* YYERRORSYMBOL is not defined */
  111891. /* This is what we do if the grammar does not define ERROR:
  111892. **
  111893. ** * Report an error message, and throw away the input token.
  111894. **
  111895. ** * If the input token is $, then fail the parse.
  111896. **
  111897. ** As before, subsequent error messages are suppressed until
  111898. ** three input tokens have been successfully shifted.
  111899. */
  111900. if( yypParser->yyerrcnt<=0 ){
  111901. yy_syntax_error(yypParser,yymajor,yyminorunion);
  111902. }
  111903. yypParser->yyerrcnt = 3;
  111904. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  111905. if( yyendofinput ){
  111906. yy_parse_failed(yypParser);
  111907. }
  111908. yymajor = YYNOCODE;
  111909. #endif
  111910. }
  111911. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  111912. return;
  111913. }
  111914. /************** End of parse.c ***********************************************/
  111915. /************** Begin file tokenize.c ****************************************/
  111916. /*
  111917. ** 2001 September 15
  111918. **
  111919. ** The author disclaims copyright to this source code. In place of
  111920. ** a legal notice, here is a blessing:
  111921. **
  111922. ** May you do good and not evil.
  111923. ** May you find forgiveness for yourself and forgive others.
  111924. ** May you share freely, never taking more than you give.
  111925. **
  111926. *************************************************************************
  111927. ** An tokenizer for SQL
  111928. **
  111929. ** This file contains C code that splits an SQL input string up into
  111930. ** individual tokens and sends those tokens one-by-one over to the
  111931. ** parser for analysis.
  111932. */
  111933. /* #include <stdlib.h> */
  111934. /*
  111935. ** The charMap() macro maps alphabetic characters into their
  111936. ** lower-case ASCII equivalent. On ASCII machines, this is just
  111937. ** an upper-to-lower case map. On EBCDIC machines we also need
  111938. ** to adjust the encoding. Only alphabetic characters and underscores
  111939. ** need to be translated.
  111940. */
  111941. #ifdef SQLITE_ASCII
  111942. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  111943. #endif
  111944. #ifdef SQLITE_EBCDIC
  111945. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  111946. const unsigned char ebcdicToAscii[] = {
  111947. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  111948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  111949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  111950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  111951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  111952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  111953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  111954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  111955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  111956. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  111957. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  111958. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  111959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  111960. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  111961. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  111962. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  111963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  111964. };
  111965. #endif
  111966. /*
  111967. ** The sqlite3KeywordCode function looks up an identifier to determine if
  111968. ** it is a keyword. If it is a keyword, the token code of that keyword is
  111969. ** returned. If the input is not a keyword, TK_ID is returned.
  111970. **
  111971. ** The implementation of this routine was generated by a program,
  111972. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  111973. ** The output of the mkkeywordhash.c program is written into a file
  111974. ** named keywordhash.h and then included into this source file by
  111975. ** the #include below.
  111976. */
  111977. /************** Include keywordhash.h in the middle of tokenize.c ************/
  111978. /************** Begin file keywordhash.h *************************************/
  111979. /***** This file contains automatically generated code ******
  111980. **
  111981. ** The code in this file has been automatically generated by
  111982. **
  111983. ** sqlite/tool/mkkeywordhash.c
  111984. **
  111985. ** The code in this file implements a function that determines whether
  111986. ** or not a given identifier is really an SQL keyword. The same thing
  111987. ** might be implemented more directly using a hand-written hash table.
  111988. ** But by using this automatically generated code, the size of the code
  111989. ** is substantially reduced. This is important for embedded applications
  111990. ** on platforms with limited memory.
  111991. */
  111992. /* Hash score: 175 */
  111993. static int keywordCode(const char *z, int n){
  111994. /* zText[] encodes 811 bytes of keywords in 541 bytes */
  111995. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  111996. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  111997. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  111998. /* UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE */
  111999. /* CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN */
  112000. /* SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME */
  112001. /* AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS */
  112002. /* CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF */
  112003. /* ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW */
  112004. /* INITIALLY */
  112005. static const char zText[540] = {
  112006. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  112007. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  112008. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  112009. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  112010. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  112011. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  112012. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  112013. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  112014. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  112015. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  112016. 'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
  112017. 'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
  112018. 'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
  112019. 'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
  112020. 'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
  112021. 'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
  112022. 'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
  112023. 'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
  112024. 'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
  112025. 'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
  112026. 'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
  112027. 'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
  112028. 'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
  112029. 'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
  112030. 'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
  112031. 'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
  112032. 'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
  112033. 'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
  112034. 'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
  112035. 'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
  112036. };
  112037. static const unsigned char aHash[127] = {
  112038. 72, 101, 114, 70, 0, 45, 0, 0, 78, 0, 73, 0, 0,
  112039. 42, 12, 74, 15, 0, 113, 81, 50, 108, 0, 19, 0, 0,
  112040. 118, 0, 116, 111, 0, 22, 89, 0, 9, 0, 0, 66, 67,
  112041. 0, 65, 6, 0, 48, 86, 98, 0, 115, 97, 0, 0, 44,
  112042. 0, 99, 24, 0, 17, 0, 119, 49, 23, 0, 5, 106, 25,
  112043. 92, 0, 0, 121, 102, 56, 120, 53, 28, 51, 0, 87, 0,
  112044. 96, 26, 0, 95, 0, 0, 0, 91, 88, 93, 84, 105, 14,
  112045. 39, 104, 0, 77, 0, 18, 85, 107, 32, 0, 117, 76, 109,
  112046. 58, 46, 80, 0, 0, 90, 40, 0, 112, 0, 36, 0, 0,
  112047. 29, 0, 82, 59, 60, 0, 20, 57, 0, 52,
  112048. };
  112049. static const unsigned char aNext[121] = {
  112050. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  112051. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  112052. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  112053. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 43, 3, 47,
  112054. 0, 0, 0, 0, 30, 0, 54, 0, 38, 0, 0, 0, 1,
  112055. 62, 0, 0, 63, 0, 41, 0, 0, 0, 0, 0, 0, 0,
  112056. 61, 0, 0, 0, 0, 31, 55, 16, 34, 10, 0, 0, 0,
  112057. 0, 0, 0, 0, 11, 68, 75, 0, 8, 0, 100, 94, 0,
  112058. 103, 0, 83, 0, 71, 0, 0, 110, 27, 37, 69, 79, 0,
  112059. 35, 64, 0, 0,
  112060. };
  112061. static const unsigned char aLen[121] = {
  112062. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  112063. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  112064. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  112065. 4, 6, 2, 3, 9, 4, 2, 6, 5, 6, 6, 5, 6,
  112066. 5, 5, 7, 7, 7, 3, 2, 4, 4, 7, 3, 6, 4,
  112067. 7, 6, 12, 6, 9, 4, 6, 5, 4, 7, 6, 5, 6,
  112068. 7, 5, 4, 5, 6, 5, 7, 3, 7, 13, 2, 2, 4,
  112069. 6, 6, 8, 5, 17, 12, 7, 8, 8, 2, 4, 4, 4,
  112070. 4, 4, 2, 2, 6, 5, 8, 5, 5, 8, 3, 5, 5,
  112071. 6, 4, 9, 3,
  112072. };
  112073. static const unsigned short int aOffset[121] = {
  112074. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  112075. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  112076. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  112077. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
  112078. 203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
  112079. 248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
  112080. 326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
  112081. 387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
  112082. 462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
  112083. 521, 527, 531, 536,
  112084. };
  112085. static const unsigned char aCode[121] = {
  112086. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  112087. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  112088. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  112089. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  112090. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  112091. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  112092. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  112093. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  112094. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  112095. TK_OR, TK_UNIQUE, TK_QUERY, TK_ATTACH, TK_HAVING,
  112096. TK_GROUP, TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RELEASE,
  112097. TK_BETWEEN, TK_NOTNULL, TK_NOT, TK_NO, TK_NULL,
  112098. TK_LIKE_KW, TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE,
  112099. TK_COLLATE, TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE,
  112100. TK_JOIN, TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE,
  112101. TK_PRAGMA, TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT,
  112102. TK_WHEN, TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE,
  112103. TK_AND, TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN,
  112104. TK_CAST, TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW,
  112105. TK_CTIME_KW, TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT,
  112106. TK_IS, TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW,
  112107. TK_LIKE_KW, TK_BY, TK_IF, TK_ISNULL, TK_ORDER,
  112108. TK_RESTRICT, TK_JOIN_KW, TK_JOIN_KW, TK_ROLLBACK, TK_ROW,
  112109. TK_UNION, TK_USING, TK_VACUUM, TK_VIEW, TK_INITIALLY,
  112110. TK_ALL,
  112111. };
  112112. int h, i;
  112113. if( n<2 ) return TK_ID;
  112114. h = ((charMap(z[0])*4) ^
  112115. (charMap(z[n-1])*3) ^
  112116. n) % 127;
  112117. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  112118. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  112119. testcase( i==0 ); /* REINDEX */
  112120. testcase( i==1 ); /* INDEXED */
  112121. testcase( i==2 ); /* INDEX */
  112122. testcase( i==3 ); /* DESC */
  112123. testcase( i==4 ); /* ESCAPE */
  112124. testcase( i==5 ); /* EACH */
  112125. testcase( i==6 ); /* CHECK */
  112126. testcase( i==7 ); /* KEY */
  112127. testcase( i==8 ); /* BEFORE */
  112128. testcase( i==9 ); /* FOREIGN */
  112129. testcase( i==10 ); /* FOR */
  112130. testcase( i==11 ); /* IGNORE */
  112131. testcase( i==12 ); /* REGEXP */
  112132. testcase( i==13 ); /* EXPLAIN */
  112133. testcase( i==14 ); /* INSTEAD */
  112134. testcase( i==15 ); /* ADD */
  112135. testcase( i==16 ); /* DATABASE */
  112136. testcase( i==17 ); /* AS */
  112137. testcase( i==18 ); /* SELECT */
  112138. testcase( i==19 ); /* TABLE */
  112139. testcase( i==20 ); /* LEFT */
  112140. testcase( i==21 ); /* THEN */
  112141. testcase( i==22 ); /* END */
  112142. testcase( i==23 ); /* DEFERRABLE */
  112143. testcase( i==24 ); /* ELSE */
  112144. testcase( i==25 ); /* EXCEPT */
  112145. testcase( i==26 ); /* TRANSACTION */
  112146. testcase( i==27 ); /* ACTION */
  112147. testcase( i==28 ); /* ON */
  112148. testcase( i==29 ); /* NATURAL */
  112149. testcase( i==30 ); /* ALTER */
  112150. testcase( i==31 ); /* RAISE */
  112151. testcase( i==32 ); /* EXCLUSIVE */
  112152. testcase( i==33 ); /* EXISTS */
  112153. testcase( i==34 ); /* SAVEPOINT */
  112154. testcase( i==35 ); /* INTERSECT */
  112155. testcase( i==36 ); /* TRIGGER */
  112156. testcase( i==37 ); /* REFERENCES */
  112157. testcase( i==38 ); /* CONSTRAINT */
  112158. testcase( i==39 ); /* INTO */
  112159. testcase( i==40 ); /* OFFSET */
  112160. testcase( i==41 ); /* OF */
  112161. testcase( i==42 ); /* SET */
  112162. testcase( i==43 ); /* TEMPORARY */
  112163. testcase( i==44 ); /* TEMP */
  112164. testcase( i==45 ); /* OR */
  112165. testcase( i==46 ); /* UNIQUE */
  112166. testcase( i==47 ); /* QUERY */
  112167. testcase( i==48 ); /* ATTACH */
  112168. testcase( i==49 ); /* HAVING */
  112169. testcase( i==50 ); /* GROUP */
  112170. testcase( i==51 ); /* UPDATE */
  112171. testcase( i==52 ); /* BEGIN */
  112172. testcase( i==53 ); /* INNER */
  112173. testcase( i==54 ); /* RELEASE */
  112174. testcase( i==55 ); /* BETWEEN */
  112175. testcase( i==56 ); /* NOTNULL */
  112176. testcase( i==57 ); /* NOT */
  112177. testcase( i==58 ); /* NO */
  112178. testcase( i==59 ); /* NULL */
  112179. testcase( i==60 ); /* LIKE */
  112180. testcase( i==61 ); /* CASCADE */
  112181. testcase( i==62 ); /* ASC */
  112182. testcase( i==63 ); /* DELETE */
  112183. testcase( i==64 ); /* CASE */
  112184. testcase( i==65 ); /* COLLATE */
  112185. testcase( i==66 ); /* CREATE */
  112186. testcase( i==67 ); /* CURRENT_DATE */
  112187. testcase( i==68 ); /* DETACH */
  112188. testcase( i==69 ); /* IMMEDIATE */
  112189. testcase( i==70 ); /* JOIN */
  112190. testcase( i==71 ); /* INSERT */
  112191. testcase( i==72 ); /* MATCH */
  112192. testcase( i==73 ); /* PLAN */
  112193. testcase( i==74 ); /* ANALYZE */
  112194. testcase( i==75 ); /* PRAGMA */
  112195. testcase( i==76 ); /* ABORT */
  112196. testcase( i==77 ); /* VALUES */
  112197. testcase( i==78 ); /* VIRTUAL */
  112198. testcase( i==79 ); /* LIMIT */
  112199. testcase( i==80 ); /* WHEN */
  112200. testcase( i==81 ); /* WHERE */
  112201. testcase( i==82 ); /* RENAME */
  112202. testcase( i==83 ); /* AFTER */
  112203. testcase( i==84 ); /* REPLACE */
  112204. testcase( i==85 ); /* AND */
  112205. testcase( i==86 ); /* DEFAULT */
  112206. testcase( i==87 ); /* AUTOINCREMENT */
  112207. testcase( i==88 ); /* TO */
  112208. testcase( i==89 ); /* IN */
  112209. testcase( i==90 ); /* CAST */
  112210. testcase( i==91 ); /* COLUMN */
  112211. testcase( i==92 ); /* COMMIT */
  112212. testcase( i==93 ); /* CONFLICT */
  112213. testcase( i==94 ); /* CROSS */
  112214. testcase( i==95 ); /* CURRENT_TIMESTAMP */
  112215. testcase( i==96 ); /* CURRENT_TIME */
  112216. testcase( i==97 ); /* PRIMARY */
  112217. testcase( i==98 ); /* DEFERRED */
  112218. testcase( i==99 ); /* DISTINCT */
  112219. testcase( i==100 ); /* IS */
  112220. testcase( i==101 ); /* DROP */
  112221. testcase( i==102 ); /* FAIL */
  112222. testcase( i==103 ); /* FROM */
  112223. testcase( i==104 ); /* FULL */
  112224. testcase( i==105 ); /* GLOB */
  112225. testcase( i==106 ); /* BY */
  112226. testcase( i==107 ); /* IF */
  112227. testcase( i==108 ); /* ISNULL */
  112228. testcase( i==109 ); /* ORDER */
  112229. testcase( i==110 ); /* RESTRICT */
  112230. testcase( i==111 ); /* OUTER */
  112231. testcase( i==112 ); /* RIGHT */
  112232. testcase( i==113 ); /* ROLLBACK */
  112233. testcase( i==114 ); /* ROW */
  112234. testcase( i==115 ); /* UNION */
  112235. testcase( i==116 ); /* USING */
  112236. testcase( i==117 ); /* VACUUM */
  112237. testcase( i==118 ); /* VIEW */
  112238. testcase( i==119 ); /* INITIALLY */
  112239. testcase( i==120 ); /* ALL */
  112240. return aCode[i];
  112241. }
  112242. }
  112243. return TK_ID;
  112244. }
  112245. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  112246. return keywordCode((char*)z, n);
  112247. }
  112248. #define SQLITE_N_KEYWORD 121
  112249. /************** End of keywordhash.h *****************************************/
  112250. /************** Continuing where we left off in tokenize.c *******************/
  112251. /*
  112252. ** If X is a character that can be used in an identifier then
  112253. ** IdChar(X) will be true. Otherwise it is false.
  112254. **
  112255. ** For ASCII, any character with the high-order bit set is
  112256. ** allowed in an identifier. For 7-bit characters,
  112257. ** sqlite3IsIdChar[X] must be 1.
  112258. **
  112259. ** For EBCDIC, the rules are more complex but have the same
  112260. ** end result.
  112261. **
  112262. ** Ticket #1066. the SQL standard does not allow '$' in the
  112263. ** middle of identfiers. But many SQL implementations do.
  112264. ** SQLite will allow '$' in identifiers for compatibility.
  112265. ** But the feature is undocumented.
  112266. */
  112267. #ifdef SQLITE_ASCII
  112268. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  112269. #endif
  112270. #ifdef SQLITE_EBCDIC
  112271. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  112272. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  112273. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  112274. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  112275. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  112276. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  112277. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  112278. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  112279. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  112280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  112281. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  112282. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  112283. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  112284. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  112285. };
  112286. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  112287. #endif
  112288. /*
  112289. ** Return the length of the token that begins at z[0].
  112290. ** Store the token type in *tokenType before returning.
  112291. */
  112292. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  112293. int i, c;
  112294. switch( *z ){
  112295. case ' ': case '\t': case '\n': case '\f': case '\r': {
  112296. testcase( z[0]==' ' );
  112297. testcase( z[0]=='\t' );
  112298. testcase( z[0]=='\n' );
  112299. testcase( z[0]=='\f' );
  112300. testcase( z[0]=='\r' );
  112301. for(i=1; sqlite3Isspace(z[i]); i++){}
  112302. *tokenType = TK_SPACE;
  112303. return i;
  112304. }
  112305. case '-': {
  112306. if( z[1]=='-' ){
  112307. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  112308. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  112309. return i;
  112310. }
  112311. *tokenType = TK_MINUS;
  112312. return 1;
  112313. }
  112314. case '(': {
  112315. *tokenType = TK_LP;
  112316. return 1;
  112317. }
  112318. case ')': {
  112319. *tokenType = TK_RP;
  112320. return 1;
  112321. }
  112322. case ';': {
  112323. *tokenType = TK_SEMI;
  112324. return 1;
  112325. }
  112326. case '+': {
  112327. *tokenType = TK_PLUS;
  112328. return 1;
  112329. }
  112330. case '*': {
  112331. *tokenType = TK_STAR;
  112332. return 1;
  112333. }
  112334. case '/': {
  112335. if( z[1]!='*' || z[2]==0 ){
  112336. *tokenType = TK_SLASH;
  112337. return 1;
  112338. }
  112339. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  112340. if( c ) i++;
  112341. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  112342. return i;
  112343. }
  112344. case '%': {
  112345. *tokenType = TK_REM;
  112346. return 1;
  112347. }
  112348. case '=': {
  112349. *tokenType = TK_EQ;
  112350. return 1 + (z[1]=='=');
  112351. }
  112352. case '<': {
  112353. if( (c=z[1])=='=' ){
  112354. *tokenType = TK_LE;
  112355. return 2;
  112356. }else if( c=='>' ){
  112357. *tokenType = TK_NE;
  112358. return 2;
  112359. }else if( c=='<' ){
  112360. *tokenType = TK_LSHIFT;
  112361. return 2;
  112362. }else{
  112363. *tokenType = TK_LT;
  112364. return 1;
  112365. }
  112366. }
  112367. case '>': {
  112368. if( (c=z[1])=='=' ){
  112369. *tokenType = TK_GE;
  112370. return 2;
  112371. }else if( c=='>' ){
  112372. *tokenType = TK_RSHIFT;
  112373. return 2;
  112374. }else{
  112375. *tokenType = TK_GT;
  112376. return 1;
  112377. }
  112378. }
  112379. case '!': {
  112380. if( z[1]!='=' ){
  112381. *tokenType = TK_ILLEGAL;
  112382. return 2;
  112383. }else{
  112384. *tokenType = TK_NE;
  112385. return 2;
  112386. }
  112387. }
  112388. case '|': {
  112389. if( z[1]!='|' ){
  112390. *tokenType = TK_BITOR;
  112391. return 1;
  112392. }else{
  112393. *tokenType = TK_CONCAT;
  112394. return 2;
  112395. }
  112396. }
  112397. case ',': {
  112398. *tokenType = TK_COMMA;
  112399. return 1;
  112400. }
  112401. case '&': {
  112402. *tokenType = TK_BITAND;
  112403. return 1;
  112404. }
  112405. case '~': {
  112406. *tokenType = TK_BITNOT;
  112407. return 1;
  112408. }
  112409. case '`':
  112410. case '\'':
  112411. case '"': {
  112412. int delim = z[0];
  112413. testcase( delim=='`' );
  112414. testcase( delim=='\'' );
  112415. testcase( delim=='"' );
  112416. for(i=1; (c=z[i])!=0; i++){
  112417. if( c==delim ){
  112418. if( z[i+1]==delim ){
  112419. i++;
  112420. }else{
  112421. break;
  112422. }
  112423. }
  112424. }
  112425. if( c=='\'' ){
  112426. *tokenType = TK_STRING;
  112427. return i+1;
  112428. }else if( c!=0 ){
  112429. *tokenType = TK_ID;
  112430. return i+1;
  112431. }else{
  112432. *tokenType = TK_ILLEGAL;
  112433. return i;
  112434. }
  112435. }
  112436. case '.': {
  112437. #ifndef SQLITE_OMIT_FLOATING_POINT
  112438. if( !sqlite3Isdigit(z[1]) )
  112439. #endif
  112440. {
  112441. *tokenType = TK_DOT;
  112442. return 1;
  112443. }
  112444. /* If the next character is a digit, this is a floating point
  112445. ** number that begins with ".". Fall thru into the next case */
  112446. }
  112447. case '0': case '1': case '2': case '3': case '4':
  112448. case '5': case '6': case '7': case '8': case '9': {
  112449. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  112450. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  112451. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  112452. testcase( z[0]=='9' );
  112453. *tokenType = TK_INTEGER;
  112454. for(i=0; sqlite3Isdigit(z[i]); i++){}
  112455. #ifndef SQLITE_OMIT_FLOATING_POINT
  112456. if( z[i]=='.' ){
  112457. i++;
  112458. while( sqlite3Isdigit(z[i]) ){ i++; }
  112459. *tokenType = TK_FLOAT;
  112460. }
  112461. if( (z[i]=='e' || z[i]=='E') &&
  112462. ( sqlite3Isdigit(z[i+1])
  112463. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  112464. )
  112465. ){
  112466. i += 2;
  112467. while( sqlite3Isdigit(z[i]) ){ i++; }
  112468. *tokenType = TK_FLOAT;
  112469. }
  112470. #endif
  112471. while( IdChar(z[i]) ){
  112472. *tokenType = TK_ILLEGAL;
  112473. i++;
  112474. }
  112475. return i;
  112476. }
  112477. case '[': {
  112478. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  112479. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  112480. return i;
  112481. }
  112482. case '?': {
  112483. *tokenType = TK_VARIABLE;
  112484. for(i=1; sqlite3Isdigit(z[i]); i++){}
  112485. return i;
  112486. }
  112487. case '#': {
  112488. for(i=1; sqlite3Isdigit(z[i]); i++){}
  112489. if( i>1 ){
  112490. /* Parameters of the form #NNN (where NNN is a number) are used
  112491. ** internally by sqlite3NestedParse. */
  112492. *tokenType = TK_REGISTER;
  112493. return i;
  112494. }
  112495. /* Fall through into the next case if the '#' is not followed by
  112496. ** a digit. Try to match #AAAA where AAAA is a parameter name. */
  112497. }
  112498. #ifndef SQLITE_OMIT_TCL_VARIABLE
  112499. case '$':
  112500. #endif
  112501. case '@': /* For compatibility with MS SQL Server */
  112502. case ':': {
  112503. int n = 0;
  112504. testcase( z[0]=='$' ); testcase( z[0]=='@' ); testcase( z[0]==':' );
  112505. *tokenType = TK_VARIABLE;
  112506. for(i=1; (c=z[i])!=0; i++){
  112507. if( IdChar(c) ){
  112508. n++;
  112509. #ifndef SQLITE_OMIT_TCL_VARIABLE
  112510. }else if( c=='(' && n>0 ){
  112511. do{
  112512. i++;
  112513. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  112514. if( c==')' ){
  112515. i++;
  112516. }else{
  112517. *tokenType = TK_ILLEGAL;
  112518. }
  112519. break;
  112520. }else if( c==':' && z[i+1]==':' ){
  112521. i++;
  112522. #endif
  112523. }else{
  112524. break;
  112525. }
  112526. }
  112527. if( n==0 ) *tokenType = TK_ILLEGAL;
  112528. return i;
  112529. }
  112530. #ifndef SQLITE_OMIT_BLOB_LITERAL
  112531. case 'x': case 'X': {
  112532. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  112533. if( z[1]=='\'' ){
  112534. *tokenType = TK_BLOB;
  112535. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  112536. if( z[i]!='\'' || i%2 ){
  112537. *tokenType = TK_ILLEGAL;
  112538. while( z[i] && z[i]!='\'' ){ i++; }
  112539. }
  112540. if( z[i] ) i++;
  112541. return i;
  112542. }
  112543. /* Otherwise fall through to the next case */
  112544. }
  112545. #endif
  112546. default: {
  112547. if( !IdChar(*z) ){
  112548. break;
  112549. }
  112550. for(i=1; IdChar(z[i]); i++){}
  112551. *tokenType = keywordCode((char*)z, i);
  112552. return i;
  112553. }
  112554. }
  112555. *tokenType = TK_ILLEGAL;
  112556. return 1;
  112557. }
  112558. /*
  112559. ** Run the parser on the given SQL string. The parser structure is
  112560. ** passed in. An SQLITE_ status code is returned. If an error occurs
  112561. ** then an and attempt is made to write an error message into
  112562. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  112563. ** error message.
  112564. */
  112565. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  112566. int nErr = 0; /* Number of errors encountered */
  112567. int i; /* Loop counter */
  112568. void *pEngine; /* The LEMON-generated LALR(1) parser */
  112569. int tokenType; /* type of the next token */
  112570. int lastTokenParsed = -1; /* type of the previous token */
  112571. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  112572. sqlite3 *db = pParse->db; /* The database connection */
  112573. int mxSqlLen; /* Max length of an SQL string */
  112574. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  112575. if( db->nVdbeActive==0 ){
  112576. db->u1.isInterrupted = 0;
  112577. }
  112578. pParse->rc = SQLITE_OK;
  112579. pParse->zTail = zSql;
  112580. i = 0;
  112581. assert( pzErrMsg!=0 );
  112582. pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
  112583. if( pEngine==0 ){
  112584. db->mallocFailed = 1;
  112585. return SQLITE_NOMEM;
  112586. }
  112587. assert( pParse->pNewTable==0 );
  112588. assert( pParse->pNewTrigger==0 );
  112589. assert( pParse->nVar==0 );
  112590. assert( pParse->nzVar==0 );
  112591. assert( pParse->azVar==0 );
  112592. enableLookaside = db->lookaside.bEnabled;
  112593. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  112594. while( !db->mallocFailed && zSql[i]!=0 ){
  112595. assert( i>=0 );
  112596. pParse->sLastToken.z = &zSql[i];
  112597. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  112598. i += pParse->sLastToken.n;
  112599. if( i>mxSqlLen ){
  112600. pParse->rc = SQLITE_TOOBIG;
  112601. break;
  112602. }
  112603. switch( tokenType ){
  112604. case TK_SPACE: {
  112605. if( db->u1.isInterrupted ){
  112606. sqlite3ErrorMsg(pParse, "interrupt");
  112607. pParse->rc = SQLITE_INTERRUPT;
  112608. goto abort_parse;
  112609. }
  112610. break;
  112611. }
  112612. case TK_ILLEGAL: {
  112613. sqlite3DbFree(db, *pzErrMsg);
  112614. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  112615. &pParse->sLastToken);
  112616. nErr++;
  112617. goto abort_parse;
  112618. }
  112619. case TK_SEMI: {
  112620. pParse->zTail = &zSql[i];
  112621. /* Fall thru into the default case */
  112622. }
  112623. default: {
  112624. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  112625. lastTokenParsed = tokenType;
  112626. if( pParse->rc!=SQLITE_OK ){
  112627. goto abort_parse;
  112628. }
  112629. break;
  112630. }
  112631. }
  112632. }
  112633. abort_parse:
  112634. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  112635. if( lastTokenParsed!=TK_SEMI ){
  112636. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  112637. pParse->zTail = &zSql[i];
  112638. }
  112639. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  112640. }
  112641. #ifdef YYTRACKMAXSTACKDEPTH
  112642. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  112643. sqlite3ParserStackPeak(pEngine)
  112644. );
  112645. #endif /* YYDEBUG */
  112646. sqlite3ParserFree(pEngine, sqlite3_free);
  112647. db->lookaside.bEnabled = enableLookaside;
  112648. if( db->mallocFailed ){
  112649. pParse->rc = SQLITE_NOMEM;
  112650. }
  112651. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  112652. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  112653. }
  112654. assert( pzErrMsg!=0 );
  112655. if( pParse->zErrMsg ){
  112656. *pzErrMsg = pParse->zErrMsg;
  112657. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  112658. pParse->zErrMsg = 0;
  112659. nErr++;
  112660. }
  112661. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  112662. sqlite3VdbeDelete(pParse->pVdbe);
  112663. pParse->pVdbe = 0;
  112664. }
  112665. #ifndef SQLITE_OMIT_SHARED_CACHE
  112666. if( pParse->nested==0 ){
  112667. sqlite3DbFree(db, pParse->aTableLock);
  112668. pParse->aTableLock = 0;
  112669. pParse->nTableLock = 0;
  112670. }
  112671. #endif
  112672. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112673. sqlite3_free(pParse->apVtabLock);
  112674. #endif
  112675. if( !IN_DECLARE_VTAB ){
  112676. /* If the pParse->declareVtab flag is set, do not delete any table
  112677. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  112678. ** will take responsibility for freeing the Table structure.
  112679. */
  112680. sqlite3DeleteTable(db, pParse->pNewTable);
  112681. }
  112682. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  112683. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  112684. sqlite3DbFree(db, pParse->azVar);
  112685. sqlite3DbFree(db, pParse->aAlias);
  112686. while( pParse->pAinc ){
  112687. AutoincInfo *p = pParse->pAinc;
  112688. pParse->pAinc = p->pNext;
  112689. sqlite3DbFree(db, p);
  112690. }
  112691. while( pParse->pZombieTab ){
  112692. Table *p = pParse->pZombieTab;
  112693. pParse->pZombieTab = p->pNextZombie;
  112694. sqlite3DeleteTable(db, p);
  112695. }
  112696. if( nErr>0 && pParse->rc==SQLITE_OK ){
  112697. pParse->rc = SQLITE_ERROR;
  112698. }
  112699. return nErr;
  112700. }
  112701. /************** End of tokenize.c ********************************************/
  112702. /************** Begin file complete.c ****************************************/
  112703. /*
  112704. ** 2001 September 15
  112705. **
  112706. ** The author disclaims copyright to this source code. In place of
  112707. ** a legal notice, here is a blessing:
  112708. **
  112709. ** May you do good and not evil.
  112710. ** May you find forgiveness for yourself and forgive others.
  112711. ** May you share freely, never taking more than you give.
  112712. **
  112713. *************************************************************************
  112714. ** An tokenizer for SQL
  112715. **
  112716. ** This file contains C code that implements the sqlite3_complete() API.
  112717. ** This code used to be part of the tokenizer.c source file. But by
  112718. ** separating it out, the code will be automatically omitted from
  112719. ** static links that do not use it.
  112720. */
  112721. #ifndef SQLITE_OMIT_COMPLETE
  112722. /*
  112723. ** This is defined in tokenize.c. We just have to import the definition.
  112724. */
  112725. #ifndef SQLITE_AMALGAMATION
  112726. #ifdef SQLITE_ASCII
  112727. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  112728. #endif
  112729. #ifdef SQLITE_EBCDIC
  112730. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  112731. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  112732. #endif
  112733. #endif /* SQLITE_AMALGAMATION */
  112734. /*
  112735. ** Token types used by the sqlite3_complete() routine. See the header
  112736. ** comments on that procedure for additional information.
  112737. */
  112738. #define tkSEMI 0
  112739. #define tkWS 1
  112740. #define tkOTHER 2
  112741. #ifndef SQLITE_OMIT_TRIGGER
  112742. #define tkEXPLAIN 3
  112743. #define tkCREATE 4
  112744. #define tkTEMP 5
  112745. #define tkTRIGGER 6
  112746. #define tkEND 7
  112747. #endif
  112748. /*
  112749. ** Return TRUE if the given SQL string ends in a semicolon.
  112750. **
  112751. ** Special handling is require for CREATE TRIGGER statements.
  112752. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  112753. ** must end with ";END;".
  112754. **
  112755. ** This implementation uses a state machine with 8 states:
  112756. **
  112757. ** (0) INVALID We have not yet seen a non-whitespace character.
  112758. **
  112759. ** (1) START At the beginning or end of an SQL statement. This routine
  112760. ** returns 1 if it ends in the START state and 0 if it ends
  112761. ** in any other state.
  112762. **
  112763. ** (2) NORMAL We are in the middle of statement which ends with a single
  112764. ** semicolon.
  112765. **
  112766. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  112767. ** a statement.
  112768. **
  112769. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  112770. ** statement, possibly preceeded by EXPLAIN and/or followed by
  112771. ** TEMP or TEMPORARY
  112772. **
  112773. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  112774. ** ended by a semicolon, the keyword END, and another semicolon.
  112775. **
  112776. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  112777. ** the end of a trigger definition.
  112778. **
  112779. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  112780. ** of a trigger difinition.
  112781. **
  112782. ** Transitions between states above are determined by tokens extracted
  112783. ** from the input. The following tokens are significant:
  112784. **
  112785. ** (0) tkSEMI A semicolon.
  112786. ** (1) tkWS Whitespace.
  112787. ** (2) tkOTHER Any other SQL token.
  112788. ** (3) tkEXPLAIN The "explain" keyword.
  112789. ** (4) tkCREATE The "create" keyword.
  112790. ** (5) tkTEMP The "temp" or "temporary" keyword.
  112791. ** (6) tkTRIGGER The "trigger" keyword.
  112792. ** (7) tkEND The "end" keyword.
  112793. **
  112794. ** Whitespace never causes a state transition and is always ignored.
  112795. ** This means that a SQL string of all whitespace is invalid.
  112796. **
  112797. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  112798. ** to recognize the end of a trigger can be omitted. All we have to do
  112799. ** is look for a semicolon that is not part of an string or comment.
  112800. */
  112801. SQLITE_API int sqlite3_complete(const char *zSql){
  112802. u8 state = 0; /* Current state, using numbers defined in header comment */
  112803. u8 token; /* Value of the next token */
  112804. #ifndef SQLITE_OMIT_TRIGGER
  112805. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  112806. ** statement. This is the normal case.
  112807. */
  112808. static const u8 trans[8][8] = {
  112809. /* Token: */
  112810. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  112811. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  112812. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  112813. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  112814. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  112815. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  112816. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  112817. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  112818. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  112819. };
  112820. #else
  112821. /* If triggers are not supported by this compile then the statement machine
  112822. ** used to detect the end of a statement is much simplier
  112823. */
  112824. static const u8 trans[3][3] = {
  112825. /* Token: */
  112826. /* State: ** SEMI WS OTHER */
  112827. /* 0 INVALID: */ { 1, 0, 2, },
  112828. /* 1 START: */ { 1, 1, 2, },
  112829. /* 2 NORMAL: */ { 1, 2, 2, },
  112830. };
  112831. #endif /* SQLITE_OMIT_TRIGGER */
  112832. while( *zSql ){
  112833. switch( *zSql ){
  112834. case ';': { /* A semicolon */
  112835. token = tkSEMI;
  112836. break;
  112837. }
  112838. case ' ':
  112839. case '\r':
  112840. case '\t':
  112841. case '\n':
  112842. case '\f': { /* White space is ignored */
  112843. token = tkWS;
  112844. break;
  112845. }
  112846. case '/': { /* C-style comments */
  112847. if( zSql[1]!='*' ){
  112848. token = tkOTHER;
  112849. break;
  112850. }
  112851. zSql += 2;
  112852. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  112853. if( zSql[0]==0 ) return 0;
  112854. zSql++;
  112855. token = tkWS;
  112856. break;
  112857. }
  112858. case '-': { /* SQL-style comments from "--" to end of line */
  112859. if( zSql[1]!='-' ){
  112860. token = tkOTHER;
  112861. break;
  112862. }
  112863. while( *zSql && *zSql!='\n' ){ zSql++; }
  112864. if( *zSql==0 ) return state==1;
  112865. token = tkWS;
  112866. break;
  112867. }
  112868. case '[': { /* Microsoft-style identifiers in [...] */
  112869. zSql++;
  112870. while( *zSql && *zSql!=']' ){ zSql++; }
  112871. if( *zSql==0 ) return 0;
  112872. token = tkOTHER;
  112873. break;
  112874. }
  112875. case '`': /* Grave-accent quoted symbols used by MySQL */
  112876. case '"': /* single- and double-quoted strings */
  112877. case '\'': {
  112878. int c = *zSql;
  112879. zSql++;
  112880. while( *zSql && *zSql!=c ){ zSql++; }
  112881. if( *zSql==0 ) return 0;
  112882. token = tkOTHER;
  112883. break;
  112884. }
  112885. default: {
  112886. #ifdef SQLITE_EBCDIC
  112887. unsigned char c;
  112888. #endif
  112889. if( IdChar((u8)*zSql) ){
  112890. /* Keywords and unquoted identifiers */
  112891. int nId;
  112892. for(nId=1; IdChar(zSql[nId]); nId++){}
  112893. #ifdef SQLITE_OMIT_TRIGGER
  112894. token = tkOTHER;
  112895. #else
  112896. switch( *zSql ){
  112897. case 'c': case 'C': {
  112898. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  112899. token = tkCREATE;
  112900. }else{
  112901. token = tkOTHER;
  112902. }
  112903. break;
  112904. }
  112905. case 't': case 'T': {
  112906. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  112907. token = tkTRIGGER;
  112908. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  112909. token = tkTEMP;
  112910. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  112911. token = tkTEMP;
  112912. }else{
  112913. token = tkOTHER;
  112914. }
  112915. break;
  112916. }
  112917. case 'e': case 'E': {
  112918. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  112919. token = tkEND;
  112920. }else
  112921. #ifndef SQLITE_OMIT_EXPLAIN
  112922. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  112923. token = tkEXPLAIN;
  112924. }else
  112925. #endif
  112926. {
  112927. token = tkOTHER;
  112928. }
  112929. break;
  112930. }
  112931. default: {
  112932. token = tkOTHER;
  112933. break;
  112934. }
  112935. }
  112936. #endif /* SQLITE_OMIT_TRIGGER */
  112937. zSql += nId-1;
  112938. }else{
  112939. /* Operators and special symbols */
  112940. token = tkOTHER;
  112941. }
  112942. break;
  112943. }
  112944. }
  112945. state = trans[state][token];
  112946. zSql++;
  112947. }
  112948. return state==1;
  112949. }
  112950. #ifndef SQLITE_OMIT_UTF16
  112951. /*
  112952. ** This routine is the same as the sqlite3_complete() routine described
  112953. ** above, except that the parameter is required to be UTF-16 encoded, not
  112954. ** UTF-8.
  112955. */
  112956. SQLITE_API int sqlite3_complete16(const void *zSql){
  112957. sqlite3_value *pVal;
  112958. char const *zSql8;
  112959. int rc = SQLITE_NOMEM;
  112960. #ifndef SQLITE_OMIT_AUTOINIT
  112961. rc = sqlite3_initialize();
  112962. if( rc ) return rc;
  112963. #endif
  112964. pVal = sqlite3ValueNew(0);
  112965. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  112966. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  112967. if( zSql8 ){
  112968. rc = sqlite3_complete(zSql8);
  112969. }else{
  112970. rc = SQLITE_NOMEM;
  112971. }
  112972. sqlite3ValueFree(pVal);
  112973. return sqlite3ApiExit(0, rc);
  112974. }
  112975. #endif /* SQLITE_OMIT_UTF16 */
  112976. #endif /* SQLITE_OMIT_COMPLETE */
  112977. /************** End of complete.c ********************************************/
  112978. /************** Begin file main.c ********************************************/
  112979. /*
  112980. ** 2001 September 15
  112981. **
  112982. ** The author disclaims copyright to this source code. In place of
  112983. ** a legal notice, here is a blessing:
  112984. **
  112985. ** May you do good and not evil.
  112986. ** May you find forgiveness for yourself and forgive others.
  112987. ** May you share freely, never taking more than you give.
  112988. **
  112989. *************************************************************************
  112990. ** Main file for the SQLite library. The routines in this file
  112991. ** implement the programmer interface to the library. Routines in
  112992. ** other files are for internal use by SQLite and should not be
  112993. ** accessed by users of the library.
  112994. */
  112995. #ifdef SQLITE_ENABLE_FTS3
  112996. /************** Include fts3.h in the middle of main.c ***********************/
  112997. /************** Begin file fts3.h ********************************************/
  112998. /*
  112999. ** 2006 Oct 10
  113000. **
  113001. ** The author disclaims copyright to this source code. In place of
  113002. ** a legal notice, here is a blessing:
  113003. **
  113004. ** May you do good and not evil.
  113005. ** May you find forgiveness for yourself and forgive others.
  113006. ** May you share freely, never taking more than you give.
  113007. **
  113008. ******************************************************************************
  113009. **
  113010. ** This header file is used by programs that want to link against the
  113011. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  113012. */
  113013. #if 0
  113014. extern "C" {
  113015. #endif /* __cplusplus */
  113016. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  113017. #if 0
  113018. } /* extern "C" */
  113019. #endif /* __cplusplus */
  113020. /************** End of fts3.h ************************************************/
  113021. /************** Continuing where we left off in main.c ***********************/
  113022. #endif
  113023. #ifdef SQLITE_ENABLE_RTREE
  113024. /************** Include rtree.h in the middle of main.c **********************/
  113025. /************** Begin file rtree.h *******************************************/
  113026. /*
  113027. ** 2008 May 26
  113028. **
  113029. ** The author disclaims copyright to this source code. In place of
  113030. ** a legal notice, here is a blessing:
  113031. **
  113032. ** May you do good and not evil.
  113033. ** May you find forgiveness for yourself and forgive others.
  113034. ** May you share freely, never taking more than you give.
  113035. **
  113036. ******************************************************************************
  113037. **
  113038. ** This header file is used by programs that want to link against the
  113039. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  113040. */
  113041. #if 0
  113042. extern "C" {
  113043. #endif /* __cplusplus */
  113044. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  113045. #if 0
  113046. } /* extern "C" */
  113047. #endif /* __cplusplus */
  113048. /************** End of rtree.h ***********************************************/
  113049. /************** Continuing where we left off in main.c ***********************/
  113050. #endif
  113051. #ifdef SQLITE_ENABLE_ICU
  113052. /************** Include sqliteicu.h in the middle of main.c ******************/
  113053. /************** Begin file sqliteicu.h ***************************************/
  113054. /*
  113055. ** 2008 May 26
  113056. **
  113057. ** The author disclaims copyright to this source code. In place of
  113058. ** a legal notice, here is a blessing:
  113059. **
  113060. ** May you do good and not evil.
  113061. ** May you find forgiveness for yourself and forgive others.
  113062. ** May you share freely, never taking more than you give.
  113063. **
  113064. ******************************************************************************
  113065. **
  113066. ** This header file is used by programs that want to link against the
  113067. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  113068. */
  113069. #if 0
  113070. extern "C" {
  113071. #endif /* __cplusplus */
  113072. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  113073. #if 0
  113074. } /* extern "C" */
  113075. #endif /* __cplusplus */
  113076. /************** End of sqliteicu.h *******************************************/
  113077. /************** Continuing where we left off in main.c ***********************/
  113078. #endif
  113079. #ifndef SQLITE_AMALGAMATION
  113080. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  113081. ** contains the text of SQLITE_VERSION macro.
  113082. */
  113083. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  113084. #endif
  113085. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  113086. ** a pointer to the to the sqlite3_version[] string constant.
  113087. */
  113088. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  113089. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  113090. ** pointer to a string constant whose value is the same as the
  113091. ** SQLITE_SOURCE_ID C preprocessor macro.
  113092. */
  113093. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  113094. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  113095. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  113096. */
  113097. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  113098. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  113099. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  113100. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  113101. */
  113102. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  113103. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  113104. /*
  113105. ** If the following function pointer is not NULL and if
  113106. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  113107. ** I/O active are written using this function. These messages
  113108. ** are intended for debugging activity only.
  113109. */
  113110. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  113111. #endif
  113112. /*
  113113. ** If the following global variable points to a string which is the
  113114. ** name of a directory, then that directory will be used to store
  113115. ** temporary files.
  113116. **
  113117. ** See also the "PRAGMA temp_store_directory" SQL command.
  113118. */
  113119. SQLITE_API char *sqlite3_temp_directory = 0;
  113120. /*
  113121. ** If the following global variable points to a string which is the
  113122. ** name of a directory, then that directory will be used to store
  113123. ** all database files specified with a relative pathname.
  113124. **
  113125. ** See also the "PRAGMA data_store_directory" SQL command.
  113126. */
  113127. SQLITE_API char *sqlite3_data_directory = 0;
  113128. /*
  113129. ** Initialize SQLite.
  113130. **
  113131. ** This routine must be called to initialize the memory allocation,
  113132. ** VFS, and mutex subsystems prior to doing any serious work with
  113133. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  113134. ** this routine will be called automatically by key routines such as
  113135. ** sqlite3_open().
  113136. **
  113137. ** This routine is a no-op except on its very first call for the process,
  113138. ** or for the first call after a call to sqlite3_shutdown.
  113139. **
  113140. ** The first thread to call this routine runs the initialization to
  113141. ** completion. If subsequent threads call this routine before the first
  113142. ** thread has finished the initialization process, then the subsequent
  113143. ** threads must block until the first thread finishes with the initialization.
  113144. **
  113145. ** The first thread might call this routine recursively. Recursive
  113146. ** calls to this routine should not block, of course. Otherwise the
  113147. ** initialization process would never complete.
  113148. **
  113149. ** Let X be the first thread to enter this routine. Let Y be some other
  113150. ** thread. Then while the initial invocation of this routine by X is
  113151. ** incomplete, it is required that:
  113152. **
  113153. ** * Calls to this routine from Y must block until the outer-most
  113154. ** call by X completes.
  113155. **
  113156. ** * Recursive calls to this routine from thread X return immediately
  113157. ** without blocking.
  113158. */
  113159. SQLITE_API int sqlite3_initialize(void){
  113160. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  113161. int rc; /* Result code */
  113162. #ifdef SQLITE_EXTRA_INIT
  113163. int bRunExtraInit = 0; /* Extra initialization needed */
  113164. #endif
  113165. #ifdef SQLITE_OMIT_WSD
  113166. rc = sqlite3_wsd_init(4096, 24);
  113167. if( rc!=SQLITE_OK ){
  113168. return rc;
  113169. }
  113170. #endif
  113171. /* If SQLite is already completely initialized, then this call
  113172. ** to sqlite3_initialize() should be a no-op. But the initialization
  113173. ** must be complete. So isInit must not be set until the very end
  113174. ** of this routine.
  113175. */
  113176. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  113177. #ifdef SQLITE_ENABLE_SQLLOG
  113178. {
  113179. extern void sqlite3_init_sqllog(void);
  113180. sqlite3_init_sqllog();
  113181. }
  113182. #endif
  113183. /* Make sure the mutex subsystem is initialized. If unable to
  113184. ** initialize the mutex subsystem, return early with the error.
  113185. ** If the system is so sick that we are unable to allocate a mutex,
  113186. ** there is not much SQLite is going to be able to do.
  113187. **
  113188. ** The mutex subsystem must take care of serializing its own
  113189. ** initialization.
  113190. */
  113191. rc = sqlite3MutexInit();
  113192. if( rc ) return rc;
  113193. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  113194. ** This operation is protected by the STATIC_MASTER mutex. Note that
  113195. ** MutexAlloc() is called for a static mutex prior to initializing the
  113196. ** malloc subsystem - this implies that the allocation of a static
  113197. ** mutex must not require support from the malloc subsystem.
  113198. */
  113199. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  113200. sqlite3_mutex_enter(pMaster);
  113201. sqlite3GlobalConfig.isMutexInit = 1;
  113202. if( !sqlite3GlobalConfig.isMallocInit ){
  113203. rc = sqlite3MallocInit();
  113204. }
  113205. if( rc==SQLITE_OK ){
  113206. sqlite3GlobalConfig.isMallocInit = 1;
  113207. if( !sqlite3GlobalConfig.pInitMutex ){
  113208. sqlite3GlobalConfig.pInitMutex =
  113209. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  113210. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  113211. rc = SQLITE_NOMEM;
  113212. }
  113213. }
  113214. }
  113215. if( rc==SQLITE_OK ){
  113216. sqlite3GlobalConfig.nRefInitMutex++;
  113217. }
  113218. sqlite3_mutex_leave(pMaster);
  113219. /* If rc is not SQLITE_OK at this point, then either the malloc
  113220. ** subsystem could not be initialized or the system failed to allocate
  113221. ** the pInitMutex mutex. Return an error in either case. */
  113222. if( rc!=SQLITE_OK ){
  113223. return rc;
  113224. }
  113225. /* Do the rest of the initialization under the recursive mutex so
  113226. ** that we will be able to handle recursive calls into
  113227. ** sqlite3_initialize(). The recursive calls normally come through
  113228. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  113229. ** recursive calls might also be possible.
  113230. **
  113231. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  113232. ** to the xInit method, so the xInit method need not be threadsafe.
  113233. **
  113234. ** The following mutex is what serializes access to the appdef pcache xInit
  113235. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  113236. ** call to sqlite3PcacheInitialize().
  113237. */
  113238. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  113239. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  113240. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  113241. sqlite3GlobalConfig.inProgress = 1;
  113242. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  113243. sqlite3RegisterGlobalFunctions();
  113244. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  113245. rc = sqlite3PcacheInitialize();
  113246. }
  113247. if( rc==SQLITE_OK ){
  113248. sqlite3GlobalConfig.isPCacheInit = 1;
  113249. rc = sqlite3OsInit();
  113250. }
  113251. if( rc==SQLITE_OK ){
  113252. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  113253. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  113254. sqlite3GlobalConfig.isInit = 1;
  113255. #ifdef SQLITE_EXTRA_INIT
  113256. bRunExtraInit = 1;
  113257. #endif
  113258. }
  113259. sqlite3GlobalConfig.inProgress = 0;
  113260. }
  113261. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  113262. /* Go back under the static mutex and clean up the recursive
  113263. ** mutex to prevent a resource leak.
  113264. */
  113265. sqlite3_mutex_enter(pMaster);
  113266. sqlite3GlobalConfig.nRefInitMutex--;
  113267. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  113268. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  113269. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  113270. sqlite3GlobalConfig.pInitMutex = 0;
  113271. }
  113272. sqlite3_mutex_leave(pMaster);
  113273. /* The following is just a sanity check to make sure SQLite has
  113274. ** been compiled correctly. It is important to run this code, but
  113275. ** we don't want to run it too often and soak up CPU cycles for no
  113276. ** reason. So we run it once during initialization.
  113277. */
  113278. #ifndef NDEBUG
  113279. #ifndef SQLITE_OMIT_FLOATING_POINT
  113280. /* This section of code's only "output" is via assert() statements. */
  113281. if ( rc==SQLITE_OK ){
  113282. u64 x = (((u64)1)<<63)-1;
  113283. double y;
  113284. assert(sizeof(x)==8);
  113285. assert(sizeof(x)==sizeof(y));
  113286. memcpy(&y, &x, 8);
  113287. assert( sqlite3IsNaN(y) );
  113288. }
  113289. #endif
  113290. #endif
  113291. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  113292. ** compile-time option.
  113293. */
  113294. #ifdef SQLITE_EXTRA_INIT
  113295. if( bRunExtraInit ){
  113296. int SQLITE_EXTRA_INIT(const char*);
  113297. rc = SQLITE_EXTRA_INIT(0);
  113298. }
  113299. #endif
  113300. return rc;
  113301. }
  113302. /*
  113303. ** Undo the effects of sqlite3_initialize(). Must not be called while
  113304. ** there are outstanding database connections or memory allocations or
  113305. ** while any part of SQLite is otherwise in use in any thread. This
  113306. ** routine is not threadsafe. But it is safe to invoke this routine
  113307. ** on when SQLite is already shut down. If SQLite is already shut down
  113308. ** when this routine is invoked, then this routine is a harmless no-op.
  113309. */
  113310. SQLITE_API int sqlite3_shutdown(void){
  113311. if( sqlite3GlobalConfig.isInit ){
  113312. #ifdef SQLITE_EXTRA_SHUTDOWN
  113313. void SQLITE_EXTRA_SHUTDOWN(void);
  113314. SQLITE_EXTRA_SHUTDOWN();
  113315. #endif
  113316. sqlite3_os_end();
  113317. sqlite3_reset_auto_extension();
  113318. sqlite3GlobalConfig.isInit = 0;
  113319. }
  113320. if( sqlite3GlobalConfig.isPCacheInit ){
  113321. sqlite3PcacheShutdown();
  113322. sqlite3GlobalConfig.isPCacheInit = 0;
  113323. }
  113324. if( sqlite3GlobalConfig.isMallocInit ){
  113325. sqlite3MallocEnd();
  113326. sqlite3GlobalConfig.isMallocInit = 0;
  113327. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  113328. /* The heap subsystem has now been shutdown and these values are supposed
  113329. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  113330. ** which would rely on that heap subsystem; therefore, make sure these
  113331. ** values cannot refer to heap memory that was just invalidated when the
  113332. ** heap subsystem was shutdown. This is only done if the current call to
  113333. ** this function resulted in the heap subsystem actually being shutdown.
  113334. */
  113335. sqlite3_data_directory = 0;
  113336. sqlite3_temp_directory = 0;
  113337. #endif
  113338. }
  113339. if( sqlite3GlobalConfig.isMutexInit ){
  113340. sqlite3MutexEnd();
  113341. sqlite3GlobalConfig.isMutexInit = 0;
  113342. }
  113343. return SQLITE_OK;
  113344. }
  113345. /*
  113346. ** This API allows applications to modify the global configuration of
  113347. ** the SQLite library at run-time.
  113348. **
  113349. ** This routine should only be called when there are no outstanding
  113350. ** database connections or memory allocations. This routine is not
  113351. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  113352. ** behavior.
  113353. */
  113354. SQLITE_API int sqlite3_config(int op, ...){
  113355. va_list ap;
  113356. int rc = SQLITE_OK;
  113357. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  113358. ** the SQLite library is in use. */
  113359. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  113360. va_start(ap, op);
  113361. switch( op ){
  113362. /* Mutex configuration options are only available in a threadsafe
  113363. ** compile.
  113364. */
  113365. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  113366. case SQLITE_CONFIG_SINGLETHREAD: {
  113367. /* Disable all mutexing */
  113368. sqlite3GlobalConfig.bCoreMutex = 0;
  113369. sqlite3GlobalConfig.bFullMutex = 0;
  113370. break;
  113371. }
  113372. case SQLITE_CONFIG_MULTITHREAD: {
  113373. /* Disable mutexing of database connections */
  113374. /* Enable mutexing of core data structures */
  113375. sqlite3GlobalConfig.bCoreMutex = 1;
  113376. sqlite3GlobalConfig.bFullMutex = 0;
  113377. break;
  113378. }
  113379. case SQLITE_CONFIG_SERIALIZED: {
  113380. /* Enable all mutexing */
  113381. sqlite3GlobalConfig.bCoreMutex = 1;
  113382. sqlite3GlobalConfig.bFullMutex = 1;
  113383. break;
  113384. }
  113385. case SQLITE_CONFIG_MUTEX: {
  113386. /* Specify an alternative mutex implementation */
  113387. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  113388. break;
  113389. }
  113390. case SQLITE_CONFIG_GETMUTEX: {
  113391. /* Retrieve the current mutex implementation */
  113392. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  113393. break;
  113394. }
  113395. #endif
  113396. case SQLITE_CONFIG_MALLOC: {
  113397. /* Specify an alternative malloc implementation */
  113398. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  113399. break;
  113400. }
  113401. case SQLITE_CONFIG_GETMALLOC: {
  113402. /* Retrieve the current malloc() implementation */
  113403. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  113404. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  113405. break;
  113406. }
  113407. case SQLITE_CONFIG_MEMSTATUS: {
  113408. /* Enable or disable the malloc status collection */
  113409. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  113410. break;
  113411. }
  113412. case SQLITE_CONFIG_SCRATCH: {
  113413. /* Designate a buffer for scratch memory space */
  113414. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  113415. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  113416. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  113417. break;
  113418. }
  113419. case SQLITE_CONFIG_PAGECACHE: {
  113420. /* Designate a buffer for page cache memory space */
  113421. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  113422. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  113423. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  113424. break;
  113425. }
  113426. case SQLITE_CONFIG_PCACHE: {
  113427. /* no-op */
  113428. break;
  113429. }
  113430. case SQLITE_CONFIG_GETPCACHE: {
  113431. /* now an error */
  113432. rc = SQLITE_ERROR;
  113433. break;
  113434. }
  113435. case SQLITE_CONFIG_PCACHE2: {
  113436. /* Specify an alternative page cache implementation */
  113437. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  113438. break;
  113439. }
  113440. case SQLITE_CONFIG_GETPCACHE2: {
  113441. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  113442. sqlite3PCacheSetDefault();
  113443. }
  113444. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  113445. break;
  113446. }
  113447. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  113448. case SQLITE_CONFIG_HEAP: {
  113449. /* Designate a buffer for heap memory space */
  113450. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  113451. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  113452. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  113453. if( sqlite3GlobalConfig.mnReq<1 ){
  113454. sqlite3GlobalConfig.mnReq = 1;
  113455. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  113456. /* cap min request size at 2^12 */
  113457. sqlite3GlobalConfig.mnReq = (1<<12);
  113458. }
  113459. if( sqlite3GlobalConfig.pHeap==0 ){
  113460. /* If the heap pointer is NULL, then restore the malloc implementation
  113461. ** back to NULL pointers too. This will cause the malloc to go
  113462. ** back to its default implementation when sqlite3_initialize() is
  113463. ** run.
  113464. */
  113465. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  113466. }else{
  113467. /* The heap pointer is not NULL, then install one of the
  113468. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  113469. ** least one of these methods is currently enabled.
  113470. */
  113471. #ifdef SQLITE_ENABLE_MEMSYS3
  113472. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  113473. #endif
  113474. #ifdef SQLITE_ENABLE_MEMSYS5
  113475. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  113476. #endif
  113477. }
  113478. break;
  113479. }
  113480. #endif
  113481. case SQLITE_CONFIG_LOOKASIDE: {
  113482. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  113483. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  113484. break;
  113485. }
  113486. /* Record a pointer to the logger function and its first argument.
  113487. ** The default is NULL. Logging is disabled if the function pointer is
  113488. ** NULL.
  113489. */
  113490. case SQLITE_CONFIG_LOG: {
  113491. /* MSVC is picky about pulling func ptrs from va lists.
  113492. ** http://support.microsoft.com/kb/47961
  113493. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  113494. */
  113495. typedef void(*LOGFUNC_t)(void*,int,const char*);
  113496. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  113497. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  113498. break;
  113499. }
  113500. case SQLITE_CONFIG_URI: {
  113501. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  113502. break;
  113503. }
  113504. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  113505. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  113506. break;
  113507. }
  113508. #ifdef SQLITE_ENABLE_SQLLOG
  113509. case SQLITE_CONFIG_SQLLOG: {
  113510. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  113511. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  113512. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  113513. break;
  113514. }
  113515. #endif
  113516. case SQLITE_CONFIG_MMAP_SIZE: {
  113517. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  113518. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  113519. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  113520. mxMmap = SQLITE_MAX_MMAP_SIZE;
  113521. }
  113522. sqlite3GlobalConfig.mxMmap = mxMmap;
  113523. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  113524. if( szMmap>mxMmap) szMmap = mxMmap;
  113525. sqlite3GlobalConfig.szMmap = szMmap;
  113526. break;
  113527. }
  113528. default: {
  113529. rc = SQLITE_ERROR;
  113530. break;
  113531. }
  113532. }
  113533. va_end(ap);
  113534. return rc;
  113535. }
  113536. /*
  113537. ** Set up the lookaside buffers for a database connection.
  113538. ** Return SQLITE_OK on success.
  113539. ** If lookaside is already active, return SQLITE_BUSY.
  113540. **
  113541. ** The sz parameter is the number of bytes in each lookaside slot.
  113542. ** The cnt parameter is the number of slots. If pStart is NULL the
  113543. ** space for the lookaside memory is obtained from sqlite3_malloc().
  113544. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  113545. ** the lookaside memory.
  113546. */
  113547. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  113548. void *pStart;
  113549. if( db->lookaside.nOut ){
  113550. return SQLITE_BUSY;
  113551. }
  113552. /* Free any existing lookaside buffer for this handle before
  113553. ** allocating a new one so we don't have to have space for
  113554. ** both at the same time.
  113555. */
  113556. if( db->lookaside.bMalloced ){
  113557. sqlite3_free(db->lookaside.pStart);
  113558. }
  113559. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  113560. ** than a pointer to be useful.
  113561. */
  113562. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  113563. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  113564. if( cnt<0 ) cnt = 0;
  113565. if( sz==0 || cnt==0 ){
  113566. sz = 0;
  113567. pStart = 0;
  113568. }else if( pBuf==0 ){
  113569. sqlite3BeginBenignMalloc();
  113570. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  113571. sqlite3EndBenignMalloc();
  113572. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  113573. }else{
  113574. pStart = pBuf;
  113575. }
  113576. db->lookaside.pStart = pStart;
  113577. db->lookaside.pFree = 0;
  113578. db->lookaside.sz = (u16)sz;
  113579. if( pStart ){
  113580. int i;
  113581. LookasideSlot *p;
  113582. assert( sz > (int)sizeof(LookasideSlot*) );
  113583. p = (LookasideSlot*)pStart;
  113584. for(i=cnt-1; i>=0; i--){
  113585. p->pNext = db->lookaside.pFree;
  113586. db->lookaside.pFree = p;
  113587. p = (LookasideSlot*)&((u8*)p)[sz];
  113588. }
  113589. db->lookaside.pEnd = p;
  113590. db->lookaside.bEnabled = 1;
  113591. db->lookaside.bMalloced = pBuf==0 ?1:0;
  113592. }else{
  113593. db->lookaside.pEnd = 0;
  113594. db->lookaside.bEnabled = 0;
  113595. db->lookaside.bMalloced = 0;
  113596. }
  113597. return SQLITE_OK;
  113598. }
  113599. /*
  113600. ** Return the mutex associated with a database connection.
  113601. */
  113602. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  113603. return db->mutex;
  113604. }
  113605. /*
  113606. ** Free up as much memory as we can from the given database
  113607. ** connection.
  113608. */
  113609. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  113610. int i;
  113611. sqlite3_mutex_enter(db->mutex);
  113612. sqlite3BtreeEnterAll(db);
  113613. for(i=0; i<db->nDb; i++){
  113614. Btree *pBt = db->aDb[i].pBt;
  113615. if( pBt ){
  113616. Pager *pPager = sqlite3BtreePager(pBt);
  113617. sqlite3PagerShrink(pPager);
  113618. }
  113619. }
  113620. sqlite3BtreeLeaveAll(db);
  113621. sqlite3_mutex_leave(db->mutex);
  113622. return SQLITE_OK;
  113623. }
  113624. /*
  113625. ** Configuration settings for an individual database connection
  113626. */
  113627. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  113628. va_list ap;
  113629. int rc;
  113630. va_start(ap, op);
  113631. switch( op ){
  113632. case SQLITE_DBCONFIG_LOOKASIDE: {
  113633. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  113634. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  113635. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  113636. rc = setupLookaside(db, pBuf, sz, cnt);
  113637. break;
  113638. }
  113639. default: {
  113640. static const struct {
  113641. int op; /* The opcode */
  113642. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  113643. } aFlagOp[] = {
  113644. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  113645. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  113646. };
  113647. unsigned int i;
  113648. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  113649. for(i=0; i<ArraySize(aFlagOp); i++){
  113650. if( aFlagOp[i].op==op ){
  113651. int onoff = va_arg(ap, int);
  113652. int *pRes = va_arg(ap, int*);
  113653. int oldFlags = db->flags;
  113654. if( onoff>0 ){
  113655. db->flags |= aFlagOp[i].mask;
  113656. }else if( onoff==0 ){
  113657. db->flags &= ~aFlagOp[i].mask;
  113658. }
  113659. if( oldFlags!=db->flags ){
  113660. sqlite3ExpirePreparedStatements(db);
  113661. }
  113662. if( pRes ){
  113663. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  113664. }
  113665. rc = SQLITE_OK;
  113666. break;
  113667. }
  113668. }
  113669. break;
  113670. }
  113671. }
  113672. va_end(ap);
  113673. return rc;
  113674. }
  113675. /*
  113676. ** Return true if the buffer z[0..n-1] contains all spaces.
  113677. */
  113678. static int allSpaces(const char *z, int n){
  113679. while( n>0 && z[n-1]==' ' ){ n--; }
  113680. return n==0;
  113681. }
  113682. /*
  113683. ** This is the default collating function named "BINARY" which is always
  113684. ** available.
  113685. **
  113686. ** If the padFlag argument is not NULL then space padding at the end
  113687. ** of strings is ignored. This implements the RTRIM collation.
  113688. */
  113689. static int binCollFunc(
  113690. void *padFlag,
  113691. int nKey1, const void *pKey1,
  113692. int nKey2, const void *pKey2
  113693. ){
  113694. int rc, n;
  113695. n = nKey1<nKey2 ? nKey1 : nKey2;
  113696. rc = memcmp(pKey1, pKey2, n);
  113697. if( rc==0 ){
  113698. if( padFlag
  113699. && allSpaces(((char*)pKey1)+n, nKey1-n)
  113700. && allSpaces(((char*)pKey2)+n, nKey2-n)
  113701. ){
  113702. /* Leave rc unchanged at 0 */
  113703. }else{
  113704. rc = nKey1 - nKey2;
  113705. }
  113706. }
  113707. return rc;
  113708. }
  113709. /*
  113710. ** Another built-in collating sequence: NOCASE.
  113711. **
  113712. ** This collating sequence is intended to be used for "case independent
  113713. ** comparison". SQLite's knowledge of upper and lower case equivalents
  113714. ** extends only to the 26 characters used in the English language.
  113715. **
  113716. ** At the moment there is only a UTF-8 implementation.
  113717. */
  113718. static int nocaseCollatingFunc(
  113719. void *NotUsed,
  113720. int nKey1, const void *pKey1,
  113721. int nKey2, const void *pKey2
  113722. ){
  113723. int r = sqlite3StrNICmp(
  113724. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  113725. UNUSED_PARAMETER(NotUsed);
  113726. if( 0==r ){
  113727. r = nKey1-nKey2;
  113728. }
  113729. return r;
  113730. }
  113731. /*
  113732. ** Return the ROWID of the most recent insert
  113733. */
  113734. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  113735. return db->lastRowid;
  113736. }
  113737. /*
  113738. ** Return the number of changes in the most recent call to sqlite3_exec().
  113739. */
  113740. SQLITE_API int sqlite3_changes(sqlite3 *db){
  113741. return db->nChange;
  113742. }
  113743. /*
  113744. ** Return the number of changes since the database handle was opened.
  113745. */
  113746. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  113747. return db->nTotalChange;
  113748. }
  113749. /*
  113750. ** Close all open savepoints. This function only manipulates fields of the
  113751. ** database handle object, it does not close any savepoints that may be open
  113752. ** at the b-tree/pager level.
  113753. */
  113754. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  113755. while( db->pSavepoint ){
  113756. Savepoint *pTmp = db->pSavepoint;
  113757. db->pSavepoint = pTmp->pNext;
  113758. sqlite3DbFree(db, pTmp);
  113759. }
  113760. db->nSavepoint = 0;
  113761. db->nStatement = 0;
  113762. db->isTransactionSavepoint = 0;
  113763. }
  113764. /*
  113765. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  113766. ** if this is not the last copy of the function, do not invoke it. Multiple
  113767. ** copies of a single function are created when create_function() is called
  113768. ** with SQLITE_ANY as the encoding.
  113769. */
  113770. static void functionDestroy(sqlite3 *db, FuncDef *p){
  113771. FuncDestructor *pDestructor = p->pDestructor;
  113772. if( pDestructor ){
  113773. pDestructor->nRef--;
  113774. if( pDestructor->nRef==0 ){
  113775. pDestructor->xDestroy(pDestructor->pUserData);
  113776. sqlite3DbFree(db, pDestructor);
  113777. }
  113778. }
  113779. }
  113780. /*
  113781. ** Disconnect all sqlite3_vtab objects that belong to database connection
  113782. ** db. This is called when db is being closed.
  113783. */
  113784. static void disconnectAllVtab(sqlite3 *db){
  113785. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113786. int i;
  113787. sqlite3BtreeEnterAll(db);
  113788. for(i=0; i<db->nDb; i++){
  113789. Schema *pSchema = db->aDb[i].pSchema;
  113790. if( db->aDb[i].pSchema ){
  113791. HashElem *p;
  113792. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  113793. Table *pTab = (Table *)sqliteHashData(p);
  113794. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  113795. }
  113796. }
  113797. }
  113798. sqlite3BtreeLeaveAll(db);
  113799. #else
  113800. UNUSED_PARAMETER(db);
  113801. #endif
  113802. }
  113803. /*
  113804. ** Return TRUE if database connection db has unfinalized prepared
  113805. ** statements or unfinished sqlite3_backup objects.
  113806. */
  113807. static int connectionIsBusy(sqlite3 *db){
  113808. int j;
  113809. assert( sqlite3_mutex_held(db->mutex) );
  113810. if( db->pVdbe ) return 1;
  113811. for(j=0; j<db->nDb; j++){
  113812. Btree *pBt = db->aDb[j].pBt;
  113813. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  113814. }
  113815. return 0;
  113816. }
  113817. /*
  113818. ** Close an existing SQLite database
  113819. */
  113820. static int sqlite3Close(sqlite3 *db, int forceZombie){
  113821. if( !db ){
  113822. return SQLITE_OK;
  113823. }
  113824. if( !sqlite3SafetyCheckSickOrOk(db) ){
  113825. return SQLITE_MISUSE_BKPT;
  113826. }
  113827. sqlite3_mutex_enter(db->mutex);
  113828. /* Force xDisconnect calls on all virtual tables */
  113829. disconnectAllVtab(db);
  113830. /* If a transaction is open, the disconnectAllVtab() call above
  113831. ** will not have called the xDisconnect() method on any virtual
  113832. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  113833. ** call will do so. We need to do this before the check for active
  113834. ** SQL statements below, as the v-table implementation may be storing
  113835. ** some prepared statements internally.
  113836. */
  113837. sqlite3VtabRollback(db);
  113838. /* Legacy behavior (sqlite3_close() behavior) is to return
  113839. ** SQLITE_BUSY if the connection can not be closed immediately.
  113840. */
  113841. if( !forceZombie && connectionIsBusy(db) ){
  113842. sqlite3Error(db, SQLITE_BUSY, "unable to close due to unfinalized "
  113843. "statements or unfinished backups");
  113844. sqlite3_mutex_leave(db->mutex);
  113845. return SQLITE_BUSY;
  113846. }
  113847. #ifdef SQLITE_ENABLE_SQLLOG
  113848. if( sqlite3GlobalConfig.xSqllog ){
  113849. /* Closing the handle. Fourth parameter is passed the value 2. */
  113850. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  113851. }
  113852. #endif
  113853. /* Convert the connection into a zombie and then close it.
  113854. */
  113855. db->magic = SQLITE_MAGIC_ZOMBIE;
  113856. sqlite3LeaveMutexAndCloseZombie(db);
  113857. return SQLITE_OK;
  113858. }
  113859. /*
  113860. ** Two variations on the public interface for closing a database
  113861. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  113862. ** leaves the connection option if there are unfinalized prepared
  113863. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  113864. ** version forces the connection to become a zombie if there are
  113865. ** unclosed resources, and arranges for deallocation when the last
  113866. ** prepare statement or sqlite3_backup closes.
  113867. */
  113868. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  113869. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  113870. /*
  113871. ** Close the mutex on database connection db.
  113872. **
  113873. ** Furthermore, if database connection db is a zombie (meaning that there
  113874. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  113875. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  113876. ** finished, then free all resources.
  113877. */
  113878. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  113879. HashElem *i; /* Hash table iterator */
  113880. int j;
  113881. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  113882. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  113883. ** then just leave the mutex and return.
  113884. */
  113885. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  113886. sqlite3_mutex_leave(db->mutex);
  113887. return;
  113888. }
  113889. /* If we reach this point, it means that the database connection has
  113890. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  113891. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  113892. ** go ahead and free all resources.
  113893. */
  113894. /* If a transaction is open, roll it back. This also ensures that if
  113895. ** any database schemas have been modified by an uncommitted transaction
  113896. ** they are reset. And that the required b-tree mutex is held to make
  113897. ** the pager rollback and schema reset an atomic operation. */
  113898. sqlite3RollbackAll(db, SQLITE_OK);
  113899. /* Free any outstanding Savepoint structures. */
  113900. sqlite3CloseSavepoints(db);
  113901. /* Close all database connections */
  113902. for(j=0; j<db->nDb; j++){
  113903. struct Db *pDb = &db->aDb[j];
  113904. if( pDb->pBt ){
  113905. sqlite3BtreeClose(pDb->pBt);
  113906. pDb->pBt = 0;
  113907. if( j!=1 ){
  113908. pDb->pSchema = 0;
  113909. }
  113910. }
  113911. }
  113912. /* Clear the TEMP schema separately and last */
  113913. if( db->aDb[1].pSchema ){
  113914. sqlite3SchemaClear(db->aDb[1].pSchema);
  113915. }
  113916. sqlite3VtabUnlockList(db);
  113917. /* Free up the array of auxiliary databases */
  113918. sqlite3CollapseDatabaseArray(db);
  113919. assert( db->nDb<=2 );
  113920. assert( db->aDb==db->aDbStatic );
  113921. /* Tell the code in notify.c that the connection no longer holds any
  113922. ** locks and does not require any further unlock-notify callbacks.
  113923. */
  113924. sqlite3ConnectionClosed(db);
  113925. for(j=0; j<ArraySize(db->aFunc.a); j++){
  113926. FuncDef *pNext, *pHash, *p;
  113927. for(p=db->aFunc.a[j]; p; p=pHash){
  113928. pHash = p->pHash;
  113929. while( p ){
  113930. functionDestroy(db, p);
  113931. pNext = p->pNext;
  113932. sqlite3DbFree(db, p);
  113933. p = pNext;
  113934. }
  113935. }
  113936. }
  113937. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  113938. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  113939. /* Invoke any destructors registered for collation sequence user data. */
  113940. for(j=0; j<3; j++){
  113941. if( pColl[j].xDel ){
  113942. pColl[j].xDel(pColl[j].pUser);
  113943. }
  113944. }
  113945. sqlite3DbFree(db, pColl);
  113946. }
  113947. sqlite3HashClear(&db->aCollSeq);
  113948. #ifndef SQLITE_OMIT_VIRTUALTABLE
  113949. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  113950. Module *pMod = (Module *)sqliteHashData(i);
  113951. if( pMod->xDestroy ){
  113952. pMod->xDestroy(pMod->pAux);
  113953. }
  113954. sqlite3DbFree(db, pMod);
  113955. }
  113956. sqlite3HashClear(&db->aModule);
  113957. #endif
  113958. sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
  113959. if( db->pErr ){
  113960. sqlite3ValueFree(db->pErr);
  113961. }
  113962. sqlite3CloseExtensions(db);
  113963. db->magic = SQLITE_MAGIC_ERROR;
  113964. /* The temp-database schema is allocated differently from the other schema
  113965. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  113966. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  113967. ** the same sqliteMalloc() as the one that allocates the database
  113968. ** structure?
  113969. */
  113970. sqlite3DbFree(db, db->aDb[1].pSchema);
  113971. sqlite3_mutex_leave(db->mutex);
  113972. db->magic = SQLITE_MAGIC_CLOSED;
  113973. sqlite3_mutex_free(db->mutex);
  113974. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  113975. if( db->lookaside.bMalloced ){
  113976. sqlite3_free(db->lookaside.pStart);
  113977. }
  113978. sqlite3_free(db);
  113979. }
  113980. /*
  113981. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  113982. ** any open cursors are invalidated ("tripped" - as in "tripping a circuit
  113983. ** breaker") and made to return tripCode if there are any further
  113984. ** attempts to use that cursor.
  113985. */
  113986. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  113987. int i;
  113988. int inTrans = 0;
  113989. assert( sqlite3_mutex_held(db->mutex) );
  113990. sqlite3BeginBenignMalloc();
  113991. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  113992. ** This is important in case the transaction being rolled back has
  113993. ** modified the database schema. If the b-tree mutexes are not taken
  113994. ** here, then another shared-cache connection might sneak in between
  113995. ** the database rollback and schema reset, which can cause false
  113996. ** corruption reports in some cases. */
  113997. sqlite3BtreeEnterAll(db);
  113998. for(i=0; i<db->nDb; i++){
  113999. Btree *p = db->aDb[i].pBt;
  114000. if( p ){
  114001. if( sqlite3BtreeIsInTrans(p) ){
  114002. inTrans = 1;
  114003. }
  114004. sqlite3BtreeRollback(p, tripCode);
  114005. }
  114006. }
  114007. sqlite3VtabRollback(db);
  114008. sqlite3EndBenignMalloc();
  114009. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  114010. sqlite3ExpirePreparedStatements(db);
  114011. sqlite3ResetAllSchemasOfConnection(db);
  114012. }
  114013. sqlite3BtreeLeaveAll(db);
  114014. /* Any deferred constraint violations have now been resolved. */
  114015. db->nDeferredCons = 0;
  114016. db->nDeferredImmCons = 0;
  114017. db->flags &= ~SQLITE_DeferFKs;
  114018. /* If one has been configured, invoke the rollback-hook callback */
  114019. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  114020. db->xRollbackCallback(db->pRollbackArg);
  114021. }
  114022. }
  114023. /*
  114024. ** Return a static string containing the name corresponding to the error code
  114025. ** specified in the argument.
  114026. */
  114027. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) || \
  114028. defined(SQLITE_DEBUG_OS_TRACE)
  114029. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  114030. const char *zName = 0;
  114031. int i, origRc = rc;
  114032. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  114033. switch( rc ){
  114034. case SQLITE_OK: zName = "SQLITE_OK"; break;
  114035. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  114036. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  114037. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  114038. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  114039. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  114040. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  114041. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  114042. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  114043. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  114044. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  114045. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  114046. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  114047. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  114048. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  114049. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  114050. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  114051. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  114052. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  114053. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  114054. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  114055. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  114056. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  114057. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  114058. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  114059. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  114060. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  114061. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  114062. case SQLITE_IOERR_BLOCKED: zName = "SQLITE_IOERR_BLOCKED"; break;
  114063. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  114064. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  114065. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  114066. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  114067. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  114068. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  114069. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  114070. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  114071. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  114072. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  114073. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  114074. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  114075. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  114076. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  114077. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  114078. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  114079. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  114080. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  114081. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  114082. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  114083. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  114084. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  114085. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  114086. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  114087. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  114088. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  114089. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  114090. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  114091. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  114092. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  114093. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  114094. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  114095. case SQLITE_CONSTRAINT_FOREIGNKEY:
  114096. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  114097. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  114098. case SQLITE_CONSTRAINT_PRIMARYKEY:
  114099. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  114100. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  114101. case SQLITE_CONSTRAINT_COMMITHOOK:
  114102. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  114103. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  114104. case SQLITE_CONSTRAINT_FUNCTION:
  114105. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  114106. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  114107. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  114108. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  114109. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  114110. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  114111. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  114112. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  114113. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  114114. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  114115. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  114116. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  114117. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  114118. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  114119. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  114120. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  114121. }
  114122. }
  114123. if( zName==0 ){
  114124. static char zBuf[50];
  114125. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  114126. zName = zBuf;
  114127. }
  114128. return zName;
  114129. }
  114130. #endif
  114131. /*
  114132. ** Return a static string that describes the kind of error specified in the
  114133. ** argument.
  114134. */
  114135. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  114136. static const char* const aMsg[] = {
  114137. /* SQLITE_OK */ "not an error",
  114138. /* SQLITE_ERROR */ "SQL logic error or missing database",
  114139. /* SQLITE_INTERNAL */ 0,
  114140. /* SQLITE_PERM */ "access permission denied",
  114141. /* SQLITE_ABORT */ "callback requested query abort",
  114142. /* SQLITE_BUSY */ "database is locked",
  114143. /* SQLITE_LOCKED */ "database table is locked",
  114144. /* SQLITE_NOMEM */ "out of memory",
  114145. /* SQLITE_READONLY */ "attempt to write a readonly database",
  114146. /* SQLITE_INTERRUPT */ "interrupted",
  114147. /* SQLITE_IOERR */ "disk I/O error",
  114148. /* SQLITE_CORRUPT */ "database disk image is malformed",
  114149. /* SQLITE_NOTFOUND */ "unknown operation",
  114150. /* SQLITE_FULL */ "database or disk is full",
  114151. /* SQLITE_CANTOPEN */ "unable to open database file",
  114152. /* SQLITE_PROTOCOL */ "locking protocol",
  114153. /* SQLITE_EMPTY */ "table contains no data",
  114154. /* SQLITE_SCHEMA */ "database schema has changed",
  114155. /* SQLITE_TOOBIG */ "string or blob too big",
  114156. /* SQLITE_CONSTRAINT */ "constraint failed",
  114157. /* SQLITE_MISMATCH */ "datatype mismatch",
  114158. /* SQLITE_MISUSE */ "library routine called out of sequence",
  114159. /* SQLITE_NOLFS */ "large file support is disabled",
  114160. /* SQLITE_AUTH */ "authorization denied",
  114161. /* SQLITE_FORMAT */ "auxiliary database format error",
  114162. /* SQLITE_RANGE */ "bind or column index out of range",
  114163. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  114164. };
  114165. const char *zErr = "unknown error";
  114166. switch( rc ){
  114167. case SQLITE_ABORT_ROLLBACK: {
  114168. zErr = "abort due to ROLLBACK";
  114169. break;
  114170. }
  114171. default: {
  114172. rc &= 0xff;
  114173. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  114174. zErr = aMsg[rc];
  114175. }
  114176. break;
  114177. }
  114178. }
  114179. return zErr;
  114180. }
  114181. /*
  114182. ** This routine implements a busy callback that sleeps and tries
  114183. ** again until a timeout value is reached. The timeout value is
  114184. ** an integer number of milliseconds passed in as the first
  114185. ** argument.
  114186. */
  114187. static int sqliteDefaultBusyCallback(
  114188. void *ptr, /* Database connection */
  114189. int count /* Number of times table has been busy */
  114190. ){
  114191. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  114192. static const u8 delays[] =
  114193. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  114194. static const u8 totals[] =
  114195. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  114196. # define NDELAY ArraySize(delays)
  114197. sqlite3 *db = (sqlite3 *)ptr;
  114198. int timeout = db->busyTimeout;
  114199. int delay, prior;
  114200. assert( count>=0 );
  114201. if( count < NDELAY ){
  114202. delay = delays[count];
  114203. prior = totals[count];
  114204. }else{
  114205. delay = delays[NDELAY-1];
  114206. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  114207. }
  114208. if( prior + delay > timeout ){
  114209. delay = timeout - prior;
  114210. if( delay<=0 ) return 0;
  114211. }
  114212. sqlite3OsSleep(db->pVfs, delay*1000);
  114213. return 1;
  114214. #else
  114215. sqlite3 *db = (sqlite3 *)ptr;
  114216. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  114217. if( (count+1)*1000 > timeout ){
  114218. return 0;
  114219. }
  114220. sqlite3OsSleep(db->pVfs, 1000000);
  114221. return 1;
  114222. #endif
  114223. }
  114224. /*
  114225. ** Invoke the given busy handler.
  114226. **
  114227. ** This routine is called when an operation failed with a lock.
  114228. ** If this routine returns non-zero, the lock is retried. If it
  114229. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  114230. */
  114231. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  114232. int rc;
  114233. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  114234. rc = p->xFunc(p->pArg, p->nBusy);
  114235. if( rc==0 ){
  114236. p->nBusy = -1;
  114237. }else{
  114238. p->nBusy++;
  114239. }
  114240. return rc;
  114241. }
  114242. /*
  114243. ** This routine sets the busy callback for an Sqlite database to the
  114244. ** given callback function with the given argument.
  114245. */
  114246. SQLITE_API int sqlite3_busy_handler(
  114247. sqlite3 *db,
  114248. int (*xBusy)(void*,int),
  114249. void *pArg
  114250. ){
  114251. sqlite3_mutex_enter(db->mutex);
  114252. db->busyHandler.xFunc = xBusy;
  114253. db->busyHandler.pArg = pArg;
  114254. db->busyHandler.nBusy = 0;
  114255. db->busyTimeout = 0;
  114256. sqlite3_mutex_leave(db->mutex);
  114257. return SQLITE_OK;
  114258. }
  114259. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  114260. /*
  114261. ** This routine sets the progress callback for an Sqlite database to the
  114262. ** given callback function with the given argument. The progress callback will
  114263. ** be invoked every nOps opcodes.
  114264. */
  114265. SQLITE_API void sqlite3_progress_handler(
  114266. sqlite3 *db,
  114267. int nOps,
  114268. int (*xProgress)(void*),
  114269. void *pArg
  114270. ){
  114271. sqlite3_mutex_enter(db->mutex);
  114272. if( nOps>0 ){
  114273. db->xProgress = xProgress;
  114274. db->nProgressOps = (unsigned)nOps;
  114275. db->pProgressArg = pArg;
  114276. }else{
  114277. db->xProgress = 0;
  114278. db->nProgressOps = 0;
  114279. db->pProgressArg = 0;
  114280. }
  114281. sqlite3_mutex_leave(db->mutex);
  114282. }
  114283. #endif
  114284. /*
  114285. ** This routine installs a default busy handler that waits for the
  114286. ** specified number of milliseconds before returning 0.
  114287. */
  114288. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  114289. if( ms>0 ){
  114290. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  114291. db->busyTimeout = ms;
  114292. }else{
  114293. sqlite3_busy_handler(db, 0, 0);
  114294. }
  114295. return SQLITE_OK;
  114296. }
  114297. /*
  114298. ** Cause any pending operation to stop at its earliest opportunity.
  114299. */
  114300. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  114301. db->u1.isInterrupted = 1;
  114302. }
  114303. /*
  114304. ** This function is exactly the same as sqlite3_create_function(), except
  114305. ** that it is designed to be called by internal code. The difference is
  114306. ** that if a malloc() fails in sqlite3_create_function(), an error code
  114307. ** is returned and the mallocFailed flag cleared.
  114308. */
  114309. SQLITE_PRIVATE int sqlite3CreateFunc(
  114310. sqlite3 *db,
  114311. const char *zFunctionName,
  114312. int nArg,
  114313. int enc,
  114314. void *pUserData,
  114315. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114316. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114317. void (*xFinal)(sqlite3_context*),
  114318. FuncDestructor *pDestructor
  114319. ){
  114320. FuncDef *p;
  114321. int nName;
  114322. assert( sqlite3_mutex_held(db->mutex) );
  114323. if( zFunctionName==0 ||
  114324. (xFunc && (xFinal || xStep)) ||
  114325. (!xFunc && (xFinal && !xStep)) ||
  114326. (!xFunc && (!xFinal && xStep)) ||
  114327. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  114328. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  114329. return SQLITE_MISUSE_BKPT;
  114330. }
  114331. #ifndef SQLITE_OMIT_UTF16
  114332. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  114333. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  114334. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  114335. **
  114336. ** If SQLITE_ANY is specified, add three versions of the function
  114337. ** to the hash table.
  114338. */
  114339. if( enc==SQLITE_UTF16 ){
  114340. enc = SQLITE_UTF16NATIVE;
  114341. }else if( enc==SQLITE_ANY ){
  114342. int rc;
  114343. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
  114344. pUserData, xFunc, xStep, xFinal, pDestructor);
  114345. if( rc==SQLITE_OK ){
  114346. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
  114347. pUserData, xFunc, xStep, xFinal, pDestructor);
  114348. }
  114349. if( rc!=SQLITE_OK ){
  114350. return rc;
  114351. }
  114352. enc = SQLITE_UTF16BE;
  114353. }
  114354. #else
  114355. enc = SQLITE_UTF8;
  114356. #endif
  114357. /* Check if an existing function is being overridden or deleted. If so,
  114358. ** and there are active VMs, then return SQLITE_BUSY. If a function
  114359. ** is being overridden/deleted but there are no active VMs, allow the
  114360. ** operation to continue but invalidate all precompiled statements.
  114361. */
  114362. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  114363. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  114364. if( db->nVdbeActive ){
  114365. sqlite3Error(db, SQLITE_BUSY,
  114366. "unable to delete/modify user-function due to active statements");
  114367. assert( !db->mallocFailed );
  114368. return SQLITE_BUSY;
  114369. }else{
  114370. sqlite3ExpirePreparedStatements(db);
  114371. }
  114372. }
  114373. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  114374. assert(p || db->mallocFailed);
  114375. if( !p ){
  114376. return SQLITE_NOMEM;
  114377. }
  114378. /* If an older version of the function with a configured destructor is
  114379. ** being replaced invoke the destructor function here. */
  114380. functionDestroy(db, p);
  114381. if( pDestructor ){
  114382. pDestructor->nRef++;
  114383. }
  114384. p->pDestructor = pDestructor;
  114385. p->funcFlags &= SQLITE_FUNC_ENCMASK;
  114386. p->xFunc = xFunc;
  114387. p->xStep = xStep;
  114388. p->xFinalize = xFinal;
  114389. p->pUserData = pUserData;
  114390. p->nArg = (u16)nArg;
  114391. return SQLITE_OK;
  114392. }
  114393. /*
  114394. ** Create new user functions.
  114395. */
  114396. SQLITE_API int sqlite3_create_function(
  114397. sqlite3 *db,
  114398. const char *zFunc,
  114399. int nArg,
  114400. int enc,
  114401. void *p,
  114402. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114403. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114404. void (*xFinal)(sqlite3_context*)
  114405. ){
  114406. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  114407. xFinal, 0);
  114408. }
  114409. SQLITE_API int sqlite3_create_function_v2(
  114410. sqlite3 *db,
  114411. const char *zFunc,
  114412. int nArg,
  114413. int enc,
  114414. void *p,
  114415. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  114416. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  114417. void (*xFinal)(sqlite3_context*),
  114418. void (*xDestroy)(void *)
  114419. ){
  114420. int rc = SQLITE_ERROR;
  114421. FuncDestructor *pArg = 0;
  114422. sqlite3_mutex_enter(db->mutex);
  114423. if( xDestroy ){
  114424. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  114425. if( !pArg ){
  114426. xDestroy(p);
  114427. goto out;
  114428. }
  114429. pArg->xDestroy = xDestroy;
  114430. pArg->pUserData = p;
  114431. }
  114432. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  114433. if( pArg && pArg->nRef==0 ){
  114434. assert( rc!=SQLITE_OK );
  114435. xDestroy(p);
  114436. sqlite3DbFree(db, pArg);
  114437. }
  114438. out:
  114439. rc = sqlite3ApiExit(db, rc);
  114440. sqlite3_mutex_leave(db->mutex);
  114441. return rc;
  114442. }
  114443. #ifndef SQLITE_OMIT_UTF16
  114444. SQLITE_API int sqlite3_create_function16(
  114445. sqlite3 *db,
  114446. const void *zFunctionName,
  114447. int nArg,
  114448. int eTextRep,
  114449. void *p,
  114450. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  114451. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  114452. void (*xFinal)(sqlite3_context*)
  114453. ){
  114454. int rc;
  114455. char *zFunc8;
  114456. sqlite3_mutex_enter(db->mutex);
  114457. assert( !db->mallocFailed );
  114458. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  114459. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  114460. sqlite3DbFree(db, zFunc8);
  114461. rc = sqlite3ApiExit(db, rc);
  114462. sqlite3_mutex_leave(db->mutex);
  114463. return rc;
  114464. }
  114465. #endif
  114466. /*
  114467. ** Declare that a function has been overloaded by a virtual table.
  114468. **
  114469. ** If the function already exists as a regular global function, then
  114470. ** this routine is a no-op. If the function does not exist, then create
  114471. ** a new one that always throws a run-time error.
  114472. **
  114473. ** When virtual tables intend to provide an overloaded function, they
  114474. ** should call this routine to make sure the global function exists.
  114475. ** A global function must exist in order for name resolution to work
  114476. ** properly.
  114477. */
  114478. SQLITE_API int sqlite3_overload_function(
  114479. sqlite3 *db,
  114480. const char *zName,
  114481. int nArg
  114482. ){
  114483. int nName = sqlite3Strlen30(zName);
  114484. int rc = SQLITE_OK;
  114485. sqlite3_mutex_enter(db->mutex);
  114486. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  114487. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  114488. 0, sqlite3InvalidFunction, 0, 0, 0);
  114489. }
  114490. rc = sqlite3ApiExit(db, rc);
  114491. sqlite3_mutex_leave(db->mutex);
  114492. return rc;
  114493. }
  114494. #ifndef SQLITE_OMIT_TRACE
  114495. /*
  114496. ** Register a trace function. The pArg from the previously registered trace
  114497. ** is returned.
  114498. **
  114499. ** A NULL trace function means that no tracing is executes. A non-NULL
  114500. ** trace is a pointer to a function that is invoked at the start of each
  114501. ** SQL statement.
  114502. */
  114503. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  114504. void *pOld;
  114505. sqlite3_mutex_enter(db->mutex);
  114506. pOld = db->pTraceArg;
  114507. db->xTrace = xTrace;
  114508. db->pTraceArg = pArg;
  114509. sqlite3_mutex_leave(db->mutex);
  114510. return pOld;
  114511. }
  114512. /*
  114513. ** Register a profile function. The pArg from the previously registered
  114514. ** profile function is returned.
  114515. **
  114516. ** A NULL profile function means that no profiling is executes. A non-NULL
  114517. ** profile is a pointer to a function that is invoked at the conclusion of
  114518. ** each SQL statement that is run.
  114519. */
  114520. SQLITE_API void *sqlite3_profile(
  114521. sqlite3 *db,
  114522. void (*xProfile)(void*,const char*,sqlite_uint64),
  114523. void *pArg
  114524. ){
  114525. void *pOld;
  114526. sqlite3_mutex_enter(db->mutex);
  114527. pOld = db->pProfileArg;
  114528. db->xProfile = xProfile;
  114529. db->pProfileArg = pArg;
  114530. sqlite3_mutex_leave(db->mutex);
  114531. return pOld;
  114532. }
  114533. #endif /* SQLITE_OMIT_TRACE */
  114534. /*
  114535. ** Register a function to be invoked when a transaction commits.
  114536. ** If the invoked function returns non-zero, then the commit becomes a
  114537. ** rollback.
  114538. */
  114539. SQLITE_API void *sqlite3_commit_hook(
  114540. sqlite3 *db, /* Attach the hook to this database */
  114541. int (*xCallback)(void*), /* Function to invoke on each commit */
  114542. void *pArg /* Argument to the function */
  114543. ){
  114544. void *pOld;
  114545. sqlite3_mutex_enter(db->mutex);
  114546. pOld = db->pCommitArg;
  114547. db->xCommitCallback = xCallback;
  114548. db->pCommitArg = pArg;
  114549. sqlite3_mutex_leave(db->mutex);
  114550. return pOld;
  114551. }
  114552. /*
  114553. ** Register a callback to be invoked each time a row is updated,
  114554. ** inserted or deleted using this database connection.
  114555. */
  114556. SQLITE_API void *sqlite3_update_hook(
  114557. sqlite3 *db, /* Attach the hook to this database */
  114558. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  114559. void *pArg /* Argument to the function */
  114560. ){
  114561. void *pRet;
  114562. sqlite3_mutex_enter(db->mutex);
  114563. pRet = db->pUpdateArg;
  114564. db->xUpdateCallback = xCallback;
  114565. db->pUpdateArg = pArg;
  114566. sqlite3_mutex_leave(db->mutex);
  114567. return pRet;
  114568. }
  114569. /*
  114570. ** Register a callback to be invoked each time a transaction is rolled
  114571. ** back by this database connection.
  114572. */
  114573. SQLITE_API void *sqlite3_rollback_hook(
  114574. sqlite3 *db, /* Attach the hook to this database */
  114575. void (*xCallback)(void*), /* Callback function */
  114576. void *pArg /* Argument to the function */
  114577. ){
  114578. void *pRet;
  114579. sqlite3_mutex_enter(db->mutex);
  114580. pRet = db->pRollbackArg;
  114581. db->xRollbackCallback = xCallback;
  114582. db->pRollbackArg = pArg;
  114583. sqlite3_mutex_leave(db->mutex);
  114584. return pRet;
  114585. }
  114586. #ifndef SQLITE_OMIT_WAL
  114587. /*
  114588. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  114589. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  114590. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  114591. ** wal_autocheckpoint()).
  114592. */
  114593. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  114594. void *pClientData, /* Argument */
  114595. sqlite3 *db, /* Connection */
  114596. const char *zDb, /* Database */
  114597. int nFrame /* Size of WAL */
  114598. ){
  114599. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  114600. sqlite3BeginBenignMalloc();
  114601. sqlite3_wal_checkpoint(db, zDb);
  114602. sqlite3EndBenignMalloc();
  114603. }
  114604. return SQLITE_OK;
  114605. }
  114606. #endif /* SQLITE_OMIT_WAL */
  114607. /*
  114608. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  114609. ** a database after committing a transaction if there are nFrame or
  114610. ** more frames in the log file. Passing zero or a negative value as the
  114611. ** nFrame parameter disables automatic checkpoints entirely.
  114612. **
  114613. ** The callback registered by this function replaces any existing callback
  114614. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  114615. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  114616. ** configured by this function.
  114617. */
  114618. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  114619. #ifdef SQLITE_OMIT_WAL
  114620. UNUSED_PARAMETER(db);
  114621. UNUSED_PARAMETER(nFrame);
  114622. #else
  114623. if( nFrame>0 ){
  114624. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  114625. }else{
  114626. sqlite3_wal_hook(db, 0, 0);
  114627. }
  114628. #endif
  114629. return SQLITE_OK;
  114630. }
  114631. /*
  114632. ** Register a callback to be invoked each time a transaction is written
  114633. ** into the write-ahead-log by this database connection.
  114634. */
  114635. SQLITE_API void *sqlite3_wal_hook(
  114636. sqlite3 *db, /* Attach the hook to this db handle */
  114637. int(*xCallback)(void *, sqlite3*, const char*, int),
  114638. void *pArg /* First argument passed to xCallback() */
  114639. ){
  114640. #ifndef SQLITE_OMIT_WAL
  114641. void *pRet;
  114642. sqlite3_mutex_enter(db->mutex);
  114643. pRet = db->pWalArg;
  114644. db->xWalCallback = xCallback;
  114645. db->pWalArg = pArg;
  114646. sqlite3_mutex_leave(db->mutex);
  114647. return pRet;
  114648. #else
  114649. return 0;
  114650. #endif
  114651. }
  114652. /*
  114653. ** Checkpoint database zDb.
  114654. */
  114655. SQLITE_API int sqlite3_wal_checkpoint_v2(
  114656. sqlite3 *db, /* Database handle */
  114657. const char *zDb, /* Name of attached database (or NULL) */
  114658. int eMode, /* SQLITE_CHECKPOINT_* value */
  114659. int *pnLog, /* OUT: Size of WAL log in frames */
  114660. int *pnCkpt /* OUT: Total number of frames checkpointed */
  114661. ){
  114662. #ifdef SQLITE_OMIT_WAL
  114663. return SQLITE_OK;
  114664. #else
  114665. int rc; /* Return code */
  114666. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  114667. /* Initialize the output variables to -1 in case an error occurs. */
  114668. if( pnLog ) *pnLog = -1;
  114669. if( pnCkpt ) *pnCkpt = -1;
  114670. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  114671. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  114672. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  114673. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  114674. return SQLITE_MISUSE;
  114675. }
  114676. sqlite3_mutex_enter(db->mutex);
  114677. if( zDb && zDb[0] ){
  114678. iDb = sqlite3FindDbName(db, zDb);
  114679. }
  114680. if( iDb<0 ){
  114681. rc = SQLITE_ERROR;
  114682. sqlite3Error(db, SQLITE_ERROR, "unknown database: %s", zDb);
  114683. }else{
  114684. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  114685. sqlite3Error(db, rc, 0);
  114686. }
  114687. rc = sqlite3ApiExit(db, rc);
  114688. sqlite3_mutex_leave(db->mutex);
  114689. return rc;
  114690. #endif
  114691. }
  114692. /*
  114693. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  114694. ** to contains a zero-length string, all attached databases are
  114695. ** checkpointed.
  114696. */
  114697. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  114698. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  114699. }
  114700. #ifndef SQLITE_OMIT_WAL
  114701. /*
  114702. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  114703. ** not currently open in WAL mode.
  114704. **
  114705. ** If a transaction is open on the database being checkpointed, this
  114706. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  114707. ** an error occurs while running the checkpoint, an SQLite error code is
  114708. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  114709. **
  114710. ** The mutex on database handle db should be held by the caller. The mutex
  114711. ** associated with the specific b-tree being checkpointed is taken by
  114712. ** this function while the checkpoint is running.
  114713. **
  114714. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  114715. ** checkpointed. If an error is encountered it is returned immediately -
  114716. ** no attempt is made to checkpoint any remaining databases.
  114717. **
  114718. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  114719. */
  114720. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  114721. int rc = SQLITE_OK; /* Return code */
  114722. int i; /* Used to iterate through attached dbs */
  114723. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  114724. assert( sqlite3_mutex_held(db->mutex) );
  114725. assert( !pnLog || *pnLog==-1 );
  114726. assert( !pnCkpt || *pnCkpt==-1 );
  114727. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  114728. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  114729. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  114730. pnLog = 0;
  114731. pnCkpt = 0;
  114732. if( rc==SQLITE_BUSY ){
  114733. bBusy = 1;
  114734. rc = SQLITE_OK;
  114735. }
  114736. }
  114737. }
  114738. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  114739. }
  114740. #endif /* SQLITE_OMIT_WAL */
  114741. /*
  114742. ** This function returns true if main-memory should be used instead of
  114743. ** a temporary file for transient pager files and statement journals.
  114744. ** The value returned depends on the value of db->temp_store (runtime
  114745. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  114746. ** following table describes the relationship between these two values
  114747. ** and this functions return value.
  114748. **
  114749. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  114750. ** ----------------- -------------- ------------------------------
  114751. ** 0 any file (return 0)
  114752. ** 1 1 file (return 0)
  114753. ** 1 2 memory (return 1)
  114754. ** 1 0 file (return 0)
  114755. ** 2 1 file (return 0)
  114756. ** 2 2 memory (return 1)
  114757. ** 2 0 memory (return 1)
  114758. ** 3 any memory (return 1)
  114759. */
  114760. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  114761. #if SQLITE_TEMP_STORE==1
  114762. return ( db->temp_store==2 );
  114763. #endif
  114764. #if SQLITE_TEMP_STORE==2
  114765. return ( db->temp_store!=1 );
  114766. #endif
  114767. #if SQLITE_TEMP_STORE==3
  114768. return 1;
  114769. #endif
  114770. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  114771. return 0;
  114772. #endif
  114773. }
  114774. /*
  114775. ** Return UTF-8 encoded English language explanation of the most recent
  114776. ** error.
  114777. */
  114778. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  114779. const char *z;
  114780. if( !db ){
  114781. return sqlite3ErrStr(SQLITE_NOMEM);
  114782. }
  114783. if( !sqlite3SafetyCheckSickOrOk(db) ){
  114784. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  114785. }
  114786. sqlite3_mutex_enter(db->mutex);
  114787. if( db->mallocFailed ){
  114788. z = sqlite3ErrStr(SQLITE_NOMEM);
  114789. }else{
  114790. z = (char*)sqlite3_value_text(db->pErr);
  114791. assert( !db->mallocFailed );
  114792. if( z==0 ){
  114793. z = sqlite3ErrStr(db->errCode);
  114794. }
  114795. }
  114796. sqlite3_mutex_leave(db->mutex);
  114797. return z;
  114798. }
  114799. #ifndef SQLITE_OMIT_UTF16
  114800. /*
  114801. ** Return UTF-16 encoded English language explanation of the most recent
  114802. ** error.
  114803. */
  114804. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  114805. static const u16 outOfMem[] = {
  114806. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  114807. };
  114808. static const u16 misuse[] = {
  114809. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  114810. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  114811. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  114812. 'o', 'u', 't', ' ',
  114813. 'o', 'f', ' ',
  114814. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  114815. };
  114816. const void *z;
  114817. if( !db ){
  114818. return (void *)outOfMem;
  114819. }
  114820. if( !sqlite3SafetyCheckSickOrOk(db) ){
  114821. return (void *)misuse;
  114822. }
  114823. sqlite3_mutex_enter(db->mutex);
  114824. if( db->mallocFailed ){
  114825. z = (void *)outOfMem;
  114826. }else{
  114827. z = sqlite3_value_text16(db->pErr);
  114828. if( z==0 ){
  114829. sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
  114830. SQLITE_UTF8, SQLITE_STATIC);
  114831. z = sqlite3_value_text16(db->pErr);
  114832. }
  114833. /* A malloc() may have failed within the call to sqlite3_value_text16()
  114834. ** above. If this is the case, then the db->mallocFailed flag needs to
  114835. ** be cleared before returning. Do this directly, instead of via
  114836. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  114837. */
  114838. db->mallocFailed = 0;
  114839. }
  114840. sqlite3_mutex_leave(db->mutex);
  114841. return z;
  114842. }
  114843. #endif /* SQLITE_OMIT_UTF16 */
  114844. /*
  114845. ** Return the most recent error code generated by an SQLite routine. If NULL is
  114846. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  114847. */
  114848. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  114849. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  114850. return SQLITE_MISUSE_BKPT;
  114851. }
  114852. if( !db || db->mallocFailed ){
  114853. return SQLITE_NOMEM;
  114854. }
  114855. return db->errCode & db->errMask;
  114856. }
  114857. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  114858. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  114859. return SQLITE_MISUSE_BKPT;
  114860. }
  114861. if( !db || db->mallocFailed ){
  114862. return SQLITE_NOMEM;
  114863. }
  114864. return db->errCode;
  114865. }
  114866. /*
  114867. ** Return a string that describes the kind of error specified in the
  114868. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  114869. ** function.
  114870. */
  114871. SQLITE_API const char *sqlite3_errstr(int rc){
  114872. return sqlite3ErrStr(rc);
  114873. }
  114874. /*
  114875. ** Create a new collating function for database "db". The name is zName
  114876. ** and the encoding is enc.
  114877. */
  114878. static int createCollation(
  114879. sqlite3* db,
  114880. const char *zName,
  114881. u8 enc,
  114882. void* pCtx,
  114883. int(*xCompare)(void*,int,const void*,int,const void*),
  114884. void(*xDel)(void*)
  114885. ){
  114886. CollSeq *pColl;
  114887. int enc2;
  114888. int nName = sqlite3Strlen30(zName);
  114889. assert( sqlite3_mutex_held(db->mutex) );
  114890. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  114891. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  114892. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  114893. */
  114894. enc2 = enc;
  114895. testcase( enc2==SQLITE_UTF16 );
  114896. testcase( enc2==SQLITE_UTF16_ALIGNED );
  114897. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  114898. enc2 = SQLITE_UTF16NATIVE;
  114899. }
  114900. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  114901. return SQLITE_MISUSE_BKPT;
  114902. }
  114903. /* Check if this call is removing or replacing an existing collation
  114904. ** sequence. If so, and there are active VMs, return busy. If there
  114905. ** are no active VMs, invalidate any pre-compiled statements.
  114906. */
  114907. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  114908. if( pColl && pColl->xCmp ){
  114909. if( db->nVdbeActive ){
  114910. sqlite3Error(db, SQLITE_BUSY,
  114911. "unable to delete/modify collation sequence due to active statements");
  114912. return SQLITE_BUSY;
  114913. }
  114914. sqlite3ExpirePreparedStatements(db);
  114915. /* If collation sequence pColl was created directly by a call to
  114916. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  114917. ** then any copies made by synthCollSeq() need to be invalidated.
  114918. ** Also, collation destructor - CollSeq.xDel() - function may need
  114919. ** to be called.
  114920. */
  114921. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  114922. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
  114923. int j;
  114924. for(j=0; j<3; j++){
  114925. CollSeq *p = &aColl[j];
  114926. if( p->enc==pColl->enc ){
  114927. if( p->xDel ){
  114928. p->xDel(p->pUser);
  114929. }
  114930. p->xCmp = 0;
  114931. }
  114932. }
  114933. }
  114934. }
  114935. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  114936. if( pColl==0 ) return SQLITE_NOMEM;
  114937. pColl->xCmp = xCompare;
  114938. pColl->pUser = pCtx;
  114939. pColl->xDel = xDel;
  114940. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  114941. sqlite3Error(db, SQLITE_OK, 0);
  114942. return SQLITE_OK;
  114943. }
  114944. /*
  114945. ** This array defines hard upper bounds on limit values. The
  114946. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  114947. ** #defines in sqlite3.h.
  114948. */
  114949. static const int aHardLimit[] = {
  114950. SQLITE_MAX_LENGTH,
  114951. SQLITE_MAX_SQL_LENGTH,
  114952. SQLITE_MAX_COLUMN,
  114953. SQLITE_MAX_EXPR_DEPTH,
  114954. SQLITE_MAX_COMPOUND_SELECT,
  114955. SQLITE_MAX_VDBE_OP,
  114956. SQLITE_MAX_FUNCTION_ARG,
  114957. SQLITE_MAX_ATTACHED,
  114958. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  114959. SQLITE_MAX_VARIABLE_NUMBER,
  114960. SQLITE_MAX_TRIGGER_DEPTH,
  114961. };
  114962. /*
  114963. ** Make sure the hard limits are set to reasonable values
  114964. */
  114965. #if SQLITE_MAX_LENGTH<100
  114966. # error SQLITE_MAX_LENGTH must be at least 100
  114967. #endif
  114968. #if SQLITE_MAX_SQL_LENGTH<100
  114969. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  114970. #endif
  114971. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  114972. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  114973. #endif
  114974. #if SQLITE_MAX_COMPOUND_SELECT<2
  114975. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  114976. #endif
  114977. #if SQLITE_MAX_VDBE_OP<40
  114978. # error SQLITE_MAX_VDBE_OP must be at least 40
  114979. #endif
  114980. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  114981. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  114982. #endif
  114983. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>62
  114984. # error SQLITE_MAX_ATTACHED must be between 0 and 62
  114985. #endif
  114986. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  114987. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  114988. #endif
  114989. #if SQLITE_MAX_COLUMN>32767
  114990. # error SQLITE_MAX_COLUMN must not exceed 32767
  114991. #endif
  114992. #if SQLITE_MAX_TRIGGER_DEPTH<1
  114993. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  114994. #endif
  114995. /*
  114996. ** Change the value of a limit. Report the old value.
  114997. ** If an invalid limit index is supplied, report -1.
  114998. ** Make no changes but still report the old value if the
  114999. ** new limit is negative.
  115000. **
  115001. ** A new lower limit does not shrink existing constructs.
  115002. ** It merely prevents new constructs that exceed the limit
  115003. ** from forming.
  115004. */
  115005. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  115006. int oldLimit;
  115007. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  115008. ** there is a hard upper bound set at compile-time by a C preprocessor
  115009. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  115010. ** "_MAX_".)
  115011. */
  115012. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  115013. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  115014. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  115015. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  115016. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  115017. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  115018. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  115019. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  115020. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  115021. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  115022. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  115023. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  115024. assert( SQLITE_LIMIT_TRIGGER_DEPTH==(SQLITE_N_LIMIT-1) );
  115025. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  115026. return -1;
  115027. }
  115028. oldLimit = db->aLimit[limitId];
  115029. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  115030. if( newLimit>aHardLimit[limitId] ){
  115031. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  115032. }
  115033. db->aLimit[limitId] = newLimit;
  115034. }
  115035. return oldLimit; /* IMP: R-53341-35419 */
  115036. }
  115037. /*
  115038. ** This function is used to parse both URIs and non-URI filenames passed by the
  115039. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  115040. ** URIs specified as part of ATTACH statements.
  115041. **
  115042. ** The first argument to this function is the name of the VFS to use (or
  115043. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  115044. ** query parameter. The second argument contains the URI (or non-URI filename)
  115045. ** itself. When this function is called the *pFlags variable should contain
  115046. ** the default flags to open the database handle with. The value stored in
  115047. ** *pFlags may be updated before returning if the URI filename contains
  115048. ** "cache=xxx" or "mode=xxx" query parameters.
  115049. **
  115050. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  115051. ** the VFS that should be used to open the database file. *pzFile is set to
  115052. ** point to a buffer containing the name of the file to open. It is the
  115053. ** responsibility of the caller to eventually call sqlite3_free() to release
  115054. ** this buffer.
  115055. **
  115056. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  115057. ** may be set to point to a buffer containing an English language error
  115058. ** message. It is the responsibility of the caller to eventually release
  115059. ** this buffer by calling sqlite3_free().
  115060. */
  115061. SQLITE_PRIVATE int sqlite3ParseUri(
  115062. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  115063. const char *zUri, /* Nul-terminated URI to parse */
  115064. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  115065. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  115066. char **pzFile, /* OUT: Filename component of URI */
  115067. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  115068. ){
  115069. int rc = SQLITE_OK;
  115070. unsigned int flags = *pFlags;
  115071. const char *zVfs = zDefaultVfs;
  115072. char *zFile;
  115073. char c;
  115074. int nUri = sqlite3Strlen30(zUri);
  115075. assert( *pzErrMsg==0 );
  115076. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  115077. && nUri>=5 && memcmp(zUri, "file:", 5)==0
  115078. ){
  115079. char *zOpt;
  115080. int eState; /* Parser state when parsing URI */
  115081. int iIn; /* Input character index */
  115082. int iOut = 0; /* Output character index */
  115083. int nByte = nUri+2; /* Bytes of space to allocate */
  115084. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  115085. ** method that there may be extra parameters following the file-name. */
  115086. flags |= SQLITE_OPEN_URI;
  115087. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  115088. zFile = sqlite3_malloc(nByte);
  115089. if( !zFile ) return SQLITE_NOMEM;
  115090. iIn = 5;
  115091. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  115092. /* Discard the scheme and authority segments of the URI. */
  115093. if( zUri[5]=='/' && zUri[6]=='/' ){
  115094. iIn = 7;
  115095. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  115096. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  115097. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  115098. iIn-7, &zUri[7]);
  115099. rc = SQLITE_ERROR;
  115100. goto parse_uri_out;
  115101. }
  115102. }
  115103. #endif
  115104. /* Copy the filename and any query parameters into the zFile buffer.
  115105. ** Decode %HH escape codes along the way.
  115106. **
  115107. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  115108. ** on the parsing context. As follows:
  115109. **
  115110. ** 0: Parsing file-name.
  115111. ** 1: Parsing name section of a name=value query parameter.
  115112. ** 2: Parsing value section of a name=value query parameter.
  115113. */
  115114. eState = 0;
  115115. while( (c = zUri[iIn])!=0 && c!='#' ){
  115116. iIn++;
  115117. if( c=='%'
  115118. && sqlite3Isxdigit(zUri[iIn])
  115119. && sqlite3Isxdigit(zUri[iIn+1])
  115120. ){
  115121. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  115122. octet += sqlite3HexToInt(zUri[iIn++]);
  115123. assert( octet>=0 && octet<256 );
  115124. if( octet==0 ){
  115125. /* This branch is taken when "%00" appears within the URI. In this
  115126. ** case we ignore all text in the remainder of the path, name or
  115127. ** value currently being parsed. So ignore the current character
  115128. ** and skip to the next "?", "=" or "&", as appropriate. */
  115129. while( (c = zUri[iIn])!=0 && c!='#'
  115130. && (eState!=0 || c!='?')
  115131. && (eState!=1 || (c!='=' && c!='&'))
  115132. && (eState!=2 || c!='&')
  115133. ){
  115134. iIn++;
  115135. }
  115136. continue;
  115137. }
  115138. c = octet;
  115139. }else if( eState==1 && (c=='&' || c=='=') ){
  115140. if( zFile[iOut-1]==0 ){
  115141. /* An empty option name. Ignore this option altogether. */
  115142. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  115143. continue;
  115144. }
  115145. if( c=='&' ){
  115146. zFile[iOut++] = '\0';
  115147. }else{
  115148. eState = 2;
  115149. }
  115150. c = 0;
  115151. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  115152. c = 0;
  115153. eState = 1;
  115154. }
  115155. zFile[iOut++] = c;
  115156. }
  115157. if( eState==1 ) zFile[iOut++] = '\0';
  115158. zFile[iOut++] = '\0';
  115159. zFile[iOut++] = '\0';
  115160. /* Check if there were any options specified that should be interpreted
  115161. ** here. Options that are interpreted here include "vfs" and those that
  115162. ** correspond to flags that may be passed to the sqlite3_open_v2()
  115163. ** method. */
  115164. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  115165. while( zOpt[0] ){
  115166. int nOpt = sqlite3Strlen30(zOpt);
  115167. char *zVal = &zOpt[nOpt+1];
  115168. int nVal = sqlite3Strlen30(zVal);
  115169. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  115170. zVfs = zVal;
  115171. }else{
  115172. struct OpenMode {
  115173. const char *z;
  115174. int mode;
  115175. } *aMode = 0;
  115176. char *zModeType = 0;
  115177. int mask = 0;
  115178. int limit = 0;
  115179. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  115180. static struct OpenMode aCacheMode[] = {
  115181. { "shared", SQLITE_OPEN_SHAREDCACHE },
  115182. { "private", SQLITE_OPEN_PRIVATECACHE },
  115183. { 0, 0 }
  115184. };
  115185. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  115186. aMode = aCacheMode;
  115187. limit = mask;
  115188. zModeType = "cache";
  115189. }
  115190. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  115191. static struct OpenMode aOpenMode[] = {
  115192. { "ro", SQLITE_OPEN_READONLY },
  115193. { "rw", SQLITE_OPEN_READWRITE },
  115194. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  115195. { "memory", SQLITE_OPEN_MEMORY },
  115196. { 0, 0 }
  115197. };
  115198. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  115199. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  115200. aMode = aOpenMode;
  115201. limit = mask & flags;
  115202. zModeType = "access";
  115203. }
  115204. if( aMode ){
  115205. int i;
  115206. int mode = 0;
  115207. for(i=0; aMode[i].z; i++){
  115208. const char *z = aMode[i].z;
  115209. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  115210. mode = aMode[i].mode;
  115211. break;
  115212. }
  115213. }
  115214. if( mode==0 ){
  115215. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  115216. rc = SQLITE_ERROR;
  115217. goto parse_uri_out;
  115218. }
  115219. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  115220. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  115221. zModeType, zVal);
  115222. rc = SQLITE_PERM;
  115223. goto parse_uri_out;
  115224. }
  115225. flags = (flags & ~mask) | mode;
  115226. }
  115227. }
  115228. zOpt = &zVal[nVal+1];
  115229. }
  115230. }else{
  115231. zFile = sqlite3_malloc(nUri+2);
  115232. if( !zFile ) return SQLITE_NOMEM;
  115233. memcpy(zFile, zUri, nUri);
  115234. zFile[nUri] = '\0';
  115235. zFile[nUri+1] = '\0';
  115236. flags &= ~SQLITE_OPEN_URI;
  115237. }
  115238. *ppVfs = sqlite3_vfs_find(zVfs);
  115239. if( *ppVfs==0 ){
  115240. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  115241. rc = SQLITE_ERROR;
  115242. }
  115243. parse_uri_out:
  115244. if( rc!=SQLITE_OK ){
  115245. sqlite3_free(zFile);
  115246. zFile = 0;
  115247. }
  115248. *pFlags = flags;
  115249. *pzFile = zFile;
  115250. return rc;
  115251. }
  115252. /*
  115253. ** This routine does the work of opening a database on behalf of
  115254. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  115255. ** is UTF-8 encoded.
  115256. */
  115257. static int openDatabase(
  115258. const char *zFilename, /* Database filename UTF-8 encoded */
  115259. sqlite3 **ppDb, /* OUT: Returned database handle */
  115260. unsigned int flags, /* Operational flags */
  115261. const char *zVfs /* Name of the VFS to use */
  115262. ){
  115263. sqlite3 *db; /* Store allocated handle here */
  115264. int rc; /* Return code */
  115265. int isThreadsafe; /* True for threadsafe connections */
  115266. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  115267. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  115268. *ppDb = 0;
  115269. #ifndef SQLITE_OMIT_AUTOINIT
  115270. rc = sqlite3_initialize();
  115271. if( rc ) return rc;
  115272. #endif
  115273. /* Only allow sensible combinations of bits in the flags argument.
  115274. ** Throw an error if any non-sense combination is used. If we
  115275. ** do not block illegal combinations here, it could trigger
  115276. ** assert() statements in deeper layers. Sensible combinations
  115277. ** are:
  115278. **
  115279. ** 1: SQLITE_OPEN_READONLY
  115280. ** 2: SQLITE_OPEN_READWRITE
  115281. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  115282. */
  115283. assert( SQLITE_OPEN_READONLY == 0x01 );
  115284. assert( SQLITE_OPEN_READWRITE == 0x02 );
  115285. assert( SQLITE_OPEN_CREATE == 0x04 );
  115286. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  115287. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  115288. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  115289. if( ((1<<(flags&7)) & 0x46)==0 ) return SQLITE_MISUSE_BKPT;
  115290. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  115291. isThreadsafe = 0;
  115292. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  115293. isThreadsafe = 0;
  115294. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  115295. isThreadsafe = 1;
  115296. }else{
  115297. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  115298. }
  115299. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  115300. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  115301. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  115302. flags |= SQLITE_OPEN_SHAREDCACHE;
  115303. }
  115304. /* Remove harmful bits from the flags parameter
  115305. **
  115306. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  115307. ** dealt with in the previous code block. Besides these, the only
  115308. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  115309. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  115310. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  115311. ** off all other flags.
  115312. */
  115313. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  115314. SQLITE_OPEN_EXCLUSIVE |
  115315. SQLITE_OPEN_MAIN_DB |
  115316. SQLITE_OPEN_TEMP_DB |
  115317. SQLITE_OPEN_TRANSIENT_DB |
  115318. SQLITE_OPEN_MAIN_JOURNAL |
  115319. SQLITE_OPEN_TEMP_JOURNAL |
  115320. SQLITE_OPEN_SUBJOURNAL |
  115321. SQLITE_OPEN_MASTER_JOURNAL |
  115322. SQLITE_OPEN_NOMUTEX |
  115323. SQLITE_OPEN_FULLMUTEX |
  115324. SQLITE_OPEN_WAL
  115325. );
  115326. /* Allocate the sqlite data structure */
  115327. db = sqlite3MallocZero( sizeof(sqlite3) );
  115328. if( db==0 ) goto opendb_out;
  115329. if( isThreadsafe ){
  115330. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  115331. if( db->mutex==0 ){
  115332. sqlite3_free(db);
  115333. db = 0;
  115334. goto opendb_out;
  115335. }
  115336. }
  115337. sqlite3_mutex_enter(db->mutex);
  115338. db->errMask = 0xff;
  115339. db->nDb = 2;
  115340. db->magic = SQLITE_MAGIC_BUSY;
  115341. db->aDb = db->aDbStatic;
  115342. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  115343. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  115344. db->autoCommit = 1;
  115345. db->nextAutovac = -1;
  115346. db->szMmap = sqlite3GlobalConfig.szMmap;
  115347. db->nextPagesize = 0;
  115348. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  115349. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  115350. | SQLITE_AutoIndex
  115351. #endif
  115352. #if SQLITE_DEFAULT_FILE_FORMAT<4
  115353. | SQLITE_LegacyFileFmt
  115354. #endif
  115355. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  115356. | SQLITE_LoadExtension
  115357. #endif
  115358. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  115359. | SQLITE_RecTriggers
  115360. #endif
  115361. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  115362. | SQLITE_ForeignKeys
  115363. #endif
  115364. ;
  115365. sqlite3HashInit(&db->aCollSeq);
  115366. #ifndef SQLITE_OMIT_VIRTUALTABLE
  115367. sqlite3HashInit(&db->aModule);
  115368. #endif
  115369. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  115370. ** and UTF-16, so add a version for each to avoid any unnecessary
  115371. ** conversions. The only error that can occur here is a malloc() failure.
  115372. */
  115373. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  115374. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  115375. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  115376. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  115377. if( db->mallocFailed ){
  115378. goto opendb_out;
  115379. }
  115380. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  115381. assert( db->pDfltColl!=0 );
  115382. /* Also add a UTF-8 case-insensitive collation sequence. */
  115383. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  115384. /* Parse the filename/URI argument. */
  115385. db->openFlags = flags;
  115386. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  115387. if( rc!=SQLITE_OK ){
  115388. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  115389. sqlite3Error(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  115390. sqlite3_free(zErrMsg);
  115391. goto opendb_out;
  115392. }
  115393. /* Open the backend database driver */
  115394. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  115395. flags | SQLITE_OPEN_MAIN_DB);
  115396. if( rc!=SQLITE_OK ){
  115397. if( rc==SQLITE_IOERR_NOMEM ){
  115398. rc = SQLITE_NOMEM;
  115399. }
  115400. sqlite3Error(db, rc, 0);
  115401. goto opendb_out;
  115402. }
  115403. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  115404. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  115405. /* The default safety_level for the main database is 'full'; for the temp
  115406. ** database it is 'NONE'. This matches the pager layer defaults.
  115407. */
  115408. db->aDb[0].zName = "main";
  115409. db->aDb[0].safety_level = 3;
  115410. db->aDb[1].zName = "temp";
  115411. db->aDb[1].safety_level = 1;
  115412. db->magic = SQLITE_MAGIC_OPEN;
  115413. if( db->mallocFailed ){
  115414. goto opendb_out;
  115415. }
  115416. /* Register all built-in functions, but do not attempt to read the
  115417. ** database schema yet. This is delayed until the first time the database
  115418. ** is accessed.
  115419. */
  115420. sqlite3Error(db, SQLITE_OK, 0);
  115421. sqlite3RegisterBuiltinFunctions(db);
  115422. /* Load automatic extensions - extensions that have been registered
  115423. ** using the sqlite3_automatic_extension() API.
  115424. */
  115425. rc = sqlite3_errcode(db);
  115426. if( rc==SQLITE_OK ){
  115427. sqlite3AutoLoadExtensions(db);
  115428. rc = sqlite3_errcode(db);
  115429. if( rc!=SQLITE_OK ){
  115430. goto opendb_out;
  115431. }
  115432. }
  115433. #ifdef SQLITE_ENABLE_FTS1
  115434. if( !db->mallocFailed ){
  115435. extern int sqlite3Fts1Init(sqlite3*);
  115436. rc = sqlite3Fts1Init(db);
  115437. }
  115438. #endif
  115439. #ifdef SQLITE_ENABLE_FTS2
  115440. if( !db->mallocFailed && rc==SQLITE_OK ){
  115441. extern int sqlite3Fts2Init(sqlite3*);
  115442. rc = sqlite3Fts2Init(db);
  115443. }
  115444. #endif
  115445. #ifdef SQLITE_ENABLE_FTS3
  115446. if( !db->mallocFailed && rc==SQLITE_OK ){
  115447. rc = sqlite3Fts3Init(db);
  115448. }
  115449. #endif
  115450. #ifdef SQLITE_ENABLE_ICU
  115451. if( !db->mallocFailed && rc==SQLITE_OK ){
  115452. rc = sqlite3IcuInit(db);
  115453. }
  115454. #endif
  115455. #ifdef SQLITE_ENABLE_RTREE
  115456. if( !db->mallocFailed && rc==SQLITE_OK){
  115457. rc = sqlite3RtreeInit(db);
  115458. }
  115459. #endif
  115460. sqlite3Error(db, rc, 0);
  115461. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  115462. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  115463. ** mode. Doing nothing at all also makes NORMAL the default.
  115464. */
  115465. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  115466. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  115467. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  115468. SQLITE_DEFAULT_LOCKING_MODE);
  115469. #endif
  115470. /* Enable the lookaside-malloc subsystem */
  115471. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  115472. sqlite3GlobalConfig.nLookaside);
  115473. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  115474. opendb_out:
  115475. sqlite3_free(zOpen);
  115476. if( db ){
  115477. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  115478. sqlite3_mutex_leave(db->mutex);
  115479. }
  115480. rc = sqlite3_errcode(db);
  115481. assert( db!=0 || rc==SQLITE_NOMEM );
  115482. if( rc==SQLITE_NOMEM ){
  115483. sqlite3_close(db);
  115484. db = 0;
  115485. }else if( rc!=SQLITE_OK ){
  115486. db->magic = SQLITE_MAGIC_SICK;
  115487. }
  115488. *ppDb = db;
  115489. #ifdef SQLITE_ENABLE_SQLLOG
  115490. if( sqlite3GlobalConfig.xSqllog ){
  115491. /* Opening a db handle. Fourth parameter is passed 0. */
  115492. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  115493. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  115494. }
  115495. #endif
  115496. return sqlite3ApiExit(0, rc);
  115497. }
  115498. /*
  115499. ** Open a new database handle.
  115500. */
  115501. SQLITE_API int sqlite3_open(
  115502. const char *zFilename,
  115503. sqlite3 **ppDb
  115504. ){
  115505. return openDatabase(zFilename, ppDb,
  115506. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  115507. }
  115508. SQLITE_API int sqlite3_open_v2(
  115509. const char *filename, /* Database filename (UTF-8) */
  115510. sqlite3 **ppDb, /* OUT: SQLite db handle */
  115511. int flags, /* Flags */
  115512. const char *zVfs /* Name of VFS module to use */
  115513. ){
  115514. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  115515. }
  115516. #ifndef SQLITE_OMIT_UTF16
  115517. /*
  115518. ** Open a new database handle.
  115519. */
  115520. SQLITE_API int sqlite3_open16(
  115521. const void *zFilename,
  115522. sqlite3 **ppDb
  115523. ){
  115524. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  115525. sqlite3_value *pVal;
  115526. int rc;
  115527. assert( zFilename );
  115528. assert( ppDb );
  115529. *ppDb = 0;
  115530. #ifndef SQLITE_OMIT_AUTOINIT
  115531. rc = sqlite3_initialize();
  115532. if( rc ) return rc;
  115533. #endif
  115534. pVal = sqlite3ValueNew(0);
  115535. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  115536. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  115537. if( zFilename8 ){
  115538. rc = openDatabase(zFilename8, ppDb,
  115539. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  115540. assert( *ppDb || rc==SQLITE_NOMEM );
  115541. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  115542. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  115543. }
  115544. }else{
  115545. rc = SQLITE_NOMEM;
  115546. }
  115547. sqlite3ValueFree(pVal);
  115548. return sqlite3ApiExit(0, rc);
  115549. }
  115550. #endif /* SQLITE_OMIT_UTF16 */
  115551. /*
  115552. ** Register a new collation sequence with the database handle db.
  115553. */
  115554. SQLITE_API int sqlite3_create_collation(
  115555. sqlite3* db,
  115556. const char *zName,
  115557. int enc,
  115558. void* pCtx,
  115559. int(*xCompare)(void*,int,const void*,int,const void*)
  115560. ){
  115561. int rc;
  115562. sqlite3_mutex_enter(db->mutex);
  115563. assert( !db->mallocFailed );
  115564. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  115565. rc = sqlite3ApiExit(db, rc);
  115566. sqlite3_mutex_leave(db->mutex);
  115567. return rc;
  115568. }
  115569. /*
  115570. ** Register a new collation sequence with the database handle db.
  115571. */
  115572. SQLITE_API int sqlite3_create_collation_v2(
  115573. sqlite3* db,
  115574. const char *zName,
  115575. int enc,
  115576. void* pCtx,
  115577. int(*xCompare)(void*,int,const void*,int,const void*),
  115578. void(*xDel)(void*)
  115579. ){
  115580. int rc;
  115581. sqlite3_mutex_enter(db->mutex);
  115582. assert( !db->mallocFailed );
  115583. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  115584. rc = sqlite3ApiExit(db, rc);
  115585. sqlite3_mutex_leave(db->mutex);
  115586. return rc;
  115587. }
  115588. #ifndef SQLITE_OMIT_UTF16
  115589. /*
  115590. ** Register a new collation sequence with the database handle db.
  115591. */
  115592. SQLITE_API int sqlite3_create_collation16(
  115593. sqlite3* db,
  115594. const void *zName,
  115595. int enc,
  115596. void* pCtx,
  115597. int(*xCompare)(void*,int,const void*,int,const void*)
  115598. ){
  115599. int rc = SQLITE_OK;
  115600. char *zName8;
  115601. sqlite3_mutex_enter(db->mutex);
  115602. assert( !db->mallocFailed );
  115603. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  115604. if( zName8 ){
  115605. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  115606. sqlite3DbFree(db, zName8);
  115607. }
  115608. rc = sqlite3ApiExit(db, rc);
  115609. sqlite3_mutex_leave(db->mutex);
  115610. return rc;
  115611. }
  115612. #endif /* SQLITE_OMIT_UTF16 */
  115613. /*
  115614. ** Register a collation sequence factory callback with the database handle
  115615. ** db. Replace any previously installed collation sequence factory.
  115616. */
  115617. SQLITE_API int sqlite3_collation_needed(
  115618. sqlite3 *db,
  115619. void *pCollNeededArg,
  115620. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  115621. ){
  115622. sqlite3_mutex_enter(db->mutex);
  115623. db->xCollNeeded = xCollNeeded;
  115624. db->xCollNeeded16 = 0;
  115625. db->pCollNeededArg = pCollNeededArg;
  115626. sqlite3_mutex_leave(db->mutex);
  115627. return SQLITE_OK;
  115628. }
  115629. #ifndef SQLITE_OMIT_UTF16
  115630. /*
  115631. ** Register a collation sequence factory callback with the database handle
  115632. ** db. Replace any previously installed collation sequence factory.
  115633. */
  115634. SQLITE_API int sqlite3_collation_needed16(
  115635. sqlite3 *db,
  115636. void *pCollNeededArg,
  115637. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  115638. ){
  115639. sqlite3_mutex_enter(db->mutex);
  115640. db->xCollNeeded = 0;
  115641. db->xCollNeeded16 = xCollNeeded16;
  115642. db->pCollNeededArg = pCollNeededArg;
  115643. sqlite3_mutex_leave(db->mutex);
  115644. return SQLITE_OK;
  115645. }
  115646. #endif /* SQLITE_OMIT_UTF16 */
  115647. #ifndef SQLITE_OMIT_DEPRECATED
  115648. /*
  115649. ** This function is now an anachronism. It used to be used to recover from a
  115650. ** malloc() failure, but SQLite now does this automatically.
  115651. */
  115652. SQLITE_API int sqlite3_global_recover(void){
  115653. return SQLITE_OK;
  115654. }
  115655. #endif
  115656. /*
  115657. ** Test to see whether or not the database connection is in autocommit
  115658. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  115659. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  115660. ** by the next COMMIT or ROLLBACK.
  115661. */
  115662. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  115663. return db->autoCommit;
  115664. }
  115665. /*
  115666. ** The following routines are subtitutes for constants SQLITE_CORRUPT,
  115667. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  115668. ** constants. They server two purposes:
  115669. **
  115670. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  115671. ** to detect when version error conditions occurs.
  115672. **
  115673. ** 2. Invoke sqlite3_log() to provide the source code location where
  115674. ** a low-level error is first detected.
  115675. */
  115676. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  115677. testcase( sqlite3GlobalConfig.xLog!=0 );
  115678. sqlite3_log(SQLITE_CORRUPT,
  115679. "database corruption at line %d of [%.10s]",
  115680. lineno, 20+sqlite3_sourceid());
  115681. return SQLITE_CORRUPT;
  115682. }
  115683. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  115684. testcase( sqlite3GlobalConfig.xLog!=0 );
  115685. sqlite3_log(SQLITE_MISUSE,
  115686. "misuse at line %d of [%.10s]",
  115687. lineno, 20+sqlite3_sourceid());
  115688. return SQLITE_MISUSE;
  115689. }
  115690. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  115691. testcase( sqlite3GlobalConfig.xLog!=0 );
  115692. sqlite3_log(SQLITE_CANTOPEN,
  115693. "cannot open file at line %d of [%.10s]",
  115694. lineno, 20+sqlite3_sourceid());
  115695. return SQLITE_CANTOPEN;
  115696. }
  115697. #ifndef SQLITE_OMIT_DEPRECATED
  115698. /*
  115699. ** This is a convenience routine that makes sure that all thread-specific
  115700. ** data for this thread has been deallocated.
  115701. **
  115702. ** SQLite no longer uses thread-specific data so this routine is now a
  115703. ** no-op. It is retained for historical compatibility.
  115704. */
  115705. SQLITE_API void sqlite3_thread_cleanup(void){
  115706. }
  115707. #endif
  115708. /*
  115709. ** Return meta information about a specific column of a database table.
  115710. ** See comment in sqlite3.h (sqlite.h.in) for details.
  115711. */
  115712. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  115713. SQLITE_API int sqlite3_table_column_metadata(
  115714. sqlite3 *db, /* Connection handle */
  115715. const char *zDbName, /* Database name or NULL */
  115716. const char *zTableName, /* Table name */
  115717. const char *zColumnName, /* Column name */
  115718. char const **pzDataType, /* OUTPUT: Declared data type */
  115719. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  115720. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  115721. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  115722. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  115723. ){
  115724. int rc;
  115725. char *zErrMsg = 0;
  115726. Table *pTab = 0;
  115727. Column *pCol = 0;
  115728. int iCol;
  115729. char const *zDataType = 0;
  115730. char const *zCollSeq = 0;
  115731. int notnull = 0;
  115732. int primarykey = 0;
  115733. int autoinc = 0;
  115734. /* Ensure the database schema has been loaded */
  115735. sqlite3_mutex_enter(db->mutex);
  115736. sqlite3BtreeEnterAll(db);
  115737. rc = sqlite3Init(db, &zErrMsg);
  115738. if( SQLITE_OK!=rc ){
  115739. goto error_out;
  115740. }
  115741. /* Locate the table in question */
  115742. pTab = sqlite3FindTable(db, zTableName, zDbName);
  115743. if( !pTab || pTab->pSelect ){
  115744. pTab = 0;
  115745. goto error_out;
  115746. }
  115747. /* Find the column for which info is requested */
  115748. if( sqlite3IsRowid(zColumnName) ){
  115749. iCol = pTab->iPKey;
  115750. if( iCol>=0 ){
  115751. pCol = &pTab->aCol[iCol];
  115752. }
  115753. }else{
  115754. for(iCol=0; iCol<pTab->nCol; iCol++){
  115755. pCol = &pTab->aCol[iCol];
  115756. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  115757. break;
  115758. }
  115759. }
  115760. if( iCol==pTab->nCol ){
  115761. pTab = 0;
  115762. goto error_out;
  115763. }
  115764. }
  115765. /* The following block stores the meta information that will be returned
  115766. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  115767. ** and autoinc. At this point there are two possibilities:
  115768. **
  115769. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  115770. ** and there is no explicitly declared IPK column.
  115771. **
  115772. ** 2. The table is not a view and the column name identified an
  115773. ** explicitly declared column. Copy meta information from *pCol.
  115774. */
  115775. if( pCol ){
  115776. zDataType = pCol->zType;
  115777. zCollSeq = pCol->zColl;
  115778. notnull = pCol->notNull!=0;
  115779. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  115780. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  115781. }else{
  115782. zDataType = "INTEGER";
  115783. primarykey = 1;
  115784. }
  115785. if( !zCollSeq ){
  115786. zCollSeq = "BINARY";
  115787. }
  115788. error_out:
  115789. sqlite3BtreeLeaveAll(db);
  115790. /* Whether the function call succeeded or failed, set the output parameters
  115791. ** to whatever their local counterparts contain. If an error did occur,
  115792. ** this has the effect of zeroing all output parameters.
  115793. */
  115794. if( pzDataType ) *pzDataType = zDataType;
  115795. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  115796. if( pNotNull ) *pNotNull = notnull;
  115797. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  115798. if( pAutoinc ) *pAutoinc = autoinc;
  115799. if( SQLITE_OK==rc && !pTab ){
  115800. sqlite3DbFree(db, zErrMsg);
  115801. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  115802. zColumnName);
  115803. rc = SQLITE_ERROR;
  115804. }
  115805. sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
  115806. sqlite3DbFree(db, zErrMsg);
  115807. rc = sqlite3ApiExit(db, rc);
  115808. sqlite3_mutex_leave(db->mutex);
  115809. return rc;
  115810. }
  115811. #endif
  115812. /*
  115813. ** Sleep for a little while. Return the amount of time slept.
  115814. */
  115815. SQLITE_API int sqlite3_sleep(int ms){
  115816. sqlite3_vfs *pVfs;
  115817. int rc;
  115818. pVfs = sqlite3_vfs_find(0);
  115819. if( pVfs==0 ) return 0;
  115820. /* This function works in milliseconds, but the underlying OsSleep()
  115821. ** API uses microseconds. Hence the 1000's.
  115822. */
  115823. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  115824. return rc;
  115825. }
  115826. /*
  115827. ** Enable or disable the extended result codes.
  115828. */
  115829. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  115830. sqlite3_mutex_enter(db->mutex);
  115831. db->errMask = onoff ? 0xffffffff : 0xff;
  115832. sqlite3_mutex_leave(db->mutex);
  115833. return SQLITE_OK;
  115834. }
  115835. /*
  115836. ** Invoke the xFileControl method on a particular database.
  115837. */
  115838. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  115839. int rc = SQLITE_ERROR;
  115840. Btree *pBtree;
  115841. sqlite3_mutex_enter(db->mutex);
  115842. pBtree = sqlite3DbNameToBtree(db, zDbName);
  115843. if( pBtree ){
  115844. Pager *pPager;
  115845. sqlite3_file *fd;
  115846. sqlite3BtreeEnter(pBtree);
  115847. pPager = sqlite3BtreePager(pBtree);
  115848. assert( pPager!=0 );
  115849. fd = sqlite3PagerFile(pPager);
  115850. assert( fd!=0 );
  115851. if( op==SQLITE_FCNTL_FILE_POINTER ){
  115852. *(sqlite3_file**)pArg = fd;
  115853. rc = SQLITE_OK;
  115854. }else if( fd->pMethods ){
  115855. rc = sqlite3OsFileControl(fd, op, pArg);
  115856. }else{
  115857. rc = SQLITE_NOTFOUND;
  115858. }
  115859. sqlite3BtreeLeave(pBtree);
  115860. }
  115861. sqlite3_mutex_leave(db->mutex);
  115862. return rc;
  115863. }
  115864. /*
  115865. ** Interface to the testing logic.
  115866. */
  115867. SQLITE_API int sqlite3_test_control(int op, ...){
  115868. int rc = 0;
  115869. #ifndef SQLITE_OMIT_BUILTIN_TEST
  115870. va_list ap;
  115871. va_start(ap, op);
  115872. switch( op ){
  115873. /*
  115874. ** Save the current state of the PRNG.
  115875. */
  115876. case SQLITE_TESTCTRL_PRNG_SAVE: {
  115877. sqlite3PrngSaveState();
  115878. break;
  115879. }
  115880. /*
  115881. ** Restore the state of the PRNG to the last state saved using
  115882. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  115883. ** this verb acts like PRNG_RESET.
  115884. */
  115885. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  115886. sqlite3PrngRestoreState();
  115887. break;
  115888. }
  115889. /*
  115890. ** Reset the PRNG back to its uninitialized state. The next call
  115891. ** to sqlite3_randomness() will reseed the PRNG using a single call
  115892. ** to the xRandomness method of the default VFS.
  115893. */
  115894. case SQLITE_TESTCTRL_PRNG_RESET: {
  115895. sqlite3PrngResetState();
  115896. break;
  115897. }
  115898. /*
  115899. ** sqlite3_test_control(BITVEC_TEST, size, program)
  115900. **
  115901. ** Run a test against a Bitvec object of size. The program argument
  115902. ** is an array of integers that defines the test. Return -1 on a
  115903. ** memory allocation error, 0 on success, or non-zero for an error.
  115904. ** See the sqlite3BitvecBuiltinTest() for additional information.
  115905. */
  115906. case SQLITE_TESTCTRL_BITVEC_TEST: {
  115907. int sz = va_arg(ap, int);
  115908. int *aProg = va_arg(ap, int*);
  115909. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  115910. break;
  115911. }
  115912. /*
  115913. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  115914. **
  115915. ** Register hooks to call to indicate which malloc() failures
  115916. ** are benign.
  115917. */
  115918. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  115919. typedef void (*void_function)(void);
  115920. void_function xBenignBegin;
  115921. void_function xBenignEnd;
  115922. xBenignBegin = va_arg(ap, void_function);
  115923. xBenignEnd = va_arg(ap, void_function);
  115924. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  115925. break;
  115926. }
  115927. /*
  115928. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  115929. **
  115930. ** Set the PENDING byte to the value in the argument, if X>0.
  115931. ** Make no changes if X==0. Return the value of the pending byte
  115932. ** as it existing before this routine was called.
  115933. **
  115934. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  115935. ** an incompatible database file format. Changing the PENDING byte
  115936. ** while any database connection is open results in undefined and
  115937. ** dileterious behavior.
  115938. */
  115939. case SQLITE_TESTCTRL_PENDING_BYTE: {
  115940. rc = PENDING_BYTE;
  115941. #ifndef SQLITE_OMIT_WSD
  115942. {
  115943. unsigned int newVal = va_arg(ap, unsigned int);
  115944. if( newVal ) sqlite3PendingByte = newVal;
  115945. }
  115946. #endif
  115947. break;
  115948. }
  115949. /*
  115950. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  115951. **
  115952. ** This action provides a run-time test to see whether or not
  115953. ** assert() was enabled at compile-time. If X is true and assert()
  115954. ** is enabled, then the return value is true. If X is true and
  115955. ** assert() is disabled, then the return value is zero. If X is
  115956. ** false and assert() is enabled, then the assertion fires and the
  115957. ** process aborts. If X is false and assert() is disabled, then the
  115958. ** return value is zero.
  115959. */
  115960. case SQLITE_TESTCTRL_ASSERT: {
  115961. volatile int x = 0;
  115962. assert( (x = va_arg(ap,int))!=0 );
  115963. rc = x;
  115964. break;
  115965. }
  115966. /*
  115967. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  115968. **
  115969. ** This action provides a run-time test to see how the ALWAYS and
  115970. ** NEVER macros were defined at compile-time.
  115971. **
  115972. ** The return value is ALWAYS(X).
  115973. **
  115974. ** The recommended test is X==2. If the return value is 2, that means
  115975. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  115976. ** default setting. If the return value is 1, then ALWAYS() is either
  115977. ** hard-coded to true or else it asserts if its argument is false.
  115978. ** The first behavior (hard-coded to true) is the case if
  115979. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  115980. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  115981. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  115982. **
  115983. ** The run-time test procedure might look something like this:
  115984. **
  115985. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  115986. ** // ALWAYS() and NEVER() are no-op pass-through macros
  115987. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  115988. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  115989. ** }else{
  115990. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  115991. ** }
  115992. */
  115993. case SQLITE_TESTCTRL_ALWAYS: {
  115994. int x = va_arg(ap,int);
  115995. rc = ALWAYS(x);
  115996. break;
  115997. }
  115998. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  115999. **
  116000. ** Set the nReserve size to N for the main database on the database
  116001. ** connection db.
  116002. */
  116003. case SQLITE_TESTCTRL_RESERVE: {
  116004. sqlite3 *db = va_arg(ap, sqlite3*);
  116005. int x = va_arg(ap,int);
  116006. sqlite3_mutex_enter(db->mutex);
  116007. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  116008. sqlite3_mutex_leave(db->mutex);
  116009. break;
  116010. }
  116011. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  116012. **
  116013. ** Enable or disable various optimizations for testing purposes. The
  116014. ** argument N is a bitmask of optimizations to be disabled. For normal
  116015. ** operation N should be 0. The idea is that a test program (like the
  116016. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  116017. ** with various optimizations disabled to verify that the same answer
  116018. ** is obtained in every case.
  116019. */
  116020. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  116021. sqlite3 *db = va_arg(ap, sqlite3*);
  116022. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  116023. break;
  116024. }
  116025. #ifdef SQLITE_N_KEYWORD
  116026. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  116027. **
  116028. ** If zWord is a keyword recognized by the parser, then return the
  116029. ** number of keywords. Or if zWord is not a keyword, return 0.
  116030. **
  116031. ** This test feature is only available in the amalgamation since
  116032. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  116033. ** is built using separate source files.
  116034. */
  116035. case SQLITE_TESTCTRL_ISKEYWORD: {
  116036. const char *zWord = va_arg(ap, const char*);
  116037. int n = sqlite3Strlen30(zWord);
  116038. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  116039. break;
  116040. }
  116041. #endif
  116042. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  116043. **
  116044. ** Pass pFree into sqlite3ScratchFree().
  116045. ** If sz>0 then allocate a scratch buffer into pNew.
  116046. */
  116047. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  116048. void *pFree, **ppNew;
  116049. int sz;
  116050. sz = va_arg(ap, int);
  116051. ppNew = va_arg(ap, void**);
  116052. pFree = va_arg(ap, void*);
  116053. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  116054. sqlite3ScratchFree(pFree);
  116055. break;
  116056. }
  116057. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  116058. **
  116059. ** If parameter onoff is non-zero, configure the wrappers so that all
  116060. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  116061. ** undo this setting.
  116062. */
  116063. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  116064. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  116065. break;
  116066. }
  116067. #if defined(SQLITE_ENABLE_TREE_EXPLAIN)
  116068. /* sqlite3_test_control(SQLITE_TESTCTRL_EXPLAIN_STMT,
  116069. ** sqlite3_stmt*,const char**);
  116070. **
  116071. ** If compiled with SQLITE_ENABLE_TREE_EXPLAIN, each sqlite3_stmt holds
  116072. ** a string that describes the optimized parse tree. This test-control
  116073. ** returns a pointer to that string.
  116074. */
  116075. case SQLITE_TESTCTRL_EXPLAIN_STMT: {
  116076. sqlite3_stmt *pStmt = va_arg(ap, sqlite3_stmt*);
  116077. const char **pzRet = va_arg(ap, const char**);
  116078. *pzRet = sqlite3VdbeExplanation((Vdbe*)pStmt);
  116079. break;
  116080. }
  116081. #endif
  116082. }
  116083. va_end(ap);
  116084. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  116085. return rc;
  116086. }
  116087. /*
  116088. ** This is a utility routine, useful to VFS implementations, that checks
  116089. ** to see if a database file was a URI that contained a specific query
  116090. ** parameter, and if so obtains the value of the query parameter.
  116091. **
  116092. ** The zFilename argument is the filename pointer passed into the xOpen()
  116093. ** method of a VFS implementation. The zParam argument is the name of the
  116094. ** query parameter we seek. This routine returns the value of the zParam
  116095. ** parameter if it exists. If the parameter does not exist, this routine
  116096. ** returns a NULL pointer.
  116097. */
  116098. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  116099. if( zFilename==0 ) return 0;
  116100. zFilename += sqlite3Strlen30(zFilename) + 1;
  116101. while( zFilename[0] ){
  116102. int x = strcmp(zFilename, zParam);
  116103. zFilename += sqlite3Strlen30(zFilename) + 1;
  116104. if( x==0 ) return zFilename;
  116105. zFilename += sqlite3Strlen30(zFilename) + 1;
  116106. }
  116107. return 0;
  116108. }
  116109. /*
  116110. ** Return a boolean value for a query parameter.
  116111. */
  116112. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  116113. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  116114. bDflt = bDflt!=0;
  116115. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  116116. }
  116117. /*
  116118. ** Return a 64-bit integer value for a query parameter.
  116119. */
  116120. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  116121. const char *zFilename, /* Filename as passed to xOpen */
  116122. const char *zParam, /* URI parameter sought */
  116123. sqlite3_int64 bDflt /* return if parameter is missing */
  116124. ){
  116125. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  116126. sqlite3_int64 v;
  116127. if( z && sqlite3Atoi64(z, &v, sqlite3Strlen30(z), SQLITE_UTF8)==SQLITE_OK ){
  116128. bDflt = v;
  116129. }
  116130. return bDflt;
  116131. }
  116132. /*
  116133. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  116134. */
  116135. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  116136. int i;
  116137. for(i=0; i<db->nDb; i++){
  116138. if( db->aDb[i].pBt
  116139. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  116140. ){
  116141. return db->aDb[i].pBt;
  116142. }
  116143. }
  116144. return 0;
  116145. }
  116146. /*
  116147. ** Return the filename of the database associated with a database
  116148. ** connection.
  116149. */
  116150. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  116151. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  116152. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  116153. }
  116154. /*
  116155. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  116156. ** no such database exists.
  116157. */
  116158. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  116159. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  116160. return pBt ? sqlite3PagerIsreadonly(sqlite3BtreePager(pBt)) : -1;
  116161. }
  116162. /************** End of main.c ************************************************/
  116163. /************** Begin file notify.c ******************************************/
  116164. /*
  116165. ** 2009 March 3
  116166. **
  116167. ** The author disclaims copyright to this source code. In place of
  116168. ** a legal notice, here is a blessing:
  116169. **
  116170. ** May you do good and not evil.
  116171. ** May you find forgiveness for yourself and forgive others.
  116172. ** May you share freely, never taking more than you give.
  116173. **
  116174. *************************************************************************
  116175. **
  116176. ** This file contains the implementation of the sqlite3_unlock_notify()
  116177. ** API method and its associated functionality.
  116178. */
  116179. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  116180. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  116181. /*
  116182. ** Public interfaces:
  116183. **
  116184. ** sqlite3ConnectionBlocked()
  116185. ** sqlite3ConnectionUnlocked()
  116186. ** sqlite3ConnectionClosed()
  116187. ** sqlite3_unlock_notify()
  116188. */
  116189. #define assertMutexHeld() \
  116190. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  116191. /*
  116192. ** Head of a linked list of all sqlite3 objects created by this process
  116193. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  116194. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  116195. ** mutex is held.
  116196. */
  116197. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  116198. #ifndef NDEBUG
  116199. /*
  116200. ** This function is a complex assert() that verifies the following
  116201. ** properties of the blocked connections list:
  116202. **
  116203. ** 1) Each entry in the list has a non-NULL value for either
  116204. ** pUnlockConnection or pBlockingConnection, or both.
  116205. **
  116206. ** 2) All entries in the list that share a common value for
  116207. ** xUnlockNotify are grouped together.
  116208. **
  116209. ** 3) If the argument db is not NULL, then none of the entries in the
  116210. ** blocked connections list have pUnlockConnection or pBlockingConnection
  116211. ** set to db. This is used when closing connection db.
  116212. */
  116213. static void checkListProperties(sqlite3 *db){
  116214. sqlite3 *p;
  116215. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  116216. int seen = 0;
  116217. sqlite3 *p2;
  116218. /* Verify property (1) */
  116219. assert( p->pUnlockConnection || p->pBlockingConnection );
  116220. /* Verify property (2) */
  116221. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  116222. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  116223. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  116224. assert( db==0 || p->pUnlockConnection!=db );
  116225. assert( db==0 || p->pBlockingConnection!=db );
  116226. }
  116227. }
  116228. }
  116229. #else
  116230. # define checkListProperties(x)
  116231. #endif
  116232. /*
  116233. ** Remove connection db from the blocked connections list. If connection
  116234. ** db is not currently a part of the list, this function is a no-op.
  116235. */
  116236. static void removeFromBlockedList(sqlite3 *db){
  116237. sqlite3 **pp;
  116238. assertMutexHeld();
  116239. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  116240. if( *pp==db ){
  116241. *pp = (*pp)->pNextBlocked;
  116242. break;
  116243. }
  116244. }
  116245. }
  116246. /*
  116247. ** Add connection db to the blocked connections list. It is assumed
  116248. ** that it is not already a part of the list.
  116249. */
  116250. static void addToBlockedList(sqlite3 *db){
  116251. sqlite3 **pp;
  116252. assertMutexHeld();
  116253. for(
  116254. pp=&sqlite3BlockedList;
  116255. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  116256. pp=&(*pp)->pNextBlocked
  116257. );
  116258. db->pNextBlocked = *pp;
  116259. *pp = db;
  116260. }
  116261. /*
  116262. ** Obtain the STATIC_MASTER mutex.
  116263. */
  116264. static void enterMutex(void){
  116265. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  116266. checkListProperties(0);
  116267. }
  116268. /*
  116269. ** Release the STATIC_MASTER mutex.
  116270. */
  116271. static void leaveMutex(void){
  116272. assertMutexHeld();
  116273. checkListProperties(0);
  116274. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  116275. }
  116276. /*
  116277. ** Register an unlock-notify callback.
  116278. **
  116279. ** This is called after connection "db" has attempted some operation
  116280. ** but has received an SQLITE_LOCKED error because another connection
  116281. ** (call it pOther) in the same process was busy using the same shared
  116282. ** cache. pOther is found by looking at db->pBlockingConnection.
  116283. **
  116284. ** If there is no blocking connection, the callback is invoked immediately,
  116285. ** before this routine returns.
  116286. **
  116287. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  116288. ** a deadlock.
  116289. **
  116290. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  116291. ** its locks.
  116292. **
  116293. ** Each call to this routine overrides any prior callbacks registered
  116294. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  116295. ** cancelled.
  116296. */
  116297. SQLITE_API int sqlite3_unlock_notify(
  116298. sqlite3 *db,
  116299. void (*xNotify)(void **, int),
  116300. void *pArg
  116301. ){
  116302. int rc = SQLITE_OK;
  116303. sqlite3_mutex_enter(db->mutex);
  116304. enterMutex();
  116305. if( xNotify==0 ){
  116306. removeFromBlockedList(db);
  116307. db->pBlockingConnection = 0;
  116308. db->pUnlockConnection = 0;
  116309. db->xUnlockNotify = 0;
  116310. db->pUnlockArg = 0;
  116311. }else if( 0==db->pBlockingConnection ){
  116312. /* The blocking transaction has been concluded. Or there never was a
  116313. ** blocking transaction. In either case, invoke the notify callback
  116314. ** immediately.
  116315. */
  116316. xNotify(&pArg, 1);
  116317. }else{
  116318. sqlite3 *p;
  116319. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  116320. if( p ){
  116321. rc = SQLITE_LOCKED; /* Deadlock detected. */
  116322. }else{
  116323. db->pUnlockConnection = db->pBlockingConnection;
  116324. db->xUnlockNotify = xNotify;
  116325. db->pUnlockArg = pArg;
  116326. removeFromBlockedList(db);
  116327. addToBlockedList(db);
  116328. }
  116329. }
  116330. leaveMutex();
  116331. assert( !db->mallocFailed );
  116332. sqlite3Error(db, rc, (rc?"database is deadlocked":0));
  116333. sqlite3_mutex_leave(db->mutex);
  116334. return rc;
  116335. }
  116336. /*
  116337. ** This function is called while stepping or preparing a statement
  116338. ** associated with connection db. The operation will return SQLITE_LOCKED
  116339. ** to the user because it requires a lock that will not be available
  116340. ** until connection pBlocker concludes its current transaction.
  116341. */
  116342. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  116343. enterMutex();
  116344. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  116345. addToBlockedList(db);
  116346. }
  116347. db->pBlockingConnection = pBlocker;
  116348. leaveMutex();
  116349. }
  116350. /*
  116351. ** This function is called when
  116352. ** the transaction opened by database db has just finished. Locks held
  116353. ** by database connection db have been released.
  116354. **
  116355. ** This function loops through each entry in the blocked connections
  116356. ** list and does the following:
  116357. **
  116358. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  116359. ** set to db, then set pBlockingConnection=0.
  116360. **
  116361. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  116362. ** set to db, then invoke the configured unlock-notify callback and
  116363. ** set pUnlockConnection=0.
  116364. **
  116365. ** 3) If the two steps above mean that pBlockingConnection==0 and
  116366. ** pUnlockConnection==0, remove the entry from the blocked connections
  116367. ** list.
  116368. */
  116369. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  116370. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  116371. int nArg = 0; /* Number of entries in aArg[] */
  116372. sqlite3 **pp; /* Iterator variable */
  116373. void **aArg; /* Arguments to the unlock callback */
  116374. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  116375. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  116376. aArg = aStatic;
  116377. enterMutex(); /* Enter STATIC_MASTER mutex */
  116378. /* This loop runs once for each entry in the blocked-connections list. */
  116379. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  116380. sqlite3 *p = *pp;
  116381. /* Step 1. */
  116382. if( p->pBlockingConnection==db ){
  116383. p->pBlockingConnection = 0;
  116384. }
  116385. /* Step 2. */
  116386. if( p->pUnlockConnection==db ){
  116387. assert( p->xUnlockNotify );
  116388. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  116389. xUnlockNotify(aArg, nArg);
  116390. nArg = 0;
  116391. }
  116392. sqlite3BeginBenignMalloc();
  116393. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  116394. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  116395. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  116396. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  116397. ){
  116398. /* The aArg[] array needs to grow. */
  116399. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  116400. if( pNew ){
  116401. memcpy(pNew, aArg, nArg*sizeof(void *));
  116402. sqlite3_free(aDyn);
  116403. aDyn = aArg = pNew;
  116404. }else{
  116405. /* This occurs when the array of context pointers that need to
  116406. ** be passed to the unlock-notify callback is larger than the
  116407. ** aStatic[] array allocated on the stack and the attempt to
  116408. ** allocate a larger array from the heap has failed.
  116409. **
  116410. ** This is a difficult situation to handle. Returning an error
  116411. ** code to the caller is insufficient, as even if an error code
  116412. ** is returned the transaction on connection db will still be
  116413. ** closed and the unlock-notify callbacks on blocked connections
  116414. ** will go unissued. This might cause the application to wait
  116415. ** indefinitely for an unlock-notify callback that will never
  116416. ** arrive.
  116417. **
  116418. ** Instead, invoke the unlock-notify callback with the context
  116419. ** array already accumulated. We can then clear the array and
  116420. ** begin accumulating any further context pointers without
  116421. ** requiring any dynamic allocation. This is sub-optimal because
  116422. ** it means that instead of one callback with a large array of
  116423. ** context pointers the application will receive two or more
  116424. ** callbacks with smaller arrays of context pointers, which will
  116425. ** reduce the applications ability to prioritize multiple
  116426. ** connections. But it is the best that can be done under the
  116427. ** circumstances.
  116428. */
  116429. xUnlockNotify(aArg, nArg);
  116430. nArg = 0;
  116431. }
  116432. }
  116433. sqlite3EndBenignMalloc();
  116434. aArg[nArg++] = p->pUnlockArg;
  116435. xUnlockNotify = p->xUnlockNotify;
  116436. p->pUnlockConnection = 0;
  116437. p->xUnlockNotify = 0;
  116438. p->pUnlockArg = 0;
  116439. }
  116440. /* Step 3. */
  116441. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  116442. /* Remove connection p from the blocked connections list. */
  116443. *pp = p->pNextBlocked;
  116444. p->pNextBlocked = 0;
  116445. }else{
  116446. pp = &p->pNextBlocked;
  116447. }
  116448. }
  116449. if( nArg!=0 ){
  116450. xUnlockNotify(aArg, nArg);
  116451. }
  116452. sqlite3_free(aDyn);
  116453. leaveMutex(); /* Leave STATIC_MASTER mutex */
  116454. }
  116455. /*
  116456. ** This is called when the database connection passed as an argument is
  116457. ** being closed. The connection is removed from the blocked list.
  116458. */
  116459. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  116460. sqlite3ConnectionUnlocked(db);
  116461. enterMutex();
  116462. removeFromBlockedList(db);
  116463. checkListProperties(db);
  116464. leaveMutex();
  116465. }
  116466. #endif
  116467. /************** End of notify.c **********************************************/
  116468. /************** Begin file fts3.c ********************************************/
  116469. /*
  116470. ** 2006 Oct 10
  116471. **
  116472. ** The author disclaims copyright to this source code. In place of
  116473. ** a legal notice, here is a blessing:
  116474. **
  116475. ** May you do good and not evil.
  116476. ** May you find forgiveness for yourself and forgive others.
  116477. ** May you share freely, never taking more than you give.
  116478. **
  116479. ******************************************************************************
  116480. **
  116481. ** This is an SQLite module implementing full-text search.
  116482. */
  116483. /*
  116484. ** The code in this file is only compiled if:
  116485. **
  116486. ** * The FTS3 module is being built as an extension
  116487. ** (in which case SQLITE_CORE is not defined), or
  116488. **
  116489. ** * The FTS3 module is being built into the core of
  116490. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  116491. */
  116492. /* The full-text index is stored in a series of b+tree (-like)
  116493. ** structures called segments which map terms to doclists. The
  116494. ** structures are like b+trees in layout, but are constructed from the
  116495. ** bottom up in optimal fashion and are not updatable. Since trees
  116496. ** are built from the bottom up, things will be described from the
  116497. ** bottom up.
  116498. **
  116499. **
  116500. **** Varints ****
  116501. ** The basic unit of encoding is a variable-length integer called a
  116502. ** varint. We encode variable-length integers in little-endian order
  116503. ** using seven bits * per byte as follows:
  116504. **
  116505. ** KEY:
  116506. ** A = 0xxxxxxx 7 bits of data and one flag bit
  116507. ** B = 1xxxxxxx 7 bits of data and one flag bit
  116508. **
  116509. ** 7 bits - A
  116510. ** 14 bits - BA
  116511. ** 21 bits - BBA
  116512. ** and so on.
  116513. **
  116514. ** This is similar in concept to how sqlite encodes "varints" but
  116515. ** the encoding is not the same. SQLite varints are big-endian
  116516. ** are are limited to 9 bytes in length whereas FTS3 varints are
  116517. ** little-endian and can be up to 10 bytes in length (in theory).
  116518. **
  116519. ** Example encodings:
  116520. **
  116521. ** 1: 0x01
  116522. ** 127: 0x7f
  116523. ** 128: 0x81 0x00
  116524. **
  116525. **
  116526. **** Document lists ****
  116527. ** A doclist (document list) holds a docid-sorted list of hits for a
  116528. ** given term. Doclists hold docids and associated token positions.
  116529. ** A docid is the unique integer identifier for a single document.
  116530. ** A position is the index of a word within the document. The first
  116531. ** word of the document has a position of 0.
  116532. **
  116533. ** FTS3 used to optionally store character offsets using a compile-time
  116534. ** option. But that functionality is no longer supported.
  116535. **
  116536. ** A doclist is stored like this:
  116537. **
  116538. ** array {
  116539. ** varint docid; (delta from previous doclist)
  116540. ** array { (position list for column 0)
  116541. ** varint position; (2 more than the delta from previous position)
  116542. ** }
  116543. ** array {
  116544. ** varint POS_COLUMN; (marks start of position list for new column)
  116545. ** varint column; (index of new column)
  116546. ** array {
  116547. ** varint position; (2 more than the delta from previous position)
  116548. ** }
  116549. ** }
  116550. ** varint POS_END; (marks end of positions for this document.
  116551. ** }
  116552. **
  116553. ** Here, array { X } means zero or more occurrences of X, adjacent in
  116554. ** memory. A "position" is an index of a token in the token stream
  116555. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  116556. ** in the same logical place as the position element, and act as sentinals
  116557. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  116558. ** The positions numbers are not stored literally but rather as two more
  116559. ** than the difference from the prior position, or the just the position plus
  116560. ** 2 for the first position. Example:
  116561. **
  116562. ** label: A B C D E F G H I J K
  116563. ** value: 123 5 9 1 1 14 35 0 234 72 0
  116564. **
  116565. ** The 123 value is the first docid. For column zero in this document
  116566. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  116567. ** at D signals the start of a new column; the 1 at E indicates that the
  116568. ** new column is column number 1. There are two positions at 12 and 45
  116569. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  116570. ** 234 at I is the delta to next docid (357). It has one position 70
  116571. ** (72-2) and then terminates with the 0 at K.
  116572. **
  116573. ** A "position-list" is the list of positions for multiple columns for
  116574. ** a single docid. A "column-list" is the set of positions for a single
  116575. ** column. Hence, a position-list consists of one or more column-lists,
  116576. ** a document record consists of a docid followed by a position-list and
  116577. ** a doclist consists of one or more document records.
  116578. **
  116579. ** A bare doclist omits the position information, becoming an
  116580. ** array of varint-encoded docids.
  116581. **
  116582. **** Segment leaf nodes ****
  116583. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  116584. ** nodes are written using LeafWriter, and read using LeafReader (to
  116585. ** iterate through a single leaf node's data) and LeavesReader (to
  116586. ** iterate through a segment's entire leaf layer). Leaf nodes have
  116587. ** the format:
  116588. **
  116589. ** varint iHeight; (height from leaf level, always 0)
  116590. ** varint nTerm; (length of first term)
  116591. ** char pTerm[nTerm]; (content of first term)
  116592. ** varint nDoclist; (length of term's associated doclist)
  116593. ** char pDoclist[nDoclist]; (content of doclist)
  116594. ** array {
  116595. ** (further terms are delta-encoded)
  116596. ** varint nPrefix; (length of prefix shared with previous term)
  116597. ** varint nSuffix; (length of unshared suffix)
  116598. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  116599. ** varint nDoclist; (length of term's associated doclist)
  116600. ** char pDoclist[nDoclist]; (content of doclist)
  116601. ** }
  116602. **
  116603. ** Here, array { X } means zero or more occurrences of X, adjacent in
  116604. ** memory.
  116605. **
  116606. ** Leaf nodes are broken into blocks which are stored contiguously in
  116607. ** the %_segments table in sorted order. This means that when the end
  116608. ** of a node is reached, the next term is in the node with the next
  116609. ** greater node id.
  116610. **
  116611. ** New data is spilled to a new leaf node when the current node
  116612. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  116613. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  116614. ** node (a leaf node with a single term and doclist). The goal of
  116615. ** these settings is to pack together groups of small doclists while
  116616. ** making it efficient to directly access large doclists. The
  116617. ** assumption is that large doclists represent terms which are more
  116618. ** likely to be query targets.
  116619. **
  116620. ** TODO(shess) It may be useful for blocking decisions to be more
  116621. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  116622. ** node rather than splitting into 2k and .5k nodes. My intuition is
  116623. ** that this might extend through 2x or 4x the pagesize.
  116624. **
  116625. **
  116626. **** Segment interior nodes ****
  116627. ** Segment interior nodes store blockids for subtree nodes and terms
  116628. ** to describe what data is stored by the each subtree. Interior
  116629. ** nodes are written using InteriorWriter, and read using
  116630. ** InteriorReader. InteriorWriters are created as needed when
  116631. ** SegmentWriter creates new leaf nodes, or when an interior node
  116632. ** itself grows too big and must be split. The format of interior
  116633. ** nodes:
  116634. **
  116635. ** varint iHeight; (height from leaf level, always >0)
  116636. ** varint iBlockid; (block id of node's leftmost subtree)
  116637. ** optional {
  116638. ** varint nTerm; (length of first term)
  116639. ** char pTerm[nTerm]; (content of first term)
  116640. ** array {
  116641. ** (further terms are delta-encoded)
  116642. ** varint nPrefix; (length of shared prefix with previous term)
  116643. ** varint nSuffix; (length of unshared suffix)
  116644. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  116645. ** }
  116646. ** }
  116647. **
  116648. ** Here, optional { X } means an optional element, while array { X }
  116649. ** means zero or more occurrences of X, adjacent in memory.
  116650. **
  116651. ** An interior node encodes n terms separating n+1 subtrees. The
  116652. ** subtree blocks are contiguous, so only the first subtree's blockid
  116653. ** is encoded. The subtree at iBlockid will contain all terms less
  116654. ** than the first term encoded (or all terms if no term is encoded).
  116655. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  116656. ** than pTerm[i+1], the subtree for that term will be rooted at
  116657. ** iBlockid+i. Interior nodes only store enough term data to
  116658. ** distinguish adjacent children (if the rightmost term of the left
  116659. ** child is "something", and the leftmost term of the right child is
  116660. ** "wicked", only "w" is stored).
  116661. **
  116662. ** New data is spilled to a new interior node at the same height when
  116663. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  116664. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  116665. ** interior nodes and making the tree too skinny. The interior nodes
  116666. ** at a given height are naturally tracked by interior nodes at
  116667. ** height+1, and so on.
  116668. **
  116669. **
  116670. **** Segment directory ****
  116671. ** The segment directory in table %_segdir stores meta-information for
  116672. ** merging and deleting segments, and also the root node of the
  116673. ** segment's tree.
  116674. **
  116675. ** The root node is the top node of the segment's tree after encoding
  116676. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  116677. ** This could be either a leaf node or an interior node. If the top
  116678. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  116679. ** and a new root interior node is generated (which should always fit
  116680. ** within ROOT_MAX because it only needs space for 2 varints, the
  116681. ** height and the blockid of the previous root).
  116682. **
  116683. ** The meta-information in the segment directory is:
  116684. ** level - segment level (see below)
  116685. ** idx - index within level
  116686. ** - (level,idx uniquely identify a segment)
  116687. ** start_block - first leaf node
  116688. ** leaves_end_block - last leaf node
  116689. ** end_block - last block (including interior nodes)
  116690. ** root - contents of root node
  116691. **
  116692. ** If the root node is a leaf node, then start_block,
  116693. ** leaves_end_block, and end_block are all 0.
  116694. **
  116695. **
  116696. **** Segment merging ****
  116697. ** To amortize update costs, segments are grouped into levels and
  116698. ** merged in batches. Each increase in level represents exponentially
  116699. ** more documents.
  116700. **
  116701. ** New documents (actually, document updates) are tokenized and
  116702. ** written individually (using LeafWriter) to a level 0 segment, with
  116703. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  116704. ** level 0 segments are merged into a single level 1 segment. Level 1
  116705. ** is populated like level 0, and eventually MERGE_COUNT level 1
  116706. ** segments are merged to a single level 2 segment (representing
  116707. ** MERGE_COUNT^2 updates), and so on.
  116708. **
  116709. ** A segment merge traverses all segments at a given level in
  116710. ** parallel, performing a straightforward sorted merge. Since segment
  116711. ** leaf nodes are written in to the %_segments table in order, this
  116712. ** merge traverses the underlying sqlite disk structures efficiently.
  116713. ** After the merge, all segment blocks from the merged level are
  116714. ** deleted.
  116715. **
  116716. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  116717. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  116718. ** very similar performance numbers to 16 on insertion, though they're
  116719. ** a tiny bit slower (perhaps due to more overhead in merge-time
  116720. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  116721. ** 16, 2 about 66% slower than 16.
  116722. **
  116723. ** At query time, high MERGE_COUNT increases the number of segments
  116724. ** which need to be scanned and merged. For instance, with 100k docs
  116725. ** inserted:
  116726. **
  116727. ** MERGE_COUNT segments
  116728. ** 16 25
  116729. ** 8 12
  116730. ** 4 10
  116731. ** 2 6
  116732. **
  116733. ** This appears to have only a moderate impact on queries for very
  116734. ** frequent terms (which are somewhat dominated by segment merge
  116735. ** costs), and infrequent and non-existent terms still seem to be fast
  116736. ** even with many segments.
  116737. **
  116738. ** TODO(shess) That said, it would be nice to have a better query-side
  116739. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  116740. ** optimizations to things like doclist merging will swing the sweet
  116741. ** spot around.
  116742. **
  116743. **
  116744. **
  116745. **** Handling of deletions and updates ****
  116746. ** Since we're using a segmented structure, with no docid-oriented
  116747. ** index into the term index, we clearly cannot simply update the term
  116748. ** index when a document is deleted or updated. For deletions, we
  116749. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  116750. ** we simply write the new doclist. Segment merges overwrite older
  116751. ** data for a particular docid with newer data, so deletes or updates
  116752. ** will eventually overtake the earlier data and knock it out. The
  116753. ** query logic likewise merges doclists so that newer data knocks out
  116754. ** older data.
  116755. */
  116756. /************** Include fts3Int.h in the middle of fts3.c ********************/
  116757. /************** Begin file fts3Int.h *****************************************/
  116758. /*
  116759. ** 2009 Nov 12
  116760. **
  116761. ** The author disclaims copyright to this source code. In place of
  116762. ** a legal notice, here is a blessing:
  116763. **
  116764. ** May you do good and not evil.
  116765. ** May you find forgiveness for yourself and forgive others.
  116766. ** May you share freely, never taking more than you give.
  116767. **
  116768. ******************************************************************************
  116769. **
  116770. */
  116771. #ifndef _FTSINT_H
  116772. #define _FTSINT_H
  116773. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  116774. # define NDEBUG 1
  116775. #endif
  116776. /*
  116777. ** FTS4 is really an extension for FTS3. It is enabled using the
  116778. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  116779. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  116780. */
  116781. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  116782. # define SQLITE_ENABLE_FTS3
  116783. #endif
  116784. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  116785. /* If not building as part of the core, include sqlite3ext.h. */
  116786. #ifndef SQLITE_CORE
  116787. SQLITE_EXTENSION_INIT3
  116788. #endif
  116789. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  116790. /************** Begin file fts3_tokenizer.h **********************************/
  116791. /*
  116792. ** 2006 July 10
  116793. **
  116794. ** The author disclaims copyright to this source code.
  116795. **
  116796. *************************************************************************
  116797. ** Defines the interface to tokenizers used by fulltext-search. There
  116798. ** are three basic components:
  116799. **
  116800. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  116801. ** interface functions. This is essentially the class structure for
  116802. ** tokenizers.
  116803. **
  116804. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  116805. ** including customization information defined at creation time.
  116806. **
  116807. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  116808. ** tokens from a particular input.
  116809. */
  116810. #ifndef _FTS3_TOKENIZER_H_
  116811. #define _FTS3_TOKENIZER_H_
  116812. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  116813. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  116814. ** we will need a way to register the API consistently.
  116815. */
  116816. /*
  116817. ** Structures used by the tokenizer interface. When a new tokenizer
  116818. ** implementation is registered, the caller provides a pointer to
  116819. ** an sqlite3_tokenizer_module containing pointers to the callback
  116820. ** functions that make up an implementation.
  116821. **
  116822. ** When an fts3 table is created, it passes any arguments passed to
  116823. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  116824. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  116825. ** implementation. The xCreate() function in turn returns an
  116826. ** sqlite3_tokenizer structure representing the specific tokenizer to
  116827. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  116828. **
  116829. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  116830. ** method is called. It returns an sqlite3_tokenizer_cursor object
  116831. ** that may be used to tokenize a specific input buffer based on
  116832. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  116833. ** object.
  116834. */
  116835. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  116836. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  116837. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  116838. struct sqlite3_tokenizer_module {
  116839. /*
  116840. ** Structure version. Should always be set to 0 or 1.
  116841. */
  116842. int iVersion;
  116843. /*
  116844. ** Create a new tokenizer. The values in the argv[] array are the
  116845. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  116846. ** TABLE statement that created the fts3 table. For example, if
  116847. ** the following SQL is executed:
  116848. **
  116849. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  116850. **
  116851. ** then argc is set to 2, and the argv[] array contains pointers
  116852. ** to the strings "arg1" and "arg2".
  116853. **
  116854. ** This method should return either SQLITE_OK (0), or an SQLite error
  116855. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  116856. ** to point at the newly created tokenizer structure. The generic
  116857. ** sqlite3_tokenizer.pModule variable should not be initialized by
  116858. ** this callback. The caller will do so.
  116859. */
  116860. int (*xCreate)(
  116861. int argc, /* Size of argv array */
  116862. const char *const*argv, /* Tokenizer argument strings */
  116863. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  116864. );
  116865. /*
  116866. ** Destroy an existing tokenizer. The fts3 module calls this method
  116867. ** exactly once for each successful call to xCreate().
  116868. */
  116869. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  116870. /*
  116871. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  116872. ** is responsible for ensuring that the input buffer remains valid
  116873. ** until the cursor is closed (using the xClose() method).
  116874. */
  116875. int (*xOpen)(
  116876. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  116877. const char *pInput, int nBytes, /* Input buffer */
  116878. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  116879. );
  116880. /*
  116881. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  116882. ** method exactly once for each successful call to xOpen().
  116883. */
  116884. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  116885. /*
  116886. ** Retrieve the next token from the tokenizer cursor pCursor. This
  116887. ** method should either return SQLITE_OK and set the values of the
  116888. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  116889. ** the end of the buffer has been reached, or an SQLite error code.
  116890. **
  116891. ** *ppToken should be set to point at a buffer containing the
  116892. ** normalized version of the token (i.e. after any case-folding and/or
  116893. ** stemming has been performed). *pnBytes should be set to the length
  116894. ** of this buffer in bytes. The input text that generated the token is
  116895. ** identified by the byte offsets returned in *piStartOffset and
  116896. ** *piEndOffset. *piStartOffset should be set to the index of the first
  116897. ** byte of the token in the input buffer. *piEndOffset should be set
  116898. ** to the index of the first byte just past the end of the token in
  116899. ** the input buffer.
  116900. **
  116901. ** The buffer *ppToken is set to point at is managed by the tokenizer
  116902. ** implementation. It is only required to be valid until the next call
  116903. ** to xNext() or xClose().
  116904. */
  116905. /* TODO(shess) current implementation requires pInput to be
  116906. ** nul-terminated. This should either be fixed, or pInput/nBytes
  116907. ** should be converted to zInput.
  116908. */
  116909. int (*xNext)(
  116910. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  116911. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  116912. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  116913. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  116914. int *piPosition /* OUT: Number of tokens returned before this one */
  116915. );
  116916. /***********************************************************************
  116917. ** Methods below this point are only available if iVersion>=1.
  116918. */
  116919. /*
  116920. ** Configure the language id of a tokenizer cursor.
  116921. */
  116922. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  116923. };
  116924. struct sqlite3_tokenizer {
  116925. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  116926. /* Tokenizer implementations will typically add additional fields */
  116927. };
  116928. struct sqlite3_tokenizer_cursor {
  116929. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  116930. /* Tokenizer implementations will typically add additional fields */
  116931. };
  116932. int fts3_global_term_cnt(int iTerm, int iCol);
  116933. int fts3_term_cnt(int iTerm, int iCol);
  116934. #endif /* _FTS3_TOKENIZER_H_ */
  116935. /************** End of fts3_tokenizer.h **************************************/
  116936. /************** Continuing where we left off in fts3Int.h ********************/
  116937. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  116938. /************** Begin file fts3_hash.h ***************************************/
  116939. /*
  116940. ** 2001 September 22
  116941. **
  116942. ** The author disclaims copyright to this source code. In place of
  116943. ** a legal notice, here is a blessing:
  116944. **
  116945. ** May you do good and not evil.
  116946. ** May you find forgiveness for yourself and forgive others.
  116947. ** May you share freely, never taking more than you give.
  116948. **
  116949. *************************************************************************
  116950. ** This is the header file for the generic hash-table implementation
  116951. ** used in SQLite. We've modified it slightly to serve as a standalone
  116952. ** hash table implementation for the full-text indexing module.
  116953. **
  116954. */
  116955. #ifndef _FTS3_HASH_H_
  116956. #define _FTS3_HASH_H_
  116957. /* Forward declarations of structures. */
  116958. typedef struct Fts3Hash Fts3Hash;
  116959. typedef struct Fts3HashElem Fts3HashElem;
  116960. /* A complete hash table is an instance of the following structure.
  116961. ** The internals of this structure are intended to be opaque -- client
  116962. ** code should not attempt to access or modify the fields of this structure
  116963. ** directly. Change this structure only by using the routines below.
  116964. ** However, many of the "procedures" and "functions" for modifying and
  116965. ** accessing this structure are really macros, so we can't really make
  116966. ** this structure opaque.
  116967. */
  116968. struct Fts3Hash {
  116969. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  116970. char copyKey; /* True if copy of key made on insert */
  116971. int count; /* Number of entries in this table */
  116972. Fts3HashElem *first; /* The first element of the array */
  116973. int htsize; /* Number of buckets in the hash table */
  116974. struct _fts3ht { /* the hash table */
  116975. int count; /* Number of entries with this hash */
  116976. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  116977. } *ht;
  116978. };
  116979. /* Each element in the hash table is an instance of the following
  116980. ** structure. All elements are stored on a single doubly-linked list.
  116981. **
  116982. ** Again, this structure is intended to be opaque, but it can't really
  116983. ** be opaque because it is used by macros.
  116984. */
  116985. struct Fts3HashElem {
  116986. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  116987. void *data; /* Data associated with this element */
  116988. void *pKey; int nKey; /* Key associated with this element */
  116989. };
  116990. /*
  116991. ** There are 2 different modes of operation for a hash table:
  116992. **
  116993. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  116994. ** (including the null-terminator, if any). Case
  116995. ** is respected in comparisons.
  116996. **
  116997. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  116998. ** memcmp() is used to compare keys.
  116999. **
  117000. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  117001. */
  117002. #define FTS3_HASH_STRING 1
  117003. #define FTS3_HASH_BINARY 2
  117004. /*
  117005. ** Access routines. To delete, insert a NULL pointer.
  117006. */
  117007. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  117008. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  117009. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  117010. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  117011. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  117012. /*
  117013. ** Shorthand for the functions above
  117014. */
  117015. #define fts3HashInit sqlite3Fts3HashInit
  117016. #define fts3HashInsert sqlite3Fts3HashInsert
  117017. #define fts3HashFind sqlite3Fts3HashFind
  117018. #define fts3HashClear sqlite3Fts3HashClear
  117019. #define fts3HashFindElem sqlite3Fts3HashFindElem
  117020. /*
  117021. ** Macros for looping over all elements of a hash table. The idiom is
  117022. ** like this:
  117023. **
  117024. ** Fts3Hash h;
  117025. ** Fts3HashElem *p;
  117026. ** ...
  117027. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  117028. ** SomeStructure *pData = fts3HashData(p);
  117029. ** // do something with pData
  117030. ** }
  117031. */
  117032. #define fts3HashFirst(H) ((H)->first)
  117033. #define fts3HashNext(E) ((E)->next)
  117034. #define fts3HashData(E) ((E)->data)
  117035. #define fts3HashKey(E) ((E)->pKey)
  117036. #define fts3HashKeysize(E) ((E)->nKey)
  117037. /*
  117038. ** Number of entries in a hash table
  117039. */
  117040. #define fts3HashCount(H) ((H)->count)
  117041. #endif /* _FTS3_HASH_H_ */
  117042. /************** End of fts3_hash.h *******************************************/
  117043. /************** Continuing where we left off in fts3Int.h ********************/
  117044. /*
  117045. ** This constant determines the maximum depth of an FTS expression tree
  117046. ** that the library will create and use. FTS uses recursion to perform
  117047. ** various operations on the query tree, so the disadvantage of a large
  117048. ** limit is that it may allow very large queries to use large amounts
  117049. ** of stack space (perhaps causing a stack overflow).
  117050. */
  117051. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  117052. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  117053. #endif
  117054. /*
  117055. ** This constant controls how often segments are merged. Once there are
  117056. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  117057. ** segment of level N+1.
  117058. */
  117059. #define FTS3_MERGE_COUNT 16
  117060. /*
  117061. ** This is the maximum amount of data (in bytes) to store in the
  117062. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  117063. ** populated as documents are inserted/updated/deleted in a transaction
  117064. ** and used to create a new segment when the transaction is committed.
  117065. ** However if this limit is reached midway through a transaction, a new
  117066. ** segment is created and the hash table cleared immediately.
  117067. */
  117068. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  117069. /*
  117070. ** Macro to return the number of elements in an array. SQLite has a
  117071. ** similar macro called ArraySize(). Use a different name to avoid
  117072. ** a collision when building an amalgamation with built-in FTS3.
  117073. */
  117074. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  117075. #ifndef MIN
  117076. # define MIN(x,y) ((x)<(y)?(x):(y))
  117077. #endif
  117078. #ifndef MAX
  117079. # define MAX(x,y) ((x)>(y)?(x):(y))
  117080. #endif
  117081. /*
  117082. ** Maximum length of a varint encoded integer. The varint format is different
  117083. ** from that used by SQLite, so the maximum length is 10, not 9.
  117084. */
  117085. #define FTS3_VARINT_MAX 10
  117086. /*
  117087. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  117088. ** in the document set and zero or more prefix indexes. All indexes are stored
  117089. ** as one or more b+-trees in the %_segments and %_segdir tables.
  117090. **
  117091. ** It is possible to determine which index a b+-tree belongs to based on the
  117092. ** value stored in the "%_segdir.level" column. Given this value L, the index
  117093. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  117094. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  117095. ** between 1024 and 2047 to index 1, and so on.
  117096. **
  117097. ** It is considered impossible for an index to use more than 1024 levels. In
  117098. ** theory though this may happen, but only after at least
  117099. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  117100. */
  117101. #define FTS3_SEGDIR_MAXLEVEL 1024
  117102. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  117103. /*
  117104. ** The testcase() macro is only used by the amalgamation. If undefined,
  117105. ** make it a no-op.
  117106. */
  117107. #ifndef testcase
  117108. # define testcase(X)
  117109. #endif
  117110. /*
  117111. ** Terminator values for position-lists and column-lists.
  117112. */
  117113. #define POS_COLUMN (1) /* Column-list terminator */
  117114. #define POS_END (0) /* Position-list terminator */
  117115. /*
  117116. ** This section provides definitions to allow the
  117117. ** FTS3 extension to be compiled outside of the
  117118. ** amalgamation.
  117119. */
  117120. #ifndef SQLITE_AMALGAMATION
  117121. /*
  117122. ** Macros indicating that conditional expressions are always true or
  117123. ** false.
  117124. */
  117125. #ifdef SQLITE_COVERAGE_TEST
  117126. # define ALWAYS(x) (1)
  117127. # define NEVER(X) (0)
  117128. #else
  117129. # define ALWAYS(x) (x)
  117130. # define NEVER(x) (x)
  117131. #endif
  117132. /*
  117133. ** Internal types used by SQLite.
  117134. */
  117135. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  117136. typedef short int i16; /* 2-byte (or larger) signed integer */
  117137. typedef unsigned int u32; /* 4-byte unsigned integer */
  117138. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  117139. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  117140. /*
  117141. ** Macro used to suppress compiler warnings for unused parameters.
  117142. */
  117143. #define UNUSED_PARAMETER(x) (void)(x)
  117144. /*
  117145. ** Activate assert() only if SQLITE_TEST is enabled.
  117146. */
  117147. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  117148. # define NDEBUG 1
  117149. #endif
  117150. /*
  117151. ** The TESTONLY macro is used to enclose variable declarations or
  117152. ** other bits of code that are needed to support the arguments
  117153. ** within testcase() and assert() macros.
  117154. */
  117155. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  117156. # define TESTONLY(X) X
  117157. #else
  117158. # define TESTONLY(X)
  117159. #endif
  117160. #endif /* SQLITE_AMALGAMATION */
  117161. #ifdef SQLITE_DEBUG
  117162. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  117163. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  117164. #else
  117165. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  117166. #endif
  117167. typedef struct Fts3Table Fts3Table;
  117168. typedef struct Fts3Cursor Fts3Cursor;
  117169. typedef struct Fts3Expr Fts3Expr;
  117170. typedef struct Fts3Phrase Fts3Phrase;
  117171. typedef struct Fts3PhraseToken Fts3PhraseToken;
  117172. typedef struct Fts3Doclist Fts3Doclist;
  117173. typedef struct Fts3SegFilter Fts3SegFilter;
  117174. typedef struct Fts3DeferredToken Fts3DeferredToken;
  117175. typedef struct Fts3SegReader Fts3SegReader;
  117176. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  117177. /*
  117178. ** A connection to a fulltext index is an instance of the following
  117179. ** structure. The xCreate and xConnect methods create an instance
  117180. ** of this structure and xDestroy and xDisconnect free that instance.
  117181. ** All other methods receive a pointer to the structure as one of their
  117182. ** arguments.
  117183. */
  117184. struct Fts3Table {
  117185. sqlite3_vtab base; /* Base class used by SQLite core */
  117186. sqlite3 *db; /* The database connection */
  117187. const char *zDb; /* logical database name */
  117188. const char *zName; /* virtual table name */
  117189. int nColumn; /* number of named columns in virtual table */
  117190. char **azColumn; /* column names. malloced */
  117191. u8 *abNotindexed; /* True for 'notindexed' columns */
  117192. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  117193. char *zContentTbl; /* content=xxx option, or NULL */
  117194. char *zLanguageid; /* languageid=xxx option, or NULL */
  117195. u8 bAutoincrmerge; /* True if automerge=1 */
  117196. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  117197. /* Precompiled statements used by the implementation. Each of these
  117198. ** statements is run and reset within a single virtual table API call.
  117199. */
  117200. sqlite3_stmt *aStmt[37];
  117201. char *zReadExprlist;
  117202. char *zWriteExprlist;
  117203. int nNodeSize; /* Soft limit for node size */
  117204. u8 bFts4; /* True for FTS4, false for FTS3 */
  117205. u8 bHasStat; /* True if %_stat table exists */
  117206. u8 bHasDocsize; /* True if %_docsize table exists */
  117207. u8 bDescIdx; /* True if doclists are in reverse order */
  117208. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  117209. int nPgsz; /* Page size for host database */
  117210. char *zSegmentsTbl; /* Name of %_segments table */
  117211. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  117212. /*
  117213. ** The following array of hash tables is used to buffer pending index
  117214. ** updates during transactions. All pending updates buffered at any one
  117215. ** time must share a common language-id (see the FTS4 langid= feature).
  117216. ** The current language id is stored in variable iPrevLangid.
  117217. **
  117218. ** A single FTS4 table may have multiple full-text indexes. For each index
  117219. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  117220. ** terms that appear in the document set. Each subsequent index in aIndex[]
  117221. ** is an index of prefixes of a specific length.
  117222. **
  117223. ** Variable nPendingData contains an estimate the memory consumed by the
  117224. ** pending data structures, including hash table overhead, but not including
  117225. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  117226. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  117227. ** recently inserted record.
  117228. */
  117229. int nIndex; /* Size of aIndex[] */
  117230. struct Fts3Index {
  117231. int nPrefix; /* Prefix length (0 for main terms index) */
  117232. Fts3Hash hPending; /* Pending terms table for this index */
  117233. } *aIndex;
  117234. int nMaxPendingData; /* Max pending data before flush to disk */
  117235. int nPendingData; /* Current bytes of pending data */
  117236. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  117237. int iPrevLangid; /* Langid of recently inserted document */
  117238. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  117239. /* State variables used for validating that the transaction control
  117240. ** methods of the virtual table are called at appropriate times. These
  117241. ** values do not contribute to FTS functionality; they are used for
  117242. ** verifying the operation of the SQLite core.
  117243. */
  117244. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  117245. int mxSavepoint; /* Largest valid xSavepoint integer */
  117246. #endif
  117247. #ifdef SQLITE_TEST
  117248. /* True to disable the incremental doclist optimization. This is controled
  117249. ** by special insert command 'test-no-incr-doclist'. */
  117250. int bNoIncrDoclist;
  117251. #endif
  117252. };
  117253. /*
  117254. ** When the core wants to read from the virtual table, it creates a
  117255. ** virtual table cursor (an instance of the following structure) using
  117256. ** the xOpen method. Cursors are destroyed using the xClose method.
  117257. */
  117258. struct Fts3Cursor {
  117259. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  117260. i16 eSearch; /* Search strategy (see below) */
  117261. u8 isEof; /* True if at End Of Results */
  117262. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  117263. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  117264. Fts3Expr *pExpr; /* Parsed MATCH query string */
  117265. int iLangid; /* Language being queried for */
  117266. int nPhrase; /* Number of matchable phrases in query */
  117267. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  117268. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  117269. char *pNextId; /* Pointer into the body of aDoclist */
  117270. char *aDoclist; /* List of docids for full-text queries */
  117271. int nDoclist; /* Size of buffer at aDoclist */
  117272. u8 bDesc; /* True to sort in descending order */
  117273. int eEvalmode; /* An FTS3_EVAL_XX constant */
  117274. int nRowAvg; /* Average size of database rows, in pages */
  117275. sqlite3_int64 nDoc; /* Documents in table */
  117276. i64 iMinDocid; /* Minimum docid to return */
  117277. i64 iMaxDocid; /* Maximum docid to return */
  117278. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  117279. u32 *aMatchinfo; /* Information about most recent match */
  117280. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  117281. char *zMatchinfo; /* Matchinfo specification */
  117282. };
  117283. #define FTS3_EVAL_FILTER 0
  117284. #define FTS3_EVAL_NEXT 1
  117285. #define FTS3_EVAL_MATCHINFO 2
  117286. /*
  117287. ** The Fts3Cursor.eSearch member is always set to one of the following.
  117288. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  117289. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  117290. ** of the column to be searched. For example, in
  117291. **
  117292. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  117293. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  117294. **
  117295. ** Because the LHS of the MATCH operator is 2nd column "b",
  117296. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  117297. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  117298. ** indicating that all columns should be searched,
  117299. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  117300. */
  117301. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  117302. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  117303. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  117304. /*
  117305. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  117306. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  117307. ** above. The upper 16-bits contain a combination of the following
  117308. ** bits, used to describe extra constraints on full-text searches.
  117309. */
  117310. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  117311. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  117312. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  117313. struct Fts3Doclist {
  117314. char *aAll; /* Array containing doclist (or NULL) */
  117315. int nAll; /* Size of a[] in bytes */
  117316. char *pNextDocid; /* Pointer to next docid */
  117317. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  117318. int bFreeList; /* True if pList should be sqlite3_free()d */
  117319. char *pList; /* Pointer to position list following iDocid */
  117320. int nList; /* Length of position list */
  117321. };
  117322. /*
  117323. ** A "phrase" is a sequence of one or more tokens that must match in
  117324. ** sequence. A single token is the base case and the most common case.
  117325. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  117326. ** nToken will be the number of tokens in the string.
  117327. */
  117328. struct Fts3PhraseToken {
  117329. char *z; /* Text of the token */
  117330. int n; /* Number of bytes in buffer z */
  117331. int isPrefix; /* True if token ends with a "*" character */
  117332. int bFirst; /* True if token must appear at position 0 */
  117333. /* Variables above this point are populated when the expression is
  117334. ** parsed (by code in fts3_expr.c). Below this point the variables are
  117335. ** used when evaluating the expression. */
  117336. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  117337. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  117338. };
  117339. struct Fts3Phrase {
  117340. /* Cache of doclist for this phrase. */
  117341. Fts3Doclist doclist;
  117342. int bIncr; /* True if doclist is loaded incrementally */
  117343. int iDoclistToken;
  117344. /* Variables below this point are populated by fts3_expr.c when parsing
  117345. ** a MATCH expression. Everything above is part of the evaluation phase.
  117346. */
  117347. int nToken; /* Number of tokens in the phrase */
  117348. int iColumn; /* Index of column this phrase must match */
  117349. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  117350. };
  117351. /*
  117352. ** A tree of these objects forms the RHS of a MATCH operator.
  117353. **
  117354. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  117355. ** points to a malloced buffer, size nDoclist bytes, containing the results
  117356. ** of this phrase query in FTS3 doclist format. As usual, the initial
  117357. ** "Length" field found in doclists stored on disk is omitted from this
  117358. ** buffer.
  117359. **
  117360. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  117361. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  117362. ** where nCol is the number of columns in the queried FTS table. The array
  117363. ** is populated as follows:
  117364. **
  117365. ** aMI[iCol*3 + 0] = Undefined
  117366. ** aMI[iCol*3 + 1] = Number of occurrences
  117367. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  117368. **
  117369. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  117370. ** when the expression node is.
  117371. */
  117372. struct Fts3Expr {
  117373. int eType; /* One of the FTSQUERY_XXX values defined below */
  117374. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  117375. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  117376. Fts3Expr *pLeft; /* Left operand */
  117377. Fts3Expr *pRight; /* Right operand */
  117378. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  117379. /* The following are used by the fts3_eval.c module. */
  117380. sqlite3_int64 iDocid; /* Current docid */
  117381. u8 bEof; /* True this expression is at EOF already */
  117382. u8 bStart; /* True if iDocid is valid */
  117383. u8 bDeferred; /* True if this expression is entirely deferred */
  117384. u32 *aMI;
  117385. };
  117386. /*
  117387. ** Candidate values for Fts3Query.eType. Note that the order of the first
  117388. ** four values is in order of precedence when parsing expressions. For
  117389. ** example, the following:
  117390. **
  117391. ** "a OR b AND c NOT d NEAR e"
  117392. **
  117393. ** is equivalent to:
  117394. **
  117395. ** "a OR (b AND (c NOT (d NEAR e)))"
  117396. */
  117397. #define FTSQUERY_NEAR 1
  117398. #define FTSQUERY_NOT 2
  117399. #define FTSQUERY_AND 3
  117400. #define FTSQUERY_OR 4
  117401. #define FTSQUERY_PHRASE 5
  117402. /* fts3_write.c */
  117403. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  117404. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  117405. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  117406. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  117407. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  117408. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  117409. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  117410. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  117411. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  117412. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  117413. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  117414. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  117415. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  117416. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  117417. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  117418. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  117419. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  117420. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  117421. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  117422. #else
  117423. # define sqlite3Fts3FreeDeferredTokens(x)
  117424. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  117425. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  117426. # define sqlite3Fts3FreeDeferredDoclists(x)
  117427. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  117428. #endif
  117429. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  117430. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  117431. /* Special values interpreted by sqlite3SegReaderCursor() */
  117432. #define FTS3_SEGCURSOR_PENDING -1
  117433. #define FTS3_SEGCURSOR_ALL -2
  117434. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  117435. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  117436. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  117437. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  117438. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  117439. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  117440. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  117441. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  117442. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  117443. #define FTS3_SEGMENT_PREFIX 0x00000008
  117444. #define FTS3_SEGMENT_SCAN 0x00000010
  117445. #define FTS3_SEGMENT_FIRST 0x00000020
  117446. /* Type passed as 4th argument to SegmentReaderIterate() */
  117447. struct Fts3SegFilter {
  117448. const char *zTerm;
  117449. int nTerm;
  117450. int iCol;
  117451. int flags;
  117452. };
  117453. struct Fts3MultiSegReader {
  117454. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  117455. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  117456. int nSegment; /* Size of apSegment array */
  117457. int nAdvance; /* How many seg-readers to advance */
  117458. Fts3SegFilter *pFilter; /* Pointer to filter object */
  117459. char *aBuffer; /* Buffer to merge doclists in */
  117460. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  117461. int iColFilter; /* If >=0, filter for this column */
  117462. int bRestart;
  117463. /* Used by fts3.c only. */
  117464. int nCost; /* Cost of running iterator */
  117465. int bLookup; /* True if a lookup of a single entry. */
  117466. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  117467. char *zTerm; /* Pointer to term buffer */
  117468. int nTerm; /* Size of zTerm in bytes */
  117469. char *aDoclist; /* Pointer to doclist buffer */
  117470. int nDoclist; /* Size of aDoclist[] in bytes */
  117471. };
  117472. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  117473. /* fts3.c */
  117474. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  117475. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  117476. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  117477. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  117478. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  117479. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  117480. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  117481. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  117482. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  117483. /* fts3_tokenizer.c */
  117484. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  117485. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  117486. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  117487. sqlite3_tokenizer **, char **
  117488. );
  117489. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  117490. /* fts3_snippet.c */
  117491. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  117492. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  117493. const char *, const char *, int, int
  117494. );
  117495. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  117496. /* fts3_expr.c */
  117497. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  117498. char **, int, int, int, const char *, int, Fts3Expr **, char **
  117499. );
  117500. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  117501. #ifdef SQLITE_TEST
  117502. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  117503. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  117504. #endif
  117505. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  117506. sqlite3_tokenizer_cursor **
  117507. );
  117508. /* fts3_aux.c */
  117509. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  117510. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  117511. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  117512. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  117513. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  117514. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  117515. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  117516. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  117517. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  117518. /* fts3_tokenize_vtab.c */
  117519. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  117520. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  117521. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  117522. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  117523. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  117524. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  117525. #endif
  117526. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  117527. #endif /* _FTSINT_H */
  117528. /************** End of fts3Int.h *********************************************/
  117529. /************** Continuing where we left off in fts3.c ***********************/
  117530. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  117531. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  117532. # define SQLITE_CORE 1
  117533. #endif
  117534. /* #include <assert.h> */
  117535. /* #include <stdlib.h> */
  117536. /* #include <stddef.h> */
  117537. /* #include <stdio.h> */
  117538. /* #include <string.h> */
  117539. /* #include <stdarg.h> */
  117540. #ifndef SQLITE_CORE
  117541. SQLITE_EXTENSION_INIT1
  117542. #endif
  117543. static int fts3EvalNext(Fts3Cursor *pCsr);
  117544. static int fts3EvalStart(Fts3Cursor *pCsr);
  117545. static int fts3TermSegReaderCursor(
  117546. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  117547. /*
  117548. ** Write a 64-bit variable-length integer to memory starting at p[0].
  117549. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  117550. ** The number of bytes written is returned.
  117551. */
  117552. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  117553. unsigned char *q = (unsigned char *) p;
  117554. sqlite_uint64 vu = v;
  117555. do{
  117556. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  117557. vu >>= 7;
  117558. }while( vu!=0 );
  117559. q[-1] &= 0x7f; /* turn off high bit in final byte */
  117560. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  117561. return (int) (q - (unsigned char *)p);
  117562. }
  117563. /*
  117564. ** Read a 64-bit variable-length integer from memory starting at p[0].
  117565. ** Return the number of bytes read, or 0 on error.
  117566. ** The value is stored in *v.
  117567. */
  117568. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  117569. const unsigned char *q = (const unsigned char *) p;
  117570. sqlite_uint64 x = 0, y = 1;
  117571. while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
  117572. x += y * (*q++ & 0x7f);
  117573. y <<= 7;
  117574. }
  117575. x += y * (*q++);
  117576. *v = (sqlite_int64) x;
  117577. return (int) (q - (unsigned char *)p);
  117578. }
  117579. /*
  117580. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  117581. ** 32-bit integer before it is returned.
  117582. */
  117583. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  117584. sqlite_int64 i;
  117585. int ret = sqlite3Fts3GetVarint(p, &i);
  117586. *pi = (int) i;
  117587. return ret;
  117588. }
  117589. /*
  117590. ** Return the number of bytes required to encode v as a varint
  117591. */
  117592. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  117593. int i = 0;
  117594. do{
  117595. i++;
  117596. v >>= 7;
  117597. }while( v!=0 );
  117598. return i;
  117599. }
  117600. /*
  117601. ** Convert an SQL-style quoted string into a normal string by removing
  117602. ** the quote characters. The conversion is done in-place. If the
  117603. ** input does not begin with a quote character, then this routine
  117604. ** is a no-op.
  117605. **
  117606. ** Examples:
  117607. **
  117608. ** "abc" becomes abc
  117609. ** 'xyz' becomes xyz
  117610. ** [pqr] becomes pqr
  117611. ** `mno` becomes mno
  117612. **
  117613. */
  117614. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  117615. char quote; /* Quote character (if any ) */
  117616. quote = z[0];
  117617. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  117618. int iIn = 1; /* Index of next byte to read from input */
  117619. int iOut = 0; /* Index of next byte to write to output */
  117620. /* If the first byte was a '[', then the close-quote character is a ']' */
  117621. if( quote=='[' ) quote = ']';
  117622. while( ALWAYS(z[iIn]) ){
  117623. if( z[iIn]==quote ){
  117624. if( z[iIn+1]!=quote ) break;
  117625. z[iOut++] = quote;
  117626. iIn += 2;
  117627. }else{
  117628. z[iOut++] = z[iIn++];
  117629. }
  117630. }
  117631. z[iOut] = '\0';
  117632. }
  117633. }
  117634. /*
  117635. ** Read a single varint from the doclist at *pp and advance *pp to point
  117636. ** to the first byte past the end of the varint. Add the value of the varint
  117637. ** to *pVal.
  117638. */
  117639. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  117640. sqlite3_int64 iVal;
  117641. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  117642. *pVal += iVal;
  117643. }
  117644. /*
  117645. ** When this function is called, *pp points to the first byte following a
  117646. ** varint that is part of a doclist (or position-list, or any other list
  117647. ** of varints). This function moves *pp to point to the start of that varint,
  117648. ** and sets *pVal by the varint value.
  117649. **
  117650. ** Argument pStart points to the first byte of the doclist that the
  117651. ** varint is part of.
  117652. */
  117653. static void fts3GetReverseVarint(
  117654. char **pp,
  117655. char *pStart,
  117656. sqlite3_int64 *pVal
  117657. ){
  117658. sqlite3_int64 iVal;
  117659. char *p;
  117660. /* Pointer p now points at the first byte past the varint we are
  117661. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  117662. ** clear on character p[-1]. */
  117663. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  117664. p++;
  117665. *pp = p;
  117666. sqlite3Fts3GetVarint(p, &iVal);
  117667. *pVal = iVal;
  117668. }
  117669. /*
  117670. ** The xDisconnect() virtual table method.
  117671. */
  117672. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  117673. Fts3Table *p = (Fts3Table *)pVtab;
  117674. int i;
  117675. assert( p->nPendingData==0 );
  117676. assert( p->pSegments==0 );
  117677. /* Free any prepared statements held */
  117678. for(i=0; i<SizeofArray(p->aStmt); i++){
  117679. sqlite3_finalize(p->aStmt[i]);
  117680. }
  117681. sqlite3_free(p->zSegmentsTbl);
  117682. sqlite3_free(p->zReadExprlist);
  117683. sqlite3_free(p->zWriteExprlist);
  117684. sqlite3_free(p->zContentTbl);
  117685. sqlite3_free(p->zLanguageid);
  117686. /* Invoke the tokenizer destructor to free the tokenizer. */
  117687. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  117688. sqlite3_free(p);
  117689. return SQLITE_OK;
  117690. }
  117691. /*
  117692. ** Construct one or more SQL statements from the format string given
  117693. ** and then evaluate those statements. The success code is written
  117694. ** into *pRc.
  117695. **
  117696. ** If *pRc is initially non-zero then this routine is a no-op.
  117697. */
  117698. static void fts3DbExec(
  117699. int *pRc, /* Success code */
  117700. sqlite3 *db, /* Database in which to run SQL */
  117701. const char *zFormat, /* Format string for SQL */
  117702. ... /* Arguments to the format string */
  117703. ){
  117704. va_list ap;
  117705. char *zSql;
  117706. if( *pRc ) return;
  117707. va_start(ap, zFormat);
  117708. zSql = sqlite3_vmprintf(zFormat, ap);
  117709. va_end(ap);
  117710. if( zSql==0 ){
  117711. *pRc = SQLITE_NOMEM;
  117712. }else{
  117713. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  117714. sqlite3_free(zSql);
  117715. }
  117716. }
  117717. /*
  117718. ** The xDestroy() virtual table method.
  117719. */
  117720. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  117721. Fts3Table *p = (Fts3Table *)pVtab;
  117722. int rc = SQLITE_OK; /* Return code */
  117723. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  117724. sqlite3 *db = p->db; /* Database handle */
  117725. /* Drop the shadow tables */
  117726. if( p->zContentTbl==0 ){
  117727. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  117728. }
  117729. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  117730. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  117731. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  117732. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  117733. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  117734. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  117735. ** Otherwise, return an SQLite error code.
  117736. */
  117737. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  117738. }
  117739. /*
  117740. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  117741. ** passed as the first argument. This is done as part of the xConnect()
  117742. ** and xCreate() methods.
  117743. **
  117744. ** If *pRc is non-zero when this function is called, it is a no-op.
  117745. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  117746. ** before returning.
  117747. */
  117748. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  117749. if( *pRc==SQLITE_OK ){
  117750. int i; /* Iterator variable */
  117751. int rc; /* Return code */
  117752. char *zSql; /* SQL statement passed to declare_vtab() */
  117753. char *zCols; /* List of user defined columns */
  117754. const char *zLanguageid;
  117755. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  117756. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  117757. /* Create a list of user columns for the virtual table */
  117758. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  117759. for(i=1; zCols && i<p->nColumn; i++){
  117760. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  117761. }
  117762. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  117763. zSql = sqlite3_mprintf(
  117764. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  117765. zCols, p->zName, zLanguageid
  117766. );
  117767. if( !zCols || !zSql ){
  117768. rc = SQLITE_NOMEM;
  117769. }else{
  117770. rc = sqlite3_declare_vtab(p->db, zSql);
  117771. }
  117772. sqlite3_free(zSql);
  117773. sqlite3_free(zCols);
  117774. *pRc = rc;
  117775. }
  117776. }
  117777. /*
  117778. ** Create the %_stat table if it does not already exist.
  117779. */
  117780. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  117781. fts3DbExec(pRc, p->db,
  117782. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  117783. "(id INTEGER PRIMARY KEY, value BLOB);",
  117784. p->zDb, p->zName
  117785. );
  117786. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  117787. }
  117788. /*
  117789. ** Create the backing store tables (%_content, %_segments and %_segdir)
  117790. ** required by the FTS3 table passed as the only argument. This is done
  117791. ** as part of the vtab xCreate() method.
  117792. **
  117793. ** If the p->bHasDocsize boolean is true (indicating that this is an
  117794. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  117795. ** %_stat tables required by FTS4.
  117796. */
  117797. static int fts3CreateTables(Fts3Table *p){
  117798. int rc = SQLITE_OK; /* Return code */
  117799. int i; /* Iterator variable */
  117800. sqlite3 *db = p->db; /* The database connection */
  117801. if( p->zContentTbl==0 ){
  117802. const char *zLanguageid = p->zLanguageid;
  117803. char *zContentCols; /* Columns of %_content table */
  117804. /* Create a list of user columns for the content table */
  117805. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  117806. for(i=0; zContentCols && i<p->nColumn; i++){
  117807. char *z = p->azColumn[i];
  117808. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  117809. }
  117810. if( zLanguageid && zContentCols ){
  117811. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  117812. }
  117813. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  117814. /* Create the content table */
  117815. fts3DbExec(&rc, db,
  117816. "CREATE TABLE %Q.'%q_content'(%s)",
  117817. p->zDb, p->zName, zContentCols
  117818. );
  117819. sqlite3_free(zContentCols);
  117820. }
  117821. /* Create other tables */
  117822. fts3DbExec(&rc, db,
  117823. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  117824. p->zDb, p->zName
  117825. );
  117826. fts3DbExec(&rc, db,
  117827. "CREATE TABLE %Q.'%q_segdir'("
  117828. "level INTEGER,"
  117829. "idx INTEGER,"
  117830. "start_block INTEGER,"
  117831. "leaves_end_block INTEGER,"
  117832. "end_block INTEGER,"
  117833. "root BLOB,"
  117834. "PRIMARY KEY(level, idx)"
  117835. ");",
  117836. p->zDb, p->zName
  117837. );
  117838. if( p->bHasDocsize ){
  117839. fts3DbExec(&rc, db,
  117840. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  117841. p->zDb, p->zName
  117842. );
  117843. }
  117844. assert( p->bHasStat==p->bFts4 );
  117845. if( p->bHasStat ){
  117846. sqlite3Fts3CreateStatTable(&rc, p);
  117847. }
  117848. return rc;
  117849. }
  117850. /*
  117851. ** Store the current database page-size in bytes in p->nPgsz.
  117852. **
  117853. ** If *pRc is non-zero when this function is called, it is a no-op.
  117854. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  117855. ** before returning.
  117856. */
  117857. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  117858. if( *pRc==SQLITE_OK ){
  117859. int rc; /* Return code */
  117860. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  117861. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  117862. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  117863. if( !zSql ){
  117864. rc = SQLITE_NOMEM;
  117865. }else{
  117866. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  117867. if( rc==SQLITE_OK ){
  117868. sqlite3_step(pStmt);
  117869. p->nPgsz = sqlite3_column_int(pStmt, 0);
  117870. rc = sqlite3_finalize(pStmt);
  117871. }else if( rc==SQLITE_AUTH ){
  117872. p->nPgsz = 1024;
  117873. rc = SQLITE_OK;
  117874. }
  117875. }
  117876. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  117877. sqlite3_free(zSql);
  117878. *pRc = rc;
  117879. }
  117880. }
  117881. /*
  117882. ** "Special" FTS4 arguments are column specifications of the following form:
  117883. **
  117884. ** <key> = <value>
  117885. **
  117886. ** There may not be whitespace surrounding the "=" character. The <value>
  117887. ** term may be quoted, but the <key> may not.
  117888. */
  117889. static int fts3IsSpecialColumn(
  117890. const char *z,
  117891. int *pnKey,
  117892. char **pzValue
  117893. ){
  117894. char *zValue;
  117895. const char *zCsr = z;
  117896. while( *zCsr!='=' ){
  117897. if( *zCsr=='\0' ) return 0;
  117898. zCsr++;
  117899. }
  117900. *pnKey = (int)(zCsr-z);
  117901. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  117902. if( zValue ){
  117903. sqlite3Fts3Dequote(zValue);
  117904. }
  117905. *pzValue = zValue;
  117906. return 1;
  117907. }
  117908. /*
  117909. ** Append the output of a printf() style formatting to an existing string.
  117910. */
  117911. static void fts3Appendf(
  117912. int *pRc, /* IN/OUT: Error code */
  117913. char **pz, /* IN/OUT: Pointer to string buffer */
  117914. const char *zFormat, /* Printf format string to append */
  117915. ... /* Arguments for printf format string */
  117916. ){
  117917. if( *pRc==SQLITE_OK ){
  117918. va_list ap;
  117919. char *z;
  117920. va_start(ap, zFormat);
  117921. z = sqlite3_vmprintf(zFormat, ap);
  117922. va_end(ap);
  117923. if( z && *pz ){
  117924. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  117925. sqlite3_free(z);
  117926. z = z2;
  117927. }
  117928. if( z==0 ) *pRc = SQLITE_NOMEM;
  117929. sqlite3_free(*pz);
  117930. *pz = z;
  117931. }
  117932. }
  117933. /*
  117934. ** Return a copy of input string zInput enclosed in double-quotes (") and
  117935. ** with all double quote characters escaped. For example:
  117936. **
  117937. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  117938. **
  117939. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  117940. ** is the callers responsibility to call sqlite3_free() to release this
  117941. ** memory.
  117942. */
  117943. static char *fts3QuoteId(char const *zInput){
  117944. int nRet;
  117945. char *zRet;
  117946. nRet = 2 + (int)strlen(zInput)*2 + 1;
  117947. zRet = sqlite3_malloc(nRet);
  117948. if( zRet ){
  117949. int i;
  117950. char *z = zRet;
  117951. *(z++) = '"';
  117952. for(i=0; zInput[i]; i++){
  117953. if( zInput[i]=='"' ) *(z++) = '"';
  117954. *(z++) = zInput[i];
  117955. }
  117956. *(z++) = '"';
  117957. *(z++) = '\0';
  117958. }
  117959. return zRet;
  117960. }
  117961. /*
  117962. ** Return a list of comma separated SQL expressions and a FROM clause that
  117963. ** could be used in a SELECT statement such as the following:
  117964. **
  117965. ** SELECT <list of expressions> FROM %_content AS x ...
  117966. **
  117967. ** to return the docid, followed by each column of text data in order
  117968. ** from left to write. If parameter zFunc is not NULL, then instead of
  117969. ** being returned directly each column of text data is passed to an SQL
  117970. ** function named zFunc first. For example, if zFunc is "unzip" and the
  117971. ** table has the three user-defined columns "a", "b", and "c", the following
  117972. ** string is returned:
  117973. **
  117974. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  117975. **
  117976. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  117977. ** is the responsibility of the caller to eventually free it.
  117978. **
  117979. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  117980. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  117981. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  117982. ** no error occurs, *pRc is left unmodified.
  117983. */
  117984. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  117985. char *zRet = 0;
  117986. char *zFree = 0;
  117987. char *zFunction;
  117988. int i;
  117989. if( p->zContentTbl==0 ){
  117990. if( !zFunc ){
  117991. zFunction = "";
  117992. }else{
  117993. zFree = zFunction = fts3QuoteId(zFunc);
  117994. }
  117995. fts3Appendf(pRc, &zRet, "docid");
  117996. for(i=0; i<p->nColumn; i++){
  117997. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  117998. }
  117999. if( p->zLanguageid ){
  118000. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  118001. }
  118002. sqlite3_free(zFree);
  118003. }else{
  118004. fts3Appendf(pRc, &zRet, "rowid");
  118005. for(i=0; i<p->nColumn; i++){
  118006. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  118007. }
  118008. if( p->zLanguageid ){
  118009. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  118010. }
  118011. }
  118012. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  118013. p->zDb,
  118014. (p->zContentTbl ? p->zContentTbl : p->zName),
  118015. (p->zContentTbl ? "" : "_content")
  118016. );
  118017. return zRet;
  118018. }
  118019. /*
  118020. ** Return a list of N comma separated question marks, where N is the number
  118021. ** of columns in the %_content table (one for the docid plus one for each
  118022. ** user-defined text column).
  118023. **
  118024. ** If argument zFunc is not NULL, then all but the first question mark
  118025. ** is preceded by zFunc and an open bracket, and followed by a closed
  118026. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  118027. ** user-defined text columns, the following string is returned:
  118028. **
  118029. ** "?, zip(?), zip(?), zip(?)"
  118030. **
  118031. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  118032. ** is the responsibility of the caller to eventually free it.
  118033. **
  118034. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  118035. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  118036. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  118037. ** no error occurs, *pRc is left unmodified.
  118038. */
  118039. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  118040. char *zRet = 0;
  118041. char *zFree = 0;
  118042. char *zFunction;
  118043. int i;
  118044. if( !zFunc ){
  118045. zFunction = "";
  118046. }else{
  118047. zFree = zFunction = fts3QuoteId(zFunc);
  118048. }
  118049. fts3Appendf(pRc, &zRet, "?");
  118050. for(i=0; i<p->nColumn; i++){
  118051. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  118052. }
  118053. if( p->zLanguageid ){
  118054. fts3Appendf(pRc, &zRet, ", ?");
  118055. }
  118056. sqlite3_free(zFree);
  118057. return zRet;
  118058. }
  118059. /*
  118060. ** This function interprets the string at (*pp) as a non-negative integer
  118061. ** value. It reads the integer and sets *pnOut to the value read, then
  118062. ** sets *pp to point to the byte immediately following the last byte of
  118063. ** the integer value.
  118064. **
  118065. ** Only decimal digits ('0'..'9') may be part of an integer value.
  118066. **
  118067. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  118068. ** the output value undefined. Otherwise SQLITE_OK is returned.
  118069. **
  118070. ** This function is used when parsing the "prefix=" FTS4 parameter.
  118071. */
  118072. static int fts3GobbleInt(const char **pp, int *pnOut){
  118073. const char *p; /* Iterator pointer */
  118074. int nInt = 0; /* Output value */
  118075. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  118076. nInt = nInt * 10 + (p[0] - '0');
  118077. }
  118078. if( p==*pp ) return SQLITE_ERROR;
  118079. *pnOut = nInt;
  118080. *pp = p;
  118081. return SQLITE_OK;
  118082. }
  118083. /*
  118084. ** This function is called to allocate an array of Fts3Index structures
  118085. ** representing the indexes maintained by the current FTS table. FTS tables
  118086. ** always maintain the main "terms" index, but may also maintain one or
  118087. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  118088. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  118089. **
  118090. ** Argument zParam is passed the value of the "prefix=" option if one was
  118091. ** specified, or NULL otherwise.
  118092. **
  118093. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  118094. ** the allocated array. *pnIndex is set to the number of elements in the
  118095. ** array. If an error does occur, an SQLite error code is returned.
  118096. **
  118097. ** Regardless of whether or not an error is returned, it is the responsibility
  118098. ** of the caller to call sqlite3_free() on the output array to free it.
  118099. */
  118100. static int fts3PrefixParameter(
  118101. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  118102. int *pnIndex, /* OUT: size of *apIndex[] array */
  118103. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  118104. ){
  118105. struct Fts3Index *aIndex; /* Allocated array */
  118106. int nIndex = 1; /* Number of entries in array */
  118107. if( zParam && zParam[0] ){
  118108. const char *p;
  118109. nIndex++;
  118110. for(p=zParam; *p; p++){
  118111. if( *p==',' ) nIndex++;
  118112. }
  118113. }
  118114. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  118115. *apIndex = aIndex;
  118116. *pnIndex = nIndex;
  118117. if( !aIndex ){
  118118. return SQLITE_NOMEM;
  118119. }
  118120. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  118121. if( zParam ){
  118122. const char *p = zParam;
  118123. int i;
  118124. for(i=1; i<nIndex; i++){
  118125. int nPrefix;
  118126. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  118127. aIndex[i].nPrefix = nPrefix;
  118128. p++;
  118129. }
  118130. }
  118131. return SQLITE_OK;
  118132. }
  118133. /*
  118134. ** This function is called when initializing an FTS4 table that uses the
  118135. ** content=xxx option. It determines the number of and names of the columns
  118136. ** of the new FTS4 table.
  118137. **
  118138. ** The third argument passed to this function is the value passed to the
  118139. ** config=xxx option (i.e. "xxx"). This function queries the database for
  118140. ** a table of that name. If found, the output variables are populated
  118141. ** as follows:
  118142. **
  118143. ** *pnCol: Set to the number of columns table xxx has,
  118144. **
  118145. ** *pnStr: Set to the total amount of space required to store a copy
  118146. ** of each columns name, including the nul-terminator.
  118147. **
  118148. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  118149. ** the name of the corresponding column in table xxx. The array
  118150. ** and its contents are allocated using a single allocation. It
  118151. ** is the responsibility of the caller to free this allocation
  118152. ** by eventually passing the *pazCol value to sqlite3_free().
  118153. **
  118154. ** If the table cannot be found, an error code is returned and the output
  118155. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  118156. ** returned (and the output variables are undefined).
  118157. */
  118158. static int fts3ContentColumns(
  118159. sqlite3 *db, /* Database handle */
  118160. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  118161. const char *zTbl, /* Name of content table */
  118162. const char ***pazCol, /* OUT: Malloc'd array of column names */
  118163. int *pnCol, /* OUT: Size of array *pazCol */
  118164. int *pnStr /* OUT: Bytes of string content */
  118165. ){
  118166. int rc = SQLITE_OK; /* Return code */
  118167. char *zSql; /* "SELECT *" statement on zTbl */
  118168. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  118169. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  118170. if( !zSql ){
  118171. rc = SQLITE_NOMEM;
  118172. }else{
  118173. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  118174. }
  118175. sqlite3_free(zSql);
  118176. if( rc==SQLITE_OK ){
  118177. const char **azCol; /* Output array */
  118178. int nStr = 0; /* Size of all column names (incl. 0x00) */
  118179. int nCol; /* Number of table columns */
  118180. int i; /* Used to iterate through columns */
  118181. /* Loop through the returned columns. Set nStr to the number of bytes of
  118182. ** space required to store a copy of each column name, including the
  118183. ** nul-terminator byte. */
  118184. nCol = sqlite3_column_count(pStmt);
  118185. for(i=0; i<nCol; i++){
  118186. const char *zCol = sqlite3_column_name(pStmt, i);
  118187. nStr += (int)strlen(zCol) + 1;
  118188. }
  118189. /* Allocate and populate the array to return. */
  118190. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  118191. if( azCol==0 ){
  118192. rc = SQLITE_NOMEM;
  118193. }else{
  118194. char *p = (char *)&azCol[nCol];
  118195. for(i=0; i<nCol; i++){
  118196. const char *zCol = sqlite3_column_name(pStmt, i);
  118197. int n = (int)strlen(zCol)+1;
  118198. memcpy(p, zCol, n);
  118199. azCol[i] = p;
  118200. p += n;
  118201. }
  118202. }
  118203. sqlite3_finalize(pStmt);
  118204. /* Set the output variables. */
  118205. *pnCol = nCol;
  118206. *pnStr = nStr;
  118207. *pazCol = azCol;
  118208. }
  118209. return rc;
  118210. }
  118211. /*
  118212. ** This function is the implementation of both the xConnect and xCreate
  118213. ** methods of the FTS3 virtual table.
  118214. **
  118215. ** The argv[] array contains the following:
  118216. **
  118217. ** argv[0] -> module name ("fts3" or "fts4")
  118218. ** argv[1] -> database name
  118219. ** argv[2] -> table name
  118220. ** argv[...] -> "column name" and other module argument fields.
  118221. */
  118222. static int fts3InitVtab(
  118223. int isCreate, /* True for xCreate, false for xConnect */
  118224. sqlite3 *db, /* The SQLite database connection */
  118225. void *pAux, /* Hash table containing tokenizers */
  118226. int argc, /* Number of elements in argv array */
  118227. const char * const *argv, /* xCreate/xConnect argument array */
  118228. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  118229. char **pzErr /* Write any error message here */
  118230. ){
  118231. Fts3Hash *pHash = (Fts3Hash *)pAux;
  118232. Fts3Table *p = 0; /* Pointer to allocated vtab */
  118233. int rc = SQLITE_OK; /* Return code */
  118234. int i; /* Iterator variable */
  118235. int nByte; /* Size of allocation used for *p */
  118236. int iCol; /* Column index */
  118237. int nString = 0; /* Bytes required to hold all column names */
  118238. int nCol = 0; /* Number of columns in the FTS table */
  118239. char *zCsr; /* Space for holding column names */
  118240. int nDb; /* Bytes required to hold database name */
  118241. int nName; /* Bytes required to hold table name */
  118242. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  118243. const char **aCol; /* Array of column names */
  118244. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  118245. int nIndex; /* Size of aIndex[] array */
  118246. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  118247. /* The results of parsing supported FTS4 key=value options: */
  118248. int bNoDocsize = 0; /* True to omit %_docsize table */
  118249. int bDescIdx = 0; /* True to store descending indexes */
  118250. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  118251. char *zCompress = 0; /* compress=? parameter (or NULL) */
  118252. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  118253. char *zContent = 0; /* content=? parameter (or NULL) */
  118254. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  118255. char **azNotindexed = 0; /* The set of notindexed= columns */
  118256. int nNotindexed = 0; /* Size of azNotindexed[] array */
  118257. assert( strlen(argv[0])==4 );
  118258. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  118259. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  118260. );
  118261. nDb = (int)strlen(argv[1]) + 1;
  118262. nName = (int)strlen(argv[2]) + 1;
  118263. nByte = sizeof(const char *) * (argc-2);
  118264. aCol = (const char **)sqlite3_malloc(nByte);
  118265. if( aCol ){
  118266. memset((void*)aCol, 0, nByte);
  118267. azNotindexed = (char **)sqlite3_malloc(nByte);
  118268. }
  118269. if( azNotindexed ){
  118270. memset(azNotindexed, 0, nByte);
  118271. }
  118272. if( !aCol || !azNotindexed ){
  118273. rc = SQLITE_NOMEM;
  118274. goto fts3_init_out;
  118275. }
  118276. /* Loop through all of the arguments passed by the user to the FTS3/4
  118277. ** module (i.e. all the column names and special arguments). This loop
  118278. ** does the following:
  118279. **
  118280. ** + Figures out the number of columns the FTSX table will have, and
  118281. ** the number of bytes of space that must be allocated to store copies
  118282. ** of the column names.
  118283. **
  118284. ** + If there is a tokenizer specification included in the arguments,
  118285. ** initializes the tokenizer pTokenizer.
  118286. */
  118287. for(i=3; rc==SQLITE_OK && i<argc; i++){
  118288. char const *z = argv[i];
  118289. int nKey;
  118290. char *zVal;
  118291. /* Check if this is a tokenizer specification */
  118292. if( !pTokenizer
  118293. && strlen(z)>8
  118294. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  118295. && 0==sqlite3Fts3IsIdChar(z[8])
  118296. ){
  118297. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  118298. }
  118299. /* Check if it is an FTS4 special argument. */
  118300. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  118301. struct Fts4Option {
  118302. const char *zOpt;
  118303. int nOpt;
  118304. } aFts4Opt[] = {
  118305. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  118306. { "prefix", 6 }, /* 1 -> PREFIX */
  118307. { "compress", 8 }, /* 2 -> COMPRESS */
  118308. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  118309. { "order", 5 }, /* 4 -> ORDER */
  118310. { "content", 7 }, /* 5 -> CONTENT */
  118311. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  118312. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  118313. };
  118314. int iOpt;
  118315. if( !zVal ){
  118316. rc = SQLITE_NOMEM;
  118317. }else{
  118318. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  118319. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  118320. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  118321. break;
  118322. }
  118323. }
  118324. if( iOpt==SizeofArray(aFts4Opt) ){
  118325. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  118326. rc = SQLITE_ERROR;
  118327. }else{
  118328. switch( iOpt ){
  118329. case 0: /* MATCHINFO */
  118330. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  118331. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  118332. rc = SQLITE_ERROR;
  118333. }
  118334. bNoDocsize = 1;
  118335. break;
  118336. case 1: /* PREFIX */
  118337. sqlite3_free(zPrefix);
  118338. zPrefix = zVal;
  118339. zVal = 0;
  118340. break;
  118341. case 2: /* COMPRESS */
  118342. sqlite3_free(zCompress);
  118343. zCompress = zVal;
  118344. zVal = 0;
  118345. break;
  118346. case 3: /* UNCOMPRESS */
  118347. sqlite3_free(zUncompress);
  118348. zUncompress = zVal;
  118349. zVal = 0;
  118350. break;
  118351. case 4: /* ORDER */
  118352. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  118353. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  118354. ){
  118355. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  118356. rc = SQLITE_ERROR;
  118357. }
  118358. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  118359. break;
  118360. case 5: /* CONTENT */
  118361. sqlite3_free(zContent);
  118362. zContent = zVal;
  118363. zVal = 0;
  118364. break;
  118365. case 6: /* LANGUAGEID */
  118366. assert( iOpt==6 );
  118367. sqlite3_free(zLanguageid);
  118368. zLanguageid = zVal;
  118369. zVal = 0;
  118370. break;
  118371. case 7: /* NOTINDEXED */
  118372. azNotindexed[nNotindexed++] = zVal;
  118373. zVal = 0;
  118374. break;
  118375. }
  118376. }
  118377. sqlite3_free(zVal);
  118378. }
  118379. }
  118380. /* Otherwise, the argument is a column name. */
  118381. else {
  118382. nString += (int)(strlen(z) + 1);
  118383. aCol[nCol++] = z;
  118384. }
  118385. }
  118386. /* If a content=xxx option was specified, the following:
  118387. **
  118388. ** 1. Ignore any compress= and uncompress= options.
  118389. **
  118390. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  118391. ** TABLE statement, use all columns from the content table.
  118392. */
  118393. if( rc==SQLITE_OK && zContent ){
  118394. sqlite3_free(zCompress);
  118395. sqlite3_free(zUncompress);
  118396. zCompress = 0;
  118397. zUncompress = 0;
  118398. if( nCol==0 ){
  118399. sqlite3_free((void*)aCol);
  118400. aCol = 0;
  118401. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  118402. /* If a languageid= option was specified, remove the language id
  118403. ** column from the aCol[] array. */
  118404. if( rc==SQLITE_OK && zLanguageid ){
  118405. int j;
  118406. for(j=0; j<nCol; j++){
  118407. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  118408. int k;
  118409. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  118410. nCol--;
  118411. break;
  118412. }
  118413. }
  118414. }
  118415. }
  118416. }
  118417. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118418. if( nCol==0 ){
  118419. assert( nString==0 );
  118420. aCol[0] = "content";
  118421. nString = 8;
  118422. nCol = 1;
  118423. }
  118424. if( pTokenizer==0 ){
  118425. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  118426. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118427. }
  118428. assert( pTokenizer );
  118429. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  118430. if( rc==SQLITE_ERROR ){
  118431. assert( zPrefix );
  118432. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  118433. }
  118434. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118435. /* Allocate and populate the Fts3Table structure. */
  118436. nByte = sizeof(Fts3Table) + /* Fts3Table */
  118437. nCol * sizeof(char *) + /* azColumn */
  118438. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  118439. nCol * sizeof(u8) + /* abNotindexed */
  118440. nName + /* zName */
  118441. nDb + /* zDb */
  118442. nString; /* Space for azColumn strings */
  118443. p = (Fts3Table*)sqlite3_malloc(nByte);
  118444. if( p==0 ){
  118445. rc = SQLITE_NOMEM;
  118446. goto fts3_init_out;
  118447. }
  118448. memset(p, 0, nByte);
  118449. p->db = db;
  118450. p->nColumn = nCol;
  118451. p->nPendingData = 0;
  118452. p->azColumn = (char **)&p[1];
  118453. p->pTokenizer = pTokenizer;
  118454. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  118455. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  118456. p->bHasStat = isFts4;
  118457. p->bFts4 = isFts4;
  118458. p->bDescIdx = bDescIdx;
  118459. p->bAutoincrmerge = 0xff; /* 0xff means setting unknown */
  118460. p->zContentTbl = zContent;
  118461. p->zLanguageid = zLanguageid;
  118462. zContent = 0;
  118463. zLanguageid = 0;
  118464. TESTONLY( p->inTransaction = -1 );
  118465. TESTONLY( p->mxSavepoint = -1 );
  118466. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  118467. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  118468. p->nIndex = nIndex;
  118469. for(i=0; i<nIndex; i++){
  118470. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  118471. }
  118472. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  118473. /* Fill in the zName and zDb fields of the vtab structure. */
  118474. zCsr = (char *)&p->abNotindexed[nCol];
  118475. p->zName = zCsr;
  118476. memcpy(zCsr, argv[2], nName);
  118477. zCsr += nName;
  118478. p->zDb = zCsr;
  118479. memcpy(zCsr, argv[1], nDb);
  118480. zCsr += nDb;
  118481. /* Fill in the azColumn array */
  118482. for(iCol=0; iCol<nCol; iCol++){
  118483. char *z;
  118484. int n = 0;
  118485. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  118486. memcpy(zCsr, z, n);
  118487. zCsr[n] = '\0';
  118488. sqlite3Fts3Dequote(zCsr);
  118489. p->azColumn[iCol] = zCsr;
  118490. zCsr += n+1;
  118491. assert( zCsr <= &((char *)p)[nByte] );
  118492. }
  118493. /* Fill in the abNotindexed array */
  118494. for(iCol=0; iCol<nCol; iCol++){
  118495. int n = (int)strlen(p->azColumn[iCol]);
  118496. for(i=0; i<nNotindexed; i++){
  118497. char *zNot = azNotindexed[i];
  118498. if( zNot && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) ){
  118499. p->abNotindexed[iCol] = 1;
  118500. sqlite3_free(zNot);
  118501. azNotindexed[i] = 0;
  118502. }
  118503. }
  118504. }
  118505. for(i=0; i<nNotindexed; i++){
  118506. if( azNotindexed[i] ){
  118507. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  118508. rc = SQLITE_ERROR;
  118509. }
  118510. }
  118511. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  118512. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  118513. rc = SQLITE_ERROR;
  118514. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  118515. }
  118516. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  118517. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  118518. if( rc!=SQLITE_OK ) goto fts3_init_out;
  118519. /* If this is an xCreate call, create the underlying tables in the
  118520. ** database. TODO: For xConnect(), it could verify that said tables exist.
  118521. */
  118522. if( isCreate ){
  118523. rc = fts3CreateTables(p);
  118524. }
  118525. /* Check to see if a legacy fts3 table has been "upgraded" by the
  118526. ** addition of a %_stat table so that it can use incremental merge.
  118527. */
  118528. if( !isFts4 && !isCreate ){
  118529. int rc2 = SQLITE_OK;
  118530. fts3DbExec(&rc2, db, "SELECT 1 FROM %Q.'%q_stat' WHERE id=2",
  118531. p->zDb, p->zName);
  118532. if( rc2==SQLITE_OK ) p->bHasStat = 1;
  118533. }
  118534. /* Figure out the page-size for the database. This is required in order to
  118535. ** estimate the cost of loading large doclists from the database. */
  118536. fts3DatabasePageSize(&rc, p);
  118537. p->nNodeSize = p->nPgsz-35;
  118538. /* Declare the table schema to SQLite. */
  118539. fts3DeclareVtab(&rc, p);
  118540. fts3_init_out:
  118541. sqlite3_free(zPrefix);
  118542. sqlite3_free(aIndex);
  118543. sqlite3_free(zCompress);
  118544. sqlite3_free(zUncompress);
  118545. sqlite3_free(zContent);
  118546. sqlite3_free(zLanguageid);
  118547. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  118548. sqlite3_free((void *)aCol);
  118549. sqlite3_free((void *)azNotindexed);
  118550. if( rc!=SQLITE_OK ){
  118551. if( p ){
  118552. fts3DisconnectMethod((sqlite3_vtab *)p);
  118553. }else if( pTokenizer ){
  118554. pTokenizer->pModule->xDestroy(pTokenizer);
  118555. }
  118556. }else{
  118557. assert( p->pSegments==0 );
  118558. *ppVTab = &p->base;
  118559. }
  118560. return rc;
  118561. }
  118562. /*
  118563. ** The xConnect() and xCreate() methods for the virtual table. All the
  118564. ** work is done in function fts3InitVtab().
  118565. */
  118566. static int fts3ConnectMethod(
  118567. sqlite3 *db, /* Database connection */
  118568. void *pAux, /* Pointer to tokenizer hash table */
  118569. int argc, /* Number of elements in argv array */
  118570. const char * const *argv, /* xCreate/xConnect argument array */
  118571. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  118572. char **pzErr /* OUT: sqlite3_malloc'd error message */
  118573. ){
  118574. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  118575. }
  118576. static int fts3CreateMethod(
  118577. sqlite3 *db, /* Database connection */
  118578. void *pAux, /* Pointer to tokenizer hash table */
  118579. int argc, /* Number of elements in argv array */
  118580. const char * const *argv, /* xCreate/xConnect argument array */
  118581. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  118582. char **pzErr /* OUT: sqlite3_malloc'd error message */
  118583. ){
  118584. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  118585. }
  118586. /*
  118587. ** Implementation of the xBestIndex method for FTS3 tables. There
  118588. ** are three possible strategies, in order of preference:
  118589. **
  118590. ** 1. Direct lookup by rowid or docid.
  118591. ** 2. Full-text search using a MATCH operator on a non-docid column.
  118592. ** 3. Linear scan of %_content table.
  118593. */
  118594. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  118595. Fts3Table *p = (Fts3Table *)pVTab;
  118596. int i; /* Iterator variable */
  118597. int iCons = -1; /* Index of constraint to use */
  118598. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  118599. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  118600. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  118601. int iIdx;
  118602. /* By default use a full table scan. This is an expensive option,
  118603. ** so search through the constraints to see if a more efficient
  118604. ** strategy is possible.
  118605. */
  118606. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  118607. pInfo->estimatedCost = 5000000;
  118608. for(i=0; i<pInfo->nConstraint; i++){
  118609. int bDocid; /* True if this constraint is on docid */
  118610. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  118611. if( pCons->usable==0 ) continue;
  118612. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  118613. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  118614. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  118615. pInfo->idxNum = FTS3_DOCID_SEARCH;
  118616. pInfo->estimatedCost = 1.0;
  118617. iCons = i;
  118618. }
  118619. /* A MATCH constraint. Use a full-text search.
  118620. **
  118621. ** If there is more than one MATCH constraint available, use the first
  118622. ** one encountered. If there is both a MATCH constraint and a direct
  118623. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  118624. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  118625. ** it would lead to an "unable to use function MATCH in the requested
  118626. ** context" error.
  118627. */
  118628. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  118629. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  118630. ){
  118631. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  118632. pInfo->estimatedCost = 2.0;
  118633. iCons = i;
  118634. }
  118635. /* Equality constraint on the langid column */
  118636. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  118637. && pCons->iColumn==p->nColumn + 2
  118638. ){
  118639. iLangidCons = i;
  118640. }
  118641. if( bDocid ){
  118642. switch( pCons->op ){
  118643. case SQLITE_INDEX_CONSTRAINT_GE:
  118644. case SQLITE_INDEX_CONSTRAINT_GT:
  118645. iDocidGe = i;
  118646. break;
  118647. case SQLITE_INDEX_CONSTRAINT_LE:
  118648. case SQLITE_INDEX_CONSTRAINT_LT:
  118649. iDocidLe = i;
  118650. break;
  118651. }
  118652. }
  118653. }
  118654. iIdx = 1;
  118655. if( iCons>=0 ){
  118656. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  118657. pInfo->aConstraintUsage[iCons].omit = 1;
  118658. }
  118659. if( iLangidCons>=0 ){
  118660. pInfo->idxNum |= FTS3_HAVE_LANGID;
  118661. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  118662. }
  118663. if( iDocidGe>=0 ){
  118664. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  118665. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  118666. }
  118667. if( iDocidLe>=0 ){
  118668. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  118669. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  118670. }
  118671. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  118672. ** docid) order. Both ascending and descending are possible.
  118673. */
  118674. if( pInfo->nOrderBy==1 ){
  118675. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  118676. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  118677. if( pOrder->desc ){
  118678. pInfo->idxStr = "DESC";
  118679. }else{
  118680. pInfo->idxStr = "ASC";
  118681. }
  118682. pInfo->orderByConsumed = 1;
  118683. }
  118684. }
  118685. assert( p->pSegments==0 );
  118686. return SQLITE_OK;
  118687. }
  118688. /*
  118689. ** Implementation of xOpen method.
  118690. */
  118691. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  118692. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  118693. UNUSED_PARAMETER(pVTab);
  118694. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  118695. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  118696. ** if the allocation fails, return SQLITE_NOMEM.
  118697. */
  118698. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  118699. if( !pCsr ){
  118700. return SQLITE_NOMEM;
  118701. }
  118702. memset(pCsr, 0, sizeof(Fts3Cursor));
  118703. return SQLITE_OK;
  118704. }
  118705. /*
  118706. ** Close the cursor. For additional information see the documentation
  118707. ** on the xClose method of the virtual table interface.
  118708. */
  118709. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  118710. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  118711. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  118712. sqlite3_finalize(pCsr->pStmt);
  118713. sqlite3Fts3ExprFree(pCsr->pExpr);
  118714. sqlite3Fts3FreeDeferredTokens(pCsr);
  118715. sqlite3_free(pCsr->aDoclist);
  118716. sqlite3_free(pCsr->aMatchinfo);
  118717. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  118718. sqlite3_free(pCsr);
  118719. return SQLITE_OK;
  118720. }
  118721. /*
  118722. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  118723. ** compose and prepare an SQL statement of the form:
  118724. **
  118725. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  118726. **
  118727. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  118728. ** it. If an error occurs, return an SQLite error code.
  118729. **
  118730. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  118731. */
  118732. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  118733. int rc = SQLITE_OK;
  118734. if( pCsr->pStmt==0 ){
  118735. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  118736. char *zSql;
  118737. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  118738. if( !zSql ) return SQLITE_NOMEM;
  118739. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  118740. sqlite3_free(zSql);
  118741. }
  118742. *ppStmt = pCsr->pStmt;
  118743. return rc;
  118744. }
  118745. /*
  118746. ** Position the pCsr->pStmt statement so that it is on the row
  118747. ** of the %_content table that contains the last match. Return
  118748. ** SQLITE_OK on success.
  118749. */
  118750. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  118751. int rc = SQLITE_OK;
  118752. if( pCsr->isRequireSeek ){
  118753. sqlite3_stmt *pStmt = 0;
  118754. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  118755. if( rc==SQLITE_OK ){
  118756. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  118757. pCsr->isRequireSeek = 0;
  118758. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  118759. return SQLITE_OK;
  118760. }else{
  118761. rc = sqlite3_reset(pCsr->pStmt);
  118762. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  118763. /* If no row was found and no error has occurred, then the %_content
  118764. ** table is missing a row that is present in the full-text index.
  118765. ** The data structures are corrupt. */
  118766. rc = FTS_CORRUPT_VTAB;
  118767. pCsr->isEof = 1;
  118768. }
  118769. }
  118770. }
  118771. }
  118772. if( rc!=SQLITE_OK && pContext ){
  118773. sqlite3_result_error_code(pContext, rc);
  118774. }
  118775. return rc;
  118776. }
  118777. /*
  118778. ** This function is used to process a single interior node when searching
  118779. ** a b-tree for a term or term prefix. The node data is passed to this
  118780. ** function via the zNode/nNode parameters. The term to search for is
  118781. ** passed in zTerm/nTerm.
  118782. **
  118783. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  118784. ** of the child node that heads the sub-tree that may contain the term.
  118785. **
  118786. ** If piLast is not NULL, then *piLast is set to the right-most child node
  118787. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  118788. ** a prefix.
  118789. **
  118790. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  118791. */
  118792. static int fts3ScanInteriorNode(
  118793. const char *zTerm, /* Term to select leaves for */
  118794. int nTerm, /* Size of term zTerm in bytes */
  118795. const char *zNode, /* Buffer containing segment interior node */
  118796. int nNode, /* Size of buffer at zNode */
  118797. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  118798. sqlite3_int64 *piLast /* OUT: Selected child node */
  118799. ){
  118800. int rc = SQLITE_OK; /* Return code */
  118801. const char *zCsr = zNode; /* Cursor to iterate through node */
  118802. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  118803. char *zBuffer = 0; /* Buffer to load terms into */
  118804. int nAlloc = 0; /* Size of allocated buffer */
  118805. int isFirstTerm = 1; /* True when processing first term on page */
  118806. sqlite3_int64 iChild; /* Block id of child node to descend to */
  118807. /* Skip over the 'height' varint that occurs at the start of every
  118808. ** interior node. Then load the blockid of the left-child of the b-tree
  118809. ** node into variable iChild.
  118810. **
  118811. ** Even if the data structure on disk is corrupted, this (reading two
  118812. ** varints from the buffer) does not risk an overread. If zNode is a
  118813. ** root node, then the buffer comes from a SELECT statement. SQLite does
  118814. ** not make this guarantee explicitly, but in practice there are always
  118815. ** either more than 20 bytes of allocated space following the nNode bytes of
  118816. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  118817. ** table, then there are always 20 bytes of zeroed padding following the
  118818. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  118819. */
  118820. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  118821. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  118822. if( zCsr>zEnd ){
  118823. return FTS_CORRUPT_VTAB;
  118824. }
  118825. while( zCsr<zEnd && (piFirst || piLast) ){
  118826. int cmp; /* memcmp() result */
  118827. int nSuffix; /* Size of term suffix */
  118828. int nPrefix = 0; /* Size of term prefix */
  118829. int nBuffer; /* Total term size */
  118830. /* Load the next term on the node into zBuffer. Use realloc() to expand
  118831. ** the size of zBuffer if required. */
  118832. if( !isFirstTerm ){
  118833. zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
  118834. }
  118835. isFirstTerm = 0;
  118836. zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
  118837. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  118838. rc = FTS_CORRUPT_VTAB;
  118839. goto finish_scan;
  118840. }
  118841. if( nPrefix+nSuffix>nAlloc ){
  118842. char *zNew;
  118843. nAlloc = (nPrefix+nSuffix) * 2;
  118844. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  118845. if( !zNew ){
  118846. rc = SQLITE_NOMEM;
  118847. goto finish_scan;
  118848. }
  118849. zBuffer = zNew;
  118850. }
  118851. assert( zBuffer );
  118852. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  118853. nBuffer = nPrefix + nSuffix;
  118854. zCsr += nSuffix;
  118855. /* Compare the term we are searching for with the term just loaded from
  118856. ** the interior node. If the specified term is greater than or equal
  118857. ** to the term from the interior node, then all terms on the sub-tree
  118858. ** headed by node iChild are smaller than zTerm. No need to search
  118859. ** iChild.
  118860. **
  118861. ** If the interior node term is larger than the specified term, then
  118862. ** the tree headed by iChild may contain the specified term.
  118863. */
  118864. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  118865. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  118866. *piFirst = iChild;
  118867. piFirst = 0;
  118868. }
  118869. if( piLast && cmp<0 ){
  118870. *piLast = iChild;
  118871. piLast = 0;
  118872. }
  118873. iChild++;
  118874. };
  118875. if( piFirst ) *piFirst = iChild;
  118876. if( piLast ) *piLast = iChild;
  118877. finish_scan:
  118878. sqlite3_free(zBuffer);
  118879. return rc;
  118880. }
  118881. /*
  118882. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  118883. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  118884. ** contains a term. This function searches the sub-tree headed by the zNode
  118885. ** node for the range of leaf nodes that may contain the specified term
  118886. ** or terms for which the specified term is a prefix.
  118887. **
  118888. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  118889. ** left-most leaf node in the tree that may contain the specified term.
  118890. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  118891. ** right-most leaf node that may contain a term for which the specified
  118892. ** term is a prefix.
  118893. **
  118894. ** It is possible that the range of returned leaf nodes does not contain
  118895. ** the specified term or any terms for which it is a prefix. However, if the
  118896. ** segment does contain any such terms, they are stored within the identified
  118897. ** range. Because this function only inspects interior segment nodes (and
  118898. ** never loads leaf nodes into memory), it is not possible to be sure.
  118899. **
  118900. ** If an error occurs, an error code other than SQLITE_OK is returned.
  118901. */
  118902. static int fts3SelectLeaf(
  118903. Fts3Table *p, /* Virtual table handle */
  118904. const char *zTerm, /* Term to select leaves for */
  118905. int nTerm, /* Size of term zTerm in bytes */
  118906. const char *zNode, /* Buffer containing segment interior node */
  118907. int nNode, /* Size of buffer at zNode */
  118908. sqlite3_int64 *piLeaf, /* Selected leaf node */
  118909. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  118910. ){
  118911. int rc; /* Return code */
  118912. int iHeight; /* Height of this node in tree */
  118913. assert( piLeaf || piLeaf2 );
  118914. sqlite3Fts3GetVarint32(zNode, &iHeight);
  118915. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  118916. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  118917. if( rc==SQLITE_OK && iHeight>1 ){
  118918. char *zBlob = 0; /* Blob read from %_segments table */
  118919. int nBlob; /* Size of zBlob in bytes */
  118920. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  118921. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  118922. if( rc==SQLITE_OK ){
  118923. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  118924. }
  118925. sqlite3_free(zBlob);
  118926. piLeaf = 0;
  118927. zBlob = 0;
  118928. }
  118929. if( rc==SQLITE_OK ){
  118930. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  118931. }
  118932. if( rc==SQLITE_OK ){
  118933. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  118934. }
  118935. sqlite3_free(zBlob);
  118936. }
  118937. return rc;
  118938. }
  118939. /*
  118940. ** This function is used to create delta-encoded serialized lists of FTS3
  118941. ** varints. Each call to this function appends a single varint to a list.
  118942. */
  118943. static void fts3PutDeltaVarint(
  118944. char **pp, /* IN/OUT: Output pointer */
  118945. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  118946. sqlite3_int64 iVal /* Write this value to the list */
  118947. ){
  118948. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  118949. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  118950. *piPrev = iVal;
  118951. }
  118952. /*
  118953. ** When this function is called, *ppPoslist is assumed to point to the
  118954. ** start of a position-list. After it returns, *ppPoslist points to the
  118955. ** first byte after the position-list.
  118956. **
  118957. ** A position list is list of positions (delta encoded) and columns for
  118958. ** a single document record of a doclist. So, in other words, this
  118959. ** routine advances *ppPoslist so that it points to the next docid in
  118960. ** the doclist, or to the first byte past the end of the doclist.
  118961. **
  118962. ** If pp is not NULL, then the contents of the position list are copied
  118963. ** to *pp. *pp is set to point to the first byte past the last byte copied
  118964. ** before this function returns.
  118965. */
  118966. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  118967. char *pEnd = *ppPoslist;
  118968. char c = 0;
  118969. /* The end of a position list is marked by a zero encoded as an FTS3
  118970. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  118971. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  118972. ** of some other, multi-byte, value.
  118973. **
  118974. ** The following while-loop moves pEnd to point to the first byte that is not
  118975. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  118976. ** pEnd once more so that it points to the byte immediately following the
  118977. ** last byte in the position-list.
  118978. */
  118979. while( *pEnd | c ){
  118980. c = *pEnd++ & 0x80;
  118981. testcase( c!=0 && (*pEnd)==0 );
  118982. }
  118983. pEnd++; /* Advance past the POS_END terminator byte */
  118984. if( pp ){
  118985. int n = (int)(pEnd - *ppPoslist);
  118986. char *p = *pp;
  118987. memcpy(p, *ppPoslist, n);
  118988. p += n;
  118989. *pp = p;
  118990. }
  118991. *ppPoslist = pEnd;
  118992. }
  118993. /*
  118994. ** When this function is called, *ppPoslist is assumed to point to the
  118995. ** start of a column-list. After it returns, *ppPoslist points to the
  118996. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  118997. **
  118998. ** A column-list is list of delta-encoded positions for a single column
  118999. ** within a single document within a doclist.
  119000. **
  119001. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  119002. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  119003. ** the POS_COLUMN or POS_END that terminates the column-list.
  119004. **
  119005. ** If pp is not NULL, then the contents of the column-list are copied
  119006. ** to *pp. *pp is set to point to the first byte past the last byte copied
  119007. ** before this function returns. The POS_COLUMN or POS_END terminator
  119008. ** is not copied into *pp.
  119009. */
  119010. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  119011. char *pEnd = *ppPoslist;
  119012. char c = 0;
  119013. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  119014. ** not part of a multi-byte varint.
  119015. */
  119016. while( 0xFE & (*pEnd | c) ){
  119017. c = *pEnd++ & 0x80;
  119018. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  119019. }
  119020. if( pp ){
  119021. int n = (int)(pEnd - *ppPoslist);
  119022. char *p = *pp;
  119023. memcpy(p, *ppPoslist, n);
  119024. p += n;
  119025. *pp = p;
  119026. }
  119027. *ppPoslist = pEnd;
  119028. }
  119029. /*
  119030. ** Value used to signify the end of an position-list. This is safe because
  119031. ** it is not possible to have a document with 2^31 terms.
  119032. */
  119033. #define POSITION_LIST_END 0x7fffffff
  119034. /*
  119035. ** This function is used to help parse position-lists. When this function is
  119036. ** called, *pp may point to the start of the next varint in the position-list
  119037. ** being parsed, or it may point to 1 byte past the end of the position-list
  119038. ** (in which case **pp will be a terminator bytes POS_END (0) or
  119039. ** (1)).
  119040. **
  119041. ** If *pp points past the end of the current position-list, set *pi to
  119042. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  119043. ** increment the current value of *pi by the value read, and set *pp to
  119044. ** point to the next value before returning.
  119045. **
  119046. ** Before calling this routine *pi must be initialized to the value of
  119047. ** the previous position, or zero if we are reading the first position
  119048. ** in the position-list. Because positions are delta-encoded, the value
  119049. ** of the previous position is needed in order to compute the value of
  119050. ** the next position.
  119051. */
  119052. static void fts3ReadNextPos(
  119053. char **pp, /* IN/OUT: Pointer into position-list buffer */
  119054. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  119055. ){
  119056. if( (**pp)&0xFE ){
  119057. fts3GetDeltaVarint(pp, pi);
  119058. *pi -= 2;
  119059. }else{
  119060. *pi = POSITION_LIST_END;
  119061. }
  119062. }
  119063. /*
  119064. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  119065. ** the value of iCol encoded as a varint to *pp. This will start a new
  119066. ** column list.
  119067. **
  119068. ** Set *pp to point to the byte just after the last byte written before
  119069. ** returning (do not modify it if iCol==0). Return the total number of bytes
  119070. ** written (0 if iCol==0).
  119071. */
  119072. static int fts3PutColNumber(char **pp, int iCol){
  119073. int n = 0; /* Number of bytes written */
  119074. if( iCol ){
  119075. char *p = *pp; /* Output pointer */
  119076. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  119077. *p = 0x01;
  119078. *pp = &p[n];
  119079. }
  119080. return n;
  119081. }
  119082. /*
  119083. ** Compute the union of two position lists. The output written
  119084. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  119085. ** order and with any duplicates removed. All pointers are
  119086. ** updated appropriately. The caller is responsible for insuring
  119087. ** that there is enough space in *pp to hold the complete output.
  119088. */
  119089. static void fts3PoslistMerge(
  119090. char **pp, /* Output buffer */
  119091. char **pp1, /* Left input list */
  119092. char **pp2 /* Right input list */
  119093. ){
  119094. char *p = *pp;
  119095. char *p1 = *pp1;
  119096. char *p2 = *pp2;
  119097. while( *p1 || *p2 ){
  119098. int iCol1; /* The current column index in pp1 */
  119099. int iCol2; /* The current column index in pp2 */
  119100. if( *p1==POS_COLUMN ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
  119101. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  119102. else iCol1 = 0;
  119103. if( *p2==POS_COLUMN ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
  119104. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  119105. else iCol2 = 0;
  119106. if( iCol1==iCol2 ){
  119107. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  119108. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  119109. sqlite3_int64 iPrev = 0;
  119110. int n = fts3PutColNumber(&p, iCol1);
  119111. p1 += n;
  119112. p2 += n;
  119113. /* At this point, both p1 and p2 point to the start of column-lists
  119114. ** for the same column (the column with index iCol1 and iCol2).
  119115. ** A column-list is a list of non-negative delta-encoded varints, each
  119116. ** incremented by 2 before being stored. Each list is terminated by a
  119117. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  119118. ** and writes the results to buffer p. p is left pointing to the byte
  119119. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  119120. ** written to the output.
  119121. */
  119122. fts3GetDeltaVarint(&p1, &i1);
  119123. fts3GetDeltaVarint(&p2, &i2);
  119124. do {
  119125. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  119126. iPrev -= 2;
  119127. if( i1==i2 ){
  119128. fts3ReadNextPos(&p1, &i1);
  119129. fts3ReadNextPos(&p2, &i2);
  119130. }else if( i1<i2 ){
  119131. fts3ReadNextPos(&p1, &i1);
  119132. }else{
  119133. fts3ReadNextPos(&p2, &i2);
  119134. }
  119135. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  119136. }else if( iCol1<iCol2 ){
  119137. p1 += fts3PutColNumber(&p, iCol1);
  119138. fts3ColumnlistCopy(&p, &p1);
  119139. }else{
  119140. p2 += fts3PutColNumber(&p, iCol2);
  119141. fts3ColumnlistCopy(&p, &p2);
  119142. }
  119143. }
  119144. *p++ = POS_END;
  119145. *pp = p;
  119146. *pp1 = p1 + 1;
  119147. *pp2 = p2 + 1;
  119148. }
  119149. /*
  119150. ** This function is used to merge two position lists into one. When it is
  119151. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  119152. ** the part of a doclist that follows each document id. For example, if a row
  119153. ** contains:
  119154. **
  119155. ** 'a b c'|'x y z'|'a b b a'
  119156. **
  119157. ** Then the position list for this row for token 'b' would consist of:
  119158. **
  119159. ** 0x02 0x01 0x02 0x03 0x03 0x00
  119160. **
  119161. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  119162. ** byte following the 0x00 terminator of their respective position lists.
  119163. **
  119164. ** If isSaveLeft is 0, an entry is added to the output position list for
  119165. ** each position in *pp2 for which there exists one or more positions in
  119166. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  119167. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  119168. ** slots before it.
  119169. **
  119170. ** e.g. nToken==1 searches for adjacent positions.
  119171. */
  119172. static int fts3PoslistPhraseMerge(
  119173. char **pp, /* IN/OUT: Preallocated output buffer */
  119174. int nToken, /* Maximum difference in token positions */
  119175. int isSaveLeft, /* Save the left position */
  119176. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  119177. char **pp1, /* IN/OUT: Left input list */
  119178. char **pp2 /* IN/OUT: Right input list */
  119179. ){
  119180. char *p = *pp;
  119181. char *p1 = *pp1;
  119182. char *p2 = *pp2;
  119183. int iCol1 = 0;
  119184. int iCol2 = 0;
  119185. /* Never set both isSaveLeft and isExact for the same invocation. */
  119186. assert( isSaveLeft==0 || isExact==0 );
  119187. assert( p!=0 && *p1!=0 && *p2!=0 );
  119188. if( *p1==POS_COLUMN ){
  119189. p1++;
  119190. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119191. }
  119192. if( *p2==POS_COLUMN ){
  119193. p2++;
  119194. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119195. }
  119196. while( 1 ){
  119197. if( iCol1==iCol2 ){
  119198. char *pSave = p;
  119199. sqlite3_int64 iPrev = 0;
  119200. sqlite3_int64 iPos1 = 0;
  119201. sqlite3_int64 iPos2 = 0;
  119202. if( iCol1 ){
  119203. *p++ = POS_COLUMN;
  119204. p += sqlite3Fts3PutVarint(p, iCol1);
  119205. }
  119206. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  119207. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  119208. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  119209. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  119210. while( 1 ){
  119211. if( iPos2==iPos1+nToken
  119212. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  119213. ){
  119214. sqlite3_int64 iSave;
  119215. iSave = isSaveLeft ? iPos1 : iPos2;
  119216. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  119217. pSave = 0;
  119218. assert( p );
  119219. }
  119220. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  119221. if( (*p2&0xFE)==0 ) break;
  119222. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  119223. }else{
  119224. if( (*p1&0xFE)==0 ) break;
  119225. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  119226. }
  119227. }
  119228. if( pSave ){
  119229. assert( pp && p );
  119230. p = pSave;
  119231. }
  119232. fts3ColumnlistCopy(0, &p1);
  119233. fts3ColumnlistCopy(0, &p2);
  119234. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  119235. if( 0==*p1 || 0==*p2 ) break;
  119236. p1++;
  119237. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119238. p2++;
  119239. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119240. }
  119241. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  119242. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  119243. ** end of the position list, or the 0x01 that precedes the next
  119244. ** column-number in the position list.
  119245. */
  119246. else if( iCol1<iCol2 ){
  119247. fts3ColumnlistCopy(0, &p1);
  119248. if( 0==*p1 ) break;
  119249. p1++;
  119250. p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
  119251. }else{
  119252. fts3ColumnlistCopy(0, &p2);
  119253. if( 0==*p2 ) break;
  119254. p2++;
  119255. p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
  119256. }
  119257. }
  119258. fts3PoslistCopy(0, &p2);
  119259. fts3PoslistCopy(0, &p1);
  119260. *pp1 = p1;
  119261. *pp2 = p2;
  119262. if( *pp==p ){
  119263. return 0;
  119264. }
  119265. *p++ = 0x00;
  119266. *pp = p;
  119267. return 1;
  119268. }
  119269. /*
  119270. ** Merge two position-lists as required by the NEAR operator. The argument
  119271. ** position lists correspond to the left and right phrases of an expression
  119272. ** like:
  119273. **
  119274. ** "phrase 1" NEAR "phrase number 2"
  119275. **
  119276. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  119277. ** expression and *pp2 to the right. As usual, the indexes in the position
  119278. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  119279. ** in the example above).
  119280. **
  119281. ** The output position list - written to *pp - is a copy of *pp2 with those
  119282. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  119283. */
  119284. static int fts3PoslistNearMerge(
  119285. char **pp, /* Output buffer */
  119286. char *aTmp, /* Temporary buffer space */
  119287. int nRight, /* Maximum difference in token positions */
  119288. int nLeft, /* Maximum difference in token positions */
  119289. char **pp1, /* IN/OUT: Left input list */
  119290. char **pp2 /* IN/OUT: Right input list */
  119291. ){
  119292. char *p1 = *pp1;
  119293. char *p2 = *pp2;
  119294. char *pTmp1 = aTmp;
  119295. char *pTmp2;
  119296. char *aTmp2;
  119297. int res = 1;
  119298. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  119299. aTmp2 = pTmp2 = pTmp1;
  119300. *pp1 = p1;
  119301. *pp2 = p2;
  119302. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  119303. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  119304. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  119305. }else if( pTmp1!=aTmp ){
  119306. fts3PoslistCopy(pp, &aTmp);
  119307. }else if( pTmp2!=aTmp2 ){
  119308. fts3PoslistCopy(pp, &aTmp2);
  119309. }else{
  119310. res = 0;
  119311. }
  119312. return res;
  119313. }
  119314. /*
  119315. ** An instance of this function is used to merge together the (potentially
  119316. ** large number of) doclists for each term that matches a prefix query.
  119317. ** See function fts3TermSelectMerge() for details.
  119318. */
  119319. typedef struct TermSelect TermSelect;
  119320. struct TermSelect {
  119321. char *aaOutput[16]; /* Malloc'd output buffers */
  119322. int anOutput[16]; /* Size each output buffer in bytes */
  119323. };
  119324. /*
  119325. ** This function is used to read a single varint from a buffer. Parameter
  119326. ** pEnd points 1 byte past the end of the buffer. When this function is
  119327. ** called, if *pp points to pEnd or greater, then the end of the buffer
  119328. ** has been reached. In this case *pp is set to 0 and the function returns.
  119329. **
  119330. ** If *pp does not point to or past pEnd, then a single varint is read
  119331. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  119332. **
  119333. ** If bDescIdx is false, the value read is added to *pVal before returning.
  119334. ** If it is true, the value read is subtracted from *pVal before this
  119335. ** function returns.
  119336. */
  119337. static void fts3GetDeltaVarint3(
  119338. char **pp, /* IN/OUT: Point to read varint from */
  119339. char *pEnd, /* End of buffer */
  119340. int bDescIdx, /* True if docids are descending */
  119341. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  119342. ){
  119343. if( *pp>=pEnd ){
  119344. *pp = 0;
  119345. }else{
  119346. sqlite3_int64 iVal;
  119347. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  119348. if( bDescIdx ){
  119349. *pVal -= iVal;
  119350. }else{
  119351. *pVal += iVal;
  119352. }
  119353. }
  119354. }
  119355. /*
  119356. ** This function is used to write a single varint to a buffer. The varint
  119357. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  119358. ** end of the value written.
  119359. **
  119360. ** If *pbFirst is zero when this function is called, the value written to
  119361. ** the buffer is that of parameter iVal.
  119362. **
  119363. ** If *pbFirst is non-zero when this function is called, then the value
  119364. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  119365. ** (if bDescIdx is non-zero).
  119366. **
  119367. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  119368. ** to the value of parameter iVal.
  119369. */
  119370. static void fts3PutDeltaVarint3(
  119371. char **pp, /* IN/OUT: Output pointer */
  119372. int bDescIdx, /* True for descending docids */
  119373. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  119374. int *pbFirst, /* IN/OUT: True after first int written */
  119375. sqlite3_int64 iVal /* Write this value to the list */
  119376. ){
  119377. sqlite3_int64 iWrite;
  119378. if( bDescIdx==0 || *pbFirst==0 ){
  119379. iWrite = iVal - *piPrev;
  119380. }else{
  119381. iWrite = *piPrev - iVal;
  119382. }
  119383. assert( *pbFirst || *piPrev==0 );
  119384. assert( *pbFirst==0 || iWrite>0 );
  119385. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  119386. *piPrev = iVal;
  119387. *pbFirst = 1;
  119388. }
  119389. /*
  119390. ** This macro is used by various functions that merge doclists. The two
  119391. ** arguments are 64-bit docid values. If the value of the stack variable
  119392. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  119393. ** Otherwise, (i2-i1).
  119394. **
  119395. ** Using this makes it easier to write code that can merge doclists that are
  119396. ** sorted in either ascending or descending order.
  119397. */
  119398. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  119399. /*
  119400. ** This function does an "OR" merge of two doclists (output contains all
  119401. ** positions contained in either argument doclist). If the docids in the
  119402. ** input doclists are sorted in ascending order, parameter bDescDoclist
  119403. ** should be false. If they are sorted in ascending order, it should be
  119404. ** passed a non-zero value.
  119405. **
  119406. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  119407. ** containing the output doclist and SQLITE_OK is returned. In this case
  119408. ** *pnOut is set to the number of bytes in the output doclist.
  119409. **
  119410. ** If an error occurs, an SQLite error code is returned. The output values
  119411. ** are undefined in this case.
  119412. */
  119413. static int fts3DoclistOrMerge(
  119414. int bDescDoclist, /* True if arguments are desc */
  119415. char *a1, int n1, /* First doclist */
  119416. char *a2, int n2, /* Second doclist */
  119417. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  119418. ){
  119419. sqlite3_int64 i1 = 0;
  119420. sqlite3_int64 i2 = 0;
  119421. sqlite3_int64 iPrev = 0;
  119422. char *pEnd1 = &a1[n1];
  119423. char *pEnd2 = &a2[n2];
  119424. char *p1 = a1;
  119425. char *p2 = a2;
  119426. char *p;
  119427. char *aOut;
  119428. int bFirstOut = 0;
  119429. *paOut = 0;
  119430. *pnOut = 0;
  119431. /* Allocate space for the output. Both the input and output doclists
  119432. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  119433. ** then the first docid in each list is simply encoded as a varint. For
  119434. ** each subsequent docid, the varint stored is the difference between the
  119435. ** current and previous docid (a positive number - since the list is in
  119436. ** ascending order).
  119437. **
  119438. ** The first docid written to the output is therefore encoded using the
  119439. ** same number of bytes as it is in whichever of the input lists it is
  119440. ** read from. And each subsequent docid read from the same input list
  119441. ** consumes either the same or less bytes as it did in the input (since
  119442. ** the difference between it and the previous value in the output must
  119443. ** be a positive value less than or equal to the delta value read from
  119444. ** the input list). The same argument applies to all but the first docid
  119445. ** read from the 'other' list. And to the contents of all position lists
  119446. ** that will be copied and merged from the input to the output.
  119447. **
  119448. ** However, if the first docid copied to the output is a negative number,
  119449. ** then the encoding of the first docid from the 'other' input list may
  119450. ** be larger in the output than it was in the input (since the delta value
  119451. ** may be a larger positive integer than the actual docid).
  119452. **
  119453. ** The space required to store the output is therefore the sum of the
  119454. ** sizes of the two inputs, plus enough space for exactly one of the input
  119455. ** docids to grow.
  119456. **
  119457. ** A symetric argument may be made if the doclists are in descending
  119458. ** order.
  119459. */
  119460. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  119461. if( !aOut ) return SQLITE_NOMEM;
  119462. p = aOut;
  119463. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  119464. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  119465. while( p1 || p2 ){
  119466. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  119467. if( p2 && p1 && iDiff==0 ){
  119468. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119469. fts3PoslistMerge(&p, &p1, &p2);
  119470. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119471. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119472. }else if( !p2 || (p1 && iDiff<0) ){
  119473. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119474. fts3PoslistCopy(&p, &p1);
  119475. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119476. }else{
  119477. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  119478. fts3PoslistCopy(&p, &p2);
  119479. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119480. }
  119481. }
  119482. *paOut = aOut;
  119483. *pnOut = (int)(p-aOut);
  119484. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  119485. return SQLITE_OK;
  119486. }
  119487. /*
  119488. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  119489. ** the output contains a copy of each position from the right-hand input
  119490. ** doclist for which there is a position in the left-hand input doclist
  119491. ** exactly nDist tokens before it.
  119492. **
  119493. ** If the docids in the input doclists are sorted in ascending order,
  119494. ** parameter bDescDoclist should be false. If they are sorted in ascending
  119495. ** order, it should be passed a non-zero value.
  119496. **
  119497. ** The right-hand input doclist is overwritten by this function.
  119498. */
  119499. static void fts3DoclistPhraseMerge(
  119500. int bDescDoclist, /* True if arguments are desc */
  119501. int nDist, /* Distance from left to right (1=adjacent) */
  119502. char *aLeft, int nLeft, /* Left doclist */
  119503. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  119504. ){
  119505. sqlite3_int64 i1 = 0;
  119506. sqlite3_int64 i2 = 0;
  119507. sqlite3_int64 iPrev = 0;
  119508. char *pEnd1 = &aLeft[nLeft];
  119509. char *pEnd2 = &aRight[*pnRight];
  119510. char *p1 = aLeft;
  119511. char *p2 = aRight;
  119512. char *p;
  119513. int bFirstOut = 0;
  119514. char *aOut = aRight;
  119515. assert( nDist>0 );
  119516. p = aOut;
  119517. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  119518. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  119519. while( p1 && p2 ){
  119520. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  119521. if( iDiff==0 ){
  119522. char *pSave = p;
  119523. sqlite3_int64 iPrevSave = iPrev;
  119524. int bFirstOutSave = bFirstOut;
  119525. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  119526. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  119527. p = pSave;
  119528. iPrev = iPrevSave;
  119529. bFirstOut = bFirstOutSave;
  119530. }
  119531. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119532. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119533. }else if( iDiff<0 ){
  119534. fts3PoslistCopy(0, &p1);
  119535. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  119536. }else{
  119537. fts3PoslistCopy(0, &p2);
  119538. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  119539. }
  119540. }
  119541. *pnRight = (int)(p - aOut);
  119542. }
  119543. /*
  119544. ** Argument pList points to a position list nList bytes in size. This
  119545. ** function checks to see if the position list contains any entries for
  119546. ** a token in position 0 (of any column). If so, it writes argument iDelta
  119547. ** to the output buffer pOut, followed by a position list consisting only
  119548. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  119549. ** The value returned is the number of bytes written to pOut (if any).
  119550. */
  119551. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  119552. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  119553. char *pList, /* Position list (no 0x00 term) */
  119554. int nList, /* Size of pList in bytes */
  119555. char *pOut /* Write output here */
  119556. ){
  119557. int nOut = 0;
  119558. int bWritten = 0; /* True once iDelta has been written */
  119559. char *p = pList;
  119560. char *pEnd = &pList[nList];
  119561. if( *p!=0x01 ){
  119562. if( *p==0x02 ){
  119563. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  119564. pOut[nOut++] = 0x02;
  119565. bWritten = 1;
  119566. }
  119567. fts3ColumnlistCopy(0, &p);
  119568. }
  119569. while( p<pEnd && *p==0x01 ){
  119570. sqlite3_int64 iCol;
  119571. p++;
  119572. p += sqlite3Fts3GetVarint(p, &iCol);
  119573. if( *p==0x02 ){
  119574. if( bWritten==0 ){
  119575. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  119576. bWritten = 1;
  119577. }
  119578. pOut[nOut++] = 0x01;
  119579. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  119580. pOut[nOut++] = 0x02;
  119581. }
  119582. fts3ColumnlistCopy(0, &p);
  119583. }
  119584. if( bWritten ){
  119585. pOut[nOut++] = 0x00;
  119586. }
  119587. return nOut;
  119588. }
  119589. /*
  119590. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  119591. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  119592. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  119593. **
  119594. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  119595. ** the responsibility of the caller to free any doclists left in the
  119596. ** TermSelect.aaOutput[] array.
  119597. */
  119598. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  119599. char *aOut = 0;
  119600. int nOut = 0;
  119601. int i;
  119602. /* Loop through the doclists in the aaOutput[] array. Merge them all
  119603. ** into a single doclist.
  119604. */
  119605. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  119606. if( pTS->aaOutput[i] ){
  119607. if( !aOut ){
  119608. aOut = pTS->aaOutput[i];
  119609. nOut = pTS->anOutput[i];
  119610. pTS->aaOutput[i] = 0;
  119611. }else{
  119612. int nNew;
  119613. char *aNew;
  119614. int rc = fts3DoclistOrMerge(p->bDescIdx,
  119615. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  119616. );
  119617. if( rc!=SQLITE_OK ){
  119618. sqlite3_free(aOut);
  119619. return rc;
  119620. }
  119621. sqlite3_free(pTS->aaOutput[i]);
  119622. sqlite3_free(aOut);
  119623. pTS->aaOutput[i] = 0;
  119624. aOut = aNew;
  119625. nOut = nNew;
  119626. }
  119627. }
  119628. }
  119629. pTS->aaOutput[0] = aOut;
  119630. pTS->anOutput[0] = nOut;
  119631. return SQLITE_OK;
  119632. }
  119633. /*
  119634. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  119635. ** as the first argument. The merge is an "OR" merge (see function
  119636. ** fts3DoclistOrMerge() for details).
  119637. **
  119638. ** This function is called with the doclist for each term that matches
  119639. ** a queried prefix. It merges all these doclists into one, the doclist
  119640. ** for the specified prefix. Since there can be a very large number of
  119641. ** doclists to merge, the merging is done pair-wise using the TermSelect
  119642. ** object.
  119643. **
  119644. ** This function returns SQLITE_OK if the merge is successful, or an
  119645. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  119646. */
  119647. static int fts3TermSelectMerge(
  119648. Fts3Table *p, /* FTS table handle */
  119649. TermSelect *pTS, /* TermSelect object to merge into */
  119650. char *aDoclist, /* Pointer to doclist */
  119651. int nDoclist /* Size of aDoclist in bytes */
  119652. ){
  119653. if( pTS->aaOutput[0]==0 ){
  119654. /* If this is the first term selected, copy the doclist to the output
  119655. ** buffer using memcpy(). */
  119656. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  119657. pTS->anOutput[0] = nDoclist;
  119658. if( pTS->aaOutput[0] ){
  119659. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  119660. }else{
  119661. return SQLITE_NOMEM;
  119662. }
  119663. }else{
  119664. char *aMerge = aDoclist;
  119665. int nMerge = nDoclist;
  119666. int iOut;
  119667. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  119668. if( pTS->aaOutput[iOut]==0 ){
  119669. assert( iOut>0 );
  119670. pTS->aaOutput[iOut] = aMerge;
  119671. pTS->anOutput[iOut] = nMerge;
  119672. break;
  119673. }else{
  119674. char *aNew;
  119675. int nNew;
  119676. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  119677. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  119678. );
  119679. if( rc!=SQLITE_OK ){
  119680. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  119681. return rc;
  119682. }
  119683. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  119684. sqlite3_free(pTS->aaOutput[iOut]);
  119685. pTS->aaOutput[iOut] = 0;
  119686. aMerge = aNew;
  119687. nMerge = nNew;
  119688. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  119689. pTS->aaOutput[iOut] = aMerge;
  119690. pTS->anOutput[iOut] = nMerge;
  119691. }
  119692. }
  119693. }
  119694. }
  119695. return SQLITE_OK;
  119696. }
  119697. /*
  119698. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  119699. */
  119700. static int fts3SegReaderCursorAppend(
  119701. Fts3MultiSegReader *pCsr,
  119702. Fts3SegReader *pNew
  119703. ){
  119704. if( (pCsr->nSegment%16)==0 ){
  119705. Fts3SegReader **apNew;
  119706. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  119707. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  119708. if( !apNew ){
  119709. sqlite3Fts3SegReaderFree(pNew);
  119710. return SQLITE_NOMEM;
  119711. }
  119712. pCsr->apSegment = apNew;
  119713. }
  119714. pCsr->apSegment[pCsr->nSegment++] = pNew;
  119715. return SQLITE_OK;
  119716. }
  119717. /*
  119718. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  119719. ** 8th argument.
  119720. **
  119721. ** This function returns SQLITE_OK if successful, or an SQLite error code
  119722. ** otherwise.
  119723. */
  119724. static int fts3SegReaderCursor(
  119725. Fts3Table *p, /* FTS3 table handle */
  119726. int iLangid, /* Language id */
  119727. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  119728. int iLevel, /* Level of segments to scan */
  119729. const char *zTerm, /* Term to query for */
  119730. int nTerm, /* Size of zTerm in bytes */
  119731. int isPrefix, /* True for a prefix search */
  119732. int isScan, /* True to scan from zTerm to EOF */
  119733. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  119734. ){
  119735. int rc = SQLITE_OK; /* Error code */
  119736. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  119737. int rc2; /* Result of sqlite3_reset() */
  119738. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  119739. ** for the pending-terms. If this is a scan, then this call must be being
  119740. ** made by an fts4aux module, not an FTS table. In this case calling
  119741. ** Fts3SegReaderPending might segfault, as the data structures used by
  119742. ** fts4aux are not completely populated. So it's easiest to filter these
  119743. ** calls out here. */
  119744. if( iLevel<0 && p->aIndex ){
  119745. Fts3SegReader *pSeg = 0;
  119746. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  119747. if( rc==SQLITE_OK && pSeg ){
  119748. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  119749. }
  119750. }
  119751. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  119752. if( rc==SQLITE_OK ){
  119753. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  119754. }
  119755. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  119756. Fts3SegReader *pSeg = 0;
  119757. /* Read the values returned by the SELECT into local variables. */
  119758. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  119759. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  119760. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  119761. int nRoot = sqlite3_column_bytes(pStmt, 4);
  119762. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  119763. /* If zTerm is not NULL, and this segment is not stored entirely on its
  119764. ** root node, the range of leaves scanned can be reduced. Do this. */
  119765. if( iStartBlock && zTerm ){
  119766. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  119767. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  119768. if( rc!=SQLITE_OK ) goto finished;
  119769. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  119770. }
  119771. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  119772. (isPrefix==0 && isScan==0),
  119773. iStartBlock, iLeavesEndBlock,
  119774. iEndBlock, zRoot, nRoot, &pSeg
  119775. );
  119776. if( rc!=SQLITE_OK ) goto finished;
  119777. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  119778. }
  119779. }
  119780. finished:
  119781. rc2 = sqlite3_reset(pStmt);
  119782. if( rc==SQLITE_DONE ) rc = rc2;
  119783. return rc;
  119784. }
  119785. /*
  119786. ** Set up a cursor object for iterating through a full-text index or a
  119787. ** single level therein.
  119788. */
  119789. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  119790. Fts3Table *p, /* FTS3 table handle */
  119791. int iLangid, /* Language-id to search */
  119792. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  119793. int iLevel, /* Level of segments to scan */
  119794. const char *zTerm, /* Term to query for */
  119795. int nTerm, /* Size of zTerm in bytes */
  119796. int isPrefix, /* True for a prefix search */
  119797. int isScan, /* True to scan from zTerm to EOF */
  119798. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  119799. ){
  119800. assert( iIndex>=0 && iIndex<p->nIndex );
  119801. assert( iLevel==FTS3_SEGCURSOR_ALL
  119802. || iLevel==FTS3_SEGCURSOR_PENDING
  119803. || iLevel>=0
  119804. );
  119805. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  119806. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  119807. assert( isPrefix==0 || isScan==0 );
  119808. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  119809. return fts3SegReaderCursor(
  119810. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  119811. );
  119812. }
  119813. /*
  119814. ** In addition to its current configuration, have the Fts3MultiSegReader
  119815. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  119816. **
  119817. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  119818. */
  119819. static int fts3SegReaderCursorAddZero(
  119820. Fts3Table *p, /* FTS virtual table handle */
  119821. int iLangid,
  119822. const char *zTerm, /* Term to scan doclist of */
  119823. int nTerm, /* Number of bytes in zTerm */
  119824. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  119825. ){
  119826. return fts3SegReaderCursor(p,
  119827. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  119828. );
  119829. }
  119830. /*
  119831. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  119832. ** if isPrefix is true, to scan the doclist for all terms for which
  119833. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  119834. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  119835. ** an SQLite error code.
  119836. **
  119837. ** It is the responsibility of the caller to free this object by eventually
  119838. ** passing it to fts3SegReaderCursorFree()
  119839. **
  119840. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  119841. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  119842. */
  119843. static int fts3TermSegReaderCursor(
  119844. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  119845. const char *zTerm, /* Term to query for */
  119846. int nTerm, /* Size of zTerm in bytes */
  119847. int isPrefix, /* True for a prefix search */
  119848. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  119849. ){
  119850. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  119851. int rc = SQLITE_NOMEM; /* Return code */
  119852. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  119853. if( pSegcsr ){
  119854. int i;
  119855. int bFound = 0; /* True once an index has been found */
  119856. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  119857. if( isPrefix ){
  119858. for(i=1; bFound==0 && i<p->nIndex; i++){
  119859. if( p->aIndex[i].nPrefix==nTerm ){
  119860. bFound = 1;
  119861. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119862. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  119863. );
  119864. pSegcsr->bLookup = 1;
  119865. }
  119866. }
  119867. for(i=1; bFound==0 && i<p->nIndex; i++){
  119868. if( p->aIndex[i].nPrefix==nTerm+1 ){
  119869. bFound = 1;
  119870. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119871. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  119872. );
  119873. if( rc==SQLITE_OK ){
  119874. rc = fts3SegReaderCursorAddZero(
  119875. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  119876. );
  119877. }
  119878. }
  119879. }
  119880. }
  119881. if( bFound==0 ){
  119882. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  119883. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  119884. );
  119885. pSegcsr->bLookup = !isPrefix;
  119886. }
  119887. }
  119888. *ppSegcsr = pSegcsr;
  119889. return rc;
  119890. }
  119891. /*
  119892. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  119893. */
  119894. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  119895. sqlite3Fts3SegReaderFinish(pSegcsr);
  119896. sqlite3_free(pSegcsr);
  119897. }
  119898. /*
  119899. ** This function retrieves the doclist for the specified term (or term
  119900. ** prefix) from the database.
  119901. */
  119902. static int fts3TermSelect(
  119903. Fts3Table *p, /* Virtual table handle */
  119904. Fts3PhraseToken *pTok, /* Token to query for */
  119905. int iColumn, /* Column to query (or -ve for all columns) */
  119906. int *pnOut, /* OUT: Size of buffer at *ppOut */
  119907. char **ppOut /* OUT: Malloced result buffer */
  119908. ){
  119909. int rc; /* Return code */
  119910. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  119911. TermSelect tsc; /* Object for pair-wise doclist merging */
  119912. Fts3SegFilter filter; /* Segment term filter configuration */
  119913. pSegcsr = pTok->pSegcsr;
  119914. memset(&tsc, 0, sizeof(TermSelect));
  119915. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  119916. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  119917. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  119918. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  119919. filter.iCol = iColumn;
  119920. filter.zTerm = pTok->z;
  119921. filter.nTerm = pTok->n;
  119922. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  119923. while( SQLITE_OK==rc
  119924. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  119925. ){
  119926. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  119927. }
  119928. if( rc==SQLITE_OK ){
  119929. rc = fts3TermSelectFinishMerge(p, &tsc);
  119930. }
  119931. if( rc==SQLITE_OK ){
  119932. *ppOut = tsc.aaOutput[0];
  119933. *pnOut = tsc.anOutput[0];
  119934. }else{
  119935. int i;
  119936. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  119937. sqlite3_free(tsc.aaOutput[i]);
  119938. }
  119939. }
  119940. fts3SegReaderCursorFree(pSegcsr);
  119941. pTok->pSegcsr = 0;
  119942. return rc;
  119943. }
  119944. /*
  119945. ** This function counts the total number of docids in the doclist stored
  119946. ** in buffer aList[], size nList bytes.
  119947. **
  119948. ** If the isPoslist argument is true, then it is assumed that the doclist
  119949. ** contains a position-list following each docid. Otherwise, it is assumed
  119950. ** that the doclist is simply a list of docids stored as delta encoded
  119951. ** varints.
  119952. */
  119953. static int fts3DoclistCountDocids(char *aList, int nList){
  119954. int nDoc = 0; /* Return value */
  119955. if( aList ){
  119956. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  119957. char *p = aList; /* Cursor */
  119958. while( p<aEnd ){
  119959. nDoc++;
  119960. while( (*p++)&0x80 ); /* Skip docid varint */
  119961. fts3PoslistCopy(0, &p); /* Skip over position list */
  119962. }
  119963. }
  119964. return nDoc;
  119965. }
  119966. /*
  119967. ** Advance the cursor to the next row in the %_content table that
  119968. ** matches the search criteria. For a MATCH search, this will be
  119969. ** the next row that matches. For a full-table scan, this will be
  119970. ** simply the next row in the %_content table. For a docid lookup,
  119971. ** this routine simply sets the EOF flag.
  119972. **
  119973. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  119974. ** even if we reach end-of-file. The fts3EofMethod() will be called
  119975. ** subsequently to determine whether or not an EOF was hit.
  119976. */
  119977. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  119978. int rc;
  119979. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  119980. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  119981. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  119982. pCsr->isEof = 1;
  119983. rc = sqlite3_reset(pCsr->pStmt);
  119984. }else{
  119985. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  119986. rc = SQLITE_OK;
  119987. }
  119988. }else{
  119989. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  119990. }
  119991. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  119992. return rc;
  119993. }
  119994. /*
  119995. ** The following are copied from sqliteInt.h.
  119996. **
  119997. ** Constants for the largest and smallest possible 64-bit signed integers.
  119998. ** These macros are designed to work correctly on both 32-bit and 64-bit
  119999. ** compilers.
  120000. */
  120001. #ifndef SQLITE_AMALGAMATION
  120002. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  120003. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  120004. #endif
  120005. /*
  120006. ** If the numeric type of argument pVal is "integer", then return it
  120007. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  120008. ** the second parameter, iDefault.
  120009. */
  120010. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  120011. if( pVal ){
  120012. int eType = sqlite3_value_numeric_type(pVal);
  120013. if( eType==SQLITE_INTEGER ){
  120014. return sqlite3_value_int64(pVal);
  120015. }
  120016. }
  120017. return iDefault;
  120018. }
  120019. /*
  120020. ** This is the xFilter interface for the virtual table. See
  120021. ** the virtual table xFilter method documentation for additional
  120022. ** information.
  120023. **
  120024. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  120025. ** the %_content table.
  120026. **
  120027. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  120028. ** in the %_content table.
  120029. **
  120030. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  120031. ** column on the left-hand side of the MATCH operator is column
  120032. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  120033. ** side of the MATCH operator.
  120034. */
  120035. static int fts3FilterMethod(
  120036. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  120037. int idxNum, /* Strategy index */
  120038. const char *idxStr, /* Unused */
  120039. int nVal, /* Number of elements in apVal */
  120040. sqlite3_value **apVal /* Arguments for the indexing scheme */
  120041. ){
  120042. int rc;
  120043. char *zSql; /* SQL statement used to access %_content */
  120044. int eSearch;
  120045. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  120046. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  120047. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  120048. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  120049. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  120050. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  120051. int iIdx;
  120052. UNUSED_PARAMETER(idxStr);
  120053. UNUSED_PARAMETER(nVal);
  120054. eSearch = (idxNum & 0x0000FFFF);
  120055. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  120056. assert( p->pSegments==0 );
  120057. /* Collect arguments into local variables */
  120058. iIdx = 0;
  120059. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  120060. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  120061. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  120062. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  120063. assert( iIdx==nVal );
  120064. /* In case the cursor has been used before, clear it now. */
  120065. sqlite3_finalize(pCsr->pStmt);
  120066. sqlite3_free(pCsr->aDoclist);
  120067. sqlite3Fts3ExprFree(pCsr->pExpr);
  120068. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  120069. /* Set the lower and upper bounds on docids to return */
  120070. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  120071. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  120072. if( idxStr ){
  120073. pCsr->bDesc = (idxStr[0]=='D');
  120074. }else{
  120075. pCsr->bDesc = p->bDescIdx;
  120076. }
  120077. pCsr->eSearch = (i16)eSearch;
  120078. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  120079. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  120080. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  120081. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  120082. return SQLITE_NOMEM;
  120083. }
  120084. pCsr->iLangid = 0;
  120085. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  120086. assert( p->base.zErrMsg==0 );
  120087. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  120088. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  120089. &p->base.zErrMsg
  120090. );
  120091. if( rc!=SQLITE_OK ){
  120092. return rc;
  120093. }
  120094. rc = fts3EvalStart(pCsr);
  120095. sqlite3Fts3SegmentsClose(p);
  120096. if( rc!=SQLITE_OK ) return rc;
  120097. pCsr->pNextId = pCsr->aDoclist;
  120098. pCsr->iPrevId = 0;
  120099. }
  120100. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  120101. ** statement loops through all rows of the %_content table. For a
  120102. ** full-text query or docid lookup, the statement retrieves a single
  120103. ** row by docid.
  120104. */
  120105. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  120106. zSql = sqlite3_mprintf(
  120107. "SELECT %s ORDER BY rowid %s",
  120108. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  120109. );
  120110. if( zSql ){
  120111. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  120112. sqlite3_free(zSql);
  120113. }else{
  120114. rc = SQLITE_NOMEM;
  120115. }
  120116. }else if( eSearch==FTS3_DOCID_SEARCH ){
  120117. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  120118. if( rc==SQLITE_OK ){
  120119. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  120120. }
  120121. }
  120122. if( rc!=SQLITE_OK ) return rc;
  120123. return fts3NextMethod(pCursor);
  120124. }
  120125. /*
  120126. ** This is the xEof method of the virtual table. SQLite calls this
  120127. ** routine to find out if it has reached the end of a result set.
  120128. */
  120129. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  120130. return ((Fts3Cursor *)pCursor)->isEof;
  120131. }
  120132. /*
  120133. ** This is the xRowid method. The SQLite core calls this routine to
  120134. ** retrieve the rowid for the current row of the result set. fts3
  120135. ** exposes %_content.docid as the rowid for the virtual table. The
  120136. ** rowid should be written to *pRowid.
  120137. */
  120138. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  120139. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  120140. *pRowid = pCsr->iPrevId;
  120141. return SQLITE_OK;
  120142. }
  120143. /*
  120144. ** This is the xColumn method, called by SQLite to request a value from
  120145. ** the row that the supplied cursor currently points to.
  120146. **
  120147. ** If:
  120148. **
  120149. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  120150. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  120151. ** (iCol == p->nColumn+1) -> Docid column
  120152. ** (iCol == p->nColumn+2) -> Langid column
  120153. */
  120154. static int fts3ColumnMethod(
  120155. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  120156. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  120157. int iCol /* Index of column to read value from */
  120158. ){
  120159. int rc = SQLITE_OK; /* Return Code */
  120160. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  120161. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  120162. /* The column value supplied by SQLite must be in range. */
  120163. assert( iCol>=0 && iCol<=p->nColumn+2 );
  120164. if( iCol==p->nColumn+1 ){
  120165. /* This call is a request for the "docid" column. Since "docid" is an
  120166. ** alias for "rowid", use the xRowid() method to obtain the value.
  120167. */
  120168. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  120169. }else if( iCol==p->nColumn ){
  120170. /* The extra column whose name is the same as the table.
  120171. ** Return a blob which is a pointer to the cursor. */
  120172. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  120173. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  120174. sqlite3_result_int64(pCtx, pCsr->iLangid);
  120175. }else{
  120176. /* The requested column is either a user column (one that contains
  120177. ** indexed data), or the language-id column. */
  120178. rc = fts3CursorSeek(0, pCsr);
  120179. if( rc==SQLITE_OK ){
  120180. if( iCol==p->nColumn+2 ){
  120181. int iLangid = 0;
  120182. if( p->zLanguageid ){
  120183. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  120184. }
  120185. sqlite3_result_int(pCtx, iLangid);
  120186. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  120187. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  120188. }
  120189. }
  120190. }
  120191. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  120192. return rc;
  120193. }
  120194. /*
  120195. ** This function is the implementation of the xUpdate callback used by
  120196. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  120197. ** inserted, updated or deleted.
  120198. */
  120199. static int fts3UpdateMethod(
  120200. sqlite3_vtab *pVtab, /* Virtual table handle */
  120201. int nArg, /* Size of argument array */
  120202. sqlite3_value **apVal, /* Array of arguments */
  120203. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  120204. ){
  120205. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  120206. }
  120207. /*
  120208. ** Implementation of xSync() method. Flush the contents of the pending-terms
  120209. ** hash-table to the database.
  120210. */
  120211. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  120212. /* Following an incremental-merge operation, assuming that the input
  120213. ** segments are not completely consumed (the usual case), they are updated
  120214. ** in place to remove the entries that have already been merged. This
  120215. ** involves updating the leaf block that contains the smallest unmerged
  120216. ** entry and each block (if any) between the leaf and the root node. So
  120217. ** if the height of the input segment b-trees is N, and input segments
  120218. ** are merged eight at a time, updating the input segments at the end
  120219. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  120220. ** small - often between 0 and 2. So the overhead of the incremental
  120221. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  120222. ** dwarfing the actual productive work accomplished, the incremental merge
  120223. ** is only attempted if it will write at least 64 leaf blocks. Hence
  120224. ** nMinMerge.
  120225. **
  120226. ** Of course, updating the input segments also involves deleting a bunch
  120227. ** of blocks from the segments table. But this is not considered overhead
  120228. ** as it would also be required by a crisis-merge that used the same input
  120229. ** segments.
  120230. */
  120231. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  120232. Fts3Table *p = (Fts3Table*)pVtab;
  120233. int rc = sqlite3Fts3PendingTermsFlush(p);
  120234. if( rc==SQLITE_OK && p->bAutoincrmerge==1 && p->nLeafAdd>(nMinMerge/16) ){
  120235. int mxLevel = 0; /* Maximum relative level value in db */
  120236. int A; /* Incr-merge parameter A */
  120237. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  120238. assert( rc==SQLITE_OK || mxLevel==0 );
  120239. A = p->nLeafAdd * mxLevel;
  120240. A += (A/2);
  120241. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, 8);
  120242. }
  120243. sqlite3Fts3SegmentsClose(p);
  120244. return rc;
  120245. }
  120246. /*
  120247. ** Implementation of xBegin() method. This is a no-op.
  120248. */
  120249. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  120250. Fts3Table *p = (Fts3Table*)pVtab;
  120251. UNUSED_PARAMETER(pVtab);
  120252. assert( p->pSegments==0 );
  120253. assert( p->nPendingData==0 );
  120254. assert( p->inTransaction!=1 );
  120255. TESTONLY( p->inTransaction = 1 );
  120256. TESTONLY( p->mxSavepoint = -1; );
  120257. p->nLeafAdd = 0;
  120258. return SQLITE_OK;
  120259. }
  120260. /*
  120261. ** Implementation of xCommit() method. This is a no-op. The contents of
  120262. ** the pending-terms hash-table have already been flushed into the database
  120263. ** by fts3SyncMethod().
  120264. */
  120265. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  120266. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  120267. UNUSED_PARAMETER(pVtab);
  120268. assert( p->nPendingData==0 );
  120269. assert( p->inTransaction!=0 );
  120270. assert( p->pSegments==0 );
  120271. TESTONLY( p->inTransaction = 0 );
  120272. TESTONLY( p->mxSavepoint = -1; );
  120273. return SQLITE_OK;
  120274. }
  120275. /*
  120276. ** Implementation of xRollback(). Discard the contents of the pending-terms
  120277. ** hash-table. Any changes made to the database are reverted by SQLite.
  120278. */
  120279. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  120280. Fts3Table *p = (Fts3Table*)pVtab;
  120281. sqlite3Fts3PendingTermsClear(p);
  120282. assert( p->inTransaction!=0 );
  120283. TESTONLY( p->inTransaction = 0 );
  120284. TESTONLY( p->mxSavepoint = -1; );
  120285. return SQLITE_OK;
  120286. }
  120287. /*
  120288. ** When called, *ppPoslist must point to the byte immediately following the
  120289. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  120290. ** moves *ppPoslist so that it instead points to the first byte of the
  120291. ** same position list.
  120292. */
  120293. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  120294. char *p = &(*ppPoslist)[-2];
  120295. char c = 0;
  120296. while( p>pStart && (c=*p--)==0 );
  120297. while( p>pStart && (*p & 0x80) | c ){
  120298. c = *p--;
  120299. }
  120300. if( p>pStart ){ p = &p[2]; }
  120301. while( *p++&0x80 );
  120302. *ppPoslist = p;
  120303. }
  120304. /*
  120305. ** Helper function used by the implementation of the overloaded snippet(),
  120306. ** offsets() and optimize() SQL functions.
  120307. **
  120308. ** If the value passed as the third argument is a blob of size
  120309. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  120310. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  120311. ** message is written to context pContext and SQLITE_ERROR returned. The
  120312. ** string passed via zFunc is used as part of the error message.
  120313. */
  120314. static int fts3FunctionArg(
  120315. sqlite3_context *pContext, /* SQL function call context */
  120316. const char *zFunc, /* Function name */
  120317. sqlite3_value *pVal, /* argv[0] passed to function */
  120318. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  120319. ){
  120320. Fts3Cursor *pRet;
  120321. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  120322. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  120323. ){
  120324. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  120325. sqlite3_result_error(pContext, zErr, -1);
  120326. sqlite3_free(zErr);
  120327. return SQLITE_ERROR;
  120328. }
  120329. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  120330. *ppCsr = pRet;
  120331. return SQLITE_OK;
  120332. }
  120333. /*
  120334. ** Implementation of the snippet() function for FTS3
  120335. */
  120336. static void fts3SnippetFunc(
  120337. sqlite3_context *pContext, /* SQLite function call context */
  120338. int nVal, /* Size of apVal[] array */
  120339. sqlite3_value **apVal /* Array of arguments */
  120340. ){
  120341. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120342. const char *zStart = "<b>";
  120343. const char *zEnd = "</b>";
  120344. const char *zEllipsis = "<b>...</b>";
  120345. int iCol = -1;
  120346. int nToken = 15; /* Default number of tokens in snippet */
  120347. /* There must be at least one argument passed to this function (otherwise
  120348. ** the non-overloaded version would have been called instead of this one).
  120349. */
  120350. assert( nVal>=1 );
  120351. if( nVal>6 ){
  120352. sqlite3_result_error(pContext,
  120353. "wrong number of arguments to function snippet()", -1);
  120354. return;
  120355. }
  120356. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  120357. switch( nVal ){
  120358. case 6: nToken = sqlite3_value_int(apVal[5]);
  120359. case 5: iCol = sqlite3_value_int(apVal[4]);
  120360. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  120361. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  120362. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  120363. }
  120364. if( !zEllipsis || !zEnd || !zStart ){
  120365. sqlite3_result_error_nomem(pContext);
  120366. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  120367. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  120368. }
  120369. }
  120370. /*
  120371. ** Implementation of the offsets() function for FTS3
  120372. */
  120373. static void fts3OffsetsFunc(
  120374. sqlite3_context *pContext, /* SQLite function call context */
  120375. int nVal, /* Size of argument array */
  120376. sqlite3_value **apVal /* Array of arguments */
  120377. ){
  120378. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120379. UNUSED_PARAMETER(nVal);
  120380. assert( nVal==1 );
  120381. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  120382. assert( pCsr );
  120383. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  120384. sqlite3Fts3Offsets(pContext, pCsr);
  120385. }
  120386. }
  120387. /*
  120388. ** Implementation of the special optimize() function for FTS3. This
  120389. ** function merges all segments in the database to a single segment.
  120390. ** Example usage is:
  120391. **
  120392. ** SELECT optimize(t) FROM t LIMIT 1;
  120393. **
  120394. ** where 't' is the name of an FTS3 table.
  120395. */
  120396. static void fts3OptimizeFunc(
  120397. sqlite3_context *pContext, /* SQLite function call context */
  120398. int nVal, /* Size of argument array */
  120399. sqlite3_value **apVal /* Array of arguments */
  120400. ){
  120401. int rc; /* Return code */
  120402. Fts3Table *p; /* Virtual table handle */
  120403. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  120404. UNUSED_PARAMETER(nVal);
  120405. assert( nVal==1 );
  120406. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  120407. p = (Fts3Table *)pCursor->base.pVtab;
  120408. assert( p );
  120409. rc = sqlite3Fts3Optimize(p);
  120410. switch( rc ){
  120411. case SQLITE_OK:
  120412. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  120413. break;
  120414. case SQLITE_DONE:
  120415. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  120416. break;
  120417. default:
  120418. sqlite3_result_error_code(pContext, rc);
  120419. break;
  120420. }
  120421. }
  120422. /*
  120423. ** Implementation of the matchinfo() function for FTS3
  120424. */
  120425. static void fts3MatchinfoFunc(
  120426. sqlite3_context *pContext, /* SQLite function call context */
  120427. int nVal, /* Size of argument array */
  120428. sqlite3_value **apVal /* Array of arguments */
  120429. ){
  120430. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  120431. assert( nVal==1 || nVal==2 );
  120432. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  120433. const char *zArg = 0;
  120434. if( nVal>1 ){
  120435. zArg = (const char *)sqlite3_value_text(apVal[1]);
  120436. }
  120437. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  120438. }
  120439. }
  120440. /*
  120441. ** This routine implements the xFindFunction method for the FTS3
  120442. ** virtual table.
  120443. */
  120444. static int fts3FindFunctionMethod(
  120445. sqlite3_vtab *pVtab, /* Virtual table handle */
  120446. int nArg, /* Number of SQL function arguments */
  120447. const char *zName, /* Name of SQL function */
  120448. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  120449. void **ppArg /* Unused */
  120450. ){
  120451. struct Overloaded {
  120452. const char *zName;
  120453. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  120454. } aOverload[] = {
  120455. { "snippet", fts3SnippetFunc },
  120456. { "offsets", fts3OffsetsFunc },
  120457. { "optimize", fts3OptimizeFunc },
  120458. { "matchinfo", fts3MatchinfoFunc },
  120459. };
  120460. int i; /* Iterator variable */
  120461. UNUSED_PARAMETER(pVtab);
  120462. UNUSED_PARAMETER(nArg);
  120463. UNUSED_PARAMETER(ppArg);
  120464. for(i=0; i<SizeofArray(aOverload); i++){
  120465. if( strcmp(zName, aOverload[i].zName)==0 ){
  120466. *pxFunc = aOverload[i].xFunc;
  120467. return 1;
  120468. }
  120469. }
  120470. /* No function of the specified name was found. Return 0. */
  120471. return 0;
  120472. }
  120473. /*
  120474. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  120475. */
  120476. static int fts3RenameMethod(
  120477. sqlite3_vtab *pVtab, /* Virtual table handle */
  120478. const char *zName /* New name of table */
  120479. ){
  120480. Fts3Table *p = (Fts3Table *)pVtab;
  120481. sqlite3 *db = p->db; /* Database connection */
  120482. int rc; /* Return Code */
  120483. /* As it happens, the pending terms table is always empty here. This is
  120484. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  120485. ** always opens a savepoint transaction. And the xSavepoint() method
  120486. ** flushes the pending terms table. But leave the (no-op) call to
  120487. ** PendingTermsFlush() in in case that changes.
  120488. */
  120489. assert( p->nPendingData==0 );
  120490. rc = sqlite3Fts3PendingTermsFlush(p);
  120491. if( p->zContentTbl==0 ){
  120492. fts3DbExec(&rc, db,
  120493. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  120494. p->zDb, p->zName, zName
  120495. );
  120496. }
  120497. if( p->bHasDocsize ){
  120498. fts3DbExec(&rc, db,
  120499. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  120500. p->zDb, p->zName, zName
  120501. );
  120502. }
  120503. if( p->bHasStat ){
  120504. fts3DbExec(&rc, db,
  120505. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  120506. p->zDb, p->zName, zName
  120507. );
  120508. }
  120509. fts3DbExec(&rc, db,
  120510. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  120511. p->zDb, p->zName, zName
  120512. );
  120513. fts3DbExec(&rc, db,
  120514. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  120515. p->zDb, p->zName, zName
  120516. );
  120517. return rc;
  120518. }
  120519. /*
  120520. ** The xSavepoint() method.
  120521. **
  120522. ** Flush the contents of the pending-terms table to disk.
  120523. */
  120524. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120525. int rc = SQLITE_OK;
  120526. UNUSED_PARAMETER(iSavepoint);
  120527. assert( ((Fts3Table *)pVtab)->inTransaction );
  120528. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  120529. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  120530. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  120531. rc = fts3SyncMethod(pVtab);
  120532. }
  120533. return rc;
  120534. }
  120535. /*
  120536. ** The xRelease() method.
  120537. **
  120538. ** This is a no-op.
  120539. */
  120540. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120541. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  120542. UNUSED_PARAMETER(iSavepoint);
  120543. UNUSED_PARAMETER(pVtab);
  120544. assert( p->inTransaction );
  120545. assert( p->mxSavepoint >= iSavepoint );
  120546. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  120547. return SQLITE_OK;
  120548. }
  120549. /*
  120550. ** The xRollbackTo() method.
  120551. **
  120552. ** Discard the contents of the pending terms table.
  120553. */
  120554. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  120555. Fts3Table *p = (Fts3Table*)pVtab;
  120556. UNUSED_PARAMETER(iSavepoint);
  120557. assert( p->inTransaction );
  120558. assert( p->mxSavepoint >= iSavepoint );
  120559. TESTONLY( p->mxSavepoint = iSavepoint );
  120560. sqlite3Fts3PendingTermsClear(p);
  120561. return SQLITE_OK;
  120562. }
  120563. static const sqlite3_module fts3Module = {
  120564. /* iVersion */ 2,
  120565. /* xCreate */ fts3CreateMethod,
  120566. /* xConnect */ fts3ConnectMethod,
  120567. /* xBestIndex */ fts3BestIndexMethod,
  120568. /* xDisconnect */ fts3DisconnectMethod,
  120569. /* xDestroy */ fts3DestroyMethod,
  120570. /* xOpen */ fts3OpenMethod,
  120571. /* xClose */ fts3CloseMethod,
  120572. /* xFilter */ fts3FilterMethod,
  120573. /* xNext */ fts3NextMethod,
  120574. /* xEof */ fts3EofMethod,
  120575. /* xColumn */ fts3ColumnMethod,
  120576. /* xRowid */ fts3RowidMethod,
  120577. /* xUpdate */ fts3UpdateMethod,
  120578. /* xBegin */ fts3BeginMethod,
  120579. /* xSync */ fts3SyncMethod,
  120580. /* xCommit */ fts3CommitMethod,
  120581. /* xRollback */ fts3RollbackMethod,
  120582. /* xFindFunction */ fts3FindFunctionMethod,
  120583. /* xRename */ fts3RenameMethod,
  120584. /* xSavepoint */ fts3SavepointMethod,
  120585. /* xRelease */ fts3ReleaseMethod,
  120586. /* xRollbackTo */ fts3RollbackToMethod,
  120587. };
  120588. /*
  120589. ** This function is registered as the module destructor (called when an
  120590. ** FTS3 enabled database connection is closed). It frees the memory
  120591. ** allocated for the tokenizer hash table.
  120592. */
  120593. static void hashDestroy(void *p){
  120594. Fts3Hash *pHash = (Fts3Hash *)p;
  120595. sqlite3Fts3HashClear(pHash);
  120596. sqlite3_free(pHash);
  120597. }
  120598. /*
  120599. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  120600. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  120601. ** respectively. The following three forward declarations are for functions
  120602. ** declared in these files used to retrieve the respective implementations.
  120603. **
  120604. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  120605. ** to by the argument to point to the "simple" tokenizer implementation.
  120606. ** And so on.
  120607. */
  120608. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120609. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120610. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120611. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  120612. #endif
  120613. #ifdef SQLITE_ENABLE_ICU
  120614. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  120615. #endif
  120616. /*
  120617. ** Initialize the fts3 extension. If this extension is built as part
  120618. ** of the sqlite library, then this function is called directly by
  120619. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  120620. ** function is called by the sqlite3_extension_init() entry point.
  120621. */
  120622. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  120623. int rc = SQLITE_OK;
  120624. Fts3Hash *pHash = 0;
  120625. const sqlite3_tokenizer_module *pSimple = 0;
  120626. const sqlite3_tokenizer_module *pPorter = 0;
  120627. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120628. const sqlite3_tokenizer_module *pUnicode = 0;
  120629. #endif
  120630. #ifdef SQLITE_ENABLE_ICU
  120631. const sqlite3_tokenizer_module *pIcu = 0;
  120632. sqlite3Fts3IcuTokenizerModule(&pIcu);
  120633. #endif
  120634. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120635. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  120636. #endif
  120637. #ifdef SQLITE_TEST
  120638. rc = sqlite3Fts3InitTerm(db);
  120639. if( rc!=SQLITE_OK ) return rc;
  120640. #endif
  120641. rc = sqlite3Fts3InitAux(db);
  120642. if( rc!=SQLITE_OK ) return rc;
  120643. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  120644. sqlite3Fts3PorterTokenizerModule(&pPorter);
  120645. /* Allocate and initialize the hash-table used to store tokenizers. */
  120646. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  120647. if( !pHash ){
  120648. rc = SQLITE_NOMEM;
  120649. }else{
  120650. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  120651. }
  120652. /* Load the built-in tokenizers into the hash table */
  120653. if( rc==SQLITE_OK ){
  120654. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  120655. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  120656. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  120657. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  120658. #endif
  120659. #ifdef SQLITE_ENABLE_ICU
  120660. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  120661. #endif
  120662. ){
  120663. rc = SQLITE_NOMEM;
  120664. }
  120665. }
  120666. #ifdef SQLITE_TEST
  120667. if( rc==SQLITE_OK ){
  120668. rc = sqlite3Fts3ExprInitTestInterface(db);
  120669. }
  120670. #endif
  120671. /* Create the virtual table wrapper around the hash-table and overload
  120672. ** the two scalar functions. If this is successful, register the
  120673. ** module with sqlite.
  120674. */
  120675. if( SQLITE_OK==rc
  120676. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  120677. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  120678. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  120679. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  120680. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  120681. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  120682. ){
  120683. rc = sqlite3_create_module_v2(
  120684. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  120685. );
  120686. if( rc==SQLITE_OK ){
  120687. rc = sqlite3_create_module_v2(
  120688. db, "fts4", &fts3Module, (void *)pHash, 0
  120689. );
  120690. }
  120691. if( rc==SQLITE_OK ){
  120692. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  120693. }
  120694. return rc;
  120695. }
  120696. /* An error has occurred. Delete the hash table and return the error code. */
  120697. assert( rc!=SQLITE_OK );
  120698. if( pHash ){
  120699. sqlite3Fts3HashClear(pHash);
  120700. sqlite3_free(pHash);
  120701. }
  120702. return rc;
  120703. }
  120704. /*
  120705. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  120706. ** by pExpr.
  120707. **
  120708. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  120709. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  120710. ** Fts3SegReader objects internally to provide an interface to seek or scan
  120711. ** within the union of all segments of a b-tree. Hence the name.
  120712. **
  120713. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  120714. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  120715. ** there exists prefix b-tree of the right length) then it may be traversed
  120716. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  120717. ** doclist and then traversed.
  120718. */
  120719. static void fts3EvalAllocateReaders(
  120720. Fts3Cursor *pCsr, /* FTS cursor handle */
  120721. Fts3Expr *pExpr, /* Allocate readers for this expression */
  120722. int *pnToken, /* OUT: Total number of tokens in phrase. */
  120723. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  120724. int *pRc /* IN/OUT: Error code */
  120725. ){
  120726. if( pExpr && SQLITE_OK==*pRc ){
  120727. if( pExpr->eType==FTSQUERY_PHRASE ){
  120728. int i;
  120729. int nToken = pExpr->pPhrase->nToken;
  120730. *pnToken += nToken;
  120731. for(i=0; i<nToken; i++){
  120732. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  120733. int rc = fts3TermSegReaderCursor(pCsr,
  120734. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  120735. );
  120736. if( rc!=SQLITE_OK ){
  120737. *pRc = rc;
  120738. return;
  120739. }
  120740. }
  120741. assert( pExpr->pPhrase->iDoclistToken==0 );
  120742. pExpr->pPhrase->iDoclistToken = -1;
  120743. }else{
  120744. *pnOr += (pExpr->eType==FTSQUERY_OR);
  120745. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  120746. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  120747. }
  120748. }
  120749. }
  120750. /*
  120751. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  120752. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  120753. **
  120754. ** This function assumes that pList points to a buffer allocated using
  120755. ** sqlite3_malloc(). This function takes responsibility for eventually
  120756. ** freeing the buffer.
  120757. */
  120758. static void fts3EvalPhraseMergeToken(
  120759. Fts3Table *pTab, /* FTS Table pointer */
  120760. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  120761. int iToken, /* Token pList/nList corresponds to */
  120762. char *pList, /* Pointer to doclist */
  120763. int nList /* Number of bytes in pList */
  120764. ){
  120765. assert( iToken!=p->iDoclistToken );
  120766. if( pList==0 ){
  120767. sqlite3_free(p->doclist.aAll);
  120768. p->doclist.aAll = 0;
  120769. p->doclist.nAll = 0;
  120770. }
  120771. else if( p->iDoclistToken<0 ){
  120772. p->doclist.aAll = pList;
  120773. p->doclist.nAll = nList;
  120774. }
  120775. else if( p->doclist.aAll==0 ){
  120776. sqlite3_free(pList);
  120777. }
  120778. else {
  120779. char *pLeft;
  120780. char *pRight;
  120781. int nLeft;
  120782. int nRight;
  120783. int nDiff;
  120784. if( p->iDoclistToken<iToken ){
  120785. pLeft = p->doclist.aAll;
  120786. nLeft = p->doclist.nAll;
  120787. pRight = pList;
  120788. nRight = nList;
  120789. nDiff = iToken - p->iDoclistToken;
  120790. }else{
  120791. pRight = p->doclist.aAll;
  120792. nRight = p->doclist.nAll;
  120793. pLeft = pList;
  120794. nLeft = nList;
  120795. nDiff = p->iDoclistToken - iToken;
  120796. }
  120797. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  120798. sqlite3_free(pLeft);
  120799. p->doclist.aAll = pRight;
  120800. p->doclist.nAll = nRight;
  120801. }
  120802. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  120803. }
  120804. /*
  120805. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  120806. ** does not take deferred tokens into account.
  120807. **
  120808. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120809. */
  120810. static int fts3EvalPhraseLoad(
  120811. Fts3Cursor *pCsr, /* FTS Cursor handle */
  120812. Fts3Phrase *p /* Phrase object */
  120813. ){
  120814. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  120815. int iToken;
  120816. int rc = SQLITE_OK;
  120817. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  120818. Fts3PhraseToken *pToken = &p->aToken[iToken];
  120819. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  120820. if( pToken->pSegcsr ){
  120821. int nThis = 0;
  120822. char *pThis = 0;
  120823. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  120824. if( rc==SQLITE_OK ){
  120825. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  120826. }
  120827. }
  120828. assert( pToken->pSegcsr==0 );
  120829. }
  120830. return rc;
  120831. }
  120832. /*
  120833. ** This function is called on each phrase after the position lists for
  120834. ** any deferred tokens have been loaded into memory. It updates the phrases
  120835. ** current position list to include only those positions that are really
  120836. ** instances of the phrase (after considering deferred tokens). If this
  120837. ** means that the phrase does not appear in the current row, doclist.pList
  120838. ** and doclist.nList are both zeroed.
  120839. **
  120840. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120841. */
  120842. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  120843. int iToken; /* Used to iterate through phrase tokens */
  120844. char *aPoslist = 0; /* Position list for deferred tokens */
  120845. int nPoslist = 0; /* Number of bytes in aPoslist */
  120846. int iPrev = -1; /* Token number of previous deferred token */
  120847. assert( pPhrase->doclist.bFreeList==0 );
  120848. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  120849. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  120850. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  120851. if( pDeferred ){
  120852. char *pList;
  120853. int nList;
  120854. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  120855. if( rc!=SQLITE_OK ) return rc;
  120856. if( pList==0 ){
  120857. sqlite3_free(aPoslist);
  120858. pPhrase->doclist.pList = 0;
  120859. pPhrase->doclist.nList = 0;
  120860. return SQLITE_OK;
  120861. }else if( aPoslist==0 ){
  120862. aPoslist = pList;
  120863. nPoslist = nList;
  120864. }else{
  120865. char *aOut = pList;
  120866. char *p1 = aPoslist;
  120867. char *p2 = aOut;
  120868. assert( iPrev>=0 );
  120869. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  120870. sqlite3_free(aPoslist);
  120871. aPoslist = pList;
  120872. nPoslist = (int)(aOut - aPoslist);
  120873. if( nPoslist==0 ){
  120874. sqlite3_free(aPoslist);
  120875. pPhrase->doclist.pList = 0;
  120876. pPhrase->doclist.nList = 0;
  120877. return SQLITE_OK;
  120878. }
  120879. }
  120880. iPrev = iToken;
  120881. }
  120882. }
  120883. if( iPrev>=0 ){
  120884. int nMaxUndeferred = pPhrase->iDoclistToken;
  120885. if( nMaxUndeferred<0 ){
  120886. pPhrase->doclist.pList = aPoslist;
  120887. pPhrase->doclist.nList = nPoslist;
  120888. pPhrase->doclist.iDocid = pCsr->iPrevId;
  120889. pPhrase->doclist.bFreeList = 1;
  120890. }else{
  120891. int nDistance;
  120892. char *p1;
  120893. char *p2;
  120894. char *aOut;
  120895. if( nMaxUndeferred>iPrev ){
  120896. p1 = aPoslist;
  120897. p2 = pPhrase->doclist.pList;
  120898. nDistance = nMaxUndeferred - iPrev;
  120899. }else{
  120900. p1 = pPhrase->doclist.pList;
  120901. p2 = aPoslist;
  120902. nDistance = iPrev - nMaxUndeferred;
  120903. }
  120904. aOut = (char *)sqlite3_malloc(nPoslist+8);
  120905. if( !aOut ){
  120906. sqlite3_free(aPoslist);
  120907. return SQLITE_NOMEM;
  120908. }
  120909. pPhrase->doclist.pList = aOut;
  120910. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  120911. pPhrase->doclist.bFreeList = 1;
  120912. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  120913. }else{
  120914. sqlite3_free(aOut);
  120915. pPhrase->doclist.pList = 0;
  120916. pPhrase->doclist.nList = 0;
  120917. }
  120918. sqlite3_free(aPoslist);
  120919. }
  120920. }
  120921. return SQLITE_OK;
  120922. }
  120923. /*
  120924. ** Maximum number of tokens a phrase may have to be considered for the
  120925. ** incremental doclists strategy.
  120926. */
  120927. #define MAX_INCR_PHRASE_TOKENS 4
  120928. /*
  120929. ** This function is called for each Fts3Phrase in a full-text query
  120930. ** expression to initialize the mechanism for returning rows. Once this
  120931. ** function has been called successfully on an Fts3Phrase, it may be
  120932. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  120933. **
  120934. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  120935. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  120936. ** memory within this call.
  120937. **
  120938. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  120939. */
  120940. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  120941. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  120942. int rc = SQLITE_OK; /* Error code */
  120943. int i;
  120944. /* Determine if doclists may be loaded from disk incrementally. This is
  120945. ** possible if the bOptOk argument is true, the FTS doclists will be
  120946. ** scanned in forward order, and the phrase consists of
  120947. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  120948. ** tokens or prefix tokens that cannot use a prefix-index. */
  120949. int bHaveIncr = 0;
  120950. int bIncrOk = (bOptOk
  120951. && pCsr->bDesc==pTab->bDescIdx
  120952. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  120953. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  120954. #ifdef SQLITE_TEST
  120955. && pTab->bNoIncrDoclist==0
  120956. #endif
  120957. );
  120958. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  120959. Fts3PhraseToken *pToken = &p->aToken[i];
  120960. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  120961. bIncrOk = 0;
  120962. }
  120963. if( pToken->pSegcsr ) bHaveIncr = 1;
  120964. }
  120965. if( bIncrOk && bHaveIncr ){
  120966. /* Use the incremental approach. */
  120967. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  120968. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  120969. Fts3PhraseToken *pToken = &p->aToken[i];
  120970. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  120971. if( pSegcsr ){
  120972. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  120973. }
  120974. }
  120975. p->bIncr = 1;
  120976. }else{
  120977. /* Load the full doclist for the phrase into memory. */
  120978. rc = fts3EvalPhraseLoad(pCsr, p);
  120979. p->bIncr = 0;
  120980. }
  120981. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  120982. return rc;
  120983. }
  120984. /*
  120985. ** This function is used to iterate backwards (from the end to start)
  120986. ** through doclists. It is used by this module to iterate through phrase
  120987. ** doclists in reverse and by the fts3_write.c module to iterate through
  120988. ** pending-terms lists when writing to databases with "order=desc".
  120989. **
  120990. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  120991. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  120992. ** function iterates from the end of the doclist to the beginning.
  120993. */
  120994. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  120995. int bDescIdx, /* True if the doclist is desc */
  120996. char *aDoclist, /* Pointer to entire doclist */
  120997. int nDoclist, /* Length of aDoclist in bytes */
  120998. char **ppIter, /* IN/OUT: Iterator pointer */
  120999. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  121000. int *pnList, /* OUT: List length pointer */
  121001. u8 *pbEof /* OUT: End-of-file flag */
  121002. ){
  121003. char *p = *ppIter;
  121004. assert( nDoclist>0 );
  121005. assert( *pbEof==0 );
  121006. assert( p || *piDocid==0 );
  121007. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  121008. if( p==0 ){
  121009. sqlite3_int64 iDocid = 0;
  121010. char *pNext = 0;
  121011. char *pDocid = aDoclist;
  121012. char *pEnd = &aDoclist[nDoclist];
  121013. int iMul = 1;
  121014. while( pDocid<pEnd ){
  121015. sqlite3_int64 iDelta;
  121016. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  121017. iDocid += (iMul * iDelta);
  121018. pNext = pDocid;
  121019. fts3PoslistCopy(0, &pDocid);
  121020. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  121021. iMul = (bDescIdx ? -1 : 1);
  121022. }
  121023. *pnList = (int)(pEnd - pNext);
  121024. *ppIter = pNext;
  121025. *piDocid = iDocid;
  121026. }else{
  121027. int iMul = (bDescIdx ? -1 : 1);
  121028. sqlite3_int64 iDelta;
  121029. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  121030. *piDocid -= (iMul * iDelta);
  121031. if( p==aDoclist ){
  121032. *pbEof = 1;
  121033. }else{
  121034. char *pSave = p;
  121035. fts3ReversePoslist(aDoclist, &p);
  121036. *pnList = (int)(pSave - p);
  121037. }
  121038. *ppIter = p;
  121039. }
  121040. }
  121041. /*
  121042. ** Iterate forwards through a doclist.
  121043. */
  121044. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  121045. int bDescIdx, /* True if the doclist is desc */
  121046. char *aDoclist, /* Pointer to entire doclist */
  121047. int nDoclist, /* Length of aDoclist in bytes */
  121048. char **ppIter, /* IN/OUT: Iterator pointer */
  121049. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  121050. u8 *pbEof /* OUT: End-of-file flag */
  121051. ){
  121052. char *p = *ppIter;
  121053. assert( nDoclist>0 );
  121054. assert( *pbEof==0 );
  121055. assert( p || *piDocid==0 );
  121056. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  121057. if( p==0 ){
  121058. p = aDoclist;
  121059. p += sqlite3Fts3GetVarint(p, piDocid);
  121060. }else{
  121061. fts3PoslistCopy(0, &p);
  121062. if( p>=&aDoclist[nDoclist] ){
  121063. *pbEof = 1;
  121064. }else{
  121065. sqlite3_int64 iVar;
  121066. p += sqlite3Fts3GetVarint(p, &iVar);
  121067. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  121068. }
  121069. }
  121070. *ppIter = p;
  121071. }
  121072. /*
  121073. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  121074. ** to true if EOF is reached.
  121075. */
  121076. static void fts3EvalDlPhraseNext(
  121077. Fts3Table *pTab,
  121078. Fts3Doclist *pDL,
  121079. u8 *pbEof
  121080. ){
  121081. char *pIter; /* Used to iterate through aAll */
  121082. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  121083. if( pDL->pNextDocid ){
  121084. pIter = pDL->pNextDocid;
  121085. }else{
  121086. pIter = pDL->aAll;
  121087. }
  121088. if( pIter>=pEnd ){
  121089. /* We have already reached the end of this doclist. EOF. */
  121090. *pbEof = 1;
  121091. }else{
  121092. sqlite3_int64 iDelta;
  121093. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  121094. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  121095. pDL->iDocid += iDelta;
  121096. }else{
  121097. pDL->iDocid -= iDelta;
  121098. }
  121099. pDL->pList = pIter;
  121100. fts3PoslistCopy(0, &pIter);
  121101. pDL->nList = (int)(pIter - pDL->pList);
  121102. /* pIter now points just past the 0x00 that terminates the position-
  121103. ** list for document pDL->iDocid. However, if this position-list was
  121104. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  121105. ** point to the start of the next docid value. The following line deals
  121106. ** with this case by advancing pIter past the zero-padding added by
  121107. ** fts3EvalNearTrim(). */
  121108. while( pIter<pEnd && *pIter==0 ) pIter++;
  121109. pDL->pNextDocid = pIter;
  121110. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  121111. *pbEof = 0;
  121112. }
  121113. }
  121114. /*
  121115. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  121116. */
  121117. typedef struct TokenDoclist TokenDoclist;
  121118. struct TokenDoclist {
  121119. int bIgnore;
  121120. sqlite3_int64 iDocid;
  121121. char *pList;
  121122. int nList;
  121123. };
  121124. /*
  121125. ** Token pToken is an incrementally loaded token that is part of a
  121126. ** multi-token phrase. Advance it to the next matching document in the
  121127. ** database and populate output variable *p with the details of the new
  121128. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  121129. **
  121130. ** If an error occurs, return an SQLite error code. Otherwise, return
  121131. ** SQLITE_OK.
  121132. */
  121133. static int incrPhraseTokenNext(
  121134. Fts3Table *pTab, /* Virtual table handle */
  121135. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  121136. int iToken, /* Specific token to advance */
  121137. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  121138. u8 *pbEof /* OUT: True if iterator is at EOF */
  121139. ){
  121140. int rc = SQLITE_OK;
  121141. if( pPhrase->iDoclistToken==iToken ){
  121142. assert( p->bIgnore==0 );
  121143. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  121144. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  121145. p->pList = pPhrase->doclist.pList;
  121146. p->nList = pPhrase->doclist.nList;
  121147. p->iDocid = pPhrase->doclist.iDocid;
  121148. }else{
  121149. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  121150. assert( pToken->pDeferred==0 );
  121151. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  121152. if( pToken->pSegcsr ){
  121153. assert( p->bIgnore==0 );
  121154. rc = sqlite3Fts3MsrIncrNext(
  121155. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  121156. );
  121157. if( p->pList==0 ) *pbEof = 1;
  121158. }else{
  121159. p->bIgnore = 1;
  121160. }
  121161. }
  121162. return rc;
  121163. }
  121164. /*
  121165. ** The phrase iterator passed as the second argument:
  121166. **
  121167. ** * features at least one token that uses an incremental doclist, and
  121168. **
  121169. ** * does not contain any deferred tokens.
  121170. **
  121171. ** Advance it to the next matching documnent in the database and populate
  121172. ** the Fts3Doclist.pList and nList fields.
  121173. **
  121174. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  121175. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  121176. ** successfully advanced, *pbEof is set to 0.
  121177. **
  121178. ** If an error occurs, return an SQLite error code. Otherwise, return
  121179. ** SQLITE_OK.
  121180. */
  121181. static int fts3EvalIncrPhraseNext(
  121182. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121183. Fts3Phrase *p, /* Phrase object to advance to next docid */
  121184. u8 *pbEof /* OUT: Set to 1 if EOF */
  121185. ){
  121186. int rc = SQLITE_OK;
  121187. Fts3Doclist *pDL = &p->doclist;
  121188. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121189. u8 bEof = 0;
  121190. /* This is only called if it is guaranteed that the phrase has at least
  121191. ** one incremental token. In which case the bIncr flag is set. */
  121192. assert( p->bIncr==1 );
  121193. if( p->nToken==1 && p->bIncr ){
  121194. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  121195. &pDL->iDocid, &pDL->pList, &pDL->nList
  121196. );
  121197. if( pDL->pList==0 ) bEof = 1;
  121198. }else{
  121199. int bDescDoclist = pCsr->bDesc;
  121200. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  121201. memset(a, 0, sizeof(a));
  121202. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  121203. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  121204. while( bEof==0 ){
  121205. int bMaxSet = 0;
  121206. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  121207. int i; /* Used to iterate through tokens */
  121208. /* Advance the iterator for each token in the phrase once. */
  121209. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  121210. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  121211. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  121212. iMax = a[i].iDocid;
  121213. bMaxSet = 1;
  121214. }
  121215. }
  121216. assert( rc!=SQLITE_OK || a[p->nToken-1].bIgnore==0 );
  121217. assert( rc!=SQLITE_OK || bMaxSet );
  121218. /* Keep advancing iterators until they all point to the same document */
  121219. for(i=0; i<p->nToken; i++){
  121220. while( rc==SQLITE_OK && bEof==0
  121221. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  121222. ){
  121223. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  121224. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  121225. iMax = a[i].iDocid;
  121226. i = 0;
  121227. }
  121228. }
  121229. }
  121230. /* Check if the current entries really are a phrase match */
  121231. if( bEof==0 ){
  121232. int nList = 0;
  121233. int nByte = a[p->nToken-1].nList;
  121234. char *aDoclist = sqlite3_malloc(nByte+1);
  121235. if( !aDoclist ) return SQLITE_NOMEM;
  121236. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  121237. for(i=0; i<(p->nToken-1); i++){
  121238. if( a[i].bIgnore==0 ){
  121239. char *pL = a[i].pList;
  121240. char *pR = aDoclist;
  121241. char *pOut = aDoclist;
  121242. int nDist = p->nToken-1-i;
  121243. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  121244. if( res==0 ) break;
  121245. nList = (int)(pOut - aDoclist);
  121246. }
  121247. }
  121248. if( i==(p->nToken-1) ){
  121249. pDL->iDocid = iMax;
  121250. pDL->pList = aDoclist;
  121251. pDL->nList = nList;
  121252. pDL->bFreeList = 1;
  121253. break;
  121254. }
  121255. sqlite3_free(aDoclist);
  121256. }
  121257. }
  121258. }
  121259. *pbEof = bEof;
  121260. return rc;
  121261. }
  121262. /*
  121263. ** Attempt to move the phrase iterator to point to the next matching docid.
  121264. ** If an error occurs, return an SQLite error code. Otherwise, return
  121265. ** SQLITE_OK.
  121266. **
  121267. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  121268. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  121269. ** successfully advanced, *pbEof is set to 0.
  121270. */
  121271. static int fts3EvalPhraseNext(
  121272. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121273. Fts3Phrase *p, /* Phrase object to advance to next docid */
  121274. u8 *pbEof /* OUT: Set to 1 if EOF */
  121275. ){
  121276. int rc = SQLITE_OK;
  121277. Fts3Doclist *pDL = &p->doclist;
  121278. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121279. if( p->bIncr ){
  121280. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  121281. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  121282. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  121283. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  121284. );
  121285. pDL->pList = pDL->pNextDocid;
  121286. }else{
  121287. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  121288. }
  121289. return rc;
  121290. }
  121291. /*
  121292. **
  121293. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121294. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  121295. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  121296. ** expressions for which all descendent tokens are deferred.
  121297. **
  121298. ** If parameter bOptOk is zero, then it is guaranteed that the
  121299. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  121300. ** each phrase in the expression (subject to deferred token processing).
  121301. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  121302. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  121303. **
  121304. ** If an error occurs within this function, *pRc is set to an SQLite error
  121305. ** code before returning.
  121306. */
  121307. static void fts3EvalStartReaders(
  121308. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121309. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  121310. int *pRc /* IN/OUT: Error code */
  121311. ){
  121312. if( pExpr && SQLITE_OK==*pRc ){
  121313. if( pExpr->eType==FTSQUERY_PHRASE ){
  121314. int i;
  121315. int nToken = pExpr->pPhrase->nToken;
  121316. for(i=0; i<nToken; i++){
  121317. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  121318. }
  121319. pExpr->bDeferred = (i==nToken);
  121320. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  121321. }else{
  121322. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  121323. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  121324. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  121325. }
  121326. }
  121327. }
  121328. /*
  121329. ** An array of the following structures is assembled as part of the process
  121330. ** of selecting tokens to defer before the query starts executing (as part
  121331. ** of the xFilter() method). There is one element in the array for each
  121332. ** token in the FTS expression.
  121333. **
  121334. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  121335. ** to phrases that are connected only by AND and NEAR operators (not OR or
  121336. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  121337. ** separately. The root of a tokens AND/NEAR cluster is stored in
  121338. ** Fts3TokenAndCost.pRoot.
  121339. */
  121340. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  121341. struct Fts3TokenAndCost {
  121342. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  121343. int iToken; /* Position of token in phrase */
  121344. Fts3PhraseToken *pToken; /* The token itself */
  121345. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  121346. int nOvfl; /* Number of overflow pages to load doclist */
  121347. int iCol; /* The column the token must match */
  121348. };
  121349. /*
  121350. ** This function is used to populate an allocated Fts3TokenAndCost array.
  121351. **
  121352. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121353. ** Otherwise, if an error occurs during execution, *pRc is set to an
  121354. ** SQLite error code.
  121355. */
  121356. static void fts3EvalTokenCosts(
  121357. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121358. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  121359. Fts3Expr *pExpr, /* Expression to consider */
  121360. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  121361. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  121362. int *pRc /* IN/OUT: Error code */
  121363. ){
  121364. if( *pRc==SQLITE_OK ){
  121365. if( pExpr->eType==FTSQUERY_PHRASE ){
  121366. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121367. int i;
  121368. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  121369. Fts3TokenAndCost *pTC = (*ppTC)++;
  121370. pTC->pPhrase = pPhrase;
  121371. pTC->iToken = i;
  121372. pTC->pRoot = pRoot;
  121373. pTC->pToken = &pPhrase->aToken[i];
  121374. pTC->iCol = pPhrase->iColumn;
  121375. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  121376. }
  121377. }else if( pExpr->eType!=FTSQUERY_NOT ){
  121378. assert( pExpr->eType==FTSQUERY_OR
  121379. || pExpr->eType==FTSQUERY_AND
  121380. || pExpr->eType==FTSQUERY_NEAR
  121381. );
  121382. assert( pExpr->pLeft && pExpr->pRight );
  121383. if( pExpr->eType==FTSQUERY_OR ){
  121384. pRoot = pExpr->pLeft;
  121385. **ppOr = pRoot;
  121386. (*ppOr)++;
  121387. }
  121388. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  121389. if( pExpr->eType==FTSQUERY_OR ){
  121390. pRoot = pExpr->pRight;
  121391. **ppOr = pRoot;
  121392. (*ppOr)++;
  121393. }
  121394. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  121395. }
  121396. }
  121397. }
  121398. /*
  121399. ** Determine the average document (row) size in pages. If successful,
  121400. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  121401. ** an SQLite error code.
  121402. **
  121403. ** The average document size in pages is calculated by first calculating
  121404. ** determining the average size in bytes, B. If B is less than the amount
  121405. ** of data that will fit on a single leaf page of an intkey table in
  121406. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  121407. ** the number of overflow pages consumed by a record B bytes in size.
  121408. */
  121409. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  121410. if( pCsr->nRowAvg==0 ){
  121411. /* The average document size, which is required to calculate the cost
  121412. ** of each doclist, has not yet been determined. Read the required
  121413. ** data from the %_stat table to calculate it.
  121414. **
  121415. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  121416. ** varints, where nCol is the number of columns in the FTS3 table.
  121417. ** The first varint is the number of documents currently stored in
  121418. ** the table. The following nCol varints contain the total amount of
  121419. ** data stored in all rows of each column of the table, from left
  121420. ** to right.
  121421. */
  121422. int rc;
  121423. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  121424. sqlite3_stmt *pStmt;
  121425. sqlite3_int64 nDoc = 0;
  121426. sqlite3_int64 nByte = 0;
  121427. const char *pEnd;
  121428. const char *a;
  121429. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  121430. if( rc!=SQLITE_OK ) return rc;
  121431. a = sqlite3_column_blob(pStmt, 0);
  121432. assert( a );
  121433. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  121434. a += sqlite3Fts3GetVarint(a, &nDoc);
  121435. while( a<pEnd ){
  121436. a += sqlite3Fts3GetVarint(a, &nByte);
  121437. }
  121438. if( nDoc==0 || nByte==0 ){
  121439. sqlite3_reset(pStmt);
  121440. return FTS_CORRUPT_VTAB;
  121441. }
  121442. pCsr->nDoc = nDoc;
  121443. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  121444. assert( pCsr->nRowAvg>0 );
  121445. rc = sqlite3_reset(pStmt);
  121446. if( rc!=SQLITE_OK ) return rc;
  121447. }
  121448. *pnPage = pCsr->nRowAvg;
  121449. return SQLITE_OK;
  121450. }
  121451. /*
  121452. ** This function is called to select the tokens (if any) that will be
  121453. ** deferred. The array aTC[] has already been populated when this is
  121454. ** called.
  121455. **
  121456. ** This function is called once for each AND/NEAR cluster in the
  121457. ** expression. Each invocation determines which tokens to defer within
  121458. ** the cluster with root node pRoot. See comments above the definition
  121459. ** of struct Fts3TokenAndCost for more details.
  121460. **
  121461. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  121462. ** called on each token to defer. Otherwise, an SQLite error code is
  121463. ** returned.
  121464. */
  121465. static int fts3EvalSelectDeferred(
  121466. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121467. Fts3Expr *pRoot, /* Consider tokens with this root node */
  121468. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  121469. int nTC /* Number of entries in aTC[] */
  121470. ){
  121471. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121472. int nDocSize = 0; /* Number of pages per doc loaded */
  121473. int rc = SQLITE_OK; /* Return code */
  121474. int ii; /* Iterator variable for various purposes */
  121475. int nOvfl = 0; /* Total overflow pages used by doclists */
  121476. int nToken = 0; /* Total number of tokens in cluster */
  121477. int nMinEst = 0; /* The minimum count for any phrase so far. */
  121478. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  121479. /* Tokens are never deferred for FTS tables created using the content=xxx
  121480. ** option. The reason being that it is not guaranteed that the content
  121481. ** table actually contains the same data as the index. To prevent this from
  121482. ** causing any problems, the deferred token optimization is completely
  121483. ** disabled for content=xxx tables. */
  121484. if( pTab->zContentTbl ){
  121485. return SQLITE_OK;
  121486. }
  121487. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  121488. ** associated with the tokens spill onto overflow pages, or if there is
  121489. ** only 1 token, exit early. No tokens to defer in this case. */
  121490. for(ii=0; ii<nTC; ii++){
  121491. if( aTC[ii].pRoot==pRoot ){
  121492. nOvfl += aTC[ii].nOvfl;
  121493. nToken++;
  121494. }
  121495. }
  121496. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  121497. /* Obtain the average docsize (in pages). */
  121498. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  121499. assert( rc!=SQLITE_OK || nDocSize>0 );
  121500. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  121501. ** of the number of overflow pages that will be loaded by the pager layer
  121502. ** to retrieve the entire doclist for the token from the full-text index.
  121503. ** Load the doclists for tokens that are either:
  121504. **
  121505. ** a. The cheapest token in the entire query (i.e. the one visited by the
  121506. ** first iteration of this loop), or
  121507. **
  121508. ** b. Part of a multi-token phrase.
  121509. **
  121510. ** After each token doclist is loaded, merge it with the others from the
  121511. ** same phrase and count the number of documents that the merged doclist
  121512. ** contains. Set variable "nMinEst" to the smallest number of documents in
  121513. ** any phrase doclist for which 1 or more token doclists have been loaded.
  121514. ** Let nOther be the number of other phrases for which it is certain that
  121515. ** one or more tokens will not be deferred.
  121516. **
  121517. ** Then, for each token, defer it if loading the doclist would result in
  121518. ** loading N or more overflow pages into memory, where N is computed as:
  121519. **
  121520. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  121521. */
  121522. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  121523. int iTC; /* Used to iterate through aTC[] array. */
  121524. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  121525. /* Set pTC to point to the cheapest remaining token. */
  121526. for(iTC=0; iTC<nTC; iTC++){
  121527. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  121528. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  121529. ){
  121530. pTC = &aTC[iTC];
  121531. }
  121532. }
  121533. assert( pTC );
  121534. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  121535. /* The number of overflow pages to load for this (and therefore all
  121536. ** subsequent) tokens is greater than the estimated number of pages
  121537. ** that will be loaded if all subsequent tokens are deferred.
  121538. */
  121539. Fts3PhraseToken *pToken = pTC->pToken;
  121540. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  121541. fts3SegReaderCursorFree(pToken->pSegcsr);
  121542. pToken->pSegcsr = 0;
  121543. }else{
  121544. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  121545. ** for-loop. Except, limit the value to 2^24 to prevent it from
  121546. ** overflowing the 32-bit integer it is stored in. */
  121547. if( ii<12 ) nLoad4 = nLoad4*4;
  121548. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  121549. /* Either this is the cheapest token in the entire query, or it is
  121550. ** part of a multi-token phrase. Either way, the entire doclist will
  121551. ** (eventually) be loaded into memory. It may as well be now. */
  121552. Fts3PhraseToken *pToken = pTC->pToken;
  121553. int nList = 0;
  121554. char *pList = 0;
  121555. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  121556. assert( rc==SQLITE_OK || pList==0 );
  121557. if( rc==SQLITE_OK ){
  121558. int nCount;
  121559. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  121560. nCount = fts3DoclistCountDocids(
  121561. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  121562. );
  121563. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  121564. }
  121565. }
  121566. }
  121567. pTC->pToken = 0;
  121568. }
  121569. return rc;
  121570. }
  121571. /*
  121572. ** This function is called from within the xFilter method. It initializes
  121573. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  121574. ** the results of a query, the caller does:
  121575. **
  121576. ** fts3EvalStart(pCsr);
  121577. ** while( 1 ){
  121578. ** fts3EvalNext(pCsr);
  121579. ** if( pCsr->bEof ) break;
  121580. ** ... return row pCsr->iPrevId to the caller ...
  121581. ** }
  121582. */
  121583. static int fts3EvalStart(Fts3Cursor *pCsr){
  121584. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  121585. int rc = SQLITE_OK;
  121586. int nToken = 0;
  121587. int nOr = 0;
  121588. /* Allocate a MultiSegReader for each token in the expression. */
  121589. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  121590. /* Determine which, if any, tokens in the expression should be deferred. */
  121591. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121592. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  121593. Fts3TokenAndCost *aTC;
  121594. Fts3Expr **apOr;
  121595. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  121596. sizeof(Fts3TokenAndCost) * nToken
  121597. + sizeof(Fts3Expr *) * nOr * 2
  121598. );
  121599. apOr = (Fts3Expr **)&aTC[nToken];
  121600. if( !aTC ){
  121601. rc = SQLITE_NOMEM;
  121602. }else{
  121603. int ii;
  121604. Fts3TokenAndCost *pTC = aTC;
  121605. Fts3Expr **ppOr = apOr;
  121606. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  121607. nToken = (int)(pTC-aTC);
  121608. nOr = (int)(ppOr-apOr);
  121609. if( rc==SQLITE_OK ){
  121610. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  121611. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  121612. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  121613. }
  121614. }
  121615. sqlite3_free(aTC);
  121616. }
  121617. }
  121618. #endif
  121619. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  121620. return rc;
  121621. }
  121622. /*
  121623. ** Invalidate the current position list for phrase pPhrase.
  121624. */
  121625. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  121626. if( pPhrase->doclist.bFreeList ){
  121627. sqlite3_free(pPhrase->doclist.pList);
  121628. }
  121629. pPhrase->doclist.pList = 0;
  121630. pPhrase->doclist.nList = 0;
  121631. pPhrase->doclist.bFreeList = 0;
  121632. }
  121633. /*
  121634. ** This function is called to edit the position list associated with
  121635. ** the phrase object passed as the fifth argument according to a NEAR
  121636. ** condition. For example:
  121637. **
  121638. ** abc NEAR/5 "def ghi"
  121639. **
  121640. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  121641. ** the example above). When this function is called, *paPoslist points to
  121642. ** the position list, and *pnToken is the number of phrase tokens in, the
  121643. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  121644. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  121645. ** the position list associated with phrase "abc".
  121646. **
  121647. ** All positions in the pPhrase position list that are not sufficiently
  121648. ** close to a position in the *paPoslist position list are removed. If this
  121649. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  121650. **
  121651. ** Before returning, *paPoslist is set to point to the position lsit
  121652. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  121653. ** pPhrase.
  121654. */
  121655. static int fts3EvalNearTrim(
  121656. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  121657. char *aTmp, /* Temporary space to use */
  121658. char **paPoslist, /* IN/OUT: Position list */
  121659. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  121660. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  121661. ){
  121662. int nParam1 = nNear + pPhrase->nToken;
  121663. int nParam2 = nNear + *pnToken;
  121664. int nNew;
  121665. char *p2;
  121666. char *pOut;
  121667. int res;
  121668. assert( pPhrase->doclist.pList );
  121669. p2 = pOut = pPhrase->doclist.pList;
  121670. res = fts3PoslistNearMerge(
  121671. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  121672. );
  121673. if( res ){
  121674. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  121675. assert( pPhrase->doclist.pList[nNew]=='\0' );
  121676. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  121677. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  121678. pPhrase->doclist.nList = nNew;
  121679. *paPoslist = pPhrase->doclist.pList;
  121680. *pnToken = pPhrase->nToken;
  121681. }
  121682. return res;
  121683. }
  121684. /*
  121685. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  121686. ** Otherwise, it advances the expression passed as the second argument to
  121687. ** point to the next matching row in the database. Expressions iterate through
  121688. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  121689. ** or descending if it is non-zero.
  121690. **
  121691. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  121692. ** successful, the following variables in pExpr are set:
  121693. **
  121694. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  121695. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  121696. **
  121697. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  121698. ** at EOF, then the following variables are populated with the position list
  121699. ** for the phrase for the visited row:
  121700. **
  121701. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  121702. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  121703. **
  121704. ** It says above that this function advances the expression to the next
  121705. ** matching row. This is usually true, but there are the following exceptions:
  121706. **
  121707. ** 1. Deferred tokens are not taken into account. If a phrase consists
  121708. ** entirely of deferred tokens, it is assumed to match every row in
  121709. ** the db. In this case the position-list is not populated at all.
  121710. **
  121711. ** Or, if a phrase contains one or more deferred tokens and one or
  121712. ** more non-deferred tokens, then the expression is advanced to the
  121713. ** next possible match, considering only non-deferred tokens. In other
  121714. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  121715. ** is advanced to the next row that contains an instance of "A * C",
  121716. ** where "*" may match any single token. The position list in this case
  121717. ** is populated as for "A * C" before returning.
  121718. **
  121719. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  121720. ** advanced to point to the next row that matches "x AND y".
  121721. **
  121722. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  121723. ** really a match, taking into account deferred tokens and NEAR operators.
  121724. */
  121725. static void fts3EvalNextRow(
  121726. Fts3Cursor *pCsr, /* FTS Cursor handle */
  121727. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  121728. int *pRc /* IN/OUT: Error code */
  121729. ){
  121730. if( *pRc==SQLITE_OK ){
  121731. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  121732. assert( pExpr->bEof==0 );
  121733. pExpr->bStart = 1;
  121734. switch( pExpr->eType ){
  121735. case FTSQUERY_NEAR:
  121736. case FTSQUERY_AND: {
  121737. Fts3Expr *pLeft = pExpr->pLeft;
  121738. Fts3Expr *pRight = pExpr->pRight;
  121739. assert( !pLeft->bDeferred || !pRight->bDeferred );
  121740. if( pLeft->bDeferred ){
  121741. /* LHS is entirely deferred. So we assume it matches every row.
  121742. ** Advance the RHS iterator to find the next row visited. */
  121743. fts3EvalNextRow(pCsr, pRight, pRc);
  121744. pExpr->iDocid = pRight->iDocid;
  121745. pExpr->bEof = pRight->bEof;
  121746. }else if( pRight->bDeferred ){
  121747. /* RHS is entirely deferred. So we assume it matches every row.
  121748. ** Advance the LHS iterator to find the next row visited. */
  121749. fts3EvalNextRow(pCsr, pLeft, pRc);
  121750. pExpr->iDocid = pLeft->iDocid;
  121751. pExpr->bEof = pLeft->bEof;
  121752. }else{
  121753. /* Neither the RHS or LHS are deferred. */
  121754. fts3EvalNextRow(pCsr, pLeft, pRc);
  121755. fts3EvalNextRow(pCsr, pRight, pRc);
  121756. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  121757. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121758. if( iDiff==0 ) break;
  121759. if( iDiff<0 ){
  121760. fts3EvalNextRow(pCsr, pLeft, pRc);
  121761. }else{
  121762. fts3EvalNextRow(pCsr, pRight, pRc);
  121763. }
  121764. }
  121765. pExpr->iDocid = pLeft->iDocid;
  121766. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  121767. }
  121768. break;
  121769. }
  121770. case FTSQUERY_OR: {
  121771. Fts3Expr *pLeft = pExpr->pLeft;
  121772. Fts3Expr *pRight = pExpr->pRight;
  121773. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121774. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  121775. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  121776. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  121777. fts3EvalNextRow(pCsr, pLeft, pRc);
  121778. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  121779. fts3EvalNextRow(pCsr, pRight, pRc);
  121780. }else{
  121781. fts3EvalNextRow(pCsr, pLeft, pRc);
  121782. fts3EvalNextRow(pCsr, pRight, pRc);
  121783. }
  121784. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  121785. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  121786. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  121787. pExpr->iDocid = pLeft->iDocid;
  121788. }else{
  121789. pExpr->iDocid = pRight->iDocid;
  121790. }
  121791. break;
  121792. }
  121793. case FTSQUERY_NOT: {
  121794. Fts3Expr *pLeft = pExpr->pLeft;
  121795. Fts3Expr *pRight = pExpr->pRight;
  121796. if( pRight->bStart==0 ){
  121797. fts3EvalNextRow(pCsr, pRight, pRc);
  121798. assert( *pRc!=SQLITE_OK || pRight->bStart );
  121799. }
  121800. fts3EvalNextRow(pCsr, pLeft, pRc);
  121801. if( pLeft->bEof==0 ){
  121802. while( !*pRc
  121803. && !pRight->bEof
  121804. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  121805. ){
  121806. fts3EvalNextRow(pCsr, pRight, pRc);
  121807. }
  121808. }
  121809. pExpr->iDocid = pLeft->iDocid;
  121810. pExpr->bEof = pLeft->bEof;
  121811. break;
  121812. }
  121813. default: {
  121814. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121815. fts3EvalInvalidatePoslist(pPhrase);
  121816. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  121817. pExpr->iDocid = pPhrase->doclist.iDocid;
  121818. break;
  121819. }
  121820. }
  121821. }
  121822. }
  121823. /*
  121824. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  121825. ** cluster, then this function returns 1 immediately.
  121826. **
  121827. ** Otherwise, it checks if the current row really does match the NEAR
  121828. ** expression, using the data currently stored in the position lists
  121829. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  121830. **
  121831. ** If the current row is a match, the position list associated with each
  121832. ** phrase in the NEAR expression is edited in place to contain only those
  121833. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  121834. ** constraints. In this case it returns 1. If the NEAR expression does not
  121835. ** match the current row, 0 is returned. The position lists may or may not
  121836. ** be edited if 0 is returned.
  121837. */
  121838. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  121839. int res = 1;
  121840. /* The following block runs if pExpr is the root of a NEAR query.
  121841. ** For example, the query:
  121842. **
  121843. ** "w" NEAR "x" NEAR "y" NEAR "z"
  121844. **
  121845. ** which is represented in tree form as:
  121846. **
  121847. ** |
  121848. ** +--NEAR--+ <-- root of NEAR query
  121849. ** | |
  121850. ** +--NEAR--+ "z"
  121851. ** | |
  121852. ** +--NEAR--+ "y"
  121853. ** | |
  121854. ** "w" "x"
  121855. **
  121856. ** The right-hand child of a NEAR node is always a phrase. The
  121857. ** left-hand child may be either a phrase or a NEAR node. There are
  121858. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  121859. */
  121860. if( *pRc==SQLITE_OK
  121861. && pExpr->eType==FTSQUERY_NEAR
  121862. && pExpr->bEof==0
  121863. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  121864. ){
  121865. Fts3Expr *p;
  121866. int nTmp = 0; /* Bytes of temp space */
  121867. char *aTmp; /* Temp space for PoslistNearMerge() */
  121868. /* Allocate temporary working space. */
  121869. for(p=pExpr; p->pLeft; p=p->pLeft){
  121870. nTmp += p->pRight->pPhrase->doclist.nList;
  121871. }
  121872. nTmp += p->pPhrase->doclist.nList;
  121873. if( nTmp==0 ){
  121874. res = 0;
  121875. }else{
  121876. aTmp = sqlite3_malloc(nTmp*2);
  121877. if( !aTmp ){
  121878. *pRc = SQLITE_NOMEM;
  121879. res = 0;
  121880. }else{
  121881. char *aPoslist = p->pPhrase->doclist.pList;
  121882. int nToken = p->pPhrase->nToken;
  121883. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  121884. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  121885. int nNear = p->nNear;
  121886. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  121887. }
  121888. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  121889. nToken = pExpr->pRight->pPhrase->nToken;
  121890. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  121891. int nNear;
  121892. Fts3Phrase *pPhrase;
  121893. assert( p->pParent && p->pParent->pLeft==p );
  121894. nNear = p->pParent->nNear;
  121895. pPhrase = (
  121896. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  121897. );
  121898. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  121899. }
  121900. }
  121901. sqlite3_free(aTmp);
  121902. }
  121903. }
  121904. return res;
  121905. }
  121906. /*
  121907. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  121908. ** Assuming no error occurs or has occurred, It returns non-zero if the
  121909. ** expression passed as the second argument matches the row that pCsr
  121910. ** currently points to, or zero if it does not.
  121911. **
  121912. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  121913. ** If an error occurs during execution of this function, *pRc is set to
  121914. ** the appropriate SQLite error code. In this case the returned value is
  121915. ** undefined.
  121916. */
  121917. static int fts3EvalTestExpr(
  121918. Fts3Cursor *pCsr, /* FTS cursor handle */
  121919. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  121920. int *pRc /* IN/OUT: Error code */
  121921. ){
  121922. int bHit = 1; /* Return value */
  121923. if( *pRc==SQLITE_OK ){
  121924. switch( pExpr->eType ){
  121925. case FTSQUERY_NEAR:
  121926. case FTSQUERY_AND:
  121927. bHit = (
  121928. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  121929. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  121930. && fts3EvalNearTest(pExpr, pRc)
  121931. );
  121932. /* If the NEAR expression does not match any rows, zero the doclist for
  121933. ** all phrases involved in the NEAR. This is because the snippet(),
  121934. ** offsets() and matchinfo() functions are not supposed to recognize
  121935. ** any instances of phrases that are part of unmatched NEAR queries.
  121936. ** For example if this expression:
  121937. **
  121938. ** ... MATCH 'a OR (b NEAR c)'
  121939. **
  121940. ** is matched against a row containing:
  121941. **
  121942. ** 'a b d e'
  121943. **
  121944. ** then any snippet() should ony highlight the "a" term, not the "b"
  121945. ** (as "b" is part of a non-matching NEAR clause).
  121946. */
  121947. if( bHit==0
  121948. && pExpr->eType==FTSQUERY_NEAR
  121949. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  121950. ){
  121951. Fts3Expr *p;
  121952. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  121953. if( p->pRight->iDocid==pCsr->iPrevId ){
  121954. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  121955. }
  121956. }
  121957. if( p->iDocid==pCsr->iPrevId ){
  121958. fts3EvalInvalidatePoslist(p->pPhrase);
  121959. }
  121960. }
  121961. break;
  121962. case FTSQUERY_OR: {
  121963. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  121964. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  121965. bHit = bHit1 || bHit2;
  121966. break;
  121967. }
  121968. case FTSQUERY_NOT:
  121969. bHit = (
  121970. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  121971. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  121972. );
  121973. break;
  121974. default: {
  121975. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121976. if( pCsr->pDeferred
  121977. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  121978. ){
  121979. Fts3Phrase *pPhrase = pExpr->pPhrase;
  121980. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  121981. if( pExpr->bDeferred ){
  121982. fts3EvalInvalidatePoslist(pPhrase);
  121983. }
  121984. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  121985. bHit = (pPhrase->doclist.pList!=0);
  121986. pExpr->iDocid = pCsr->iPrevId;
  121987. }else
  121988. #endif
  121989. {
  121990. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  121991. }
  121992. break;
  121993. }
  121994. }
  121995. }
  121996. return bHit;
  121997. }
  121998. /*
  121999. ** This function is called as the second part of each xNext operation when
  122000. ** iterating through the results of a full-text query. At this point the
  122001. ** cursor points to a row that matches the query expression, with the
  122002. ** following caveats:
  122003. **
  122004. ** * Up until this point, "NEAR" operators in the expression have been
  122005. ** treated as "AND".
  122006. **
  122007. ** * Deferred tokens have not yet been considered.
  122008. **
  122009. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  122010. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  122011. ** operators and deferred tokens the current row is still a match for the
  122012. ** expression. It returns 1 if both of the following are true:
  122013. **
  122014. ** 1. *pRc is SQLITE_OK when this function returns, and
  122015. **
  122016. ** 2. After scanning the current FTS table row for the deferred tokens,
  122017. ** it is determined that the row does *not* match the query.
  122018. **
  122019. ** Or, if no error occurs and it seems the current row does match the FTS
  122020. ** query, return 0.
  122021. */
  122022. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  122023. int rc = *pRc;
  122024. int bMiss = 0;
  122025. if( rc==SQLITE_OK ){
  122026. /* If there are one or more deferred tokens, load the current row into
  122027. ** memory and scan it to determine the position list for each deferred
  122028. ** token. Then, see if this row is really a match, considering deferred
  122029. ** tokens and NEAR operators (neither of which were taken into account
  122030. ** earlier, by fts3EvalNextRow()).
  122031. */
  122032. if( pCsr->pDeferred ){
  122033. rc = fts3CursorSeek(0, pCsr);
  122034. if( rc==SQLITE_OK ){
  122035. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  122036. }
  122037. }
  122038. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  122039. /* Free the position-lists accumulated for each deferred token above. */
  122040. sqlite3Fts3FreeDeferredDoclists(pCsr);
  122041. *pRc = rc;
  122042. }
  122043. return (rc==SQLITE_OK && bMiss);
  122044. }
  122045. /*
  122046. ** Advance to the next document that matches the FTS expression in
  122047. ** Fts3Cursor.pExpr.
  122048. */
  122049. static int fts3EvalNext(Fts3Cursor *pCsr){
  122050. int rc = SQLITE_OK; /* Return Code */
  122051. Fts3Expr *pExpr = pCsr->pExpr;
  122052. assert( pCsr->isEof==0 );
  122053. if( pExpr==0 ){
  122054. pCsr->isEof = 1;
  122055. }else{
  122056. do {
  122057. if( pCsr->isRequireSeek==0 ){
  122058. sqlite3_reset(pCsr->pStmt);
  122059. }
  122060. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  122061. fts3EvalNextRow(pCsr, pExpr, &rc);
  122062. pCsr->isEof = pExpr->bEof;
  122063. pCsr->isRequireSeek = 1;
  122064. pCsr->isMatchinfoNeeded = 1;
  122065. pCsr->iPrevId = pExpr->iDocid;
  122066. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  122067. }
  122068. /* Check if the cursor is past the end of the docid range specified
  122069. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  122070. if( rc==SQLITE_OK && (
  122071. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  122072. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  122073. )){
  122074. pCsr->isEof = 1;
  122075. }
  122076. return rc;
  122077. }
  122078. /*
  122079. ** Restart interation for expression pExpr so that the next call to
  122080. ** fts3EvalNext() visits the first row. Do not allow incremental
  122081. ** loading or merging of phrase doclists for this iteration.
  122082. **
  122083. ** If *pRc is other than SQLITE_OK when this function is called, it is
  122084. ** a no-op. If an error occurs within this function, *pRc is set to an
  122085. ** SQLite error code before returning.
  122086. */
  122087. static void fts3EvalRestart(
  122088. Fts3Cursor *pCsr,
  122089. Fts3Expr *pExpr,
  122090. int *pRc
  122091. ){
  122092. if( pExpr && *pRc==SQLITE_OK ){
  122093. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122094. if( pPhrase ){
  122095. fts3EvalInvalidatePoslist(pPhrase);
  122096. if( pPhrase->bIncr ){
  122097. int i;
  122098. for(i=0; i<pPhrase->nToken; i++){
  122099. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  122100. assert( pToken->pDeferred==0 );
  122101. if( pToken->pSegcsr ){
  122102. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  122103. }
  122104. }
  122105. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  122106. }
  122107. pPhrase->doclist.pNextDocid = 0;
  122108. pPhrase->doclist.iDocid = 0;
  122109. }
  122110. pExpr->iDocid = 0;
  122111. pExpr->bEof = 0;
  122112. pExpr->bStart = 0;
  122113. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  122114. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  122115. }
  122116. }
  122117. /*
  122118. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  122119. ** expression rooted at pExpr, the cursor iterates through all rows matched
  122120. ** by pExpr, calling this function for each row. This function increments
  122121. ** the values in Fts3Expr.aMI[] according to the position-list currently
  122122. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  122123. ** expression nodes.
  122124. */
  122125. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  122126. if( pExpr ){
  122127. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122128. if( pPhrase && pPhrase->doclist.pList ){
  122129. int iCol = 0;
  122130. char *p = pPhrase->doclist.pList;
  122131. assert( *p );
  122132. while( 1 ){
  122133. u8 c = 0;
  122134. int iCnt = 0;
  122135. while( 0xFE & (*p | c) ){
  122136. if( (c&0x80)==0 ) iCnt++;
  122137. c = *p++ & 0x80;
  122138. }
  122139. /* aMI[iCol*3 + 1] = Number of occurrences
  122140. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  122141. */
  122142. pExpr->aMI[iCol*3 + 1] += iCnt;
  122143. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  122144. if( *p==0x00 ) break;
  122145. p++;
  122146. p += sqlite3Fts3GetVarint32(p, &iCol);
  122147. }
  122148. }
  122149. fts3EvalUpdateCounts(pExpr->pLeft);
  122150. fts3EvalUpdateCounts(pExpr->pRight);
  122151. }
  122152. }
  122153. /*
  122154. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  122155. **
  122156. ** If it is not already allocated and populated, this function allocates and
  122157. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  122158. ** of a NEAR expression, then it also allocates and populates the same array
  122159. ** for all other phrases that are part of the NEAR expression.
  122160. **
  122161. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  122162. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  122163. */
  122164. static int fts3EvalGatherStats(
  122165. Fts3Cursor *pCsr, /* Cursor object */
  122166. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  122167. ){
  122168. int rc = SQLITE_OK; /* Return code */
  122169. assert( pExpr->eType==FTSQUERY_PHRASE );
  122170. if( pExpr->aMI==0 ){
  122171. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122172. Fts3Expr *pRoot; /* Root of NEAR expression */
  122173. Fts3Expr *p; /* Iterator used for several purposes */
  122174. sqlite3_int64 iPrevId = pCsr->iPrevId;
  122175. sqlite3_int64 iDocid;
  122176. u8 bEof;
  122177. /* Find the root of the NEAR expression */
  122178. pRoot = pExpr;
  122179. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  122180. pRoot = pRoot->pParent;
  122181. }
  122182. iDocid = pRoot->iDocid;
  122183. bEof = pRoot->bEof;
  122184. assert( pRoot->bStart );
  122185. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  122186. for(p=pRoot; p; p=p->pLeft){
  122187. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  122188. assert( pE->aMI==0 );
  122189. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  122190. if( !pE->aMI ) return SQLITE_NOMEM;
  122191. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  122192. }
  122193. fts3EvalRestart(pCsr, pRoot, &rc);
  122194. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  122195. do {
  122196. /* Ensure the %_content statement is reset. */
  122197. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  122198. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  122199. /* Advance to the next document */
  122200. fts3EvalNextRow(pCsr, pRoot, &rc);
  122201. pCsr->isEof = pRoot->bEof;
  122202. pCsr->isRequireSeek = 1;
  122203. pCsr->isMatchinfoNeeded = 1;
  122204. pCsr->iPrevId = pRoot->iDocid;
  122205. }while( pCsr->isEof==0
  122206. && pRoot->eType==FTSQUERY_NEAR
  122207. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  122208. );
  122209. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  122210. fts3EvalUpdateCounts(pRoot);
  122211. }
  122212. }
  122213. pCsr->isEof = 0;
  122214. pCsr->iPrevId = iPrevId;
  122215. if( bEof ){
  122216. pRoot->bEof = bEof;
  122217. }else{
  122218. /* Caution: pRoot may iterate through docids in ascending or descending
  122219. ** order. For this reason, even though it seems more defensive, the
  122220. ** do loop can not be written:
  122221. **
  122222. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  122223. */
  122224. fts3EvalRestart(pCsr, pRoot, &rc);
  122225. do {
  122226. fts3EvalNextRow(pCsr, pRoot, &rc);
  122227. assert( pRoot->bEof==0 );
  122228. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  122229. fts3EvalTestDeferredAndNear(pCsr, &rc);
  122230. }
  122231. }
  122232. return rc;
  122233. }
  122234. /*
  122235. ** This function is used by the matchinfo() module to query a phrase
  122236. ** expression node for the following information:
  122237. **
  122238. ** 1. The total number of occurrences of the phrase in each column of
  122239. ** the FTS table (considering all rows), and
  122240. **
  122241. ** 2. For each column, the number of rows in the table for which the
  122242. ** column contains at least one instance of the phrase.
  122243. **
  122244. ** If no error occurs, SQLITE_OK is returned and the values for each column
  122245. ** written into the array aiOut as follows:
  122246. **
  122247. ** aiOut[iCol*3 + 1] = Number of occurrences
  122248. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  122249. **
  122250. ** Caveats:
  122251. **
  122252. ** * If a phrase consists entirely of deferred tokens, then all output
  122253. ** values are set to the number of documents in the table. In other
  122254. ** words we assume that very common tokens occur exactly once in each
  122255. ** column of each row of the table.
  122256. **
  122257. ** * If a phrase contains some deferred tokens (and some non-deferred
  122258. ** tokens), count the potential occurrence identified by considering
  122259. ** the non-deferred tokens instead of actual phrase occurrences.
  122260. **
  122261. ** * If the phrase is part of a NEAR expression, then only phrase instances
  122262. ** that meet the NEAR constraint are included in the counts.
  122263. */
  122264. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  122265. Fts3Cursor *pCsr, /* FTS cursor handle */
  122266. Fts3Expr *pExpr, /* Phrase expression */
  122267. u32 *aiOut /* Array to write results into (see above) */
  122268. ){
  122269. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122270. int rc = SQLITE_OK;
  122271. int iCol;
  122272. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  122273. assert( pCsr->nDoc>0 );
  122274. for(iCol=0; iCol<pTab->nColumn; iCol++){
  122275. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  122276. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  122277. }
  122278. }else{
  122279. rc = fts3EvalGatherStats(pCsr, pExpr);
  122280. if( rc==SQLITE_OK ){
  122281. assert( pExpr->aMI );
  122282. for(iCol=0; iCol<pTab->nColumn; iCol++){
  122283. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  122284. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  122285. }
  122286. }
  122287. }
  122288. return rc;
  122289. }
  122290. /*
  122291. ** The expression pExpr passed as the second argument to this function
  122292. ** must be of type FTSQUERY_PHRASE.
  122293. **
  122294. ** The returned value is either NULL or a pointer to a buffer containing
  122295. ** a position-list indicating the occurrences of the phrase in column iCol
  122296. ** of the current row.
  122297. **
  122298. ** More specifically, the returned buffer contains 1 varint for each
  122299. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  122300. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  122301. ** if the requested column contains "a b X c d X X" and the position-list
  122302. ** for 'X' is requested, the buffer returned may contain:
  122303. **
  122304. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  122305. **
  122306. ** This function works regardless of whether or not the phrase is deferred,
  122307. ** incremental, or neither.
  122308. */
  122309. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  122310. Fts3Cursor *pCsr, /* FTS3 cursor object */
  122311. Fts3Expr *pExpr, /* Phrase to return doclist for */
  122312. int iCol, /* Column to return position list for */
  122313. char **ppOut /* OUT: Pointer to position list */
  122314. ){
  122315. Fts3Phrase *pPhrase = pExpr->pPhrase;
  122316. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  122317. char *pIter;
  122318. int iThis;
  122319. sqlite3_int64 iDocid;
  122320. /* If this phrase is applies specifically to some column other than
  122321. ** column iCol, return a NULL pointer. */
  122322. *ppOut = 0;
  122323. assert( iCol>=0 && iCol<pTab->nColumn );
  122324. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  122325. return SQLITE_OK;
  122326. }
  122327. iDocid = pExpr->iDocid;
  122328. pIter = pPhrase->doclist.pList;
  122329. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  122330. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  122331. int iMul; /* +1 if csr dir matches index dir, else -1 */
  122332. int bOr = 0;
  122333. u8 bEof = 0;
  122334. u8 bTreeEof = 0;
  122335. Fts3Expr *p; /* Used to iterate from pExpr to root */
  122336. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  122337. /* Check if this phrase descends from an OR expression node. If not,
  122338. ** return NULL. Otherwise, the entry that corresponds to docid
  122339. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  122340. ** tree that the node is part of has been marked as EOF, but the node
  122341. ** itself is not EOF, then it may point to an earlier entry. */
  122342. pNear = pExpr;
  122343. for(p=pExpr->pParent; p; p=p->pParent){
  122344. if( p->eType==FTSQUERY_OR ) bOr = 1;
  122345. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  122346. if( p->bEof ) bTreeEof = 1;
  122347. }
  122348. if( bOr==0 ) return SQLITE_OK;
  122349. /* This is the descendent of an OR node. In this case we cannot use
  122350. ** an incremental phrase. Load the entire doclist for the phrase
  122351. ** into memory in this case. */
  122352. if( pPhrase->bIncr ){
  122353. int rc = SQLITE_OK;
  122354. int bEofSave = pExpr->bEof;
  122355. fts3EvalRestart(pCsr, pExpr, &rc);
  122356. while( rc==SQLITE_OK && !pExpr->bEof ){
  122357. fts3EvalNextRow(pCsr, pExpr, &rc);
  122358. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  122359. }
  122360. pIter = pPhrase->doclist.pList;
  122361. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  122362. if( rc!=SQLITE_OK ) return rc;
  122363. }
  122364. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  122365. while( bTreeEof==1
  122366. && pNear->bEof==0
  122367. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  122368. ){
  122369. int rc = SQLITE_OK;
  122370. fts3EvalNextRow(pCsr, pExpr, &rc);
  122371. if( rc!=SQLITE_OK ) return rc;
  122372. iDocid = pExpr->iDocid;
  122373. pIter = pPhrase->doclist.pList;
  122374. }
  122375. bEof = (pPhrase->doclist.nAll==0);
  122376. assert( bDescDoclist==0 || bDescDoclist==1 );
  122377. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  122378. if( bEof==0 ){
  122379. if( pCsr->bDesc==bDescDoclist ){
  122380. int dummy;
  122381. if( pNear->bEof ){
  122382. /* This expression is already at EOF. So position it to point to the
  122383. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  122384. ** iDocid is already set for this entry, so all that is required is
  122385. ** to set pIter to point to the first byte of the last position-list
  122386. ** in the doclist.
  122387. **
  122388. ** It would also be correct to set pIter and iDocid to zero. In
  122389. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  122390. ** would also move the iterator to point to the last entry in the
  122391. ** doclist. However, this is expensive, as to do so it has to
  122392. ** iterate through the entire doclist from start to finish (since
  122393. ** it does not know the docid for the last entry). */
  122394. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  122395. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  122396. }
  122397. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  122398. sqlite3Fts3DoclistPrev(
  122399. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  122400. &pIter, &iDocid, &dummy, &bEof
  122401. );
  122402. }
  122403. }else{
  122404. if( pNear->bEof ){
  122405. pIter = 0;
  122406. iDocid = 0;
  122407. }
  122408. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  122409. sqlite3Fts3DoclistNext(
  122410. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  122411. &pIter, &iDocid, &bEof
  122412. );
  122413. }
  122414. }
  122415. }
  122416. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  122417. }
  122418. if( pIter==0 ) return SQLITE_OK;
  122419. if( *pIter==0x01 ){
  122420. pIter++;
  122421. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  122422. }else{
  122423. iThis = 0;
  122424. }
  122425. while( iThis<iCol ){
  122426. fts3ColumnlistCopy(0, &pIter);
  122427. if( *pIter==0x00 ) return 0;
  122428. pIter++;
  122429. pIter += sqlite3Fts3GetVarint32(pIter, &iThis);
  122430. }
  122431. *ppOut = ((iCol==iThis)?pIter:0);
  122432. return SQLITE_OK;
  122433. }
  122434. /*
  122435. ** Free all components of the Fts3Phrase structure that were allocated by
  122436. ** the eval module. Specifically, this means to free:
  122437. **
  122438. ** * the contents of pPhrase->doclist, and
  122439. ** * any Fts3MultiSegReader objects held by phrase tokens.
  122440. */
  122441. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  122442. if( pPhrase ){
  122443. int i;
  122444. sqlite3_free(pPhrase->doclist.aAll);
  122445. fts3EvalInvalidatePoslist(pPhrase);
  122446. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  122447. for(i=0; i<pPhrase->nToken; i++){
  122448. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  122449. pPhrase->aToken[i].pSegcsr = 0;
  122450. }
  122451. }
  122452. }
  122453. /*
  122454. ** Return SQLITE_CORRUPT_VTAB.
  122455. */
  122456. #ifdef SQLITE_DEBUG
  122457. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  122458. return SQLITE_CORRUPT_VTAB;
  122459. }
  122460. #endif
  122461. #if !SQLITE_CORE
  122462. /*
  122463. ** Initialize API pointer table, if required.
  122464. */
  122465. #ifdef _WIN32
  122466. __declspec(dllexport)
  122467. #endif
  122468. SQLITE_API int sqlite3_fts3_init(
  122469. sqlite3 *db,
  122470. char **pzErrMsg,
  122471. const sqlite3_api_routines *pApi
  122472. ){
  122473. SQLITE_EXTENSION_INIT2(pApi)
  122474. return sqlite3Fts3Init(db);
  122475. }
  122476. #endif
  122477. #endif
  122478. /************** End of fts3.c ************************************************/
  122479. /************** Begin file fts3_aux.c ****************************************/
  122480. /*
  122481. ** 2011 Jan 27
  122482. **
  122483. ** The author disclaims copyright to this source code. In place of
  122484. ** a legal notice, here is a blessing:
  122485. **
  122486. ** May you do good and not evil.
  122487. ** May you find forgiveness for yourself and forgive others.
  122488. ** May you share freely, never taking more than you give.
  122489. **
  122490. ******************************************************************************
  122491. **
  122492. */
  122493. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122494. /* #include <string.h> */
  122495. /* #include <assert.h> */
  122496. typedef struct Fts3auxTable Fts3auxTable;
  122497. typedef struct Fts3auxCursor Fts3auxCursor;
  122498. struct Fts3auxTable {
  122499. sqlite3_vtab base; /* Base class used by SQLite core */
  122500. Fts3Table *pFts3Tab;
  122501. };
  122502. struct Fts3auxCursor {
  122503. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  122504. Fts3MultiSegReader csr; /* Must be right after "base" */
  122505. Fts3SegFilter filter;
  122506. char *zStop;
  122507. int nStop; /* Byte-length of string zStop */
  122508. int iLangid; /* Language id to query */
  122509. int isEof; /* True if cursor is at EOF */
  122510. sqlite3_int64 iRowid; /* Current rowid */
  122511. int iCol; /* Current value of 'col' column */
  122512. int nStat; /* Size of aStat[] array */
  122513. struct Fts3auxColstats {
  122514. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  122515. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  122516. } *aStat;
  122517. };
  122518. /*
  122519. ** Schema of the terms table.
  122520. */
  122521. #define FTS3_AUX_SCHEMA \
  122522. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  122523. /*
  122524. ** This function does all the work for both the xConnect and xCreate methods.
  122525. ** These tables have no persistent representation of their own, so xConnect
  122526. ** and xCreate are identical operations.
  122527. */
  122528. static int fts3auxConnectMethod(
  122529. sqlite3 *db, /* Database connection */
  122530. void *pUnused, /* Unused */
  122531. int argc, /* Number of elements in argv array */
  122532. const char * const *argv, /* xCreate/xConnect argument array */
  122533. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  122534. char **pzErr /* OUT: sqlite3_malloc'd error message */
  122535. ){
  122536. char const *zDb; /* Name of database (e.g. "main") */
  122537. char const *zFts3; /* Name of fts3 table */
  122538. int nDb; /* Result of strlen(zDb) */
  122539. int nFts3; /* Result of strlen(zFts3) */
  122540. int nByte; /* Bytes of space to allocate here */
  122541. int rc; /* value returned by declare_vtab() */
  122542. Fts3auxTable *p; /* Virtual table object to return */
  122543. UNUSED_PARAMETER(pUnused);
  122544. /* The user should invoke this in one of two forms:
  122545. **
  122546. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  122547. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  122548. */
  122549. if( argc!=4 && argc!=5 ) goto bad_args;
  122550. zDb = argv[1];
  122551. nDb = (int)strlen(zDb);
  122552. if( argc==5 ){
  122553. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  122554. zDb = argv[3];
  122555. nDb = (int)strlen(zDb);
  122556. zFts3 = argv[4];
  122557. }else{
  122558. goto bad_args;
  122559. }
  122560. }else{
  122561. zFts3 = argv[3];
  122562. }
  122563. nFts3 = (int)strlen(zFts3);
  122564. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  122565. if( rc!=SQLITE_OK ) return rc;
  122566. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  122567. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  122568. if( !p ) return SQLITE_NOMEM;
  122569. memset(p, 0, nByte);
  122570. p->pFts3Tab = (Fts3Table *)&p[1];
  122571. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  122572. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  122573. p->pFts3Tab->db = db;
  122574. p->pFts3Tab->nIndex = 1;
  122575. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  122576. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  122577. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  122578. *ppVtab = (sqlite3_vtab *)p;
  122579. return SQLITE_OK;
  122580. bad_args:
  122581. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  122582. return SQLITE_ERROR;
  122583. }
  122584. /*
  122585. ** This function does the work for both the xDisconnect and xDestroy methods.
  122586. ** These tables have no persistent representation of their own, so xDisconnect
  122587. ** and xDestroy are identical operations.
  122588. */
  122589. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  122590. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  122591. Fts3Table *pFts3 = p->pFts3Tab;
  122592. int i;
  122593. /* Free any prepared statements held */
  122594. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  122595. sqlite3_finalize(pFts3->aStmt[i]);
  122596. }
  122597. sqlite3_free(pFts3->zSegmentsTbl);
  122598. sqlite3_free(p);
  122599. return SQLITE_OK;
  122600. }
  122601. #define FTS4AUX_EQ_CONSTRAINT 1
  122602. #define FTS4AUX_GE_CONSTRAINT 2
  122603. #define FTS4AUX_LE_CONSTRAINT 4
  122604. /*
  122605. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  122606. */
  122607. static int fts3auxBestIndexMethod(
  122608. sqlite3_vtab *pVTab,
  122609. sqlite3_index_info *pInfo
  122610. ){
  122611. int i;
  122612. int iEq = -1;
  122613. int iGe = -1;
  122614. int iLe = -1;
  122615. int iLangid = -1;
  122616. int iNext = 1; /* Next free argvIndex value */
  122617. UNUSED_PARAMETER(pVTab);
  122618. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  122619. if( pInfo->nOrderBy==1
  122620. && pInfo->aOrderBy[0].iColumn==0
  122621. && pInfo->aOrderBy[0].desc==0
  122622. ){
  122623. pInfo->orderByConsumed = 1;
  122624. }
  122625. /* Search for equality and range constraints on the "term" column.
  122626. ** And equality constraints on the hidden "languageid" column. */
  122627. for(i=0; i<pInfo->nConstraint; i++){
  122628. if( pInfo->aConstraint[i].usable ){
  122629. int op = pInfo->aConstraint[i].op;
  122630. int iCol = pInfo->aConstraint[i].iColumn;
  122631. if( iCol==0 ){
  122632. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  122633. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  122634. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  122635. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  122636. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  122637. }
  122638. if( iCol==4 ){
  122639. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  122640. }
  122641. }
  122642. }
  122643. if( iEq>=0 ){
  122644. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  122645. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  122646. pInfo->estimatedCost = 5;
  122647. }else{
  122648. pInfo->idxNum = 0;
  122649. pInfo->estimatedCost = 20000;
  122650. if( iGe>=0 ){
  122651. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  122652. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  122653. pInfo->estimatedCost /= 2;
  122654. }
  122655. if( iLe>=0 ){
  122656. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  122657. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  122658. pInfo->estimatedCost /= 2;
  122659. }
  122660. }
  122661. if( iLangid>=0 ){
  122662. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  122663. pInfo->estimatedCost--;
  122664. }
  122665. return SQLITE_OK;
  122666. }
  122667. /*
  122668. ** xOpen - Open a cursor.
  122669. */
  122670. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  122671. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  122672. UNUSED_PARAMETER(pVTab);
  122673. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  122674. if( !pCsr ) return SQLITE_NOMEM;
  122675. memset(pCsr, 0, sizeof(Fts3auxCursor));
  122676. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  122677. return SQLITE_OK;
  122678. }
  122679. /*
  122680. ** xClose - Close a cursor.
  122681. */
  122682. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  122683. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122684. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122685. sqlite3Fts3SegmentsClose(pFts3);
  122686. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  122687. sqlite3_free((void *)pCsr->filter.zTerm);
  122688. sqlite3_free(pCsr->zStop);
  122689. sqlite3_free(pCsr->aStat);
  122690. sqlite3_free(pCsr);
  122691. return SQLITE_OK;
  122692. }
  122693. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  122694. if( nSize>pCsr->nStat ){
  122695. struct Fts3auxColstats *aNew;
  122696. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  122697. sizeof(struct Fts3auxColstats) * nSize
  122698. );
  122699. if( aNew==0 ) return SQLITE_NOMEM;
  122700. memset(&aNew[pCsr->nStat], 0,
  122701. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  122702. );
  122703. pCsr->aStat = aNew;
  122704. pCsr->nStat = nSize;
  122705. }
  122706. return SQLITE_OK;
  122707. }
  122708. /*
  122709. ** xNext - Advance the cursor to the next row, if any.
  122710. */
  122711. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  122712. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122713. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122714. int rc;
  122715. /* Increment our pretend rowid value. */
  122716. pCsr->iRowid++;
  122717. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  122718. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  122719. }
  122720. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  122721. if( rc==SQLITE_ROW ){
  122722. int i = 0;
  122723. int nDoclist = pCsr->csr.nDoclist;
  122724. char *aDoclist = pCsr->csr.aDoclist;
  122725. int iCol;
  122726. int eState = 0;
  122727. if( pCsr->zStop ){
  122728. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  122729. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  122730. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  122731. pCsr->isEof = 1;
  122732. return SQLITE_OK;
  122733. }
  122734. }
  122735. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  122736. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  122737. iCol = 0;
  122738. while( i<nDoclist ){
  122739. sqlite3_int64 v = 0;
  122740. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  122741. switch( eState ){
  122742. /* State 0. In this state the integer just read was a docid. */
  122743. case 0:
  122744. pCsr->aStat[0].nDoc++;
  122745. eState = 1;
  122746. iCol = 0;
  122747. break;
  122748. /* State 1. In this state we are expecting either a 1, indicating
  122749. ** that the following integer will be a column number, or the
  122750. ** start of a position list for column 0.
  122751. **
  122752. ** The only difference between state 1 and state 2 is that if the
  122753. ** integer encountered in state 1 is not 0 or 1, then we need to
  122754. ** increment the column 0 "nDoc" count for this term.
  122755. */
  122756. case 1:
  122757. assert( iCol==0 );
  122758. if( v>1 ){
  122759. pCsr->aStat[1].nDoc++;
  122760. }
  122761. eState = 2;
  122762. /* fall through */
  122763. case 2:
  122764. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  122765. eState = 0;
  122766. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  122767. eState = 3;
  122768. }else{ /* 2 or greater. A position. */
  122769. pCsr->aStat[iCol+1].nOcc++;
  122770. pCsr->aStat[0].nOcc++;
  122771. }
  122772. break;
  122773. /* State 3. The integer just read is a column number. */
  122774. default: assert( eState==3 );
  122775. iCol = (int)v;
  122776. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  122777. pCsr->aStat[iCol+1].nDoc++;
  122778. eState = 2;
  122779. break;
  122780. }
  122781. }
  122782. pCsr->iCol = 0;
  122783. rc = SQLITE_OK;
  122784. }else{
  122785. pCsr->isEof = 1;
  122786. }
  122787. return rc;
  122788. }
  122789. /*
  122790. ** xFilter - Initialize a cursor to point at the start of its data.
  122791. */
  122792. static int fts3auxFilterMethod(
  122793. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  122794. int idxNum, /* Strategy index */
  122795. const char *idxStr, /* Unused */
  122796. int nVal, /* Number of elements in apVal */
  122797. sqlite3_value **apVal /* Arguments for the indexing scheme */
  122798. ){
  122799. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122800. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  122801. int rc;
  122802. int isScan = 0;
  122803. int iLangVal = 0; /* Language id to query */
  122804. int iEq = -1; /* Index of term=? value in apVal */
  122805. int iGe = -1; /* Index of term>=? value in apVal */
  122806. int iLe = -1; /* Index of term<=? value in apVal */
  122807. int iLangid = -1; /* Index of languageid=? value in apVal */
  122808. int iNext = 0;
  122809. UNUSED_PARAMETER(nVal);
  122810. UNUSED_PARAMETER(idxStr);
  122811. assert( idxStr==0 );
  122812. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  122813. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  122814. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  122815. );
  122816. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  122817. iEq = iNext++;
  122818. }else{
  122819. isScan = 1;
  122820. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  122821. iGe = iNext++;
  122822. }
  122823. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  122824. iLe = iNext++;
  122825. }
  122826. }
  122827. if( iNext<nVal ){
  122828. iLangid = iNext++;
  122829. }
  122830. /* In case this cursor is being reused, close and zero it. */
  122831. testcase(pCsr->filter.zTerm);
  122832. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  122833. sqlite3_free((void *)pCsr->filter.zTerm);
  122834. sqlite3_free(pCsr->aStat);
  122835. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  122836. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  122837. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  122838. if( iEq>=0 || iGe>=0 ){
  122839. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  122840. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  122841. if( zStr ){
  122842. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  122843. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  122844. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  122845. }
  122846. }
  122847. if( iLe>=0 ){
  122848. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  122849. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  122850. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  122851. }
  122852. if( iLangid>=0 ){
  122853. iLangVal = sqlite3_value_int(apVal[iLangid]);
  122854. /* If the user specified a negative value for the languageid, use zero
  122855. ** instead. This works, as the "languageid=?" constraint will also
  122856. ** be tested by the VDBE layer. The test will always be false (since
  122857. ** this module will not return a row with a negative languageid), and
  122858. ** so the overall query will return zero rows. */
  122859. if( iLangVal<0 ) iLangVal = 0;
  122860. }
  122861. pCsr->iLangid = iLangVal;
  122862. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  122863. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  122864. );
  122865. if( rc==SQLITE_OK ){
  122866. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  122867. }
  122868. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  122869. return rc;
  122870. }
  122871. /*
  122872. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  122873. */
  122874. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  122875. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122876. return pCsr->isEof;
  122877. }
  122878. /*
  122879. ** xColumn - Return a column value.
  122880. */
  122881. static int fts3auxColumnMethod(
  122882. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  122883. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  122884. int iCol /* Index of column to read value from */
  122885. ){
  122886. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  122887. assert( p->isEof==0 );
  122888. switch( iCol ){
  122889. case 0: /* term */
  122890. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  122891. break;
  122892. case 1: /* col */
  122893. if( p->iCol ){
  122894. sqlite3_result_int(pCtx, p->iCol-1);
  122895. }else{
  122896. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  122897. }
  122898. break;
  122899. case 2: /* documents */
  122900. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  122901. break;
  122902. case 3: /* occurrences */
  122903. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  122904. break;
  122905. default: /* languageid */
  122906. assert( iCol==4 );
  122907. sqlite3_result_int(pCtx, p->iLangid);
  122908. break;
  122909. }
  122910. return SQLITE_OK;
  122911. }
  122912. /*
  122913. ** xRowid - Return the current rowid for the cursor.
  122914. */
  122915. static int fts3auxRowidMethod(
  122916. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  122917. sqlite_int64 *pRowid /* OUT: Rowid value */
  122918. ){
  122919. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  122920. *pRowid = pCsr->iRowid;
  122921. return SQLITE_OK;
  122922. }
  122923. /*
  122924. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  122925. ** if successful or an error code if sqlite3_create_module() fails.
  122926. */
  122927. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  122928. static const sqlite3_module fts3aux_module = {
  122929. 0, /* iVersion */
  122930. fts3auxConnectMethod, /* xCreate */
  122931. fts3auxConnectMethod, /* xConnect */
  122932. fts3auxBestIndexMethod, /* xBestIndex */
  122933. fts3auxDisconnectMethod, /* xDisconnect */
  122934. fts3auxDisconnectMethod, /* xDestroy */
  122935. fts3auxOpenMethod, /* xOpen */
  122936. fts3auxCloseMethod, /* xClose */
  122937. fts3auxFilterMethod, /* xFilter */
  122938. fts3auxNextMethod, /* xNext */
  122939. fts3auxEofMethod, /* xEof */
  122940. fts3auxColumnMethod, /* xColumn */
  122941. fts3auxRowidMethod, /* xRowid */
  122942. 0, /* xUpdate */
  122943. 0, /* xBegin */
  122944. 0, /* xSync */
  122945. 0, /* xCommit */
  122946. 0, /* xRollback */
  122947. 0, /* xFindFunction */
  122948. 0, /* xRename */
  122949. 0, /* xSavepoint */
  122950. 0, /* xRelease */
  122951. 0 /* xRollbackTo */
  122952. };
  122953. int rc; /* Return code */
  122954. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  122955. return rc;
  122956. }
  122957. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  122958. /************** End of fts3_aux.c ********************************************/
  122959. /************** Begin file fts3_expr.c ***************************************/
  122960. /*
  122961. ** 2008 Nov 28
  122962. **
  122963. ** The author disclaims copyright to this source code. In place of
  122964. ** a legal notice, here is a blessing:
  122965. **
  122966. ** May you do good and not evil.
  122967. ** May you find forgiveness for yourself and forgive others.
  122968. ** May you share freely, never taking more than you give.
  122969. **
  122970. ******************************************************************************
  122971. **
  122972. ** This module contains code that implements a parser for fts3 query strings
  122973. ** (the right-hand argument to the MATCH operator). Because the supported
  122974. ** syntax is relatively simple, the whole tokenizer/parser system is
  122975. ** hand-coded.
  122976. */
  122977. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  122978. /*
  122979. ** By default, this module parses the legacy syntax that has been
  122980. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  122981. ** is defined, then it uses the new syntax. The differences between
  122982. ** the new and the old syntaxes are:
  122983. **
  122984. ** a) The new syntax supports parenthesis. The old does not.
  122985. **
  122986. ** b) The new syntax supports the AND and NOT operators. The old does not.
  122987. **
  122988. ** c) The old syntax supports the "-" token qualifier. This is not
  122989. ** supported by the new syntax (it is replaced by the NOT operator).
  122990. **
  122991. ** d) When using the old syntax, the OR operator has a greater precedence
  122992. ** than an implicit AND. When using the new, both implicity and explicit
  122993. ** AND operators have a higher precedence than OR.
  122994. **
  122995. ** If compiled with SQLITE_TEST defined, then this module exports the
  122996. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  122997. ** to zero causes the module to use the old syntax. If it is set to
  122998. ** non-zero the new syntax is activated. This is so both syntaxes can
  122999. ** be tested using a single build of testfixture.
  123000. **
  123001. ** The following describes the syntax supported by the fts3 MATCH
  123002. ** operator in a similar format to that used by the lemon parser
  123003. ** generator. This module does not use actually lemon, it uses a
  123004. ** custom parser.
  123005. **
  123006. ** query ::= andexpr (OR andexpr)*.
  123007. **
  123008. ** andexpr ::= notexpr (AND? notexpr)*.
  123009. **
  123010. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  123011. ** notexpr ::= LP query RP.
  123012. **
  123013. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  123014. **
  123015. ** distance_opt ::= .
  123016. ** distance_opt ::= / INTEGER.
  123017. **
  123018. ** phrase ::= TOKEN.
  123019. ** phrase ::= COLUMN:TOKEN.
  123020. ** phrase ::= "TOKEN TOKEN TOKEN...".
  123021. */
  123022. #ifdef SQLITE_TEST
  123023. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  123024. #else
  123025. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  123026. # define sqlite3_fts3_enable_parentheses 1
  123027. # else
  123028. # define sqlite3_fts3_enable_parentheses 0
  123029. # endif
  123030. #endif
  123031. /*
  123032. ** Default span for NEAR operators.
  123033. */
  123034. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  123035. /* #include <string.h> */
  123036. /* #include <assert.h> */
  123037. /*
  123038. ** isNot:
  123039. ** This variable is used by function getNextNode(). When getNextNode() is
  123040. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  123041. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  123042. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  123043. ** zero.
  123044. */
  123045. typedef struct ParseContext ParseContext;
  123046. struct ParseContext {
  123047. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  123048. int iLangid; /* Language id used with tokenizer */
  123049. const char **azCol; /* Array of column names for fts3 table */
  123050. int bFts4; /* True to allow FTS4-only syntax */
  123051. int nCol; /* Number of entries in azCol[] */
  123052. int iDefaultCol; /* Default column to query */
  123053. int isNot; /* True if getNextNode() sees a unary - */
  123054. sqlite3_context *pCtx; /* Write error message here */
  123055. int nNest; /* Number of nested brackets */
  123056. };
  123057. /*
  123058. ** This function is equivalent to the standard isspace() function.
  123059. **
  123060. ** The standard isspace() can be awkward to use safely, because although it
  123061. ** is defined to accept an argument of type int, its behavior when passed
  123062. ** an integer that falls outside of the range of the unsigned char type
  123063. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  123064. ** is defined to accept an argument of type char, and always returns 0 for
  123065. ** any values that fall outside of the range of the unsigned char type (i.e.
  123066. ** negative values).
  123067. */
  123068. static int fts3isspace(char c){
  123069. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  123070. }
  123071. /*
  123072. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  123073. ** zero the memory before returning a pointer to it. If unsuccessful,
  123074. ** return NULL.
  123075. */
  123076. static void *fts3MallocZero(int nByte){
  123077. void *pRet = sqlite3_malloc(nByte);
  123078. if( pRet ) memset(pRet, 0, nByte);
  123079. return pRet;
  123080. }
  123081. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  123082. sqlite3_tokenizer *pTokenizer,
  123083. int iLangid,
  123084. const char *z,
  123085. int n,
  123086. sqlite3_tokenizer_cursor **ppCsr
  123087. ){
  123088. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123089. sqlite3_tokenizer_cursor *pCsr = 0;
  123090. int rc;
  123091. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  123092. assert( rc==SQLITE_OK || pCsr==0 );
  123093. if( rc==SQLITE_OK ){
  123094. pCsr->pTokenizer = pTokenizer;
  123095. if( pModule->iVersion>=1 ){
  123096. rc = pModule->xLanguageid(pCsr, iLangid);
  123097. if( rc!=SQLITE_OK ){
  123098. pModule->xClose(pCsr);
  123099. pCsr = 0;
  123100. }
  123101. }
  123102. }
  123103. *ppCsr = pCsr;
  123104. return rc;
  123105. }
  123106. /*
  123107. ** Extract the next token from buffer z (length n) using the tokenizer
  123108. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  123109. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  123110. ** single token and set *ppExpr to point to it. If the end of the buffer is
  123111. ** reached before a token is found, set *ppExpr to zero. It is the
  123112. ** responsibility of the caller to eventually deallocate the allocated
  123113. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  123114. **
  123115. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  123116. ** fails.
  123117. */
  123118. static int getNextToken(
  123119. ParseContext *pParse, /* fts3 query parse context */
  123120. int iCol, /* Value for Fts3Phrase.iColumn */
  123121. const char *z, int n, /* Input string */
  123122. Fts3Expr **ppExpr, /* OUT: expression */
  123123. int *pnConsumed /* OUT: Number of bytes consumed */
  123124. ){
  123125. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  123126. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123127. int rc;
  123128. sqlite3_tokenizer_cursor *pCursor;
  123129. Fts3Expr *pRet = 0;
  123130. int nConsumed = 0;
  123131. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, n, &pCursor);
  123132. if( rc==SQLITE_OK ){
  123133. const char *zToken;
  123134. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  123135. int nByte; /* total space to allocate */
  123136. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  123137. if( rc==SQLITE_OK ){
  123138. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  123139. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  123140. if( !pRet ){
  123141. rc = SQLITE_NOMEM;
  123142. }else{
  123143. pRet->eType = FTSQUERY_PHRASE;
  123144. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  123145. pRet->pPhrase->nToken = 1;
  123146. pRet->pPhrase->iColumn = iCol;
  123147. pRet->pPhrase->aToken[0].n = nToken;
  123148. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  123149. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  123150. if( iEnd<n && z[iEnd]=='*' ){
  123151. pRet->pPhrase->aToken[0].isPrefix = 1;
  123152. iEnd++;
  123153. }
  123154. while( 1 ){
  123155. if( !sqlite3_fts3_enable_parentheses
  123156. && iStart>0 && z[iStart-1]=='-'
  123157. ){
  123158. pParse->isNot = 1;
  123159. iStart--;
  123160. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  123161. pRet->pPhrase->aToken[0].bFirst = 1;
  123162. iStart--;
  123163. }else{
  123164. break;
  123165. }
  123166. }
  123167. }
  123168. nConsumed = iEnd;
  123169. }
  123170. pModule->xClose(pCursor);
  123171. }
  123172. *pnConsumed = nConsumed;
  123173. *ppExpr = pRet;
  123174. return rc;
  123175. }
  123176. /*
  123177. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  123178. ** then free the old allocation.
  123179. */
  123180. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  123181. void *pRet = sqlite3_realloc(pOrig, nNew);
  123182. if( !pRet ){
  123183. sqlite3_free(pOrig);
  123184. }
  123185. return pRet;
  123186. }
  123187. /*
  123188. ** Buffer zInput, length nInput, contains the contents of a quoted string
  123189. ** that appeared as part of an fts3 query expression. Neither quote character
  123190. ** is included in the buffer. This function attempts to tokenize the entire
  123191. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  123192. ** containing the results.
  123193. **
  123194. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  123195. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  123196. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  123197. ** to 0.
  123198. */
  123199. static int getNextString(
  123200. ParseContext *pParse, /* fts3 query parse context */
  123201. const char *zInput, int nInput, /* Input string */
  123202. Fts3Expr **ppExpr /* OUT: expression */
  123203. ){
  123204. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  123205. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  123206. int rc;
  123207. Fts3Expr *p = 0;
  123208. sqlite3_tokenizer_cursor *pCursor = 0;
  123209. char *zTemp = 0;
  123210. int nTemp = 0;
  123211. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  123212. int nToken = 0;
  123213. /* The final Fts3Expr data structure, including the Fts3Phrase,
  123214. ** Fts3PhraseToken structures token buffers are all stored as a single
  123215. ** allocation so that the expression can be freed with a single call to
  123216. ** sqlite3_free(). Setting this up requires a two pass approach.
  123217. **
  123218. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  123219. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  123220. ** to assemble data in two dynamic buffers:
  123221. **
  123222. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  123223. ** structure, followed by the array of Fts3PhraseToken
  123224. ** structures. This pass only populates the Fts3PhraseToken array.
  123225. **
  123226. ** Buffer zTemp: Contains copies of all tokens.
  123227. **
  123228. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  123229. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  123230. ** structures.
  123231. */
  123232. rc = sqlite3Fts3OpenTokenizer(
  123233. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  123234. if( rc==SQLITE_OK ){
  123235. int ii;
  123236. for(ii=0; rc==SQLITE_OK; ii++){
  123237. const char *zByte;
  123238. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  123239. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  123240. if( rc==SQLITE_OK ){
  123241. Fts3PhraseToken *pToken;
  123242. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  123243. if( !p ) goto no_mem;
  123244. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  123245. if( !zTemp ) goto no_mem;
  123246. assert( nToken==ii );
  123247. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  123248. memset(pToken, 0, sizeof(Fts3PhraseToken));
  123249. memcpy(&zTemp[nTemp], zByte, nByte);
  123250. nTemp += nByte;
  123251. pToken->n = nByte;
  123252. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  123253. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  123254. nToken = ii+1;
  123255. }
  123256. }
  123257. pModule->xClose(pCursor);
  123258. pCursor = 0;
  123259. }
  123260. if( rc==SQLITE_DONE ){
  123261. int jj;
  123262. char *zBuf = 0;
  123263. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  123264. if( !p ) goto no_mem;
  123265. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  123266. p->eType = FTSQUERY_PHRASE;
  123267. p->pPhrase = (Fts3Phrase *)&p[1];
  123268. p->pPhrase->iColumn = pParse->iDefaultCol;
  123269. p->pPhrase->nToken = nToken;
  123270. zBuf = (char *)&p->pPhrase->aToken[nToken];
  123271. if( zTemp ){
  123272. memcpy(zBuf, zTemp, nTemp);
  123273. sqlite3_free(zTemp);
  123274. }else{
  123275. assert( nTemp==0 );
  123276. }
  123277. for(jj=0; jj<p->pPhrase->nToken; jj++){
  123278. p->pPhrase->aToken[jj].z = zBuf;
  123279. zBuf += p->pPhrase->aToken[jj].n;
  123280. }
  123281. rc = SQLITE_OK;
  123282. }
  123283. *ppExpr = p;
  123284. return rc;
  123285. no_mem:
  123286. if( pCursor ){
  123287. pModule->xClose(pCursor);
  123288. }
  123289. sqlite3_free(zTemp);
  123290. sqlite3_free(p);
  123291. *ppExpr = 0;
  123292. return SQLITE_NOMEM;
  123293. }
  123294. /*
  123295. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  123296. ** call fts3ExprParse(). So this forward declaration is required.
  123297. */
  123298. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  123299. /*
  123300. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  123301. ** structure, or set to 0 if the end of the input buffer is reached.
  123302. **
  123303. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  123304. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  123305. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  123306. */
  123307. static int getNextNode(
  123308. ParseContext *pParse, /* fts3 query parse context */
  123309. const char *z, int n, /* Input string */
  123310. Fts3Expr **ppExpr, /* OUT: expression */
  123311. int *pnConsumed /* OUT: Number of bytes consumed */
  123312. ){
  123313. static const struct Fts3Keyword {
  123314. char *z; /* Keyword text */
  123315. unsigned char n; /* Length of the keyword */
  123316. unsigned char parenOnly; /* Only valid in paren mode */
  123317. unsigned char eType; /* Keyword code */
  123318. } aKeyword[] = {
  123319. { "OR" , 2, 0, FTSQUERY_OR },
  123320. { "AND", 3, 1, FTSQUERY_AND },
  123321. { "NOT", 3, 1, FTSQUERY_NOT },
  123322. { "NEAR", 4, 0, FTSQUERY_NEAR }
  123323. };
  123324. int ii;
  123325. int iCol;
  123326. int iColLen;
  123327. int rc;
  123328. Fts3Expr *pRet = 0;
  123329. const char *zInput = z;
  123330. int nInput = n;
  123331. pParse->isNot = 0;
  123332. /* Skip over any whitespace before checking for a keyword, an open or
  123333. ** close bracket, or a quoted string.
  123334. */
  123335. while( nInput>0 && fts3isspace(*zInput) ){
  123336. nInput--;
  123337. zInput++;
  123338. }
  123339. if( nInput==0 ){
  123340. return SQLITE_DONE;
  123341. }
  123342. /* See if we are dealing with a keyword. */
  123343. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  123344. const struct Fts3Keyword *pKey = &aKeyword[ii];
  123345. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  123346. continue;
  123347. }
  123348. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  123349. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  123350. int nKey = pKey->n;
  123351. char cNext;
  123352. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  123353. if( pKey->eType==FTSQUERY_NEAR ){
  123354. assert( nKey==4 );
  123355. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  123356. nNear = 0;
  123357. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  123358. nNear = nNear * 10 + (zInput[nKey] - '0');
  123359. }
  123360. }
  123361. }
  123362. /* At this point this is probably a keyword. But for that to be true,
  123363. ** the next byte must contain either whitespace, an open or close
  123364. ** parenthesis, a quote character, or EOF.
  123365. */
  123366. cNext = zInput[nKey];
  123367. if( fts3isspace(cNext)
  123368. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  123369. ){
  123370. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  123371. if( !pRet ){
  123372. return SQLITE_NOMEM;
  123373. }
  123374. pRet->eType = pKey->eType;
  123375. pRet->nNear = nNear;
  123376. *ppExpr = pRet;
  123377. *pnConsumed = (int)((zInput - z) + nKey);
  123378. return SQLITE_OK;
  123379. }
  123380. /* Turns out that wasn't a keyword after all. This happens if the
  123381. ** user has supplied a token such as "ORacle". Continue.
  123382. */
  123383. }
  123384. }
  123385. /* Check for an open bracket. */
  123386. if( sqlite3_fts3_enable_parentheses ){
  123387. if( *zInput=='(' ){
  123388. int nConsumed;
  123389. pParse->nNest++;
  123390. rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
  123391. if( rc==SQLITE_OK && !*ppExpr ){
  123392. rc = SQLITE_DONE;
  123393. }
  123394. *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
  123395. return rc;
  123396. }
  123397. /* Check for a close bracket. */
  123398. if( *zInput==')' ){
  123399. pParse->nNest--;
  123400. *pnConsumed = (int)((zInput - z) + 1);
  123401. return SQLITE_DONE;
  123402. }
  123403. }
  123404. /* See if we are dealing with a quoted phrase. If this is the case, then
  123405. ** search for the closing quote and pass the whole string to getNextString()
  123406. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  123407. ** a quote character embedded in a string.
  123408. */
  123409. if( *zInput=='"' ){
  123410. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  123411. *pnConsumed = (int)((zInput - z) + ii + 1);
  123412. if( ii==nInput ){
  123413. return SQLITE_ERROR;
  123414. }
  123415. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  123416. }
  123417. /* If control flows to this point, this must be a regular token, or
  123418. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  123419. ** interface. Before doing so, figure out if there is an explicit
  123420. ** column specifier for the token.
  123421. **
  123422. ** TODO: Strangely, it is not possible to associate a column specifier
  123423. ** with a quoted phrase, only with a single token. Not sure if this was
  123424. ** an implementation artifact or an intentional decision when fts3 was
  123425. ** first implemented. Whichever it was, this module duplicates the
  123426. ** limitation.
  123427. */
  123428. iCol = pParse->iDefaultCol;
  123429. iColLen = 0;
  123430. for(ii=0; ii<pParse->nCol; ii++){
  123431. const char *zStr = pParse->azCol[ii];
  123432. int nStr = (int)strlen(zStr);
  123433. if( nInput>nStr && zInput[nStr]==':'
  123434. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  123435. ){
  123436. iCol = ii;
  123437. iColLen = (int)((zInput - z) + nStr + 1);
  123438. break;
  123439. }
  123440. }
  123441. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  123442. *pnConsumed += iColLen;
  123443. return rc;
  123444. }
  123445. /*
  123446. ** The argument is an Fts3Expr structure for a binary operator (any type
  123447. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  123448. ** precedence of the operator. Lower values have a higher precedence (i.e.
  123449. ** group more tightly). For example, in the C language, the == operator
  123450. ** groups more tightly than ||, and would therefore have a higher precedence.
  123451. **
  123452. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  123453. ** is defined), the order of the operators in precedence from highest to
  123454. ** lowest is:
  123455. **
  123456. ** NEAR
  123457. ** NOT
  123458. ** AND (including implicit ANDs)
  123459. ** OR
  123460. **
  123461. ** Note that when using the old query syntax, the OR operator has a higher
  123462. ** precedence than the AND operator.
  123463. */
  123464. static int opPrecedence(Fts3Expr *p){
  123465. assert( p->eType!=FTSQUERY_PHRASE );
  123466. if( sqlite3_fts3_enable_parentheses ){
  123467. return p->eType;
  123468. }else if( p->eType==FTSQUERY_NEAR ){
  123469. return 1;
  123470. }else if( p->eType==FTSQUERY_OR ){
  123471. return 2;
  123472. }
  123473. assert( p->eType==FTSQUERY_AND );
  123474. return 3;
  123475. }
  123476. /*
  123477. ** Argument ppHead contains a pointer to the current head of a query
  123478. ** expression tree being parsed. pPrev is the expression node most recently
  123479. ** inserted into the tree. This function adds pNew, which is always a binary
  123480. ** operator node, into the expression tree based on the relative precedence
  123481. ** of pNew and the existing nodes of the tree. This may result in the head
  123482. ** of the tree changing, in which case *ppHead is set to the new root node.
  123483. */
  123484. static void insertBinaryOperator(
  123485. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  123486. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  123487. Fts3Expr *pNew /* New binary node to insert into expression tree */
  123488. ){
  123489. Fts3Expr *pSplit = pPrev;
  123490. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  123491. pSplit = pSplit->pParent;
  123492. }
  123493. if( pSplit->pParent ){
  123494. assert( pSplit->pParent->pRight==pSplit );
  123495. pSplit->pParent->pRight = pNew;
  123496. pNew->pParent = pSplit->pParent;
  123497. }else{
  123498. *ppHead = pNew;
  123499. }
  123500. pNew->pLeft = pSplit;
  123501. pSplit->pParent = pNew;
  123502. }
  123503. /*
  123504. ** Parse the fts3 query expression found in buffer z, length n. This function
  123505. ** returns either when the end of the buffer is reached or an unmatched
  123506. ** closing bracket - ')' - is encountered.
  123507. **
  123508. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  123509. ** parsed form of the expression and *pnConsumed is set to the number of
  123510. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  123511. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  123512. */
  123513. static int fts3ExprParse(
  123514. ParseContext *pParse, /* fts3 query parse context */
  123515. const char *z, int n, /* Text of MATCH query */
  123516. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  123517. int *pnConsumed /* OUT: Number of bytes consumed */
  123518. ){
  123519. Fts3Expr *pRet = 0;
  123520. Fts3Expr *pPrev = 0;
  123521. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  123522. int nIn = n;
  123523. const char *zIn = z;
  123524. int rc = SQLITE_OK;
  123525. int isRequirePhrase = 1;
  123526. while( rc==SQLITE_OK ){
  123527. Fts3Expr *p = 0;
  123528. int nByte = 0;
  123529. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  123530. if( rc==SQLITE_OK ){
  123531. int isPhrase;
  123532. if( !sqlite3_fts3_enable_parentheses
  123533. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  123534. ){
  123535. /* Create an implicit NOT operator. */
  123536. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  123537. if( !pNot ){
  123538. sqlite3Fts3ExprFree(p);
  123539. rc = SQLITE_NOMEM;
  123540. goto exprparse_out;
  123541. }
  123542. pNot->eType = FTSQUERY_NOT;
  123543. pNot->pRight = p;
  123544. p->pParent = pNot;
  123545. if( pNotBranch ){
  123546. pNot->pLeft = pNotBranch;
  123547. pNotBranch->pParent = pNot;
  123548. }
  123549. pNotBranch = pNot;
  123550. p = pPrev;
  123551. }else{
  123552. int eType = p->eType;
  123553. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  123554. /* The isRequirePhrase variable is set to true if a phrase or
  123555. ** an expression contained in parenthesis is required. If a
  123556. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  123557. ** isRequirePhrase is set, this is a syntax error.
  123558. */
  123559. if( !isPhrase && isRequirePhrase ){
  123560. sqlite3Fts3ExprFree(p);
  123561. rc = SQLITE_ERROR;
  123562. goto exprparse_out;
  123563. }
  123564. if( isPhrase && !isRequirePhrase ){
  123565. /* Insert an implicit AND operator. */
  123566. Fts3Expr *pAnd;
  123567. assert( pRet && pPrev );
  123568. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  123569. if( !pAnd ){
  123570. sqlite3Fts3ExprFree(p);
  123571. rc = SQLITE_NOMEM;
  123572. goto exprparse_out;
  123573. }
  123574. pAnd->eType = FTSQUERY_AND;
  123575. insertBinaryOperator(&pRet, pPrev, pAnd);
  123576. pPrev = pAnd;
  123577. }
  123578. /* This test catches attempts to make either operand of a NEAR
  123579. ** operator something other than a phrase. For example, either of
  123580. ** the following:
  123581. **
  123582. ** (bracketed expression) NEAR phrase
  123583. ** phrase NEAR (bracketed expression)
  123584. **
  123585. ** Return an error in either case.
  123586. */
  123587. if( pPrev && (
  123588. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  123589. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  123590. )){
  123591. sqlite3Fts3ExprFree(p);
  123592. rc = SQLITE_ERROR;
  123593. goto exprparse_out;
  123594. }
  123595. if( isPhrase ){
  123596. if( pRet ){
  123597. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  123598. pPrev->pRight = p;
  123599. p->pParent = pPrev;
  123600. }else{
  123601. pRet = p;
  123602. }
  123603. }else{
  123604. insertBinaryOperator(&pRet, pPrev, p);
  123605. }
  123606. isRequirePhrase = !isPhrase;
  123607. }
  123608. assert( nByte>0 );
  123609. }
  123610. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  123611. nIn -= nByte;
  123612. zIn += nByte;
  123613. pPrev = p;
  123614. }
  123615. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  123616. rc = SQLITE_ERROR;
  123617. }
  123618. if( rc==SQLITE_DONE ){
  123619. rc = SQLITE_OK;
  123620. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  123621. if( !pRet ){
  123622. rc = SQLITE_ERROR;
  123623. }else{
  123624. Fts3Expr *pIter = pNotBranch;
  123625. while( pIter->pLeft ){
  123626. pIter = pIter->pLeft;
  123627. }
  123628. pIter->pLeft = pRet;
  123629. pRet->pParent = pIter;
  123630. pRet = pNotBranch;
  123631. }
  123632. }
  123633. }
  123634. *pnConsumed = n - nIn;
  123635. exprparse_out:
  123636. if( rc!=SQLITE_OK ){
  123637. sqlite3Fts3ExprFree(pRet);
  123638. sqlite3Fts3ExprFree(pNotBranch);
  123639. pRet = 0;
  123640. }
  123641. *ppExpr = pRet;
  123642. return rc;
  123643. }
  123644. /*
  123645. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  123646. ** as the only argument is more than nMaxDepth.
  123647. */
  123648. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  123649. int rc = SQLITE_OK;
  123650. if( p ){
  123651. if( nMaxDepth<0 ){
  123652. rc = SQLITE_TOOBIG;
  123653. }else{
  123654. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  123655. if( rc==SQLITE_OK ){
  123656. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  123657. }
  123658. }
  123659. }
  123660. return rc;
  123661. }
  123662. /*
  123663. ** This function attempts to transform the expression tree at (*pp) to
  123664. ** an equivalent but more balanced form. The tree is modified in place.
  123665. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  123666. ** new root expression node.
  123667. **
  123668. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  123669. **
  123670. ** Otherwise, if an error occurs, an SQLite error code is returned and
  123671. ** expression (*pp) freed.
  123672. */
  123673. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  123674. int rc = SQLITE_OK; /* Return code */
  123675. Fts3Expr *pRoot = *pp; /* Initial root node */
  123676. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  123677. int eType = pRoot->eType; /* Type of node in this tree */
  123678. if( nMaxDepth==0 ){
  123679. rc = SQLITE_ERROR;
  123680. }
  123681. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  123682. Fts3Expr **apLeaf;
  123683. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  123684. if( 0==apLeaf ){
  123685. rc = SQLITE_NOMEM;
  123686. }else{
  123687. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  123688. }
  123689. if( rc==SQLITE_OK ){
  123690. int i;
  123691. Fts3Expr *p;
  123692. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  123693. for(p=pRoot; p->eType==eType; p=p->pLeft){
  123694. assert( p->pParent==0 || p->pParent->pLeft==p );
  123695. assert( p->pLeft && p->pRight );
  123696. }
  123697. /* This loop runs once for each leaf in the tree of eType nodes. */
  123698. while( 1 ){
  123699. int iLvl;
  123700. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  123701. assert( pParent==0 || pParent->pLeft==p );
  123702. p->pParent = 0;
  123703. if( pParent ){
  123704. pParent->pLeft = 0;
  123705. }else{
  123706. pRoot = 0;
  123707. }
  123708. rc = fts3ExprBalance(&p, nMaxDepth-1);
  123709. if( rc!=SQLITE_OK ) break;
  123710. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  123711. if( apLeaf[iLvl]==0 ){
  123712. apLeaf[iLvl] = p;
  123713. p = 0;
  123714. }else{
  123715. assert( pFree );
  123716. pFree->pLeft = apLeaf[iLvl];
  123717. pFree->pRight = p;
  123718. pFree->pLeft->pParent = pFree;
  123719. pFree->pRight->pParent = pFree;
  123720. p = pFree;
  123721. pFree = pFree->pParent;
  123722. p->pParent = 0;
  123723. apLeaf[iLvl] = 0;
  123724. }
  123725. }
  123726. if( p ){
  123727. sqlite3Fts3ExprFree(p);
  123728. rc = SQLITE_TOOBIG;
  123729. break;
  123730. }
  123731. /* If that was the last leaf node, break out of the loop */
  123732. if( pParent==0 ) break;
  123733. /* Set $p to point to the next leaf in the tree of eType nodes */
  123734. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  123735. /* Remove pParent from the original tree. */
  123736. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  123737. pParent->pRight->pParent = pParent->pParent;
  123738. if( pParent->pParent ){
  123739. pParent->pParent->pLeft = pParent->pRight;
  123740. }else{
  123741. assert( pParent==pRoot );
  123742. pRoot = pParent->pRight;
  123743. }
  123744. /* Link pParent into the free node list. It will be used as an
  123745. ** internal node of the new tree. */
  123746. pParent->pParent = pFree;
  123747. pFree = pParent;
  123748. }
  123749. if( rc==SQLITE_OK ){
  123750. p = 0;
  123751. for(i=0; i<nMaxDepth; i++){
  123752. if( apLeaf[i] ){
  123753. if( p==0 ){
  123754. p = apLeaf[i];
  123755. p->pParent = 0;
  123756. }else{
  123757. assert( pFree!=0 );
  123758. pFree->pRight = p;
  123759. pFree->pLeft = apLeaf[i];
  123760. pFree->pLeft->pParent = pFree;
  123761. pFree->pRight->pParent = pFree;
  123762. p = pFree;
  123763. pFree = pFree->pParent;
  123764. p->pParent = 0;
  123765. }
  123766. }
  123767. }
  123768. pRoot = p;
  123769. }else{
  123770. /* An error occurred. Delete the contents of the apLeaf[] array
  123771. ** and pFree list. Everything else is cleaned up by the call to
  123772. ** sqlite3Fts3ExprFree(pRoot) below. */
  123773. Fts3Expr *pDel;
  123774. for(i=0; i<nMaxDepth; i++){
  123775. sqlite3Fts3ExprFree(apLeaf[i]);
  123776. }
  123777. while( (pDel=pFree)!=0 ){
  123778. pFree = pDel->pParent;
  123779. sqlite3_free(pDel);
  123780. }
  123781. }
  123782. assert( pFree==0 );
  123783. sqlite3_free( apLeaf );
  123784. }
  123785. }
  123786. if( rc!=SQLITE_OK ){
  123787. sqlite3Fts3ExprFree(pRoot);
  123788. pRoot = 0;
  123789. }
  123790. *pp = pRoot;
  123791. return rc;
  123792. }
  123793. /*
  123794. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  123795. ** differences:
  123796. **
  123797. ** 1. It does not do expression rebalancing.
  123798. ** 2. It does not check that the expression does not exceed the
  123799. ** maximum allowable depth.
  123800. ** 3. Even if it fails, *ppExpr may still be set to point to an
  123801. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  123802. ** in this case.
  123803. */
  123804. static int fts3ExprParseUnbalanced(
  123805. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  123806. int iLangid, /* Language id for tokenizer */
  123807. char **azCol, /* Array of column names for fts3 table */
  123808. int bFts4, /* True to allow FTS4-only syntax */
  123809. int nCol, /* Number of entries in azCol[] */
  123810. int iDefaultCol, /* Default column to query */
  123811. const char *z, int n, /* Text of MATCH query */
  123812. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  123813. ){
  123814. int nParsed;
  123815. int rc;
  123816. ParseContext sParse;
  123817. memset(&sParse, 0, sizeof(ParseContext));
  123818. sParse.pTokenizer = pTokenizer;
  123819. sParse.iLangid = iLangid;
  123820. sParse.azCol = (const char **)azCol;
  123821. sParse.nCol = nCol;
  123822. sParse.iDefaultCol = iDefaultCol;
  123823. sParse.bFts4 = bFts4;
  123824. if( z==0 ){
  123825. *ppExpr = 0;
  123826. return SQLITE_OK;
  123827. }
  123828. if( n<0 ){
  123829. n = (int)strlen(z);
  123830. }
  123831. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  123832. assert( rc==SQLITE_OK || *ppExpr==0 );
  123833. /* Check for mismatched parenthesis */
  123834. if( rc==SQLITE_OK && sParse.nNest ){
  123835. rc = SQLITE_ERROR;
  123836. }
  123837. return rc;
  123838. }
  123839. /*
  123840. ** Parameters z and n contain a pointer to and length of a buffer containing
  123841. ** an fts3 query expression, respectively. This function attempts to parse the
  123842. ** query expression and create a tree of Fts3Expr structures representing the
  123843. ** parsed expression. If successful, *ppExpr is set to point to the head
  123844. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  123845. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  123846. ** error) is returned and *ppExpr is set to 0.
  123847. **
  123848. ** If parameter n is a negative number, then z is assumed to point to a
  123849. ** nul-terminated string and the length is determined using strlen().
  123850. **
  123851. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  123852. ** use to normalize query tokens while parsing the expression. The azCol[]
  123853. ** array, which is assumed to contain nCol entries, should contain the names
  123854. ** of each column in the target fts3 table, in order from left to right.
  123855. ** Column names must be nul-terminated strings.
  123856. **
  123857. ** The iDefaultCol parameter should be passed the index of the table column
  123858. ** that appears on the left-hand-side of the MATCH operator (the default
  123859. ** column to match against for tokens for which a column name is not explicitly
  123860. ** specified as part of the query string), or -1 if tokens may by default
  123861. ** match any table column.
  123862. */
  123863. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  123864. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  123865. int iLangid, /* Language id for tokenizer */
  123866. char **azCol, /* Array of column names for fts3 table */
  123867. int bFts4, /* True to allow FTS4-only syntax */
  123868. int nCol, /* Number of entries in azCol[] */
  123869. int iDefaultCol, /* Default column to query */
  123870. const char *z, int n, /* Text of MATCH query */
  123871. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  123872. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  123873. ){
  123874. int rc = fts3ExprParseUnbalanced(
  123875. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  123876. );
  123877. /* Rebalance the expression. And check that its depth does not exceed
  123878. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  123879. if( rc==SQLITE_OK && *ppExpr ){
  123880. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  123881. if( rc==SQLITE_OK ){
  123882. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  123883. }
  123884. }
  123885. if( rc!=SQLITE_OK ){
  123886. sqlite3Fts3ExprFree(*ppExpr);
  123887. *ppExpr = 0;
  123888. if( rc==SQLITE_TOOBIG ){
  123889. *pzErr = sqlite3_mprintf(
  123890. "FTS expression tree is too large (maximum depth %d)",
  123891. SQLITE_FTS3_MAX_EXPR_DEPTH
  123892. );
  123893. rc = SQLITE_ERROR;
  123894. }else if( rc==SQLITE_ERROR ){
  123895. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  123896. }
  123897. }
  123898. return rc;
  123899. }
  123900. /*
  123901. ** Free a single node of an expression tree.
  123902. */
  123903. static void fts3FreeExprNode(Fts3Expr *p){
  123904. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  123905. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  123906. sqlite3_free(p->aMI);
  123907. sqlite3_free(p);
  123908. }
  123909. /*
  123910. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  123911. **
  123912. ** This function would be simpler if it recursively called itself. But
  123913. ** that would mean passing a sufficiently large expression to ExprParse()
  123914. ** could cause a stack overflow.
  123915. */
  123916. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  123917. Fts3Expr *p;
  123918. assert( pDel==0 || pDel->pParent==0 );
  123919. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  123920. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  123921. }
  123922. while( p ){
  123923. Fts3Expr *pParent = p->pParent;
  123924. fts3FreeExprNode(p);
  123925. if( pParent && p==pParent->pLeft && pParent->pRight ){
  123926. p = pParent->pRight;
  123927. while( p && (p->pLeft || p->pRight) ){
  123928. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  123929. p = (p->pLeft ? p->pLeft : p->pRight);
  123930. }
  123931. }else{
  123932. p = pParent;
  123933. }
  123934. }
  123935. }
  123936. /****************************************************************************
  123937. *****************************************************************************
  123938. ** Everything after this point is just test code.
  123939. */
  123940. #ifdef SQLITE_TEST
  123941. /* #include <stdio.h> */
  123942. /*
  123943. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  123944. */
  123945. static int queryTestTokenizer(
  123946. sqlite3 *db,
  123947. const char *zName,
  123948. const sqlite3_tokenizer_module **pp
  123949. ){
  123950. int rc;
  123951. sqlite3_stmt *pStmt;
  123952. const char zSql[] = "SELECT fts3_tokenizer(?)";
  123953. *pp = 0;
  123954. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  123955. if( rc!=SQLITE_OK ){
  123956. return rc;
  123957. }
  123958. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  123959. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  123960. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  123961. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  123962. }
  123963. }
  123964. return sqlite3_finalize(pStmt);
  123965. }
  123966. /*
  123967. ** Return a pointer to a buffer containing a text representation of the
  123968. ** expression passed as the first argument. The buffer is obtained from
  123969. ** sqlite3_malloc(). It is the responsibility of the caller to use
  123970. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  123971. ** NULL is returned.
  123972. **
  123973. ** If the second argument is not NULL, then its contents are prepended to
  123974. ** the returned expression text and then freed using sqlite3_free().
  123975. */
  123976. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  123977. if( pExpr==0 ){
  123978. return sqlite3_mprintf("");
  123979. }
  123980. switch( pExpr->eType ){
  123981. case FTSQUERY_PHRASE: {
  123982. Fts3Phrase *pPhrase = pExpr->pPhrase;
  123983. int i;
  123984. zBuf = sqlite3_mprintf(
  123985. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  123986. for(i=0; zBuf && i<pPhrase->nToken; i++){
  123987. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  123988. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  123989. (pPhrase->aToken[i].isPrefix?"+":"")
  123990. );
  123991. }
  123992. return zBuf;
  123993. }
  123994. case FTSQUERY_NEAR:
  123995. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  123996. break;
  123997. case FTSQUERY_NOT:
  123998. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  123999. break;
  124000. case FTSQUERY_AND:
  124001. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  124002. break;
  124003. case FTSQUERY_OR:
  124004. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  124005. break;
  124006. }
  124007. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  124008. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  124009. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  124010. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  124011. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  124012. return zBuf;
  124013. }
  124014. /*
  124015. ** This is the implementation of a scalar SQL function used to test the
  124016. ** expression parser. It should be called as follows:
  124017. **
  124018. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  124019. **
  124020. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  124021. ** to parse the query expression (see README.tokenizers). The second argument
  124022. ** is the query expression to parse. Each subsequent argument is the name
  124023. ** of a column of the fts3 table that the query expression may refer to.
  124024. ** For example:
  124025. **
  124026. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  124027. */
  124028. static void fts3ExprTest(
  124029. sqlite3_context *context,
  124030. int argc,
  124031. sqlite3_value **argv
  124032. ){
  124033. sqlite3_tokenizer_module const *pModule = 0;
  124034. sqlite3_tokenizer *pTokenizer = 0;
  124035. int rc;
  124036. char **azCol = 0;
  124037. const char *zExpr;
  124038. int nExpr;
  124039. int nCol;
  124040. int ii;
  124041. Fts3Expr *pExpr;
  124042. char *zBuf = 0;
  124043. sqlite3 *db = sqlite3_context_db_handle(context);
  124044. if( argc<3 ){
  124045. sqlite3_result_error(context,
  124046. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  124047. );
  124048. return;
  124049. }
  124050. rc = queryTestTokenizer(db,
  124051. (const char *)sqlite3_value_text(argv[0]), &pModule);
  124052. if( rc==SQLITE_NOMEM ){
  124053. sqlite3_result_error_nomem(context);
  124054. goto exprtest_out;
  124055. }else if( !pModule ){
  124056. sqlite3_result_error(context, "No such tokenizer module", -1);
  124057. goto exprtest_out;
  124058. }
  124059. rc = pModule->xCreate(0, 0, &pTokenizer);
  124060. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  124061. if( rc==SQLITE_NOMEM ){
  124062. sqlite3_result_error_nomem(context);
  124063. goto exprtest_out;
  124064. }
  124065. pTokenizer->pModule = pModule;
  124066. zExpr = (const char *)sqlite3_value_text(argv[1]);
  124067. nExpr = sqlite3_value_bytes(argv[1]);
  124068. nCol = argc-2;
  124069. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  124070. if( !azCol ){
  124071. sqlite3_result_error_nomem(context);
  124072. goto exprtest_out;
  124073. }
  124074. for(ii=0; ii<nCol; ii++){
  124075. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  124076. }
  124077. if( sqlite3_user_data(context) ){
  124078. char *zDummy = 0;
  124079. rc = sqlite3Fts3ExprParse(
  124080. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  124081. );
  124082. assert( rc==SQLITE_OK || pExpr==0 );
  124083. sqlite3_free(zDummy);
  124084. }else{
  124085. rc = fts3ExprParseUnbalanced(
  124086. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  124087. );
  124088. }
  124089. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  124090. sqlite3Fts3ExprFree(pExpr);
  124091. sqlite3_result_error(context, "Error parsing expression", -1);
  124092. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  124093. sqlite3_result_error_nomem(context);
  124094. }else{
  124095. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  124096. sqlite3_free(zBuf);
  124097. }
  124098. sqlite3Fts3ExprFree(pExpr);
  124099. exprtest_out:
  124100. if( pModule && pTokenizer ){
  124101. rc = pModule->xDestroy(pTokenizer);
  124102. }
  124103. sqlite3_free(azCol);
  124104. }
  124105. /*
  124106. ** Register the query expression parser test function fts3_exprtest()
  124107. ** with database connection db.
  124108. */
  124109. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  124110. int rc = sqlite3_create_function(
  124111. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  124112. );
  124113. if( rc==SQLITE_OK ){
  124114. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  124115. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  124116. );
  124117. }
  124118. return rc;
  124119. }
  124120. #endif
  124121. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124122. /************** End of fts3_expr.c *******************************************/
  124123. /************** Begin file fts3_hash.c ***************************************/
  124124. /*
  124125. ** 2001 September 22
  124126. **
  124127. ** The author disclaims copyright to this source code. In place of
  124128. ** a legal notice, here is a blessing:
  124129. **
  124130. ** May you do good and not evil.
  124131. ** May you find forgiveness for yourself and forgive others.
  124132. ** May you share freely, never taking more than you give.
  124133. **
  124134. *************************************************************************
  124135. ** This is the implementation of generic hash-tables used in SQLite.
  124136. ** We've modified it slightly to serve as a standalone hash table
  124137. ** implementation for the full-text indexing module.
  124138. */
  124139. /*
  124140. ** The code in this file is only compiled if:
  124141. **
  124142. ** * The FTS3 module is being built as an extension
  124143. ** (in which case SQLITE_CORE is not defined), or
  124144. **
  124145. ** * The FTS3 module is being built into the core of
  124146. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  124147. */
  124148. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124149. /* #include <assert.h> */
  124150. /* #include <stdlib.h> */
  124151. /* #include <string.h> */
  124152. /*
  124153. ** Malloc and Free functions
  124154. */
  124155. static void *fts3HashMalloc(int n){
  124156. void *p = sqlite3_malloc(n);
  124157. if( p ){
  124158. memset(p, 0, n);
  124159. }
  124160. return p;
  124161. }
  124162. static void fts3HashFree(void *p){
  124163. sqlite3_free(p);
  124164. }
  124165. /* Turn bulk memory into a hash table object by initializing the
  124166. ** fields of the Hash structure.
  124167. **
  124168. ** "pNew" is a pointer to the hash table that is to be initialized.
  124169. ** keyClass is one of the constants
  124170. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  124171. ** determines what kind of key the hash table will use. "copyKey" is
  124172. ** true if the hash table should make its own private copy of keys and
  124173. ** false if it should just use the supplied pointer.
  124174. */
  124175. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  124176. assert( pNew!=0 );
  124177. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  124178. pNew->keyClass = keyClass;
  124179. pNew->copyKey = copyKey;
  124180. pNew->first = 0;
  124181. pNew->count = 0;
  124182. pNew->htsize = 0;
  124183. pNew->ht = 0;
  124184. }
  124185. /* Remove all entries from a hash table. Reclaim all memory.
  124186. ** Call this routine to delete a hash table or to reset a hash table
  124187. ** to the empty state.
  124188. */
  124189. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  124190. Fts3HashElem *elem; /* For looping over all elements of the table */
  124191. assert( pH!=0 );
  124192. elem = pH->first;
  124193. pH->first = 0;
  124194. fts3HashFree(pH->ht);
  124195. pH->ht = 0;
  124196. pH->htsize = 0;
  124197. while( elem ){
  124198. Fts3HashElem *next_elem = elem->next;
  124199. if( pH->copyKey && elem->pKey ){
  124200. fts3HashFree(elem->pKey);
  124201. }
  124202. fts3HashFree(elem);
  124203. elem = next_elem;
  124204. }
  124205. pH->count = 0;
  124206. }
  124207. /*
  124208. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  124209. */
  124210. static int fts3StrHash(const void *pKey, int nKey){
  124211. const char *z = (const char *)pKey;
  124212. int h = 0;
  124213. if( nKey<=0 ) nKey = (int) strlen(z);
  124214. while( nKey > 0 ){
  124215. h = (h<<3) ^ h ^ *z++;
  124216. nKey--;
  124217. }
  124218. return h & 0x7fffffff;
  124219. }
  124220. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  124221. if( n1!=n2 ) return 1;
  124222. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  124223. }
  124224. /*
  124225. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  124226. */
  124227. static int fts3BinHash(const void *pKey, int nKey){
  124228. int h = 0;
  124229. const char *z = (const char *)pKey;
  124230. while( nKey-- > 0 ){
  124231. h = (h<<3) ^ h ^ *(z++);
  124232. }
  124233. return h & 0x7fffffff;
  124234. }
  124235. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  124236. if( n1!=n2 ) return 1;
  124237. return memcmp(pKey1,pKey2,n1);
  124238. }
  124239. /*
  124240. ** Return a pointer to the appropriate hash function given the key class.
  124241. **
  124242. ** The C syntax in this function definition may be unfamilar to some
  124243. ** programmers, so we provide the following additional explanation:
  124244. **
  124245. ** The name of the function is "ftsHashFunction". The function takes a
  124246. ** single parameter "keyClass". The return value of ftsHashFunction()
  124247. ** is a pointer to another function. Specifically, the return value
  124248. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  124249. ** with types "const void*" and "int" and returns an "int".
  124250. */
  124251. static int (*ftsHashFunction(int keyClass))(const void*,int){
  124252. if( keyClass==FTS3_HASH_STRING ){
  124253. return &fts3StrHash;
  124254. }else{
  124255. assert( keyClass==FTS3_HASH_BINARY );
  124256. return &fts3BinHash;
  124257. }
  124258. }
  124259. /*
  124260. ** Return a pointer to the appropriate hash function given the key class.
  124261. **
  124262. ** For help in interpreted the obscure C code in the function definition,
  124263. ** see the header comment on the previous function.
  124264. */
  124265. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  124266. if( keyClass==FTS3_HASH_STRING ){
  124267. return &fts3StrCompare;
  124268. }else{
  124269. assert( keyClass==FTS3_HASH_BINARY );
  124270. return &fts3BinCompare;
  124271. }
  124272. }
  124273. /* Link an element into the hash table
  124274. */
  124275. static void fts3HashInsertElement(
  124276. Fts3Hash *pH, /* The complete hash table */
  124277. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  124278. Fts3HashElem *pNew /* The element to be inserted */
  124279. ){
  124280. Fts3HashElem *pHead; /* First element already in pEntry */
  124281. pHead = pEntry->chain;
  124282. if( pHead ){
  124283. pNew->next = pHead;
  124284. pNew->prev = pHead->prev;
  124285. if( pHead->prev ){ pHead->prev->next = pNew; }
  124286. else { pH->first = pNew; }
  124287. pHead->prev = pNew;
  124288. }else{
  124289. pNew->next = pH->first;
  124290. if( pH->first ){ pH->first->prev = pNew; }
  124291. pNew->prev = 0;
  124292. pH->first = pNew;
  124293. }
  124294. pEntry->count++;
  124295. pEntry->chain = pNew;
  124296. }
  124297. /* Resize the hash table so that it cantains "new_size" buckets.
  124298. ** "new_size" must be a power of 2. The hash table might fail
  124299. ** to resize if sqliteMalloc() fails.
  124300. **
  124301. ** Return non-zero if a memory allocation error occurs.
  124302. */
  124303. static int fts3Rehash(Fts3Hash *pH, int new_size){
  124304. struct _fts3ht *new_ht; /* The new hash table */
  124305. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  124306. int (*xHash)(const void*,int); /* The hash function */
  124307. assert( (new_size & (new_size-1))==0 );
  124308. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  124309. if( new_ht==0 ) return 1;
  124310. fts3HashFree(pH->ht);
  124311. pH->ht = new_ht;
  124312. pH->htsize = new_size;
  124313. xHash = ftsHashFunction(pH->keyClass);
  124314. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  124315. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  124316. next_elem = elem->next;
  124317. fts3HashInsertElement(pH, &new_ht[h], elem);
  124318. }
  124319. return 0;
  124320. }
  124321. /* This function (for internal use only) locates an element in an
  124322. ** hash table that matches the given key. The hash for this key has
  124323. ** already been computed and is passed as the 4th parameter.
  124324. */
  124325. static Fts3HashElem *fts3FindElementByHash(
  124326. const Fts3Hash *pH, /* The pH to be searched */
  124327. const void *pKey, /* The key we are searching for */
  124328. int nKey,
  124329. int h /* The hash for this key. */
  124330. ){
  124331. Fts3HashElem *elem; /* Used to loop thru the element list */
  124332. int count; /* Number of elements left to test */
  124333. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  124334. if( pH->ht ){
  124335. struct _fts3ht *pEntry = &pH->ht[h];
  124336. elem = pEntry->chain;
  124337. count = pEntry->count;
  124338. xCompare = ftsCompareFunction(pH->keyClass);
  124339. while( count-- && elem ){
  124340. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  124341. return elem;
  124342. }
  124343. elem = elem->next;
  124344. }
  124345. }
  124346. return 0;
  124347. }
  124348. /* Remove a single entry from the hash table given a pointer to that
  124349. ** element and a hash on the element's key.
  124350. */
  124351. static void fts3RemoveElementByHash(
  124352. Fts3Hash *pH, /* The pH containing "elem" */
  124353. Fts3HashElem* elem, /* The element to be removed from the pH */
  124354. int h /* Hash value for the element */
  124355. ){
  124356. struct _fts3ht *pEntry;
  124357. if( elem->prev ){
  124358. elem->prev->next = elem->next;
  124359. }else{
  124360. pH->first = elem->next;
  124361. }
  124362. if( elem->next ){
  124363. elem->next->prev = elem->prev;
  124364. }
  124365. pEntry = &pH->ht[h];
  124366. if( pEntry->chain==elem ){
  124367. pEntry->chain = elem->next;
  124368. }
  124369. pEntry->count--;
  124370. if( pEntry->count<=0 ){
  124371. pEntry->chain = 0;
  124372. }
  124373. if( pH->copyKey && elem->pKey ){
  124374. fts3HashFree(elem->pKey);
  124375. }
  124376. fts3HashFree( elem );
  124377. pH->count--;
  124378. if( pH->count<=0 ){
  124379. assert( pH->first==0 );
  124380. assert( pH->count==0 );
  124381. fts3HashClear(pH);
  124382. }
  124383. }
  124384. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  124385. const Fts3Hash *pH,
  124386. const void *pKey,
  124387. int nKey
  124388. ){
  124389. int h; /* A hash on key */
  124390. int (*xHash)(const void*,int); /* The hash function */
  124391. if( pH==0 || pH->ht==0 ) return 0;
  124392. xHash = ftsHashFunction(pH->keyClass);
  124393. assert( xHash!=0 );
  124394. h = (*xHash)(pKey,nKey);
  124395. assert( (pH->htsize & (pH->htsize-1))==0 );
  124396. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  124397. }
  124398. /*
  124399. ** Attempt to locate an element of the hash table pH with a key
  124400. ** that matches pKey,nKey. Return the data for this element if it is
  124401. ** found, or NULL if there is no match.
  124402. */
  124403. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  124404. Fts3HashElem *pElem; /* The element that matches key (if any) */
  124405. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  124406. return pElem ? pElem->data : 0;
  124407. }
  124408. /* Insert an element into the hash table pH. The key is pKey,nKey
  124409. ** and the data is "data".
  124410. **
  124411. ** If no element exists with a matching key, then a new
  124412. ** element is created. A copy of the key is made if the copyKey
  124413. ** flag is set. NULL is returned.
  124414. **
  124415. ** If another element already exists with the same key, then the
  124416. ** new data replaces the old data and the old data is returned.
  124417. ** The key is not copied in this instance. If a malloc fails, then
  124418. ** the new data is returned and the hash table is unchanged.
  124419. **
  124420. ** If the "data" parameter to this function is NULL, then the
  124421. ** element corresponding to "key" is removed from the hash table.
  124422. */
  124423. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  124424. Fts3Hash *pH, /* The hash table to insert into */
  124425. const void *pKey, /* The key */
  124426. int nKey, /* Number of bytes in the key */
  124427. void *data /* The data */
  124428. ){
  124429. int hraw; /* Raw hash value of the key */
  124430. int h; /* the hash of the key modulo hash table size */
  124431. Fts3HashElem *elem; /* Used to loop thru the element list */
  124432. Fts3HashElem *new_elem; /* New element added to the pH */
  124433. int (*xHash)(const void*,int); /* The hash function */
  124434. assert( pH!=0 );
  124435. xHash = ftsHashFunction(pH->keyClass);
  124436. assert( xHash!=0 );
  124437. hraw = (*xHash)(pKey, nKey);
  124438. assert( (pH->htsize & (pH->htsize-1))==0 );
  124439. h = hraw & (pH->htsize-1);
  124440. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  124441. if( elem ){
  124442. void *old_data = elem->data;
  124443. if( data==0 ){
  124444. fts3RemoveElementByHash(pH,elem,h);
  124445. }else{
  124446. elem->data = data;
  124447. }
  124448. return old_data;
  124449. }
  124450. if( data==0 ) return 0;
  124451. if( (pH->htsize==0 && fts3Rehash(pH,8))
  124452. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  124453. ){
  124454. pH->count = 0;
  124455. return data;
  124456. }
  124457. assert( pH->htsize>0 );
  124458. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  124459. if( new_elem==0 ) return data;
  124460. if( pH->copyKey && pKey!=0 ){
  124461. new_elem->pKey = fts3HashMalloc( nKey );
  124462. if( new_elem->pKey==0 ){
  124463. fts3HashFree(new_elem);
  124464. return data;
  124465. }
  124466. memcpy((void*)new_elem->pKey, pKey, nKey);
  124467. }else{
  124468. new_elem->pKey = (void*)pKey;
  124469. }
  124470. new_elem->nKey = nKey;
  124471. pH->count++;
  124472. assert( pH->htsize>0 );
  124473. assert( (pH->htsize & (pH->htsize-1))==0 );
  124474. h = hraw & (pH->htsize-1);
  124475. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  124476. new_elem->data = data;
  124477. return 0;
  124478. }
  124479. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  124480. /************** End of fts3_hash.c *******************************************/
  124481. /************** Begin file fts3_porter.c *************************************/
  124482. /*
  124483. ** 2006 September 30
  124484. **
  124485. ** The author disclaims copyright to this source code. In place of
  124486. ** a legal notice, here is a blessing:
  124487. **
  124488. ** May you do good and not evil.
  124489. ** May you find forgiveness for yourself and forgive others.
  124490. ** May you share freely, never taking more than you give.
  124491. **
  124492. *************************************************************************
  124493. ** Implementation of the full-text-search tokenizer that implements
  124494. ** a Porter stemmer.
  124495. */
  124496. /*
  124497. ** The code in this file is only compiled if:
  124498. **
  124499. ** * The FTS3 module is being built as an extension
  124500. ** (in which case SQLITE_CORE is not defined), or
  124501. **
  124502. ** * The FTS3 module is being built into the core of
  124503. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  124504. */
  124505. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  124506. /* #include <assert.h> */
  124507. /* #include <stdlib.h> */
  124508. /* #include <stdio.h> */
  124509. /* #include <string.h> */
  124510. /*
  124511. ** Class derived from sqlite3_tokenizer
  124512. */
  124513. typedef struct porter_tokenizer {
  124514. sqlite3_tokenizer base; /* Base class */
  124515. } porter_tokenizer;
  124516. /*
  124517. ** Class derived from sqlite3_tokenizer_cursor
  124518. */
  124519. typedef struct porter_tokenizer_cursor {
  124520. sqlite3_tokenizer_cursor base;
  124521. const char *zInput; /* input we are tokenizing */
  124522. int nInput; /* size of the input */
  124523. int iOffset; /* current position in zInput */
  124524. int iToken; /* index of next token to be returned */
  124525. char *zToken; /* storage for current token */
  124526. int nAllocated; /* space allocated to zToken buffer */
  124527. } porter_tokenizer_cursor;
  124528. /*
  124529. ** Create a new tokenizer instance.
  124530. */
  124531. static int porterCreate(
  124532. int argc, const char * const *argv,
  124533. sqlite3_tokenizer **ppTokenizer
  124534. ){
  124535. porter_tokenizer *t;
  124536. UNUSED_PARAMETER(argc);
  124537. UNUSED_PARAMETER(argv);
  124538. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  124539. if( t==NULL ) return SQLITE_NOMEM;
  124540. memset(t, 0, sizeof(*t));
  124541. *ppTokenizer = &t->base;
  124542. return SQLITE_OK;
  124543. }
  124544. /*
  124545. ** Destroy a tokenizer
  124546. */
  124547. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  124548. sqlite3_free(pTokenizer);
  124549. return SQLITE_OK;
  124550. }
  124551. /*
  124552. ** Prepare to begin tokenizing a particular string. The input
  124553. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  124554. ** used to incrementally tokenize this string is returned in
  124555. ** *ppCursor.
  124556. */
  124557. static int porterOpen(
  124558. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  124559. const char *zInput, int nInput, /* String to be tokenized */
  124560. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  124561. ){
  124562. porter_tokenizer_cursor *c;
  124563. UNUSED_PARAMETER(pTokenizer);
  124564. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  124565. if( c==NULL ) return SQLITE_NOMEM;
  124566. c->zInput = zInput;
  124567. if( zInput==0 ){
  124568. c->nInput = 0;
  124569. }else if( nInput<0 ){
  124570. c->nInput = (int)strlen(zInput);
  124571. }else{
  124572. c->nInput = nInput;
  124573. }
  124574. c->iOffset = 0; /* start tokenizing at the beginning */
  124575. c->iToken = 0;
  124576. c->zToken = NULL; /* no space allocated, yet. */
  124577. c->nAllocated = 0;
  124578. *ppCursor = &c->base;
  124579. return SQLITE_OK;
  124580. }
  124581. /*
  124582. ** Close a tokenization cursor previously opened by a call to
  124583. ** porterOpen() above.
  124584. */
  124585. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  124586. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  124587. sqlite3_free(c->zToken);
  124588. sqlite3_free(c);
  124589. return SQLITE_OK;
  124590. }
  124591. /*
  124592. ** Vowel or consonant
  124593. */
  124594. static const char cType[] = {
  124595. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  124596. 1, 1, 1, 2, 1
  124597. };
  124598. /*
  124599. ** isConsonant() and isVowel() determine if their first character in
  124600. ** the string they point to is a consonant or a vowel, according
  124601. ** to Porter ruls.
  124602. **
  124603. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  124604. ** 'Y' is a consonant unless it follows another consonant,
  124605. ** in which case it is a vowel.
  124606. **
  124607. ** In these routine, the letters are in reverse order. So the 'y' rule
  124608. ** is that 'y' is a consonant unless it is followed by another
  124609. ** consonent.
  124610. */
  124611. static int isVowel(const char*);
  124612. static int isConsonant(const char *z){
  124613. int j;
  124614. char x = *z;
  124615. if( x==0 ) return 0;
  124616. assert( x>='a' && x<='z' );
  124617. j = cType[x-'a'];
  124618. if( j<2 ) return j;
  124619. return z[1]==0 || isVowel(z + 1);
  124620. }
  124621. static int isVowel(const char *z){
  124622. int j;
  124623. char x = *z;
  124624. if( x==0 ) return 0;
  124625. assert( x>='a' && x<='z' );
  124626. j = cType[x-'a'];
  124627. if( j<2 ) return 1-j;
  124628. return isConsonant(z + 1);
  124629. }
  124630. /*
  124631. ** Let any sequence of one or more vowels be represented by V and let
  124632. ** C be sequence of one or more consonants. Then every word can be
  124633. ** represented as:
  124634. **
  124635. ** [C] (VC){m} [V]
  124636. **
  124637. ** In prose: A word is an optional consonant followed by zero or
  124638. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  124639. ** number of vowel consonant pairs. This routine computes the value
  124640. ** of m for the first i bytes of a word.
  124641. **
  124642. ** Return true if the m-value for z is 1 or more. In other words,
  124643. ** return true if z contains at least one vowel that is followed
  124644. ** by a consonant.
  124645. **
  124646. ** In this routine z[] is in reverse order. So we are really looking
  124647. ** for an instance of of a consonant followed by a vowel.
  124648. */
  124649. static int m_gt_0(const char *z){
  124650. while( isVowel(z) ){ z++; }
  124651. if( *z==0 ) return 0;
  124652. while( isConsonant(z) ){ z++; }
  124653. return *z!=0;
  124654. }
  124655. /* Like mgt0 above except we are looking for a value of m which is
  124656. ** exactly 1
  124657. */
  124658. static int m_eq_1(const char *z){
  124659. while( isVowel(z) ){ z++; }
  124660. if( *z==0 ) return 0;
  124661. while( isConsonant(z) ){ z++; }
  124662. if( *z==0 ) return 0;
  124663. while( isVowel(z) ){ z++; }
  124664. if( *z==0 ) return 1;
  124665. while( isConsonant(z) ){ z++; }
  124666. return *z==0;
  124667. }
  124668. /* Like mgt0 above except we are looking for a value of m>1 instead
  124669. ** or m>0
  124670. */
  124671. static int m_gt_1(const char *z){
  124672. while( isVowel(z) ){ z++; }
  124673. if( *z==0 ) return 0;
  124674. while( isConsonant(z) ){ z++; }
  124675. if( *z==0 ) return 0;
  124676. while( isVowel(z) ){ z++; }
  124677. if( *z==0 ) return 0;
  124678. while( isConsonant(z) ){ z++; }
  124679. return *z!=0;
  124680. }
  124681. /*
  124682. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  124683. */
  124684. static int hasVowel(const char *z){
  124685. while( isConsonant(z) ){ z++; }
  124686. return *z!=0;
  124687. }
  124688. /*
  124689. ** Return TRUE if the word ends in a double consonant.
  124690. **
  124691. ** The text is reversed here. So we are really looking at
  124692. ** the first two characters of z[].
  124693. */
  124694. static int doubleConsonant(const char *z){
  124695. return isConsonant(z) && z[0]==z[1];
  124696. }
  124697. /*
  124698. ** Return TRUE if the word ends with three letters which
  124699. ** are consonant-vowel-consonent and where the final consonant
  124700. ** is not 'w', 'x', or 'y'.
  124701. **
  124702. ** The word is reversed here. So we are really checking the
  124703. ** first three letters and the first one cannot be in [wxy].
  124704. */
  124705. static int star_oh(const char *z){
  124706. return
  124707. isConsonant(z) &&
  124708. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  124709. isVowel(z+1) &&
  124710. isConsonant(z+2);
  124711. }
  124712. /*
  124713. ** If the word ends with zFrom and xCond() is true for the stem
  124714. ** of the word that preceeds the zFrom ending, then change the
  124715. ** ending to zTo.
  124716. **
  124717. ** The input word *pz and zFrom are both in reverse order. zTo
  124718. ** is in normal order.
  124719. **
  124720. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  124721. ** match. Not that TRUE is returned even if xCond() fails and
  124722. ** no substitution occurs.
  124723. */
  124724. static int stem(
  124725. char **pz, /* The word being stemmed (Reversed) */
  124726. const char *zFrom, /* If the ending matches this... (Reversed) */
  124727. const char *zTo, /* ... change the ending to this (not reversed) */
  124728. int (*xCond)(const char*) /* Condition that must be true */
  124729. ){
  124730. char *z = *pz;
  124731. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  124732. if( *zFrom!=0 ) return 0;
  124733. if( xCond && !xCond(z) ) return 1;
  124734. while( *zTo ){
  124735. *(--z) = *(zTo++);
  124736. }
  124737. *pz = z;
  124738. return 1;
  124739. }
  124740. /*
  124741. ** This is the fallback stemmer used when the porter stemmer is
  124742. ** inappropriate. The input word is copied into the output with
  124743. ** US-ASCII case folding. If the input word is too long (more
  124744. ** than 20 bytes if it contains no digits or more than 6 bytes if
  124745. ** it contains digits) then word is truncated to 20 or 6 bytes
  124746. ** by taking 10 or 3 bytes from the beginning and end.
  124747. */
  124748. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  124749. int i, mx, j;
  124750. int hasDigit = 0;
  124751. for(i=0; i<nIn; i++){
  124752. char c = zIn[i];
  124753. if( c>='A' && c<='Z' ){
  124754. zOut[i] = c - 'A' + 'a';
  124755. }else{
  124756. if( c>='0' && c<='9' ) hasDigit = 1;
  124757. zOut[i] = c;
  124758. }
  124759. }
  124760. mx = hasDigit ? 3 : 10;
  124761. if( nIn>mx*2 ){
  124762. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  124763. zOut[j] = zOut[i];
  124764. }
  124765. i = j;
  124766. }
  124767. zOut[i] = 0;
  124768. *pnOut = i;
  124769. }
  124770. /*
  124771. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  124772. ** zOut is at least big enough to hold nIn bytes. Write the actual
  124773. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  124774. **
  124775. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  124776. ** are converted to lower case. Upper-case UTF characters are
  124777. ** unchanged.
  124778. **
  124779. ** Words that are longer than about 20 bytes are stemmed by retaining
  124780. ** a few bytes from the beginning and the end of the word. If the
  124781. ** word contains digits, 3 bytes are taken from the beginning and
  124782. ** 3 bytes from the end. For long words without digits, 10 bytes
  124783. ** are taken from each end. US-ASCII case folding still applies.
  124784. **
  124785. ** If the input word contains not digits but does characters not
  124786. ** in [a-zA-Z] then no stemming is attempted and this routine just
  124787. ** copies the input into the input into the output with US-ASCII
  124788. ** case folding.
  124789. **
  124790. ** Stemming never increases the length of the word. So there is
  124791. ** no chance of overflowing the zOut buffer.
  124792. */
  124793. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  124794. int i, j;
  124795. char zReverse[28];
  124796. char *z, *z2;
  124797. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  124798. /* The word is too big or too small for the porter stemmer.
  124799. ** Fallback to the copy stemmer */
  124800. copy_stemmer(zIn, nIn, zOut, pnOut);
  124801. return;
  124802. }
  124803. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  124804. char c = zIn[i];
  124805. if( c>='A' && c<='Z' ){
  124806. zReverse[j] = c + 'a' - 'A';
  124807. }else if( c>='a' && c<='z' ){
  124808. zReverse[j] = c;
  124809. }else{
  124810. /* The use of a character not in [a-zA-Z] means that we fallback
  124811. ** to the copy stemmer */
  124812. copy_stemmer(zIn, nIn, zOut, pnOut);
  124813. return;
  124814. }
  124815. }
  124816. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  124817. z = &zReverse[j+1];
  124818. /* Step 1a */
  124819. if( z[0]=='s' ){
  124820. if(
  124821. !stem(&z, "sess", "ss", 0) &&
  124822. !stem(&z, "sei", "i", 0) &&
  124823. !stem(&z, "ss", "ss", 0)
  124824. ){
  124825. z++;
  124826. }
  124827. }
  124828. /* Step 1b */
  124829. z2 = z;
  124830. if( stem(&z, "dee", "ee", m_gt_0) ){
  124831. /* Do nothing. The work was all in the test */
  124832. }else if(
  124833. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  124834. && z!=z2
  124835. ){
  124836. if( stem(&z, "ta", "ate", 0) ||
  124837. stem(&z, "lb", "ble", 0) ||
  124838. stem(&z, "zi", "ize", 0) ){
  124839. /* Do nothing. The work was all in the test */
  124840. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  124841. z++;
  124842. }else if( m_eq_1(z) && star_oh(z) ){
  124843. *(--z) = 'e';
  124844. }
  124845. }
  124846. /* Step 1c */
  124847. if( z[0]=='y' && hasVowel(z+1) ){
  124848. z[0] = 'i';
  124849. }
  124850. /* Step 2 */
  124851. switch( z[1] ){
  124852. case 'a':
  124853. stem(&z, "lanoita", "ate", m_gt_0) ||
  124854. stem(&z, "lanoit", "tion", m_gt_0);
  124855. break;
  124856. case 'c':
  124857. stem(&z, "icne", "ence", m_gt_0) ||
  124858. stem(&z, "icna", "ance", m_gt_0);
  124859. break;
  124860. case 'e':
  124861. stem(&z, "rezi", "ize", m_gt_0);
  124862. break;
  124863. case 'g':
  124864. stem(&z, "igol", "log", m_gt_0);
  124865. break;
  124866. case 'l':
  124867. stem(&z, "ilb", "ble", m_gt_0) ||
  124868. stem(&z, "illa", "al", m_gt_0) ||
  124869. stem(&z, "iltne", "ent", m_gt_0) ||
  124870. stem(&z, "ile", "e", m_gt_0) ||
  124871. stem(&z, "ilsuo", "ous", m_gt_0);
  124872. break;
  124873. case 'o':
  124874. stem(&z, "noitazi", "ize", m_gt_0) ||
  124875. stem(&z, "noita", "ate", m_gt_0) ||
  124876. stem(&z, "rota", "ate", m_gt_0);
  124877. break;
  124878. case 's':
  124879. stem(&z, "msila", "al", m_gt_0) ||
  124880. stem(&z, "ssenevi", "ive", m_gt_0) ||
  124881. stem(&z, "ssenluf", "ful", m_gt_0) ||
  124882. stem(&z, "ssensuo", "ous", m_gt_0);
  124883. break;
  124884. case 't':
  124885. stem(&z, "itila", "al", m_gt_0) ||
  124886. stem(&z, "itivi", "ive", m_gt_0) ||
  124887. stem(&z, "itilib", "ble", m_gt_0);
  124888. break;
  124889. }
  124890. /* Step 3 */
  124891. switch( z[0] ){
  124892. case 'e':
  124893. stem(&z, "etaci", "ic", m_gt_0) ||
  124894. stem(&z, "evita", "", m_gt_0) ||
  124895. stem(&z, "ezila", "al", m_gt_0);
  124896. break;
  124897. case 'i':
  124898. stem(&z, "itici", "ic", m_gt_0);
  124899. break;
  124900. case 'l':
  124901. stem(&z, "laci", "ic", m_gt_0) ||
  124902. stem(&z, "luf", "", m_gt_0);
  124903. break;
  124904. case 's':
  124905. stem(&z, "ssen", "", m_gt_0);
  124906. break;
  124907. }
  124908. /* Step 4 */
  124909. switch( z[1] ){
  124910. case 'a':
  124911. if( z[0]=='l' && m_gt_1(z+2) ){
  124912. z += 2;
  124913. }
  124914. break;
  124915. case 'c':
  124916. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  124917. z += 4;
  124918. }
  124919. break;
  124920. case 'e':
  124921. if( z[0]=='r' && m_gt_1(z+2) ){
  124922. z += 2;
  124923. }
  124924. break;
  124925. case 'i':
  124926. if( z[0]=='c' && m_gt_1(z+2) ){
  124927. z += 2;
  124928. }
  124929. break;
  124930. case 'l':
  124931. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  124932. z += 4;
  124933. }
  124934. break;
  124935. case 'n':
  124936. if( z[0]=='t' ){
  124937. if( z[2]=='a' ){
  124938. if( m_gt_1(z+3) ){
  124939. z += 3;
  124940. }
  124941. }else if( z[2]=='e' ){
  124942. stem(&z, "tneme", "", m_gt_1) ||
  124943. stem(&z, "tnem", "", m_gt_1) ||
  124944. stem(&z, "tne", "", m_gt_1);
  124945. }
  124946. }
  124947. break;
  124948. case 'o':
  124949. if( z[0]=='u' ){
  124950. if( m_gt_1(z+2) ){
  124951. z += 2;
  124952. }
  124953. }else if( z[3]=='s' || z[3]=='t' ){
  124954. stem(&z, "noi", "", m_gt_1);
  124955. }
  124956. break;
  124957. case 's':
  124958. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  124959. z += 3;
  124960. }
  124961. break;
  124962. case 't':
  124963. stem(&z, "eta", "", m_gt_1) ||
  124964. stem(&z, "iti", "", m_gt_1);
  124965. break;
  124966. case 'u':
  124967. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  124968. z += 3;
  124969. }
  124970. break;
  124971. case 'v':
  124972. case 'z':
  124973. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  124974. z += 3;
  124975. }
  124976. break;
  124977. }
  124978. /* Step 5a */
  124979. if( z[0]=='e' ){
  124980. if( m_gt_1(z+1) ){
  124981. z++;
  124982. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  124983. z++;
  124984. }
  124985. }
  124986. /* Step 5b */
  124987. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  124988. z++;
  124989. }
  124990. /* z[] is now the stemmed word in reverse order. Flip it back
  124991. ** around into forward order and return.
  124992. */
  124993. *pnOut = i = (int)strlen(z);
  124994. zOut[i] = 0;
  124995. while( *z ){
  124996. zOut[--i] = *(z++);
  124997. }
  124998. }
  124999. /*
  125000. ** Characters that can be part of a token. We assume any character
  125001. ** whose value is greater than 0x80 (any UTF character) can be
  125002. ** part of a token. In other words, delimiters all must have
  125003. ** values of 0x7f or lower.
  125004. */
  125005. static const char porterIdChar[] = {
  125006. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  125007. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  125008. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  125009. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  125010. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  125011. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  125012. };
  125013. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  125014. /*
  125015. ** Extract the next token from a tokenization cursor. The cursor must
  125016. ** have been opened by a prior call to porterOpen().
  125017. */
  125018. static int porterNext(
  125019. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  125020. const char **pzToken, /* OUT: *pzToken is the token text */
  125021. int *pnBytes, /* OUT: Number of bytes in token */
  125022. int *piStartOffset, /* OUT: Starting offset of token */
  125023. int *piEndOffset, /* OUT: Ending offset of token */
  125024. int *piPosition /* OUT: Position integer of token */
  125025. ){
  125026. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  125027. const char *z = c->zInput;
  125028. while( c->iOffset<c->nInput ){
  125029. int iStartOffset, ch;
  125030. /* Scan past delimiter characters */
  125031. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  125032. c->iOffset++;
  125033. }
  125034. /* Count non-delimiter characters. */
  125035. iStartOffset = c->iOffset;
  125036. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  125037. c->iOffset++;
  125038. }
  125039. if( c->iOffset>iStartOffset ){
  125040. int n = c->iOffset-iStartOffset;
  125041. if( n>c->nAllocated ){
  125042. char *pNew;
  125043. c->nAllocated = n+20;
  125044. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  125045. if( !pNew ) return SQLITE_NOMEM;
  125046. c->zToken = pNew;
  125047. }
  125048. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  125049. *pzToken = c->zToken;
  125050. *piStartOffset = iStartOffset;
  125051. *piEndOffset = c->iOffset;
  125052. *piPosition = c->iToken++;
  125053. return SQLITE_OK;
  125054. }
  125055. }
  125056. return SQLITE_DONE;
  125057. }
  125058. /*
  125059. ** The set of routines that implement the porter-stemmer tokenizer
  125060. */
  125061. static const sqlite3_tokenizer_module porterTokenizerModule = {
  125062. 0,
  125063. porterCreate,
  125064. porterDestroy,
  125065. porterOpen,
  125066. porterClose,
  125067. porterNext,
  125068. 0
  125069. };
  125070. /*
  125071. ** Allocate a new porter tokenizer. Return a pointer to the new
  125072. ** tokenizer in *ppModule
  125073. */
  125074. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  125075. sqlite3_tokenizer_module const**ppModule
  125076. ){
  125077. *ppModule = &porterTokenizerModule;
  125078. }
  125079. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125080. /************** End of fts3_porter.c *****************************************/
  125081. /************** Begin file fts3_tokenizer.c **********************************/
  125082. /*
  125083. ** 2007 June 22
  125084. **
  125085. ** The author disclaims copyright to this source code. In place of
  125086. ** a legal notice, here is a blessing:
  125087. **
  125088. ** May you do good and not evil.
  125089. ** May you find forgiveness for yourself and forgive others.
  125090. ** May you share freely, never taking more than you give.
  125091. **
  125092. ******************************************************************************
  125093. **
  125094. ** This is part of an SQLite module implementing full-text search.
  125095. ** This particular file implements the generic tokenizer interface.
  125096. */
  125097. /*
  125098. ** The code in this file is only compiled if:
  125099. **
  125100. ** * The FTS3 module is being built as an extension
  125101. ** (in which case SQLITE_CORE is not defined), or
  125102. **
  125103. ** * The FTS3 module is being built into the core of
  125104. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  125105. */
  125106. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125107. /* #include <assert.h> */
  125108. /* #include <string.h> */
  125109. /*
  125110. ** Implementation of the SQL scalar function for accessing the underlying
  125111. ** hash table. This function may be called as follows:
  125112. **
  125113. ** SELECT <function-name>(<key-name>);
  125114. ** SELECT <function-name>(<key-name>, <pointer>);
  125115. **
  125116. ** where <function-name> is the name passed as the second argument
  125117. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  125118. **
  125119. ** If the <pointer> argument is specified, it must be a blob value
  125120. ** containing a pointer to be stored as the hash data corresponding
  125121. ** to the string <key-name>. If <pointer> is not specified, then
  125122. ** the string <key-name> must already exist in the has table. Otherwise,
  125123. ** an error is returned.
  125124. **
  125125. ** Whether or not the <pointer> argument is specified, the value returned
  125126. ** is a blob containing the pointer stored as the hash data corresponding
  125127. ** to string <key-name> (after the hash-table is updated, if applicable).
  125128. */
  125129. static void scalarFunc(
  125130. sqlite3_context *context,
  125131. int argc,
  125132. sqlite3_value **argv
  125133. ){
  125134. Fts3Hash *pHash;
  125135. void *pPtr = 0;
  125136. const unsigned char *zName;
  125137. int nName;
  125138. assert( argc==1 || argc==2 );
  125139. pHash = (Fts3Hash *)sqlite3_user_data(context);
  125140. zName = sqlite3_value_text(argv[0]);
  125141. nName = sqlite3_value_bytes(argv[0])+1;
  125142. if( argc==2 ){
  125143. void *pOld;
  125144. int n = sqlite3_value_bytes(argv[1]);
  125145. if( n!=sizeof(pPtr) ){
  125146. sqlite3_result_error(context, "argument type mismatch", -1);
  125147. return;
  125148. }
  125149. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  125150. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  125151. if( pOld==pPtr ){
  125152. sqlite3_result_error(context, "out of memory", -1);
  125153. return;
  125154. }
  125155. }else{
  125156. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  125157. if( !pPtr ){
  125158. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125159. sqlite3_result_error(context, zErr, -1);
  125160. sqlite3_free(zErr);
  125161. return;
  125162. }
  125163. }
  125164. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  125165. }
  125166. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  125167. static const char isFtsIdChar[] = {
  125168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  125169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  125170. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  125171. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  125172. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  125173. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  125174. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  125175. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  125176. };
  125177. return (c&0x80 || isFtsIdChar[(int)(c)]);
  125178. }
  125179. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  125180. const char *z1;
  125181. const char *z2 = 0;
  125182. /* Find the start of the next token. */
  125183. z1 = zStr;
  125184. while( z2==0 ){
  125185. char c = *z1;
  125186. switch( c ){
  125187. case '\0': return 0; /* No more tokens here */
  125188. case '\'':
  125189. case '"':
  125190. case '`': {
  125191. z2 = z1;
  125192. while( *++z2 && (*z2!=c || *++z2==c) );
  125193. break;
  125194. }
  125195. case '[':
  125196. z2 = &z1[1];
  125197. while( *z2 && z2[0]!=']' ) z2++;
  125198. if( *z2 ) z2++;
  125199. break;
  125200. default:
  125201. if( sqlite3Fts3IsIdChar(*z1) ){
  125202. z2 = &z1[1];
  125203. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  125204. }else{
  125205. z1++;
  125206. }
  125207. }
  125208. }
  125209. *pn = (int)(z2-z1);
  125210. return z1;
  125211. }
  125212. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  125213. Fts3Hash *pHash, /* Tokenizer hash table */
  125214. const char *zArg, /* Tokenizer name */
  125215. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  125216. char **pzErr /* OUT: Set to malloced error message */
  125217. ){
  125218. int rc;
  125219. char *z = (char *)zArg;
  125220. int n = 0;
  125221. char *zCopy;
  125222. char *zEnd; /* Pointer to nul-term of zCopy */
  125223. sqlite3_tokenizer_module *m;
  125224. zCopy = sqlite3_mprintf("%s", zArg);
  125225. if( !zCopy ) return SQLITE_NOMEM;
  125226. zEnd = &zCopy[strlen(zCopy)];
  125227. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  125228. z[n] = '\0';
  125229. sqlite3Fts3Dequote(z);
  125230. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  125231. if( !m ){
  125232. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  125233. rc = SQLITE_ERROR;
  125234. }else{
  125235. char const **aArg = 0;
  125236. int iArg = 0;
  125237. z = &z[n+1];
  125238. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  125239. int nNew = sizeof(char *)*(iArg+1);
  125240. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  125241. if( !aNew ){
  125242. sqlite3_free(zCopy);
  125243. sqlite3_free((void *)aArg);
  125244. return SQLITE_NOMEM;
  125245. }
  125246. aArg = aNew;
  125247. aArg[iArg++] = z;
  125248. z[n] = '\0';
  125249. sqlite3Fts3Dequote(z);
  125250. z = &z[n+1];
  125251. }
  125252. rc = m->xCreate(iArg, aArg, ppTok);
  125253. assert( rc!=SQLITE_OK || *ppTok );
  125254. if( rc!=SQLITE_OK ){
  125255. *pzErr = sqlite3_mprintf("unknown tokenizer");
  125256. }else{
  125257. (*ppTok)->pModule = m;
  125258. }
  125259. sqlite3_free((void *)aArg);
  125260. }
  125261. sqlite3_free(zCopy);
  125262. return rc;
  125263. }
  125264. #ifdef SQLITE_TEST
  125265. #include <tcl.h>
  125266. /* #include <string.h> */
  125267. /*
  125268. ** Implementation of a special SQL scalar function for testing tokenizers
  125269. ** designed to be used in concert with the Tcl testing framework. This
  125270. ** function must be called with two or more arguments:
  125271. **
  125272. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  125273. **
  125274. ** where <function-name> is the name passed as the second argument
  125275. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  125276. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  125277. **
  125278. ** The return value is a string that may be interpreted as a Tcl
  125279. ** list. For each token in the <input-string>, three elements are
  125280. ** added to the returned list. The first is the token position, the
  125281. ** second is the token text (folded, stemmed, etc.) and the third is the
  125282. ** substring of <input-string> associated with the token. For example,
  125283. ** using the built-in "simple" tokenizer:
  125284. **
  125285. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  125286. **
  125287. ** will return the string:
  125288. **
  125289. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  125290. **
  125291. */
  125292. static void testFunc(
  125293. sqlite3_context *context,
  125294. int argc,
  125295. sqlite3_value **argv
  125296. ){
  125297. Fts3Hash *pHash;
  125298. sqlite3_tokenizer_module *p;
  125299. sqlite3_tokenizer *pTokenizer = 0;
  125300. sqlite3_tokenizer_cursor *pCsr = 0;
  125301. const char *zErr = 0;
  125302. const char *zName;
  125303. int nName;
  125304. const char *zInput;
  125305. int nInput;
  125306. const char *azArg[64];
  125307. const char *zToken;
  125308. int nToken = 0;
  125309. int iStart = 0;
  125310. int iEnd = 0;
  125311. int iPos = 0;
  125312. int i;
  125313. Tcl_Obj *pRet;
  125314. if( argc<2 ){
  125315. sqlite3_result_error(context, "insufficient arguments", -1);
  125316. return;
  125317. }
  125318. nName = sqlite3_value_bytes(argv[0]);
  125319. zName = (const char *)sqlite3_value_text(argv[0]);
  125320. nInput = sqlite3_value_bytes(argv[argc-1]);
  125321. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  125322. pHash = (Fts3Hash *)sqlite3_user_data(context);
  125323. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  125324. if( !p ){
  125325. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125326. sqlite3_result_error(context, zErr, -1);
  125327. sqlite3_free(zErr);
  125328. return;
  125329. }
  125330. pRet = Tcl_NewObj();
  125331. Tcl_IncrRefCount(pRet);
  125332. for(i=1; i<argc-1; i++){
  125333. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  125334. }
  125335. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  125336. zErr = "error in xCreate()";
  125337. goto finish;
  125338. }
  125339. pTokenizer->pModule = p;
  125340. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  125341. zErr = "error in xOpen()";
  125342. goto finish;
  125343. }
  125344. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  125345. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  125346. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  125347. zToken = &zInput[iStart];
  125348. nToken = iEnd-iStart;
  125349. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  125350. }
  125351. if( SQLITE_OK!=p->xClose(pCsr) ){
  125352. zErr = "error in xClose()";
  125353. goto finish;
  125354. }
  125355. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  125356. zErr = "error in xDestroy()";
  125357. goto finish;
  125358. }
  125359. finish:
  125360. if( zErr ){
  125361. sqlite3_result_error(context, zErr, -1);
  125362. }else{
  125363. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  125364. }
  125365. Tcl_DecrRefCount(pRet);
  125366. }
  125367. static
  125368. int registerTokenizer(
  125369. sqlite3 *db,
  125370. char *zName,
  125371. const sqlite3_tokenizer_module *p
  125372. ){
  125373. int rc;
  125374. sqlite3_stmt *pStmt;
  125375. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  125376. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125377. if( rc!=SQLITE_OK ){
  125378. return rc;
  125379. }
  125380. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  125381. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  125382. sqlite3_step(pStmt);
  125383. return sqlite3_finalize(pStmt);
  125384. }
  125385. static
  125386. int queryTokenizer(
  125387. sqlite3 *db,
  125388. char *zName,
  125389. const sqlite3_tokenizer_module **pp
  125390. ){
  125391. int rc;
  125392. sqlite3_stmt *pStmt;
  125393. const char zSql[] = "SELECT fts3_tokenizer(?)";
  125394. *pp = 0;
  125395. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  125396. if( rc!=SQLITE_OK ){
  125397. return rc;
  125398. }
  125399. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  125400. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  125401. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  125402. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  125403. }
  125404. }
  125405. return sqlite3_finalize(pStmt);
  125406. }
  125407. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125408. /*
  125409. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  125410. ** This function is used for testing only, it is not included in the
  125411. ** build unless SQLITE_TEST is defined.
  125412. **
  125413. ** The purpose of this is to test that the fts3_tokenizer() function
  125414. ** can be used as designed by the C-code in the queryTokenizer and
  125415. ** registerTokenizer() functions above. These two functions are repeated
  125416. ** in the README.tokenizer file as an example, so it is important to
  125417. ** test them.
  125418. **
  125419. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  125420. ** function with no arguments. An assert() will fail if a problem is
  125421. ** detected. i.e.:
  125422. **
  125423. ** SELECT fts3_tokenizer_internal_test();
  125424. **
  125425. */
  125426. static void intTestFunc(
  125427. sqlite3_context *context,
  125428. int argc,
  125429. sqlite3_value **argv
  125430. ){
  125431. int rc;
  125432. const sqlite3_tokenizer_module *p1;
  125433. const sqlite3_tokenizer_module *p2;
  125434. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  125435. UNUSED_PARAMETER(argc);
  125436. UNUSED_PARAMETER(argv);
  125437. /* Test the query function */
  125438. sqlite3Fts3SimpleTokenizerModule(&p1);
  125439. rc = queryTokenizer(db, "simple", &p2);
  125440. assert( rc==SQLITE_OK );
  125441. assert( p1==p2 );
  125442. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  125443. assert( rc==SQLITE_ERROR );
  125444. assert( p2==0 );
  125445. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  125446. /* Test the storage function */
  125447. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  125448. assert( rc==SQLITE_OK );
  125449. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  125450. assert( rc==SQLITE_OK );
  125451. assert( p2==p1 );
  125452. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  125453. }
  125454. #endif
  125455. /*
  125456. ** Set up SQL objects in database db used to access the contents of
  125457. ** the hash table pointed to by argument pHash. The hash table must
  125458. ** been initialized to use string keys, and to take a private copy
  125459. ** of the key when a value is inserted. i.e. by a call similar to:
  125460. **
  125461. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  125462. **
  125463. ** This function adds a scalar function (see header comment above
  125464. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  125465. ** defined at compilation time, a temporary virtual table (see header
  125466. ** comment above struct HashTableVtab) to the database schema. Both
  125467. ** provide read/write access to the contents of *pHash.
  125468. **
  125469. ** The third argument to this function, zName, is used as the name
  125470. ** of both the scalar and, if created, the virtual table.
  125471. */
  125472. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  125473. sqlite3 *db,
  125474. Fts3Hash *pHash,
  125475. const char *zName
  125476. ){
  125477. int rc = SQLITE_OK;
  125478. void *p = (void *)pHash;
  125479. const int any = SQLITE_ANY;
  125480. #ifdef SQLITE_TEST
  125481. char *zTest = 0;
  125482. char *zTest2 = 0;
  125483. void *pdb = (void *)db;
  125484. zTest = sqlite3_mprintf("%s_test", zName);
  125485. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  125486. if( !zTest || !zTest2 ){
  125487. rc = SQLITE_NOMEM;
  125488. }
  125489. #endif
  125490. if( SQLITE_OK==rc ){
  125491. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  125492. }
  125493. if( SQLITE_OK==rc ){
  125494. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  125495. }
  125496. #ifdef SQLITE_TEST
  125497. if( SQLITE_OK==rc ){
  125498. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  125499. }
  125500. if( SQLITE_OK==rc ){
  125501. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  125502. }
  125503. #endif
  125504. #ifdef SQLITE_TEST
  125505. sqlite3_free(zTest);
  125506. sqlite3_free(zTest2);
  125507. #endif
  125508. return rc;
  125509. }
  125510. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125511. /************** End of fts3_tokenizer.c **************************************/
  125512. /************** Begin file fts3_tokenizer1.c *********************************/
  125513. /*
  125514. ** 2006 Oct 10
  125515. **
  125516. ** The author disclaims copyright to this source code. In place of
  125517. ** a legal notice, here is a blessing:
  125518. **
  125519. ** May you do good and not evil.
  125520. ** May you find forgiveness for yourself and forgive others.
  125521. ** May you share freely, never taking more than you give.
  125522. **
  125523. ******************************************************************************
  125524. **
  125525. ** Implementation of the "simple" full-text-search tokenizer.
  125526. */
  125527. /*
  125528. ** The code in this file is only compiled if:
  125529. **
  125530. ** * The FTS3 module is being built as an extension
  125531. ** (in which case SQLITE_CORE is not defined), or
  125532. **
  125533. ** * The FTS3 module is being built into the core of
  125534. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  125535. */
  125536. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125537. /* #include <assert.h> */
  125538. /* #include <stdlib.h> */
  125539. /* #include <stdio.h> */
  125540. /* #include <string.h> */
  125541. typedef struct simple_tokenizer {
  125542. sqlite3_tokenizer base;
  125543. char delim[128]; /* flag ASCII delimiters */
  125544. } simple_tokenizer;
  125545. typedef struct simple_tokenizer_cursor {
  125546. sqlite3_tokenizer_cursor base;
  125547. const char *pInput; /* input we are tokenizing */
  125548. int nBytes; /* size of the input */
  125549. int iOffset; /* current position in pInput */
  125550. int iToken; /* index of next token to be returned */
  125551. char *pToken; /* storage for current token */
  125552. int nTokenAllocated; /* space allocated to zToken buffer */
  125553. } simple_tokenizer_cursor;
  125554. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  125555. return c<0x80 && t->delim[c];
  125556. }
  125557. static int fts3_isalnum(int x){
  125558. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  125559. }
  125560. /*
  125561. ** Create a new tokenizer instance.
  125562. */
  125563. static int simpleCreate(
  125564. int argc, const char * const *argv,
  125565. sqlite3_tokenizer **ppTokenizer
  125566. ){
  125567. simple_tokenizer *t;
  125568. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  125569. if( t==NULL ) return SQLITE_NOMEM;
  125570. memset(t, 0, sizeof(*t));
  125571. /* TODO(shess) Delimiters need to remain the same from run to run,
  125572. ** else we need to reindex. One solution would be a meta-table to
  125573. ** track such information in the database, then we'd only want this
  125574. ** information on the initial create.
  125575. */
  125576. if( argc>1 ){
  125577. int i, n = (int)strlen(argv[1]);
  125578. for(i=0; i<n; i++){
  125579. unsigned char ch = argv[1][i];
  125580. /* We explicitly don't support UTF-8 delimiters for now. */
  125581. if( ch>=0x80 ){
  125582. sqlite3_free(t);
  125583. return SQLITE_ERROR;
  125584. }
  125585. t->delim[ch] = 1;
  125586. }
  125587. } else {
  125588. /* Mark non-alphanumeric ASCII characters as delimiters */
  125589. int i;
  125590. for(i=1; i<0x80; i++){
  125591. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  125592. }
  125593. }
  125594. *ppTokenizer = &t->base;
  125595. return SQLITE_OK;
  125596. }
  125597. /*
  125598. ** Destroy a tokenizer
  125599. */
  125600. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  125601. sqlite3_free(pTokenizer);
  125602. return SQLITE_OK;
  125603. }
  125604. /*
  125605. ** Prepare to begin tokenizing a particular string. The input
  125606. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  125607. ** used to incrementally tokenize this string is returned in
  125608. ** *ppCursor.
  125609. */
  125610. static int simpleOpen(
  125611. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  125612. const char *pInput, int nBytes, /* String to be tokenized */
  125613. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  125614. ){
  125615. simple_tokenizer_cursor *c;
  125616. UNUSED_PARAMETER(pTokenizer);
  125617. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  125618. if( c==NULL ) return SQLITE_NOMEM;
  125619. c->pInput = pInput;
  125620. if( pInput==0 ){
  125621. c->nBytes = 0;
  125622. }else if( nBytes<0 ){
  125623. c->nBytes = (int)strlen(pInput);
  125624. }else{
  125625. c->nBytes = nBytes;
  125626. }
  125627. c->iOffset = 0; /* start tokenizing at the beginning */
  125628. c->iToken = 0;
  125629. c->pToken = NULL; /* no space allocated, yet. */
  125630. c->nTokenAllocated = 0;
  125631. *ppCursor = &c->base;
  125632. return SQLITE_OK;
  125633. }
  125634. /*
  125635. ** Close a tokenization cursor previously opened by a call to
  125636. ** simpleOpen() above.
  125637. */
  125638. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  125639. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  125640. sqlite3_free(c->pToken);
  125641. sqlite3_free(c);
  125642. return SQLITE_OK;
  125643. }
  125644. /*
  125645. ** Extract the next token from a tokenization cursor. The cursor must
  125646. ** have been opened by a prior call to simpleOpen().
  125647. */
  125648. static int simpleNext(
  125649. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  125650. const char **ppToken, /* OUT: *ppToken is the token text */
  125651. int *pnBytes, /* OUT: Number of bytes in token */
  125652. int *piStartOffset, /* OUT: Starting offset of token */
  125653. int *piEndOffset, /* OUT: Ending offset of token */
  125654. int *piPosition /* OUT: Position integer of token */
  125655. ){
  125656. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  125657. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  125658. unsigned char *p = (unsigned char *)c->pInput;
  125659. while( c->iOffset<c->nBytes ){
  125660. int iStartOffset;
  125661. /* Scan past delimiter characters */
  125662. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  125663. c->iOffset++;
  125664. }
  125665. /* Count non-delimiter characters. */
  125666. iStartOffset = c->iOffset;
  125667. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  125668. c->iOffset++;
  125669. }
  125670. if( c->iOffset>iStartOffset ){
  125671. int i, n = c->iOffset-iStartOffset;
  125672. if( n>c->nTokenAllocated ){
  125673. char *pNew;
  125674. c->nTokenAllocated = n+20;
  125675. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  125676. if( !pNew ) return SQLITE_NOMEM;
  125677. c->pToken = pNew;
  125678. }
  125679. for(i=0; i<n; i++){
  125680. /* TODO(shess) This needs expansion to handle UTF-8
  125681. ** case-insensitivity.
  125682. */
  125683. unsigned char ch = p[iStartOffset+i];
  125684. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  125685. }
  125686. *ppToken = c->pToken;
  125687. *pnBytes = n;
  125688. *piStartOffset = iStartOffset;
  125689. *piEndOffset = c->iOffset;
  125690. *piPosition = c->iToken++;
  125691. return SQLITE_OK;
  125692. }
  125693. }
  125694. return SQLITE_DONE;
  125695. }
  125696. /*
  125697. ** The set of routines that implement the simple tokenizer
  125698. */
  125699. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  125700. 0,
  125701. simpleCreate,
  125702. simpleDestroy,
  125703. simpleOpen,
  125704. simpleClose,
  125705. simpleNext,
  125706. 0,
  125707. };
  125708. /*
  125709. ** Allocate a new simple tokenizer. Return a pointer to the new
  125710. ** tokenizer in *ppModule
  125711. */
  125712. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  125713. sqlite3_tokenizer_module const**ppModule
  125714. ){
  125715. *ppModule = &simpleTokenizerModule;
  125716. }
  125717. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  125718. /************** End of fts3_tokenizer1.c *************************************/
  125719. /************** Begin file fts3_tokenize_vtab.c ******************************/
  125720. /*
  125721. ** 2013 Apr 22
  125722. **
  125723. ** The author disclaims copyright to this source code. In place of
  125724. ** a legal notice, here is a blessing:
  125725. **
  125726. ** May you do good and not evil.
  125727. ** May you find forgiveness for yourself and forgive others.
  125728. ** May you share freely, never taking more than you give.
  125729. **
  125730. ******************************************************************************
  125731. **
  125732. ** This file contains code for the "fts3tokenize" virtual table module.
  125733. ** An fts3tokenize virtual table is created as follows:
  125734. **
  125735. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  125736. ** <tokenizer-name>, <arg-1>, ...
  125737. ** );
  125738. **
  125739. ** The table created has the following schema:
  125740. **
  125741. ** CREATE TABLE <tbl>(input, token, start, end, position)
  125742. **
  125743. ** When queried, the query must include a WHERE clause of type:
  125744. **
  125745. ** input = <string>
  125746. **
  125747. ** The virtual table module tokenizes this <string>, using the FTS3
  125748. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  125749. ** statement and returns one row for each token in the result. With
  125750. ** fields set as follows:
  125751. **
  125752. ** input: Always set to a copy of <string>
  125753. ** token: A token from the input.
  125754. ** start: Byte offset of the token within the input <string>.
  125755. ** end: Byte offset of the byte immediately following the end of the
  125756. ** token within the input string.
  125757. ** pos: Token offset of token within input.
  125758. **
  125759. */
  125760. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  125761. /* #include <string.h> */
  125762. /* #include <assert.h> */
  125763. typedef struct Fts3tokTable Fts3tokTable;
  125764. typedef struct Fts3tokCursor Fts3tokCursor;
  125765. /*
  125766. ** Virtual table structure.
  125767. */
  125768. struct Fts3tokTable {
  125769. sqlite3_vtab base; /* Base class used by SQLite core */
  125770. const sqlite3_tokenizer_module *pMod;
  125771. sqlite3_tokenizer *pTok;
  125772. };
  125773. /*
  125774. ** Virtual table cursor structure.
  125775. */
  125776. struct Fts3tokCursor {
  125777. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  125778. char *zInput; /* Input string */
  125779. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  125780. int iRowid; /* Current 'rowid' value */
  125781. const char *zToken; /* Current 'token' value */
  125782. int nToken; /* Size of zToken in bytes */
  125783. int iStart; /* Current 'start' value */
  125784. int iEnd; /* Current 'end' value */
  125785. int iPos; /* Current 'pos' value */
  125786. };
  125787. /*
  125788. ** Query FTS for the tokenizer implementation named zName.
  125789. */
  125790. static int fts3tokQueryTokenizer(
  125791. Fts3Hash *pHash,
  125792. const char *zName,
  125793. const sqlite3_tokenizer_module **pp,
  125794. char **pzErr
  125795. ){
  125796. sqlite3_tokenizer_module *p;
  125797. int nName = (int)strlen(zName);
  125798. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  125799. if( !p ){
  125800. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  125801. return SQLITE_ERROR;
  125802. }
  125803. *pp = p;
  125804. return SQLITE_OK;
  125805. }
  125806. /*
  125807. ** The second argument, argv[], is an array of pointers to nul-terminated
  125808. ** strings. This function makes a copy of the array and strings into a
  125809. ** single block of memory. It then dequotes any of the strings that appear
  125810. ** to be quoted.
  125811. **
  125812. ** If successful, output parameter *pazDequote is set to point at the
  125813. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  125814. ** responsible for eventually calling sqlite3_free() to free the array
  125815. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  125816. ** The final value of *pazDequote is undefined in this case.
  125817. */
  125818. static int fts3tokDequoteArray(
  125819. int argc, /* Number of elements in argv[] */
  125820. const char * const *argv, /* Input array */
  125821. char ***pazDequote /* Output array */
  125822. ){
  125823. int rc = SQLITE_OK; /* Return code */
  125824. if( argc==0 ){
  125825. *pazDequote = 0;
  125826. }else{
  125827. int i;
  125828. int nByte = 0;
  125829. char **azDequote;
  125830. for(i=0; i<argc; i++){
  125831. nByte += (int)(strlen(argv[i]) + 1);
  125832. }
  125833. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  125834. if( azDequote==0 ){
  125835. rc = SQLITE_NOMEM;
  125836. }else{
  125837. char *pSpace = (char *)&azDequote[argc];
  125838. for(i=0; i<argc; i++){
  125839. int n = (int)strlen(argv[i]);
  125840. azDequote[i] = pSpace;
  125841. memcpy(pSpace, argv[i], n+1);
  125842. sqlite3Fts3Dequote(pSpace);
  125843. pSpace += (n+1);
  125844. }
  125845. }
  125846. }
  125847. return rc;
  125848. }
  125849. /*
  125850. ** Schema of the tokenizer table.
  125851. */
  125852. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  125853. /*
  125854. ** This function does all the work for both the xConnect and xCreate methods.
  125855. ** These tables have no persistent representation of their own, so xConnect
  125856. ** and xCreate are identical operations.
  125857. **
  125858. ** argv[0]: module name
  125859. ** argv[1]: database name
  125860. ** argv[2]: table name
  125861. ** argv[3]: first argument (tokenizer name)
  125862. */
  125863. static int fts3tokConnectMethod(
  125864. sqlite3 *db, /* Database connection */
  125865. void *pHash, /* Hash table of tokenizers */
  125866. int argc, /* Number of elements in argv array */
  125867. const char * const *argv, /* xCreate/xConnect argument array */
  125868. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  125869. char **pzErr /* OUT: sqlite3_malloc'd error message */
  125870. ){
  125871. Fts3tokTable *pTab;
  125872. const sqlite3_tokenizer_module *pMod = 0;
  125873. sqlite3_tokenizer *pTok = 0;
  125874. int rc;
  125875. char **azDequote = 0;
  125876. int nDequote;
  125877. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  125878. if( rc!=SQLITE_OK ) return rc;
  125879. nDequote = argc-3;
  125880. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  125881. if( rc==SQLITE_OK ){
  125882. const char *zModule;
  125883. if( nDequote<1 ){
  125884. zModule = "simple";
  125885. }else{
  125886. zModule = azDequote[0];
  125887. }
  125888. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  125889. }
  125890. assert( (rc==SQLITE_OK)==(pMod!=0) );
  125891. if( rc==SQLITE_OK ){
  125892. const char * const *azArg = (const char * const *)&azDequote[1];
  125893. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  125894. }
  125895. if( rc==SQLITE_OK ){
  125896. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  125897. if( pTab==0 ){
  125898. rc = SQLITE_NOMEM;
  125899. }
  125900. }
  125901. if( rc==SQLITE_OK ){
  125902. memset(pTab, 0, sizeof(Fts3tokTable));
  125903. pTab->pMod = pMod;
  125904. pTab->pTok = pTok;
  125905. *ppVtab = &pTab->base;
  125906. }else{
  125907. if( pTok ){
  125908. pMod->xDestroy(pTok);
  125909. }
  125910. }
  125911. sqlite3_free(azDequote);
  125912. return rc;
  125913. }
  125914. /*
  125915. ** This function does the work for both the xDisconnect and xDestroy methods.
  125916. ** These tables have no persistent representation of their own, so xDisconnect
  125917. ** and xDestroy are identical operations.
  125918. */
  125919. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  125920. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  125921. pTab->pMod->xDestroy(pTab->pTok);
  125922. sqlite3_free(pTab);
  125923. return SQLITE_OK;
  125924. }
  125925. /*
  125926. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  125927. */
  125928. static int fts3tokBestIndexMethod(
  125929. sqlite3_vtab *pVTab,
  125930. sqlite3_index_info *pInfo
  125931. ){
  125932. int i;
  125933. UNUSED_PARAMETER(pVTab);
  125934. for(i=0; i<pInfo->nConstraint; i++){
  125935. if( pInfo->aConstraint[i].usable
  125936. && pInfo->aConstraint[i].iColumn==0
  125937. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  125938. ){
  125939. pInfo->idxNum = 1;
  125940. pInfo->aConstraintUsage[i].argvIndex = 1;
  125941. pInfo->aConstraintUsage[i].omit = 1;
  125942. pInfo->estimatedCost = 1;
  125943. return SQLITE_OK;
  125944. }
  125945. }
  125946. pInfo->idxNum = 0;
  125947. assert( pInfo->estimatedCost>1000000.0 );
  125948. return SQLITE_OK;
  125949. }
  125950. /*
  125951. ** xOpen - Open a cursor.
  125952. */
  125953. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  125954. Fts3tokCursor *pCsr;
  125955. UNUSED_PARAMETER(pVTab);
  125956. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  125957. if( pCsr==0 ){
  125958. return SQLITE_NOMEM;
  125959. }
  125960. memset(pCsr, 0, sizeof(Fts3tokCursor));
  125961. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  125962. return SQLITE_OK;
  125963. }
  125964. /*
  125965. ** Reset the tokenizer cursor passed as the only argument. As if it had
  125966. ** just been returned by fts3tokOpenMethod().
  125967. */
  125968. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  125969. if( pCsr->pCsr ){
  125970. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  125971. pTab->pMod->xClose(pCsr->pCsr);
  125972. pCsr->pCsr = 0;
  125973. }
  125974. sqlite3_free(pCsr->zInput);
  125975. pCsr->zInput = 0;
  125976. pCsr->zToken = 0;
  125977. pCsr->nToken = 0;
  125978. pCsr->iStart = 0;
  125979. pCsr->iEnd = 0;
  125980. pCsr->iPos = 0;
  125981. pCsr->iRowid = 0;
  125982. }
  125983. /*
  125984. ** xClose - Close a cursor.
  125985. */
  125986. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  125987. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  125988. fts3tokResetCursor(pCsr);
  125989. sqlite3_free(pCsr);
  125990. return SQLITE_OK;
  125991. }
  125992. /*
  125993. ** xNext - Advance the cursor to the next row, if any.
  125994. */
  125995. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  125996. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  125997. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  125998. int rc; /* Return code */
  125999. pCsr->iRowid++;
  126000. rc = pTab->pMod->xNext(pCsr->pCsr,
  126001. &pCsr->zToken, &pCsr->nToken,
  126002. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  126003. );
  126004. if( rc!=SQLITE_OK ){
  126005. fts3tokResetCursor(pCsr);
  126006. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  126007. }
  126008. return rc;
  126009. }
  126010. /*
  126011. ** xFilter - Initialize a cursor to point at the start of its data.
  126012. */
  126013. static int fts3tokFilterMethod(
  126014. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  126015. int idxNum, /* Strategy index */
  126016. const char *idxStr, /* Unused */
  126017. int nVal, /* Number of elements in apVal */
  126018. sqlite3_value **apVal /* Arguments for the indexing scheme */
  126019. ){
  126020. int rc = SQLITE_ERROR;
  126021. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126022. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  126023. UNUSED_PARAMETER(idxStr);
  126024. UNUSED_PARAMETER(nVal);
  126025. fts3tokResetCursor(pCsr);
  126026. if( idxNum==1 ){
  126027. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  126028. int nByte = sqlite3_value_bytes(apVal[0]);
  126029. pCsr->zInput = sqlite3_malloc(nByte+1);
  126030. if( pCsr->zInput==0 ){
  126031. rc = SQLITE_NOMEM;
  126032. }else{
  126033. memcpy(pCsr->zInput, zByte, nByte);
  126034. pCsr->zInput[nByte] = 0;
  126035. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  126036. if( rc==SQLITE_OK ){
  126037. pCsr->pCsr->pTokenizer = pTab->pTok;
  126038. }
  126039. }
  126040. }
  126041. if( rc!=SQLITE_OK ) return rc;
  126042. return fts3tokNextMethod(pCursor);
  126043. }
  126044. /*
  126045. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  126046. */
  126047. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  126048. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126049. return (pCsr->zToken==0);
  126050. }
  126051. /*
  126052. ** xColumn - Return a column value.
  126053. */
  126054. static int fts3tokColumnMethod(
  126055. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  126056. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  126057. int iCol /* Index of column to read value from */
  126058. ){
  126059. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126060. /* CREATE TABLE x(input, token, start, end, position) */
  126061. switch( iCol ){
  126062. case 0:
  126063. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  126064. break;
  126065. case 1:
  126066. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  126067. break;
  126068. case 2:
  126069. sqlite3_result_int(pCtx, pCsr->iStart);
  126070. break;
  126071. case 3:
  126072. sqlite3_result_int(pCtx, pCsr->iEnd);
  126073. break;
  126074. default:
  126075. assert( iCol==4 );
  126076. sqlite3_result_int(pCtx, pCsr->iPos);
  126077. break;
  126078. }
  126079. return SQLITE_OK;
  126080. }
  126081. /*
  126082. ** xRowid - Return the current rowid for the cursor.
  126083. */
  126084. static int fts3tokRowidMethod(
  126085. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  126086. sqlite_int64 *pRowid /* OUT: Rowid value */
  126087. ){
  126088. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  126089. *pRowid = (sqlite3_int64)pCsr->iRowid;
  126090. return SQLITE_OK;
  126091. }
  126092. /*
  126093. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  126094. ** if successful or an error code if sqlite3_create_module() fails.
  126095. */
  126096. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  126097. static const sqlite3_module fts3tok_module = {
  126098. 0, /* iVersion */
  126099. fts3tokConnectMethod, /* xCreate */
  126100. fts3tokConnectMethod, /* xConnect */
  126101. fts3tokBestIndexMethod, /* xBestIndex */
  126102. fts3tokDisconnectMethod, /* xDisconnect */
  126103. fts3tokDisconnectMethod, /* xDestroy */
  126104. fts3tokOpenMethod, /* xOpen */
  126105. fts3tokCloseMethod, /* xClose */
  126106. fts3tokFilterMethod, /* xFilter */
  126107. fts3tokNextMethod, /* xNext */
  126108. fts3tokEofMethod, /* xEof */
  126109. fts3tokColumnMethod, /* xColumn */
  126110. fts3tokRowidMethod, /* xRowid */
  126111. 0, /* xUpdate */
  126112. 0, /* xBegin */
  126113. 0, /* xSync */
  126114. 0, /* xCommit */
  126115. 0, /* xRollback */
  126116. 0, /* xFindFunction */
  126117. 0, /* xRename */
  126118. 0, /* xSavepoint */
  126119. 0, /* xRelease */
  126120. 0 /* xRollbackTo */
  126121. };
  126122. int rc; /* Return code */
  126123. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  126124. return rc;
  126125. }
  126126. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  126127. /************** End of fts3_tokenize_vtab.c **********************************/
  126128. /************** Begin file fts3_write.c **************************************/
  126129. /*
  126130. ** 2009 Oct 23
  126131. **
  126132. ** The author disclaims copyright to this source code. In place of
  126133. ** a legal notice, here is a blessing:
  126134. **
  126135. ** May you do good and not evil.
  126136. ** May you find forgiveness for yourself and forgive others.
  126137. ** May you share freely, never taking more than you give.
  126138. **
  126139. ******************************************************************************
  126140. **
  126141. ** This file is part of the SQLite FTS3 extension module. Specifically,
  126142. ** this file contains code to insert, update and delete rows from FTS3
  126143. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  126144. ** of the sub-routines used to merge segments are also used by the query
  126145. ** code in fts3.c.
  126146. */
  126147. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126148. /* #include <string.h> */
  126149. /* #include <assert.h> */
  126150. /* #include <stdlib.h> */
  126151. #define FTS_MAX_APPENDABLE_HEIGHT 16
  126152. /*
  126153. ** When full-text index nodes are loaded from disk, the buffer that they
  126154. ** are loaded into has the following number of bytes of padding at the end
  126155. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  126156. ** of 920 bytes is allocated for it.
  126157. **
  126158. ** This means that if we have a pointer into a buffer containing node data,
  126159. ** it is always safe to read up to two varints from it without risking an
  126160. ** overread, even if the node data is corrupted.
  126161. */
  126162. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  126163. /*
  126164. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  126165. ** memory incrementally instead of all at once. This can be a big performance
  126166. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  126167. ** method before retrieving all query results (as may happen, for example,
  126168. ** if a query has a LIMIT clause).
  126169. **
  126170. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  126171. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  126172. ** The code is written so that the hard lower-limit for each of these values
  126173. ** is 1. Clearly such small values would be inefficient, but can be useful
  126174. ** for testing purposes.
  126175. **
  126176. ** If this module is built with SQLITE_TEST defined, these constants may
  126177. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  126178. ** a Tcl interface to read and write the values.
  126179. */
  126180. #ifdef SQLITE_TEST
  126181. int test_fts3_node_chunksize = (4*1024);
  126182. int test_fts3_node_chunk_threshold = (4*1024)*4;
  126183. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  126184. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  126185. #else
  126186. # define FTS3_NODE_CHUNKSIZE (4*1024)
  126187. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  126188. #endif
  126189. /*
  126190. ** The two values that may be meaningfully bound to the :1 parameter in
  126191. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  126192. */
  126193. #define FTS_STAT_DOCTOTAL 0
  126194. #define FTS_STAT_INCRMERGEHINT 1
  126195. #define FTS_STAT_AUTOINCRMERGE 2
  126196. /*
  126197. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  126198. ** and incremental merge operation that takes place. This is used for
  126199. ** debugging FTS only, it should not usually be turned on in production
  126200. ** systems.
  126201. */
  126202. #ifdef FTS3_LOG_MERGES
  126203. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  126204. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  126205. }
  126206. #else
  126207. #define fts3LogMerge(x, y)
  126208. #endif
  126209. typedef struct PendingList PendingList;
  126210. typedef struct SegmentNode SegmentNode;
  126211. typedef struct SegmentWriter SegmentWriter;
  126212. /*
  126213. ** An instance of the following data structure is used to build doclists
  126214. ** incrementally. See function fts3PendingListAppend() for details.
  126215. */
  126216. struct PendingList {
  126217. int nData;
  126218. char *aData;
  126219. int nSpace;
  126220. sqlite3_int64 iLastDocid;
  126221. sqlite3_int64 iLastCol;
  126222. sqlite3_int64 iLastPos;
  126223. };
  126224. /*
  126225. ** Each cursor has a (possibly empty) linked list of the following objects.
  126226. */
  126227. struct Fts3DeferredToken {
  126228. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  126229. int iCol; /* Column token must occur in */
  126230. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  126231. PendingList *pList; /* Doclist is assembled here */
  126232. };
  126233. /*
  126234. ** An instance of this structure is used to iterate through the terms on
  126235. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  126236. ** this structure are only manipulated by code in this file, opaque handles
  126237. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  126238. ** terms when querying the full-text index. See functions:
  126239. **
  126240. ** sqlite3Fts3SegReaderNew()
  126241. ** sqlite3Fts3SegReaderFree()
  126242. ** sqlite3Fts3SegReaderIterate()
  126243. **
  126244. ** Methods used to manipulate Fts3SegReader structures:
  126245. **
  126246. ** fts3SegReaderNext()
  126247. ** fts3SegReaderFirstDocid()
  126248. ** fts3SegReaderNextDocid()
  126249. */
  126250. struct Fts3SegReader {
  126251. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  126252. u8 bLookup; /* True for a lookup only */
  126253. u8 rootOnly; /* True for a root-only reader */
  126254. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  126255. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  126256. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  126257. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  126258. char *aNode; /* Pointer to node data (or NULL) */
  126259. int nNode; /* Size of buffer at aNode (or 0) */
  126260. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  126261. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  126262. Fts3HashElem **ppNextElem;
  126263. /* Variables set by fts3SegReaderNext(). These may be read directly
  126264. ** by the caller. They are valid from the time SegmentReaderNew() returns
  126265. ** until SegmentReaderNext() returns something other than SQLITE_OK
  126266. ** (i.e. SQLITE_DONE).
  126267. */
  126268. int nTerm; /* Number of bytes in current term */
  126269. char *zTerm; /* Pointer to current term */
  126270. int nTermAlloc; /* Allocated size of zTerm buffer */
  126271. char *aDoclist; /* Pointer to doclist of current entry */
  126272. int nDoclist; /* Size of doclist in current entry */
  126273. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  126274. ** through the current doclist (aDoclist/nDoclist).
  126275. */
  126276. char *pOffsetList;
  126277. int nOffsetList; /* For descending pending seg-readers only */
  126278. sqlite3_int64 iDocid;
  126279. };
  126280. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  126281. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  126282. /*
  126283. ** An instance of this structure is used to create a segment b-tree in the
  126284. ** database. The internal details of this type are only accessed by the
  126285. ** following functions:
  126286. **
  126287. ** fts3SegWriterAdd()
  126288. ** fts3SegWriterFlush()
  126289. ** fts3SegWriterFree()
  126290. */
  126291. struct SegmentWriter {
  126292. SegmentNode *pTree; /* Pointer to interior tree structure */
  126293. sqlite3_int64 iFirst; /* First slot in %_segments written */
  126294. sqlite3_int64 iFree; /* Next free slot in %_segments */
  126295. char *zTerm; /* Pointer to previous term buffer */
  126296. int nTerm; /* Number of bytes in zTerm */
  126297. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  126298. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  126299. int nSize; /* Size of allocation at aData */
  126300. int nData; /* Bytes of data in aData */
  126301. char *aData; /* Pointer to block from malloc() */
  126302. };
  126303. /*
  126304. ** Type SegmentNode is used by the following three functions to create
  126305. ** the interior part of the segment b+-tree structures (everything except
  126306. ** the leaf nodes). These functions and type are only ever used by code
  126307. ** within the fts3SegWriterXXX() family of functions described above.
  126308. **
  126309. ** fts3NodeAddTerm()
  126310. ** fts3NodeWrite()
  126311. ** fts3NodeFree()
  126312. **
  126313. ** When a b+tree is written to the database (either as a result of a merge
  126314. ** or the pending-terms table being flushed), leaves are written into the
  126315. ** database file as soon as they are completely populated. The interior of
  126316. ** the tree is assembled in memory and written out only once all leaves have
  126317. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  126318. ** very large, meaning that the interior of the tree consumes relatively
  126319. ** little memory.
  126320. */
  126321. struct SegmentNode {
  126322. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  126323. SegmentNode *pRight; /* Pointer to right-sibling */
  126324. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  126325. int nEntry; /* Number of terms written to node so far */
  126326. char *zTerm; /* Pointer to previous term buffer */
  126327. int nTerm; /* Number of bytes in zTerm */
  126328. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  126329. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  126330. int nData; /* Bytes of valid data so far */
  126331. char *aData; /* Node data */
  126332. };
  126333. /*
  126334. ** Valid values for the second argument to fts3SqlStmt().
  126335. */
  126336. #define SQL_DELETE_CONTENT 0
  126337. #define SQL_IS_EMPTY 1
  126338. #define SQL_DELETE_ALL_CONTENT 2
  126339. #define SQL_DELETE_ALL_SEGMENTS 3
  126340. #define SQL_DELETE_ALL_SEGDIR 4
  126341. #define SQL_DELETE_ALL_DOCSIZE 5
  126342. #define SQL_DELETE_ALL_STAT 6
  126343. #define SQL_SELECT_CONTENT_BY_ROWID 7
  126344. #define SQL_NEXT_SEGMENT_INDEX 8
  126345. #define SQL_INSERT_SEGMENTS 9
  126346. #define SQL_NEXT_SEGMENTS_ID 10
  126347. #define SQL_INSERT_SEGDIR 11
  126348. #define SQL_SELECT_LEVEL 12
  126349. #define SQL_SELECT_LEVEL_RANGE 13
  126350. #define SQL_SELECT_LEVEL_COUNT 14
  126351. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  126352. #define SQL_DELETE_SEGDIR_LEVEL 16
  126353. #define SQL_DELETE_SEGMENTS_RANGE 17
  126354. #define SQL_CONTENT_INSERT 18
  126355. #define SQL_DELETE_DOCSIZE 19
  126356. #define SQL_REPLACE_DOCSIZE 20
  126357. #define SQL_SELECT_DOCSIZE 21
  126358. #define SQL_SELECT_STAT 22
  126359. #define SQL_REPLACE_STAT 23
  126360. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  126361. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  126362. #define SQL_DELETE_SEGDIR_RANGE 26
  126363. #define SQL_SELECT_ALL_LANGID 27
  126364. #define SQL_FIND_MERGE_LEVEL 28
  126365. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  126366. #define SQL_DELETE_SEGDIR_ENTRY 30
  126367. #define SQL_SHIFT_SEGDIR_ENTRY 31
  126368. #define SQL_SELECT_SEGDIR 32
  126369. #define SQL_CHOMP_SEGDIR 33
  126370. #define SQL_SEGMENT_IS_APPENDABLE 34
  126371. #define SQL_SELECT_INDEXES 35
  126372. #define SQL_SELECT_MXLEVEL 36
  126373. /*
  126374. ** This function is used to obtain an SQLite prepared statement handle
  126375. ** for the statement identified by the second argument. If successful,
  126376. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  126377. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  126378. **
  126379. ** If argument apVal is not NULL, then it must point to an array with
  126380. ** at least as many entries as the requested statement has bound
  126381. ** parameters. The values are bound to the statements parameters before
  126382. ** returning.
  126383. */
  126384. static int fts3SqlStmt(
  126385. Fts3Table *p, /* Virtual table handle */
  126386. int eStmt, /* One of the SQL_XXX constants above */
  126387. sqlite3_stmt **pp, /* OUT: Statement handle */
  126388. sqlite3_value **apVal /* Values to bind to statement */
  126389. ){
  126390. const char *azSql[] = {
  126391. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  126392. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  126393. /* 2 */ "DELETE FROM %Q.'%q_content'",
  126394. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  126395. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  126396. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  126397. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  126398. /* 7 */ "SELECT %s WHERE rowid=?",
  126399. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  126400. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  126401. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  126402. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  126403. /* Return segments in order from oldest to newest.*/
  126404. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126405. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  126406. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126407. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  126408. "ORDER BY level DESC, idx ASC",
  126409. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  126410. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  126411. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  126412. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  126413. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  126414. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  126415. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  126416. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  126417. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  126418. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  126419. /* 24 */ "",
  126420. /* 25 */ "",
  126421. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  126422. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  126423. /* This statement is used to determine which level to read the input from
  126424. ** when performing an incremental merge. It returns the absolute level number
  126425. ** of the oldest level in the db that contains at least ? segments. Or,
  126426. ** if no level in the FTS index contains more than ? segments, the statement
  126427. ** returns zero rows. */
  126428. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  126429. " ORDER BY (level %% 1024) ASC LIMIT 1",
  126430. /* Estimate the upper limit on the number of leaf nodes in a new segment
  126431. ** created by merging the oldest :2 segments from absolute level :1. See
  126432. ** function sqlite3Fts3Incrmerge() for details. */
  126433. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  126434. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  126435. /* SQL_DELETE_SEGDIR_ENTRY
  126436. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  126437. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  126438. /* SQL_SHIFT_SEGDIR_ENTRY
  126439. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  126440. ** to :1. */
  126441. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  126442. /* SQL_SELECT_SEGDIR
  126443. ** Read a single entry from the %_segdir table. The entry from absolute
  126444. ** level :1 with index value :2. */
  126445. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  126446. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  126447. /* SQL_CHOMP_SEGDIR
  126448. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  126449. ** entry located on absolute level :3 with index :4. */
  126450. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  126451. "WHERE level = ? AND idx = ?",
  126452. /* SQL_SEGMENT_IS_APPENDABLE
  126453. ** Return a single row if the segment with end_block=? is appendable. Or
  126454. ** no rows otherwise. */
  126455. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  126456. /* SQL_SELECT_INDEXES
  126457. ** Return the list of valid segment indexes for absolute level ? */
  126458. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  126459. /* SQL_SELECT_MXLEVEL
  126460. ** Return the largest relative level in the FTS index or indexes. */
  126461. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'"
  126462. };
  126463. int rc = SQLITE_OK;
  126464. sqlite3_stmt *pStmt;
  126465. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  126466. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  126467. pStmt = p->aStmt[eStmt];
  126468. if( !pStmt ){
  126469. char *zSql;
  126470. if( eStmt==SQL_CONTENT_INSERT ){
  126471. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  126472. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  126473. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  126474. }else{
  126475. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  126476. }
  126477. if( !zSql ){
  126478. rc = SQLITE_NOMEM;
  126479. }else{
  126480. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  126481. sqlite3_free(zSql);
  126482. assert( rc==SQLITE_OK || pStmt==0 );
  126483. p->aStmt[eStmt] = pStmt;
  126484. }
  126485. }
  126486. if( apVal ){
  126487. int i;
  126488. int nParam = sqlite3_bind_parameter_count(pStmt);
  126489. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  126490. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  126491. }
  126492. }
  126493. *pp = pStmt;
  126494. return rc;
  126495. }
  126496. static int fts3SelectDocsize(
  126497. Fts3Table *pTab, /* FTS3 table handle */
  126498. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  126499. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126500. ){
  126501. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  126502. int rc; /* Return code */
  126503. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  126504. if( rc==SQLITE_OK ){
  126505. sqlite3_bind_int64(pStmt, 1, iDocid);
  126506. rc = sqlite3_step(pStmt);
  126507. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  126508. rc = sqlite3_reset(pStmt);
  126509. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  126510. pStmt = 0;
  126511. }else{
  126512. rc = SQLITE_OK;
  126513. }
  126514. }
  126515. *ppStmt = pStmt;
  126516. return rc;
  126517. }
  126518. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  126519. Fts3Table *pTab, /* Fts3 table handle */
  126520. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126521. ){
  126522. sqlite3_stmt *pStmt = 0;
  126523. int rc;
  126524. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  126525. if( rc==SQLITE_OK ){
  126526. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  126527. if( sqlite3_step(pStmt)!=SQLITE_ROW
  126528. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  126529. ){
  126530. rc = sqlite3_reset(pStmt);
  126531. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  126532. pStmt = 0;
  126533. }
  126534. }
  126535. *ppStmt = pStmt;
  126536. return rc;
  126537. }
  126538. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  126539. Fts3Table *pTab, /* Fts3 table handle */
  126540. sqlite3_int64 iDocid, /* Docid to read size data for */
  126541. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  126542. ){
  126543. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  126544. }
  126545. /*
  126546. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  126547. ** array apVal[] to the SQL statement identified by eStmt, the statement
  126548. ** is executed.
  126549. **
  126550. ** Returns SQLITE_OK if the statement is successfully executed, or an
  126551. ** SQLite error code otherwise.
  126552. */
  126553. static void fts3SqlExec(
  126554. int *pRC, /* Result code */
  126555. Fts3Table *p, /* The FTS3 table */
  126556. int eStmt, /* Index of statement to evaluate */
  126557. sqlite3_value **apVal /* Parameters to bind */
  126558. ){
  126559. sqlite3_stmt *pStmt;
  126560. int rc;
  126561. if( *pRC ) return;
  126562. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  126563. if( rc==SQLITE_OK ){
  126564. sqlite3_step(pStmt);
  126565. rc = sqlite3_reset(pStmt);
  126566. }
  126567. *pRC = rc;
  126568. }
  126569. /*
  126570. ** This function ensures that the caller has obtained an exclusive
  126571. ** shared-cache table-lock on the %_segdir table. This is required before
  126572. ** writing data to the fts3 table. If this lock is not acquired first, then
  126573. ** the caller may end up attempting to take this lock as part of committing
  126574. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  126575. ** LOCKED_SHAREDCACHEto a COMMIT command.
  126576. **
  126577. ** It is best to avoid this because if FTS3 returns any error when
  126578. ** committing a transaction, the whole transaction will be rolled back.
  126579. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  126580. ** It can still happen if the user locks the underlying tables directly
  126581. ** instead of accessing them via FTS.
  126582. */
  126583. static int fts3Writelock(Fts3Table *p){
  126584. int rc = SQLITE_OK;
  126585. if( p->nPendingData==0 ){
  126586. sqlite3_stmt *pStmt;
  126587. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  126588. if( rc==SQLITE_OK ){
  126589. sqlite3_bind_null(pStmt, 1);
  126590. sqlite3_step(pStmt);
  126591. rc = sqlite3_reset(pStmt);
  126592. }
  126593. }
  126594. return rc;
  126595. }
  126596. /*
  126597. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  126598. ** Within each language id, a separate index is maintained to store the
  126599. ** document terms, and each configured prefix size (configured the FTS
  126600. ** "prefix=" option). And each index consists of multiple levels ("relative
  126601. ** levels").
  126602. **
  126603. ** All three of these values (the language id, the specific index and the
  126604. ** level within the index) are encoded in 64-bit integer values stored
  126605. ** in the %_segdir table on disk. This function is used to convert three
  126606. ** separate component values into the single 64-bit integer value that
  126607. ** can be used to query the %_segdir table.
  126608. **
  126609. ** Specifically, each language-id/index combination is allocated 1024
  126610. ** 64-bit integer level values ("absolute levels"). The main terms index
  126611. ** for language-id 0 is allocate values 0-1023. The first prefix index
  126612. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  126613. ** Language 1 indexes are allocated immediately following language 0.
  126614. **
  126615. ** So, for a system with nPrefix prefix indexes configured, the block of
  126616. ** absolute levels that corresponds to language-id iLangid and index
  126617. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  126618. */
  126619. static sqlite3_int64 getAbsoluteLevel(
  126620. Fts3Table *p, /* FTS3 table handle */
  126621. int iLangid, /* Language id */
  126622. int iIndex, /* Index in p->aIndex[] */
  126623. int iLevel /* Level of segments */
  126624. ){
  126625. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  126626. assert( iLangid>=0 );
  126627. assert( p->nIndex>0 );
  126628. assert( iIndex>=0 && iIndex<p->nIndex );
  126629. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  126630. return iBase + iLevel;
  126631. }
  126632. /*
  126633. ** Set *ppStmt to a statement handle that may be used to iterate through
  126634. ** all rows in the %_segdir table, from oldest to newest. If successful,
  126635. ** return SQLITE_OK. If an error occurs while preparing the statement,
  126636. ** return an SQLite error code.
  126637. **
  126638. ** There is only ever one instance of this SQL statement compiled for
  126639. ** each FTS3 table.
  126640. **
  126641. ** The statement returns the following columns from the %_segdir table:
  126642. **
  126643. ** 0: idx
  126644. ** 1: start_block
  126645. ** 2: leaves_end_block
  126646. ** 3: end_block
  126647. ** 4: root
  126648. */
  126649. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  126650. Fts3Table *p, /* FTS3 table */
  126651. int iLangid, /* Language being queried */
  126652. int iIndex, /* Index for p->aIndex[] */
  126653. int iLevel, /* Level to select (relative level) */
  126654. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  126655. ){
  126656. int rc;
  126657. sqlite3_stmt *pStmt = 0;
  126658. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  126659. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  126660. assert( iIndex>=0 && iIndex<p->nIndex );
  126661. if( iLevel<0 ){
  126662. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  126663. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  126664. if( rc==SQLITE_OK ){
  126665. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  126666. sqlite3_bind_int64(pStmt, 2,
  126667. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  126668. );
  126669. }
  126670. }else{
  126671. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  126672. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  126673. if( rc==SQLITE_OK ){
  126674. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  126675. }
  126676. }
  126677. *ppStmt = pStmt;
  126678. return rc;
  126679. }
  126680. /*
  126681. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  126682. ** if successful, or an SQLite error code otherwise.
  126683. **
  126684. ** This function also serves to allocate the PendingList structure itself.
  126685. ** For example, to create a new PendingList structure containing two
  126686. ** varints:
  126687. **
  126688. ** PendingList *p = 0;
  126689. ** fts3PendingListAppendVarint(&p, 1);
  126690. ** fts3PendingListAppendVarint(&p, 2);
  126691. */
  126692. static int fts3PendingListAppendVarint(
  126693. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  126694. sqlite3_int64 i /* Value to append to data */
  126695. ){
  126696. PendingList *p = *pp;
  126697. /* Allocate or grow the PendingList as required. */
  126698. if( !p ){
  126699. p = sqlite3_malloc(sizeof(*p) + 100);
  126700. if( !p ){
  126701. return SQLITE_NOMEM;
  126702. }
  126703. p->nSpace = 100;
  126704. p->aData = (char *)&p[1];
  126705. p->nData = 0;
  126706. }
  126707. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  126708. int nNew = p->nSpace * 2;
  126709. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  126710. if( !p ){
  126711. sqlite3_free(*pp);
  126712. *pp = 0;
  126713. return SQLITE_NOMEM;
  126714. }
  126715. p->nSpace = nNew;
  126716. p->aData = (char *)&p[1];
  126717. }
  126718. /* Append the new serialized varint to the end of the list. */
  126719. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  126720. p->aData[p->nData] = '\0';
  126721. *pp = p;
  126722. return SQLITE_OK;
  126723. }
  126724. /*
  126725. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  126726. ** is returned if the structure is sqlite3_realloced as part of adding
  126727. ** the entry. Otherwise, zero.
  126728. **
  126729. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  126730. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  126731. ** it is set to SQLITE_OK.
  126732. */
  126733. static int fts3PendingListAppend(
  126734. PendingList **pp, /* IN/OUT: PendingList structure */
  126735. sqlite3_int64 iDocid, /* Docid for entry to add */
  126736. sqlite3_int64 iCol, /* Column for entry to add */
  126737. sqlite3_int64 iPos, /* Position of term for entry to add */
  126738. int *pRc /* OUT: Return code */
  126739. ){
  126740. PendingList *p = *pp;
  126741. int rc = SQLITE_OK;
  126742. assert( !p || p->iLastDocid<=iDocid );
  126743. if( !p || p->iLastDocid!=iDocid ){
  126744. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  126745. if( p ){
  126746. assert( p->nData<p->nSpace );
  126747. assert( p->aData[p->nData]==0 );
  126748. p->nData++;
  126749. }
  126750. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  126751. goto pendinglistappend_out;
  126752. }
  126753. p->iLastCol = -1;
  126754. p->iLastPos = 0;
  126755. p->iLastDocid = iDocid;
  126756. }
  126757. if( iCol>0 && p->iLastCol!=iCol ){
  126758. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  126759. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  126760. ){
  126761. goto pendinglistappend_out;
  126762. }
  126763. p->iLastCol = iCol;
  126764. p->iLastPos = 0;
  126765. }
  126766. if( iCol>=0 ){
  126767. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  126768. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  126769. if( rc==SQLITE_OK ){
  126770. p->iLastPos = iPos;
  126771. }
  126772. }
  126773. pendinglistappend_out:
  126774. *pRc = rc;
  126775. if( p!=*pp ){
  126776. *pp = p;
  126777. return 1;
  126778. }
  126779. return 0;
  126780. }
  126781. /*
  126782. ** Free a PendingList object allocated by fts3PendingListAppend().
  126783. */
  126784. static void fts3PendingListDelete(PendingList *pList){
  126785. sqlite3_free(pList);
  126786. }
  126787. /*
  126788. ** Add an entry to one of the pending-terms hash tables.
  126789. */
  126790. static int fts3PendingTermsAddOne(
  126791. Fts3Table *p,
  126792. int iCol,
  126793. int iPos,
  126794. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  126795. const char *zToken,
  126796. int nToken
  126797. ){
  126798. PendingList *pList;
  126799. int rc = SQLITE_OK;
  126800. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  126801. if( pList ){
  126802. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  126803. }
  126804. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  126805. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  126806. /* Malloc failed while inserting the new entry. This can only
  126807. ** happen if there was no previous entry for this token.
  126808. */
  126809. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  126810. sqlite3_free(pList);
  126811. rc = SQLITE_NOMEM;
  126812. }
  126813. }
  126814. if( rc==SQLITE_OK ){
  126815. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  126816. }
  126817. return rc;
  126818. }
  126819. /*
  126820. ** Tokenize the nul-terminated string zText and add all tokens to the
  126821. ** pending-terms hash-table. The docid used is that currently stored in
  126822. ** p->iPrevDocid, and the column is specified by argument iCol.
  126823. **
  126824. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  126825. */
  126826. static int fts3PendingTermsAdd(
  126827. Fts3Table *p, /* Table into which text will be inserted */
  126828. int iLangid, /* Language id to use */
  126829. const char *zText, /* Text of document to be inserted */
  126830. int iCol, /* Column into which text is being inserted */
  126831. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  126832. ){
  126833. int rc;
  126834. int iStart = 0;
  126835. int iEnd = 0;
  126836. int iPos = 0;
  126837. int nWord = 0;
  126838. char const *zToken;
  126839. int nToken = 0;
  126840. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  126841. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  126842. sqlite3_tokenizer_cursor *pCsr;
  126843. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  126844. const char**,int*,int*,int*,int*);
  126845. assert( pTokenizer && pModule );
  126846. /* If the user has inserted a NULL value, this function may be called with
  126847. ** zText==0. In this case, add zero token entries to the hash table and
  126848. ** return early. */
  126849. if( zText==0 ){
  126850. *pnWord = 0;
  126851. return SQLITE_OK;
  126852. }
  126853. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  126854. if( rc!=SQLITE_OK ){
  126855. return rc;
  126856. }
  126857. xNext = pModule->xNext;
  126858. while( SQLITE_OK==rc
  126859. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  126860. ){
  126861. int i;
  126862. if( iPos>=nWord ) nWord = iPos+1;
  126863. /* Positions cannot be negative; we use -1 as a terminator internally.
  126864. ** Tokens must have a non-zero length.
  126865. */
  126866. if( iPos<0 || !zToken || nToken<=0 ){
  126867. rc = SQLITE_ERROR;
  126868. break;
  126869. }
  126870. /* Add the term to the terms index */
  126871. rc = fts3PendingTermsAddOne(
  126872. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  126873. );
  126874. /* Add the term to each of the prefix indexes that it is not too
  126875. ** short for. */
  126876. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  126877. struct Fts3Index *pIndex = &p->aIndex[i];
  126878. if( nToken<pIndex->nPrefix ) continue;
  126879. rc = fts3PendingTermsAddOne(
  126880. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  126881. );
  126882. }
  126883. }
  126884. pModule->xClose(pCsr);
  126885. *pnWord += nWord;
  126886. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  126887. }
  126888. /*
  126889. ** Calling this function indicates that subsequent calls to
  126890. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  126891. ** contents of the document with docid iDocid.
  126892. */
  126893. static int fts3PendingTermsDocid(
  126894. Fts3Table *p, /* Full-text table handle */
  126895. int iLangid, /* Language id of row being written */
  126896. sqlite_int64 iDocid /* Docid of row being written */
  126897. ){
  126898. assert( iLangid>=0 );
  126899. /* TODO(shess) Explore whether partially flushing the buffer on
  126900. ** forced-flush would provide better performance. I suspect that if
  126901. ** we ordered the doclists by size and flushed the largest until the
  126902. ** buffer was half empty, that would let the less frequent terms
  126903. ** generate longer doclists.
  126904. */
  126905. if( iDocid<=p->iPrevDocid
  126906. || p->iPrevLangid!=iLangid
  126907. || p->nPendingData>p->nMaxPendingData
  126908. ){
  126909. int rc = sqlite3Fts3PendingTermsFlush(p);
  126910. if( rc!=SQLITE_OK ) return rc;
  126911. }
  126912. p->iPrevDocid = iDocid;
  126913. p->iPrevLangid = iLangid;
  126914. return SQLITE_OK;
  126915. }
  126916. /*
  126917. ** Discard the contents of the pending-terms hash tables.
  126918. */
  126919. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  126920. int i;
  126921. for(i=0; i<p->nIndex; i++){
  126922. Fts3HashElem *pElem;
  126923. Fts3Hash *pHash = &p->aIndex[i].hPending;
  126924. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  126925. PendingList *pList = (PendingList *)fts3HashData(pElem);
  126926. fts3PendingListDelete(pList);
  126927. }
  126928. fts3HashClear(pHash);
  126929. }
  126930. p->nPendingData = 0;
  126931. }
  126932. /*
  126933. ** This function is called by the xUpdate() method as part of an INSERT
  126934. ** operation. It adds entries for each term in the new record to the
  126935. ** pendingTerms hash table.
  126936. **
  126937. ** Argument apVal is the same as the similarly named argument passed to
  126938. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  126939. */
  126940. static int fts3InsertTerms(
  126941. Fts3Table *p,
  126942. int iLangid,
  126943. sqlite3_value **apVal,
  126944. u32 *aSz
  126945. ){
  126946. int i; /* Iterator variable */
  126947. for(i=2; i<p->nColumn+2; i++){
  126948. int iCol = i-2;
  126949. if( p->abNotindexed[iCol]==0 ){
  126950. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  126951. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  126952. if( rc!=SQLITE_OK ){
  126953. return rc;
  126954. }
  126955. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  126956. }
  126957. }
  126958. return SQLITE_OK;
  126959. }
  126960. /*
  126961. ** This function is called by the xUpdate() method for an INSERT operation.
  126962. ** The apVal parameter is passed a copy of the apVal argument passed by
  126963. ** SQLite to the xUpdate() method. i.e:
  126964. **
  126965. ** apVal[0] Not used for INSERT.
  126966. ** apVal[1] rowid
  126967. ** apVal[2] Left-most user-defined column
  126968. ** ...
  126969. ** apVal[p->nColumn+1] Right-most user-defined column
  126970. ** apVal[p->nColumn+2] Hidden column with same name as table
  126971. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  126972. ** apVal[p->nColumn+4] Hidden languageid column
  126973. */
  126974. static int fts3InsertData(
  126975. Fts3Table *p, /* Full-text table */
  126976. sqlite3_value **apVal, /* Array of values to insert */
  126977. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  126978. ){
  126979. int rc; /* Return code */
  126980. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  126981. if( p->zContentTbl ){
  126982. sqlite3_value *pRowid = apVal[p->nColumn+3];
  126983. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  126984. pRowid = apVal[1];
  126985. }
  126986. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  126987. return SQLITE_CONSTRAINT;
  126988. }
  126989. *piDocid = sqlite3_value_int64(pRowid);
  126990. return SQLITE_OK;
  126991. }
  126992. /* Locate the statement handle used to insert data into the %_content
  126993. ** table. The SQL for this statement is:
  126994. **
  126995. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  126996. **
  126997. ** The statement features N '?' variables, where N is the number of user
  126998. ** defined columns in the FTS3 table, plus one for the docid field.
  126999. */
  127000. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  127001. if( rc==SQLITE_OK && p->zLanguageid ){
  127002. rc = sqlite3_bind_int(
  127003. pContentInsert, p->nColumn+2,
  127004. sqlite3_value_int(apVal[p->nColumn+4])
  127005. );
  127006. }
  127007. if( rc!=SQLITE_OK ) return rc;
  127008. /* There is a quirk here. The users INSERT statement may have specified
  127009. ** a value for the "rowid" field, for the "docid" field, or for both.
  127010. ** Which is a problem, since "rowid" and "docid" are aliases for the
  127011. ** same value. For example:
  127012. **
  127013. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  127014. **
  127015. ** In FTS3, this is an error. It is an error to specify non-NULL values
  127016. ** for both docid and some other rowid alias.
  127017. */
  127018. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  127019. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  127020. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  127021. ){
  127022. /* A rowid/docid conflict. */
  127023. return SQLITE_ERROR;
  127024. }
  127025. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  127026. if( rc!=SQLITE_OK ) return rc;
  127027. }
  127028. /* Execute the statement to insert the record. Set *piDocid to the
  127029. ** new docid value.
  127030. */
  127031. sqlite3_step(pContentInsert);
  127032. rc = sqlite3_reset(pContentInsert);
  127033. *piDocid = sqlite3_last_insert_rowid(p->db);
  127034. return rc;
  127035. }
  127036. /*
  127037. ** Remove all data from the FTS3 table. Clear the hash table containing
  127038. ** pending terms.
  127039. */
  127040. static int fts3DeleteAll(Fts3Table *p, int bContent){
  127041. int rc = SQLITE_OK; /* Return code */
  127042. /* Discard the contents of the pending-terms hash table. */
  127043. sqlite3Fts3PendingTermsClear(p);
  127044. /* Delete everything from the shadow tables. Except, leave %_content as
  127045. ** is if bContent is false. */
  127046. assert( p->zContentTbl==0 || bContent==0 );
  127047. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  127048. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  127049. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  127050. if( p->bHasDocsize ){
  127051. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  127052. }
  127053. if( p->bHasStat ){
  127054. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  127055. }
  127056. return rc;
  127057. }
  127058. /*
  127059. **
  127060. */
  127061. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  127062. int iLangid = 0;
  127063. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  127064. return iLangid;
  127065. }
  127066. /*
  127067. ** The first element in the apVal[] array is assumed to contain the docid
  127068. ** (an integer) of a row about to be deleted. Remove all terms from the
  127069. ** full-text index.
  127070. */
  127071. static void fts3DeleteTerms(
  127072. int *pRC, /* Result code */
  127073. Fts3Table *p, /* The FTS table to delete from */
  127074. sqlite3_value *pRowid, /* The docid to be deleted */
  127075. u32 *aSz, /* Sizes of deleted document written here */
  127076. int *pbFound /* OUT: Set to true if row really does exist */
  127077. ){
  127078. int rc;
  127079. sqlite3_stmt *pSelect;
  127080. assert( *pbFound==0 );
  127081. if( *pRC ) return;
  127082. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  127083. if( rc==SQLITE_OK ){
  127084. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  127085. int i;
  127086. int iLangid = langidFromSelect(p, pSelect);
  127087. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  127088. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  127089. int iCol = i-1;
  127090. if( p->abNotindexed[iCol]==0 ){
  127091. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  127092. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  127093. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  127094. }
  127095. }
  127096. if( rc!=SQLITE_OK ){
  127097. sqlite3_reset(pSelect);
  127098. *pRC = rc;
  127099. return;
  127100. }
  127101. *pbFound = 1;
  127102. }
  127103. rc = sqlite3_reset(pSelect);
  127104. }else{
  127105. sqlite3_reset(pSelect);
  127106. }
  127107. *pRC = rc;
  127108. }
  127109. /*
  127110. ** Forward declaration to account for the circular dependency between
  127111. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  127112. */
  127113. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  127114. /*
  127115. ** This function allocates a new level iLevel index in the segdir table.
  127116. ** Usually, indexes are allocated within a level sequentially starting
  127117. ** with 0, so the allocated index is one greater than the value returned
  127118. ** by:
  127119. **
  127120. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  127121. **
  127122. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  127123. ** level, they are merged into a single level (iLevel+1) segment and the
  127124. ** allocated index is 0.
  127125. **
  127126. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  127127. ** returned. Otherwise, an SQLite error code is returned.
  127128. */
  127129. static int fts3AllocateSegdirIdx(
  127130. Fts3Table *p,
  127131. int iLangid, /* Language id */
  127132. int iIndex, /* Index for p->aIndex */
  127133. int iLevel,
  127134. int *piIdx
  127135. ){
  127136. int rc; /* Return Code */
  127137. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  127138. int iNext = 0; /* Result of query pNextIdx */
  127139. assert( iLangid>=0 );
  127140. assert( p->nIndex>=1 );
  127141. /* Set variable iNext to the next available segdir index at level iLevel. */
  127142. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  127143. if( rc==SQLITE_OK ){
  127144. sqlite3_bind_int64(
  127145. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  127146. );
  127147. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  127148. iNext = sqlite3_column_int(pNextIdx, 0);
  127149. }
  127150. rc = sqlite3_reset(pNextIdx);
  127151. }
  127152. if( rc==SQLITE_OK ){
  127153. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  127154. ** full, merge all segments in level iLevel into a single iLevel+1
  127155. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  127156. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  127157. */
  127158. if( iNext>=FTS3_MERGE_COUNT ){
  127159. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  127160. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  127161. *piIdx = 0;
  127162. }else{
  127163. *piIdx = iNext;
  127164. }
  127165. }
  127166. return rc;
  127167. }
  127168. /*
  127169. ** The %_segments table is declared as follows:
  127170. **
  127171. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  127172. **
  127173. ** This function reads data from a single row of the %_segments table. The
  127174. ** specific row is identified by the iBlockid parameter. If paBlob is not
  127175. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  127176. ** with the contents of the blob stored in the "block" column of the
  127177. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  127178. ** to the size of the blob in bytes before returning.
  127179. **
  127180. ** If an error occurs, or the table does not contain the specified row,
  127181. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  127182. ** paBlob is non-NULL, then it is the responsibility of the caller to
  127183. ** eventually free the returned buffer.
  127184. **
  127185. ** This function may leave an open sqlite3_blob* handle in the
  127186. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  127187. ** to this function. The handle may be closed by calling the
  127188. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  127189. ** performance improvement, but the blob handle should always be closed
  127190. ** before control is returned to the user (to prevent a lock being held
  127191. ** on the database file for longer than necessary). Thus, any virtual table
  127192. ** method (xFilter etc.) that may directly or indirectly call this function
  127193. ** must call sqlite3Fts3SegmentsClose() before returning.
  127194. */
  127195. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  127196. Fts3Table *p, /* FTS3 table handle */
  127197. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  127198. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  127199. int *pnBlob, /* OUT: Size of blob data */
  127200. int *pnLoad /* OUT: Bytes actually loaded */
  127201. ){
  127202. int rc; /* Return code */
  127203. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  127204. assert( pnBlob );
  127205. if( p->pSegments ){
  127206. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  127207. }else{
  127208. if( 0==p->zSegmentsTbl ){
  127209. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  127210. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  127211. }
  127212. rc = sqlite3_blob_open(
  127213. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  127214. );
  127215. }
  127216. if( rc==SQLITE_OK ){
  127217. int nByte = sqlite3_blob_bytes(p->pSegments);
  127218. *pnBlob = nByte;
  127219. if( paBlob ){
  127220. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  127221. if( !aByte ){
  127222. rc = SQLITE_NOMEM;
  127223. }else{
  127224. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  127225. nByte = FTS3_NODE_CHUNKSIZE;
  127226. *pnLoad = nByte;
  127227. }
  127228. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  127229. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  127230. if( rc!=SQLITE_OK ){
  127231. sqlite3_free(aByte);
  127232. aByte = 0;
  127233. }
  127234. }
  127235. *paBlob = aByte;
  127236. }
  127237. }
  127238. return rc;
  127239. }
  127240. /*
  127241. ** Close the blob handle at p->pSegments, if it is open. See comments above
  127242. ** the sqlite3Fts3ReadBlock() function for details.
  127243. */
  127244. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  127245. sqlite3_blob_close(p->pSegments);
  127246. p->pSegments = 0;
  127247. }
  127248. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  127249. int nRead; /* Number of bytes to read */
  127250. int rc; /* Return code */
  127251. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  127252. rc = sqlite3_blob_read(
  127253. pReader->pBlob,
  127254. &pReader->aNode[pReader->nPopulate],
  127255. nRead,
  127256. pReader->nPopulate
  127257. );
  127258. if( rc==SQLITE_OK ){
  127259. pReader->nPopulate += nRead;
  127260. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  127261. if( pReader->nPopulate==pReader->nNode ){
  127262. sqlite3_blob_close(pReader->pBlob);
  127263. pReader->pBlob = 0;
  127264. pReader->nPopulate = 0;
  127265. }
  127266. }
  127267. return rc;
  127268. }
  127269. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  127270. int rc = SQLITE_OK;
  127271. assert( !pReader->pBlob
  127272. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  127273. );
  127274. while( pReader->pBlob && rc==SQLITE_OK
  127275. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  127276. ){
  127277. rc = fts3SegReaderIncrRead(pReader);
  127278. }
  127279. return rc;
  127280. }
  127281. /*
  127282. ** Set an Fts3SegReader cursor to point at EOF.
  127283. */
  127284. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  127285. if( !fts3SegReaderIsRootOnly(pSeg) ){
  127286. sqlite3_free(pSeg->aNode);
  127287. sqlite3_blob_close(pSeg->pBlob);
  127288. pSeg->pBlob = 0;
  127289. }
  127290. pSeg->aNode = 0;
  127291. }
  127292. /*
  127293. ** Move the iterator passed as the first argument to the next term in the
  127294. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  127295. ** SQLITE_DONE. Otherwise, an SQLite error code.
  127296. */
  127297. static int fts3SegReaderNext(
  127298. Fts3Table *p,
  127299. Fts3SegReader *pReader,
  127300. int bIncr
  127301. ){
  127302. int rc; /* Return code of various sub-routines */
  127303. char *pNext; /* Cursor variable */
  127304. int nPrefix; /* Number of bytes in term prefix */
  127305. int nSuffix; /* Number of bytes in term suffix */
  127306. if( !pReader->aDoclist ){
  127307. pNext = pReader->aNode;
  127308. }else{
  127309. pNext = &pReader->aDoclist[pReader->nDoclist];
  127310. }
  127311. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  127312. if( fts3SegReaderIsPending(pReader) ){
  127313. Fts3HashElem *pElem = *(pReader->ppNextElem);
  127314. if( pElem==0 ){
  127315. pReader->aNode = 0;
  127316. }else{
  127317. PendingList *pList = (PendingList *)fts3HashData(pElem);
  127318. pReader->zTerm = (char *)fts3HashKey(pElem);
  127319. pReader->nTerm = fts3HashKeysize(pElem);
  127320. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  127321. pReader->aNode = pReader->aDoclist = pList->aData;
  127322. pReader->ppNextElem++;
  127323. assert( pReader->aNode );
  127324. }
  127325. return SQLITE_OK;
  127326. }
  127327. fts3SegReaderSetEof(pReader);
  127328. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  127329. ** blocks have already been traversed. */
  127330. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  127331. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  127332. return SQLITE_OK;
  127333. }
  127334. rc = sqlite3Fts3ReadBlock(
  127335. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  127336. (bIncr ? &pReader->nPopulate : 0)
  127337. );
  127338. if( rc!=SQLITE_OK ) return rc;
  127339. assert( pReader->pBlob==0 );
  127340. if( bIncr && pReader->nPopulate<pReader->nNode ){
  127341. pReader->pBlob = p->pSegments;
  127342. p->pSegments = 0;
  127343. }
  127344. pNext = pReader->aNode;
  127345. }
  127346. assert( !fts3SegReaderIsPending(pReader) );
  127347. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  127348. if( rc!=SQLITE_OK ) return rc;
  127349. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  127350. ** safe (no risk of overread) even if the node data is corrupted. */
  127351. pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
  127352. pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
  127353. if( nPrefix<0 || nSuffix<=0
  127354. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  127355. ){
  127356. return FTS_CORRUPT_VTAB;
  127357. }
  127358. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  127359. int nNew = (nPrefix+nSuffix)*2;
  127360. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  127361. if( !zNew ){
  127362. return SQLITE_NOMEM;
  127363. }
  127364. pReader->zTerm = zNew;
  127365. pReader->nTermAlloc = nNew;
  127366. }
  127367. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  127368. if( rc!=SQLITE_OK ) return rc;
  127369. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  127370. pReader->nTerm = nPrefix+nSuffix;
  127371. pNext += nSuffix;
  127372. pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
  127373. pReader->aDoclist = pNext;
  127374. pReader->pOffsetList = 0;
  127375. /* Check that the doclist does not appear to extend past the end of the
  127376. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  127377. ** of these statements is untrue, then the data structure is corrupt.
  127378. */
  127379. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  127380. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  127381. ){
  127382. return FTS_CORRUPT_VTAB;
  127383. }
  127384. return SQLITE_OK;
  127385. }
  127386. /*
  127387. ** Set the SegReader to point to the first docid in the doclist associated
  127388. ** with the current term.
  127389. */
  127390. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  127391. int rc = SQLITE_OK;
  127392. assert( pReader->aDoclist );
  127393. assert( !pReader->pOffsetList );
  127394. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  127395. u8 bEof = 0;
  127396. pReader->iDocid = 0;
  127397. pReader->nOffsetList = 0;
  127398. sqlite3Fts3DoclistPrev(0,
  127399. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  127400. &pReader->iDocid, &pReader->nOffsetList, &bEof
  127401. );
  127402. }else{
  127403. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  127404. if( rc==SQLITE_OK ){
  127405. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  127406. pReader->pOffsetList = &pReader->aDoclist[n];
  127407. }
  127408. }
  127409. return rc;
  127410. }
  127411. /*
  127412. ** Advance the SegReader to point to the next docid in the doclist
  127413. ** associated with the current term.
  127414. **
  127415. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  127416. ** *ppOffsetList is set to point to the first column-offset list
  127417. ** in the doclist entry (i.e. immediately past the docid varint).
  127418. ** *pnOffsetList is set to the length of the set of column-offset
  127419. ** lists, not including the nul-terminator byte. For example:
  127420. */
  127421. static int fts3SegReaderNextDocid(
  127422. Fts3Table *pTab,
  127423. Fts3SegReader *pReader, /* Reader to advance to next docid */
  127424. char **ppOffsetList, /* OUT: Pointer to current position-list */
  127425. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  127426. ){
  127427. int rc = SQLITE_OK;
  127428. char *p = pReader->pOffsetList;
  127429. char c = 0;
  127430. assert( p );
  127431. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  127432. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  127433. ** Pending-terms doclists are always built up in ascending order, so
  127434. ** we have to iterate through them backwards here. */
  127435. u8 bEof = 0;
  127436. if( ppOffsetList ){
  127437. *ppOffsetList = pReader->pOffsetList;
  127438. *pnOffsetList = pReader->nOffsetList - 1;
  127439. }
  127440. sqlite3Fts3DoclistPrev(0,
  127441. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  127442. &pReader->nOffsetList, &bEof
  127443. );
  127444. if( bEof ){
  127445. pReader->pOffsetList = 0;
  127446. }else{
  127447. pReader->pOffsetList = p;
  127448. }
  127449. }else{
  127450. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  127451. /* Pointer p currently points at the first byte of an offset list. The
  127452. ** following block advances it to point one byte past the end of
  127453. ** the same offset list. */
  127454. while( 1 ){
  127455. /* The following line of code (and the "p++" below the while() loop) is
  127456. ** normally all that is required to move pointer p to the desired
  127457. ** position. The exception is if this node is being loaded from disk
  127458. ** incrementally and pointer "p" now points to the first byte past
  127459. ** the populated part of pReader->aNode[].
  127460. */
  127461. while( *p | c ) c = *p++ & 0x80;
  127462. assert( *p==0 );
  127463. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  127464. rc = fts3SegReaderIncrRead(pReader);
  127465. if( rc!=SQLITE_OK ) return rc;
  127466. }
  127467. p++;
  127468. /* If required, populate the output variables with a pointer to and the
  127469. ** size of the previous offset-list.
  127470. */
  127471. if( ppOffsetList ){
  127472. *ppOffsetList = pReader->pOffsetList;
  127473. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  127474. }
  127475. /* List may have been edited in place by fts3EvalNearTrim() */
  127476. while( p<pEnd && *p==0 ) p++;
  127477. /* If there are no more entries in the doclist, set pOffsetList to
  127478. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  127479. ** Fts3SegReader.pOffsetList to point to the next offset list before
  127480. ** returning.
  127481. */
  127482. if( p>=pEnd ){
  127483. pReader->pOffsetList = 0;
  127484. }else{
  127485. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  127486. if( rc==SQLITE_OK ){
  127487. sqlite3_int64 iDelta;
  127488. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  127489. if( pTab->bDescIdx ){
  127490. pReader->iDocid -= iDelta;
  127491. }else{
  127492. pReader->iDocid += iDelta;
  127493. }
  127494. }
  127495. }
  127496. }
  127497. return SQLITE_OK;
  127498. }
  127499. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  127500. Fts3Cursor *pCsr,
  127501. Fts3MultiSegReader *pMsr,
  127502. int *pnOvfl
  127503. ){
  127504. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  127505. int nOvfl = 0;
  127506. int ii;
  127507. int rc = SQLITE_OK;
  127508. int pgsz = p->nPgsz;
  127509. assert( p->bFts4 );
  127510. assert( pgsz>0 );
  127511. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  127512. Fts3SegReader *pReader = pMsr->apSegment[ii];
  127513. if( !fts3SegReaderIsPending(pReader)
  127514. && !fts3SegReaderIsRootOnly(pReader)
  127515. ){
  127516. sqlite3_int64 jj;
  127517. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  127518. int nBlob;
  127519. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  127520. if( rc!=SQLITE_OK ) break;
  127521. if( (nBlob+35)>pgsz ){
  127522. nOvfl += (nBlob + 34)/pgsz;
  127523. }
  127524. }
  127525. }
  127526. }
  127527. *pnOvfl = nOvfl;
  127528. return rc;
  127529. }
  127530. /*
  127531. ** Free all allocations associated with the iterator passed as the
  127532. ** second argument.
  127533. */
  127534. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  127535. if( pReader && !fts3SegReaderIsPending(pReader) ){
  127536. sqlite3_free(pReader->zTerm);
  127537. if( !fts3SegReaderIsRootOnly(pReader) ){
  127538. sqlite3_free(pReader->aNode);
  127539. sqlite3_blob_close(pReader->pBlob);
  127540. }
  127541. }
  127542. sqlite3_free(pReader);
  127543. }
  127544. /*
  127545. ** Allocate a new SegReader object.
  127546. */
  127547. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  127548. int iAge, /* Segment "age". */
  127549. int bLookup, /* True for a lookup only */
  127550. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  127551. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  127552. sqlite3_int64 iEndBlock, /* Final block of segment */
  127553. const char *zRoot, /* Buffer containing root node */
  127554. int nRoot, /* Size of buffer containing root node */
  127555. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  127556. ){
  127557. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  127558. int nExtra = 0; /* Bytes to allocate segment root node */
  127559. assert( iStartLeaf<=iEndLeaf );
  127560. if( iStartLeaf==0 ){
  127561. nExtra = nRoot + FTS3_NODE_PADDING;
  127562. }
  127563. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  127564. if( !pReader ){
  127565. return SQLITE_NOMEM;
  127566. }
  127567. memset(pReader, 0, sizeof(Fts3SegReader));
  127568. pReader->iIdx = iAge;
  127569. pReader->bLookup = bLookup!=0;
  127570. pReader->iStartBlock = iStartLeaf;
  127571. pReader->iLeafEndBlock = iEndLeaf;
  127572. pReader->iEndBlock = iEndBlock;
  127573. if( nExtra ){
  127574. /* The entire segment is stored in the root node. */
  127575. pReader->aNode = (char *)&pReader[1];
  127576. pReader->rootOnly = 1;
  127577. pReader->nNode = nRoot;
  127578. memcpy(pReader->aNode, zRoot, nRoot);
  127579. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  127580. }else{
  127581. pReader->iCurrentBlock = iStartLeaf-1;
  127582. }
  127583. *ppReader = pReader;
  127584. return SQLITE_OK;
  127585. }
  127586. /*
  127587. ** This is a comparison function used as a qsort() callback when sorting
  127588. ** an array of pending terms by term. This occurs as part of flushing
  127589. ** the contents of the pending-terms hash table to the database.
  127590. */
  127591. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  127592. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  127593. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  127594. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  127595. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  127596. int n = (n1<n2 ? n1 : n2);
  127597. int c = memcmp(z1, z2, n);
  127598. if( c==0 ){
  127599. c = n1 - n2;
  127600. }
  127601. return c;
  127602. }
  127603. /*
  127604. ** This function is used to allocate an Fts3SegReader that iterates through
  127605. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  127606. **
  127607. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  127608. ** through each term in the pending-terms table. Or, if isPrefixIter is
  127609. ** non-zero, it iterates through each term and its prefixes. For example, if
  127610. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  127611. ** "firebird", then the iterator visits the following 'terms' (in the order
  127612. ** shown):
  127613. **
  127614. ** f fi fir fire fireb firebi firebir firebird
  127615. ** m my mys mysq mysql
  127616. ** s sq sql sqli sqlit sqlite
  127617. **
  127618. ** Whereas if isPrefixIter is zero, the terms visited are:
  127619. **
  127620. ** firebird mysql sqlite
  127621. */
  127622. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  127623. Fts3Table *p, /* Virtual table handle */
  127624. int iIndex, /* Index for p->aIndex */
  127625. const char *zTerm, /* Term to search for */
  127626. int nTerm, /* Size of buffer zTerm */
  127627. int bPrefix, /* True for a prefix iterator */
  127628. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  127629. ){
  127630. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  127631. Fts3HashElem *pE; /* Iterator variable */
  127632. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  127633. int nElem = 0; /* Size of array at aElem */
  127634. int rc = SQLITE_OK; /* Return Code */
  127635. Fts3Hash *pHash;
  127636. pHash = &p->aIndex[iIndex].hPending;
  127637. if( bPrefix ){
  127638. int nAlloc = 0; /* Size of allocated array at aElem */
  127639. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  127640. char *zKey = (char *)fts3HashKey(pE);
  127641. int nKey = fts3HashKeysize(pE);
  127642. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  127643. if( nElem==nAlloc ){
  127644. Fts3HashElem **aElem2;
  127645. nAlloc += 16;
  127646. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  127647. aElem, nAlloc*sizeof(Fts3HashElem *)
  127648. );
  127649. if( !aElem2 ){
  127650. rc = SQLITE_NOMEM;
  127651. nElem = 0;
  127652. break;
  127653. }
  127654. aElem = aElem2;
  127655. }
  127656. aElem[nElem++] = pE;
  127657. }
  127658. }
  127659. /* If more than one term matches the prefix, sort the Fts3HashElem
  127660. ** objects in term order using qsort(). This uses the same comparison
  127661. ** callback as is used when flushing terms to disk.
  127662. */
  127663. if( nElem>1 ){
  127664. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  127665. }
  127666. }else{
  127667. /* The query is a simple term lookup that matches at most one term in
  127668. ** the index. All that is required is a straight hash-lookup.
  127669. **
  127670. ** Because the stack address of pE may be accessed via the aElem pointer
  127671. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  127672. ** within this entire function, not just this "else{...}" block.
  127673. */
  127674. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  127675. if( pE ){
  127676. aElem = &pE;
  127677. nElem = 1;
  127678. }
  127679. }
  127680. if( nElem>0 ){
  127681. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  127682. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  127683. if( !pReader ){
  127684. rc = SQLITE_NOMEM;
  127685. }else{
  127686. memset(pReader, 0, nByte);
  127687. pReader->iIdx = 0x7FFFFFFF;
  127688. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  127689. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  127690. }
  127691. }
  127692. if( bPrefix ){
  127693. sqlite3_free(aElem);
  127694. }
  127695. *ppReader = pReader;
  127696. return rc;
  127697. }
  127698. /*
  127699. ** Compare the entries pointed to by two Fts3SegReader structures.
  127700. ** Comparison is as follows:
  127701. **
  127702. ** 1) EOF is greater than not EOF.
  127703. **
  127704. ** 2) The current terms (if any) are compared using memcmp(). If one
  127705. ** term is a prefix of another, the longer term is considered the
  127706. ** larger.
  127707. **
  127708. ** 3) By segment age. An older segment is considered larger.
  127709. */
  127710. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127711. int rc;
  127712. if( pLhs->aNode && pRhs->aNode ){
  127713. int rc2 = pLhs->nTerm - pRhs->nTerm;
  127714. if( rc2<0 ){
  127715. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  127716. }else{
  127717. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  127718. }
  127719. if( rc==0 ){
  127720. rc = rc2;
  127721. }
  127722. }else{
  127723. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  127724. }
  127725. if( rc==0 ){
  127726. rc = pRhs->iIdx - pLhs->iIdx;
  127727. }
  127728. assert( rc!=0 );
  127729. return rc;
  127730. }
  127731. /*
  127732. ** A different comparison function for SegReader structures. In this
  127733. ** version, it is assumed that each SegReader points to an entry in
  127734. ** a doclist for identical terms. Comparison is made as follows:
  127735. **
  127736. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  127737. **
  127738. ** 2) By current docid.
  127739. **
  127740. ** 3) By segment age. An older segment is considered larger.
  127741. */
  127742. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127743. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  127744. if( rc==0 ){
  127745. if( pLhs->iDocid==pRhs->iDocid ){
  127746. rc = pRhs->iIdx - pLhs->iIdx;
  127747. }else{
  127748. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  127749. }
  127750. }
  127751. assert( pLhs->aNode && pRhs->aNode );
  127752. return rc;
  127753. }
  127754. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  127755. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  127756. if( rc==0 ){
  127757. if( pLhs->iDocid==pRhs->iDocid ){
  127758. rc = pRhs->iIdx - pLhs->iIdx;
  127759. }else{
  127760. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  127761. }
  127762. }
  127763. assert( pLhs->aNode && pRhs->aNode );
  127764. return rc;
  127765. }
  127766. /*
  127767. ** Compare the term that the Fts3SegReader object passed as the first argument
  127768. ** points to with the term specified by arguments zTerm and nTerm.
  127769. **
  127770. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  127771. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  127772. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  127773. */
  127774. static int fts3SegReaderTermCmp(
  127775. Fts3SegReader *pSeg, /* Segment reader object */
  127776. const char *zTerm, /* Term to compare to */
  127777. int nTerm /* Size of term zTerm in bytes */
  127778. ){
  127779. int res = 0;
  127780. if( pSeg->aNode ){
  127781. if( pSeg->nTerm>nTerm ){
  127782. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  127783. }else{
  127784. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  127785. }
  127786. if( res==0 ){
  127787. res = pSeg->nTerm-nTerm;
  127788. }
  127789. }
  127790. return res;
  127791. }
  127792. /*
  127793. ** Argument apSegment is an array of nSegment elements. It is known that
  127794. ** the final (nSegment-nSuspect) members are already in sorted order
  127795. ** (according to the comparison function provided). This function shuffles
  127796. ** the array around until all entries are in sorted order.
  127797. */
  127798. static void fts3SegReaderSort(
  127799. Fts3SegReader **apSegment, /* Array to sort entries of */
  127800. int nSegment, /* Size of apSegment array */
  127801. int nSuspect, /* Unsorted entry count */
  127802. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  127803. ){
  127804. int i; /* Iterator variable */
  127805. assert( nSuspect<=nSegment );
  127806. if( nSuspect==nSegment ) nSuspect--;
  127807. for(i=nSuspect-1; i>=0; i--){
  127808. int j;
  127809. for(j=i; j<(nSegment-1); j++){
  127810. Fts3SegReader *pTmp;
  127811. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  127812. pTmp = apSegment[j+1];
  127813. apSegment[j+1] = apSegment[j];
  127814. apSegment[j] = pTmp;
  127815. }
  127816. }
  127817. #ifndef NDEBUG
  127818. /* Check that the list really is sorted now. */
  127819. for(i=0; i<(nSuspect-1); i++){
  127820. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  127821. }
  127822. #endif
  127823. }
  127824. /*
  127825. ** Insert a record into the %_segments table.
  127826. */
  127827. static int fts3WriteSegment(
  127828. Fts3Table *p, /* Virtual table handle */
  127829. sqlite3_int64 iBlock, /* Block id for new block */
  127830. char *z, /* Pointer to buffer containing block data */
  127831. int n /* Size of buffer z in bytes */
  127832. ){
  127833. sqlite3_stmt *pStmt;
  127834. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  127835. if( rc==SQLITE_OK ){
  127836. sqlite3_bind_int64(pStmt, 1, iBlock);
  127837. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  127838. sqlite3_step(pStmt);
  127839. rc = sqlite3_reset(pStmt);
  127840. }
  127841. return rc;
  127842. }
  127843. /*
  127844. ** Find the largest relative level number in the table. If successful, set
  127845. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  127846. ** set *pnMax to zero and return an SQLite error code.
  127847. */
  127848. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  127849. int rc;
  127850. int mxLevel = 0;
  127851. sqlite3_stmt *pStmt = 0;
  127852. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  127853. if( rc==SQLITE_OK ){
  127854. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  127855. mxLevel = sqlite3_column_int(pStmt, 0);
  127856. }
  127857. rc = sqlite3_reset(pStmt);
  127858. }
  127859. *pnMax = mxLevel;
  127860. return rc;
  127861. }
  127862. /*
  127863. ** Insert a record into the %_segdir table.
  127864. */
  127865. static int fts3WriteSegdir(
  127866. Fts3Table *p, /* Virtual table handle */
  127867. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  127868. int iIdx, /* Value for "idx" field */
  127869. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  127870. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  127871. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  127872. char *zRoot, /* Blob value for "root" field */
  127873. int nRoot /* Number of bytes in buffer zRoot */
  127874. ){
  127875. sqlite3_stmt *pStmt;
  127876. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  127877. if( rc==SQLITE_OK ){
  127878. sqlite3_bind_int64(pStmt, 1, iLevel);
  127879. sqlite3_bind_int(pStmt, 2, iIdx);
  127880. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  127881. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  127882. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  127883. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  127884. sqlite3_step(pStmt);
  127885. rc = sqlite3_reset(pStmt);
  127886. }
  127887. return rc;
  127888. }
  127889. /*
  127890. ** Return the size of the common prefix (if any) shared by zPrev and
  127891. ** zNext, in bytes. For example,
  127892. **
  127893. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  127894. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  127895. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  127896. */
  127897. static int fts3PrefixCompress(
  127898. const char *zPrev, /* Buffer containing previous term */
  127899. int nPrev, /* Size of buffer zPrev in bytes */
  127900. const char *zNext, /* Buffer containing next term */
  127901. int nNext /* Size of buffer zNext in bytes */
  127902. ){
  127903. int n;
  127904. UNUSED_PARAMETER(nNext);
  127905. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  127906. return n;
  127907. }
  127908. /*
  127909. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  127910. ** (according to memcmp) than the previous term.
  127911. */
  127912. static int fts3NodeAddTerm(
  127913. Fts3Table *p, /* Virtual table handle */
  127914. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  127915. int isCopyTerm, /* True if zTerm/nTerm is transient */
  127916. const char *zTerm, /* Pointer to buffer containing term */
  127917. int nTerm /* Size of term in bytes */
  127918. ){
  127919. SegmentNode *pTree = *ppTree;
  127920. int rc;
  127921. SegmentNode *pNew;
  127922. /* First try to append the term to the current node. Return early if
  127923. ** this is possible.
  127924. */
  127925. if( pTree ){
  127926. int nData = pTree->nData; /* Current size of node in bytes */
  127927. int nReq = nData; /* Required space after adding zTerm */
  127928. int nPrefix; /* Number of bytes of prefix compression */
  127929. int nSuffix; /* Suffix length */
  127930. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  127931. nSuffix = nTerm-nPrefix;
  127932. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  127933. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  127934. if( nReq>p->nNodeSize ){
  127935. /* An unusual case: this is the first term to be added to the node
  127936. ** and the static node buffer (p->nNodeSize bytes) is not large
  127937. ** enough. Use a separately malloced buffer instead This wastes
  127938. ** p->nNodeSize bytes, but since this scenario only comes about when
  127939. ** the database contain two terms that share a prefix of almost 2KB,
  127940. ** this is not expected to be a serious problem.
  127941. */
  127942. assert( pTree->aData==(char *)&pTree[1] );
  127943. pTree->aData = (char *)sqlite3_malloc(nReq);
  127944. if( !pTree->aData ){
  127945. return SQLITE_NOMEM;
  127946. }
  127947. }
  127948. if( pTree->zTerm ){
  127949. /* There is no prefix-length field for first term in a node */
  127950. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  127951. }
  127952. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  127953. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  127954. pTree->nData = nData + nSuffix;
  127955. pTree->nEntry++;
  127956. if( isCopyTerm ){
  127957. if( pTree->nMalloc<nTerm ){
  127958. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  127959. if( !zNew ){
  127960. return SQLITE_NOMEM;
  127961. }
  127962. pTree->nMalloc = nTerm*2;
  127963. pTree->zMalloc = zNew;
  127964. }
  127965. pTree->zTerm = pTree->zMalloc;
  127966. memcpy(pTree->zTerm, zTerm, nTerm);
  127967. pTree->nTerm = nTerm;
  127968. }else{
  127969. pTree->zTerm = (char *)zTerm;
  127970. pTree->nTerm = nTerm;
  127971. }
  127972. return SQLITE_OK;
  127973. }
  127974. }
  127975. /* If control flows to here, it was not possible to append zTerm to the
  127976. ** current node. Create a new node (a right-sibling of the current node).
  127977. ** If this is the first node in the tree, the term is added to it.
  127978. **
  127979. ** Otherwise, the term is not added to the new node, it is left empty for
  127980. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  127981. ** has no parent, one is created here.
  127982. */
  127983. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  127984. if( !pNew ){
  127985. return SQLITE_NOMEM;
  127986. }
  127987. memset(pNew, 0, sizeof(SegmentNode));
  127988. pNew->nData = 1 + FTS3_VARINT_MAX;
  127989. pNew->aData = (char *)&pNew[1];
  127990. if( pTree ){
  127991. SegmentNode *pParent = pTree->pParent;
  127992. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  127993. if( pTree->pParent==0 ){
  127994. pTree->pParent = pParent;
  127995. }
  127996. pTree->pRight = pNew;
  127997. pNew->pLeftmost = pTree->pLeftmost;
  127998. pNew->pParent = pParent;
  127999. pNew->zMalloc = pTree->zMalloc;
  128000. pNew->nMalloc = pTree->nMalloc;
  128001. pTree->zMalloc = 0;
  128002. }else{
  128003. pNew->pLeftmost = pNew;
  128004. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  128005. }
  128006. *ppTree = pNew;
  128007. return rc;
  128008. }
  128009. /*
  128010. ** Helper function for fts3NodeWrite().
  128011. */
  128012. static int fts3TreeFinishNode(
  128013. SegmentNode *pTree,
  128014. int iHeight,
  128015. sqlite3_int64 iLeftChild
  128016. ){
  128017. int nStart;
  128018. assert( iHeight>=1 && iHeight<128 );
  128019. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  128020. pTree->aData[nStart] = (char)iHeight;
  128021. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  128022. return nStart;
  128023. }
  128024. /*
  128025. ** Write the buffer for the segment node pTree and all of its peers to the
  128026. ** database. Then call this function recursively to write the parent of
  128027. ** pTree and its peers to the database.
  128028. **
  128029. ** Except, if pTree is a root node, do not write it to the database. Instead,
  128030. ** set output variables *paRoot and *pnRoot to contain the root node.
  128031. **
  128032. ** If successful, SQLITE_OK is returned and output variable *piLast is
  128033. ** set to the largest blockid written to the database (or zero if no
  128034. ** blocks were written to the db). Otherwise, an SQLite error code is
  128035. ** returned.
  128036. */
  128037. static int fts3NodeWrite(
  128038. Fts3Table *p, /* Virtual table handle */
  128039. SegmentNode *pTree, /* SegmentNode handle */
  128040. int iHeight, /* Height of this node in tree */
  128041. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  128042. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  128043. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  128044. char **paRoot, /* OUT: Data for root node */
  128045. int *pnRoot /* OUT: Size of root node in bytes */
  128046. ){
  128047. int rc = SQLITE_OK;
  128048. if( !pTree->pParent ){
  128049. /* Root node of the tree. */
  128050. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  128051. *piLast = iFree-1;
  128052. *pnRoot = pTree->nData - nStart;
  128053. *paRoot = &pTree->aData[nStart];
  128054. }else{
  128055. SegmentNode *pIter;
  128056. sqlite3_int64 iNextFree = iFree;
  128057. sqlite3_int64 iNextLeaf = iLeaf;
  128058. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  128059. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  128060. int nWrite = pIter->nData - nStart;
  128061. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  128062. iNextFree++;
  128063. iNextLeaf += (pIter->nEntry+1);
  128064. }
  128065. if( rc==SQLITE_OK ){
  128066. assert( iNextLeaf==iFree );
  128067. rc = fts3NodeWrite(
  128068. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  128069. );
  128070. }
  128071. }
  128072. return rc;
  128073. }
  128074. /*
  128075. ** Free all memory allocations associated with the tree pTree.
  128076. */
  128077. static void fts3NodeFree(SegmentNode *pTree){
  128078. if( pTree ){
  128079. SegmentNode *p = pTree->pLeftmost;
  128080. fts3NodeFree(p->pParent);
  128081. while( p ){
  128082. SegmentNode *pRight = p->pRight;
  128083. if( p->aData!=(char *)&p[1] ){
  128084. sqlite3_free(p->aData);
  128085. }
  128086. assert( pRight==0 || p->zMalloc==0 );
  128087. sqlite3_free(p->zMalloc);
  128088. sqlite3_free(p);
  128089. p = pRight;
  128090. }
  128091. }
  128092. }
  128093. /*
  128094. ** Add a term to the segment being constructed by the SegmentWriter object
  128095. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  128096. ** be passed NULL. This function will allocate a new SegmentWriter object
  128097. ** and return it via the input/output variable *ppWriter in this case.
  128098. **
  128099. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  128100. */
  128101. static int fts3SegWriterAdd(
  128102. Fts3Table *p, /* Virtual table handle */
  128103. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  128104. int isCopyTerm, /* True if buffer zTerm must be copied */
  128105. const char *zTerm, /* Pointer to buffer containing term */
  128106. int nTerm, /* Size of term in bytes */
  128107. const char *aDoclist, /* Pointer to buffer containing doclist */
  128108. int nDoclist /* Size of doclist in bytes */
  128109. ){
  128110. int nPrefix; /* Size of term prefix in bytes */
  128111. int nSuffix; /* Size of term suffix in bytes */
  128112. int nReq; /* Number of bytes required on leaf page */
  128113. int nData;
  128114. SegmentWriter *pWriter = *ppWriter;
  128115. if( !pWriter ){
  128116. int rc;
  128117. sqlite3_stmt *pStmt;
  128118. /* Allocate the SegmentWriter structure */
  128119. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  128120. if( !pWriter ) return SQLITE_NOMEM;
  128121. memset(pWriter, 0, sizeof(SegmentWriter));
  128122. *ppWriter = pWriter;
  128123. /* Allocate a buffer in which to accumulate data */
  128124. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  128125. if( !pWriter->aData ) return SQLITE_NOMEM;
  128126. pWriter->nSize = p->nNodeSize;
  128127. /* Find the next free blockid in the %_segments table */
  128128. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  128129. if( rc!=SQLITE_OK ) return rc;
  128130. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128131. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  128132. pWriter->iFirst = pWriter->iFree;
  128133. }
  128134. rc = sqlite3_reset(pStmt);
  128135. if( rc!=SQLITE_OK ) return rc;
  128136. }
  128137. nData = pWriter->nData;
  128138. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  128139. nSuffix = nTerm-nPrefix;
  128140. /* Figure out how many bytes are required by this new entry */
  128141. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  128142. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  128143. nSuffix + /* Term suffix */
  128144. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  128145. nDoclist; /* Doclist data */
  128146. if( nData>0 && nData+nReq>p->nNodeSize ){
  128147. int rc;
  128148. /* The current leaf node is full. Write it out to the database. */
  128149. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  128150. if( rc!=SQLITE_OK ) return rc;
  128151. p->nLeafAdd++;
  128152. /* Add the current term to the interior node tree. The term added to
  128153. ** the interior tree must:
  128154. **
  128155. ** a) be greater than the largest term on the leaf node just written
  128156. ** to the database (still available in pWriter->zTerm), and
  128157. **
  128158. ** b) be less than or equal to the term about to be added to the new
  128159. ** leaf node (zTerm/nTerm).
  128160. **
  128161. ** In other words, it must be the prefix of zTerm 1 byte longer than
  128162. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  128163. */
  128164. assert( nPrefix<nTerm );
  128165. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  128166. if( rc!=SQLITE_OK ) return rc;
  128167. nData = 0;
  128168. pWriter->nTerm = 0;
  128169. nPrefix = 0;
  128170. nSuffix = nTerm;
  128171. nReq = 1 + /* varint containing prefix size */
  128172. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  128173. nTerm + /* Term suffix */
  128174. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  128175. nDoclist; /* Doclist data */
  128176. }
  128177. /* If the buffer currently allocated is too small for this entry, realloc
  128178. ** the buffer to make it large enough.
  128179. */
  128180. if( nReq>pWriter->nSize ){
  128181. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  128182. if( !aNew ) return SQLITE_NOMEM;
  128183. pWriter->aData = aNew;
  128184. pWriter->nSize = nReq;
  128185. }
  128186. assert( nData+nReq<=pWriter->nSize );
  128187. /* Append the prefix-compressed term and doclist to the buffer. */
  128188. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  128189. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  128190. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  128191. nData += nSuffix;
  128192. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  128193. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  128194. pWriter->nData = nData + nDoclist;
  128195. /* Save the current term so that it can be used to prefix-compress the next.
  128196. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  128197. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  128198. ** store a copy of the pointer.
  128199. */
  128200. if( isCopyTerm ){
  128201. if( nTerm>pWriter->nMalloc ){
  128202. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  128203. if( !zNew ){
  128204. return SQLITE_NOMEM;
  128205. }
  128206. pWriter->nMalloc = nTerm*2;
  128207. pWriter->zMalloc = zNew;
  128208. pWriter->zTerm = zNew;
  128209. }
  128210. assert( pWriter->zTerm==pWriter->zMalloc );
  128211. memcpy(pWriter->zTerm, zTerm, nTerm);
  128212. }else{
  128213. pWriter->zTerm = (char *)zTerm;
  128214. }
  128215. pWriter->nTerm = nTerm;
  128216. return SQLITE_OK;
  128217. }
  128218. /*
  128219. ** Flush all data associated with the SegmentWriter object pWriter to the
  128220. ** database. This function must be called after all terms have been added
  128221. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  128222. ** returned. Otherwise, an SQLite error code.
  128223. */
  128224. static int fts3SegWriterFlush(
  128225. Fts3Table *p, /* Virtual table handle */
  128226. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  128227. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  128228. int iIdx /* Value for 'idx' column of %_segdir */
  128229. ){
  128230. int rc; /* Return code */
  128231. if( pWriter->pTree ){
  128232. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  128233. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  128234. char *zRoot = NULL; /* Pointer to buffer containing root node */
  128235. int nRoot = 0; /* Size of buffer zRoot */
  128236. iLastLeaf = pWriter->iFree;
  128237. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  128238. if( rc==SQLITE_OK ){
  128239. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  128240. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  128241. }
  128242. if( rc==SQLITE_OK ){
  128243. rc = fts3WriteSegdir(
  128244. p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
  128245. }
  128246. }else{
  128247. /* The entire tree fits on the root node. Write it to the segdir table. */
  128248. rc = fts3WriteSegdir(
  128249. p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
  128250. }
  128251. p->nLeafAdd++;
  128252. return rc;
  128253. }
  128254. /*
  128255. ** Release all memory held by the SegmentWriter object passed as the
  128256. ** first argument.
  128257. */
  128258. static void fts3SegWriterFree(SegmentWriter *pWriter){
  128259. if( pWriter ){
  128260. sqlite3_free(pWriter->aData);
  128261. sqlite3_free(pWriter->zMalloc);
  128262. fts3NodeFree(pWriter->pTree);
  128263. sqlite3_free(pWriter);
  128264. }
  128265. }
  128266. /*
  128267. ** The first value in the apVal[] array is assumed to contain an integer.
  128268. ** This function tests if there exist any documents with docid values that
  128269. ** are different from that integer. i.e. if deleting the document with docid
  128270. ** pRowid would mean the FTS3 table were empty.
  128271. **
  128272. ** If successful, *pisEmpty is set to true if the table is empty except for
  128273. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  128274. ** error occurs, an SQLite error code is returned.
  128275. */
  128276. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  128277. sqlite3_stmt *pStmt;
  128278. int rc;
  128279. if( p->zContentTbl ){
  128280. /* If using the content=xxx option, assume the table is never empty */
  128281. *pisEmpty = 0;
  128282. rc = SQLITE_OK;
  128283. }else{
  128284. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  128285. if( rc==SQLITE_OK ){
  128286. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128287. *pisEmpty = sqlite3_column_int(pStmt, 0);
  128288. }
  128289. rc = sqlite3_reset(pStmt);
  128290. }
  128291. }
  128292. return rc;
  128293. }
  128294. /*
  128295. ** Set *pnMax to the largest segment level in the database for the index
  128296. ** iIndex.
  128297. **
  128298. ** Segment levels are stored in the 'level' column of the %_segdir table.
  128299. **
  128300. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  128301. */
  128302. static int fts3SegmentMaxLevel(
  128303. Fts3Table *p,
  128304. int iLangid,
  128305. int iIndex,
  128306. sqlite3_int64 *pnMax
  128307. ){
  128308. sqlite3_stmt *pStmt;
  128309. int rc;
  128310. assert( iIndex>=0 && iIndex<p->nIndex );
  128311. /* Set pStmt to the compiled version of:
  128312. **
  128313. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  128314. **
  128315. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  128316. */
  128317. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  128318. if( rc!=SQLITE_OK ) return rc;
  128319. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  128320. sqlite3_bind_int64(pStmt, 2,
  128321. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  128322. );
  128323. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128324. *pnMax = sqlite3_column_int64(pStmt, 0);
  128325. }
  128326. return sqlite3_reset(pStmt);
  128327. }
  128328. /*
  128329. ** Delete all entries in the %_segments table associated with the segment
  128330. ** opened with seg-reader pSeg. This function does not affect the contents
  128331. ** of the %_segdir table.
  128332. */
  128333. static int fts3DeleteSegment(
  128334. Fts3Table *p, /* FTS table handle */
  128335. Fts3SegReader *pSeg /* Segment to delete */
  128336. ){
  128337. int rc = SQLITE_OK; /* Return code */
  128338. if( pSeg->iStartBlock ){
  128339. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  128340. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  128341. if( rc==SQLITE_OK ){
  128342. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  128343. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  128344. sqlite3_step(pDelete);
  128345. rc = sqlite3_reset(pDelete);
  128346. }
  128347. }
  128348. return rc;
  128349. }
  128350. /*
  128351. ** This function is used after merging multiple segments into a single large
  128352. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  128353. ** it:
  128354. **
  128355. ** 1) Deletes all %_segments entries for the segments associated with
  128356. ** each of the SegReader objects in the array passed as the third
  128357. ** argument, and
  128358. **
  128359. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  128360. ** entries regardless of level if (iLevel<0).
  128361. **
  128362. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  128363. */
  128364. static int fts3DeleteSegdir(
  128365. Fts3Table *p, /* Virtual table handle */
  128366. int iLangid, /* Language id */
  128367. int iIndex, /* Index for p->aIndex */
  128368. int iLevel, /* Level of %_segdir entries to delete */
  128369. Fts3SegReader **apSegment, /* Array of SegReader objects */
  128370. int nReader /* Size of array apSegment */
  128371. ){
  128372. int rc = SQLITE_OK; /* Return Code */
  128373. int i; /* Iterator variable */
  128374. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  128375. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  128376. rc = fts3DeleteSegment(p, apSegment[i]);
  128377. }
  128378. if( rc!=SQLITE_OK ){
  128379. return rc;
  128380. }
  128381. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  128382. if( iLevel==FTS3_SEGCURSOR_ALL ){
  128383. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  128384. if( rc==SQLITE_OK ){
  128385. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  128386. sqlite3_bind_int64(pDelete, 2,
  128387. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  128388. );
  128389. }
  128390. }else{
  128391. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  128392. if( rc==SQLITE_OK ){
  128393. sqlite3_bind_int64(
  128394. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  128395. );
  128396. }
  128397. }
  128398. if( rc==SQLITE_OK ){
  128399. sqlite3_step(pDelete);
  128400. rc = sqlite3_reset(pDelete);
  128401. }
  128402. return rc;
  128403. }
  128404. /*
  128405. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  128406. ** a position list that may (or may not) feature multiple columns. This
  128407. ** function adjusts the pointer *ppList and the length *pnList so that they
  128408. ** identify the subset of the position list that corresponds to column iCol.
  128409. **
  128410. ** If there are no entries in the input position list for column iCol, then
  128411. ** *pnList is set to zero before returning.
  128412. **
  128413. ** If parameter bZero is non-zero, then any part of the input list following
  128414. ** the end of the output list is zeroed before returning.
  128415. */
  128416. static void fts3ColumnFilter(
  128417. int iCol, /* Column to filter on */
  128418. int bZero, /* Zero out anything following *ppList */
  128419. char **ppList, /* IN/OUT: Pointer to position list */
  128420. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  128421. ){
  128422. char *pList = *ppList;
  128423. int nList = *pnList;
  128424. char *pEnd = &pList[nList];
  128425. int iCurrent = 0;
  128426. char *p = pList;
  128427. assert( iCol>=0 );
  128428. while( 1 ){
  128429. char c = 0;
  128430. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  128431. if( iCol==iCurrent ){
  128432. nList = (int)(p - pList);
  128433. break;
  128434. }
  128435. nList -= (int)(p - pList);
  128436. pList = p;
  128437. if( nList==0 ){
  128438. break;
  128439. }
  128440. p = &pList[1];
  128441. p += sqlite3Fts3GetVarint32(p, &iCurrent);
  128442. }
  128443. if( bZero && &pList[nList]!=pEnd ){
  128444. memset(&pList[nList], 0, pEnd - &pList[nList]);
  128445. }
  128446. *ppList = pList;
  128447. *pnList = nList;
  128448. }
  128449. /*
  128450. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  128451. ** existing data). Grow the buffer if required.
  128452. **
  128453. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  128454. ** trying to resize the buffer, return SQLITE_NOMEM.
  128455. */
  128456. static int fts3MsrBufferData(
  128457. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  128458. char *pList,
  128459. int nList
  128460. ){
  128461. if( nList>pMsr->nBuffer ){
  128462. char *pNew;
  128463. pMsr->nBuffer = nList*2;
  128464. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  128465. if( !pNew ) return SQLITE_NOMEM;
  128466. pMsr->aBuffer = pNew;
  128467. }
  128468. memcpy(pMsr->aBuffer, pList, nList);
  128469. return SQLITE_OK;
  128470. }
  128471. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  128472. Fts3Table *p, /* Virtual table handle */
  128473. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  128474. sqlite3_int64 *piDocid, /* OUT: Docid value */
  128475. char **paPoslist, /* OUT: Pointer to position list */
  128476. int *pnPoslist /* OUT: Size of position list in bytes */
  128477. ){
  128478. int nMerge = pMsr->nAdvance;
  128479. Fts3SegReader **apSegment = pMsr->apSegment;
  128480. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128481. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128482. );
  128483. if( nMerge==0 ){
  128484. *paPoslist = 0;
  128485. return SQLITE_OK;
  128486. }
  128487. while( 1 ){
  128488. Fts3SegReader *pSeg;
  128489. pSeg = pMsr->apSegment[0];
  128490. if( pSeg->pOffsetList==0 ){
  128491. *paPoslist = 0;
  128492. break;
  128493. }else{
  128494. int rc;
  128495. char *pList;
  128496. int nList;
  128497. int j;
  128498. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  128499. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  128500. j = 1;
  128501. while( rc==SQLITE_OK
  128502. && j<nMerge
  128503. && apSegment[j]->pOffsetList
  128504. && apSegment[j]->iDocid==iDocid
  128505. ){
  128506. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  128507. j++;
  128508. }
  128509. if( rc!=SQLITE_OK ) return rc;
  128510. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  128511. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  128512. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  128513. if( rc!=SQLITE_OK ) return rc;
  128514. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  128515. pList = pMsr->aBuffer;
  128516. }
  128517. if( pMsr->iColFilter>=0 ){
  128518. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  128519. }
  128520. if( nList>0 ){
  128521. *paPoslist = pList;
  128522. *piDocid = iDocid;
  128523. *pnPoslist = nList;
  128524. break;
  128525. }
  128526. }
  128527. }
  128528. return SQLITE_OK;
  128529. }
  128530. static int fts3SegReaderStart(
  128531. Fts3Table *p, /* Virtual table handle */
  128532. Fts3MultiSegReader *pCsr, /* Cursor object */
  128533. const char *zTerm, /* Term searched for (or NULL) */
  128534. int nTerm /* Length of zTerm in bytes */
  128535. ){
  128536. int i;
  128537. int nSeg = pCsr->nSegment;
  128538. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  128539. ** for, then advance each segment iterator until it points to a term of
  128540. ** equal or greater value than the specified term. This prevents many
  128541. ** unnecessary merge/sort operations for the case where single segment
  128542. ** b-tree leaf nodes contain more than one term.
  128543. */
  128544. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  128545. int res = 0;
  128546. Fts3SegReader *pSeg = pCsr->apSegment[i];
  128547. do {
  128548. int rc = fts3SegReaderNext(p, pSeg, 0);
  128549. if( rc!=SQLITE_OK ) return rc;
  128550. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  128551. if( pSeg->bLookup && res!=0 ){
  128552. fts3SegReaderSetEof(pSeg);
  128553. }
  128554. }
  128555. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  128556. return SQLITE_OK;
  128557. }
  128558. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  128559. Fts3Table *p, /* Virtual table handle */
  128560. Fts3MultiSegReader *pCsr, /* Cursor object */
  128561. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  128562. ){
  128563. pCsr->pFilter = pFilter;
  128564. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  128565. }
  128566. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  128567. Fts3Table *p, /* Virtual table handle */
  128568. Fts3MultiSegReader *pCsr, /* Cursor object */
  128569. int iCol, /* Column to match on. */
  128570. const char *zTerm, /* Term to iterate through a doclist for */
  128571. int nTerm /* Number of bytes in zTerm */
  128572. ){
  128573. int i;
  128574. int rc;
  128575. int nSegment = pCsr->nSegment;
  128576. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128577. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128578. );
  128579. assert( pCsr->pFilter==0 );
  128580. assert( zTerm && nTerm>0 );
  128581. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  128582. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  128583. if( rc!=SQLITE_OK ) return rc;
  128584. /* Determine how many of the segments actually point to zTerm/nTerm. */
  128585. for(i=0; i<nSegment; i++){
  128586. Fts3SegReader *pSeg = pCsr->apSegment[i];
  128587. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  128588. break;
  128589. }
  128590. }
  128591. pCsr->nAdvance = i;
  128592. /* Advance each of the segments to point to the first docid. */
  128593. for(i=0; i<pCsr->nAdvance; i++){
  128594. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  128595. if( rc!=SQLITE_OK ) return rc;
  128596. }
  128597. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  128598. assert( iCol<0 || iCol<p->nColumn );
  128599. pCsr->iColFilter = iCol;
  128600. return SQLITE_OK;
  128601. }
  128602. /*
  128603. ** This function is called on a MultiSegReader that has been started using
  128604. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  128605. ** have been made. Calling this function puts the MultiSegReader in such
  128606. ** a state that if the next two calls are:
  128607. **
  128608. ** sqlite3Fts3SegReaderStart()
  128609. ** sqlite3Fts3SegReaderStep()
  128610. **
  128611. ** then the entire doclist for the term is available in
  128612. ** MultiSegReader.aDoclist/nDoclist.
  128613. */
  128614. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  128615. int i; /* Used to iterate through segment-readers */
  128616. assert( pCsr->zTerm==0 );
  128617. assert( pCsr->nTerm==0 );
  128618. assert( pCsr->aDoclist==0 );
  128619. assert( pCsr->nDoclist==0 );
  128620. pCsr->nAdvance = 0;
  128621. pCsr->bRestart = 1;
  128622. for(i=0; i<pCsr->nSegment; i++){
  128623. pCsr->apSegment[i]->pOffsetList = 0;
  128624. pCsr->apSegment[i]->nOffsetList = 0;
  128625. pCsr->apSegment[i]->iDocid = 0;
  128626. }
  128627. return SQLITE_OK;
  128628. }
  128629. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  128630. Fts3Table *p, /* Virtual table handle */
  128631. Fts3MultiSegReader *pCsr /* Cursor object */
  128632. ){
  128633. int rc = SQLITE_OK;
  128634. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  128635. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  128636. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  128637. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  128638. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  128639. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  128640. Fts3SegReader **apSegment = pCsr->apSegment;
  128641. int nSegment = pCsr->nSegment;
  128642. Fts3SegFilter *pFilter = pCsr->pFilter;
  128643. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  128644. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  128645. );
  128646. if( pCsr->nSegment==0 ) return SQLITE_OK;
  128647. do {
  128648. int nMerge;
  128649. int i;
  128650. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  128651. ** forward. Then sort the list in order of current term again.
  128652. */
  128653. for(i=0; i<pCsr->nAdvance; i++){
  128654. Fts3SegReader *pSeg = apSegment[i];
  128655. if( pSeg->bLookup ){
  128656. fts3SegReaderSetEof(pSeg);
  128657. }else{
  128658. rc = fts3SegReaderNext(p, pSeg, 0);
  128659. }
  128660. if( rc!=SQLITE_OK ) return rc;
  128661. }
  128662. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  128663. pCsr->nAdvance = 0;
  128664. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  128665. assert( rc==SQLITE_OK );
  128666. if( apSegment[0]->aNode==0 ) break;
  128667. pCsr->nTerm = apSegment[0]->nTerm;
  128668. pCsr->zTerm = apSegment[0]->zTerm;
  128669. /* If this is a prefix-search, and if the term that apSegment[0] points
  128670. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  128671. ** required callbacks have been made. In this case exit early.
  128672. **
  128673. ** Similarly, if this is a search for an exact match, and the first term
  128674. ** of segment apSegment[0] is not a match, exit early.
  128675. */
  128676. if( pFilter->zTerm && !isScan ){
  128677. if( pCsr->nTerm<pFilter->nTerm
  128678. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  128679. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  128680. ){
  128681. break;
  128682. }
  128683. }
  128684. nMerge = 1;
  128685. while( nMerge<nSegment
  128686. && apSegment[nMerge]->aNode
  128687. && apSegment[nMerge]->nTerm==pCsr->nTerm
  128688. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  128689. ){
  128690. nMerge++;
  128691. }
  128692. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  128693. if( nMerge==1
  128694. && !isIgnoreEmpty
  128695. && !isFirst
  128696. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  128697. ){
  128698. pCsr->nDoclist = apSegment[0]->nDoclist;
  128699. if( fts3SegReaderIsPending(apSegment[0]) ){
  128700. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  128701. pCsr->aDoclist = pCsr->aBuffer;
  128702. }else{
  128703. pCsr->aDoclist = apSegment[0]->aDoclist;
  128704. }
  128705. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  128706. }else{
  128707. int nDoclist = 0; /* Size of doclist */
  128708. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  128709. /* The current term of the first nMerge entries in the array
  128710. ** of Fts3SegReader objects is the same. The doclists must be merged
  128711. ** and a single term returned with the merged doclist.
  128712. */
  128713. for(i=0; i<nMerge; i++){
  128714. fts3SegReaderFirstDocid(p, apSegment[i]);
  128715. }
  128716. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  128717. while( apSegment[0]->pOffsetList ){
  128718. int j; /* Number of segments that share a docid */
  128719. char *pList = 0;
  128720. int nList = 0;
  128721. int nByte;
  128722. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  128723. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  128724. j = 1;
  128725. while( j<nMerge
  128726. && apSegment[j]->pOffsetList
  128727. && apSegment[j]->iDocid==iDocid
  128728. ){
  128729. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  128730. j++;
  128731. }
  128732. if( isColFilter ){
  128733. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  128734. }
  128735. if( !isIgnoreEmpty || nList>0 ){
  128736. /* Calculate the 'docid' delta value to write into the merged
  128737. ** doclist. */
  128738. sqlite3_int64 iDelta;
  128739. if( p->bDescIdx && nDoclist>0 ){
  128740. iDelta = iPrev - iDocid;
  128741. }else{
  128742. iDelta = iDocid - iPrev;
  128743. }
  128744. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  128745. assert( nDoclist>0 || iDelta==iDocid );
  128746. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  128747. if( nDoclist+nByte>pCsr->nBuffer ){
  128748. char *aNew;
  128749. pCsr->nBuffer = (nDoclist+nByte)*2;
  128750. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  128751. if( !aNew ){
  128752. return SQLITE_NOMEM;
  128753. }
  128754. pCsr->aBuffer = aNew;
  128755. }
  128756. if( isFirst ){
  128757. char *a = &pCsr->aBuffer[nDoclist];
  128758. int nWrite;
  128759. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  128760. if( nWrite ){
  128761. iPrev = iDocid;
  128762. nDoclist += nWrite;
  128763. }
  128764. }else{
  128765. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  128766. iPrev = iDocid;
  128767. if( isRequirePos ){
  128768. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  128769. nDoclist += nList;
  128770. pCsr->aBuffer[nDoclist++] = '\0';
  128771. }
  128772. }
  128773. }
  128774. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  128775. }
  128776. if( nDoclist>0 ){
  128777. pCsr->aDoclist = pCsr->aBuffer;
  128778. pCsr->nDoclist = nDoclist;
  128779. rc = SQLITE_ROW;
  128780. }
  128781. }
  128782. pCsr->nAdvance = nMerge;
  128783. }while( rc==SQLITE_OK );
  128784. return rc;
  128785. }
  128786. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  128787. Fts3MultiSegReader *pCsr /* Cursor object */
  128788. ){
  128789. if( pCsr ){
  128790. int i;
  128791. for(i=0; i<pCsr->nSegment; i++){
  128792. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  128793. }
  128794. sqlite3_free(pCsr->apSegment);
  128795. sqlite3_free(pCsr->aBuffer);
  128796. pCsr->nSegment = 0;
  128797. pCsr->apSegment = 0;
  128798. pCsr->aBuffer = 0;
  128799. }
  128800. }
  128801. /*
  128802. ** Merge all level iLevel segments in the database into a single
  128803. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  128804. ** single segment with a level equal to the numerically largest level
  128805. ** currently present in the database.
  128806. **
  128807. ** If this function is called with iLevel<0, but there is only one
  128808. ** segment in the database, SQLITE_DONE is returned immediately.
  128809. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  128810. ** an SQLite error code is returned.
  128811. */
  128812. static int fts3SegmentMerge(
  128813. Fts3Table *p,
  128814. int iLangid, /* Language id to merge */
  128815. int iIndex, /* Index in p->aIndex[] to merge */
  128816. int iLevel /* Level to merge */
  128817. ){
  128818. int rc; /* Return code */
  128819. int iIdx = 0; /* Index of new segment */
  128820. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  128821. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  128822. Fts3SegFilter filter; /* Segment term filter condition */
  128823. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  128824. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  128825. assert( iLevel==FTS3_SEGCURSOR_ALL
  128826. || iLevel==FTS3_SEGCURSOR_PENDING
  128827. || iLevel>=0
  128828. );
  128829. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  128830. assert( iIndex>=0 && iIndex<p->nIndex );
  128831. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  128832. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  128833. if( iLevel==FTS3_SEGCURSOR_ALL ){
  128834. /* This call is to merge all segments in the database to a single
  128835. ** segment. The level of the new segment is equal to the numerically
  128836. ** greatest segment level currently present in the database for this
  128837. ** index. The idx of the new segment is always 0. */
  128838. if( csr.nSegment==1 ){
  128839. rc = SQLITE_DONE;
  128840. goto finished;
  128841. }
  128842. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iNewLevel);
  128843. bIgnoreEmpty = 1;
  128844. }else if( iLevel==FTS3_SEGCURSOR_PENDING ){
  128845. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, 0);
  128846. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, 0, &iIdx);
  128847. }else{
  128848. /* This call is to merge all segments at level iLevel. find the next
  128849. ** available segment index at level iLevel+1. The call to
  128850. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  128851. ** a single iLevel+2 segment if necessary. */
  128852. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  128853. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  128854. }
  128855. if( rc!=SQLITE_OK ) goto finished;
  128856. assert( csr.nSegment>0 );
  128857. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  128858. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  128859. memset(&filter, 0, sizeof(Fts3SegFilter));
  128860. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  128861. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  128862. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  128863. while( SQLITE_OK==rc ){
  128864. rc = sqlite3Fts3SegReaderStep(p, &csr);
  128865. if( rc!=SQLITE_ROW ) break;
  128866. rc = fts3SegWriterAdd(p, &pWriter, 1,
  128867. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  128868. }
  128869. if( rc!=SQLITE_OK ) goto finished;
  128870. assert( pWriter );
  128871. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  128872. rc = fts3DeleteSegdir(
  128873. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  128874. );
  128875. if( rc!=SQLITE_OK ) goto finished;
  128876. }
  128877. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  128878. finished:
  128879. fts3SegWriterFree(pWriter);
  128880. sqlite3Fts3SegReaderFinish(&csr);
  128881. return rc;
  128882. }
  128883. /*
  128884. ** Flush the contents of pendingTerms to level 0 segments.
  128885. */
  128886. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  128887. int rc = SQLITE_OK;
  128888. int i;
  128889. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  128890. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  128891. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  128892. }
  128893. sqlite3Fts3PendingTermsClear(p);
  128894. /* Determine the auto-incr-merge setting if unknown. If enabled,
  128895. ** estimate the number of leaf blocks of content to be written
  128896. */
  128897. if( rc==SQLITE_OK && p->bHasStat
  128898. && p->bAutoincrmerge==0xff && p->nLeafAdd>0
  128899. ){
  128900. sqlite3_stmt *pStmt = 0;
  128901. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  128902. if( rc==SQLITE_OK ){
  128903. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  128904. rc = sqlite3_step(pStmt);
  128905. p->bAutoincrmerge = (rc==SQLITE_ROW && sqlite3_column_int(pStmt, 0));
  128906. rc = sqlite3_reset(pStmt);
  128907. }
  128908. }
  128909. return rc;
  128910. }
  128911. /*
  128912. ** Encode N integers as varints into a blob.
  128913. */
  128914. static void fts3EncodeIntArray(
  128915. int N, /* The number of integers to encode */
  128916. u32 *a, /* The integer values */
  128917. char *zBuf, /* Write the BLOB here */
  128918. int *pNBuf /* Write number of bytes if zBuf[] used here */
  128919. ){
  128920. int i, j;
  128921. for(i=j=0; i<N; i++){
  128922. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  128923. }
  128924. *pNBuf = j;
  128925. }
  128926. /*
  128927. ** Decode a blob of varints into N integers
  128928. */
  128929. static void fts3DecodeIntArray(
  128930. int N, /* The number of integers to decode */
  128931. u32 *a, /* Write the integer values */
  128932. const char *zBuf, /* The BLOB containing the varints */
  128933. int nBuf /* size of the BLOB */
  128934. ){
  128935. int i, j;
  128936. UNUSED_PARAMETER(nBuf);
  128937. for(i=j=0; i<N; i++){
  128938. sqlite3_int64 x;
  128939. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  128940. assert(j<=nBuf);
  128941. a[i] = (u32)(x & 0xffffffff);
  128942. }
  128943. }
  128944. /*
  128945. ** Insert the sizes (in tokens) for each column of the document
  128946. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  128947. ** a blob of varints.
  128948. */
  128949. static void fts3InsertDocsize(
  128950. int *pRC, /* Result code */
  128951. Fts3Table *p, /* Table into which to insert */
  128952. u32 *aSz /* Sizes of each column, in tokens */
  128953. ){
  128954. char *pBlob; /* The BLOB encoding of the document size */
  128955. int nBlob; /* Number of bytes in the BLOB */
  128956. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  128957. int rc; /* Result code from subfunctions */
  128958. if( *pRC ) return;
  128959. pBlob = sqlite3_malloc( 10*p->nColumn );
  128960. if( pBlob==0 ){
  128961. *pRC = SQLITE_NOMEM;
  128962. return;
  128963. }
  128964. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  128965. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  128966. if( rc ){
  128967. sqlite3_free(pBlob);
  128968. *pRC = rc;
  128969. return;
  128970. }
  128971. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  128972. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  128973. sqlite3_step(pStmt);
  128974. *pRC = sqlite3_reset(pStmt);
  128975. }
  128976. /*
  128977. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  128978. ** where N is the number of user defined columns in the fts3 table plus
  128979. ** two. If nCol is the number of user defined columns, then values of the
  128980. ** varints are set as follows:
  128981. **
  128982. ** Varint 0: Total number of rows in the table.
  128983. **
  128984. ** Varint 1..nCol: For each column, the total number of tokens stored in
  128985. ** the column for all rows of the table.
  128986. **
  128987. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  128988. ** columns of all rows of the table.
  128989. **
  128990. */
  128991. static void fts3UpdateDocTotals(
  128992. int *pRC, /* The result code */
  128993. Fts3Table *p, /* Table being updated */
  128994. u32 *aSzIns, /* Size increases */
  128995. u32 *aSzDel, /* Size decreases */
  128996. int nChng /* Change in the number of documents */
  128997. ){
  128998. char *pBlob; /* Storage for BLOB written into %_stat */
  128999. int nBlob; /* Size of BLOB written into %_stat */
  129000. u32 *a; /* Array of integers that becomes the BLOB */
  129001. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  129002. int i; /* Loop counter */
  129003. int rc; /* Result code from subfunctions */
  129004. const int nStat = p->nColumn+2;
  129005. if( *pRC ) return;
  129006. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  129007. if( a==0 ){
  129008. *pRC = SQLITE_NOMEM;
  129009. return;
  129010. }
  129011. pBlob = (char*)&a[nStat];
  129012. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  129013. if( rc ){
  129014. sqlite3_free(a);
  129015. *pRC = rc;
  129016. return;
  129017. }
  129018. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  129019. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  129020. fts3DecodeIntArray(nStat, a,
  129021. sqlite3_column_blob(pStmt, 0),
  129022. sqlite3_column_bytes(pStmt, 0));
  129023. }else{
  129024. memset(a, 0, sizeof(u32)*(nStat) );
  129025. }
  129026. rc = sqlite3_reset(pStmt);
  129027. if( rc!=SQLITE_OK ){
  129028. sqlite3_free(a);
  129029. *pRC = rc;
  129030. return;
  129031. }
  129032. if( nChng<0 && a[0]<(u32)(-nChng) ){
  129033. a[0] = 0;
  129034. }else{
  129035. a[0] += nChng;
  129036. }
  129037. for(i=0; i<p->nColumn+1; i++){
  129038. u32 x = a[i+1];
  129039. if( x+aSzIns[i] < aSzDel[i] ){
  129040. x = 0;
  129041. }else{
  129042. x = x + aSzIns[i] - aSzDel[i];
  129043. }
  129044. a[i+1] = x;
  129045. }
  129046. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  129047. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  129048. if( rc ){
  129049. sqlite3_free(a);
  129050. *pRC = rc;
  129051. return;
  129052. }
  129053. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  129054. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  129055. sqlite3_step(pStmt);
  129056. *pRC = sqlite3_reset(pStmt);
  129057. sqlite3_free(a);
  129058. }
  129059. /*
  129060. ** Merge the entire database so that there is one segment for each
  129061. ** iIndex/iLangid combination.
  129062. */
  129063. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  129064. int bSeenDone = 0;
  129065. int rc;
  129066. sqlite3_stmt *pAllLangid = 0;
  129067. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  129068. if( rc==SQLITE_OK ){
  129069. int rc2;
  129070. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  129071. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  129072. int i;
  129073. int iLangid = sqlite3_column_int(pAllLangid, 0);
  129074. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  129075. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  129076. if( rc==SQLITE_DONE ){
  129077. bSeenDone = 1;
  129078. rc = SQLITE_OK;
  129079. }
  129080. }
  129081. }
  129082. rc2 = sqlite3_reset(pAllLangid);
  129083. if( rc==SQLITE_OK ) rc = rc2;
  129084. }
  129085. sqlite3Fts3SegmentsClose(p);
  129086. sqlite3Fts3PendingTermsClear(p);
  129087. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  129088. }
  129089. /*
  129090. ** This function is called when the user executes the following statement:
  129091. **
  129092. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  129093. **
  129094. ** The entire FTS index is discarded and rebuilt. If the table is one
  129095. ** created using the content=xxx option, then the new index is based on
  129096. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  129097. ** on the contents of the %_content table.
  129098. */
  129099. static int fts3DoRebuild(Fts3Table *p){
  129100. int rc; /* Return Code */
  129101. rc = fts3DeleteAll(p, 0);
  129102. if( rc==SQLITE_OK ){
  129103. u32 *aSz = 0;
  129104. u32 *aSzIns = 0;
  129105. u32 *aSzDel = 0;
  129106. sqlite3_stmt *pStmt = 0;
  129107. int nEntry = 0;
  129108. /* Compose and prepare an SQL statement to loop through the content table */
  129109. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  129110. if( !zSql ){
  129111. rc = SQLITE_NOMEM;
  129112. }else{
  129113. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  129114. sqlite3_free(zSql);
  129115. }
  129116. if( rc==SQLITE_OK ){
  129117. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  129118. aSz = (u32 *)sqlite3_malloc(nByte);
  129119. if( aSz==0 ){
  129120. rc = SQLITE_NOMEM;
  129121. }else{
  129122. memset(aSz, 0, nByte);
  129123. aSzIns = &aSz[p->nColumn+1];
  129124. aSzDel = &aSzIns[p->nColumn+1];
  129125. }
  129126. }
  129127. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  129128. int iCol;
  129129. int iLangid = langidFromSelect(p, pStmt);
  129130. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  129131. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  129132. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  129133. if( p->abNotindexed[iCol]==0 ){
  129134. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  129135. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  129136. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  129137. }
  129138. }
  129139. if( p->bHasDocsize ){
  129140. fts3InsertDocsize(&rc, p, aSz);
  129141. }
  129142. if( rc!=SQLITE_OK ){
  129143. sqlite3_finalize(pStmt);
  129144. pStmt = 0;
  129145. }else{
  129146. nEntry++;
  129147. for(iCol=0; iCol<=p->nColumn; iCol++){
  129148. aSzIns[iCol] += aSz[iCol];
  129149. }
  129150. }
  129151. }
  129152. if( p->bFts4 ){
  129153. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  129154. }
  129155. sqlite3_free(aSz);
  129156. if( pStmt ){
  129157. int rc2 = sqlite3_finalize(pStmt);
  129158. if( rc==SQLITE_OK ){
  129159. rc = rc2;
  129160. }
  129161. }
  129162. }
  129163. return rc;
  129164. }
  129165. /*
  129166. ** This function opens a cursor used to read the input data for an
  129167. ** incremental merge operation. Specifically, it opens a cursor to scan
  129168. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  129169. ** level iAbsLevel.
  129170. */
  129171. static int fts3IncrmergeCsr(
  129172. Fts3Table *p, /* FTS3 table handle */
  129173. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  129174. int nSeg, /* Number of segments to merge */
  129175. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  129176. ){
  129177. int rc; /* Return Code */
  129178. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  129179. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  129180. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  129181. memset(pCsr, 0, sizeof(*pCsr));
  129182. nByte = sizeof(Fts3SegReader *) * nSeg;
  129183. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  129184. if( pCsr->apSegment==0 ){
  129185. rc = SQLITE_NOMEM;
  129186. }else{
  129187. memset(pCsr->apSegment, 0, nByte);
  129188. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  129189. }
  129190. if( rc==SQLITE_OK ){
  129191. int i;
  129192. int rc2;
  129193. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  129194. assert( pCsr->nSegment==0 );
  129195. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  129196. rc = sqlite3Fts3SegReaderNew(i, 0,
  129197. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  129198. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  129199. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  129200. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  129201. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  129202. &pCsr->apSegment[i]
  129203. );
  129204. pCsr->nSegment++;
  129205. }
  129206. rc2 = sqlite3_reset(pStmt);
  129207. if( rc==SQLITE_OK ) rc = rc2;
  129208. }
  129209. return rc;
  129210. }
  129211. typedef struct IncrmergeWriter IncrmergeWriter;
  129212. typedef struct NodeWriter NodeWriter;
  129213. typedef struct Blob Blob;
  129214. typedef struct NodeReader NodeReader;
  129215. /*
  129216. ** An instance of the following structure is used as a dynamic buffer
  129217. ** to build up nodes or other blobs of data in.
  129218. **
  129219. ** The function blobGrowBuffer() is used to extend the allocation.
  129220. */
  129221. struct Blob {
  129222. char *a; /* Pointer to allocation */
  129223. int n; /* Number of valid bytes of data in a[] */
  129224. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  129225. };
  129226. /*
  129227. ** This structure is used to build up buffers containing segment b-tree
  129228. ** nodes (blocks).
  129229. */
  129230. struct NodeWriter {
  129231. sqlite3_int64 iBlock; /* Current block id */
  129232. Blob key; /* Last key written to the current block */
  129233. Blob block; /* Current block image */
  129234. };
  129235. /*
  129236. ** An object of this type contains the state required to create or append
  129237. ** to an appendable b-tree segment.
  129238. */
  129239. struct IncrmergeWriter {
  129240. int nLeafEst; /* Space allocated for leaf blocks */
  129241. int nWork; /* Number of leaf pages flushed */
  129242. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  129243. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  129244. sqlite3_int64 iStart; /* Block number of first allocated block */
  129245. sqlite3_int64 iEnd; /* Block number of last allocated block */
  129246. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  129247. };
  129248. /*
  129249. ** An object of the following type is used to read data from a single
  129250. ** FTS segment node. See the following functions:
  129251. **
  129252. ** nodeReaderInit()
  129253. ** nodeReaderNext()
  129254. ** nodeReaderRelease()
  129255. */
  129256. struct NodeReader {
  129257. const char *aNode;
  129258. int nNode;
  129259. int iOff; /* Current offset within aNode[] */
  129260. /* Output variables. Containing the current node entry. */
  129261. sqlite3_int64 iChild; /* Pointer to child node */
  129262. Blob term; /* Current term */
  129263. const char *aDoclist; /* Pointer to doclist */
  129264. int nDoclist; /* Size of doclist in bytes */
  129265. };
  129266. /*
  129267. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  129268. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  129269. ** bytes in size, extend (realloc) it to be so.
  129270. **
  129271. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  129272. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  129273. ** to reflect the new size of the pBlob->a[] buffer.
  129274. */
  129275. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  129276. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  129277. int nAlloc = nMin;
  129278. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  129279. if( a ){
  129280. pBlob->nAlloc = nAlloc;
  129281. pBlob->a = a;
  129282. }else{
  129283. *pRc = SQLITE_NOMEM;
  129284. }
  129285. }
  129286. }
  129287. /*
  129288. ** Attempt to advance the node-reader object passed as the first argument to
  129289. ** the next entry on the node.
  129290. **
  129291. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  129292. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  129293. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  129294. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  129295. ** variables for the new entry.
  129296. */
  129297. static int nodeReaderNext(NodeReader *p){
  129298. int bFirst = (p->term.n==0); /* True for first term on the node */
  129299. int nPrefix = 0; /* Bytes to copy from previous term */
  129300. int nSuffix = 0; /* Bytes to append to the prefix */
  129301. int rc = SQLITE_OK; /* Return code */
  129302. assert( p->aNode );
  129303. if( p->iChild && bFirst==0 ) p->iChild++;
  129304. if( p->iOff>=p->nNode ){
  129305. /* EOF */
  129306. p->aNode = 0;
  129307. }else{
  129308. if( bFirst==0 ){
  129309. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  129310. }
  129311. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  129312. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  129313. if( rc==SQLITE_OK ){
  129314. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  129315. p->term.n = nPrefix+nSuffix;
  129316. p->iOff += nSuffix;
  129317. if( p->iChild==0 ){
  129318. p->iOff += sqlite3Fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  129319. p->aDoclist = &p->aNode[p->iOff];
  129320. p->iOff += p->nDoclist;
  129321. }
  129322. }
  129323. }
  129324. assert( p->iOff<=p->nNode );
  129325. return rc;
  129326. }
  129327. /*
  129328. ** Release all dynamic resources held by node-reader object *p.
  129329. */
  129330. static void nodeReaderRelease(NodeReader *p){
  129331. sqlite3_free(p->term.a);
  129332. }
  129333. /*
  129334. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  129335. **
  129336. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  129337. ** point to the first entry on the node (if any). Otherwise, an SQLite
  129338. ** error code is returned.
  129339. */
  129340. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  129341. memset(p, 0, sizeof(NodeReader));
  129342. p->aNode = aNode;
  129343. p->nNode = nNode;
  129344. /* Figure out if this is a leaf or an internal node. */
  129345. if( p->aNode[0] ){
  129346. /* An internal node. */
  129347. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  129348. }else{
  129349. p->iOff = 1;
  129350. }
  129351. return nodeReaderNext(p);
  129352. }
  129353. /*
  129354. ** This function is called while writing an FTS segment each time a leaf o
  129355. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  129356. ** to be greater than the largest key on the node just written, but smaller
  129357. ** than or equal to the first key that will be written to the next leaf
  129358. ** node.
  129359. **
  129360. ** The block id of the leaf node just written to disk may be found in
  129361. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  129362. */
  129363. static int fts3IncrmergePush(
  129364. Fts3Table *p, /* Fts3 table handle */
  129365. IncrmergeWriter *pWriter, /* Writer object */
  129366. const char *zTerm, /* Term to write to internal node */
  129367. int nTerm /* Bytes at zTerm */
  129368. ){
  129369. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  129370. int iLayer;
  129371. assert( nTerm>0 );
  129372. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  129373. sqlite3_int64 iNextPtr = 0;
  129374. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  129375. int rc = SQLITE_OK;
  129376. int nPrefix;
  129377. int nSuffix;
  129378. int nSpace;
  129379. /* Figure out how much space the key will consume if it is written to
  129380. ** the current node of layer iLayer. Due to the prefix compression,
  129381. ** the space required changes depending on which node the key is to
  129382. ** be added to. */
  129383. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  129384. nSuffix = nTerm - nPrefix;
  129385. nSpace = sqlite3Fts3VarintLen(nPrefix);
  129386. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129387. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  129388. /* If the current node of layer iLayer contains zero keys, or if adding
  129389. ** the key to it will not cause it to grow to larger than nNodeSize
  129390. ** bytes in size, write the key here. */
  129391. Blob *pBlk = &pNode->block;
  129392. if( pBlk->n==0 ){
  129393. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  129394. if( rc==SQLITE_OK ){
  129395. pBlk->a[0] = (char)iLayer;
  129396. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  129397. }
  129398. }
  129399. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  129400. blobGrowBuffer(&pNode->key, nTerm, &rc);
  129401. if( rc==SQLITE_OK ){
  129402. if( pNode->key.n ){
  129403. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  129404. }
  129405. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  129406. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  129407. pBlk->n += nSuffix;
  129408. memcpy(pNode->key.a, zTerm, nTerm);
  129409. pNode->key.n = nTerm;
  129410. }
  129411. }else{
  129412. /* Otherwise, flush the current node of layer iLayer to disk.
  129413. ** Then allocate a new, empty sibling node. The key will be written
  129414. ** into the parent of this node. */
  129415. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  129416. assert( pNode->block.nAlloc>=p->nNodeSize );
  129417. pNode->block.a[0] = (char)iLayer;
  129418. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  129419. iNextPtr = pNode->iBlock;
  129420. pNode->iBlock++;
  129421. pNode->key.n = 0;
  129422. }
  129423. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  129424. iPtr = iNextPtr;
  129425. }
  129426. assert( 0 );
  129427. return 0;
  129428. }
  129429. /*
  129430. ** Append a term and (optionally) doclist to the FTS segment node currently
  129431. ** stored in blob *pNode. The node need not contain any terms, but the
  129432. ** header must be written before this function is called.
  129433. **
  129434. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  129435. ** followed by the left-hand-child varint for an internal node.
  129436. **
  129437. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  129438. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  129439. ** node, both aDoclist and nDoclist must be passed 0.
  129440. **
  129441. ** If the size of the value in blob pPrev is zero, then this is the first
  129442. ** term written to the node. Otherwise, pPrev contains a copy of the
  129443. ** previous term. Before this function returns, it is updated to contain a
  129444. ** copy of zTerm/nTerm.
  129445. **
  129446. ** It is assumed that the buffer associated with pNode is already large
  129447. ** enough to accommodate the new entry. The buffer associated with pPrev
  129448. ** is extended by this function if requrired.
  129449. **
  129450. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  129451. ** returned. Otherwise, SQLITE_OK.
  129452. */
  129453. static int fts3AppendToNode(
  129454. Blob *pNode, /* Current node image to append to */
  129455. Blob *pPrev, /* Buffer containing previous term written */
  129456. const char *zTerm, /* New term to write */
  129457. int nTerm, /* Size of zTerm in bytes */
  129458. const char *aDoclist, /* Doclist (or NULL) to write */
  129459. int nDoclist /* Size of aDoclist in bytes */
  129460. ){
  129461. int rc = SQLITE_OK; /* Return code */
  129462. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  129463. int nPrefix; /* Size of term prefix in bytes */
  129464. int nSuffix; /* Size of term suffix in bytes */
  129465. /* Node must have already been started. There must be a doclist for a
  129466. ** leaf node, and there must not be a doclist for an internal node. */
  129467. assert( pNode->n>0 );
  129468. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  129469. blobGrowBuffer(pPrev, nTerm, &rc);
  129470. if( rc!=SQLITE_OK ) return rc;
  129471. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  129472. nSuffix = nTerm - nPrefix;
  129473. memcpy(pPrev->a, zTerm, nTerm);
  129474. pPrev->n = nTerm;
  129475. if( bFirst==0 ){
  129476. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  129477. }
  129478. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  129479. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  129480. pNode->n += nSuffix;
  129481. if( aDoclist ){
  129482. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  129483. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  129484. pNode->n += nDoclist;
  129485. }
  129486. assert( pNode->n<=pNode->nAlloc );
  129487. return SQLITE_OK;
  129488. }
  129489. /*
  129490. ** Append the current term and doclist pointed to by cursor pCsr to the
  129491. ** appendable b-tree segment opened for writing by pWriter.
  129492. **
  129493. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  129494. */
  129495. static int fts3IncrmergeAppend(
  129496. Fts3Table *p, /* Fts3 table handle */
  129497. IncrmergeWriter *pWriter, /* Writer object */
  129498. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  129499. ){
  129500. const char *zTerm = pCsr->zTerm;
  129501. int nTerm = pCsr->nTerm;
  129502. const char *aDoclist = pCsr->aDoclist;
  129503. int nDoclist = pCsr->nDoclist;
  129504. int rc = SQLITE_OK; /* Return code */
  129505. int nSpace; /* Total space in bytes required on leaf */
  129506. int nPrefix; /* Size of prefix shared with previous term */
  129507. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  129508. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  129509. pLeaf = &pWriter->aNodeWriter[0];
  129510. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  129511. nSuffix = nTerm - nPrefix;
  129512. nSpace = sqlite3Fts3VarintLen(nPrefix);
  129513. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129514. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  129515. /* If the current block is not empty, and if adding this term/doclist
  129516. ** to the current block would make it larger than Fts3Table.nNodeSize
  129517. ** bytes, write this block out to the database. */
  129518. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  129519. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  129520. pWriter->nWork++;
  129521. /* Add the current term to the parent node. The term added to the
  129522. ** parent must:
  129523. **
  129524. ** a) be greater than the largest term on the leaf node just written
  129525. ** to the database (still available in pLeaf->key), and
  129526. **
  129527. ** b) be less than or equal to the term about to be added to the new
  129528. ** leaf node (zTerm/nTerm).
  129529. **
  129530. ** In other words, it must be the prefix of zTerm 1 byte longer than
  129531. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  129532. */
  129533. if( rc==SQLITE_OK ){
  129534. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  129535. }
  129536. /* Advance to the next output block */
  129537. pLeaf->iBlock++;
  129538. pLeaf->key.n = 0;
  129539. pLeaf->block.n = 0;
  129540. nSuffix = nTerm;
  129541. nSpace = 1;
  129542. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  129543. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  129544. }
  129545. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  129546. if( rc==SQLITE_OK ){
  129547. if( pLeaf->block.n==0 ){
  129548. pLeaf->block.n = 1;
  129549. pLeaf->block.a[0] = '\0';
  129550. }
  129551. rc = fts3AppendToNode(
  129552. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  129553. );
  129554. }
  129555. return rc;
  129556. }
  129557. /*
  129558. ** This function is called to release all dynamic resources held by the
  129559. ** merge-writer object pWriter, and if no error has occurred, to flush
  129560. ** all outstanding node buffers held by pWriter to disk.
  129561. **
  129562. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  129563. ** is made to write any data to disk. Instead, this function serves only
  129564. ** to release outstanding resources.
  129565. **
  129566. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  129567. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  129568. ** returning.
  129569. */
  129570. static void fts3IncrmergeRelease(
  129571. Fts3Table *p, /* FTS3 table handle */
  129572. IncrmergeWriter *pWriter, /* Merge-writer object */
  129573. int *pRc /* IN/OUT: Error code */
  129574. ){
  129575. int i; /* Used to iterate through non-root layers */
  129576. int iRoot; /* Index of root in pWriter->aNodeWriter */
  129577. NodeWriter *pRoot; /* NodeWriter for root node */
  129578. int rc = *pRc; /* Error code */
  129579. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  129580. ** root node. If the segment fits entirely on a single leaf node, iRoot
  129581. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  129582. ** will be 1. And so on. */
  129583. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  129584. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  129585. if( pNode->block.n>0 ) break;
  129586. assert( *pRc || pNode->block.nAlloc==0 );
  129587. assert( *pRc || pNode->key.nAlloc==0 );
  129588. sqlite3_free(pNode->block.a);
  129589. sqlite3_free(pNode->key.a);
  129590. }
  129591. /* Empty output segment. This is a no-op. */
  129592. if( iRoot<0 ) return;
  129593. /* The entire output segment fits on a single node. Normally, this means
  129594. ** the node would be stored as a blob in the "root" column of the %_segdir
  129595. ** table. However, this is not permitted in this case. The problem is that
  129596. ** space has already been reserved in the %_segments table, and so the
  129597. ** start_block and end_block fields of the %_segdir table must be populated.
  129598. ** And, by design or by accident, released versions of FTS cannot handle
  129599. ** segments that fit entirely on the root node with start_block!=0.
  129600. **
  129601. ** Instead, create a synthetic root node that contains nothing but a
  129602. ** pointer to the single content node. So that the segment consists of a
  129603. ** single leaf and a single interior (root) node.
  129604. **
  129605. ** Todo: Better might be to defer allocating space in the %_segments
  129606. ** table until we are sure it is needed.
  129607. */
  129608. if( iRoot==0 ){
  129609. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  129610. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  129611. if( rc==SQLITE_OK ){
  129612. pBlock->a[0] = 0x01;
  129613. pBlock->n = 1 + sqlite3Fts3PutVarint(
  129614. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  129615. );
  129616. }
  129617. iRoot = 1;
  129618. }
  129619. pRoot = &pWriter->aNodeWriter[iRoot];
  129620. /* Flush all currently outstanding nodes to disk. */
  129621. for(i=0; i<iRoot; i++){
  129622. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  129623. if( pNode->block.n>0 && rc==SQLITE_OK ){
  129624. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  129625. }
  129626. sqlite3_free(pNode->block.a);
  129627. sqlite3_free(pNode->key.a);
  129628. }
  129629. /* Write the %_segdir record. */
  129630. if( rc==SQLITE_OK ){
  129631. rc = fts3WriteSegdir(p,
  129632. pWriter->iAbsLevel+1, /* level */
  129633. pWriter->iIdx, /* idx */
  129634. pWriter->iStart, /* start_block */
  129635. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  129636. pWriter->iEnd, /* end_block */
  129637. pRoot->block.a, pRoot->block.n /* root */
  129638. );
  129639. }
  129640. sqlite3_free(pRoot->block.a);
  129641. sqlite3_free(pRoot->key.a);
  129642. *pRc = rc;
  129643. }
  129644. /*
  129645. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  129646. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  129647. ** the other, it is considered to be smaller than the other.
  129648. **
  129649. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  129650. ** if it is greater.
  129651. */
  129652. static int fts3TermCmp(
  129653. const char *zLhs, int nLhs, /* LHS of comparison */
  129654. const char *zRhs, int nRhs /* RHS of comparison */
  129655. ){
  129656. int nCmp = MIN(nLhs, nRhs);
  129657. int res;
  129658. res = memcmp(zLhs, zRhs, nCmp);
  129659. if( res==0 ) res = nLhs - nRhs;
  129660. return res;
  129661. }
  129662. /*
  129663. ** Query to see if the entry in the %_segments table with blockid iEnd is
  129664. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  129665. ** returning. Otherwise, set *pbRes to 0.
  129666. **
  129667. ** Or, if an error occurs while querying the database, return an SQLite
  129668. ** error code. The final value of *pbRes is undefined in this case.
  129669. **
  129670. ** This is used to test if a segment is an "appendable" segment. If it
  129671. ** is, then a NULL entry has been inserted into the %_segments table
  129672. ** with blockid %_segdir.end_block.
  129673. */
  129674. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  129675. int bRes = 0; /* Result to set *pbRes to */
  129676. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  129677. int rc; /* Return code */
  129678. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  129679. if( rc==SQLITE_OK ){
  129680. sqlite3_bind_int64(pCheck, 1, iEnd);
  129681. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  129682. rc = sqlite3_reset(pCheck);
  129683. }
  129684. *pbRes = bRes;
  129685. return rc;
  129686. }
  129687. /*
  129688. ** This function is called when initializing an incremental-merge operation.
  129689. ** It checks if the existing segment with index value iIdx at absolute level
  129690. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  129691. ** merge-writer object *pWriter is initialized to write to it.
  129692. **
  129693. ** An existing segment can be appended to by an incremental merge if:
  129694. **
  129695. ** * It was initially created as an appendable segment (with all required
  129696. ** space pre-allocated), and
  129697. **
  129698. ** * The first key read from the input (arguments zKey and nKey) is
  129699. ** greater than the largest key currently stored in the potential
  129700. ** output segment.
  129701. */
  129702. static int fts3IncrmergeLoad(
  129703. Fts3Table *p, /* Fts3 table handle */
  129704. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  129705. int iIdx, /* Index of candidate output segment */
  129706. const char *zKey, /* First key to write */
  129707. int nKey, /* Number of bytes in nKey */
  129708. IncrmergeWriter *pWriter /* Populate this object */
  129709. ){
  129710. int rc; /* Return code */
  129711. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  129712. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  129713. if( rc==SQLITE_OK ){
  129714. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  129715. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  129716. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  129717. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  129718. int nRoot = 0; /* Size of aRoot[] in bytes */
  129719. int rc2; /* Return code from sqlite3_reset() */
  129720. int bAppendable = 0; /* Set to true if segment is appendable */
  129721. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  129722. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  129723. sqlite3_bind_int(pSelect, 2, iIdx);
  129724. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  129725. iStart = sqlite3_column_int64(pSelect, 1);
  129726. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  129727. iEnd = sqlite3_column_int64(pSelect, 3);
  129728. nRoot = sqlite3_column_bytes(pSelect, 4);
  129729. aRoot = sqlite3_column_blob(pSelect, 4);
  129730. }else{
  129731. return sqlite3_reset(pSelect);
  129732. }
  129733. /* Check for the zero-length marker in the %_segments table */
  129734. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  129735. /* Check that zKey/nKey is larger than the largest key the candidate */
  129736. if( rc==SQLITE_OK && bAppendable ){
  129737. char *aLeaf = 0;
  129738. int nLeaf = 0;
  129739. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  129740. if( rc==SQLITE_OK ){
  129741. NodeReader reader;
  129742. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  129743. rc==SQLITE_OK && reader.aNode;
  129744. rc = nodeReaderNext(&reader)
  129745. ){
  129746. assert( reader.aNode );
  129747. }
  129748. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  129749. bAppendable = 0;
  129750. }
  129751. nodeReaderRelease(&reader);
  129752. }
  129753. sqlite3_free(aLeaf);
  129754. }
  129755. if( rc==SQLITE_OK && bAppendable ){
  129756. /* It is possible to append to this segment. Set up the IncrmergeWriter
  129757. ** object to do so. */
  129758. int i;
  129759. int nHeight = (int)aRoot[0];
  129760. NodeWriter *pNode;
  129761. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  129762. pWriter->iStart = iStart;
  129763. pWriter->iEnd = iEnd;
  129764. pWriter->iAbsLevel = iAbsLevel;
  129765. pWriter->iIdx = iIdx;
  129766. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  129767. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  129768. }
  129769. pNode = &pWriter->aNodeWriter[nHeight];
  129770. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  129771. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  129772. if( rc==SQLITE_OK ){
  129773. memcpy(pNode->block.a, aRoot, nRoot);
  129774. pNode->block.n = nRoot;
  129775. }
  129776. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  129777. NodeReader reader;
  129778. pNode = &pWriter->aNodeWriter[i];
  129779. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  129780. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  129781. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  129782. if( rc==SQLITE_OK ){
  129783. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  129784. pNode->key.n = reader.term.n;
  129785. if( i>0 ){
  129786. char *aBlock = 0;
  129787. int nBlock = 0;
  129788. pNode = &pWriter->aNodeWriter[i-1];
  129789. pNode->iBlock = reader.iChild;
  129790. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  129791. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  129792. if( rc==SQLITE_OK ){
  129793. memcpy(pNode->block.a, aBlock, nBlock);
  129794. pNode->block.n = nBlock;
  129795. }
  129796. sqlite3_free(aBlock);
  129797. }
  129798. }
  129799. nodeReaderRelease(&reader);
  129800. }
  129801. }
  129802. rc2 = sqlite3_reset(pSelect);
  129803. if( rc==SQLITE_OK ) rc = rc2;
  129804. }
  129805. return rc;
  129806. }
  129807. /*
  129808. ** Determine the largest segment index value that exists within absolute
  129809. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  129810. ** one before returning SQLITE_OK. Or, if there are no segments at all
  129811. ** within level iAbsLevel, set *piIdx to zero.
  129812. **
  129813. ** If an error occurs, return an SQLite error code. The final value of
  129814. ** *piIdx is undefined in this case.
  129815. */
  129816. static int fts3IncrmergeOutputIdx(
  129817. Fts3Table *p, /* FTS Table handle */
  129818. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  129819. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  129820. ){
  129821. int rc;
  129822. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  129823. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  129824. if( rc==SQLITE_OK ){
  129825. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  129826. sqlite3_step(pOutputIdx);
  129827. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  129828. rc = sqlite3_reset(pOutputIdx);
  129829. }
  129830. return rc;
  129831. }
  129832. /*
  129833. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  129834. ** with idx value iIdx.
  129835. **
  129836. ** In the %_segdir table, a segment is defined by the values in three
  129837. ** columns:
  129838. **
  129839. ** start_block
  129840. ** leaves_end_block
  129841. ** end_block
  129842. **
  129843. ** When an appendable segment is allocated, it is estimated that the
  129844. ** maximum number of leaf blocks that may be required is the sum of the
  129845. ** number of leaf blocks consumed by the input segments, plus the number
  129846. ** of input segments, multiplied by two. This value is stored in stack
  129847. ** variable nLeafEst.
  129848. **
  129849. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  129850. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  129851. ** array of leaf nodes starts at the first block allocated. The array
  129852. ** of interior nodes that are parents of the leaf nodes start at block
  129853. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  129854. **
  129855. ** In the actual code below, the value "16" is replaced with the
  129856. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  129857. */
  129858. static int fts3IncrmergeWriter(
  129859. Fts3Table *p, /* Fts3 table handle */
  129860. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  129861. int iIdx, /* Index of new output segment */
  129862. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  129863. IncrmergeWriter *pWriter /* Populate this object */
  129864. ){
  129865. int rc; /* Return Code */
  129866. int i; /* Iterator variable */
  129867. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  129868. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  129869. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  129870. /* Calculate nLeafEst. */
  129871. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  129872. if( rc==SQLITE_OK ){
  129873. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  129874. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  129875. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  129876. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  129877. }
  129878. rc = sqlite3_reset(pLeafEst);
  129879. }
  129880. if( rc!=SQLITE_OK ) return rc;
  129881. /* Calculate the first block to use in the output segment */
  129882. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  129883. if( rc==SQLITE_OK ){
  129884. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  129885. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  129886. pWriter->iEnd = pWriter->iStart - 1;
  129887. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  129888. }
  129889. rc = sqlite3_reset(pFirstBlock);
  129890. }
  129891. if( rc!=SQLITE_OK ) return rc;
  129892. /* Insert the marker in the %_segments table to make sure nobody tries
  129893. ** to steal the space just allocated. This is also used to identify
  129894. ** appendable segments. */
  129895. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  129896. if( rc!=SQLITE_OK ) return rc;
  129897. pWriter->iAbsLevel = iAbsLevel;
  129898. pWriter->nLeafEst = nLeafEst;
  129899. pWriter->iIdx = iIdx;
  129900. /* Set up the array of NodeWriter objects */
  129901. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  129902. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  129903. }
  129904. return SQLITE_OK;
  129905. }
  129906. /*
  129907. ** Remove an entry from the %_segdir table. This involves running the
  129908. ** following two statements:
  129909. **
  129910. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  129911. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  129912. **
  129913. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  129914. ** statement ensures that the remaining segments have contiguously allocated
  129915. ** idx values.
  129916. */
  129917. static int fts3RemoveSegdirEntry(
  129918. Fts3Table *p, /* FTS3 table handle */
  129919. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  129920. int iIdx /* Index of %_segdir entry to delete */
  129921. ){
  129922. int rc; /* Return code */
  129923. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  129924. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  129925. if( rc==SQLITE_OK ){
  129926. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  129927. sqlite3_bind_int(pDelete, 2, iIdx);
  129928. sqlite3_step(pDelete);
  129929. rc = sqlite3_reset(pDelete);
  129930. }
  129931. return rc;
  129932. }
  129933. /*
  129934. ** One or more segments have just been removed from absolute level iAbsLevel.
  129935. ** Update the 'idx' values of the remaining segments in the level so that
  129936. ** the idx values are a contiguous sequence starting from 0.
  129937. */
  129938. static int fts3RepackSegdirLevel(
  129939. Fts3Table *p, /* FTS3 table handle */
  129940. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  129941. ){
  129942. int rc; /* Return code */
  129943. int *aIdx = 0; /* Array of remaining idx values */
  129944. int nIdx = 0; /* Valid entries in aIdx[] */
  129945. int nAlloc = 0; /* Allocated size of aIdx[] */
  129946. int i; /* Iterator variable */
  129947. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  129948. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  129949. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  129950. if( rc==SQLITE_OK ){
  129951. int rc2;
  129952. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  129953. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  129954. if( nIdx>=nAlloc ){
  129955. int *aNew;
  129956. nAlloc += 16;
  129957. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  129958. if( !aNew ){
  129959. rc = SQLITE_NOMEM;
  129960. break;
  129961. }
  129962. aIdx = aNew;
  129963. }
  129964. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  129965. }
  129966. rc2 = sqlite3_reset(pSelect);
  129967. if( rc==SQLITE_OK ) rc = rc2;
  129968. }
  129969. if( rc==SQLITE_OK ){
  129970. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  129971. }
  129972. if( rc==SQLITE_OK ){
  129973. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  129974. }
  129975. assert( p->bIgnoreSavepoint==0 );
  129976. p->bIgnoreSavepoint = 1;
  129977. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  129978. if( aIdx[i]!=i ){
  129979. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  129980. sqlite3_bind_int(pUpdate, 1, i);
  129981. sqlite3_step(pUpdate);
  129982. rc = sqlite3_reset(pUpdate);
  129983. }
  129984. }
  129985. p->bIgnoreSavepoint = 0;
  129986. sqlite3_free(aIdx);
  129987. return rc;
  129988. }
  129989. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  129990. pNode->a[0] = (char)iHeight;
  129991. if( iChild ){
  129992. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  129993. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  129994. }else{
  129995. assert( pNode->nAlloc>=1 );
  129996. pNode->n = 1;
  129997. }
  129998. }
  129999. /*
  130000. ** The first two arguments are a pointer to and the size of a segment b-tree
  130001. ** node. The node may be a leaf or an internal node.
  130002. **
  130003. ** This function creates a new node image in blob object *pNew by copying
  130004. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  130005. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  130006. */
  130007. static int fts3TruncateNode(
  130008. const char *aNode, /* Current node image */
  130009. int nNode, /* Size of aNode in bytes */
  130010. Blob *pNew, /* OUT: Write new node image here */
  130011. const char *zTerm, /* Omit all terms smaller than this */
  130012. int nTerm, /* Size of zTerm in bytes */
  130013. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  130014. ){
  130015. NodeReader reader; /* Reader object */
  130016. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  130017. int rc = SQLITE_OK; /* Return code */
  130018. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  130019. /* Allocate required output space */
  130020. blobGrowBuffer(pNew, nNode, &rc);
  130021. if( rc!=SQLITE_OK ) return rc;
  130022. pNew->n = 0;
  130023. /* Populate new node buffer */
  130024. for(rc = nodeReaderInit(&reader, aNode, nNode);
  130025. rc==SQLITE_OK && reader.aNode;
  130026. rc = nodeReaderNext(&reader)
  130027. ){
  130028. if( pNew->n==0 ){
  130029. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  130030. if( res<0 || (bLeaf==0 && res==0) ) continue;
  130031. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  130032. *piBlock = reader.iChild;
  130033. }
  130034. rc = fts3AppendToNode(
  130035. pNew, &prev, reader.term.a, reader.term.n,
  130036. reader.aDoclist, reader.nDoclist
  130037. );
  130038. if( rc!=SQLITE_OK ) break;
  130039. }
  130040. if( pNew->n==0 ){
  130041. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  130042. *piBlock = reader.iChild;
  130043. }
  130044. assert( pNew->n<=pNew->nAlloc );
  130045. nodeReaderRelease(&reader);
  130046. sqlite3_free(prev.a);
  130047. return rc;
  130048. }
  130049. /*
  130050. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  130051. ** level iAbsLevel. This may involve deleting entries from the %_segments
  130052. ** table, and modifying existing entries in both the %_segments and %_segdir
  130053. ** tables.
  130054. **
  130055. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  130056. ** SQLite error code otherwise.
  130057. */
  130058. static int fts3TruncateSegment(
  130059. Fts3Table *p, /* FTS3 table handle */
  130060. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  130061. int iIdx, /* Index within level of segment to modify */
  130062. const char *zTerm, /* Remove terms smaller than this */
  130063. int nTerm /* Number of bytes in buffer zTerm */
  130064. ){
  130065. int rc = SQLITE_OK; /* Return code */
  130066. Blob root = {0,0,0}; /* New root page image */
  130067. Blob block = {0,0,0}; /* Buffer used for any other block */
  130068. sqlite3_int64 iBlock = 0; /* Block id */
  130069. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  130070. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  130071. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  130072. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  130073. if( rc==SQLITE_OK ){
  130074. int rc2; /* sqlite3_reset() return code */
  130075. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  130076. sqlite3_bind_int(pFetch, 2, iIdx);
  130077. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  130078. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  130079. int nRoot = sqlite3_column_bytes(pFetch, 4);
  130080. iOldStart = sqlite3_column_int64(pFetch, 1);
  130081. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  130082. }
  130083. rc2 = sqlite3_reset(pFetch);
  130084. if( rc==SQLITE_OK ) rc = rc2;
  130085. }
  130086. while( rc==SQLITE_OK && iBlock ){
  130087. char *aBlock = 0;
  130088. int nBlock = 0;
  130089. iNewStart = iBlock;
  130090. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  130091. if( rc==SQLITE_OK ){
  130092. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  130093. }
  130094. if( rc==SQLITE_OK ){
  130095. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  130096. }
  130097. sqlite3_free(aBlock);
  130098. }
  130099. /* Variable iNewStart now contains the first valid leaf node. */
  130100. if( rc==SQLITE_OK && iNewStart ){
  130101. sqlite3_stmt *pDel = 0;
  130102. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  130103. if( rc==SQLITE_OK ){
  130104. sqlite3_bind_int64(pDel, 1, iOldStart);
  130105. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  130106. sqlite3_step(pDel);
  130107. rc = sqlite3_reset(pDel);
  130108. }
  130109. }
  130110. if( rc==SQLITE_OK ){
  130111. sqlite3_stmt *pChomp = 0;
  130112. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  130113. if( rc==SQLITE_OK ){
  130114. sqlite3_bind_int64(pChomp, 1, iNewStart);
  130115. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  130116. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  130117. sqlite3_bind_int(pChomp, 4, iIdx);
  130118. sqlite3_step(pChomp);
  130119. rc = sqlite3_reset(pChomp);
  130120. }
  130121. }
  130122. sqlite3_free(root.a);
  130123. sqlite3_free(block.a);
  130124. return rc;
  130125. }
  130126. /*
  130127. ** This function is called after an incrmental-merge operation has run to
  130128. ** merge (or partially merge) two or more segments from absolute level
  130129. ** iAbsLevel.
  130130. **
  130131. ** Each input segment is either removed from the db completely (if all of
  130132. ** its data was copied to the output segment by the incrmerge operation)
  130133. ** or modified in place so that it no longer contains those entries that
  130134. ** have been duplicated in the output segment.
  130135. */
  130136. static int fts3IncrmergeChomp(
  130137. Fts3Table *p, /* FTS table handle */
  130138. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  130139. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  130140. int *pnRem /* Number of segments not deleted */
  130141. ){
  130142. int i;
  130143. int nRem = 0;
  130144. int rc = SQLITE_OK;
  130145. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  130146. Fts3SegReader *pSeg = 0;
  130147. int j;
  130148. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  130149. ** somewhere in the pCsr->apSegment[] array. */
  130150. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  130151. pSeg = pCsr->apSegment[j];
  130152. if( pSeg->iIdx==i ) break;
  130153. }
  130154. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  130155. if( pSeg->aNode==0 ){
  130156. /* Seg-reader is at EOF. Remove the entire input segment. */
  130157. rc = fts3DeleteSegment(p, pSeg);
  130158. if( rc==SQLITE_OK ){
  130159. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  130160. }
  130161. *pnRem = 0;
  130162. }else{
  130163. /* The incremental merge did not copy all the data from this
  130164. ** segment to the upper level. The segment is modified in place
  130165. ** so that it contains no keys smaller than zTerm/nTerm. */
  130166. const char *zTerm = pSeg->zTerm;
  130167. int nTerm = pSeg->nTerm;
  130168. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  130169. nRem++;
  130170. }
  130171. }
  130172. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  130173. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  130174. }
  130175. *pnRem = nRem;
  130176. return rc;
  130177. }
  130178. /*
  130179. ** Store an incr-merge hint in the database.
  130180. */
  130181. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  130182. sqlite3_stmt *pReplace = 0;
  130183. int rc; /* Return code */
  130184. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  130185. if( rc==SQLITE_OK ){
  130186. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  130187. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  130188. sqlite3_step(pReplace);
  130189. rc = sqlite3_reset(pReplace);
  130190. }
  130191. return rc;
  130192. }
  130193. /*
  130194. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  130195. ** exists, is stored in the rowid==1 row of the %_stat table.
  130196. **
  130197. ** If successful, populate blob *pHint with the value read from the %_stat
  130198. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  130199. ** SQLite error code.
  130200. */
  130201. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  130202. sqlite3_stmt *pSelect = 0;
  130203. int rc;
  130204. pHint->n = 0;
  130205. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  130206. if( rc==SQLITE_OK ){
  130207. int rc2;
  130208. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  130209. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  130210. const char *aHint = sqlite3_column_blob(pSelect, 0);
  130211. int nHint = sqlite3_column_bytes(pSelect, 0);
  130212. if( aHint ){
  130213. blobGrowBuffer(pHint, nHint, &rc);
  130214. if( rc==SQLITE_OK ){
  130215. memcpy(pHint->a, aHint, nHint);
  130216. pHint->n = nHint;
  130217. }
  130218. }
  130219. }
  130220. rc2 = sqlite3_reset(pSelect);
  130221. if( rc==SQLITE_OK ) rc = rc2;
  130222. }
  130223. return rc;
  130224. }
  130225. /*
  130226. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  130227. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  130228. ** consists of two varints, the absolute level number of the input segments
  130229. ** and the number of input segments.
  130230. **
  130231. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  130232. ** set *pRc to an SQLite error code before returning.
  130233. */
  130234. static void fts3IncrmergeHintPush(
  130235. Blob *pHint, /* Hint blob to append to */
  130236. i64 iAbsLevel, /* First varint to store in hint */
  130237. int nInput, /* Second varint to store in hint */
  130238. int *pRc /* IN/OUT: Error code */
  130239. ){
  130240. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  130241. if( *pRc==SQLITE_OK ){
  130242. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  130243. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  130244. }
  130245. }
  130246. /*
  130247. ** Read the last entry (most recently pushed) from the hint blob *pHint
  130248. ** and then remove the entry. Write the two values read to *piAbsLevel and
  130249. ** *pnInput before returning.
  130250. **
  130251. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  130252. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  130253. */
  130254. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  130255. const int nHint = pHint->n;
  130256. int i;
  130257. i = pHint->n-2;
  130258. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  130259. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  130260. pHint->n = i;
  130261. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  130262. i += sqlite3Fts3GetVarint32(&pHint->a[i], pnInput);
  130263. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  130264. return SQLITE_OK;
  130265. }
  130266. /*
  130267. ** Attempt an incremental merge that writes nMerge leaf blocks.
  130268. **
  130269. ** Incremental merges happen nMin segments at a time. The two
  130270. ** segments to be merged are the nMin oldest segments (the ones with
  130271. ** the smallest indexes) in the highest level that contains at least
  130272. ** nMin segments. Multiple merges might occur in an attempt to write the
  130273. ** quota of nMerge leaf blocks.
  130274. */
  130275. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  130276. int rc; /* Return code */
  130277. int nRem = nMerge; /* Number of leaf pages yet to be written */
  130278. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  130279. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  130280. IncrmergeWriter *pWriter; /* Writer object */
  130281. int nSeg = 0; /* Number of input segments */
  130282. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  130283. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  130284. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  130285. /* Allocate space for the cursor, filter and writer objects */
  130286. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  130287. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  130288. if( !pWriter ) return SQLITE_NOMEM;
  130289. pFilter = (Fts3SegFilter *)&pWriter[1];
  130290. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  130291. rc = fts3IncrmergeHintLoad(p, &hint);
  130292. while( rc==SQLITE_OK && nRem>0 ){
  130293. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  130294. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  130295. int bUseHint = 0; /* True if attempting to append */
  130296. /* Search the %_segdir table for the absolute level with the smallest
  130297. ** relative level number that contains at least nMin segments, if any.
  130298. ** If one is found, set iAbsLevel to the absolute level number and
  130299. ** nSeg to nMin. If no level with at least nMin segments can be found,
  130300. ** set nSeg to -1.
  130301. */
  130302. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  130303. sqlite3_bind_int(pFindLevel, 1, nMin);
  130304. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  130305. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  130306. nSeg = nMin;
  130307. }else{
  130308. nSeg = -1;
  130309. }
  130310. rc = sqlite3_reset(pFindLevel);
  130311. /* If the hint read from the %_stat table is not empty, check if the
  130312. ** last entry in it specifies a relative level smaller than or equal
  130313. ** to the level identified by the block above (if any). If so, this
  130314. ** iteration of the loop will work on merging at the hinted level.
  130315. */
  130316. if( rc==SQLITE_OK && hint.n ){
  130317. int nHint = hint.n;
  130318. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  130319. int nHintSeg = 0; /* Hint number of segments */
  130320. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  130321. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  130322. iAbsLevel = iHintAbsLevel;
  130323. nSeg = nHintSeg;
  130324. bUseHint = 1;
  130325. bDirtyHint = 1;
  130326. }else{
  130327. /* This undoes the effect of the HintPop() above - so that no entry
  130328. ** is removed from the hint blob. */
  130329. hint.n = nHint;
  130330. }
  130331. }
  130332. /* If nSeg is less that zero, then there is no level with at least
  130333. ** nMin segments and no hint in the %_stat table. No work to do.
  130334. ** Exit early in this case. */
  130335. if( nSeg<0 ) break;
  130336. /* Open a cursor to iterate through the contents of the oldest nSeg
  130337. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  130338. ** the 'hint' parameters, it is possible that there are less than nSeg
  130339. ** segments available in level iAbsLevel. In this case, no work is
  130340. ** done on iAbsLevel - fall through to the next iteration of the loop
  130341. ** to start work on some other level. */
  130342. memset(pWriter, 0, nAlloc);
  130343. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  130344. if( rc==SQLITE_OK ){
  130345. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  130346. }
  130347. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  130348. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  130349. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  130350. ){
  130351. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  130352. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  130353. if( rc==SQLITE_OK ){
  130354. if( bUseHint && iIdx>0 ){
  130355. const char *zKey = pCsr->zTerm;
  130356. int nKey = pCsr->nTerm;
  130357. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  130358. }else{
  130359. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  130360. }
  130361. }
  130362. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  130363. fts3LogMerge(nSeg, iAbsLevel);
  130364. do {
  130365. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  130366. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  130367. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  130368. }while( rc==SQLITE_ROW );
  130369. /* Update or delete the input segments */
  130370. if( rc==SQLITE_OK ){
  130371. nRem -= (1 + pWriter->nWork);
  130372. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  130373. if( nSeg!=0 ){
  130374. bDirtyHint = 1;
  130375. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  130376. }
  130377. }
  130378. }
  130379. fts3IncrmergeRelease(p, pWriter, &rc);
  130380. }
  130381. sqlite3Fts3SegReaderFinish(pCsr);
  130382. }
  130383. /* Write the hint values into the %_stat table for the next incr-merger */
  130384. if( bDirtyHint && rc==SQLITE_OK ){
  130385. rc = fts3IncrmergeHintStore(p, &hint);
  130386. }
  130387. sqlite3_free(pWriter);
  130388. sqlite3_free(hint.a);
  130389. return rc;
  130390. }
  130391. /*
  130392. ** Convert the text beginning at *pz into an integer and return
  130393. ** its value. Advance *pz to point to the first character past
  130394. ** the integer.
  130395. */
  130396. static int fts3Getint(const char **pz){
  130397. const char *z = *pz;
  130398. int i = 0;
  130399. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  130400. *pz = z;
  130401. return i;
  130402. }
  130403. /*
  130404. ** Process statements of the form:
  130405. **
  130406. ** INSERT INTO table(table) VALUES('merge=A,B');
  130407. **
  130408. ** A and B are integers that decode to be the number of leaf pages
  130409. ** written for the merge, and the minimum number of segments on a level
  130410. ** before it will be selected for a merge, respectively.
  130411. */
  130412. static int fts3DoIncrmerge(
  130413. Fts3Table *p, /* FTS3 table handle */
  130414. const char *zParam /* Nul-terminated string containing "A,B" */
  130415. ){
  130416. int rc;
  130417. int nMin = (FTS3_MERGE_COUNT / 2);
  130418. int nMerge = 0;
  130419. const char *z = zParam;
  130420. /* Read the first integer value */
  130421. nMerge = fts3Getint(&z);
  130422. /* If the first integer value is followed by a ',', read the second
  130423. ** integer value. */
  130424. if( z[0]==',' && z[1]!='\0' ){
  130425. z++;
  130426. nMin = fts3Getint(&z);
  130427. }
  130428. if( z[0]!='\0' || nMin<2 ){
  130429. rc = SQLITE_ERROR;
  130430. }else{
  130431. rc = SQLITE_OK;
  130432. if( !p->bHasStat ){
  130433. assert( p->bFts4==0 );
  130434. sqlite3Fts3CreateStatTable(&rc, p);
  130435. }
  130436. if( rc==SQLITE_OK ){
  130437. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  130438. }
  130439. sqlite3Fts3SegmentsClose(p);
  130440. }
  130441. return rc;
  130442. }
  130443. /*
  130444. ** Process statements of the form:
  130445. **
  130446. ** INSERT INTO table(table) VALUES('automerge=X');
  130447. **
  130448. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  130449. ** turn it on. The setting is persistent.
  130450. */
  130451. static int fts3DoAutoincrmerge(
  130452. Fts3Table *p, /* FTS3 table handle */
  130453. const char *zParam /* Nul-terminated string containing boolean */
  130454. ){
  130455. int rc = SQLITE_OK;
  130456. sqlite3_stmt *pStmt = 0;
  130457. p->bAutoincrmerge = fts3Getint(&zParam)!=0;
  130458. if( !p->bHasStat ){
  130459. assert( p->bFts4==0 );
  130460. sqlite3Fts3CreateStatTable(&rc, p);
  130461. if( rc ) return rc;
  130462. }
  130463. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  130464. if( rc ) return rc;
  130465. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  130466. sqlite3_bind_int(pStmt, 2, p->bAutoincrmerge);
  130467. sqlite3_step(pStmt);
  130468. rc = sqlite3_reset(pStmt);
  130469. return rc;
  130470. }
  130471. /*
  130472. ** Return a 64-bit checksum for the FTS index entry specified by the
  130473. ** arguments to this function.
  130474. */
  130475. static u64 fts3ChecksumEntry(
  130476. const char *zTerm, /* Pointer to buffer containing term */
  130477. int nTerm, /* Size of zTerm in bytes */
  130478. int iLangid, /* Language id for current row */
  130479. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  130480. i64 iDocid, /* Docid for current row. */
  130481. int iCol, /* Column number */
  130482. int iPos /* Position */
  130483. ){
  130484. int i;
  130485. u64 ret = (u64)iDocid;
  130486. ret += (ret<<3) + iLangid;
  130487. ret += (ret<<3) + iIndex;
  130488. ret += (ret<<3) + iCol;
  130489. ret += (ret<<3) + iPos;
  130490. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  130491. return ret;
  130492. }
  130493. /*
  130494. ** Return a checksum of all entries in the FTS index that correspond to
  130495. ** language id iLangid. The checksum is calculated by XORing the checksums
  130496. ** of each individual entry (see fts3ChecksumEntry()) together.
  130497. **
  130498. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  130499. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  130500. ** return value is undefined in this case.
  130501. */
  130502. static u64 fts3ChecksumIndex(
  130503. Fts3Table *p, /* FTS3 table handle */
  130504. int iLangid, /* Language id to return cksum for */
  130505. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  130506. int *pRc /* OUT: Return code */
  130507. ){
  130508. Fts3SegFilter filter;
  130509. Fts3MultiSegReader csr;
  130510. int rc;
  130511. u64 cksum = 0;
  130512. assert( *pRc==SQLITE_OK );
  130513. memset(&filter, 0, sizeof(filter));
  130514. memset(&csr, 0, sizeof(csr));
  130515. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  130516. filter.flags |= FTS3_SEGMENT_SCAN;
  130517. rc = sqlite3Fts3SegReaderCursor(
  130518. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  130519. );
  130520. if( rc==SQLITE_OK ){
  130521. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  130522. }
  130523. if( rc==SQLITE_OK ){
  130524. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  130525. char *pCsr = csr.aDoclist;
  130526. char *pEnd = &pCsr[csr.nDoclist];
  130527. i64 iDocid = 0;
  130528. i64 iCol = 0;
  130529. i64 iPos = 0;
  130530. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  130531. while( pCsr<pEnd ){
  130532. i64 iVal = 0;
  130533. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  130534. if( pCsr<pEnd ){
  130535. if( iVal==0 || iVal==1 ){
  130536. iCol = 0;
  130537. iPos = 0;
  130538. if( iVal ){
  130539. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  130540. }else{
  130541. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  130542. iDocid += iVal;
  130543. }
  130544. }else{
  130545. iPos += (iVal - 2);
  130546. cksum = cksum ^ fts3ChecksumEntry(
  130547. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  130548. (int)iCol, (int)iPos
  130549. );
  130550. }
  130551. }
  130552. }
  130553. }
  130554. }
  130555. sqlite3Fts3SegReaderFinish(&csr);
  130556. *pRc = rc;
  130557. return cksum;
  130558. }
  130559. /*
  130560. ** Check if the contents of the FTS index match the current contents of the
  130561. ** content table. If no error occurs and the contents do match, set *pbOk
  130562. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  130563. ** to false before returning.
  130564. **
  130565. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  130566. ** code. The final value of *pbOk is undefined in this case.
  130567. */
  130568. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  130569. int rc = SQLITE_OK; /* Return code */
  130570. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  130571. u64 cksum2 = 0; /* Checksum based on %_content contents */
  130572. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  130573. /* This block calculates the checksum according to the FTS index. */
  130574. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  130575. if( rc==SQLITE_OK ){
  130576. int rc2;
  130577. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  130578. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  130579. int iLangid = sqlite3_column_int(pAllLangid, 0);
  130580. int i;
  130581. for(i=0; i<p->nIndex; i++){
  130582. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  130583. }
  130584. }
  130585. rc2 = sqlite3_reset(pAllLangid);
  130586. if( rc==SQLITE_OK ) rc = rc2;
  130587. }
  130588. /* This block calculates the checksum according to the %_content table */
  130589. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  130590. if( rc==SQLITE_OK ){
  130591. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  130592. sqlite3_stmt *pStmt = 0;
  130593. char *zSql;
  130594. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  130595. if( !zSql ){
  130596. rc = SQLITE_NOMEM;
  130597. }else{
  130598. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  130599. sqlite3_free(zSql);
  130600. }
  130601. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  130602. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  130603. int iLang = langidFromSelect(p, pStmt);
  130604. int iCol;
  130605. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  130606. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  130607. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  130608. sqlite3_tokenizer_cursor *pT = 0;
  130609. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText, &pT);
  130610. while( rc==SQLITE_OK ){
  130611. char const *zToken; /* Buffer containing token */
  130612. int nToken = 0; /* Number of bytes in token */
  130613. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  130614. int iPos = 0; /* Position of token in zText */
  130615. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  130616. if( rc==SQLITE_OK ){
  130617. int i;
  130618. cksum2 = cksum2 ^ fts3ChecksumEntry(
  130619. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  130620. );
  130621. for(i=1; i<p->nIndex; i++){
  130622. if( p->aIndex[i].nPrefix<=nToken ){
  130623. cksum2 = cksum2 ^ fts3ChecksumEntry(
  130624. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  130625. );
  130626. }
  130627. }
  130628. }
  130629. }
  130630. if( pT ) pModule->xClose(pT);
  130631. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130632. }
  130633. }
  130634. sqlite3_finalize(pStmt);
  130635. }
  130636. *pbOk = (cksum1==cksum2);
  130637. return rc;
  130638. }
  130639. /*
  130640. ** Run the integrity-check. If no error occurs and the current contents of
  130641. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  130642. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  130643. **
  130644. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  130645. ** error code.
  130646. **
  130647. ** The integrity-check works as follows. For each token and indexed token
  130648. ** prefix in the document set, a 64-bit checksum is calculated (by code
  130649. ** in fts3ChecksumEntry()) based on the following:
  130650. **
  130651. ** + The index number (0 for the main index, 1 for the first prefix
  130652. ** index etc.),
  130653. ** + The token (or token prefix) text itself,
  130654. ** + The language-id of the row it appears in,
  130655. ** + The docid of the row it appears in,
  130656. ** + The column it appears in, and
  130657. ** + The tokens position within that column.
  130658. **
  130659. ** The checksums for all entries in the index are XORed together to create
  130660. ** a single checksum for the entire index.
  130661. **
  130662. ** The integrity-check code calculates the same checksum in two ways:
  130663. **
  130664. ** 1. By scanning the contents of the FTS index, and
  130665. ** 2. By scanning and tokenizing the content table.
  130666. **
  130667. ** If the two checksums are identical, the integrity-check is deemed to have
  130668. ** passed.
  130669. */
  130670. static int fts3DoIntegrityCheck(
  130671. Fts3Table *p /* FTS3 table handle */
  130672. ){
  130673. int rc;
  130674. int bOk = 0;
  130675. rc = fts3IntegrityCheck(p, &bOk);
  130676. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  130677. return rc;
  130678. }
  130679. /*
  130680. ** Handle a 'special' INSERT of the form:
  130681. **
  130682. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  130683. **
  130684. ** Argument pVal contains the result of <expr>. Currently the only
  130685. ** meaningful value to insert is the text 'optimize'.
  130686. */
  130687. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  130688. int rc; /* Return Code */
  130689. const char *zVal = (const char *)sqlite3_value_text(pVal);
  130690. int nVal = sqlite3_value_bytes(pVal);
  130691. if( !zVal ){
  130692. return SQLITE_NOMEM;
  130693. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  130694. rc = fts3DoOptimize(p, 0);
  130695. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  130696. rc = fts3DoRebuild(p);
  130697. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  130698. rc = fts3DoIntegrityCheck(p);
  130699. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  130700. rc = fts3DoIncrmerge(p, &zVal[6]);
  130701. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  130702. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  130703. #ifdef SQLITE_TEST
  130704. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  130705. p->nNodeSize = atoi(&zVal[9]);
  130706. rc = SQLITE_OK;
  130707. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  130708. p->nMaxPendingData = atoi(&zVal[11]);
  130709. rc = SQLITE_OK;
  130710. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  130711. p->bNoIncrDoclist = atoi(&zVal[21]);
  130712. rc = SQLITE_OK;
  130713. #endif
  130714. }else{
  130715. rc = SQLITE_ERROR;
  130716. }
  130717. return rc;
  130718. }
  130719. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  130720. /*
  130721. ** Delete all cached deferred doclists. Deferred doclists are cached
  130722. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  130723. */
  130724. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  130725. Fts3DeferredToken *pDef;
  130726. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  130727. fts3PendingListDelete(pDef->pList);
  130728. pDef->pList = 0;
  130729. }
  130730. }
  130731. /*
  130732. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  130733. ** this list using sqlite3Fts3DeferToken().
  130734. */
  130735. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  130736. Fts3DeferredToken *pDef;
  130737. Fts3DeferredToken *pNext;
  130738. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  130739. pNext = pDef->pNext;
  130740. fts3PendingListDelete(pDef->pList);
  130741. sqlite3_free(pDef);
  130742. }
  130743. pCsr->pDeferred = 0;
  130744. }
  130745. /*
  130746. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  130747. ** based on the row that pCsr currently points to.
  130748. **
  130749. ** A deferred-doclist is like any other doclist with position information
  130750. ** included, except that it only contains entries for a single row of the
  130751. ** table, not for all rows.
  130752. */
  130753. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  130754. int rc = SQLITE_OK; /* Return code */
  130755. if( pCsr->pDeferred ){
  130756. int i; /* Used to iterate through table columns */
  130757. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  130758. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  130759. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  130760. sqlite3_tokenizer *pT = p->pTokenizer;
  130761. sqlite3_tokenizer_module const *pModule = pT->pModule;
  130762. assert( pCsr->isRequireSeek==0 );
  130763. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  130764. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  130765. if( p->abNotindexed[i]==0 ){
  130766. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  130767. sqlite3_tokenizer_cursor *pTC = 0;
  130768. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  130769. while( rc==SQLITE_OK ){
  130770. char const *zToken; /* Buffer containing token */
  130771. int nToken = 0; /* Number of bytes in token */
  130772. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  130773. int iPos = 0; /* Position of token in zText */
  130774. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  130775. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  130776. Fts3PhraseToken *pPT = pDef->pToken;
  130777. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  130778. && (pPT->bFirst==0 || iPos==0)
  130779. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  130780. && (0==memcmp(zToken, pPT->z, pPT->n))
  130781. ){
  130782. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  130783. }
  130784. }
  130785. }
  130786. if( pTC ) pModule->xClose(pTC);
  130787. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130788. }
  130789. }
  130790. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  130791. if( pDef->pList ){
  130792. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  130793. }
  130794. }
  130795. }
  130796. return rc;
  130797. }
  130798. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  130799. Fts3DeferredToken *p,
  130800. char **ppData,
  130801. int *pnData
  130802. ){
  130803. char *pRet;
  130804. int nSkip;
  130805. sqlite3_int64 dummy;
  130806. *ppData = 0;
  130807. *pnData = 0;
  130808. if( p->pList==0 ){
  130809. return SQLITE_OK;
  130810. }
  130811. pRet = (char *)sqlite3_malloc(p->pList->nData);
  130812. if( !pRet ) return SQLITE_NOMEM;
  130813. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  130814. *pnData = p->pList->nData - nSkip;
  130815. *ppData = pRet;
  130816. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  130817. return SQLITE_OK;
  130818. }
  130819. /*
  130820. ** Add an entry for token pToken to the pCsr->pDeferred list.
  130821. */
  130822. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  130823. Fts3Cursor *pCsr, /* Fts3 table cursor */
  130824. Fts3PhraseToken *pToken, /* Token to defer */
  130825. int iCol /* Column that token must appear in (or -1) */
  130826. ){
  130827. Fts3DeferredToken *pDeferred;
  130828. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  130829. if( !pDeferred ){
  130830. return SQLITE_NOMEM;
  130831. }
  130832. memset(pDeferred, 0, sizeof(*pDeferred));
  130833. pDeferred->pToken = pToken;
  130834. pDeferred->pNext = pCsr->pDeferred;
  130835. pDeferred->iCol = iCol;
  130836. pCsr->pDeferred = pDeferred;
  130837. assert( pToken->pDeferred==0 );
  130838. pToken->pDeferred = pDeferred;
  130839. return SQLITE_OK;
  130840. }
  130841. #endif
  130842. /*
  130843. ** SQLite value pRowid contains the rowid of a row that may or may not be
  130844. ** present in the FTS3 table. If it is, delete it and adjust the contents
  130845. ** of subsiduary data structures accordingly.
  130846. */
  130847. static int fts3DeleteByRowid(
  130848. Fts3Table *p,
  130849. sqlite3_value *pRowid,
  130850. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  130851. u32 *aSzDel
  130852. ){
  130853. int rc = SQLITE_OK; /* Return code */
  130854. int bFound = 0; /* True if *pRowid really is in the table */
  130855. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  130856. if( bFound && rc==SQLITE_OK ){
  130857. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  130858. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  130859. if( rc==SQLITE_OK ){
  130860. if( isEmpty ){
  130861. /* Deleting this row means the whole table is empty. In this case
  130862. ** delete the contents of all three tables and throw away any
  130863. ** data in the pendingTerms hash table. */
  130864. rc = fts3DeleteAll(p, 1);
  130865. *pnChng = 0;
  130866. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  130867. }else{
  130868. *pnChng = *pnChng - 1;
  130869. if( p->zContentTbl==0 ){
  130870. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  130871. }
  130872. if( p->bHasDocsize ){
  130873. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  130874. }
  130875. }
  130876. }
  130877. }
  130878. return rc;
  130879. }
  130880. /*
  130881. ** This function does the work for the xUpdate method of FTS3 virtual
  130882. ** tables. The schema of the virtual table being:
  130883. **
  130884. ** CREATE TABLE <table name>(
  130885. ** <user columns>,
  130886. ** <table name> HIDDEN,
  130887. ** docid HIDDEN,
  130888. ** <langid> HIDDEN
  130889. ** );
  130890. **
  130891. **
  130892. */
  130893. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  130894. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  130895. int nArg, /* Size of argument array */
  130896. sqlite3_value **apVal, /* Array of arguments */
  130897. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  130898. ){
  130899. Fts3Table *p = (Fts3Table *)pVtab;
  130900. int rc = SQLITE_OK; /* Return Code */
  130901. int isRemove = 0; /* True for an UPDATE or DELETE */
  130902. u32 *aSzIns = 0; /* Sizes of inserted documents */
  130903. u32 *aSzDel = 0; /* Sizes of deleted documents */
  130904. int nChng = 0; /* Net change in number of documents */
  130905. int bInsertDone = 0;
  130906. assert( p->pSegments==0 );
  130907. assert(
  130908. nArg==1 /* DELETE operations */
  130909. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  130910. );
  130911. /* Check for a "special" INSERT operation. One of the form:
  130912. **
  130913. ** INSERT INTO xyz(xyz) VALUES('command');
  130914. */
  130915. if( nArg>1
  130916. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  130917. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  130918. ){
  130919. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  130920. goto update_out;
  130921. }
  130922. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  130923. rc = SQLITE_CONSTRAINT;
  130924. goto update_out;
  130925. }
  130926. /* Allocate space to hold the change in document sizes */
  130927. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  130928. if( aSzDel==0 ){
  130929. rc = SQLITE_NOMEM;
  130930. goto update_out;
  130931. }
  130932. aSzIns = &aSzDel[p->nColumn+1];
  130933. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  130934. rc = fts3Writelock(p);
  130935. if( rc!=SQLITE_OK ) goto update_out;
  130936. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  130937. ** value, then this operation requires constraint handling.
  130938. **
  130939. ** If the on-conflict mode is REPLACE, this means that the existing row
  130940. ** should be deleted from the database before inserting the new row. Or,
  130941. ** if the on-conflict mode is other than REPLACE, then this method must
  130942. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  130943. ** modify the database file.
  130944. */
  130945. if( nArg>1 && p->zContentTbl==0 ){
  130946. /* Find the value object that holds the new rowid value. */
  130947. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  130948. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  130949. pNewRowid = apVal[1];
  130950. }
  130951. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  130952. sqlite3_value_type(apVal[0])==SQLITE_NULL
  130953. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  130954. )){
  130955. /* The new rowid is not NULL (in this case the rowid will be
  130956. ** automatically assigned and there is no chance of a conflict), and
  130957. ** the statement is either an INSERT or an UPDATE that modifies the
  130958. ** rowid column. So if the conflict mode is REPLACE, then delete any
  130959. ** existing row with rowid=pNewRowid.
  130960. **
  130961. ** Or, if the conflict mode is not REPLACE, insert the new record into
  130962. ** the %_content table. If we hit the duplicate rowid constraint (or any
  130963. ** other error) while doing so, return immediately.
  130964. **
  130965. ** This branch may also run if pNewRowid contains a value that cannot
  130966. ** be losslessly converted to an integer. In this case, the eventual
  130967. ** call to fts3InsertData() (either just below or further on in this
  130968. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  130969. ** invoked, it will delete zero rows (since no row will have
  130970. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  130971. */
  130972. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  130973. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  130974. }else{
  130975. rc = fts3InsertData(p, apVal, pRowid);
  130976. bInsertDone = 1;
  130977. }
  130978. }
  130979. }
  130980. if( rc!=SQLITE_OK ){
  130981. goto update_out;
  130982. }
  130983. /* If this is a DELETE or UPDATE operation, remove the old record. */
  130984. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  130985. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  130986. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  130987. isRemove = 1;
  130988. }
  130989. /* If this is an INSERT or UPDATE operation, insert the new record. */
  130990. if( nArg>1 && rc==SQLITE_OK ){
  130991. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  130992. if( bInsertDone==0 ){
  130993. rc = fts3InsertData(p, apVal, pRowid);
  130994. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  130995. rc = FTS_CORRUPT_VTAB;
  130996. }
  130997. }
  130998. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  130999. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  131000. }
  131001. if( rc==SQLITE_OK ){
  131002. assert( p->iPrevDocid==*pRowid );
  131003. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  131004. }
  131005. if( p->bHasDocsize ){
  131006. fts3InsertDocsize(&rc, p, aSzIns);
  131007. }
  131008. nChng++;
  131009. }
  131010. if( p->bFts4 ){
  131011. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  131012. }
  131013. update_out:
  131014. sqlite3_free(aSzDel);
  131015. sqlite3Fts3SegmentsClose(p);
  131016. return rc;
  131017. }
  131018. /*
  131019. ** Flush any data in the pending-terms hash table to disk. If successful,
  131020. ** merge all segments in the database (including the new segment, if
  131021. ** there was any data to flush) into a single segment.
  131022. */
  131023. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  131024. int rc;
  131025. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  131026. if( rc==SQLITE_OK ){
  131027. rc = fts3DoOptimize(p, 1);
  131028. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  131029. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  131030. if( rc2!=SQLITE_OK ) rc = rc2;
  131031. }else{
  131032. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  131033. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  131034. }
  131035. }
  131036. sqlite3Fts3SegmentsClose(p);
  131037. return rc;
  131038. }
  131039. #endif
  131040. /************** End of fts3_write.c ******************************************/
  131041. /************** Begin file fts3_snippet.c ************************************/
  131042. /*
  131043. ** 2009 Oct 23
  131044. **
  131045. ** The author disclaims copyright to this source code. In place of
  131046. ** a legal notice, here is a blessing:
  131047. **
  131048. ** May you do good and not evil.
  131049. ** May you find forgiveness for yourself and forgive others.
  131050. ** May you share freely, never taking more than you give.
  131051. **
  131052. ******************************************************************************
  131053. */
  131054. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  131055. /* #include <string.h> */
  131056. /* #include <assert.h> */
  131057. /*
  131058. ** Characters that may appear in the second argument to matchinfo().
  131059. */
  131060. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  131061. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  131062. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  131063. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  131064. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  131065. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  131066. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  131067. /*
  131068. ** The default value for the second argument to matchinfo().
  131069. */
  131070. #define FTS3_MATCHINFO_DEFAULT "pcx"
  131071. /*
  131072. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  131073. ** Fts3Expr.aDoclist[]/nDoclist.
  131074. */
  131075. typedef struct LoadDoclistCtx LoadDoclistCtx;
  131076. struct LoadDoclistCtx {
  131077. Fts3Cursor *pCsr; /* FTS3 Cursor */
  131078. int nPhrase; /* Number of phrases seen so far */
  131079. int nToken; /* Number of tokens seen so far */
  131080. };
  131081. /*
  131082. ** The following types are used as part of the implementation of the
  131083. ** fts3BestSnippet() routine.
  131084. */
  131085. typedef struct SnippetIter SnippetIter;
  131086. typedef struct SnippetPhrase SnippetPhrase;
  131087. typedef struct SnippetFragment SnippetFragment;
  131088. struct SnippetIter {
  131089. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  131090. int iCol; /* Extract snippet from this column */
  131091. int nSnippet; /* Requested snippet length (in tokens) */
  131092. int nPhrase; /* Number of phrases in query */
  131093. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  131094. int iCurrent; /* First token of current snippet */
  131095. };
  131096. struct SnippetPhrase {
  131097. int nToken; /* Number of tokens in phrase */
  131098. char *pList; /* Pointer to start of phrase position list */
  131099. int iHead; /* Next value in position list */
  131100. char *pHead; /* Position list data following iHead */
  131101. int iTail; /* Next value in trailing position list */
  131102. char *pTail; /* Position list data following iTail */
  131103. };
  131104. struct SnippetFragment {
  131105. int iCol; /* Column snippet is extracted from */
  131106. int iPos; /* Index of first token in snippet */
  131107. u64 covered; /* Mask of query phrases covered */
  131108. u64 hlmask; /* Mask of snippet terms to highlight */
  131109. };
  131110. /*
  131111. ** This type is used as an fts3ExprIterate() context object while
  131112. ** accumulating the data returned by the matchinfo() function.
  131113. */
  131114. typedef struct MatchInfo MatchInfo;
  131115. struct MatchInfo {
  131116. Fts3Cursor *pCursor; /* FTS3 Cursor */
  131117. int nCol; /* Number of columns in table */
  131118. int nPhrase; /* Number of matchable phrases in query */
  131119. sqlite3_int64 nDoc; /* Number of docs in database */
  131120. u32 *aMatchinfo; /* Pre-allocated buffer */
  131121. };
  131122. /*
  131123. ** The snippet() and offsets() functions both return text values. An instance
  131124. ** of the following structure is used to accumulate those values while the
  131125. ** functions are running. See fts3StringAppend() for details.
  131126. */
  131127. typedef struct StrBuffer StrBuffer;
  131128. struct StrBuffer {
  131129. char *z; /* Pointer to buffer containing string */
  131130. int n; /* Length of z in bytes (excl. nul-term) */
  131131. int nAlloc; /* Allocated size of buffer z in bytes */
  131132. };
  131133. /*
  131134. ** This function is used to help iterate through a position-list. A position
  131135. ** list is a list of unique integers, sorted from smallest to largest. Each
  131136. ** element of the list is represented by an FTS3 varint that takes the value
  131137. ** of the difference between the current element and the previous one plus
  131138. ** two. For example, to store the position-list:
  131139. **
  131140. ** 4 9 113
  131141. **
  131142. ** the three varints:
  131143. **
  131144. ** 6 7 106
  131145. **
  131146. ** are encoded.
  131147. **
  131148. ** When this function is called, *pp points to the start of an element of
  131149. ** the list. *piPos contains the value of the previous entry in the list.
  131150. ** After it returns, *piPos contains the value of the next element of the
  131151. ** list and *pp is advanced to the following varint.
  131152. */
  131153. static void fts3GetDeltaPosition(char **pp, int *piPos){
  131154. int iVal;
  131155. *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
  131156. *piPos += (iVal-2);
  131157. }
  131158. /*
  131159. ** Helper function for fts3ExprIterate() (see below).
  131160. */
  131161. static int fts3ExprIterate2(
  131162. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  131163. int *piPhrase, /* Pointer to phrase counter */
  131164. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  131165. void *pCtx /* Second argument to pass to callback */
  131166. ){
  131167. int rc; /* Return code */
  131168. int eType = pExpr->eType; /* Type of expression node pExpr */
  131169. if( eType!=FTSQUERY_PHRASE ){
  131170. assert( pExpr->pLeft && pExpr->pRight );
  131171. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  131172. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  131173. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  131174. }
  131175. }else{
  131176. rc = x(pExpr, *piPhrase, pCtx);
  131177. (*piPhrase)++;
  131178. }
  131179. return rc;
  131180. }
  131181. /*
  131182. ** Iterate through all phrase nodes in an FTS3 query, except those that
  131183. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  131184. ** For each phrase node found, the supplied callback function is invoked.
  131185. **
  131186. ** If the callback function returns anything other than SQLITE_OK,
  131187. ** the iteration is abandoned and the error code returned immediately.
  131188. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  131189. ** all eligible phrase nodes.
  131190. */
  131191. static int fts3ExprIterate(
  131192. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  131193. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  131194. void *pCtx /* Second argument to pass to callback */
  131195. ){
  131196. int iPhrase = 0; /* Variable used as the phrase counter */
  131197. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  131198. }
  131199. /*
  131200. ** This is an fts3ExprIterate() callback used while loading the doclists
  131201. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  131202. ** fts3ExprLoadDoclists().
  131203. */
  131204. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131205. int rc = SQLITE_OK;
  131206. Fts3Phrase *pPhrase = pExpr->pPhrase;
  131207. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  131208. UNUSED_PARAMETER(iPhrase);
  131209. p->nPhrase++;
  131210. p->nToken += pPhrase->nToken;
  131211. return rc;
  131212. }
  131213. /*
  131214. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  131215. ** pCsr.
  131216. **
  131217. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  131218. ** phrases in the expression (all phrases except those directly or
  131219. ** indirectly descended from the right-hand-side of a NOT operator). If
  131220. ** pnToken is not NULL, then it is set to the number of tokens in all
  131221. ** matchable phrases of the expression.
  131222. */
  131223. static int fts3ExprLoadDoclists(
  131224. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  131225. int *pnPhrase, /* OUT: Number of phrases in query */
  131226. int *pnToken /* OUT: Number of tokens in query */
  131227. ){
  131228. int rc; /* Return Code */
  131229. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  131230. sCtx.pCsr = pCsr;
  131231. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  131232. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  131233. if( pnToken ) *pnToken = sCtx.nToken;
  131234. return rc;
  131235. }
  131236. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131237. (*(int *)ctx)++;
  131238. UNUSED_PARAMETER(pExpr);
  131239. UNUSED_PARAMETER(iPhrase);
  131240. return SQLITE_OK;
  131241. }
  131242. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  131243. int nPhrase = 0;
  131244. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  131245. return nPhrase;
  131246. }
  131247. /*
  131248. ** Advance the position list iterator specified by the first two
  131249. ** arguments so that it points to the first element with a value greater
  131250. ** than or equal to parameter iNext.
  131251. */
  131252. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  131253. char *pIter = *ppIter;
  131254. if( pIter ){
  131255. int iIter = *piIter;
  131256. while( iIter<iNext ){
  131257. if( 0==(*pIter & 0xFE) ){
  131258. iIter = -1;
  131259. pIter = 0;
  131260. break;
  131261. }
  131262. fts3GetDeltaPosition(&pIter, &iIter);
  131263. }
  131264. *piIter = iIter;
  131265. *ppIter = pIter;
  131266. }
  131267. }
  131268. /*
  131269. ** Advance the snippet iterator to the next candidate snippet.
  131270. */
  131271. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  131272. int i; /* Loop counter */
  131273. if( pIter->iCurrent<0 ){
  131274. /* The SnippetIter object has just been initialized. The first snippet
  131275. ** candidate always starts at offset 0 (even if this candidate has a
  131276. ** score of 0.0).
  131277. */
  131278. pIter->iCurrent = 0;
  131279. /* Advance the 'head' iterator of each phrase to the first offset that
  131280. ** is greater than or equal to (iNext+nSnippet).
  131281. */
  131282. for(i=0; i<pIter->nPhrase; i++){
  131283. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131284. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  131285. }
  131286. }else{
  131287. int iStart;
  131288. int iEnd = 0x7FFFFFFF;
  131289. for(i=0; i<pIter->nPhrase; i++){
  131290. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131291. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  131292. iEnd = pPhrase->iHead;
  131293. }
  131294. }
  131295. if( iEnd==0x7FFFFFFF ){
  131296. return 1;
  131297. }
  131298. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  131299. for(i=0; i<pIter->nPhrase; i++){
  131300. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131301. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  131302. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  131303. }
  131304. }
  131305. return 0;
  131306. }
  131307. /*
  131308. ** Retrieve information about the current candidate snippet of snippet
  131309. ** iterator pIter.
  131310. */
  131311. static void fts3SnippetDetails(
  131312. SnippetIter *pIter, /* Snippet iterator */
  131313. u64 mCovered, /* Bitmask of phrases already covered */
  131314. int *piToken, /* OUT: First token of proposed snippet */
  131315. int *piScore, /* OUT: "Score" for this snippet */
  131316. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  131317. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  131318. ){
  131319. int iStart = pIter->iCurrent; /* First token of snippet */
  131320. int iScore = 0; /* Score of this snippet */
  131321. int i; /* Loop counter */
  131322. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  131323. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  131324. for(i=0; i<pIter->nPhrase; i++){
  131325. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  131326. if( pPhrase->pTail ){
  131327. char *pCsr = pPhrase->pTail;
  131328. int iCsr = pPhrase->iTail;
  131329. while( iCsr<(iStart+pIter->nSnippet) ){
  131330. int j;
  131331. u64 mPhrase = (u64)1 << i;
  131332. u64 mPos = (u64)1 << (iCsr - iStart);
  131333. assert( iCsr>=iStart );
  131334. if( (mCover|mCovered)&mPhrase ){
  131335. iScore++;
  131336. }else{
  131337. iScore += 1000;
  131338. }
  131339. mCover |= mPhrase;
  131340. for(j=0; j<pPhrase->nToken; j++){
  131341. mHighlight |= (mPos>>j);
  131342. }
  131343. if( 0==(*pCsr & 0x0FE) ) break;
  131344. fts3GetDeltaPosition(&pCsr, &iCsr);
  131345. }
  131346. }
  131347. }
  131348. /* Set the output variables before returning. */
  131349. *piToken = iStart;
  131350. *piScore = iScore;
  131351. *pmCover = mCover;
  131352. *pmHighlight = mHighlight;
  131353. }
  131354. /*
  131355. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  131356. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  131357. */
  131358. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  131359. SnippetIter *p = (SnippetIter *)ctx;
  131360. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  131361. char *pCsr;
  131362. int rc;
  131363. pPhrase->nToken = pExpr->pPhrase->nToken;
  131364. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  131365. assert( rc==SQLITE_OK || pCsr==0 );
  131366. if( pCsr ){
  131367. int iFirst = 0;
  131368. pPhrase->pList = pCsr;
  131369. fts3GetDeltaPosition(&pCsr, &iFirst);
  131370. assert( iFirst>=0 );
  131371. pPhrase->pHead = pCsr;
  131372. pPhrase->pTail = pCsr;
  131373. pPhrase->iHead = iFirst;
  131374. pPhrase->iTail = iFirst;
  131375. }else{
  131376. assert( rc!=SQLITE_OK || (
  131377. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  131378. ));
  131379. }
  131380. return rc;
  131381. }
  131382. /*
  131383. ** Select the fragment of text consisting of nFragment contiguous tokens
  131384. ** from column iCol that represent the "best" snippet. The best snippet
  131385. ** is the snippet with the highest score, where scores are calculated
  131386. ** by adding:
  131387. **
  131388. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  131389. **
  131390. ** (b) +1000 points for the first occurrence of each matchable phrase in
  131391. ** the snippet for which the corresponding mCovered bit is not set.
  131392. **
  131393. ** The selected snippet parameters are stored in structure *pFragment before
  131394. ** returning. The score of the selected snippet is stored in *piScore
  131395. ** before returning.
  131396. */
  131397. static int fts3BestSnippet(
  131398. int nSnippet, /* Desired snippet length */
  131399. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  131400. int iCol, /* Index of column to create snippet from */
  131401. u64 mCovered, /* Mask of phrases already covered */
  131402. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  131403. SnippetFragment *pFragment, /* OUT: Best snippet found */
  131404. int *piScore /* OUT: Score of snippet pFragment */
  131405. ){
  131406. int rc; /* Return Code */
  131407. int nList; /* Number of phrases in expression */
  131408. SnippetIter sIter; /* Iterates through snippet candidates */
  131409. int nByte; /* Number of bytes of space to allocate */
  131410. int iBestScore = -1; /* Best snippet score found so far */
  131411. int i; /* Loop counter */
  131412. memset(&sIter, 0, sizeof(sIter));
  131413. /* Iterate through the phrases in the expression to count them. The same
  131414. ** callback makes sure the doclists are loaded for each phrase.
  131415. */
  131416. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  131417. if( rc!=SQLITE_OK ){
  131418. return rc;
  131419. }
  131420. /* Now that it is known how many phrases there are, allocate and zero
  131421. ** the required space using malloc().
  131422. */
  131423. nByte = sizeof(SnippetPhrase) * nList;
  131424. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  131425. if( !sIter.aPhrase ){
  131426. return SQLITE_NOMEM;
  131427. }
  131428. memset(sIter.aPhrase, 0, nByte);
  131429. /* Initialize the contents of the SnippetIter object. Then iterate through
  131430. ** the set of phrases in the expression to populate the aPhrase[] array.
  131431. */
  131432. sIter.pCsr = pCsr;
  131433. sIter.iCol = iCol;
  131434. sIter.nSnippet = nSnippet;
  131435. sIter.nPhrase = nList;
  131436. sIter.iCurrent = -1;
  131437. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  131438. /* Set the *pmSeen output variable. */
  131439. for(i=0; i<nList; i++){
  131440. if( sIter.aPhrase[i].pHead ){
  131441. *pmSeen |= (u64)1 << i;
  131442. }
  131443. }
  131444. /* Loop through all candidate snippets. Store the best snippet in
  131445. ** *pFragment. Store its associated 'score' in iBestScore.
  131446. */
  131447. pFragment->iCol = iCol;
  131448. while( !fts3SnippetNextCandidate(&sIter) ){
  131449. int iPos;
  131450. int iScore;
  131451. u64 mCover;
  131452. u64 mHighlight;
  131453. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  131454. assert( iScore>=0 );
  131455. if( iScore>iBestScore ){
  131456. pFragment->iPos = iPos;
  131457. pFragment->hlmask = mHighlight;
  131458. pFragment->covered = mCover;
  131459. iBestScore = iScore;
  131460. }
  131461. }
  131462. sqlite3_free(sIter.aPhrase);
  131463. *piScore = iBestScore;
  131464. return SQLITE_OK;
  131465. }
  131466. /*
  131467. ** Append a string to the string-buffer passed as the first argument.
  131468. **
  131469. ** If nAppend is negative, then the length of the string zAppend is
  131470. ** determined using strlen().
  131471. */
  131472. static int fts3StringAppend(
  131473. StrBuffer *pStr, /* Buffer to append to */
  131474. const char *zAppend, /* Pointer to data to append to buffer */
  131475. int nAppend /* Size of zAppend in bytes (or -1) */
  131476. ){
  131477. if( nAppend<0 ){
  131478. nAppend = (int)strlen(zAppend);
  131479. }
  131480. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  131481. ** to grow the buffer until so that it is big enough to accomadate the
  131482. ** appended data.
  131483. */
  131484. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  131485. int nAlloc = pStr->nAlloc+nAppend+100;
  131486. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  131487. if( !zNew ){
  131488. return SQLITE_NOMEM;
  131489. }
  131490. pStr->z = zNew;
  131491. pStr->nAlloc = nAlloc;
  131492. }
  131493. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  131494. /* Append the data to the string buffer. */
  131495. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  131496. pStr->n += nAppend;
  131497. pStr->z[pStr->n] = '\0';
  131498. return SQLITE_OK;
  131499. }
  131500. /*
  131501. ** The fts3BestSnippet() function often selects snippets that end with a
  131502. ** query term. That is, the final term of the snippet is always a term
  131503. ** that requires highlighting. For example, if 'X' is a highlighted term
  131504. ** and '.' is a non-highlighted term, BestSnippet() may select:
  131505. **
  131506. ** ........X.....X
  131507. **
  131508. ** This function "shifts" the beginning of the snippet forward in the
  131509. ** document so that there are approximately the same number of
  131510. ** non-highlighted terms to the right of the final highlighted term as there
  131511. ** are to the left of the first highlighted term. For example, to this:
  131512. **
  131513. ** ....X.....X....
  131514. **
  131515. ** This is done as part of extracting the snippet text, not when selecting
  131516. ** the snippet. Snippet selection is done based on doclists only, so there
  131517. ** is no way for fts3BestSnippet() to know whether or not the document
  131518. ** actually contains terms that follow the final highlighted term.
  131519. */
  131520. static int fts3SnippetShift(
  131521. Fts3Table *pTab, /* FTS3 table snippet comes from */
  131522. int iLangid, /* Language id to use in tokenizing */
  131523. int nSnippet, /* Number of tokens desired for snippet */
  131524. const char *zDoc, /* Document text to extract snippet from */
  131525. int nDoc, /* Size of buffer zDoc in bytes */
  131526. int *piPos, /* IN/OUT: First token of snippet */
  131527. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  131528. ){
  131529. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  131530. if( hlmask ){
  131531. int nLeft; /* Tokens to the left of first highlight */
  131532. int nRight; /* Tokens to the right of last highlight */
  131533. int nDesired; /* Ideal number of tokens to shift forward */
  131534. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  131535. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  131536. nDesired = (nLeft-nRight)/2;
  131537. /* Ideally, the start of the snippet should be pushed forward in the
  131538. ** document nDesired tokens. This block checks if there are actually
  131539. ** nDesired tokens to the right of the snippet. If so, *piPos and
  131540. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  131541. ** right. Otherwise, the snippet is shifted by the number of tokens
  131542. ** available.
  131543. */
  131544. if( nDesired>0 ){
  131545. int nShift; /* Number of tokens to shift snippet by */
  131546. int iCurrent = 0; /* Token counter */
  131547. int rc; /* Return Code */
  131548. sqlite3_tokenizer_module *pMod;
  131549. sqlite3_tokenizer_cursor *pC;
  131550. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  131551. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  131552. ** or more tokens in zDoc/nDoc.
  131553. */
  131554. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  131555. if( rc!=SQLITE_OK ){
  131556. return rc;
  131557. }
  131558. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  131559. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  131560. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  131561. }
  131562. pMod->xClose(pC);
  131563. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  131564. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  131565. assert( nShift<=nDesired );
  131566. if( nShift>0 ){
  131567. *piPos += nShift;
  131568. *pHlmask = hlmask >> nShift;
  131569. }
  131570. }
  131571. }
  131572. return SQLITE_OK;
  131573. }
  131574. /*
  131575. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  131576. ** append it to string buffer pOut.
  131577. */
  131578. static int fts3SnippetText(
  131579. Fts3Cursor *pCsr, /* FTS3 Cursor */
  131580. SnippetFragment *pFragment, /* Snippet to extract */
  131581. int iFragment, /* Fragment number */
  131582. int isLast, /* True for final fragment in snippet */
  131583. int nSnippet, /* Number of tokens in extracted snippet */
  131584. const char *zOpen, /* String inserted before highlighted term */
  131585. const char *zClose, /* String inserted after highlighted term */
  131586. const char *zEllipsis, /* String inserted between snippets */
  131587. StrBuffer *pOut /* Write output here */
  131588. ){
  131589. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131590. int rc; /* Return code */
  131591. const char *zDoc; /* Document text to extract snippet from */
  131592. int nDoc; /* Size of zDoc in bytes */
  131593. int iCurrent = 0; /* Current token number of document */
  131594. int iEnd = 0; /* Byte offset of end of current token */
  131595. int isShiftDone = 0; /* True after snippet is shifted */
  131596. int iPos = pFragment->iPos; /* First token of snippet */
  131597. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  131598. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  131599. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  131600. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  131601. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  131602. if( zDoc==0 ){
  131603. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  131604. return SQLITE_NOMEM;
  131605. }
  131606. return SQLITE_OK;
  131607. }
  131608. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  131609. /* Open a token cursor on the document. */
  131610. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  131611. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  131612. if( rc!=SQLITE_OK ){
  131613. return rc;
  131614. }
  131615. while( rc==SQLITE_OK ){
  131616. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  131617. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  131618. int iBegin = 0; /* Offset in zDoc of start of token */
  131619. int iFin = 0; /* Offset in zDoc of end of token */
  131620. int isHighlight = 0; /* True for highlighted terms */
  131621. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  131622. ** in the FTS code the variable that the third argument to xNext points to
  131623. ** is initialized to zero before the first (*but not necessarily
  131624. ** subsequent*) call to xNext(). This is done for a particular application
  131625. ** that needs to know whether or not the tokenizer is being used for
  131626. ** snippet generation or for some other purpose.
  131627. **
  131628. ** Extreme care is required when writing code to depend on this
  131629. ** initialization. It is not a documented part of the tokenizer interface.
  131630. ** If a tokenizer is used directly by any code outside of FTS, this
  131631. ** convention might not be respected. */
  131632. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  131633. if( rc!=SQLITE_OK ){
  131634. if( rc==SQLITE_DONE ){
  131635. /* Special case - the last token of the snippet is also the last token
  131636. ** of the column. Append any punctuation that occurred between the end
  131637. ** of the previous token and the end of the document to the output.
  131638. ** Then break out of the loop. */
  131639. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  131640. }
  131641. break;
  131642. }
  131643. if( iCurrent<iPos ){ continue; }
  131644. if( !isShiftDone ){
  131645. int n = nDoc - iBegin;
  131646. rc = fts3SnippetShift(
  131647. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  131648. );
  131649. isShiftDone = 1;
  131650. /* Now that the shift has been done, check if the initial "..." are
  131651. ** required. They are required if (a) this is not the first fragment,
  131652. ** or (b) this fragment does not begin at position 0 of its column.
  131653. */
  131654. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  131655. rc = fts3StringAppend(pOut, zEllipsis, -1);
  131656. }
  131657. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  131658. }
  131659. if( iCurrent>=(iPos+nSnippet) ){
  131660. if( isLast ){
  131661. rc = fts3StringAppend(pOut, zEllipsis, -1);
  131662. }
  131663. break;
  131664. }
  131665. /* Set isHighlight to true if this term should be highlighted. */
  131666. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  131667. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  131668. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  131669. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  131670. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  131671. iEnd = iFin;
  131672. }
  131673. pMod->xClose(pC);
  131674. return rc;
  131675. }
  131676. /*
  131677. ** This function is used to count the entries in a column-list (a
  131678. ** delta-encoded list of term offsets within a single column of a single
  131679. ** row). When this function is called, *ppCollist should point to the
  131680. ** beginning of the first varint in the column-list (the varint that
  131681. ** contains the position of the first matching term in the column data).
  131682. ** Before returning, *ppCollist is set to point to the first byte after
  131683. ** the last varint in the column-list (either the 0x00 signifying the end
  131684. ** of the position-list, or the 0x01 that precedes the column number of
  131685. ** the next column in the position-list).
  131686. **
  131687. ** The number of elements in the column-list is returned.
  131688. */
  131689. static int fts3ColumnlistCount(char **ppCollist){
  131690. char *pEnd = *ppCollist;
  131691. char c = 0;
  131692. int nEntry = 0;
  131693. /* A column-list is terminated by either a 0x01 or 0x00. */
  131694. while( 0xFE & (*pEnd | c) ){
  131695. c = *pEnd++ & 0x80;
  131696. if( !c ) nEntry++;
  131697. }
  131698. *ppCollist = pEnd;
  131699. return nEntry;
  131700. }
  131701. /*
  131702. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  131703. ** for a single query.
  131704. **
  131705. ** fts3ExprIterate() callback to load the 'global' elements of a
  131706. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  131707. ** of the matchinfo array that are constant for all rows returned by the
  131708. ** current query.
  131709. **
  131710. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  131711. ** function populates Matchinfo.aMatchinfo[] as follows:
  131712. **
  131713. ** for(iCol=0; iCol<nCol; iCol++){
  131714. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  131715. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  131716. ** }
  131717. **
  131718. ** where X is the number of matches for phrase iPhrase is column iCol of all
  131719. ** rows of the table. Y is the number of rows for which column iCol contains
  131720. ** at least one instance of phrase iPhrase.
  131721. **
  131722. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  131723. ** Y values are set to nDoc, where nDoc is the number of documents in the
  131724. ** file system. This is done because the full-text index doclist is required
  131725. ** to calculate these values properly, and the full-text index doclist is
  131726. ** not available for deferred tokens.
  131727. */
  131728. static int fts3ExprGlobalHitsCb(
  131729. Fts3Expr *pExpr, /* Phrase expression node */
  131730. int iPhrase, /* Phrase number (numbered from zero) */
  131731. void *pCtx /* Pointer to MatchInfo structure */
  131732. ){
  131733. MatchInfo *p = (MatchInfo *)pCtx;
  131734. return sqlite3Fts3EvalPhraseStats(
  131735. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  131736. );
  131737. }
  131738. /*
  131739. ** fts3ExprIterate() callback used to collect the "local" part of the
  131740. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  131741. ** array that are different for each row returned by the query.
  131742. */
  131743. static int fts3ExprLocalHitsCb(
  131744. Fts3Expr *pExpr, /* Phrase expression node */
  131745. int iPhrase, /* Phrase number */
  131746. void *pCtx /* Pointer to MatchInfo structure */
  131747. ){
  131748. int rc = SQLITE_OK;
  131749. MatchInfo *p = (MatchInfo *)pCtx;
  131750. int iStart = iPhrase * p->nCol * 3;
  131751. int i;
  131752. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  131753. char *pCsr;
  131754. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  131755. if( pCsr ){
  131756. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  131757. }else{
  131758. p->aMatchinfo[iStart+i*3] = 0;
  131759. }
  131760. }
  131761. return rc;
  131762. }
  131763. static int fts3MatchinfoCheck(
  131764. Fts3Table *pTab,
  131765. char cArg,
  131766. char **pzErr
  131767. ){
  131768. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  131769. || (cArg==FTS3_MATCHINFO_NCOL)
  131770. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  131771. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  131772. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  131773. || (cArg==FTS3_MATCHINFO_LCS)
  131774. || (cArg==FTS3_MATCHINFO_HITS)
  131775. ){
  131776. return SQLITE_OK;
  131777. }
  131778. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  131779. return SQLITE_ERROR;
  131780. }
  131781. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  131782. int nVal; /* Number of integers output by cArg */
  131783. switch( cArg ){
  131784. case FTS3_MATCHINFO_NDOC:
  131785. case FTS3_MATCHINFO_NPHRASE:
  131786. case FTS3_MATCHINFO_NCOL:
  131787. nVal = 1;
  131788. break;
  131789. case FTS3_MATCHINFO_AVGLENGTH:
  131790. case FTS3_MATCHINFO_LENGTH:
  131791. case FTS3_MATCHINFO_LCS:
  131792. nVal = pInfo->nCol;
  131793. break;
  131794. default:
  131795. assert( cArg==FTS3_MATCHINFO_HITS );
  131796. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  131797. break;
  131798. }
  131799. return nVal;
  131800. }
  131801. static int fts3MatchinfoSelectDoctotal(
  131802. Fts3Table *pTab,
  131803. sqlite3_stmt **ppStmt,
  131804. sqlite3_int64 *pnDoc,
  131805. const char **paLen
  131806. ){
  131807. sqlite3_stmt *pStmt;
  131808. const char *a;
  131809. sqlite3_int64 nDoc;
  131810. if( !*ppStmt ){
  131811. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  131812. if( rc!=SQLITE_OK ) return rc;
  131813. }
  131814. pStmt = *ppStmt;
  131815. assert( sqlite3_data_count(pStmt)==1 );
  131816. a = sqlite3_column_blob(pStmt, 0);
  131817. a += sqlite3Fts3GetVarint(a, &nDoc);
  131818. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  131819. *pnDoc = (u32)nDoc;
  131820. if( paLen ) *paLen = a;
  131821. return SQLITE_OK;
  131822. }
  131823. /*
  131824. ** An instance of the following structure is used to store state while
  131825. ** iterating through a multi-column position-list corresponding to the
  131826. ** hits for a single phrase on a single row in order to calculate the
  131827. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  131828. */
  131829. typedef struct LcsIterator LcsIterator;
  131830. struct LcsIterator {
  131831. Fts3Expr *pExpr; /* Pointer to phrase expression */
  131832. int iPosOffset; /* Tokens count up to end of this phrase */
  131833. char *pRead; /* Cursor used to iterate through aDoclist */
  131834. int iPos; /* Current position */
  131835. };
  131836. /*
  131837. ** If LcsIterator.iCol is set to the following value, the iterator has
  131838. ** finished iterating through all offsets for all columns.
  131839. */
  131840. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  131841. static int fts3MatchinfoLcsCb(
  131842. Fts3Expr *pExpr, /* Phrase expression node */
  131843. int iPhrase, /* Phrase number (numbered from zero) */
  131844. void *pCtx /* Pointer to MatchInfo structure */
  131845. ){
  131846. LcsIterator *aIter = (LcsIterator *)pCtx;
  131847. aIter[iPhrase].pExpr = pExpr;
  131848. return SQLITE_OK;
  131849. }
  131850. /*
  131851. ** Advance the iterator passed as an argument to the next position. Return
  131852. ** 1 if the iterator is at EOF or if it now points to the start of the
  131853. ** position list for the next column.
  131854. */
  131855. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  131856. char *pRead = pIter->pRead;
  131857. sqlite3_int64 iRead;
  131858. int rc = 0;
  131859. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  131860. if( iRead==0 || iRead==1 ){
  131861. pRead = 0;
  131862. rc = 1;
  131863. }else{
  131864. pIter->iPos += (int)(iRead-2);
  131865. }
  131866. pIter->pRead = pRead;
  131867. return rc;
  131868. }
  131869. /*
  131870. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  131871. **
  131872. ** If the call is successful, the longest-common-substring lengths for each
  131873. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  131874. ** array before returning. SQLITE_OK is returned in this case.
  131875. **
  131876. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  131877. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  131878. ** undefined.
  131879. */
  131880. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  131881. LcsIterator *aIter;
  131882. int i;
  131883. int iCol;
  131884. int nToken = 0;
  131885. /* Allocate and populate the array of LcsIterator objects. The array
  131886. ** contains one element for each matchable phrase in the query.
  131887. **/
  131888. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  131889. if( !aIter ) return SQLITE_NOMEM;
  131890. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  131891. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  131892. for(i=0; i<pInfo->nPhrase; i++){
  131893. LcsIterator *pIter = &aIter[i];
  131894. nToken -= pIter->pExpr->pPhrase->nToken;
  131895. pIter->iPosOffset = nToken;
  131896. }
  131897. for(iCol=0; iCol<pInfo->nCol; iCol++){
  131898. int nLcs = 0; /* LCS value for this column */
  131899. int nLive = 0; /* Number of iterators in aIter not at EOF */
  131900. for(i=0; i<pInfo->nPhrase; i++){
  131901. int rc;
  131902. LcsIterator *pIt = &aIter[i];
  131903. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  131904. if( rc!=SQLITE_OK ) return rc;
  131905. if( pIt->pRead ){
  131906. pIt->iPos = pIt->iPosOffset;
  131907. fts3LcsIteratorAdvance(&aIter[i]);
  131908. nLive++;
  131909. }
  131910. }
  131911. while( nLive>0 ){
  131912. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  131913. int nThisLcs = 0; /* LCS for the current iterator positions */
  131914. for(i=0; i<pInfo->nPhrase; i++){
  131915. LcsIterator *pIter = &aIter[i];
  131916. if( pIter->pRead==0 ){
  131917. /* This iterator is already at EOF for this column. */
  131918. nThisLcs = 0;
  131919. }else{
  131920. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  131921. pAdv = pIter;
  131922. }
  131923. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  131924. nThisLcs++;
  131925. }else{
  131926. nThisLcs = 1;
  131927. }
  131928. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  131929. }
  131930. }
  131931. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  131932. }
  131933. pInfo->aMatchinfo[iCol] = nLcs;
  131934. }
  131935. sqlite3_free(aIter);
  131936. return SQLITE_OK;
  131937. }
  131938. /*
  131939. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  131940. ** be returned by the matchinfo() function. Argument zArg contains the
  131941. ** format string passed as the second argument to matchinfo (or the
  131942. ** default value "pcx" if no second argument was specified). The format
  131943. ** string has already been validated and the pInfo->aMatchinfo[] array
  131944. ** is guaranteed to be large enough for the output.
  131945. **
  131946. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  131947. ** If it is false, then assume that those fields that do not change between
  131948. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  131949. ** have already been populated.
  131950. **
  131951. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  131952. ** occurs. If a value other than SQLITE_OK is returned, the state the
  131953. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  131954. */
  131955. static int fts3MatchinfoValues(
  131956. Fts3Cursor *pCsr, /* FTS3 cursor object */
  131957. int bGlobal, /* True to grab the global stats */
  131958. MatchInfo *pInfo, /* Matchinfo context object */
  131959. const char *zArg /* Matchinfo format string */
  131960. ){
  131961. int rc = SQLITE_OK;
  131962. int i;
  131963. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  131964. sqlite3_stmt *pSelect = 0;
  131965. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  131966. switch( zArg[i] ){
  131967. case FTS3_MATCHINFO_NPHRASE:
  131968. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  131969. break;
  131970. case FTS3_MATCHINFO_NCOL:
  131971. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  131972. break;
  131973. case FTS3_MATCHINFO_NDOC:
  131974. if( bGlobal ){
  131975. sqlite3_int64 nDoc = 0;
  131976. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  131977. pInfo->aMatchinfo[0] = (u32)nDoc;
  131978. }
  131979. break;
  131980. case FTS3_MATCHINFO_AVGLENGTH:
  131981. if( bGlobal ){
  131982. sqlite3_int64 nDoc; /* Number of rows in table */
  131983. const char *a; /* Aggregate column length array */
  131984. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  131985. if( rc==SQLITE_OK ){
  131986. int iCol;
  131987. for(iCol=0; iCol<pInfo->nCol; iCol++){
  131988. u32 iVal;
  131989. sqlite3_int64 nToken;
  131990. a += sqlite3Fts3GetVarint(a, &nToken);
  131991. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  131992. pInfo->aMatchinfo[iCol] = iVal;
  131993. }
  131994. }
  131995. }
  131996. break;
  131997. case FTS3_MATCHINFO_LENGTH: {
  131998. sqlite3_stmt *pSelectDocsize = 0;
  131999. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  132000. if( rc==SQLITE_OK ){
  132001. int iCol;
  132002. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  132003. for(iCol=0; iCol<pInfo->nCol; iCol++){
  132004. sqlite3_int64 nToken;
  132005. a += sqlite3Fts3GetVarint(a, &nToken);
  132006. pInfo->aMatchinfo[iCol] = (u32)nToken;
  132007. }
  132008. }
  132009. sqlite3_reset(pSelectDocsize);
  132010. break;
  132011. }
  132012. case FTS3_MATCHINFO_LCS:
  132013. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  132014. if( rc==SQLITE_OK ){
  132015. rc = fts3MatchinfoLcs(pCsr, pInfo);
  132016. }
  132017. break;
  132018. default: {
  132019. Fts3Expr *pExpr;
  132020. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  132021. pExpr = pCsr->pExpr;
  132022. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  132023. if( rc!=SQLITE_OK ) break;
  132024. if( bGlobal ){
  132025. if( pCsr->pDeferred ){
  132026. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  132027. if( rc!=SQLITE_OK ) break;
  132028. }
  132029. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  132030. if( rc!=SQLITE_OK ) break;
  132031. }
  132032. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  132033. break;
  132034. }
  132035. }
  132036. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  132037. }
  132038. sqlite3_reset(pSelect);
  132039. return rc;
  132040. }
  132041. /*
  132042. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  132043. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  132044. */
  132045. static int fts3GetMatchinfo(
  132046. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  132047. const char *zArg /* Second argument to matchinfo() function */
  132048. ){
  132049. MatchInfo sInfo;
  132050. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132051. int rc = SQLITE_OK;
  132052. int bGlobal = 0; /* Collect 'global' stats as well as local */
  132053. memset(&sInfo, 0, sizeof(MatchInfo));
  132054. sInfo.pCursor = pCsr;
  132055. sInfo.nCol = pTab->nColumn;
  132056. /* If there is cached matchinfo() data, but the format string for the
  132057. ** cache does not match the format string for this request, discard
  132058. ** the cached data. */
  132059. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  132060. assert( pCsr->aMatchinfo );
  132061. sqlite3_free(pCsr->aMatchinfo);
  132062. pCsr->zMatchinfo = 0;
  132063. pCsr->aMatchinfo = 0;
  132064. }
  132065. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  132066. ** matchinfo function has been called for this query. In this case
  132067. ** allocate the array used to accumulate the matchinfo data and
  132068. ** initialize those elements that are constant for every row.
  132069. */
  132070. if( pCsr->aMatchinfo==0 ){
  132071. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  132072. int nArg; /* Bytes in zArg */
  132073. int i; /* Used to iterate through zArg */
  132074. /* Determine the number of phrases in the query */
  132075. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  132076. sInfo.nPhrase = pCsr->nPhrase;
  132077. /* Determine the number of integers in the buffer returned by this call. */
  132078. for(i=0; zArg[i]; i++){
  132079. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  132080. }
  132081. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  132082. nArg = (int)strlen(zArg);
  132083. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  132084. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  132085. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  132086. pCsr->nMatchinfo = nMatchinfo;
  132087. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  132088. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  132089. pCsr->isMatchinfoNeeded = 1;
  132090. bGlobal = 1;
  132091. }
  132092. sInfo.aMatchinfo = pCsr->aMatchinfo;
  132093. sInfo.nPhrase = pCsr->nPhrase;
  132094. if( pCsr->isMatchinfoNeeded ){
  132095. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  132096. pCsr->isMatchinfoNeeded = 0;
  132097. }
  132098. return rc;
  132099. }
  132100. /*
  132101. ** Implementation of snippet() function.
  132102. */
  132103. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  132104. sqlite3_context *pCtx, /* SQLite function call context */
  132105. Fts3Cursor *pCsr, /* Cursor object */
  132106. const char *zStart, /* Snippet start text - "<b>" */
  132107. const char *zEnd, /* Snippet end text - "</b>" */
  132108. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  132109. int iCol, /* Extract snippet from this column */
  132110. int nToken /* Approximate number of tokens in snippet */
  132111. ){
  132112. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132113. int rc = SQLITE_OK;
  132114. int i;
  132115. StrBuffer res = {0, 0, 0};
  132116. /* The returned text includes up to four fragments of text extracted from
  132117. ** the data in the current row. The first iteration of the for(...) loop
  132118. ** below attempts to locate a single fragment of text nToken tokens in
  132119. ** size that contains at least one instance of all phrases in the query
  132120. ** expression that appear in the current row. If such a fragment of text
  132121. ** cannot be found, the second iteration of the loop attempts to locate
  132122. ** a pair of fragments, and so on.
  132123. */
  132124. int nSnippet = 0; /* Number of fragments in this snippet */
  132125. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  132126. int nFToken = -1; /* Number of tokens in each fragment */
  132127. if( !pCsr->pExpr ){
  132128. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  132129. return;
  132130. }
  132131. for(nSnippet=1; 1; nSnippet++){
  132132. int iSnip; /* Loop counter 0..nSnippet-1 */
  132133. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  132134. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  132135. if( nToken>=0 ){
  132136. nFToken = (nToken+nSnippet-1) / nSnippet;
  132137. }else{
  132138. nFToken = -1 * nToken;
  132139. }
  132140. for(iSnip=0; iSnip<nSnippet; iSnip++){
  132141. int iBestScore = -1; /* Best score of columns checked so far */
  132142. int iRead; /* Used to iterate through columns */
  132143. SnippetFragment *pFragment = &aSnippet[iSnip];
  132144. memset(pFragment, 0, sizeof(*pFragment));
  132145. /* Loop through all columns of the table being considered for snippets.
  132146. ** If the iCol argument to this function was negative, this means all
  132147. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  132148. */
  132149. for(iRead=0; iRead<pTab->nColumn; iRead++){
  132150. SnippetFragment sF = {0, 0, 0, 0};
  132151. int iS;
  132152. if( iCol>=0 && iRead!=iCol ) continue;
  132153. /* Find the best snippet of nFToken tokens in column iRead. */
  132154. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  132155. if( rc!=SQLITE_OK ){
  132156. goto snippet_out;
  132157. }
  132158. if( iS>iBestScore ){
  132159. *pFragment = sF;
  132160. iBestScore = iS;
  132161. }
  132162. }
  132163. mCovered |= pFragment->covered;
  132164. }
  132165. /* If all query phrases seen by fts3BestSnippet() are present in at least
  132166. ** one of the nSnippet snippet fragments, break out of the loop.
  132167. */
  132168. assert( (mCovered&mSeen)==mCovered );
  132169. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  132170. }
  132171. assert( nFToken>0 );
  132172. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  132173. rc = fts3SnippetText(pCsr, &aSnippet[i],
  132174. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  132175. );
  132176. }
  132177. snippet_out:
  132178. sqlite3Fts3SegmentsClose(pTab);
  132179. if( rc!=SQLITE_OK ){
  132180. sqlite3_result_error_code(pCtx, rc);
  132181. sqlite3_free(res.z);
  132182. }else{
  132183. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  132184. }
  132185. }
  132186. typedef struct TermOffset TermOffset;
  132187. typedef struct TermOffsetCtx TermOffsetCtx;
  132188. struct TermOffset {
  132189. char *pList; /* Position-list */
  132190. int iPos; /* Position just read from pList */
  132191. int iOff; /* Offset of this term from read positions */
  132192. };
  132193. struct TermOffsetCtx {
  132194. Fts3Cursor *pCsr;
  132195. int iCol; /* Column of table to populate aTerm for */
  132196. int iTerm;
  132197. sqlite3_int64 iDocid;
  132198. TermOffset *aTerm;
  132199. };
  132200. /*
  132201. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  132202. */
  132203. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  132204. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  132205. int nTerm; /* Number of tokens in phrase */
  132206. int iTerm; /* For looping through nTerm phrase terms */
  132207. char *pList; /* Pointer to position list for phrase */
  132208. int iPos = 0; /* First position in position-list */
  132209. int rc;
  132210. UNUSED_PARAMETER(iPhrase);
  132211. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  132212. nTerm = pExpr->pPhrase->nToken;
  132213. if( pList ){
  132214. fts3GetDeltaPosition(&pList, &iPos);
  132215. assert( iPos>=0 );
  132216. }
  132217. for(iTerm=0; iTerm<nTerm; iTerm++){
  132218. TermOffset *pT = &p->aTerm[p->iTerm++];
  132219. pT->iOff = nTerm-iTerm-1;
  132220. pT->pList = pList;
  132221. pT->iPos = iPos;
  132222. }
  132223. return rc;
  132224. }
  132225. /*
  132226. ** Implementation of offsets() function.
  132227. */
  132228. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  132229. sqlite3_context *pCtx, /* SQLite function call context */
  132230. Fts3Cursor *pCsr /* Cursor object */
  132231. ){
  132232. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132233. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  132234. int rc; /* Return Code */
  132235. int nToken; /* Number of tokens in query */
  132236. int iCol; /* Column currently being processed */
  132237. StrBuffer res = {0, 0, 0}; /* Result string */
  132238. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  132239. if( !pCsr->pExpr ){
  132240. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  132241. return;
  132242. }
  132243. memset(&sCtx, 0, sizeof(sCtx));
  132244. assert( pCsr->isRequireSeek==0 );
  132245. /* Count the number of terms in the query */
  132246. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  132247. if( rc!=SQLITE_OK ) goto offsets_out;
  132248. /* Allocate the array of TermOffset iterators. */
  132249. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  132250. if( 0==sCtx.aTerm ){
  132251. rc = SQLITE_NOMEM;
  132252. goto offsets_out;
  132253. }
  132254. sCtx.iDocid = pCsr->iPrevId;
  132255. sCtx.pCsr = pCsr;
  132256. /* Loop through the table columns, appending offset information to
  132257. ** string-buffer res for each column.
  132258. */
  132259. for(iCol=0; iCol<pTab->nColumn; iCol++){
  132260. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  132261. const char *ZDUMMY; /* Dummy argument used with xNext() */
  132262. int NDUMMY = 0; /* Dummy argument used with xNext() */
  132263. int iStart = 0;
  132264. int iEnd = 0;
  132265. int iCurrent = 0;
  132266. const char *zDoc;
  132267. int nDoc;
  132268. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  132269. ** no way that this operation can fail, so the return code from
  132270. ** fts3ExprIterate() can be discarded.
  132271. */
  132272. sCtx.iCol = iCol;
  132273. sCtx.iTerm = 0;
  132274. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  132275. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  132276. ** in column iCol, jump immediately to the next iteration of the loop.
  132277. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  132278. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  132279. ** to the caller.
  132280. */
  132281. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  132282. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  132283. if( zDoc==0 ){
  132284. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  132285. continue;
  132286. }
  132287. rc = SQLITE_NOMEM;
  132288. goto offsets_out;
  132289. }
  132290. /* Initialize a tokenizer iterator to iterate through column iCol. */
  132291. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  132292. zDoc, nDoc, &pC
  132293. );
  132294. if( rc!=SQLITE_OK ) goto offsets_out;
  132295. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  132296. while( rc==SQLITE_OK ){
  132297. int i; /* Used to loop through terms */
  132298. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  132299. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  132300. for(i=0; i<nToken; i++){
  132301. TermOffset *pT = &sCtx.aTerm[i];
  132302. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  132303. iMinPos = pT->iPos-pT->iOff;
  132304. pTerm = pT;
  132305. }
  132306. }
  132307. if( !pTerm ){
  132308. /* All offsets for this column have been gathered. */
  132309. rc = SQLITE_DONE;
  132310. }else{
  132311. assert( iCurrent<=iMinPos );
  132312. if( 0==(0xFE&*pTerm->pList) ){
  132313. pTerm->pList = 0;
  132314. }else{
  132315. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  132316. }
  132317. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  132318. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  132319. }
  132320. if( rc==SQLITE_OK ){
  132321. char aBuffer[64];
  132322. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  132323. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  132324. );
  132325. rc = fts3StringAppend(&res, aBuffer, -1);
  132326. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  132327. rc = FTS_CORRUPT_VTAB;
  132328. }
  132329. }
  132330. }
  132331. if( rc==SQLITE_DONE ){
  132332. rc = SQLITE_OK;
  132333. }
  132334. pMod->xClose(pC);
  132335. if( rc!=SQLITE_OK ) goto offsets_out;
  132336. }
  132337. offsets_out:
  132338. sqlite3_free(sCtx.aTerm);
  132339. assert( rc!=SQLITE_DONE );
  132340. sqlite3Fts3SegmentsClose(pTab);
  132341. if( rc!=SQLITE_OK ){
  132342. sqlite3_result_error_code(pCtx, rc);
  132343. sqlite3_free(res.z);
  132344. }else{
  132345. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  132346. }
  132347. return;
  132348. }
  132349. /*
  132350. ** Implementation of matchinfo() function.
  132351. */
  132352. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  132353. sqlite3_context *pContext, /* Function call context */
  132354. Fts3Cursor *pCsr, /* FTS3 table cursor */
  132355. const char *zArg /* Second arg to matchinfo() function */
  132356. ){
  132357. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  132358. int rc;
  132359. int i;
  132360. const char *zFormat;
  132361. if( zArg ){
  132362. for(i=0; zArg[i]; i++){
  132363. char *zErr = 0;
  132364. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  132365. sqlite3_result_error(pContext, zErr, -1);
  132366. sqlite3_free(zErr);
  132367. return;
  132368. }
  132369. }
  132370. zFormat = zArg;
  132371. }else{
  132372. zFormat = FTS3_MATCHINFO_DEFAULT;
  132373. }
  132374. if( !pCsr->pExpr ){
  132375. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  132376. return;
  132377. }
  132378. /* Retrieve matchinfo() data. */
  132379. rc = fts3GetMatchinfo(pCsr, zFormat);
  132380. sqlite3Fts3SegmentsClose(pTab);
  132381. if( rc!=SQLITE_OK ){
  132382. sqlite3_result_error_code(pContext, rc);
  132383. }else{
  132384. int n = pCsr->nMatchinfo * sizeof(u32);
  132385. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  132386. }
  132387. }
  132388. #endif
  132389. /************** End of fts3_snippet.c ****************************************/
  132390. /************** Begin file fts3_unicode.c ************************************/
  132391. /*
  132392. ** 2012 May 24
  132393. **
  132394. ** The author disclaims copyright to this source code. In place of
  132395. ** a legal notice, here is a blessing:
  132396. **
  132397. ** May you do good and not evil.
  132398. ** May you find forgiveness for yourself and forgive others.
  132399. ** May you share freely, never taking more than you give.
  132400. **
  132401. ******************************************************************************
  132402. **
  132403. ** Implementation of the "unicode" full-text-search tokenizer.
  132404. */
  132405. #ifdef SQLITE_ENABLE_FTS4_UNICODE61
  132406. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  132407. /* #include <assert.h> */
  132408. /* #include <stdlib.h> */
  132409. /* #include <stdio.h> */
  132410. /* #include <string.h> */
  132411. /*
  132412. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  132413. ** from the sqlite3 source file utf.c. If this file is compiled as part
  132414. ** of the amalgamation, they are not required.
  132415. */
  132416. #ifndef SQLITE_AMALGAMATION
  132417. static const unsigned char sqlite3Utf8Trans1[] = {
  132418. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132419. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  132420. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  132421. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  132422. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132423. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  132424. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  132425. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  132426. };
  132427. #define READ_UTF8(zIn, zTerm, c) \
  132428. c = *(zIn++); \
  132429. if( c>=0xc0 ){ \
  132430. c = sqlite3Utf8Trans1[c-0xc0]; \
  132431. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  132432. c = (c<<6) + (0x3f & *(zIn++)); \
  132433. } \
  132434. if( c<0x80 \
  132435. || (c&0xFFFFF800)==0xD800 \
  132436. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  132437. }
  132438. #define WRITE_UTF8(zOut, c) { \
  132439. if( c<0x00080 ){ \
  132440. *zOut++ = (u8)(c&0xFF); \
  132441. } \
  132442. else if( c<0x00800 ){ \
  132443. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  132444. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132445. } \
  132446. else if( c<0x10000 ){ \
  132447. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  132448. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  132449. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132450. }else{ \
  132451. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  132452. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  132453. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  132454. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  132455. } \
  132456. }
  132457. #endif /* ifndef SQLITE_AMALGAMATION */
  132458. typedef struct unicode_tokenizer unicode_tokenizer;
  132459. typedef struct unicode_cursor unicode_cursor;
  132460. struct unicode_tokenizer {
  132461. sqlite3_tokenizer base;
  132462. int bRemoveDiacritic;
  132463. int nException;
  132464. int *aiException;
  132465. };
  132466. struct unicode_cursor {
  132467. sqlite3_tokenizer_cursor base;
  132468. const unsigned char *aInput; /* Input text being tokenized */
  132469. int nInput; /* Size of aInput[] in bytes */
  132470. int iOff; /* Current offset within aInput[] */
  132471. int iToken; /* Index of next token to be returned */
  132472. char *zToken; /* storage for current token */
  132473. int nAlloc; /* space allocated at zToken */
  132474. };
  132475. /*
  132476. ** Destroy a tokenizer allocated by unicodeCreate().
  132477. */
  132478. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  132479. if( pTokenizer ){
  132480. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  132481. sqlite3_free(p->aiException);
  132482. sqlite3_free(p);
  132483. }
  132484. return SQLITE_OK;
  132485. }
  132486. /*
  132487. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  132488. ** statement has specified that the tokenizer for this table shall consider
  132489. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  132490. ** token characters (if bAlnum==1).
  132491. **
  132492. ** For each codepoint in the zIn/nIn string, this function checks if the
  132493. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  132494. ** If so, no action is taken. Otherwise, the codepoint is added to the
  132495. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  132496. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  132497. ** codepoints in the aiException[] array.
  132498. **
  132499. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  132500. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  132501. ** It is not possible to change the behavior of the tokenizer with respect
  132502. ** to these codepoints.
  132503. */
  132504. static int unicodeAddExceptions(
  132505. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  132506. int bAlnum, /* Replace Isalnum() return value with this */
  132507. const char *zIn, /* Array of characters to make exceptions */
  132508. int nIn /* Length of z in bytes */
  132509. ){
  132510. const unsigned char *z = (const unsigned char *)zIn;
  132511. const unsigned char *zTerm = &z[nIn];
  132512. int iCode;
  132513. int nEntry = 0;
  132514. assert( bAlnum==0 || bAlnum==1 );
  132515. while( z<zTerm ){
  132516. READ_UTF8(z, zTerm, iCode);
  132517. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  132518. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  132519. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  132520. ){
  132521. nEntry++;
  132522. }
  132523. }
  132524. if( nEntry ){
  132525. int *aNew; /* New aiException[] array */
  132526. int nNew; /* Number of valid entries in array aNew[] */
  132527. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  132528. if( aNew==0 ) return SQLITE_NOMEM;
  132529. nNew = p->nException;
  132530. z = (const unsigned char *)zIn;
  132531. while( z<zTerm ){
  132532. READ_UTF8(z, zTerm, iCode);
  132533. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  132534. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  132535. ){
  132536. int i, j;
  132537. for(i=0; i<nNew && aNew[i]<iCode; i++);
  132538. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  132539. aNew[i] = iCode;
  132540. nNew++;
  132541. }
  132542. }
  132543. p->aiException = aNew;
  132544. p->nException = nNew;
  132545. }
  132546. return SQLITE_OK;
  132547. }
  132548. /*
  132549. ** Return true if the p->aiException[] array contains the value iCode.
  132550. */
  132551. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  132552. if( p->nException>0 ){
  132553. int *a = p->aiException;
  132554. int iLo = 0;
  132555. int iHi = p->nException-1;
  132556. while( iHi>=iLo ){
  132557. int iTest = (iHi + iLo) / 2;
  132558. if( iCode==a[iTest] ){
  132559. return 1;
  132560. }else if( iCode>a[iTest] ){
  132561. iLo = iTest+1;
  132562. }else{
  132563. iHi = iTest-1;
  132564. }
  132565. }
  132566. }
  132567. return 0;
  132568. }
  132569. /*
  132570. ** Return true if, for the purposes of tokenization, codepoint iCode is
  132571. ** considered a token character (not a separator).
  132572. */
  132573. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  132574. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  132575. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  132576. }
  132577. /*
  132578. ** Create a new tokenizer instance.
  132579. */
  132580. static int unicodeCreate(
  132581. int nArg, /* Size of array argv[] */
  132582. const char * const *azArg, /* Tokenizer creation arguments */
  132583. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  132584. ){
  132585. unicode_tokenizer *pNew; /* New tokenizer object */
  132586. int i;
  132587. int rc = SQLITE_OK;
  132588. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  132589. if( pNew==NULL ) return SQLITE_NOMEM;
  132590. memset(pNew, 0, sizeof(unicode_tokenizer));
  132591. pNew->bRemoveDiacritic = 1;
  132592. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  132593. const char *z = azArg[i];
  132594. int n = strlen(z);
  132595. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  132596. pNew->bRemoveDiacritic = 1;
  132597. }
  132598. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  132599. pNew->bRemoveDiacritic = 0;
  132600. }
  132601. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  132602. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  132603. }
  132604. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  132605. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  132606. }
  132607. else{
  132608. /* Unrecognized argument */
  132609. rc = SQLITE_ERROR;
  132610. }
  132611. }
  132612. if( rc!=SQLITE_OK ){
  132613. unicodeDestroy((sqlite3_tokenizer *)pNew);
  132614. pNew = 0;
  132615. }
  132616. *pp = (sqlite3_tokenizer *)pNew;
  132617. return rc;
  132618. }
  132619. /*
  132620. ** Prepare to begin tokenizing a particular string. The input
  132621. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  132622. ** used to incrementally tokenize this string is returned in
  132623. ** *ppCursor.
  132624. */
  132625. static int unicodeOpen(
  132626. sqlite3_tokenizer *p, /* The tokenizer */
  132627. const char *aInput, /* Input string */
  132628. int nInput, /* Size of string aInput in bytes */
  132629. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  132630. ){
  132631. unicode_cursor *pCsr;
  132632. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  132633. if( pCsr==0 ){
  132634. return SQLITE_NOMEM;
  132635. }
  132636. memset(pCsr, 0, sizeof(unicode_cursor));
  132637. pCsr->aInput = (const unsigned char *)aInput;
  132638. if( aInput==0 ){
  132639. pCsr->nInput = 0;
  132640. }else if( nInput<0 ){
  132641. pCsr->nInput = (int)strlen(aInput);
  132642. }else{
  132643. pCsr->nInput = nInput;
  132644. }
  132645. *pp = &pCsr->base;
  132646. UNUSED_PARAMETER(p);
  132647. return SQLITE_OK;
  132648. }
  132649. /*
  132650. ** Close a tokenization cursor previously opened by a call to
  132651. ** simpleOpen() above.
  132652. */
  132653. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  132654. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  132655. sqlite3_free(pCsr->zToken);
  132656. sqlite3_free(pCsr);
  132657. return SQLITE_OK;
  132658. }
  132659. /*
  132660. ** Extract the next token from a tokenization cursor. The cursor must
  132661. ** have been opened by a prior call to simpleOpen().
  132662. */
  132663. static int unicodeNext(
  132664. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  132665. const char **paToken, /* OUT: Token text */
  132666. int *pnToken, /* OUT: Number of bytes at *paToken */
  132667. int *piStart, /* OUT: Starting offset of token */
  132668. int *piEnd, /* OUT: Ending offset of token */
  132669. int *piPos /* OUT: Position integer of token */
  132670. ){
  132671. unicode_cursor *pCsr = (unicode_cursor *)pC;
  132672. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  132673. int iCode;
  132674. char *zOut;
  132675. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  132676. const unsigned char *zStart = z;
  132677. const unsigned char *zEnd;
  132678. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  132679. /* Scan past any delimiter characters before the start of the next token.
  132680. ** Return SQLITE_DONE early if this takes us all the way to the end of
  132681. ** the input. */
  132682. while( z<zTerm ){
  132683. READ_UTF8(z, zTerm, iCode);
  132684. if( unicodeIsAlnum(p, iCode) ) break;
  132685. zStart = z;
  132686. }
  132687. if( zStart>=zTerm ) return SQLITE_DONE;
  132688. zOut = pCsr->zToken;
  132689. do {
  132690. int iOut;
  132691. /* Grow the output buffer if required. */
  132692. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  132693. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  132694. if( !zNew ) return SQLITE_NOMEM;
  132695. zOut = &zNew[zOut - pCsr->zToken];
  132696. pCsr->zToken = zNew;
  132697. pCsr->nAlloc += 64;
  132698. }
  132699. /* Write the folded case of the last character read to the output */
  132700. zEnd = z;
  132701. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  132702. if( iOut ){
  132703. WRITE_UTF8(zOut, iOut);
  132704. }
  132705. /* If the cursor is not at EOF, read the next character */
  132706. if( z>=zTerm ) break;
  132707. READ_UTF8(z, zTerm, iCode);
  132708. }while( unicodeIsAlnum(p, iCode)
  132709. || sqlite3FtsUnicodeIsdiacritic(iCode)
  132710. );
  132711. /* Set the output variables and return. */
  132712. pCsr->iOff = (z - pCsr->aInput);
  132713. *paToken = pCsr->zToken;
  132714. *pnToken = zOut - pCsr->zToken;
  132715. *piStart = (zStart - pCsr->aInput);
  132716. *piEnd = (zEnd - pCsr->aInput);
  132717. *piPos = pCsr->iToken++;
  132718. return SQLITE_OK;
  132719. }
  132720. /*
  132721. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  132722. ** structure for the unicode tokenizer.
  132723. */
  132724. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  132725. static const sqlite3_tokenizer_module module = {
  132726. 0,
  132727. unicodeCreate,
  132728. unicodeDestroy,
  132729. unicodeOpen,
  132730. unicodeClose,
  132731. unicodeNext,
  132732. 0,
  132733. };
  132734. *ppModule = &module;
  132735. }
  132736. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  132737. #endif /* ifndef SQLITE_ENABLE_FTS4_UNICODE61 */
  132738. /************** End of fts3_unicode.c ****************************************/
  132739. /************** Begin file fts3_unicode2.c ***********************************/
  132740. /*
  132741. ** 2012 May 25
  132742. **
  132743. ** The author disclaims copyright to this source code. In place of
  132744. ** a legal notice, here is a blessing:
  132745. **
  132746. ** May you do good and not evil.
  132747. ** May you find forgiveness for yourself and forgive others.
  132748. ** May you share freely, never taking more than you give.
  132749. **
  132750. ******************************************************************************
  132751. */
  132752. /*
  132753. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  132754. */
  132755. #if defined(SQLITE_ENABLE_FTS4_UNICODE61)
  132756. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  132757. /* #include <assert.h> */
  132758. /*
  132759. ** Return true if the argument corresponds to a unicode codepoint
  132760. ** classified as either a letter or a number. Otherwise false.
  132761. **
  132762. ** The results are undefined if the value passed to this function
  132763. ** is less than zero.
  132764. */
  132765. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  132766. /* Each unsigned integer in the following array corresponds to a contiguous
  132767. ** range of unicode codepoints that are not either letters or numbers (i.e.
  132768. ** codepoints for which this function should return 0).
  132769. **
  132770. ** The most significant 22 bits in each 32-bit value contain the first
  132771. ** codepoint in the range. The least significant 10 bits are used to store
  132772. ** the size of the range (always at least 1). In other words, the value
  132773. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  132774. ** C. It is not possible to represent a range larger than 1023 codepoints
  132775. ** using this format.
  132776. */
  132777. const static unsigned int aEntry[] = {
  132778. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  132779. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  132780. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  132781. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  132782. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  132783. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  132784. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  132785. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  132786. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  132787. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  132788. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  132789. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  132790. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  132791. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  132792. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  132793. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  132794. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  132795. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  132796. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  132797. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  132798. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  132799. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  132800. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  132801. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  132802. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  132803. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  132804. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  132805. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  132806. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  132807. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  132808. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  132809. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  132810. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  132811. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  132812. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  132813. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  132814. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  132815. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  132816. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  132817. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  132818. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  132819. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  132820. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  132821. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  132822. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  132823. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  132824. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  132825. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  132826. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  132827. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  132828. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  132829. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  132830. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  132831. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  132832. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  132833. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  132834. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  132835. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  132836. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  132837. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  132838. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  132839. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  132840. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  132841. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  132842. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  132843. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  132844. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  132845. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  132846. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  132847. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  132848. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  132849. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  132850. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  132851. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  132852. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  132853. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  132854. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  132855. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  132856. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  132857. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  132858. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  132859. 0x380400F0,
  132860. };
  132861. static const unsigned int aAscii[4] = {
  132862. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  132863. };
  132864. if( c<128 ){
  132865. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  132866. }else if( c<(1<<22) ){
  132867. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  132868. int iRes;
  132869. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  132870. int iLo = 0;
  132871. while( iHi>=iLo ){
  132872. int iTest = (iHi + iLo) / 2;
  132873. if( key >= aEntry[iTest] ){
  132874. iRes = iTest;
  132875. iLo = iTest+1;
  132876. }else{
  132877. iHi = iTest-1;
  132878. }
  132879. }
  132880. assert( aEntry[0]<key );
  132881. assert( key>=aEntry[iRes] );
  132882. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  132883. }
  132884. return 1;
  132885. }
  132886. /*
  132887. ** If the argument is a codepoint corresponding to a lowercase letter
  132888. ** in the ASCII range with a diacritic added, return the codepoint
  132889. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  132890. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  132891. ** E"). The resuls of passing a codepoint that corresponds to an
  132892. ** uppercase letter are undefined.
  132893. */
  132894. static int remove_diacritic(int c){
  132895. unsigned short aDia[] = {
  132896. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  132897. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  132898. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  132899. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  132900. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  132901. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  132902. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  132903. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  132904. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  132905. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  132906. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  132907. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  132908. 62924, 63050, 63082, 63274, 63390,
  132909. };
  132910. char aChar[] = {
  132911. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  132912. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  132913. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  132914. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  132915. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  132916. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  132917. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  132918. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  132919. 'e', 'i', 'o', 'u', 'y',
  132920. };
  132921. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  132922. int iRes = 0;
  132923. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  132924. int iLo = 0;
  132925. while( iHi>=iLo ){
  132926. int iTest = (iHi + iLo) / 2;
  132927. if( key >= aDia[iTest] ){
  132928. iRes = iTest;
  132929. iLo = iTest+1;
  132930. }else{
  132931. iHi = iTest-1;
  132932. }
  132933. }
  132934. assert( key>=aDia[iRes] );
  132935. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  132936. };
  132937. /*
  132938. ** Return true if the argument interpreted as a unicode codepoint
  132939. ** is a diacritical modifier character.
  132940. */
  132941. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  132942. unsigned int mask0 = 0x08029FDF;
  132943. unsigned int mask1 = 0x000361F8;
  132944. if( c<768 || c>817 ) return 0;
  132945. return (c < 768+32) ?
  132946. (mask0 & (1 << (c-768))) :
  132947. (mask1 & (1 << (c-768-32)));
  132948. }
  132949. /*
  132950. ** Interpret the argument as a unicode codepoint. If the codepoint
  132951. ** is an upper case character that has a lower case equivalent,
  132952. ** return the codepoint corresponding to the lower case version.
  132953. ** Otherwise, return a copy of the argument.
  132954. **
  132955. ** The results are undefined if the value passed to this function
  132956. ** is less than zero.
  132957. */
  132958. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  132959. /* Each entry in the following array defines a rule for folding a range
  132960. ** of codepoints to lower case. The rule applies to a range of nRange
  132961. ** codepoints starting at codepoint iCode.
  132962. **
  132963. ** If the least significant bit in flags is clear, then the rule applies
  132964. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  132965. ** need to be folded). Or, if it is set, then the rule only applies to
  132966. ** every second codepoint in the range, starting with codepoint C.
  132967. **
  132968. ** The 7 most significant bits in flags are an index into the aiOff[]
  132969. ** array. If a specific codepoint C does require folding, then its lower
  132970. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  132971. **
  132972. ** The contents of this array are generated by parsing the CaseFolding.txt
  132973. ** file distributed as part of the "Unicode Character Database". See
  132974. ** http://www.unicode.org for details.
  132975. */
  132976. static const struct TableEntry {
  132977. unsigned short iCode;
  132978. unsigned char flags;
  132979. unsigned char nRange;
  132980. } aEntry[] = {
  132981. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  132982. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  132983. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  132984. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  132985. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  132986. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  132987. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  132988. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  132989. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  132990. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  132991. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  132992. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  132993. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  132994. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  132995. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  132996. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  132997. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  132998. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  132999. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  133000. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  133001. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  133002. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  133003. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  133004. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  133005. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  133006. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  133007. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  133008. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  133009. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  133010. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  133011. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  133012. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  133013. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  133014. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  133015. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  133016. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  133017. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  133018. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  133019. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  133020. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  133021. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  133022. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  133023. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  133024. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  133025. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  133026. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  133027. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  133028. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  133029. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  133030. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  133031. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  133032. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  133033. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  133034. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  133035. {65313, 14, 26},
  133036. };
  133037. static const unsigned short aiOff[] = {
  133038. 1, 2, 8, 15, 16, 26, 28, 32,
  133039. 37, 38, 40, 48, 63, 64, 69, 71,
  133040. 79, 80, 116, 202, 203, 205, 206, 207,
  133041. 209, 210, 211, 213, 214, 217, 218, 219,
  133042. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  133043. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  133044. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  133045. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  133046. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  133047. 65514, 65521, 65527, 65528, 65529,
  133048. };
  133049. int ret = c;
  133050. assert( c>=0 );
  133051. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  133052. if( c<128 ){
  133053. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  133054. }else if( c<65536 ){
  133055. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  133056. int iLo = 0;
  133057. int iRes = -1;
  133058. while( iHi>=iLo ){
  133059. int iTest = (iHi + iLo) / 2;
  133060. int cmp = (c - aEntry[iTest].iCode);
  133061. if( cmp>=0 ){
  133062. iRes = iTest;
  133063. iLo = iTest+1;
  133064. }else{
  133065. iHi = iTest-1;
  133066. }
  133067. }
  133068. assert( iRes<0 || c>=aEntry[iRes].iCode );
  133069. if( iRes>=0 ){
  133070. const struct TableEntry *p = &aEntry[iRes];
  133071. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  133072. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  133073. assert( ret>0 );
  133074. }
  133075. }
  133076. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  133077. }
  133078. else if( c>=66560 && c<66600 ){
  133079. ret = c + 40;
  133080. }
  133081. return ret;
  133082. }
  133083. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  133084. #endif /* !defined(SQLITE_ENABLE_FTS4_UNICODE61) */
  133085. /************** End of fts3_unicode2.c ***************************************/
  133086. /************** Begin file rtree.c *******************************************/
  133087. /*
  133088. ** 2001 September 15
  133089. **
  133090. ** The author disclaims copyright to this source code. In place of
  133091. ** a legal notice, here is a blessing:
  133092. **
  133093. ** May you do good and not evil.
  133094. ** May you find forgiveness for yourself and forgive others.
  133095. ** May you share freely, never taking more than you give.
  133096. **
  133097. *************************************************************************
  133098. ** This file contains code for implementations of the r-tree and r*-tree
  133099. ** algorithms packaged as an SQLite virtual table module.
  133100. */
  133101. /*
  133102. ** Database Format of R-Tree Tables
  133103. ** --------------------------------
  133104. **
  133105. ** The data structure for a single virtual r-tree table is stored in three
  133106. ** native SQLite tables declared as follows. In each case, the '%' character
  133107. ** in the table name is replaced with the user-supplied name of the r-tree
  133108. ** table.
  133109. **
  133110. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  133111. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  133112. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  133113. **
  133114. ** The data for each node of the r-tree structure is stored in the %_node
  133115. ** table. For each node that is not the root node of the r-tree, there is
  133116. ** an entry in the %_parent table associating the node with its parent.
  133117. ** And for each row of data in the table, there is an entry in the %_rowid
  133118. ** table that maps from the entries rowid to the id of the node that it
  133119. ** is stored on.
  133120. **
  133121. ** The root node of an r-tree always exists, even if the r-tree table is
  133122. ** empty. The nodeno of the root node is always 1. All other nodes in the
  133123. ** table must be the same size as the root node. The content of each node
  133124. ** is formatted as follows:
  133125. **
  133126. ** 1. If the node is the root node (node 1), then the first 2 bytes
  133127. ** of the node contain the tree depth as a big-endian integer.
  133128. ** For non-root nodes, the first 2 bytes are left unused.
  133129. **
  133130. ** 2. The next 2 bytes contain the number of entries currently
  133131. ** stored in the node.
  133132. **
  133133. ** 3. The remainder of the node contains the node entries. Each entry
  133134. ** consists of a single 8-byte integer followed by an even number
  133135. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  133136. ** of a record. For internal nodes it is the node number of a
  133137. ** child page.
  133138. */
  133139. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  133140. /*
  133141. ** This file contains an implementation of a couple of different variants
  133142. ** of the r-tree algorithm. See the README file for further details. The
  133143. ** same data-structure is used for all, but the algorithms for insert and
  133144. ** delete operations vary. The variants used are selected at compile time
  133145. ** by defining the following symbols:
  133146. */
  133147. /* Either, both or none of the following may be set to activate
  133148. ** r*tree variant algorithms.
  133149. */
  133150. #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
  133151. #define VARIANT_RSTARTREE_REINSERT 1
  133152. /*
  133153. ** Exactly one of the following must be set to 1.
  133154. */
  133155. #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
  133156. #define VARIANT_GUTTMAN_LINEAR_SPLIT 0
  133157. #define VARIANT_RSTARTREE_SPLIT 1
  133158. #define VARIANT_GUTTMAN_SPLIT \
  133159. (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
  133160. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  133161. #define PickNext QuadraticPickNext
  133162. #define PickSeeds QuadraticPickSeeds
  133163. #define AssignCells splitNodeGuttman
  133164. #endif
  133165. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  133166. #define PickNext LinearPickNext
  133167. #define PickSeeds LinearPickSeeds
  133168. #define AssignCells splitNodeGuttman
  133169. #endif
  133170. #if VARIANT_RSTARTREE_SPLIT
  133171. #define AssignCells splitNodeStartree
  133172. #endif
  133173. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  133174. # define NDEBUG 1
  133175. #endif
  133176. #ifndef SQLITE_CORE
  133177. SQLITE_EXTENSION_INIT1
  133178. #else
  133179. #endif
  133180. /* #include <string.h> */
  133181. /* #include <assert.h> */
  133182. #ifndef SQLITE_AMALGAMATION
  133183. #include "sqlite3rtree.h"
  133184. typedef sqlite3_int64 i64;
  133185. typedef unsigned char u8;
  133186. typedef unsigned int u32;
  133187. #endif
  133188. /* The following macro is used to suppress compiler warnings.
  133189. */
  133190. #ifndef UNUSED_PARAMETER
  133191. # define UNUSED_PARAMETER(x) (void)(x)
  133192. #endif
  133193. typedef struct Rtree Rtree;
  133194. typedef struct RtreeCursor RtreeCursor;
  133195. typedef struct RtreeNode RtreeNode;
  133196. typedef struct RtreeCell RtreeCell;
  133197. typedef struct RtreeConstraint RtreeConstraint;
  133198. typedef struct RtreeMatchArg RtreeMatchArg;
  133199. typedef struct RtreeGeomCallback RtreeGeomCallback;
  133200. typedef union RtreeCoord RtreeCoord;
  133201. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  133202. #define RTREE_MAX_DIMENSIONS 5
  133203. /* Size of hash table Rtree.aHash. This hash table is not expected to
  133204. ** ever contain very many entries, so a fixed number of buckets is
  133205. ** used.
  133206. */
  133207. #define HASHSIZE 128
  133208. /*
  133209. ** An rtree virtual-table object.
  133210. */
  133211. struct Rtree {
  133212. sqlite3_vtab base;
  133213. sqlite3 *db; /* Host database connection */
  133214. int iNodeSize; /* Size in bytes of each node in the node table */
  133215. int nDim; /* Number of dimensions */
  133216. int nBytesPerCell; /* Bytes consumed per cell */
  133217. int iDepth; /* Current depth of the r-tree structure */
  133218. char *zDb; /* Name of database containing r-tree table */
  133219. char *zName; /* Name of r-tree table */
  133220. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  133221. int nBusy; /* Current number of users of this structure */
  133222. /* List of nodes removed during a CondenseTree operation. List is
  133223. ** linked together via the pointer normally used for hash chains -
  133224. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  133225. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  133226. */
  133227. RtreeNode *pDeleted;
  133228. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  133229. /* Statements to read/write/delete a record from xxx_node */
  133230. sqlite3_stmt *pReadNode;
  133231. sqlite3_stmt *pWriteNode;
  133232. sqlite3_stmt *pDeleteNode;
  133233. /* Statements to read/write/delete a record from xxx_rowid */
  133234. sqlite3_stmt *pReadRowid;
  133235. sqlite3_stmt *pWriteRowid;
  133236. sqlite3_stmt *pDeleteRowid;
  133237. /* Statements to read/write/delete a record from xxx_parent */
  133238. sqlite3_stmt *pReadParent;
  133239. sqlite3_stmt *pWriteParent;
  133240. sqlite3_stmt *pDeleteParent;
  133241. int eCoordType;
  133242. };
  133243. /* Possible values for eCoordType: */
  133244. #define RTREE_COORD_REAL32 0
  133245. #define RTREE_COORD_INT32 1
  133246. /*
  133247. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  133248. ** only deal with integer coordinates. No floating point operations
  133249. ** will be done.
  133250. */
  133251. #ifdef SQLITE_RTREE_INT_ONLY
  133252. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  133253. typedef int RtreeValue; /* Low accuracy coordinate */
  133254. #else
  133255. typedef double RtreeDValue; /* High accuracy coordinate */
  133256. typedef float RtreeValue; /* Low accuracy coordinate */
  133257. #endif
  133258. /*
  133259. ** The minimum number of cells allowed for a node is a third of the
  133260. ** maximum. In Gutman's notation:
  133261. **
  133262. ** m = M/3
  133263. **
  133264. ** If an R*-tree "Reinsert" operation is required, the same number of
  133265. ** cells are removed from the overfull node and reinserted into the tree.
  133266. */
  133267. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  133268. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  133269. #define RTREE_MAXCELLS 51
  133270. /*
  133271. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  133272. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  133273. ** Therefore all non-root nodes must contain at least 3 entries. Since
  133274. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  133275. ** 40 or less.
  133276. */
  133277. #define RTREE_MAX_DEPTH 40
  133278. /*
  133279. ** An rtree cursor object.
  133280. */
  133281. struct RtreeCursor {
  133282. sqlite3_vtab_cursor base;
  133283. RtreeNode *pNode; /* Node cursor is currently pointing at */
  133284. int iCell; /* Index of current cell in pNode */
  133285. int iStrategy; /* Copy of idxNum search parameter */
  133286. int nConstraint; /* Number of entries in aConstraint */
  133287. RtreeConstraint *aConstraint; /* Search constraints. */
  133288. };
  133289. union RtreeCoord {
  133290. RtreeValue f;
  133291. int i;
  133292. };
  133293. /*
  133294. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  133295. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  133296. ** variable pRtree points to the Rtree structure associated with the
  133297. ** RtreeCoord.
  133298. */
  133299. #ifdef SQLITE_RTREE_INT_ONLY
  133300. # define DCOORD(coord) ((RtreeDValue)coord.i)
  133301. #else
  133302. # define DCOORD(coord) ( \
  133303. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  133304. ((double)coord.f) : \
  133305. ((double)coord.i) \
  133306. )
  133307. #endif
  133308. /*
  133309. ** A search constraint.
  133310. */
  133311. struct RtreeConstraint {
  133312. int iCoord; /* Index of constrained coordinate */
  133313. int op; /* Constraining operation */
  133314. RtreeDValue rValue; /* Constraint value. */
  133315. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  133316. sqlite3_rtree_geometry *pGeom; /* Constraint callback argument for a MATCH */
  133317. };
  133318. /* Possible values for RtreeConstraint.op */
  133319. #define RTREE_EQ 0x41
  133320. #define RTREE_LE 0x42
  133321. #define RTREE_LT 0x43
  133322. #define RTREE_GE 0x44
  133323. #define RTREE_GT 0x45
  133324. #define RTREE_MATCH 0x46
  133325. /*
  133326. ** An rtree structure node.
  133327. */
  133328. struct RtreeNode {
  133329. RtreeNode *pParent; /* Parent node */
  133330. i64 iNode;
  133331. int nRef;
  133332. int isDirty;
  133333. u8 *zData;
  133334. RtreeNode *pNext; /* Next node in this hash chain */
  133335. };
  133336. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  133337. /*
  133338. ** Structure to store a deserialized rtree record.
  133339. */
  133340. struct RtreeCell {
  133341. i64 iRowid;
  133342. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
  133343. };
  133344. /*
  133345. ** Value for the first field of every RtreeMatchArg object. The MATCH
  133346. ** operator tests that the first field of a blob operand matches this
  133347. ** value to avoid operating on invalid blobs (which could cause a segfault).
  133348. */
  133349. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  133350. /*
  133351. ** An instance of this structure must be supplied as a blob argument to
  133352. ** the right-hand-side of an SQL MATCH operator used to constrain an
  133353. ** r-tree query.
  133354. */
  133355. struct RtreeMatchArg {
  133356. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  133357. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue*, int *);
  133358. void *pContext;
  133359. int nParam;
  133360. RtreeDValue aParam[1];
  133361. };
  133362. /*
  133363. ** When a geometry callback is created (see sqlite3_rtree_geometry_callback),
  133364. ** a single instance of the following structure is allocated. It is used
  133365. ** as the context for the user-function created by by s_r_g_c(). The object
  133366. ** is eventually deleted by the destructor mechanism provided by
  133367. ** sqlite3_create_function_v2() (which is called by s_r_g_c() to create
  133368. ** the geometry callback function).
  133369. */
  133370. struct RtreeGeomCallback {
  133371. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  133372. void *pContext;
  133373. };
  133374. #ifndef MAX
  133375. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  133376. #endif
  133377. #ifndef MIN
  133378. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  133379. #endif
  133380. /*
  133381. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  133382. ** 64 bit integer. The deserialized value is returned.
  133383. */
  133384. static int readInt16(u8 *p){
  133385. return (p[0]<<8) + p[1];
  133386. }
  133387. static void readCoord(u8 *p, RtreeCoord *pCoord){
  133388. u32 i = (
  133389. (((u32)p[0]) << 24) +
  133390. (((u32)p[1]) << 16) +
  133391. (((u32)p[2]) << 8) +
  133392. (((u32)p[3]) << 0)
  133393. );
  133394. *(u32 *)pCoord = i;
  133395. }
  133396. static i64 readInt64(u8 *p){
  133397. return (
  133398. (((i64)p[0]) << 56) +
  133399. (((i64)p[1]) << 48) +
  133400. (((i64)p[2]) << 40) +
  133401. (((i64)p[3]) << 32) +
  133402. (((i64)p[4]) << 24) +
  133403. (((i64)p[5]) << 16) +
  133404. (((i64)p[6]) << 8) +
  133405. (((i64)p[7]) << 0)
  133406. );
  133407. }
  133408. /*
  133409. ** Functions to serialize a 16 bit integer, 32 bit real number and
  133410. ** 64 bit integer. The value returned is the number of bytes written
  133411. ** to the argument buffer (always 2, 4 and 8 respectively).
  133412. */
  133413. static int writeInt16(u8 *p, int i){
  133414. p[0] = (i>> 8)&0xFF;
  133415. p[1] = (i>> 0)&0xFF;
  133416. return 2;
  133417. }
  133418. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  133419. u32 i;
  133420. assert( sizeof(RtreeCoord)==4 );
  133421. assert( sizeof(u32)==4 );
  133422. i = *(u32 *)pCoord;
  133423. p[0] = (i>>24)&0xFF;
  133424. p[1] = (i>>16)&0xFF;
  133425. p[2] = (i>> 8)&0xFF;
  133426. p[3] = (i>> 0)&0xFF;
  133427. return 4;
  133428. }
  133429. static int writeInt64(u8 *p, i64 i){
  133430. p[0] = (i>>56)&0xFF;
  133431. p[1] = (i>>48)&0xFF;
  133432. p[2] = (i>>40)&0xFF;
  133433. p[3] = (i>>32)&0xFF;
  133434. p[4] = (i>>24)&0xFF;
  133435. p[5] = (i>>16)&0xFF;
  133436. p[6] = (i>> 8)&0xFF;
  133437. p[7] = (i>> 0)&0xFF;
  133438. return 8;
  133439. }
  133440. /*
  133441. ** Increment the reference count of node p.
  133442. */
  133443. static void nodeReference(RtreeNode *p){
  133444. if( p ){
  133445. p->nRef++;
  133446. }
  133447. }
  133448. /*
  133449. ** Clear the content of node p (set all bytes to 0x00).
  133450. */
  133451. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  133452. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  133453. p->isDirty = 1;
  133454. }
  133455. /*
  133456. ** Given a node number iNode, return the corresponding key to use
  133457. ** in the Rtree.aHash table.
  133458. */
  133459. static int nodeHash(i64 iNode){
  133460. return (
  133461. (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^
  133462. (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
  133463. ) % HASHSIZE;
  133464. }
  133465. /*
  133466. ** Search the node hash table for node iNode. If found, return a pointer
  133467. ** to it. Otherwise, return 0.
  133468. */
  133469. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  133470. RtreeNode *p;
  133471. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  133472. return p;
  133473. }
  133474. /*
  133475. ** Add node pNode to the node hash table.
  133476. */
  133477. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  133478. int iHash;
  133479. assert( pNode->pNext==0 );
  133480. iHash = nodeHash(pNode->iNode);
  133481. pNode->pNext = pRtree->aHash[iHash];
  133482. pRtree->aHash[iHash] = pNode;
  133483. }
  133484. /*
  133485. ** Remove node pNode from the node hash table.
  133486. */
  133487. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  133488. RtreeNode **pp;
  133489. if( pNode->iNode!=0 ){
  133490. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  133491. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  133492. *pp = pNode->pNext;
  133493. pNode->pNext = 0;
  133494. }
  133495. }
  133496. /*
  133497. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  133498. ** indicating that node has not yet been assigned a node number. It is
  133499. ** assigned a node number when nodeWrite() is called to write the
  133500. ** node contents out to the database.
  133501. */
  133502. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  133503. RtreeNode *pNode;
  133504. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  133505. if( pNode ){
  133506. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  133507. pNode->zData = (u8 *)&pNode[1];
  133508. pNode->nRef = 1;
  133509. pNode->pParent = pParent;
  133510. pNode->isDirty = 1;
  133511. nodeReference(pParent);
  133512. }
  133513. return pNode;
  133514. }
  133515. /*
  133516. ** Obtain a reference to an r-tree node.
  133517. */
  133518. static int
  133519. nodeAcquire(
  133520. Rtree *pRtree, /* R-tree structure */
  133521. i64 iNode, /* Node number to load */
  133522. RtreeNode *pParent, /* Either the parent node or NULL */
  133523. RtreeNode **ppNode /* OUT: Acquired node */
  133524. ){
  133525. int rc;
  133526. int rc2 = SQLITE_OK;
  133527. RtreeNode *pNode;
  133528. /* Check if the requested node is already in the hash table. If so,
  133529. ** increase its reference count and return it.
  133530. */
  133531. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  133532. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  133533. if( pParent && !pNode->pParent ){
  133534. nodeReference(pParent);
  133535. pNode->pParent = pParent;
  133536. }
  133537. pNode->nRef++;
  133538. *ppNode = pNode;
  133539. return SQLITE_OK;
  133540. }
  133541. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  133542. rc = sqlite3_step(pRtree->pReadNode);
  133543. if( rc==SQLITE_ROW ){
  133544. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  133545. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  133546. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  133547. if( !pNode ){
  133548. rc2 = SQLITE_NOMEM;
  133549. }else{
  133550. pNode->pParent = pParent;
  133551. pNode->zData = (u8 *)&pNode[1];
  133552. pNode->nRef = 1;
  133553. pNode->iNode = iNode;
  133554. pNode->isDirty = 0;
  133555. pNode->pNext = 0;
  133556. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  133557. nodeReference(pParent);
  133558. }
  133559. }
  133560. }
  133561. rc = sqlite3_reset(pRtree->pReadNode);
  133562. if( rc==SQLITE_OK ) rc = rc2;
  133563. /* If the root node was just loaded, set pRtree->iDepth to the height
  133564. ** of the r-tree structure. A height of zero means all data is stored on
  133565. ** the root node. A height of one means the children of the root node
  133566. ** are the leaves, and so on. If the depth as specified on the root node
  133567. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  133568. */
  133569. if( pNode && iNode==1 ){
  133570. pRtree->iDepth = readInt16(pNode->zData);
  133571. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  133572. rc = SQLITE_CORRUPT_VTAB;
  133573. }
  133574. }
  133575. /* If no error has occurred so far, check if the "number of entries"
  133576. ** field on the node is too large. If so, set the return code to
  133577. ** SQLITE_CORRUPT_VTAB.
  133578. */
  133579. if( pNode && rc==SQLITE_OK ){
  133580. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  133581. rc = SQLITE_CORRUPT_VTAB;
  133582. }
  133583. }
  133584. if( rc==SQLITE_OK ){
  133585. if( pNode!=0 ){
  133586. nodeHashInsert(pRtree, pNode);
  133587. }else{
  133588. rc = SQLITE_CORRUPT_VTAB;
  133589. }
  133590. *ppNode = pNode;
  133591. }else{
  133592. sqlite3_free(pNode);
  133593. *ppNode = 0;
  133594. }
  133595. return rc;
  133596. }
  133597. /*
  133598. ** Overwrite cell iCell of node pNode with the contents of pCell.
  133599. */
  133600. static void nodeOverwriteCell(
  133601. Rtree *pRtree,
  133602. RtreeNode *pNode,
  133603. RtreeCell *pCell,
  133604. int iCell
  133605. ){
  133606. int ii;
  133607. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  133608. p += writeInt64(p, pCell->iRowid);
  133609. for(ii=0; ii<(pRtree->nDim*2); ii++){
  133610. p += writeCoord(p, &pCell->aCoord[ii]);
  133611. }
  133612. pNode->isDirty = 1;
  133613. }
  133614. /*
  133615. ** Remove cell the cell with index iCell from node pNode.
  133616. */
  133617. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  133618. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  133619. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  133620. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  133621. memmove(pDst, pSrc, nByte);
  133622. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  133623. pNode->isDirty = 1;
  133624. }
  133625. /*
  133626. ** Insert the contents of cell pCell into node pNode. If the insert
  133627. ** is successful, return SQLITE_OK.
  133628. **
  133629. ** If there is not enough free space in pNode, return SQLITE_FULL.
  133630. */
  133631. static int
  133632. nodeInsertCell(
  133633. Rtree *pRtree,
  133634. RtreeNode *pNode,
  133635. RtreeCell *pCell
  133636. ){
  133637. int nCell; /* Current number of cells in pNode */
  133638. int nMaxCell; /* Maximum number of cells for pNode */
  133639. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  133640. nCell = NCELL(pNode);
  133641. assert( nCell<=nMaxCell );
  133642. if( nCell<nMaxCell ){
  133643. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  133644. writeInt16(&pNode->zData[2], nCell+1);
  133645. pNode->isDirty = 1;
  133646. }
  133647. return (nCell==nMaxCell);
  133648. }
  133649. /*
  133650. ** If the node is dirty, write it out to the database.
  133651. */
  133652. static int
  133653. nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  133654. int rc = SQLITE_OK;
  133655. if( pNode->isDirty ){
  133656. sqlite3_stmt *p = pRtree->pWriteNode;
  133657. if( pNode->iNode ){
  133658. sqlite3_bind_int64(p, 1, pNode->iNode);
  133659. }else{
  133660. sqlite3_bind_null(p, 1);
  133661. }
  133662. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  133663. sqlite3_step(p);
  133664. pNode->isDirty = 0;
  133665. rc = sqlite3_reset(p);
  133666. if( pNode->iNode==0 && rc==SQLITE_OK ){
  133667. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  133668. nodeHashInsert(pRtree, pNode);
  133669. }
  133670. }
  133671. return rc;
  133672. }
  133673. /*
  133674. ** Release a reference to a node. If the node is dirty and the reference
  133675. ** count drops to zero, the node data is written to the database.
  133676. */
  133677. static int
  133678. nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  133679. int rc = SQLITE_OK;
  133680. if( pNode ){
  133681. assert( pNode->nRef>0 );
  133682. pNode->nRef--;
  133683. if( pNode->nRef==0 ){
  133684. if( pNode->iNode==1 ){
  133685. pRtree->iDepth = -1;
  133686. }
  133687. if( pNode->pParent ){
  133688. rc = nodeRelease(pRtree, pNode->pParent);
  133689. }
  133690. if( rc==SQLITE_OK ){
  133691. rc = nodeWrite(pRtree, pNode);
  133692. }
  133693. nodeHashDelete(pRtree, pNode);
  133694. sqlite3_free(pNode);
  133695. }
  133696. }
  133697. return rc;
  133698. }
  133699. /*
  133700. ** Return the 64-bit integer value associated with cell iCell of
  133701. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  133702. ** an internal node, then the 64-bit integer is a child page number.
  133703. */
  133704. static i64 nodeGetRowid(
  133705. Rtree *pRtree,
  133706. RtreeNode *pNode,
  133707. int iCell
  133708. ){
  133709. assert( iCell<NCELL(pNode) );
  133710. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  133711. }
  133712. /*
  133713. ** Return coordinate iCoord from cell iCell in node pNode.
  133714. */
  133715. static void nodeGetCoord(
  133716. Rtree *pRtree,
  133717. RtreeNode *pNode,
  133718. int iCell,
  133719. int iCoord,
  133720. RtreeCoord *pCoord /* Space to write result to */
  133721. ){
  133722. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  133723. }
  133724. /*
  133725. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  133726. ** to by pCell with the results.
  133727. */
  133728. static void nodeGetCell(
  133729. Rtree *pRtree,
  133730. RtreeNode *pNode,
  133731. int iCell,
  133732. RtreeCell *pCell
  133733. ){
  133734. int ii;
  133735. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  133736. for(ii=0; ii<pRtree->nDim*2; ii++){
  133737. nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
  133738. }
  133739. }
  133740. /* Forward declaration for the function that does the work of
  133741. ** the virtual table module xCreate() and xConnect() methods.
  133742. */
  133743. static int rtreeInit(
  133744. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  133745. );
  133746. /*
  133747. ** Rtree virtual table module xCreate method.
  133748. */
  133749. static int rtreeCreate(
  133750. sqlite3 *db,
  133751. void *pAux,
  133752. int argc, const char *const*argv,
  133753. sqlite3_vtab **ppVtab,
  133754. char **pzErr
  133755. ){
  133756. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  133757. }
  133758. /*
  133759. ** Rtree virtual table module xConnect method.
  133760. */
  133761. static int rtreeConnect(
  133762. sqlite3 *db,
  133763. void *pAux,
  133764. int argc, const char *const*argv,
  133765. sqlite3_vtab **ppVtab,
  133766. char **pzErr
  133767. ){
  133768. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  133769. }
  133770. /*
  133771. ** Increment the r-tree reference count.
  133772. */
  133773. static void rtreeReference(Rtree *pRtree){
  133774. pRtree->nBusy++;
  133775. }
  133776. /*
  133777. ** Decrement the r-tree reference count. When the reference count reaches
  133778. ** zero the structure is deleted.
  133779. */
  133780. static void rtreeRelease(Rtree *pRtree){
  133781. pRtree->nBusy--;
  133782. if( pRtree->nBusy==0 ){
  133783. sqlite3_finalize(pRtree->pReadNode);
  133784. sqlite3_finalize(pRtree->pWriteNode);
  133785. sqlite3_finalize(pRtree->pDeleteNode);
  133786. sqlite3_finalize(pRtree->pReadRowid);
  133787. sqlite3_finalize(pRtree->pWriteRowid);
  133788. sqlite3_finalize(pRtree->pDeleteRowid);
  133789. sqlite3_finalize(pRtree->pReadParent);
  133790. sqlite3_finalize(pRtree->pWriteParent);
  133791. sqlite3_finalize(pRtree->pDeleteParent);
  133792. sqlite3_free(pRtree);
  133793. }
  133794. }
  133795. /*
  133796. ** Rtree virtual table module xDisconnect method.
  133797. */
  133798. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  133799. rtreeRelease((Rtree *)pVtab);
  133800. return SQLITE_OK;
  133801. }
  133802. /*
  133803. ** Rtree virtual table module xDestroy method.
  133804. */
  133805. static int rtreeDestroy(sqlite3_vtab *pVtab){
  133806. Rtree *pRtree = (Rtree *)pVtab;
  133807. int rc;
  133808. char *zCreate = sqlite3_mprintf(
  133809. "DROP TABLE '%q'.'%q_node';"
  133810. "DROP TABLE '%q'.'%q_rowid';"
  133811. "DROP TABLE '%q'.'%q_parent';",
  133812. pRtree->zDb, pRtree->zName,
  133813. pRtree->zDb, pRtree->zName,
  133814. pRtree->zDb, pRtree->zName
  133815. );
  133816. if( !zCreate ){
  133817. rc = SQLITE_NOMEM;
  133818. }else{
  133819. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  133820. sqlite3_free(zCreate);
  133821. }
  133822. if( rc==SQLITE_OK ){
  133823. rtreeRelease(pRtree);
  133824. }
  133825. return rc;
  133826. }
  133827. /*
  133828. ** Rtree virtual table module xOpen method.
  133829. */
  133830. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  133831. int rc = SQLITE_NOMEM;
  133832. RtreeCursor *pCsr;
  133833. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  133834. if( pCsr ){
  133835. memset(pCsr, 0, sizeof(RtreeCursor));
  133836. pCsr->base.pVtab = pVTab;
  133837. rc = SQLITE_OK;
  133838. }
  133839. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  133840. return rc;
  133841. }
  133842. /*
  133843. ** Free the RtreeCursor.aConstraint[] array and its contents.
  133844. */
  133845. static void freeCursorConstraints(RtreeCursor *pCsr){
  133846. if( pCsr->aConstraint ){
  133847. int i; /* Used to iterate through constraint array */
  133848. for(i=0; i<pCsr->nConstraint; i++){
  133849. sqlite3_rtree_geometry *pGeom = pCsr->aConstraint[i].pGeom;
  133850. if( pGeom ){
  133851. if( pGeom->xDelUser ) pGeom->xDelUser(pGeom->pUser);
  133852. sqlite3_free(pGeom);
  133853. }
  133854. }
  133855. sqlite3_free(pCsr->aConstraint);
  133856. pCsr->aConstraint = 0;
  133857. }
  133858. }
  133859. /*
  133860. ** Rtree virtual table module xClose method.
  133861. */
  133862. static int rtreeClose(sqlite3_vtab_cursor *cur){
  133863. Rtree *pRtree = (Rtree *)(cur->pVtab);
  133864. int rc;
  133865. RtreeCursor *pCsr = (RtreeCursor *)cur;
  133866. freeCursorConstraints(pCsr);
  133867. rc = nodeRelease(pRtree, pCsr->pNode);
  133868. sqlite3_free(pCsr);
  133869. return rc;
  133870. }
  133871. /*
  133872. ** Rtree virtual table module xEof method.
  133873. **
  133874. ** Return non-zero if the cursor does not currently point to a valid
  133875. ** record (i.e if the scan has finished), or zero otherwise.
  133876. */
  133877. static int rtreeEof(sqlite3_vtab_cursor *cur){
  133878. RtreeCursor *pCsr = (RtreeCursor *)cur;
  133879. return (pCsr->pNode==0);
  133880. }
  133881. /*
  133882. ** The r-tree constraint passed as the second argument to this function is
  133883. ** guaranteed to be a MATCH constraint.
  133884. */
  133885. static int testRtreeGeom(
  133886. Rtree *pRtree, /* R-Tree object */
  133887. RtreeConstraint *pConstraint, /* MATCH constraint to test */
  133888. RtreeCell *pCell, /* Cell to test */
  133889. int *pbRes /* OUT: Test result */
  133890. ){
  133891. int i;
  133892. RtreeDValue aCoord[RTREE_MAX_DIMENSIONS*2];
  133893. int nCoord = pRtree->nDim*2;
  133894. assert( pConstraint->op==RTREE_MATCH );
  133895. assert( pConstraint->pGeom );
  133896. for(i=0; i<nCoord; i++){
  133897. aCoord[i] = DCOORD(pCell->aCoord[i]);
  133898. }
  133899. return pConstraint->xGeom(pConstraint->pGeom, nCoord, aCoord, pbRes);
  133900. }
  133901. /*
  133902. ** Cursor pCursor currently points to a cell in a non-leaf page.
  133903. ** Set *pbEof to true if the sub-tree headed by the cell is filtered
  133904. ** (excluded) by the constraints in the pCursor->aConstraint[]
  133905. ** array, or false otherwise.
  133906. **
  133907. ** Return SQLITE_OK if successful or an SQLite error code if an error
  133908. ** occurs within a geometry callback.
  133909. */
  133910. static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  133911. RtreeCell cell;
  133912. int ii;
  133913. int bRes = 0;
  133914. int rc = SQLITE_OK;
  133915. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  133916. for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
  133917. RtreeConstraint *p = &pCursor->aConstraint[ii];
  133918. RtreeDValue cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
  133919. RtreeDValue cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
  133920. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  133921. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  133922. );
  133923. switch( p->op ){
  133924. case RTREE_LE: case RTREE_LT:
  133925. bRes = p->rValue<cell_min;
  133926. break;
  133927. case RTREE_GE: case RTREE_GT:
  133928. bRes = p->rValue>cell_max;
  133929. break;
  133930. case RTREE_EQ:
  133931. bRes = (p->rValue>cell_max || p->rValue<cell_min);
  133932. break;
  133933. default: {
  133934. assert( p->op==RTREE_MATCH );
  133935. rc = testRtreeGeom(pRtree, p, &cell, &bRes);
  133936. bRes = !bRes;
  133937. break;
  133938. }
  133939. }
  133940. }
  133941. *pbEof = bRes;
  133942. return rc;
  133943. }
  133944. /*
  133945. ** Test if the cell that cursor pCursor currently points to
  133946. ** would be filtered (excluded) by the constraints in the
  133947. ** pCursor->aConstraint[] array. If so, set *pbEof to true before
  133948. ** returning. If the cell is not filtered (excluded) by the constraints,
  133949. ** set pbEof to zero.
  133950. **
  133951. ** Return SQLITE_OK if successful or an SQLite error code if an error
  133952. ** occurs within a geometry callback.
  133953. **
  133954. ** This function assumes that the cell is part of a leaf node.
  133955. */
  133956. static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor, int *pbEof){
  133957. RtreeCell cell;
  133958. int ii;
  133959. *pbEof = 0;
  133960. nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
  133961. for(ii=0; ii<pCursor->nConstraint; ii++){
  133962. RtreeConstraint *p = &pCursor->aConstraint[ii];
  133963. RtreeDValue coord = DCOORD(cell.aCoord[p->iCoord]);
  133964. int res;
  133965. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  133966. || p->op==RTREE_GT || p->op==RTREE_EQ || p->op==RTREE_MATCH
  133967. );
  133968. switch( p->op ){
  133969. case RTREE_LE: res = (coord<=p->rValue); break;
  133970. case RTREE_LT: res = (coord<p->rValue); break;
  133971. case RTREE_GE: res = (coord>=p->rValue); break;
  133972. case RTREE_GT: res = (coord>p->rValue); break;
  133973. case RTREE_EQ: res = (coord==p->rValue); break;
  133974. default: {
  133975. int rc;
  133976. assert( p->op==RTREE_MATCH );
  133977. rc = testRtreeGeom(pRtree, p, &cell, &res);
  133978. if( rc!=SQLITE_OK ){
  133979. return rc;
  133980. }
  133981. break;
  133982. }
  133983. }
  133984. if( !res ){
  133985. *pbEof = 1;
  133986. return SQLITE_OK;
  133987. }
  133988. }
  133989. return SQLITE_OK;
  133990. }
  133991. /*
  133992. ** Cursor pCursor currently points at a node that heads a sub-tree of
  133993. ** height iHeight (if iHeight==0, then the node is a leaf). Descend
  133994. ** to point to the left-most cell of the sub-tree that matches the
  133995. ** configured constraints.
  133996. */
  133997. static int descendToCell(
  133998. Rtree *pRtree,
  133999. RtreeCursor *pCursor,
  134000. int iHeight,
  134001. int *pEof /* OUT: Set to true if cannot descend */
  134002. ){
  134003. int isEof;
  134004. int rc;
  134005. int ii;
  134006. RtreeNode *pChild;
  134007. sqlite3_int64 iRowid;
  134008. RtreeNode *pSavedNode = pCursor->pNode;
  134009. int iSavedCell = pCursor->iCell;
  134010. assert( iHeight>=0 );
  134011. if( iHeight==0 ){
  134012. rc = testRtreeEntry(pRtree, pCursor, &isEof);
  134013. }else{
  134014. rc = testRtreeCell(pRtree, pCursor, &isEof);
  134015. }
  134016. if( rc!=SQLITE_OK || isEof || iHeight==0 ){
  134017. goto descend_to_cell_out;
  134018. }
  134019. iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
  134020. rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
  134021. if( rc!=SQLITE_OK ){
  134022. goto descend_to_cell_out;
  134023. }
  134024. nodeRelease(pRtree, pCursor->pNode);
  134025. pCursor->pNode = pChild;
  134026. isEof = 1;
  134027. for(ii=0; isEof && ii<NCELL(pChild); ii++){
  134028. pCursor->iCell = ii;
  134029. rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
  134030. if( rc!=SQLITE_OK ){
  134031. goto descend_to_cell_out;
  134032. }
  134033. }
  134034. if( isEof ){
  134035. assert( pCursor->pNode==pChild );
  134036. nodeReference(pSavedNode);
  134037. nodeRelease(pRtree, pChild);
  134038. pCursor->pNode = pSavedNode;
  134039. pCursor->iCell = iSavedCell;
  134040. }
  134041. descend_to_cell_out:
  134042. *pEof = isEof;
  134043. return rc;
  134044. }
  134045. /*
  134046. ** One of the cells in node pNode is guaranteed to have a 64-bit
  134047. ** integer value equal to iRowid. Return the index of this cell.
  134048. */
  134049. static int nodeRowidIndex(
  134050. Rtree *pRtree,
  134051. RtreeNode *pNode,
  134052. i64 iRowid,
  134053. int *piIndex
  134054. ){
  134055. int ii;
  134056. int nCell = NCELL(pNode);
  134057. for(ii=0; ii<nCell; ii++){
  134058. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  134059. *piIndex = ii;
  134060. return SQLITE_OK;
  134061. }
  134062. }
  134063. return SQLITE_CORRUPT_VTAB;
  134064. }
  134065. /*
  134066. ** Return the index of the cell containing a pointer to node pNode
  134067. ** in its parent. If pNode is the root node, return -1.
  134068. */
  134069. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  134070. RtreeNode *pParent = pNode->pParent;
  134071. if( pParent ){
  134072. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  134073. }
  134074. *piIndex = -1;
  134075. return SQLITE_OK;
  134076. }
  134077. /*
  134078. ** Rtree virtual table module xNext method.
  134079. */
  134080. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  134081. Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
  134082. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134083. int rc = SQLITE_OK;
  134084. /* RtreeCursor.pNode must not be NULL. If is is NULL, then this cursor is
  134085. ** already at EOF. It is against the rules to call the xNext() method of
  134086. ** a cursor that has already reached EOF.
  134087. */
  134088. assert( pCsr->pNode );
  134089. if( pCsr->iStrategy==1 ){
  134090. /* This "scan" is a direct lookup by rowid. There is no next entry. */
  134091. nodeRelease(pRtree, pCsr->pNode);
  134092. pCsr->pNode = 0;
  134093. }else{
  134094. /* Move to the next entry that matches the configured constraints. */
  134095. int iHeight = 0;
  134096. while( pCsr->pNode ){
  134097. RtreeNode *pNode = pCsr->pNode;
  134098. int nCell = NCELL(pNode);
  134099. for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
  134100. int isEof;
  134101. rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
  134102. if( rc!=SQLITE_OK || !isEof ){
  134103. return rc;
  134104. }
  134105. }
  134106. pCsr->pNode = pNode->pParent;
  134107. rc = nodeParentIndex(pRtree, pNode, &pCsr->iCell);
  134108. if( rc!=SQLITE_OK ){
  134109. return rc;
  134110. }
  134111. nodeReference(pCsr->pNode);
  134112. nodeRelease(pRtree, pNode);
  134113. iHeight++;
  134114. }
  134115. }
  134116. return rc;
  134117. }
  134118. /*
  134119. ** Rtree virtual table module xRowid method.
  134120. */
  134121. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  134122. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  134123. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134124. assert(pCsr->pNode);
  134125. *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  134126. return SQLITE_OK;
  134127. }
  134128. /*
  134129. ** Rtree virtual table module xColumn method.
  134130. */
  134131. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  134132. Rtree *pRtree = (Rtree *)cur->pVtab;
  134133. RtreeCursor *pCsr = (RtreeCursor *)cur;
  134134. if( i==0 ){
  134135. i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
  134136. sqlite3_result_int64(ctx, iRowid);
  134137. }else{
  134138. RtreeCoord c;
  134139. nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
  134140. #ifndef SQLITE_RTREE_INT_ONLY
  134141. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  134142. sqlite3_result_double(ctx, c.f);
  134143. }else
  134144. #endif
  134145. {
  134146. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  134147. sqlite3_result_int(ctx, c.i);
  134148. }
  134149. }
  134150. return SQLITE_OK;
  134151. }
  134152. /*
  134153. ** Use nodeAcquire() to obtain the leaf node containing the record with
  134154. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  134155. ** return SQLITE_OK. If there is no such record in the table, set
  134156. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  134157. ** to zero and return an SQLite error code.
  134158. */
  134159. static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
  134160. int rc;
  134161. *ppLeaf = 0;
  134162. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  134163. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  134164. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  134165. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  134166. sqlite3_reset(pRtree->pReadRowid);
  134167. }else{
  134168. rc = sqlite3_reset(pRtree->pReadRowid);
  134169. }
  134170. return rc;
  134171. }
  134172. /*
  134173. ** This function is called to configure the RtreeConstraint object passed
  134174. ** as the second argument for a MATCH constraint. The value passed as the
  134175. ** first argument to this function is the right-hand operand to the MATCH
  134176. ** operator.
  134177. */
  134178. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  134179. RtreeMatchArg *p;
  134180. sqlite3_rtree_geometry *pGeom;
  134181. int nBlob;
  134182. /* Check that value is actually a blob. */
  134183. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  134184. /* Check that the blob is roughly the right size. */
  134185. nBlob = sqlite3_value_bytes(pValue);
  134186. if( nBlob<(int)sizeof(RtreeMatchArg)
  134187. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  134188. ){
  134189. return SQLITE_ERROR;
  134190. }
  134191. pGeom = (sqlite3_rtree_geometry *)sqlite3_malloc(
  134192. sizeof(sqlite3_rtree_geometry) + nBlob
  134193. );
  134194. if( !pGeom ) return SQLITE_NOMEM;
  134195. memset(pGeom, 0, sizeof(sqlite3_rtree_geometry));
  134196. p = (RtreeMatchArg *)&pGeom[1];
  134197. memcpy(p, sqlite3_value_blob(pValue), nBlob);
  134198. if( p->magic!=RTREE_GEOMETRY_MAGIC
  134199. || nBlob!=(int)(sizeof(RtreeMatchArg) + (p->nParam-1)*sizeof(RtreeDValue))
  134200. ){
  134201. sqlite3_free(pGeom);
  134202. return SQLITE_ERROR;
  134203. }
  134204. pGeom->pContext = p->pContext;
  134205. pGeom->nParam = p->nParam;
  134206. pGeom->aParam = p->aParam;
  134207. pCons->xGeom = p->xGeom;
  134208. pCons->pGeom = pGeom;
  134209. return SQLITE_OK;
  134210. }
  134211. /*
  134212. ** Rtree virtual table module xFilter method.
  134213. */
  134214. static int rtreeFilter(
  134215. sqlite3_vtab_cursor *pVtabCursor,
  134216. int idxNum, const char *idxStr,
  134217. int argc, sqlite3_value **argv
  134218. ){
  134219. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  134220. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  134221. RtreeNode *pRoot = 0;
  134222. int ii;
  134223. int rc = SQLITE_OK;
  134224. rtreeReference(pRtree);
  134225. freeCursorConstraints(pCsr);
  134226. pCsr->iStrategy = idxNum;
  134227. if( idxNum==1 ){
  134228. /* Special case - lookup by rowid. */
  134229. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  134230. i64 iRowid = sqlite3_value_int64(argv[0]);
  134231. rc = findLeafNode(pRtree, iRowid, &pLeaf);
  134232. pCsr->pNode = pLeaf;
  134233. if( pLeaf ){
  134234. assert( rc==SQLITE_OK );
  134235. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &pCsr->iCell);
  134236. }
  134237. }else{
  134238. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  134239. ** with the configured constraints.
  134240. */
  134241. if( argc>0 ){
  134242. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  134243. pCsr->nConstraint = argc;
  134244. if( !pCsr->aConstraint ){
  134245. rc = SQLITE_NOMEM;
  134246. }else{
  134247. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  134248. assert( (idxStr==0 && argc==0)
  134249. || (idxStr && (int)strlen(idxStr)==argc*2) );
  134250. for(ii=0; ii<argc; ii++){
  134251. RtreeConstraint *p = &pCsr->aConstraint[ii];
  134252. p->op = idxStr[ii*2];
  134253. p->iCoord = idxStr[ii*2+1]-'a';
  134254. if( p->op==RTREE_MATCH ){
  134255. /* A MATCH operator. The right-hand-side must be a blob that
  134256. ** can be cast into an RtreeMatchArg object. One created using
  134257. ** an sqlite3_rtree_geometry_callback() SQL user function.
  134258. */
  134259. rc = deserializeGeometry(argv[ii], p);
  134260. if( rc!=SQLITE_OK ){
  134261. break;
  134262. }
  134263. }else{
  134264. #ifdef SQLITE_RTREE_INT_ONLY
  134265. p->rValue = sqlite3_value_int64(argv[ii]);
  134266. #else
  134267. p->rValue = sqlite3_value_double(argv[ii]);
  134268. #endif
  134269. }
  134270. }
  134271. }
  134272. }
  134273. if( rc==SQLITE_OK ){
  134274. pCsr->pNode = 0;
  134275. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  134276. }
  134277. if( rc==SQLITE_OK ){
  134278. int isEof = 1;
  134279. int nCell = NCELL(pRoot);
  134280. pCsr->pNode = pRoot;
  134281. for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
  134282. assert( pCsr->pNode==pRoot );
  134283. rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
  134284. if( !isEof ){
  134285. break;
  134286. }
  134287. }
  134288. if( rc==SQLITE_OK && isEof ){
  134289. assert( pCsr->pNode==pRoot );
  134290. nodeRelease(pRtree, pRoot);
  134291. pCsr->pNode = 0;
  134292. }
  134293. assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
  134294. }
  134295. }
  134296. rtreeRelease(pRtree);
  134297. return rc;
  134298. }
  134299. /*
  134300. ** Rtree virtual table module xBestIndex method. There are three
  134301. ** table scan strategies to choose from (in order from most to
  134302. ** least desirable):
  134303. **
  134304. ** idxNum idxStr Strategy
  134305. ** ------------------------------------------------
  134306. ** 1 Unused Direct lookup by rowid.
  134307. ** 2 See below R-tree query or full-table scan.
  134308. ** ------------------------------------------------
  134309. **
  134310. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  134311. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  134312. ** constraint used. The first two bytes of idxStr correspond to
  134313. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  134314. ** (argvIndex==1) etc.
  134315. **
  134316. ** The first of each pair of bytes in idxStr identifies the constraint
  134317. ** operator as follows:
  134318. **
  134319. ** Operator Byte Value
  134320. ** ----------------------
  134321. ** = 0x41 ('A')
  134322. ** <= 0x42 ('B')
  134323. ** < 0x43 ('C')
  134324. ** >= 0x44 ('D')
  134325. ** > 0x45 ('E')
  134326. ** MATCH 0x46 ('F')
  134327. ** ----------------------
  134328. **
  134329. ** The second of each pair of bytes identifies the coordinate column
  134330. ** to which the constraint applies. The leftmost coordinate column
  134331. ** is 'a', the second from the left 'b' etc.
  134332. */
  134333. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  134334. int rc = SQLITE_OK;
  134335. int ii;
  134336. int iIdx = 0;
  134337. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  134338. memset(zIdxStr, 0, sizeof(zIdxStr));
  134339. UNUSED_PARAMETER(tab);
  134340. assert( pIdxInfo->idxStr==0 );
  134341. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  134342. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  134343. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  134344. /* We have an equality constraint on the rowid. Use strategy 1. */
  134345. int jj;
  134346. for(jj=0; jj<ii; jj++){
  134347. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  134348. pIdxInfo->aConstraintUsage[jj].omit = 0;
  134349. }
  134350. pIdxInfo->idxNum = 1;
  134351. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  134352. pIdxInfo->aConstraintUsage[jj].omit = 1;
  134353. /* This strategy involves a two rowid lookups on an B-Tree structures
  134354. ** and then a linear search of an R-Tree node. This should be
  134355. ** considered almost as quick as a direct rowid lookup (for which
  134356. ** sqlite uses an internal cost of 0.0).
  134357. */
  134358. pIdxInfo->estimatedCost = 10.0;
  134359. return SQLITE_OK;
  134360. }
  134361. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  134362. u8 op;
  134363. switch( p->op ){
  134364. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  134365. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  134366. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  134367. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  134368. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  134369. default:
  134370. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  134371. op = RTREE_MATCH;
  134372. break;
  134373. }
  134374. zIdxStr[iIdx++] = op;
  134375. zIdxStr[iIdx++] = p->iColumn - 1 + 'a';
  134376. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  134377. pIdxInfo->aConstraintUsage[ii].omit = 1;
  134378. }
  134379. }
  134380. pIdxInfo->idxNum = 2;
  134381. pIdxInfo->needToFreeIdxStr = 1;
  134382. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  134383. return SQLITE_NOMEM;
  134384. }
  134385. assert( iIdx>=0 );
  134386. pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
  134387. return rc;
  134388. }
  134389. /*
  134390. ** Return the N-dimensional volumn of the cell stored in *p.
  134391. */
  134392. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  134393. RtreeDValue area = (RtreeDValue)1;
  134394. int ii;
  134395. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134396. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  134397. }
  134398. return area;
  134399. }
  134400. /*
  134401. ** Return the margin length of cell p. The margin length is the sum
  134402. ** of the objects size in each dimension.
  134403. */
  134404. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  134405. RtreeDValue margin = (RtreeDValue)0;
  134406. int ii;
  134407. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134408. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  134409. }
  134410. return margin;
  134411. }
  134412. /*
  134413. ** Store the union of cells p1 and p2 in p1.
  134414. */
  134415. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  134416. int ii;
  134417. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  134418. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134419. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  134420. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  134421. }
  134422. }else{
  134423. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134424. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  134425. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  134426. }
  134427. }
  134428. }
  134429. /*
  134430. ** Return true if the area covered by p2 is a subset of the area covered
  134431. ** by p1. False otherwise.
  134432. */
  134433. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  134434. int ii;
  134435. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  134436. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  134437. RtreeCoord *a1 = &p1->aCoord[ii];
  134438. RtreeCoord *a2 = &p2->aCoord[ii];
  134439. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  134440. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  134441. ){
  134442. return 0;
  134443. }
  134444. }
  134445. return 1;
  134446. }
  134447. /*
  134448. ** Return the amount cell p would grow by if it were unioned with pCell.
  134449. */
  134450. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  134451. RtreeDValue area;
  134452. RtreeCell cell;
  134453. memcpy(&cell, p, sizeof(RtreeCell));
  134454. area = cellArea(pRtree, &cell);
  134455. cellUnion(pRtree, &cell, pCell);
  134456. return (cellArea(pRtree, &cell)-area);
  134457. }
  134458. #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
  134459. static RtreeDValue cellOverlap(
  134460. Rtree *pRtree,
  134461. RtreeCell *p,
  134462. RtreeCell *aCell,
  134463. int nCell,
  134464. int iExclude
  134465. ){
  134466. int ii;
  134467. RtreeDValue overlap = 0.0;
  134468. for(ii=0; ii<nCell; ii++){
  134469. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134470. if( ii!=iExclude )
  134471. #else
  134472. assert( iExclude==-1 );
  134473. UNUSED_PARAMETER(iExclude);
  134474. #endif
  134475. {
  134476. int jj;
  134477. RtreeDValue o = (RtreeDValue)1;
  134478. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  134479. RtreeDValue x1, x2;
  134480. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  134481. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  134482. if( x2<x1 ){
  134483. o = 0.0;
  134484. break;
  134485. }else{
  134486. o = o * (x2-x1);
  134487. }
  134488. }
  134489. overlap += o;
  134490. }
  134491. }
  134492. return overlap;
  134493. }
  134494. #endif
  134495. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134496. static RtreeDValue cellOverlapEnlargement(
  134497. Rtree *pRtree,
  134498. RtreeCell *p,
  134499. RtreeCell *pInsert,
  134500. RtreeCell *aCell,
  134501. int nCell,
  134502. int iExclude
  134503. ){
  134504. RtreeDValue before, after;
  134505. before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  134506. cellUnion(pRtree, p, pInsert);
  134507. after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
  134508. return (after-before);
  134509. }
  134510. #endif
  134511. /*
  134512. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  134513. ** ChooseSubTree in r*tree terminology.
  134514. */
  134515. static int ChooseLeaf(
  134516. Rtree *pRtree, /* Rtree table */
  134517. RtreeCell *pCell, /* Cell to insert into rtree */
  134518. int iHeight, /* Height of sub-tree rooted at pCell */
  134519. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  134520. ){
  134521. int rc;
  134522. int ii;
  134523. RtreeNode *pNode;
  134524. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  134525. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  134526. int iCell;
  134527. sqlite3_int64 iBest = 0;
  134528. RtreeDValue fMinGrowth = 0.0;
  134529. RtreeDValue fMinArea = 0.0;
  134530. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134531. RtreeDValue fMinOverlap = 0.0;
  134532. RtreeDValue overlap;
  134533. #endif
  134534. int nCell = NCELL(pNode);
  134535. RtreeCell cell;
  134536. RtreeNode *pChild;
  134537. RtreeCell *aCell = 0;
  134538. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134539. if( ii==(pRtree->iDepth-1) ){
  134540. int jj;
  134541. aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
  134542. if( !aCell ){
  134543. rc = SQLITE_NOMEM;
  134544. nodeRelease(pRtree, pNode);
  134545. pNode = 0;
  134546. continue;
  134547. }
  134548. for(jj=0; jj<nCell; jj++){
  134549. nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
  134550. }
  134551. }
  134552. #endif
  134553. /* Select the child node which will be enlarged the least if pCell
  134554. ** is inserted into it. Resolve ties by choosing the entry with
  134555. ** the smallest area.
  134556. */
  134557. for(iCell=0; iCell<nCell; iCell++){
  134558. int bBest = 0;
  134559. RtreeDValue growth;
  134560. RtreeDValue area;
  134561. nodeGetCell(pRtree, pNode, iCell, &cell);
  134562. growth = cellGrowth(pRtree, &cell, pCell);
  134563. area = cellArea(pRtree, &cell);
  134564. #if VARIANT_RSTARTREE_CHOOSESUBTREE
  134565. if( ii==(pRtree->iDepth-1) ){
  134566. overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
  134567. }else{
  134568. overlap = 0.0;
  134569. }
  134570. if( (iCell==0)
  134571. || (overlap<fMinOverlap)
  134572. || (overlap==fMinOverlap && growth<fMinGrowth)
  134573. || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
  134574. ){
  134575. bBest = 1;
  134576. fMinOverlap = overlap;
  134577. }
  134578. #else
  134579. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  134580. bBest = 1;
  134581. }
  134582. #endif
  134583. if( bBest ){
  134584. fMinGrowth = growth;
  134585. fMinArea = area;
  134586. iBest = cell.iRowid;
  134587. }
  134588. }
  134589. sqlite3_free(aCell);
  134590. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  134591. nodeRelease(pRtree, pNode);
  134592. pNode = pChild;
  134593. }
  134594. *ppLeaf = pNode;
  134595. return rc;
  134596. }
  134597. /*
  134598. ** A cell with the same content as pCell has just been inserted into
  134599. ** the node pNode. This function updates the bounding box cells in
  134600. ** all ancestor elements.
  134601. */
  134602. static int AdjustTree(
  134603. Rtree *pRtree, /* Rtree table */
  134604. RtreeNode *pNode, /* Adjust ancestry of this node. */
  134605. RtreeCell *pCell /* This cell was just inserted */
  134606. ){
  134607. RtreeNode *p = pNode;
  134608. while( p->pParent ){
  134609. RtreeNode *pParent = p->pParent;
  134610. RtreeCell cell;
  134611. int iCell;
  134612. if( nodeParentIndex(pRtree, p, &iCell) ){
  134613. return SQLITE_CORRUPT_VTAB;
  134614. }
  134615. nodeGetCell(pRtree, pParent, iCell, &cell);
  134616. if( !cellContains(pRtree, &cell, pCell) ){
  134617. cellUnion(pRtree, &cell, pCell);
  134618. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  134619. }
  134620. p = pParent;
  134621. }
  134622. return SQLITE_OK;
  134623. }
  134624. /*
  134625. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  134626. */
  134627. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  134628. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  134629. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  134630. sqlite3_step(pRtree->pWriteRowid);
  134631. return sqlite3_reset(pRtree->pWriteRowid);
  134632. }
  134633. /*
  134634. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  134635. */
  134636. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  134637. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  134638. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  134639. sqlite3_step(pRtree->pWriteParent);
  134640. return sqlite3_reset(pRtree->pWriteParent);
  134641. }
  134642. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  134643. #if VARIANT_GUTTMAN_LINEAR_SPLIT
  134644. /*
  134645. ** Implementation of the linear variant of the PickNext() function from
  134646. ** Guttman[84].
  134647. */
  134648. static RtreeCell *LinearPickNext(
  134649. Rtree *pRtree,
  134650. RtreeCell *aCell,
  134651. int nCell,
  134652. RtreeCell *pLeftBox,
  134653. RtreeCell *pRightBox,
  134654. int *aiUsed
  134655. ){
  134656. int ii;
  134657. for(ii=0; aiUsed[ii]; ii++);
  134658. aiUsed[ii] = 1;
  134659. return &aCell[ii];
  134660. }
  134661. /*
  134662. ** Implementation of the linear variant of the PickSeeds() function from
  134663. ** Guttman[84].
  134664. */
  134665. static void LinearPickSeeds(
  134666. Rtree *pRtree,
  134667. RtreeCell *aCell,
  134668. int nCell,
  134669. int *piLeftSeed,
  134670. int *piRightSeed
  134671. ){
  134672. int i;
  134673. int iLeftSeed = 0;
  134674. int iRightSeed = 1;
  134675. RtreeDValue maxNormalInnerWidth = (RtreeDValue)0;
  134676. /* Pick two "seed" cells from the array of cells. The algorithm used
  134677. ** here is the LinearPickSeeds algorithm from Gutman[1984]. The
  134678. ** indices of the two seed cells in the array are stored in local
  134679. ** variables iLeftSeek and iRightSeed.
  134680. */
  134681. for(i=0; i<pRtree->nDim; i++){
  134682. RtreeDValue x1 = DCOORD(aCell[0].aCoord[i*2]);
  134683. RtreeDValue x2 = DCOORD(aCell[0].aCoord[i*2+1]);
  134684. RtreeDValue x3 = x1;
  134685. RtreeDValue x4 = x2;
  134686. int jj;
  134687. int iCellLeft = 0;
  134688. int iCellRight = 0;
  134689. for(jj=1; jj<nCell; jj++){
  134690. RtreeDValue left = DCOORD(aCell[jj].aCoord[i*2]);
  134691. RtreeDValue right = DCOORD(aCell[jj].aCoord[i*2+1]);
  134692. if( left<x1 ) x1 = left;
  134693. if( right>x4 ) x4 = right;
  134694. if( left>x3 ){
  134695. x3 = left;
  134696. iCellRight = jj;
  134697. }
  134698. if( right<x2 ){
  134699. x2 = right;
  134700. iCellLeft = jj;
  134701. }
  134702. }
  134703. if( x4!=x1 ){
  134704. RtreeDValue normalwidth = (x3 - x2) / (x4 - x1);
  134705. if( normalwidth>maxNormalInnerWidth ){
  134706. iLeftSeed = iCellLeft;
  134707. iRightSeed = iCellRight;
  134708. }
  134709. }
  134710. }
  134711. *piLeftSeed = iLeftSeed;
  134712. *piRightSeed = iRightSeed;
  134713. }
  134714. #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
  134715. #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
  134716. /*
  134717. ** Implementation of the quadratic variant of the PickNext() function from
  134718. ** Guttman[84].
  134719. */
  134720. static RtreeCell *QuadraticPickNext(
  134721. Rtree *pRtree,
  134722. RtreeCell *aCell,
  134723. int nCell,
  134724. RtreeCell *pLeftBox,
  134725. RtreeCell *pRightBox,
  134726. int *aiUsed
  134727. ){
  134728. #define FABS(a) ((a)<0.0?-1.0*(a):(a))
  134729. int iSelect = -1;
  134730. RtreeDValue fDiff;
  134731. int ii;
  134732. for(ii=0; ii<nCell; ii++){
  134733. if( aiUsed[ii]==0 ){
  134734. RtreeDValue left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  134735. RtreeDValue right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
  134736. RtreeDValue diff = FABS(right-left);
  134737. if( iSelect<0 || diff>fDiff ){
  134738. fDiff = diff;
  134739. iSelect = ii;
  134740. }
  134741. }
  134742. }
  134743. aiUsed[iSelect] = 1;
  134744. return &aCell[iSelect];
  134745. }
  134746. /*
  134747. ** Implementation of the quadratic variant of the PickSeeds() function from
  134748. ** Guttman[84].
  134749. */
  134750. static void QuadraticPickSeeds(
  134751. Rtree *pRtree,
  134752. RtreeCell *aCell,
  134753. int nCell,
  134754. int *piLeftSeed,
  134755. int *piRightSeed
  134756. ){
  134757. int ii;
  134758. int jj;
  134759. int iLeftSeed = 0;
  134760. int iRightSeed = 1;
  134761. RtreeDValue fWaste = 0.0;
  134762. for(ii=0; ii<nCell; ii++){
  134763. for(jj=ii+1; jj<nCell; jj++){
  134764. RtreeDValue right = cellArea(pRtree, &aCell[jj]);
  134765. RtreeDValue growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
  134766. RtreeDValue waste = growth - right;
  134767. if( waste>fWaste ){
  134768. iLeftSeed = ii;
  134769. iRightSeed = jj;
  134770. fWaste = waste;
  134771. }
  134772. }
  134773. }
  134774. *piLeftSeed = iLeftSeed;
  134775. *piRightSeed = iRightSeed;
  134776. }
  134777. #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
  134778. /*
  134779. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  134780. ** nIdx. The aIdx array contains the set of integers from 0 to
  134781. ** (nIdx-1) in no particular order. This function sorts the values
  134782. ** in aIdx according to the indexed values in aDistance. For
  134783. ** example, assuming the inputs:
  134784. **
  134785. ** aIdx = { 0, 1, 2, 3 }
  134786. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  134787. **
  134788. ** this function sets the aIdx array to contain:
  134789. **
  134790. ** aIdx = { 0, 1, 2, 3 }
  134791. **
  134792. ** The aSpare array is used as temporary working space by the
  134793. ** sorting algorithm.
  134794. */
  134795. static void SortByDistance(
  134796. int *aIdx,
  134797. int nIdx,
  134798. RtreeDValue *aDistance,
  134799. int *aSpare
  134800. ){
  134801. if( nIdx>1 ){
  134802. int iLeft = 0;
  134803. int iRight = 0;
  134804. int nLeft = nIdx/2;
  134805. int nRight = nIdx-nLeft;
  134806. int *aLeft = aIdx;
  134807. int *aRight = &aIdx[nLeft];
  134808. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  134809. SortByDistance(aRight, nRight, aDistance, aSpare);
  134810. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  134811. aLeft = aSpare;
  134812. while( iLeft<nLeft || iRight<nRight ){
  134813. if( iLeft==nLeft ){
  134814. aIdx[iLeft+iRight] = aRight[iRight];
  134815. iRight++;
  134816. }else if( iRight==nRight ){
  134817. aIdx[iLeft+iRight] = aLeft[iLeft];
  134818. iLeft++;
  134819. }else{
  134820. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  134821. RtreeDValue fRight = aDistance[aRight[iRight]];
  134822. if( fLeft<fRight ){
  134823. aIdx[iLeft+iRight] = aLeft[iLeft];
  134824. iLeft++;
  134825. }else{
  134826. aIdx[iLeft+iRight] = aRight[iRight];
  134827. iRight++;
  134828. }
  134829. }
  134830. }
  134831. #if 0
  134832. /* Check that the sort worked */
  134833. {
  134834. int jj;
  134835. for(jj=1; jj<nIdx; jj++){
  134836. RtreeDValue left = aDistance[aIdx[jj-1]];
  134837. RtreeDValue right = aDistance[aIdx[jj]];
  134838. assert( left<=right );
  134839. }
  134840. }
  134841. #endif
  134842. }
  134843. }
  134844. /*
  134845. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  134846. ** nIdx. The aIdx array contains the set of integers from 0 to
  134847. ** (nIdx-1) in no particular order. This function sorts the values
  134848. ** in aIdx according to dimension iDim of the cells in aCell. The
  134849. ** minimum value of dimension iDim is considered first, the
  134850. ** maximum used to break ties.
  134851. **
  134852. ** The aSpare array is used as temporary working space by the
  134853. ** sorting algorithm.
  134854. */
  134855. static void SortByDimension(
  134856. Rtree *pRtree,
  134857. int *aIdx,
  134858. int nIdx,
  134859. int iDim,
  134860. RtreeCell *aCell,
  134861. int *aSpare
  134862. ){
  134863. if( nIdx>1 ){
  134864. int iLeft = 0;
  134865. int iRight = 0;
  134866. int nLeft = nIdx/2;
  134867. int nRight = nIdx-nLeft;
  134868. int *aLeft = aIdx;
  134869. int *aRight = &aIdx[nLeft];
  134870. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  134871. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  134872. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  134873. aLeft = aSpare;
  134874. while( iLeft<nLeft || iRight<nRight ){
  134875. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  134876. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  134877. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  134878. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  134879. if( (iLeft!=nLeft) && ((iRight==nRight)
  134880. || (xleft1<xright1)
  134881. || (xleft1==xright1 && xleft2<xright2)
  134882. )){
  134883. aIdx[iLeft+iRight] = aLeft[iLeft];
  134884. iLeft++;
  134885. }else{
  134886. aIdx[iLeft+iRight] = aRight[iRight];
  134887. iRight++;
  134888. }
  134889. }
  134890. #if 0
  134891. /* Check that the sort worked */
  134892. {
  134893. int jj;
  134894. for(jj=1; jj<nIdx; jj++){
  134895. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  134896. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  134897. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  134898. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  134899. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  134900. }
  134901. }
  134902. #endif
  134903. }
  134904. }
  134905. #if VARIANT_RSTARTREE_SPLIT
  134906. /*
  134907. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  134908. */
  134909. static int splitNodeStartree(
  134910. Rtree *pRtree,
  134911. RtreeCell *aCell,
  134912. int nCell,
  134913. RtreeNode *pLeft,
  134914. RtreeNode *pRight,
  134915. RtreeCell *pBboxLeft,
  134916. RtreeCell *pBboxRight
  134917. ){
  134918. int **aaSorted;
  134919. int *aSpare;
  134920. int ii;
  134921. int iBestDim = 0;
  134922. int iBestSplit = 0;
  134923. RtreeDValue fBestMargin = 0.0;
  134924. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  134925. aaSorted = (int **)sqlite3_malloc(nByte);
  134926. if( !aaSorted ){
  134927. return SQLITE_NOMEM;
  134928. }
  134929. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  134930. memset(aaSorted, 0, nByte);
  134931. for(ii=0; ii<pRtree->nDim; ii++){
  134932. int jj;
  134933. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  134934. for(jj=0; jj<nCell; jj++){
  134935. aaSorted[ii][jj] = jj;
  134936. }
  134937. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  134938. }
  134939. for(ii=0; ii<pRtree->nDim; ii++){
  134940. RtreeDValue margin = 0.0;
  134941. RtreeDValue fBestOverlap = 0.0;
  134942. RtreeDValue fBestArea = 0.0;
  134943. int iBestLeft = 0;
  134944. int nLeft;
  134945. for(
  134946. nLeft=RTREE_MINCELLS(pRtree);
  134947. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  134948. nLeft++
  134949. ){
  134950. RtreeCell left;
  134951. RtreeCell right;
  134952. int kk;
  134953. RtreeDValue overlap;
  134954. RtreeDValue area;
  134955. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  134956. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  134957. for(kk=1; kk<(nCell-1); kk++){
  134958. if( kk<nLeft ){
  134959. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  134960. }else{
  134961. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  134962. }
  134963. }
  134964. margin += cellMargin(pRtree, &left);
  134965. margin += cellMargin(pRtree, &right);
  134966. overlap = cellOverlap(pRtree, &left, &right, 1, -1);
  134967. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  134968. if( (nLeft==RTREE_MINCELLS(pRtree))
  134969. || (overlap<fBestOverlap)
  134970. || (overlap==fBestOverlap && area<fBestArea)
  134971. ){
  134972. iBestLeft = nLeft;
  134973. fBestOverlap = overlap;
  134974. fBestArea = area;
  134975. }
  134976. }
  134977. if( ii==0 || margin<fBestMargin ){
  134978. iBestDim = ii;
  134979. fBestMargin = margin;
  134980. iBestSplit = iBestLeft;
  134981. }
  134982. }
  134983. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  134984. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  134985. for(ii=0; ii<nCell; ii++){
  134986. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  134987. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  134988. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  134989. nodeInsertCell(pRtree, pTarget, pCell);
  134990. cellUnion(pRtree, pBbox, pCell);
  134991. }
  134992. sqlite3_free(aaSorted);
  134993. return SQLITE_OK;
  134994. }
  134995. #endif
  134996. #if VARIANT_GUTTMAN_SPLIT
  134997. /*
  134998. ** Implementation of the regular R-tree SplitNode from Guttman[1984].
  134999. */
  135000. static int splitNodeGuttman(
  135001. Rtree *pRtree,
  135002. RtreeCell *aCell,
  135003. int nCell,
  135004. RtreeNode *pLeft,
  135005. RtreeNode *pRight,
  135006. RtreeCell *pBboxLeft,
  135007. RtreeCell *pBboxRight
  135008. ){
  135009. int iLeftSeed = 0;
  135010. int iRightSeed = 1;
  135011. int *aiUsed;
  135012. int i;
  135013. aiUsed = sqlite3_malloc(sizeof(int)*nCell);
  135014. if( !aiUsed ){
  135015. return SQLITE_NOMEM;
  135016. }
  135017. memset(aiUsed, 0, sizeof(int)*nCell);
  135018. PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
  135019. memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
  135020. memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
  135021. nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
  135022. nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
  135023. aiUsed[iLeftSeed] = 1;
  135024. aiUsed[iRightSeed] = 1;
  135025. for(i=nCell-2; i>0; i--){
  135026. RtreeCell *pNext;
  135027. pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
  135028. RtreeDValue diff =
  135029. cellGrowth(pRtree, pBboxLeft, pNext) -
  135030. cellGrowth(pRtree, pBboxRight, pNext)
  135031. ;
  135032. if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
  135033. || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
  135034. ){
  135035. nodeInsertCell(pRtree, pRight, pNext);
  135036. cellUnion(pRtree, pBboxRight, pNext);
  135037. }else{
  135038. nodeInsertCell(pRtree, pLeft, pNext);
  135039. cellUnion(pRtree, pBboxLeft, pNext);
  135040. }
  135041. }
  135042. sqlite3_free(aiUsed);
  135043. return SQLITE_OK;
  135044. }
  135045. #endif
  135046. static int updateMapping(
  135047. Rtree *pRtree,
  135048. i64 iRowid,
  135049. RtreeNode *pNode,
  135050. int iHeight
  135051. ){
  135052. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  135053. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  135054. if( iHeight>0 ){
  135055. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  135056. if( pChild ){
  135057. nodeRelease(pRtree, pChild->pParent);
  135058. nodeReference(pNode);
  135059. pChild->pParent = pNode;
  135060. }
  135061. }
  135062. return xSetMapping(pRtree, iRowid, pNode->iNode);
  135063. }
  135064. static int SplitNode(
  135065. Rtree *pRtree,
  135066. RtreeNode *pNode,
  135067. RtreeCell *pCell,
  135068. int iHeight
  135069. ){
  135070. int i;
  135071. int newCellIsRight = 0;
  135072. int rc = SQLITE_OK;
  135073. int nCell = NCELL(pNode);
  135074. RtreeCell *aCell;
  135075. int *aiUsed;
  135076. RtreeNode *pLeft = 0;
  135077. RtreeNode *pRight = 0;
  135078. RtreeCell leftbbox;
  135079. RtreeCell rightbbox;
  135080. /* Allocate an array and populate it with a copy of pCell and
  135081. ** all cells from node pLeft. Then zero the original node.
  135082. */
  135083. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  135084. if( !aCell ){
  135085. rc = SQLITE_NOMEM;
  135086. goto splitnode_out;
  135087. }
  135088. aiUsed = (int *)&aCell[nCell+1];
  135089. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  135090. for(i=0; i<nCell; i++){
  135091. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  135092. }
  135093. nodeZero(pRtree, pNode);
  135094. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  135095. nCell++;
  135096. if( pNode->iNode==1 ){
  135097. pRight = nodeNew(pRtree, pNode);
  135098. pLeft = nodeNew(pRtree, pNode);
  135099. pRtree->iDepth++;
  135100. pNode->isDirty = 1;
  135101. writeInt16(pNode->zData, pRtree->iDepth);
  135102. }else{
  135103. pLeft = pNode;
  135104. pRight = nodeNew(pRtree, pLeft->pParent);
  135105. nodeReference(pLeft);
  135106. }
  135107. if( !pLeft || !pRight ){
  135108. rc = SQLITE_NOMEM;
  135109. goto splitnode_out;
  135110. }
  135111. memset(pLeft->zData, 0, pRtree->iNodeSize);
  135112. memset(pRight->zData, 0, pRtree->iNodeSize);
  135113. rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
  135114. if( rc!=SQLITE_OK ){
  135115. goto splitnode_out;
  135116. }
  135117. /* Ensure both child nodes have node numbers assigned to them by calling
  135118. ** nodeWrite(). Node pRight always needs a node number, as it was created
  135119. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  135120. ** In this case avoid the all to nodeWrite().
  135121. */
  135122. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  135123. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  135124. ){
  135125. goto splitnode_out;
  135126. }
  135127. rightbbox.iRowid = pRight->iNode;
  135128. leftbbox.iRowid = pLeft->iNode;
  135129. if( pNode->iNode==1 ){
  135130. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  135131. if( rc!=SQLITE_OK ){
  135132. goto splitnode_out;
  135133. }
  135134. }else{
  135135. RtreeNode *pParent = pLeft->pParent;
  135136. int iCell;
  135137. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  135138. if( rc==SQLITE_OK ){
  135139. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  135140. rc = AdjustTree(pRtree, pParent, &leftbbox);
  135141. }
  135142. if( rc!=SQLITE_OK ){
  135143. goto splitnode_out;
  135144. }
  135145. }
  135146. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  135147. goto splitnode_out;
  135148. }
  135149. for(i=0; i<NCELL(pRight); i++){
  135150. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  135151. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  135152. if( iRowid==pCell->iRowid ){
  135153. newCellIsRight = 1;
  135154. }
  135155. if( rc!=SQLITE_OK ){
  135156. goto splitnode_out;
  135157. }
  135158. }
  135159. if( pNode->iNode==1 ){
  135160. for(i=0; i<NCELL(pLeft); i++){
  135161. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  135162. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  135163. if( rc!=SQLITE_OK ){
  135164. goto splitnode_out;
  135165. }
  135166. }
  135167. }else if( newCellIsRight==0 ){
  135168. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  135169. }
  135170. if( rc==SQLITE_OK ){
  135171. rc = nodeRelease(pRtree, pRight);
  135172. pRight = 0;
  135173. }
  135174. if( rc==SQLITE_OK ){
  135175. rc = nodeRelease(pRtree, pLeft);
  135176. pLeft = 0;
  135177. }
  135178. splitnode_out:
  135179. nodeRelease(pRtree, pRight);
  135180. nodeRelease(pRtree, pLeft);
  135181. sqlite3_free(aCell);
  135182. return rc;
  135183. }
  135184. /*
  135185. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  135186. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  135187. ** the pLeaf->pParent chain all the way up to the root node.
  135188. **
  135189. ** This operation is required when a row is deleted (or updated - an update
  135190. ** is implemented as a delete followed by an insert). SQLite provides the
  135191. ** rowid of the row to delete, which can be used to find the leaf on which
  135192. ** the entry resides (argument pLeaf). Once the leaf is located, this
  135193. ** function is called to determine its ancestry.
  135194. */
  135195. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  135196. int rc = SQLITE_OK;
  135197. RtreeNode *pChild = pLeaf;
  135198. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  135199. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  135200. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  135201. rc = sqlite3_step(pRtree->pReadParent);
  135202. if( rc==SQLITE_ROW ){
  135203. RtreeNode *pTest; /* Used to test for reference loops */
  135204. i64 iNode; /* Node number of parent node */
  135205. /* Before setting pChild->pParent, test that we are not creating a
  135206. ** loop of references (as we would if, say, pChild==pParent). We don't
  135207. ** want to do this as it leads to a memory leak when trying to delete
  135208. ** the referenced counted node structures.
  135209. */
  135210. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  135211. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  135212. if( !pTest ){
  135213. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  135214. }
  135215. }
  135216. rc = sqlite3_reset(pRtree->pReadParent);
  135217. if( rc==SQLITE_OK ) rc = rc2;
  135218. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  135219. pChild = pChild->pParent;
  135220. }
  135221. return rc;
  135222. }
  135223. static int deleteCell(Rtree *, RtreeNode *, int, int);
  135224. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  135225. int rc;
  135226. int rc2;
  135227. RtreeNode *pParent = 0;
  135228. int iCell;
  135229. assert( pNode->nRef==1 );
  135230. /* Remove the entry in the parent cell. */
  135231. rc = nodeParentIndex(pRtree, pNode, &iCell);
  135232. if( rc==SQLITE_OK ){
  135233. pParent = pNode->pParent;
  135234. pNode->pParent = 0;
  135235. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  135236. }
  135237. rc2 = nodeRelease(pRtree, pParent);
  135238. if( rc==SQLITE_OK ){
  135239. rc = rc2;
  135240. }
  135241. if( rc!=SQLITE_OK ){
  135242. return rc;
  135243. }
  135244. /* Remove the xxx_node entry. */
  135245. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  135246. sqlite3_step(pRtree->pDeleteNode);
  135247. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  135248. return rc;
  135249. }
  135250. /* Remove the xxx_parent entry. */
  135251. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  135252. sqlite3_step(pRtree->pDeleteParent);
  135253. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  135254. return rc;
  135255. }
  135256. /* Remove the node from the in-memory hash table and link it into
  135257. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  135258. */
  135259. nodeHashDelete(pRtree, pNode);
  135260. pNode->iNode = iHeight;
  135261. pNode->pNext = pRtree->pDeleted;
  135262. pNode->nRef++;
  135263. pRtree->pDeleted = pNode;
  135264. return SQLITE_OK;
  135265. }
  135266. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  135267. RtreeNode *pParent = pNode->pParent;
  135268. int rc = SQLITE_OK;
  135269. if( pParent ){
  135270. int ii;
  135271. int nCell = NCELL(pNode);
  135272. RtreeCell box; /* Bounding box for pNode */
  135273. nodeGetCell(pRtree, pNode, 0, &box);
  135274. for(ii=1; ii<nCell; ii++){
  135275. RtreeCell cell;
  135276. nodeGetCell(pRtree, pNode, ii, &cell);
  135277. cellUnion(pRtree, &box, &cell);
  135278. }
  135279. box.iRowid = pNode->iNode;
  135280. rc = nodeParentIndex(pRtree, pNode, &ii);
  135281. if( rc==SQLITE_OK ){
  135282. nodeOverwriteCell(pRtree, pParent, &box, ii);
  135283. rc = fixBoundingBox(pRtree, pParent);
  135284. }
  135285. }
  135286. return rc;
  135287. }
  135288. /*
  135289. ** Delete the cell at index iCell of node pNode. After removing the
  135290. ** cell, adjust the r-tree data structure if required.
  135291. */
  135292. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  135293. RtreeNode *pParent;
  135294. int rc;
  135295. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  135296. return rc;
  135297. }
  135298. /* Remove the cell from the node. This call just moves bytes around
  135299. ** the in-memory node image, so it cannot fail.
  135300. */
  135301. nodeDeleteCell(pRtree, pNode, iCell);
  135302. /* If the node is not the tree root and now has less than the minimum
  135303. ** number of cells, remove it from the tree. Otherwise, update the
  135304. ** cell in the parent node so that it tightly contains the updated
  135305. ** node.
  135306. */
  135307. pParent = pNode->pParent;
  135308. assert( pParent || pNode->iNode==1 );
  135309. if( pParent ){
  135310. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  135311. rc = removeNode(pRtree, pNode, iHeight);
  135312. }else{
  135313. rc = fixBoundingBox(pRtree, pNode);
  135314. }
  135315. }
  135316. return rc;
  135317. }
  135318. static int Reinsert(
  135319. Rtree *pRtree,
  135320. RtreeNode *pNode,
  135321. RtreeCell *pCell,
  135322. int iHeight
  135323. ){
  135324. int *aOrder;
  135325. int *aSpare;
  135326. RtreeCell *aCell;
  135327. RtreeDValue *aDistance;
  135328. int nCell;
  135329. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  135330. int iDim;
  135331. int ii;
  135332. int rc = SQLITE_OK;
  135333. int n;
  135334. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  135335. nCell = NCELL(pNode)+1;
  135336. n = (nCell+1)&(~1);
  135337. /* Allocate the buffers used by this operation. The allocation is
  135338. ** relinquished before this function returns.
  135339. */
  135340. aCell = (RtreeCell *)sqlite3_malloc(n * (
  135341. sizeof(RtreeCell) + /* aCell array */
  135342. sizeof(int) + /* aOrder array */
  135343. sizeof(int) + /* aSpare array */
  135344. sizeof(RtreeDValue) /* aDistance array */
  135345. ));
  135346. if( !aCell ){
  135347. return SQLITE_NOMEM;
  135348. }
  135349. aOrder = (int *)&aCell[n];
  135350. aSpare = (int *)&aOrder[n];
  135351. aDistance = (RtreeDValue *)&aSpare[n];
  135352. for(ii=0; ii<nCell; ii++){
  135353. if( ii==(nCell-1) ){
  135354. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  135355. }else{
  135356. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  135357. }
  135358. aOrder[ii] = ii;
  135359. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135360. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  135361. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  135362. }
  135363. }
  135364. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135365. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  135366. }
  135367. for(ii=0; ii<nCell; ii++){
  135368. aDistance[ii] = 0.0;
  135369. for(iDim=0; iDim<pRtree->nDim; iDim++){
  135370. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  135371. DCOORD(aCell[ii].aCoord[iDim*2]));
  135372. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  135373. }
  135374. }
  135375. SortByDistance(aOrder, nCell, aDistance, aSpare);
  135376. nodeZero(pRtree, pNode);
  135377. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  135378. RtreeCell *p = &aCell[aOrder[ii]];
  135379. nodeInsertCell(pRtree, pNode, p);
  135380. if( p->iRowid==pCell->iRowid ){
  135381. if( iHeight==0 ){
  135382. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  135383. }else{
  135384. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  135385. }
  135386. }
  135387. }
  135388. if( rc==SQLITE_OK ){
  135389. rc = fixBoundingBox(pRtree, pNode);
  135390. }
  135391. for(; rc==SQLITE_OK && ii<nCell; ii++){
  135392. /* Find a node to store this cell in. pNode->iNode currently contains
  135393. ** the height of the sub-tree headed by the cell.
  135394. */
  135395. RtreeNode *pInsert;
  135396. RtreeCell *p = &aCell[aOrder[ii]];
  135397. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  135398. if( rc==SQLITE_OK ){
  135399. int rc2;
  135400. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  135401. rc2 = nodeRelease(pRtree, pInsert);
  135402. if( rc==SQLITE_OK ){
  135403. rc = rc2;
  135404. }
  135405. }
  135406. }
  135407. sqlite3_free(aCell);
  135408. return rc;
  135409. }
  135410. /*
  135411. ** Insert cell pCell into node pNode. Node pNode is the head of a
  135412. ** subtree iHeight high (leaf nodes have iHeight==0).
  135413. */
  135414. static int rtreeInsertCell(
  135415. Rtree *pRtree,
  135416. RtreeNode *pNode,
  135417. RtreeCell *pCell,
  135418. int iHeight
  135419. ){
  135420. int rc = SQLITE_OK;
  135421. if( iHeight>0 ){
  135422. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  135423. if( pChild ){
  135424. nodeRelease(pRtree, pChild->pParent);
  135425. nodeReference(pNode);
  135426. pChild->pParent = pNode;
  135427. }
  135428. }
  135429. if( nodeInsertCell(pRtree, pNode, pCell) ){
  135430. #if VARIANT_RSTARTREE_REINSERT
  135431. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  135432. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  135433. }else{
  135434. pRtree->iReinsertHeight = iHeight;
  135435. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  135436. }
  135437. #else
  135438. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  135439. #endif
  135440. }else{
  135441. rc = AdjustTree(pRtree, pNode, pCell);
  135442. if( rc==SQLITE_OK ){
  135443. if( iHeight==0 ){
  135444. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  135445. }else{
  135446. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  135447. }
  135448. }
  135449. }
  135450. return rc;
  135451. }
  135452. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  135453. int ii;
  135454. int rc = SQLITE_OK;
  135455. int nCell = NCELL(pNode);
  135456. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  135457. RtreeNode *pInsert;
  135458. RtreeCell cell;
  135459. nodeGetCell(pRtree, pNode, ii, &cell);
  135460. /* Find a node to store this cell in. pNode->iNode currently contains
  135461. ** the height of the sub-tree headed by the cell.
  135462. */
  135463. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  135464. if( rc==SQLITE_OK ){
  135465. int rc2;
  135466. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  135467. rc2 = nodeRelease(pRtree, pInsert);
  135468. if( rc==SQLITE_OK ){
  135469. rc = rc2;
  135470. }
  135471. }
  135472. }
  135473. return rc;
  135474. }
  135475. /*
  135476. ** Select a currently unused rowid for a new r-tree record.
  135477. */
  135478. static int newRowid(Rtree *pRtree, i64 *piRowid){
  135479. int rc;
  135480. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  135481. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  135482. sqlite3_step(pRtree->pWriteRowid);
  135483. rc = sqlite3_reset(pRtree->pWriteRowid);
  135484. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  135485. return rc;
  135486. }
  135487. /*
  135488. ** Remove the entry with rowid=iDelete from the r-tree structure.
  135489. */
  135490. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  135491. int rc; /* Return code */
  135492. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  135493. int iCell; /* Index of iDelete cell in pLeaf */
  135494. RtreeNode *pRoot; /* Root node of rtree structure */
  135495. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  135496. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  135497. /* Obtain a reference to the leaf node that contains the entry
  135498. ** about to be deleted.
  135499. */
  135500. if( rc==SQLITE_OK ){
  135501. rc = findLeafNode(pRtree, iDelete, &pLeaf);
  135502. }
  135503. /* Delete the cell in question from the leaf node. */
  135504. if( rc==SQLITE_OK ){
  135505. int rc2;
  135506. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  135507. if( rc==SQLITE_OK ){
  135508. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  135509. }
  135510. rc2 = nodeRelease(pRtree, pLeaf);
  135511. if( rc==SQLITE_OK ){
  135512. rc = rc2;
  135513. }
  135514. }
  135515. /* Delete the corresponding entry in the <rtree>_rowid table. */
  135516. if( rc==SQLITE_OK ){
  135517. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  135518. sqlite3_step(pRtree->pDeleteRowid);
  135519. rc = sqlite3_reset(pRtree->pDeleteRowid);
  135520. }
  135521. /* Check if the root node now has exactly one child. If so, remove
  135522. ** it, schedule the contents of the child for reinsertion and
  135523. ** reduce the tree height by one.
  135524. **
  135525. ** This is equivalent to copying the contents of the child into
  135526. ** the root node (the operation that Gutman's paper says to perform
  135527. ** in this scenario).
  135528. */
  135529. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  135530. int rc2;
  135531. RtreeNode *pChild;
  135532. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  135533. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  135534. if( rc==SQLITE_OK ){
  135535. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  135536. }
  135537. rc2 = nodeRelease(pRtree, pChild);
  135538. if( rc==SQLITE_OK ) rc = rc2;
  135539. if( rc==SQLITE_OK ){
  135540. pRtree->iDepth--;
  135541. writeInt16(pRoot->zData, pRtree->iDepth);
  135542. pRoot->isDirty = 1;
  135543. }
  135544. }
  135545. /* Re-insert the contents of any underfull nodes removed from the tree. */
  135546. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  135547. if( rc==SQLITE_OK ){
  135548. rc = reinsertNodeContent(pRtree, pLeaf);
  135549. }
  135550. pRtree->pDeleted = pLeaf->pNext;
  135551. sqlite3_free(pLeaf);
  135552. }
  135553. /* Release the reference to the root node. */
  135554. if( rc==SQLITE_OK ){
  135555. rc = nodeRelease(pRtree, pRoot);
  135556. }else{
  135557. nodeRelease(pRtree, pRoot);
  135558. }
  135559. return rc;
  135560. }
  135561. /*
  135562. ** Rounding constants for float->double conversion.
  135563. */
  135564. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  135565. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  135566. #if !defined(SQLITE_RTREE_INT_ONLY)
  135567. /*
  135568. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  135569. ** while taking care to round toward negative or positive, respectively.
  135570. */
  135571. static RtreeValue rtreeValueDown(sqlite3_value *v){
  135572. double d = sqlite3_value_double(v);
  135573. float f = (float)d;
  135574. if( f>d ){
  135575. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  135576. }
  135577. return f;
  135578. }
  135579. static RtreeValue rtreeValueUp(sqlite3_value *v){
  135580. double d = sqlite3_value_double(v);
  135581. float f = (float)d;
  135582. if( f<d ){
  135583. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  135584. }
  135585. return f;
  135586. }
  135587. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  135588. /*
  135589. ** The xUpdate method for rtree module virtual tables.
  135590. */
  135591. static int rtreeUpdate(
  135592. sqlite3_vtab *pVtab,
  135593. int nData,
  135594. sqlite3_value **azData,
  135595. sqlite_int64 *pRowid
  135596. ){
  135597. Rtree *pRtree = (Rtree *)pVtab;
  135598. int rc = SQLITE_OK;
  135599. RtreeCell cell; /* New cell to insert if nData>1 */
  135600. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  135601. rtreeReference(pRtree);
  135602. assert(nData>=1);
  135603. /* Constraint handling. A write operation on an r-tree table may return
  135604. ** SQLITE_CONSTRAINT for two reasons:
  135605. **
  135606. ** 1. A duplicate rowid value, or
  135607. ** 2. The supplied data violates the "x2>=x1" constraint.
  135608. **
  135609. ** In the first case, if the conflict-handling mode is REPLACE, then
  135610. ** the conflicting row can be removed before proceeding. In the second
  135611. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  135612. ** conflict-handling mode specified by the user.
  135613. */
  135614. if( nData>1 ){
  135615. int ii;
  135616. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  135617. assert( nData==(pRtree->nDim*2 + 3) );
  135618. #ifndef SQLITE_RTREE_INT_ONLY
  135619. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  135620. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  135621. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  135622. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  135623. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  135624. rc = SQLITE_CONSTRAINT;
  135625. goto constraint;
  135626. }
  135627. }
  135628. }else
  135629. #endif
  135630. {
  135631. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  135632. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  135633. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  135634. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  135635. rc = SQLITE_CONSTRAINT;
  135636. goto constraint;
  135637. }
  135638. }
  135639. }
  135640. /* If a rowid value was supplied, check if it is already present in
  135641. ** the table. If so, the constraint has failed. */
  135642. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  135643. cell.iRowid = sqlite3_value_int64(azData[2]);
  135644. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  135645. || sqlite3_value_int64(azData[0])!=cell.iRowid
  135646. ){
  135647. int steprc;
  135648. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  135649. steprc = sqlite3_step(pRtree->pReadRowid);
  135650. rc = sqlite3_reset(pRtree->pReadRowid);
  135651. if( SQLITE_ROW==steprc ){
  135652. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  135653. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  135654. }else{
  135655. rc = SQLITE_CONSTRAINT;
  135656. goto constraint;
  135657. }
  135658. }
  135659. }
  135660. bHaveRowid = 1;
  135661. }
  135662. }
  135663. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  135664. ** record to delete from the r-tree table. The following block does
  135665. ** just that.
  135666. */
  135667. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  135668. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  135669. }
  135670. /* If the azData[] array contains more than one element, elements
  135671. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  135672. ** the r-tree structure.
  135673. */
  135674. if( rc==SQLITE_OK && nData>1 ){
  135675. /* Insert the new record into the r-tree */
  135676. RtreeNode *pLeaf = 0;
  135677. /* Figure out the rowid of the new row. */
  135678. if( bHaveRowid==0 ){
  135679. rc = newRowid(pRtree, &cell.iRowid);
  135680. }
  135681. *pRowid = cell.iRowid;
  135682. if( rc==SQLITE_OK ){
  135683. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  135684. }
  135685. if( rc==SQLITE_OK ){
  135686. int rc2;
  135687. pRtree->iReinsertHeight = -1;
  135688. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  135689. rc2 = nodeRelease(pRtree, pLeaf);
  135690. if( rc==SQLITE_OK ){
  135691. rc = rc2;
  135692. }
  135693. }
  135694. }
  135695. constraint:
  135696. rtreeRelease(pRtree);
  135697. return rc;
  135698. }
  135699. /*
  135700. ** The xRename method for rtree module virtual tables.
  135701. */
  135702. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  135703. Rtree *pRtree = (Rtree *)pVtab;
  135704. int rc = SQLITE_NOMEM;
  135705. char *zSql = sqlite3_mprintf(
  135706. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  135707. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  135708. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  135709. , pRtree->zDb, pRtree->zName, zNewName
  135710. , pRtree->zDb, pRtree->zName, zNewName
  135711. , pRtree->zDb, pRtree->zName, zNewName
  135712. );
  135713. if( zSql ){
  135714. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  135715. sqlite3_free(zSql);
  135716. }
  135717. return rc;
  135718. }
  135719. static sqlite3_module rtreeModule = {
  135720. 0, /* iVersion */
  135721. rtreeCreate, /* xCreate - create a table */
  135722. rtreeConnect, /* xConnect - connect to an existing table */
  135723. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  135724. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  135725. rtreeDestroy, /* xDestroy - Drop a table */
  135726. rtreeOpen, /* xOpen - open a cursor */
  135727. rtreeClose, /* xClose - close a cursor */
  135728. rtreeFilter, /* xFilter - configure scan constraints */
  135729. rtreeNext, /* xNext - advance a cursor */
  135730. rtreeEof, /* xEof */
  135731. rtreeColumn, /* xColumn - read data */
  135732. rtreeRowid, /* xRowid - read data */
  135733. rtreeUpdate, /* xUpdate - write data */
  135734. 0, /* xBegin - begin transaction */
  135735. 0, /* xSync - sync transaction */
  135736. 0, /* xCommit - commit transaction */
  135737. 0, /* xRollback - rollback transaction */
  135738. 0, /* xFindFunction - function overloading */
  135739. rtreeRename, /* xRename - rename the table */
  135740. 0, /* xSavepoint */
  135741. 0, /* xRelease */
  135742. 0 /* xRollbackTo */
  135743. };
  135744. static int rtreeSqlInit(
  135745. Rtree *pRtree,
  135746. sqlite3 *db,
  135747. const char *zDb,
  135748. const char *zPrefix,
  135749. int isCreate
  135750. ){
  135751. int rc = SQLITE_OK;
  135752. #define N_STATEMENT 9
  135753. static const char *azSql[N_STATEMENT] = {
  135754. /* Read and write the xxx_node table */
  135755. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  135756. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  135757. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  135758. /* Read and write the xxx_rowid table */
  135759. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  135760. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  135761. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  135762. /* Read and write the xxx_parent table */
  135763. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  135764. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  135765. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  135766. };
  135767. sqlite3_stmt **appStmt[N_STATEMENT];
  135768. int i;
  135769. pRtree->db = db;
  135770. if( isCreate ){
  135771. char *zCreate = sqlite3_mprintf(
  135772. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  135773. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  135774. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
  135775. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  135776. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  135777. );
  135778. if( !zCreate ){
  135779. return SQLITE_NOMEM;
  135780. }
  135781. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  135782. sqlite3_free(zCreate);
  135783. if( rc!=SQLITE_OK ){
  135784. return rc;
  135785. }
  135786. }
  135787. appStmt[0] = &pRtree->pReadNode;
  135788. appStmt[1] = &pRtree->pWriteNode;
  135789. appStmt[2] = &pRtree->pDeleteNode;
  135790. appStmt[3] = &pRtree->pReadRowid;
  135791. appStmt[4] = &pRtree->pWriteRowid;
  135792. appStmt[5] = &pRtree->pDeleteRowid;
  135793. appStmt[6] = &pRtree->pReadParent;
  135794. appStmt[7] = &pRtree->pWriteParent;
  135795. appStmt[8] = &pRtree->pDeleteParent;
  135796. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  135797. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  135798. if( zSql ){
  135799. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  135800. }else{
  135801. rc = SQLITE_NOMEM;
  135802. }
  135803. sqlite3_free(zSql);
  135804. }
  135805. return rc;
  135806. }
  135807. /*
  135808. ** The second argument to this function contains the text of an SQL statement
  135809. ** that returns a single integer value. The statement is compiled and executed
  135810. ** using database connection db. If successful, the integer value returned
  135811. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  135812. ** code is returned and the value of *piVal after returning is not defined.
  135813. */
  135814. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  135815. int rc = SQLITE_NOMEM;
  135816. if( zSql ){
  135817. sqlite3_stmt *pStmt = 0;
  135818. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  135819. if( rc==SQLITE_OK ){
  135820. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  135821. *piVal = sqlite3_column_int(pStmt, 0);
  135822. }
  135823. rc = sqlite3_finalize(pStmt);
  135824. }
  135825. }
  135826. return rc;
  135827. }
  135828. /*
  135829. ** This function is called from within the xConnect() or xCreate() method to
  135830. ** determine the node-size used by the rtree table being created or connected
  135831. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  135832. ** Otherwise, an SQLite error code is returned.
  135833. **
  135834. ** If this function is being called as part of an xConnect(), then the rtree
  135835. ** table already exists. In this case the node-size is determined by inspecting
  135836. ** the root node of the tree.
  135837. **
  135838. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  135839. ** This ensures that each node is stored on a single database page. If the
  135840. ** database page-size is so large that more than RTREE_MAXCELLS entries
  135841. ** would fit in a single node, use a smaller node-size.
  135842. */
  135843. static int getNodeSize(
  135844. sqlite3 *db, /* Database handle */
  135845. Rtree *pRtree, /* Rtree handle */
  135846. int isCreate, /* True for xCreate, false for xConnect */
  135847. char **pzErr /* OUT: Error message, if any */
  135848. ){
  135849. int rc;
  135850. char *zSql;
  135851. if( isCreate ){
  135852. int iPageSize = 0;
  135853. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  135854. rc = getIntFromStmt(db, zSql, &iPageSize);
  135855. if( rc==SQLITE_OK ){
  135856. pRtree->iNodeSize = iPageSize-64;
  135857. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  135858. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  135859. }
  135860. }else{
  135861. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135862. }
  135863. }else{
  135864. zSql = sqlite3_mprintf(
  135865. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  135866. pRtree->zDb, pRtree->zName
  135867. );
  135868. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  135869. if( rc!=SQLITE_OK ){
  135870. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135871. }
  135872. }
  135873. sqlite3_free(zSql);
  135874. return rc;
  135875. }
  135876. /*
  135877. ** This function is the implementation of both the xConnect and xCreate
  135878. ** methods of the r-tree virtual table.
  135879. **
  135880. ** argv[0] -> module name
  135881. ** argv[1] -> database name
  135882. ** argv[2] -> table name
  135883. ** argv[...] -> column names...
  135884. */
  135885. static int rtreeInit(
  135886. sqlite3 *db, /* Database connection */
  135887. void *pAux, /* One of the RTREE_COORD_* constants */
  135888. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  135889. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  135890. char **pzErr, /* OUT: Error message, if any */
  135891. int isCreate /* True for xCreate, false for xConnect */
  135892. ){
  135893. int rc = SQLITE_OK;
  135894. Rtree *pRtree;
  135895. int nDb; /* Length of string argv[1] */
  135896. int nName; /* Length of string argv[2] */
  135897. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  135898. const char *aErrMsg[] = {
  135899. 0, /* 0 */
  135900. "Wrong number of columns for an rtree table", /* 1 */
  135901. "Too few columns for an rtree table", /* 2 */
  135902. "Too many columns for an rtree table" /* 3 */
  135903. };
  135904. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  135905. if( aErrMsg[iErr] ){
  135906. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  135907. return SQLITE_ERROR;
  135908. }
  135909. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  135910. /* Allocate the sqlite3_vtab structure */
  135911. nDb = (int)strlen(argv[1]);
  135912. nName = (int)strlen(argv[2]);
  135913. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  135914. if( !pRtree ){
  135915. return SQLITE_NOMEM;
  135916. }
  135917. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  135918. pRtree->nBusy = 1;
  135919. pRtree->base.pModule = &rtreeModule;
  135920. pRtree->zDb = (char *)&pRtree[1];
  135921. pRtree->zName = &pRtree->zDb[nDb+1];
  135922. pRtree->nDim = (argc-4)/2;
  135923. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  135924. pRtree->eCoordType = eCoordType;
  135925. memcpy(pRtree->zDb, argv[1], nDb);
  135926. memcpy(pRtree->zName, argv[2], nName);
  135927. /* Figure out the node size to use. */
  135928. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  135929. /* Create/Connect to the underlying relational database schema. If
  135930. ** that is successful, call sqlite3_declare_vtab() to configure
  135931. ** the r-tree table schema.
  135932. */
  135933. if( rc==SQLITE_OK ){
  135934. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  135935. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135936. }else{
  135937. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  135938. char *zTmp;
  135939. int ii;
  135940. for(ii=4; zSql && ii<argc; ii++){
  135941. zTmp = zSql;
  135942. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  135943. sqlite3_free(zTmp);
  135944. }
  135945. if( zSql ){
  135946. zTmp = zSql;
  135947. zSql = sqlite3_mprintf("%s);", zTmp);
  135948. sqlite3_free(zTmp);
  135949. }
  135950. if( !zSql ){
  135951. rc = SQLITE_NOMEM;
  135952. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  135953. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  135954. }
  135955. sqlite3_free(zSql);
  135956. }
  135957. }
  135958. if( rc==SQLITE_OK ){
  135959. *ppVtab = (sqlite3_vtab *)pRtree;
  135960. }else{
  135961. rtreeRelease(pRtree);
  135962. }
  135963. return rc;
  135964. }
  135965. /*
  135966. ** Implementation of a scalar function that decodes r-tree nodes to
  135967. ** human readable strings. This can be used for debugging and analysis.
  135968. **
  135969. ** The scalar function takes two arguments, a blob of data containing
  135970. ** an r-tree node, and the number of dimensions the r-tree indexes.
  135971. ** For a two-dimensional r-tree structure called "rt", to deserialize
  135972. ** all nodes, a statement like:
  135973. **
  135974. ** SELECT rtreenode(2, data) FROM rt_node;
  135975. **
  135976. ** The human readable string takes the form of a Tcl list with one
  135977. ** entry for each cell in the r-tree node. Each entry is itself a
  135978. ** list, containing the 8-byte rowid/pageno followed by the
  135979. ** <num-dimension>*2 coordinates.
  135980. */
  135981. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  135982. char *zText = 0;
  135983. RtreeNode node;
  135984. Rtree tree;
  135985. int ii;
  135986. UNUSED_PARAMETER(nArg);
  135987. memset(&node, 0, sizeof(RtreeNode));
  135988. memset(&tree, 0, sizeof(Rtree));
  135989. tree.nDim = sqlite3_value_int(apArg[0]);
  135990. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  135991. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  135992. for(ii=0; ii<NCELL(&node); ii++){
  135993. char zCell[512];
  135994. int nCell = 0;
  135995. RtreeCell cell;
  135996. int jj;
  135997. nodeGetCell(&tree, &node, ii, &cell);
  135998. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  135999. nCell = (int)strlen(zCell);
  136000. for(jj=0; jj<tree.nDim*2; jj++){
  136001. #ifndef SQLITE_RTREE_INT_ONLY
  136002. sqlite3_snprintf(512-nCell,&zCell[nCell], " %f",
  136003. (double)cell.aCoord[jj].f);
  136004. #else
  136005. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  136006. cell.aCoord[jj].i);
  136007. #endif
  136008. nCell = (int)strlen(zCell);
  136009. }
  136010. if( zText ){
  136011. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  136012. sqlite3_free(zText);
  136013. zText = zTextNew;
  136014. }else{
  136015. zText = sqlite3_mprintf("{%s}", zCell);
  136016. }
  136017. }
  136018. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  136019. }
  136020. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  136021. UNUSED_PARAMETER(nArg);
  136022. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  136023. || sqlite3_value_bytes(apArg[0])<2
  136024. ){
  136025. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  136026. }else{
  136027. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  136028. sqlite3_result_int(ctx, readInt16(zBlob));
  136029. }
  136030. }
  136031. /*
  136032. ** Register the r-tree module with database handle db. This creates the
  136033. ** virtual table module "rtree" and the debugging/analysis scalar
  136034. ** function "rtreenode".
  136035. */
  136036. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  136037. const int utf8 = SQLITE_UTF8;
  136038. int rc;
  136039. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  136040. if( rc==SQLITE_OK ){
  136041. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  136042. }
  136043. if( rc==SQLITE_OK ){
  136044. #ifdef SQLITE_RTREE_INT_ONLY
  136045. void *c = (void *)RTREE_COORD_INT32;
  136046. #else
  136047. void *c = (void *)RTREE_COORD_REAL32;
  136048. #endif
  136049. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  136050. }
  136051. if( rc==SQLITE_OK ){
  136052. void *c = (void *)RTREE_COORD_INT32;
  136053. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  136054. }
  136055. return rc;
  136056. }
  136057. /*
  136058. ** A version of sqlite3_free() that can be used as a callback. This is used
  136059. ** in two places - as the destructor for the blob value returned by the
  136060. ** invocation of a geometry function, and as the destructor for the geometry
  136061. ** functions themselves.
  136062. */
  136063. static void doSqlite3Free(void *p){
  136064. sqlite3_free(p);
  136065. }
  136066. /*
  136067. ** Each call to sqlite3_rtree_geometry_callback() creates an ordinary SQLite
  136068. ** scalar user function. This C function is the callback used for all such
  136069. ** registered SQL functions.
  136070. **
  136071. ** The scalar user functions return a blob that is interpreted by r-tree
  136072. ** table MATCH operators.
  136073. */
  136074. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  136075. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  136076. RtreeMatchArg *pBlob;
  136077. int nBlob;
  136078. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  136079. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  136080. if( !pBlob ){
  136081. sqlite3_result_error_nomem(ctx);
  136082. }else{
  136083. int i;
  136084. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  136085. pBlob->xGeom = pGeomCtx->xGeom;
  136086. pBlob->pContext = pGeomCtx->pContext;
  136087. pBlob->nParam = nArg;
  136088. for(i=0; i<nArg; i++){
  136089. #ifdef SQLITE_RTREE_INT_ONLY
  136090. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  136091. #else
  136092. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  136093. #endif
  136094. }
  136095. sqlite3_result_blob(ctx, pBlob, nBlob, doSqlite3Free);
  136096. }
  136097. }
  136098. /*
  136099. ** Register a new geometry function for use with the r-tree MATCH operator.
  136100. */
  136101. SQLITE_API int sqlite3_rtree_geometry_callback(
  136102. sqlite3 *db,
  136103. const char *zGeom,
  136104. int (*xGeom)(sqlite3_rtree_geometry *, int, RtreeDValue *, int *),
  136105. void *pContext
  136106. ){
  136107. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  136108. /* Allocate and populate the context object. */
  136109. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  136110. if( !pGeomCtx ) return SQLITE_NOMEM;
  136111. pGeomCtx->xGeom = xGeom;
  136112. pGeomCtx->pContext = pContext;
  136113. /* Create the new user-function. Register a destructor function to delete
  136114. ** the context object when it is no longer required. */
  136115. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  136116. (void *)pGeomCtx, geomCallback, 0, 0, doSqlite3Free
  136117. );
  136118. }
  136119. #if !SQLITE_CORE
  136120. #ifdef _WIN32
  136121. __declspec(dllexport)
  136122. #endif
  136123. SQLITE_API int sqlite3_rtree_init(
  136124. sqlite3 *db,
  136125. char **pzErrMsg,
  136126. const sqlite3_api_routines *pApi
  136127. ){
  136128. SQLITE_EXTENSION_INIT2(pApi)
  136129. return sqlite3RtreeInit(db);
  136130. }
  136131. #endif
  136132. #endif
  136133. /************** End of rtree.c ***********************************************/
  136134. /************** Begin file icu.c *********************************************/
  136135. /*
  136136. ** 2007 May 6
  136137. **
  136138. ** The author disclaims copyright to this source code. In place of
  136139. ** a legal notice, here is a blessing:
  136140. **
  136141. ** May you do good and not evil.
  136142. ** May you find forgiveness for yourself and forgive others.
  136143. ** May you share freely, never taking more than you give.
  136144. **
  136145. *************************************************************************
  136146. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  136147. **
  136148. ** This file implements an integration between the ICU library
  136149. ** ("International Components for Unicode", an open-source library
  136150. ** for handling unicode data) and SQLite. The integration uses
  136151. ** ICU to provide the following to SQLite:
  136152. **
  136153. ** * An implementation of the SQL regexp() function (and hence REGEXP
  136154. ** operator) using the ICU uregex_XX() APIs.
  136155. **
  136156. ** * Implementations of the SQL scalar upper() and lower() functions
  136157. ** for case mapping.
  136158. **
  136159. ** * Integration of ICU and SQLite collation sequences.
  136160. **
  136161. ** * An implementation of the LIKE operator that uses ICU to
  136162. ** provide case-independent matching.
  136163. */
  136164. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  136165. /* Include ICU headers */
  136166. #include <unicode/utypes.h>
  136167. #include <unicode/uregex.h>
  136168. #include <unicode/ustring.h>
  136169. #include <unicode/ucol.h>
  136170. /* #include <assert.h> */
  136171. #ifndef SQLITE_CORE
  136172. SQLITE_EXTENSION_INIT1
  136173. #else
  136174. #endif
  136175. /*
  136176. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  136177. ** operator.
  136178. */
  136179. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  136180. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  136181. #endif
  136182. /*
  136183. ** Version of sqlite3_free() that is always a function, never a macro.
  136184. */
  136185. static void xFree(void *p){
  136186. sqlite3_free(p);
  136187. }
  136188. /*
  136189. ** Compare two UTF-8 strings for equality where the first string is
  136190. ** a "LIKE" expression. Return true (1) if they are the same and
  136191. ** false (0) if they are different.
  136192. */
  136193. static int icuLikeCompare(
  136194. const uint8_t *zPattern, /* LIKE pattern */
  136195. const uint8_t *zString, /* The UTF-8 string to compare against */
  136196. const UChar32 uEsc /* The escape character */
  136197. ){
  136198. static const int MATCH_ONE = (UChar32)'_';
  136199. static const int MATCH_ALL = (UChar32)'%';
  136200. int iPattern = 0; /* Current byte index in zPattern */
  136201. int iString = 0; /* Current byte index in zString */
  136202. int prevEscape = 0; /* True if the previous character was uEsc */
  136203. while( zPattern[iPattern]!=0 ){
  136204. /* Read (and consume) the next character from the input pattern. */
  136205. UChar32 uPattern;
  136206. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  136207. assert(uPattern!=0);
  136208. /* There are now 4 possibilities:
  136209. **
  136210. ** 1. uPattern is an unescaped match-all character "%",
  136211. ** 2. uPattern is an unescaped match-one character "_",
  136212. ** 3. uPattern is an unescaped escape character, or
  136213. ** 4. uPattern is to be handled as an ordinary character
  136214. */
  136215. if( !prevEscape && uPattern==MATCH_ALL ){
  136216. /* Case 1. */
  136217. uint8_t c;
  136218. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  136219. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  136220. ** test string.
  136221. */
  136222. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  136223. if( c==MATCH_ONE ){
  136224. if( zString[iString]==0 ) return 0;
  136225. U8_FWD_1_UNSAFE(zString, iString);
  136226. }
  136227. iPattern++;
  136228. }
  136229. if( zPattern[iPattern]==0 ) return 1;
  136230. while( zString[iString] ){
  136231. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  136232. return 1;
  136233. }
  136234. U8_FWD_1_UNSAFE(zString, iString);
  136235. }
  136236. return 0;
  136237. }else if( !prevEscape && uPattern==MATCH_ONE ){
  136238. /* Case 2. */
  136239. if( zString[iString]==0 ) return 0;
  136240. U8_FWD_1_UNSAFE(zString, iString);
  136241. }else if( !prevEscape && uPattern==uEsc){
  136242. /* Case 3. */
  136243. prevEscape = 1;
  136244. }else{
  136245. /* Case 4. */
  136246. UChar32 uString;
  136247. U8_NEXT_UNSAFE(zString, iString, uString);
  136248. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  136249. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  136250. if( uString!=uPattern ){
  136251. return 0;
  136252. }
  136253. prevEscape = 0;
  136254. }
  136255. }
  136256. return zString[iString]==0;
  136257. }
  136258. /*
  136259. ** Implementation of the like() SQL function. This function implements
  136260. ** the build-in LIKE operator. The first argument to the function is the
  136261. ** pattern and the second argument is the string. So, the SQL statements:
  136262. **
  136263. ** A LIKE B
  136264. **
  136265. ** is implemented as like(B, A). If there is an escape character E,
  136266. **
  136267. ** A LIKE B ESCAPE E
  136268. **
  136269. ** is mapped to like(B, A, E).
  136270. */
  136271. static void icuLikeFunc(
  136272. sqlite3_context *context,
  136273. int argc,
  136274. sqlite3_value **argv
  136275. ){
  136276. const unsigned char *zA = sqlite3_value_text(argv[0]);
  136277. const unsigned char *zB = sqlite3_value_text(argv[1]);
  136278. UChar32 uEsc = 0;
  136279. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  136280. ** of deep recursion and N*N behavior in patternCompare().
  136281. */
  136282. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  136283. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  136284. return;
  136285. }
  136286. if( argc==3 ){
  136287. /* The escape character string must consist of a single UTF-8 character.
  136288. ** Otherwise, return an error.
  136289. */
  136290. int nE= sqlite3_value_bytes(argv[2]);
  136291. const unsigned char *zE = sqlite3_value_text(argv[2]);
  136292. int i = 0;
  136293. if( zE==0 ) return;
  136294. U8_NEXT(zE, i, nE, uEsc);
  136295. if( i!=nE){
  136296. sqlite3_result_error(context,
  136297. "ESCAPE expression must be a single character", -1);
  136298. return;
  136299. }
  136300. }
  136301. if( zA && zB ){
  136302. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  136303. }
  136304. }
  136305. /*
  136306. ** This function is called when an ICU function called from within
  136307. ** the implementation of an SQL scalar function returns an error.
  136308. **
  136309. ** The scalar function context passed as the first argument is
  136310. ** loaded with an error message based on the following two args.
  136311. */
  136312. static void icuFunctionError(
  136313. sqlite3_context *pCtx, /* SQLite scalar function context */
  136314. const char *zName, /* Name of ICU function that failed */
  136315. UErrorCode e /* Error code returned by ICU function */
  136316. ){
  136317. char zBuf[128];
  136318. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  136319. zBuf[127] = '\0';
  136320. sqlite3_result_error(pCtx, zBuf, -1);
  136321. }
  136322. /*
  136323. ** Function to delete compiled regexp objects. Registered as
  136324. ** a destructor function with sqlite3_set_auxdata().
  136325. */
  136326. static void icuRegexpDelete(void *p){
  136327. URegularExpression *pExpr = (URegularExpression *)p;
  136328. uregex_close(pExpr);
  136329. }
  136330. /*
  136331. ** Implementation of SQLite REGEXP operator. This scalar function takes
  136332. ** two arguments. The first is a regular expression pattern to compile
  136333. ** the second is a string to match against that pattern. If either
  136334. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  136335. ** is 1 if the string matches the pattern, or 0 otherwise.
  136336. **
  136337. ** SQLite maps the regexp() function to the regexp() operator such
  136338. ** that the following two are equivalent:
  136339. **
  136340. ** zString REGEXP zPattern
  136341. ** regexp(zPattern, zString)
  136342. **
  136343. ** Uses the following ICU regexp APIs:
  136344. **
  136345. ** uregex_open()
  136346. ** uregex_matches()
  136347. ** uregex_close()
  136348. */
  136349. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  136350. UErrorCode status = U_ZERO_ERROR;
  136351. URegularExpression *pExpr;
  136352. UBool res;
  136353. const UChar *zString = sqlite3_value_text16(apArg[1]);
  136354. (void)nArg; /* Unused parameter */
  136355. /* If the left hand side of the regexp operator is NULL,
  136356. ** then the result is also NULL.
  136357. */
  136358. if( !zString ){
  136359. return;
  136360. }
  136361. pExpr = sqlite3_get_auxdata(p, 0);
  136362. if( !pExpr ){
  136363. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  136364. if( !zPattern ){
  136365. return;
  136366. }
  136367. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  136368. if( U_SUCCESS(status) ){
  136369. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  136370. }else{
  136371. assert(!pExpr);
  136372. icuFunctionError(p, "uregex_open", status);
  136373. return;
  136374. }
  136375. }
  136376. /* Configure the text that the regular expression operates on. */
  136377. uregex_setText(pExpr, zString, -1, &status);
  136378. if( !U_SUCCESS(status) ){
  136379. icuFunctionError(p, "uregex_setText", status);
  136380. return;
  136381. }
  136382. /* Attempt the match */
  136383. res = uregex_matches(pExpr, 0, &status);
  136384. if( !U_SUCCESS(status) ){
  136385. icuFunctionError(p, "uregex_matches", status);
  136386. return;
  136387. }
  136388. /* Set the text that the regular expression operates on to a NULL
  136389. ** pointer. This is not really necessary, but it is tidier than
  136390. ** leaving the regular expression object configured with an invalid
  136391. ** pointer after this function returns.
  136392. */
  136393. uregex_setText(pExpr, 0, 0, &status);
  136394. /* Return 1 or 0. */
  136395. sqlite3_result_int(p, res ? 1 : 0);
  136396. }
  136397. /*
  136398. ** Implementations of scalar functions for case mapping - upper() and
  136399. ** lower(). Function upper() converts its input to upper-case (ABC).
  136400. ** Function lower() converts to lower-case (abc).
  136401. **
  136402. ** ICU provides two types of case mapping, "general" case mapping and
  136403. ** "language specific". Refer to ICU documentation for the differences
  136404. ** between the two.
  136405. **
  136406. ** To utilise "general" case mapping, the upper() or lower() scalar
  136407. ** functions are invoked with one argument:
  136408. **
  136409. ** upper('ABC') -> 'abc'
  136410. ** lower('abc') -> 'ABC'
  136411. **
  136412. ** To access ICU "language specific" case mapping, upper() or lower()
  136413. ** should be invoked with two arguments. The second argument is the name
  136414. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  136415. ** as the second argument is the same as invoking the 1 argument version
  136416. ** of upper() or lower().
  136417. **
  136418. ** lower('I', 'en_us') -> 'i'
  136419. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  136420. **
  136421. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  136422. */
  136423. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  136424. const UChar *zInput;
  136425. UChar *zOutput;
  136426. int nInput;
  136427. int nOutput;
  136428. UErrorCode status = U_ZERO_ERROR;
  136429. const char *zLocale = 0;
  136430. assert(nArg==1 || nArg==2);
  136431. if( nArg==2 ){
  136432. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  136433. }
  136434. zInput = sqlite3_value_text16(apArg[0]);
  136435. if( !zInput ){
  136436. return;
  136437. }
  136438. nInput = sqlite3_value_bytes16(apArg[0]);
  136439. nOutput = nInput * 2 + 2;
  136440. zOutput = sqlite3_malloc(nOutput);
  136441. if( !zOutput ){
  136442. return;
  136443. }
  136444. if( sqlite3_user_data(p) ){
  136445. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  136446. }else{
  136447. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  136448. }
  136449. if( !U_SUCCESS(status) ){
  136450. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  136451. return;
  136452. }
  136453. sqlite3_result_text16(p, zOutput, -1, xFree);
  136454. }
  136455. /*
  136456. ** Collation sequence destructor function. The pCtx argument points to
  136457. ** a UCollator structure previously allocated using ucol_open().
  136458. */
  136459. static void icuCollationDel(void *pCtx){
  136460. UCollator *p = (UCollator *)pCtx;
  136461. ucol_close(p);
  136462. }
  136463. /*
  136464. ** Collation sequence comparison function. The pCtx argument points to
  136465. ** a UCollator structure previously allocated using ucol_open().
  136466. */
  136467. static int icuCollationColl(
  136468. void *pCtx,
  136469. int nLeft,
  136470. const void *zLeft,
  136471. int nRight,
  136472. const void *zRight
  136473. ){
  136474. UCollationResult res;
  136475. UCollator *p = (UCollator *)pCtx;
  136476. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  136477. switch( res ){
  136478. case UCOL_LESS: return -1;
  136479. case UCOL_GREATER: return +1;
  136480. case UCOL_EQUAL: return 0;
  136481. }
  136482. assert(!"Unexpected return value from ucol_strcoll()");
  136483. return 0;
  136484. }
  136485. /*
  136486. ** Implementation of the scalar function icu_load_collation().
  136487. **
  136488. ** This scalar function is used to add ICU collation based collation
  136489. ** types to an SQLite database connection. It is intended to be called
  136490. ** as follows:
  136491. **
  136492. ** SELECT icu_load_collation(<locale>, <collation-name>);
  136493. **
  136494. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  136495. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  136496. ** collation sequence to create.
  136497. */
  136498. static void icuLoadCollation(
  136499. sqlite3_context *p,
  136500. int nArg,
  136501. sqlite3_value **apArg
  136502. ){
  136503. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  136504. UErrorCode status = U_ZERO_ERROR;
  136505. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  136506. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  136507. UCollator *pUCollator; /* ICU library collation object */
  136508. int rc; /* Return code from sqlite3_create_collation_x() */
  136509. assert(nArg==2);
  136510. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  136511. zName = (const char *)sqlite3_value_text(apArg[1]);
  136512. if( !zLocale || !zName ){
  136513. return;
  136514. }
  136515. pUCollator = ucol_open(zLocale, &status);
  136516. if( !U_SUCCESS(status) ){
  136517. icuFunctionError(p, "ucol_open", status);
  136518. return;
  136519. }
  136520. assert(p);
  136521. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  136522. icuCollationColl, icuCollationDel
  136523. );
  136524. if( rc!=SQLITE_OK ){
  136525. ucol_close(pUCollator);
  136526. sqlite3_result_error(p, "Error registering collation function", -1);
  136527. }
  136528. }
  136529. /*
  136530. ** Register the ICU extension functions with database db.
  136531. */
  136532. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  136533. struct IcuScalar {
  136534. const char *zName; /* Function name */
  136535. int nArg; /* Number of arguments */
  136536. int enc; /* Optimal text encoding */
  136537. void *pContext; /* sqlite3_user_data() context */
  136538. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  136539. } scalars[] = {
  136540. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  136541. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  136542. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  136543. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  136544. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  136545. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  136546. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  136547. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  136548. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  136549. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  136550. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  136551. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  136552. };
  136553. int rc = SQLITE_OK;
  136554. int i;
  136555. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  136556. struct IcuScalar *p = &scalars[i];
  136557. rc = sqlite3_create_function(
  136558. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  136559. );
  136560. }
  136561. return rc;
  136562. }
  136563. #if !SQLITE_CORE
  136564. #ifdef _WIN32
  136565. __declspec(dllexport)
  136566. #endif
  136567. SQLITE_API int sqlite3_icu_init(
  136568. sqlite3 *db,
  136569. char **pzErrMsg,
  136570. const sqlite3_api_routines *pApi
  136571. ){
  136572. SQLITE_EXTENSION_INIT2(pApi)
  136573. return sqlite3IcuInit(db);
  136574. }
  136575. #endif
  136576. #endif
  136577. /************** End of icu.c *************************************************/
  136578. /************** Begin file fts3_icu.c ****************************************/
  136579. /*
  136580. ** 2007 June 22
  136581. **
  136582. ** The author disclaims copyright to this source code. In place of
  136583. ** a legal notice, here is a blessing:
  136584. **
  136585. ** May you do good and not evil.
  136586. ** May you find forgiveness for yourself and forgive others.
  136587. ** May you share freely, never taking more than you give.
  136588. **
  136589. *************************************************************************
  136590. ** This file implements a tokenizer for fts3 based on the ICU library.
  136591. */
  136592. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  136593. #ifdef SQLITE_ENABLE_ICU
  136594. /* #include <assert.h> */
  136595. /* #include <string.h> */
  136596. #include <unicode/ubrk.h>
  136597. /* #include <unicode/ucol.h> */
  136598. /* #include <unicode/ustring.h> */
  136599. #include <unicode/utf16.h>
  136600. typedef struct IcuTokenizer IcuTokenizer;
  136601. typedef struct IcuCursor IcuCursor;
  136602. struct IcuTokenizer {
  136603. sqlite3_tokenizer base;
  136604. char *zLocale;
  136605. };
  136606. struct IcuCursor {
  136607. sqlite3_tokenizer_cursor base;
  136608. UBreakIterator *pIter; /* ICU break-iterator object */
  136609. int nChar; /* Number of UChar elements in pInput */
  136610. UChar *aChar; /* Copy of input using utf-16 encoding */
  136611. int *aOffset; /* Offsets of each character in utf-8 input */
  136612. int nBuffer;
  136613. char *zBuffer;
  136614. int iToken;
  136615. };
  136616. /*
  136617. ** Create a new tokenizer instance.
  136618. */
  136619. static int icuCreate(
  136620. int argc, /* Number of entries in argv[] */
  136621. const char * const *argv, /* Tokenizer creation arguments */
  136622. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  136623. ){
  136624. IcuTokenizer *p;
  136625. int n = 0;
  136626. if( argc>0 ){
  136627. n = strlen(argv[0])+1;
  136628. }
  136629. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  136630. if( !p ){
  136631. return SQLITE_NOMEM;
  136632. }
  136633. memset(p, 0, sizeof(IcuTokenizer));
  136634. if( n ){
  136635. p->zLocale = (char *)&p[1];
  136636. memcpy(p->zLocale, argv[0], n);
  136637. }
  136638. *ppTokenizer = (sqlite3_tokenizer *)p;
  136639. return SQLITE_OK;
  136640. }
  136641. /*
  136642. ** Destroy a tokenizer
  136643. */
  136644. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  136645. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  136646. sqlite3_free(p);
  136647. return SQLITE_OK;
  136648. }
  136649. /*
  136650. ** Prepare to begin tokenizing a particular string. The input
  136651. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  136652. ** used to incrementally tokenize this string is returned in
  136653. ** *ppCursor.
  136654. */
  136655. static int icuOpen(
  136656. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  136657. const char *zInput, /* Input string */
  136658. int nInput, /* Length of zInput in bytes */
  136659. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  136660. ){
  136661. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  136662. IcuCursor *pCsr;
  136663. const int32_t opt = U_FOLD_CASE_DEFAULT;
  136664. UErrorCode status = U_ZERO_ERROR;
  136665. int nChar;
  136666. UChar32 c;
  136667. int iInput = 0;
  136668. int iOut = 0;
  136669. *ppCursor = 0;
  136670. if( zInput==0 ){
  136671. nInput = 0;
  136672. zInput = "";
  136673. }else if( nInput<0 ){
  136674. nInput = strlen(zInput);
  136675. }
  136676. nChar = nInput+1;
  136677. pCsr = (IcuCursor *)sqlite3_malloc(
  136678. sizeof(IcuCursor) + /* IcuCursor */
  136679. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  136680. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  136681. );
  136682. if( !pCsr ){
  136683. return SQLITE_NOMEM;
  136684. }
  136685. memset(pCsr, 0, sizeof(IcuCursor));
  136686. pCsr->aChar = (UChar *)&pCsr[1];
  136687. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  136688. pCsr->aOffset[iOut] = iInput;
  136689. U8_NEXT(zInput, iInput, nInput, c);
  136690. while( c>0 ){
  136691. int isError = 0;
  136692. c = u_foldCase(c, opt);
  136693. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  136694. if( isError ){
  136695. sqlite3_free(pCsr);
  136696. return SQLITE_ERROR;
  136697. }
  136698. pCsr->aOffset[iOut] = iInput;
  136699. if( iInput<nInput ){
  136700. U8_NEXT(zInput, iInput, nInput, c);
  136701. }else{
  136702. c = 0;
  136703. }
  136704. }
  136705. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  136706. if( !U_SUCCESS(status) ){
  136707. sqlite3_free(pCsr);
  136708. return SQLITE_ERROR;
  136709. }
  136710. pCsr->nChar = iOut;
  136711. ubrk_first(pCsr->pIter);
  136712. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  136713. return SQLITE_OK;
  136714. }
  136715. /*
  136716. ** Close a tokenization cursor previously opened by a call to icuOpen().
  136717. */
  136718. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  136719. IcuCursor *pCsr = (IcuCursor *)pCursor;
  136720. ubrk_close(pCsr->pIter);
  136721. sqlite3_free(pCsr->zBuffer);
  136722. sqlite3_free(pCsr);
  136723. return SQLITE_OK;
  136724. }
  136725. /*
  136726. ** Extract the next token from a tokenization cursor.
  136727. */
  136728. static int icuNext(
  136729. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  136730. const char **ppToken, /* OUT: *ppToken is the token text */
  136731. int *pnBytes, /* OUT: Number of bytes in token */
  136732. int *piStartOffset, /* OUT: Starting offset of token */
  136733. int *piEndOffset, /* OUT: Ending offset of token */
  136734. int *piPosition /* OUT: Position integer of token */
  136735. ){
  136736. IcuCursor *pCsr = (IcuCursor *)pCursor;
  136737. int iStart = 0;
  136738. int iEnd = 0;
  136739. int nByte = 0;
  136740. while( iStart==iEnd ){
  136741. UChar32 c;
  136742. iStart = ubrk_current(pCsr->pIter);
  136743. iEnd = ubrk_next(pCsr->pIter);
  136744. if( iEnd==UBRK_DONE ){
  136745. return SQLITE_DONE;
  136746. }
  136747. while( iStart<iEnd ){
  136748. int iWhite = iStart;
  136749. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  136750. if( u_isspace(c) ){
  136751. iStart = iWhite;
  136752. }else{
  136753. break;
  136754. }
  136755. }
  136756. assert(iStart<=iEnd);
  136757. }
  136758. do {
  136759. UErrorCode status = U_ZERO_ERROR;
  136760. if( nByte ){
  136761. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  136762. if( !zNew ){
  136763. return SQLITE_NOMEM;
  136764. }
  136765. pCsr->zBuffer = zNew;
  136766. pCsr->nBuffer = nByte;
  136767. }
  136768. u_strToUTF8(
  136769. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  136770. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  136771. &status /* Output success/failure */
  136772. );
  136773. } while( nByte>pCsr->nBuffer );
  136774. *ppToken = pCsr->zBuffer;
  136775. *pnBytes = nByte;
  136776. *piStartOffset = pCsr->aOffset[iStart];
  136777. *piEndOffset = pCsr->aOffset[iEnd];
  136778. *piPosition = pCsr->iToken++;
  136779. return SQLITE_OK;
  136780. }
  136781. /*
  136782. ** The set of routines that implement the simple tokenizer
  136783. */
  136784. static const sqlite3_tokenizer_module icuTokenizerModule = {
  136785. 0, /* iVersion */
  136786. icuCreate, /* xCreate */
  136787. icuDestroy, /* xCreate */
  136788. icuOpen, /* xOpen */
  136789. icuClose, /* xClose */
  136790. icuNext, /* xNext */
  136791. };
  136792. /*
  136793. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  136794. */
  136795. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  136796. sqlite3_tokenizer_module const**ppModule
  136797. ){
  136798. *ppModule = &icuTokenizerModule;
  136799. }
  136800. #endif /* defined(SQLITE_ENABLE_ICU) */
  136801. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  136802. /************** End of fts3_icu.c ********************************************/