No Description

090-restore-sqlite2.patch 1.6MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845
  1. --- /dev/null
  2. +++ b/ext/sqlite/config.m4
  3. @@ -0,0 +1,157 @@
  4. +dnl $Id$
  5. +dnl config.m4 for extension sqlite
  6. +dnl vim:et:ts=2:sw=2
  7. +
  8. +PHP_ARG_WITH(sqlite, for sqlite support,
  9. +[ --without-sqlite=DIR Do not include sqlite support. DIR is the sqlite base
  10. + install directory [BUNDLED]], yes)
  11. +
  12. +PHP_ARG_ENABLE(sqlite-utf8, whether to enable UTF-8 support in sqlite (default: ISO-8859-1),
  13. +[ --enable-sqlite-utf8 SQLite: Enable UTF-8 support for SQLite], no, no)
  14. +
  15. +
  16. +
  17. +dnl
  18. +dnl PHP_PROG_LEMON
  19. +dnl
  20. +dnl Search for lemon binary and check its version
  21. +dnl
  22. +AC_DEFUN([PHP_PROG_LEMON],[
  23. + # we only support certain lemon versions
  24. + lemon_version_list="1.0"
  25. +
  26. + AC_CHECK_PROG(LEMON, lemon, lemon)
  27. + if test "$LEMON"; then
  28. + AC_CACHE_CHECK([for lemon version], php_cv_lemon_version, [
  29. + lemon_version=`$LEMON -x 2>/dev/null | $SED -e 's/^.* //'`
  30. + php_cv_lemon_version=invalid
  31. + for lemon_check_version in $lemon_version_list; do
  32. + if test "$lemon_version" = "$lemon_check_version"; then
  33. + php_cv_lemon_version="$lemon_check_version (ok)"
  34. + fi
  35. + done
  36. + ])
  37. + else
  38. + lemon_version=none
  39. + fi
  40. + case $php_cv_lemon_version in
  41. + ""|invalid[)]
  42. + lemon_msg="lemon versions supported for regeneration of libsqlite parsers: $lemon_version_list (found: $lemon_version)."
  43. + AC_MSG_WARN([$lemon_msg])
  44. + LEMON="exit 0;"
  45. + ;;
  46. + esac
  47. + PHP_SUBST(LEMON)
  48. +])
  49. +
  50. +
  51. +if test "$PHP_SQLITE" != "no"; then
  52. + if test "$PHP_PDO" != "no"; then
  53. + PHP_CHECK_PDO_INCLUDES([], [AC_MSG_WARN([Cannot find php_pdo_driver.h.])])
  54. + if test -n "$pdo_inc_path"; then
  55. + AC_DEFINE([PHP_SQLITE2_HAVE_PDO], [1], [Have PDO])
  56. + pdo_inc_path="-I$pdo_inc_path"
  57. + fi
  58. + fi
  59. +
  60. + if test "$PHP_SQLITE" != "yes"; then
  61. + SEARCH_PATH="/usr/local /usr"
  62. + SEARCH_FOR="/include/sqlite.h"
  63. + if test -r $PHP_SQLITE/; then # path given as parameter
  64. + SQLITE_DIR=$PHP_SQLITE
  65. + else # search default path list
  66. + AC_MSG_CHECKING([for sqlite files in default path])
  67. + for i in $SEARCH_PATH ; do
  68. + if test -r $i/$SEARCH_FOR; then
  69. + SQLITE_DIR=$i
  70. + AC_MSG_RESULT(found in $i)
  71. + fi
  72. + done
  73. + fi
  74. +
  75. + if test -z "$SQLITE_DIR"; then
  76. + AC_MSG_RESULT([not found])
  77. + AC_MSG_ERROR([Please reinstall the sqlite distribution from http://www.sqlite.org])
  78. + fi
  79. +
  80. + PHP_CHECK_LIBRARY(sqlite, sqlite_open, [
  81. + PHP_ADD_LIBRARY_WITH_PATH(sqlite, $SQLITE_DIR/$PHP_LIBDIR, SQLITE_SHARED_LIBADD)
  82. + PHP_ADD_INCLUDE($SQLITE_DIR/include)
  83. + ],[
  84. + AC_MSG_ERROR([wrong sqlite lib version or lib not found])
  85. + ],[
  86. + -L$SQLITE_DIR/$PHP_LIBDIR -lm
  87. + ])
  88. + SQLITE_MODULE_TYPE=external
  89. + PHP_SQLITE_CFLAGS=$pdo_inc_path
  90. + sqlite_extra_sources="libsqlite/src/encode.c"
  91. + else
  92. + # use bundled library
  93. + PHP_PROG_LEMON
  94. + SQLITE_MODULE_TYPE=builtin
  95. + PHP_SQLITE_CFLAGS="-I@ext_srcdir@/libsqlite/src -I@ext_builddir@/libsqlite/src $pdo_inc_path"
  96. + sqlite_extra_sources="libsqlite/src/opcodes.c \
  97. + libsqlite/src/parse.c libsqlite/src/encode.c \
  98. + libsqlite/src/auth.c libsqlite/src/btree.c libsqlite/src/build.c \
  99. + libsqlite/src/delete.c libsqlite/src/expr.c libsqlite/src/func.c \
  100. + libsqlite/src/hash.c libsqlite/src/insert.c libsqlite/src/main.c \
  101. + libsqlite/src/os.c libsqlite/src/pager.c \
  102. + libsqlite/src/printf.c libsqlite/src/random.c \
  103. + libsqlite/src/select.c libsqlite/src/table.c libsqlite/src/tokenize.c \
  104. + libsqlite/src/update.c libsqlite/src/util.c libsqlite/src/vdbe.c \
  105. + libsqlite/src/attach.c libsqlite/src/btree_rb.c libsqlite/src/pragma.c \
  106. + libsqlite/src/vacuum.c libsqlite/src/copy.c \
  107. + libsqlite/src/vdbeaux.c libsqlite/src/date.c \
  108. + libsqlite/src/where.c libsqlite/src/trigger.c"
  109. + fi
  110. + dnl
  111. + dnl Common for both bundled/external
  112. + dnl
  113. + sqlite_sources="sqlite.c sess_sqlite.c pdo_sqlite2.c $sqlite_extra_sources"
  114. + PHP_NEW_EXTENSION(sqlite, $sqlite_sources, $ext_shared,,$PHP_SQLITE_CFLAGS)
  115. + PHP_ADD_EXTENSION_DEP(sqlite, spl, true)
  116. + PHP_ADD_EXTENSION_DEP(sqlite, pdo, true)
  117. +
  118. + PHP_ADD_MAKEFILE_FRAGMENT
  119. + PHP_SUBST(SQLITE_SHARED_LIBADD)
  120. + PHP_INSTALL_HEADERS([$ext_builddir/libsqlite/src/sqlite.h])
  121. +
  122. + if test "$SQLITE_MODULE_TYPE" = "builtin"; then
  123. + PHP_ADD_BUILD_DIR($ext_builddir/libsqlite/src, 1)
  124. + AC_CHECK_SIZEOF(char *, 4)
  125. + AC_DEFINE(SQLITE_PTR_SZ, SIZEOF_CHAR_P, [Size of a pointer])
  126. + dnl use latin 1 for SQLite older than 2.8.9; the utf-8 handling
  127. + dnl in funcs.c uses assert(), which is a bit silly and something
  128. + dnl we want to avoid. This assert() was removed in SQLite 2.8.9.
  129. + if test "$PHP_SQLITE_UTF8" = "yes"; then
  130. + SQLITE_ENCODING="UTF8"
  131. + AC_DEFINE(SQLITE_UTF8, 1, [ ])
  132. + else
  133. + SQLITE_ENCODING="ISO8859"
  134. + fi
  135. + PHP_SUBST(SQLITE_ENCODING)
  136. +
  137. + SQLITE_VERSION=`cat $ext_srcdir/libsqlite/VERSION`
  138. + PHP_SUBST(SQLITE_VERSION)
  139. +
  140. + sed -e s/--VERS--/$SQLITE_VERSION/ -e s/--ENCODING--/$SQLITE_ENCODING/ $ext_srcdir/libsqlite/src/sqlite.h.in > $ext_builddir/libsqlite/src/sqlite.h
  141. +
  142. + if test "$ext_shared" = "no" || test "$ext_srcdir" != "$abs_srcdir"; then
  143. + echo '#include <php_config.h>' > $ext_builddir/libsqlite/src/config.h
  144. + else
  145. + echo "#include \"$abs_builddir/config.h\"" > $ext_builddir/libsqlite/src/config.h
  146. + fi
  147. +
  148. + cat >> $ext_builddir/libsqlite/src/config.h <<EOF
  149. +#if ZTS
  150. +# define THREADSAFE 1
  151. +#endif
  152. +#if !ZEND_DEBUG
  153. +# define NDEBUG
  154. +#endif
  155. +EOF
  156. + fi
  157. +
  158. + AC_CHECK_FUNCS(usleep nanosleep)
  159. + AC_CHECK_HEADERS(time.h)
  160. +fi
  161. --- /dev/null
  162. +++ b/ext/sqlite/config.w32
  163. @@ -0,0 +1,39 @@
  164. +// $Id$
  165. +// vim:ft=javascript
  166. +
  167. +ARG_WITH("sqlite", "SQLite support", "no");
  168. +
  169. +if (PHP_SQLITE != "no") {
  170. + copy_and_subst(configure_module_dirname + "\\libsqlite\\src\\sqlite.h.in",
  171. + configure_module_dirname + "\\libsqlite\\src\\sqlite.h", new Array(
  172. + "--VERS--", file_get_contents(configure_module_dirname + "\\libsqlite\\VERSION").replace(new RegExp("[\r\n]+", "g"), ""),
  173. + "--ENCODING--", "ISO8859"
  174. + ));
  175. +
  176. + FSO.CopyFile(configure_module_dirname + "\\libsqlite\\src\\sqlite_config.w32.h",
  177. + configure_module_dirname + "\\libsqlite\\src\\config.h");
  178. +
  179. + if (FSO.FileExists(configure_module_dirname + "\\..\\pdo\\php_pdo_driver.h")) {
  180. + PHP_SQLITE2_PDO_CFLAGS = " /DPHP_SQLITE2_HAVE_PDO=1 /I " + configure_module_dirname + "\\..";
  181. + ADD_EXTENSION_DEP('sqlite', 'pdo')
  182. + } else {
  183. + PHP_SQLITE2_PDO_CFLAGS = "";
  184. + }
  185. +
  186. + EXTENSION("sqlite", "sqlite.c sess_sqlite.c pdo_sqlite2.c", null,
  187. + "/D PHP_SQLITE_EXPORTS /I " + configure_module_dirname + "/libsqlite/src" +
  188. + PHP_SQLITE2_PDO_CFLAGS);
  189. +
  190. +
  191. + ADD_SOURCES(configure_module_dirname + "/libsqlite/src", "opcodes.c parse.c encode.c \
  192. + auth.c btree.c build.c delete.c expr.c func.c hash.c insert.c \
  193. + main.c os.c pager.c printf.c random.c select.c table.c tokenize.c \
  194. + update.c util.c vdbe.c attach.c btree_rb.c pragma.c vacuum.c \
  195. + copy.c where.c trigger.c vdbeaux.c date.c", "sqlite");
  196. +
  197. + AC_DEFINE("HAVE_SQLITE", 1, "SQLite support");
  198. + if (!PHP_SQLITE_SHARED) {
  199. + ADD_DEF_FILE(configure_module_dirname + "\\php_sqlite.def");
  200. + }
  201. + ADD_EXTENSION_DEP('sqlite', 'spl')
  202. +}
  203. --- /dev/null
  204. +++ b/ext/sqlite/CREDITS
  205. @@ -0,0 +1,2 @@
  206. +SQLite
  207. +Wez Furlong, Tal Peer, Marcus Boerger, Ilia Alshanetsky
  208. --- /dev/null
  209. +++ b/ext/sqlite/libsqlite/README
  210. @@ -0,0 +1,37 @@
  211. +This directory contains source code to
  212. +
  213. + SQLite: An Embeddable SQL Database Engine
  214. +
  215. +To compile the project, first create a directory in which to place
  216. +the build products. It is recommended, but not required, that the
  217. +build directory be separate from the source directory. Cd into the
  218. +build directory and then from the build directory run the configure
  219. +script found at the root of the source tree. Then run "make".
  220. +
  221. +For example:
  222. +
  223. + tar xzf sqlite.tar.gz ;# Unpack the source tree into "sqlite"
  224. + mkdir bld ;# Build will occur in a sibling directory
  225. + cd bld ;# Change to the build directory
  226. + ../sqlite/configure ;# Run the configure script
  227. + make ;# Run the makefile.
  228. +
  229. +The configure script uses autoconf 2.50 and libtool. If the configure
  230. +script does not work out for you, there is a generic makefile named
  231. +"Makefile.linux-gcc" in the top directory of the source tree that you
  232. +can copy and edit to suite your needs. Comments on the generic makefile
  233. +show what changes are needed.
  234. +
  235. +The linux binaries on the website are created using the generic makefile,
  236. +not the configure script. The configure script is unmaintained. (You
  237. +can volunteer to take over maintenance of the configure script, if you want!)
  238. +The windows binaries on the website are created using MinGW32 configured
  239. +as a cross-compiler running under Linux. For details, see the ./publish.sh
  240. +script at the top-level of the source tree.
  241. +
  242. +Contacts:
  243. +
  244. + http://www.sqlite.org/
  245. + http://www.hwaci.com/sw/sqlite/
  246. + http://groups.yahoo.com/group/sqlite/
  247. + drh@hwaci.com
  248. --- /dev/null
  249. +++ b/ext/sqlite/libsqlite/src/attach.c
  250. @@ -0,0 +1,311 @@
  251. +/*
  252. +** 2003 April 6
  253. +**
  254. +** The author disclaims copyright to this source code. In place of
  255. +** a legal notice, here is a blessing:
  256. +**
  257. +** May you do good and not evil.
  258. +** May you find forgiveness for yourself and forgive others.
  259. +** May you share freely, never taking more than you give.
  260. +**
  261. +*************************************************************************
  262. +** This file contains code used to implement the ATTACH and DETACH commands.
  263. +**
  264. +** $Id$
  265. +*/
  266. +#include "sqliteInt.h"
  267. +
  268. +/*
  269. +** This routine is called by the parser to process an ATTACH statement:
  270. +**
  271. +** ATTACH DATABASE filename AS dbname
  272. +**
  273. +** The pFilename and pDbname arguments are the tokens that define the
  274. +** filename and dbname in the ATTACH statement.
  275. +*/
  276. +void sqliteAttach(Parse *pParse, Token *pFilename, Token *pDbname, Token *pKey){
  277. + Db *aNew;
  278. + int rc, i;
  279. + char *zFile, *zName;
  280. + sqlite *db;
  281. + Vdbe *v;
  282. +
  283. + v = sqliteGetVdbe(pParse);
  284. + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
  285. + if( pParse->explain ) return;
  286. + db = pParse->db;
  287. + if( db->file_format<4 ){
  288. + sqliteErrorMsg(pParse, "cannot attach auxiliary databases to an "
  289. + "older format master database", 0);
  290. + pParse->rc = SQLITE_ERROR;
  291. + return;
  292. + }
  293. + if( db->nDb>=MAX_ATTACHED+2 ){
  294. + sqliteErrorMsg(pParse, "too many attached databases - max %d",
  295. + MAX_ATTACHED);
  296. + pParse->rc = SQLITE_ERROR;
  297. + return;
  298. + }
  299. +
  300. + zFile = 0;
  301. + sqliteSetNString(&zFile, pFilename->z, pFilename->n, 0);
  302. + if( zFile==0 ) return;
  303. + sqliteDequote(zFile);
  304. +#ifndef SQLITE_OMIT_AUTHORIZATION
  305. + if( sqliteAuthCheck(pParse, SQLITE_ATTACH, zFile, 0, 0)!=SQLITE_OK ){
  306. + sqliteFree(zFile);
  307. + return;
  308. + }
  309. +#endif /* SQLITE_OMIT_AUTHORIZATION */
  310. +
  311. + zName = 0;
  312. + sqliteSetNString(&zName, pDbname->z, pDbname->n, 0);
  313. + if( zName==0 ) return;
  314. + sqliteDequote(zName);
  315. + for(i=0; i<db->nDb; i++){
  316. + if( db->aDb[i].zName && sqliteStrICmp(db->aDb[i].zName, zName)==0 ){
  317. + sqliteErrorMsg(pParse, "database %z is already in use", zName);
  318. + pParse->rc = SQLITE_ERROR;
  319. + sqliteFree(zFile);
  320. + return;
  321. + }
  322. + }
  323. +
  324. + if( db->aDb==db->aDbStatic ){
  325. + aNew = sqliteMalloc( sizeof(db->aDb[0])*3 );
  326. + if( aNew==0 ) return;
  327. + memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  328. + }else{
  329. + aNew = sqliteRealloc(db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  330. + if( aNew==0 ) return;
  331. + }
  332. + db->aDb = aNew;
  333. + aNew = &db->aDb[db->nDb++];
  334. + memset(aNew, 0, sizeof(*aNew));
  335. + sqliteHashInit(&aNew->tblHash, SQLITE_HASH_STRING, 0);
  336. + sqliteHashInit(&aNew->idxHash, SQLITE_HASH_STRING, 0);
  337. + sqliteHashInit(&aNew->trigHash, SQLITE_HASH_STRING, 0);
  338. + sqliteHashInit(&aNew->aFKey, SQLITE_HASH_STRING, 1);
  339. + aNew->zName = zName;
  340. + rc = sqliteBtreeFactory(db, zFile, 0, MAX_PAGES, &aNew->pBt);
  341. + if( rc ){
  342. + sqliteErrorMsg(pParse, "unable to open database: %s", zFile);
  343. + }
  344. +#if SQLITE_HAS_CODEC
  345. + {
  346. + extern int sqliteCodecAttach(sqlite*, int, void*, int);
  347. + char *zKey = 0;
  348. + int nKey;
  349. + if( pKey && pKey->z && pKey->n ){
  350. + sqliteSetNString(&zKey, pKey->z, pKey->n, 0);
  351. + sqliteDequote(zKey);
  352. + nKey = strlen(zKey);
  353. + }else{
  354. + zKey = 0;
  355. + nKey = 0;
  356. + }
  357. + sqliteCodecAttach(db, db->nDb-1, zKey, nKey);
  358. + }
  359. +#endif
  360. + sqliteFree(zFile);
  361. + db->flags &= ~SQLITE_Initialized;
  362. + if( pParse->nErr ) return;
  363. + if( rc==SQLITE_OK ){
  364. + rc = sqliteInit(pParse->db, &pParse->zErrMsg);
  365. + }
  366. + if( rc ){
  367. + int i = db->nDb - 1;
  368. + assert( i>=2 );
  369. + if( db->aDb[i].pBt ){
  370. + sqliteBtreeClose(db->aDb[i].pBt);
  371. + db->aDb[i].pBt = 0;
  372. + }
  373. + sqliteResetInternalSchema(db, 0);
  374. + pParse->nErr++;
  375. + pParse->rc = SQLITE_ERROR;
  376. + }
  377. +}
  378. +
  379. +/*
  380. +** This routine is called by the parser to process a DETACH statement:
  381. +**
  382. +** DETACH DATABASE dbname
  383. +**
  384. +** The pDbname argument is the name of the database in the DETACH statement.
  385. +*/
  386. +void sqliteDetach(Parse *pParse, Token *pDbname){
  387. + int i;
  388. + sqlite *db;
  389. + Vdbe *v;
  390. + Db *pDb;
  391. +
  392. + v = sqliteGetVdbe(pParse);
  393. + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
  394. + if( pParse->explain ) return;
  395. + db = pParse->db;
  396. + for(i=0; i<db->nDb; i++){
  397. + pDb = &db->aDb[i];
  398. + if( pDb->pBt==0 || pDb->zName==0 ) continue;
  399. + if( strlen(pDb->zName)!=pDbname->n ) continue;
  400. + if( sqliteStrNICmp(pDb->zName, pDbname->z, pDbname->n)==0 ) break;
  401. + }
  402. + if( i>=db->nDb ){
  403. + sqliteErrorMsg(pParse, "no such database: %T", pDbname);
  404. + return;
  405. + }
  406. + if( i<2 ){
  407. + sqliteErrorMsg(pParse, "cannot detach database %T", pDbname);
  408. + return;
  409. + }
  410. +#ifndef SQLITE_OMIT_AUTHORIZATION
  411. + if( sqliteAuthCheck(pParse,SQLITE_DETACH,db->aDb[i].zName,0,0)!=SQLITE_OK ){
  412. + return;
  413. + }
  414. +#endif /* SQLITE_OMIT_AUTHORIZATION */
  415. + sqliteBtreeClose(pDb->pBt);
  416. + pDb->pBt = 0;
  417. + sqliteFree(pDb->zName);
  418. + sqliteResetInternalSchema(db, i);
  419. + if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
  420. + db->nDb--;
  421. + if( i<db->nDb ){
  422. + db->aDb[i] = db->aDb[db->nDb];
  423. + memset(&db->aDb[db->nDb], 0, sizeof(db->aDb[0]));
  424. + sqliteResetInternalSchema(db, i);
  425. + }
  426. +}
  427. +
  428. +/*
  429. +** Initialize a DbFixer structure. This routine must be called prior
  430. +** to passing the structure to one of the sqliteFixAAAA() routines below.
  431. +**
  432. +** The return value indicates whether or not fixation is required. TRUE
  433. +** means we do need to fix the database references, FALSE means we do not.
  434. +*/
  435. +int sqliteFixInit(
  436. + DbFixer *pFix, /* The fixer to be initialized */
  437. + Parse *pParse, /* Error messages will be written here */
  438. + int iDb, /* This is the database that must must be used */
  439. + const char *zType, /* "view", "trigger", or "index" */
  440. + const Token *pName /* Name of the view, trigger, or index */
  441. +){
  442. + sqlite *db;
  443. +
  444. + if( iDb<0 || iDb==1 ) return 0;
  445. + db = pParse->db;
  446. + assert( db->nDb>iDb );
  447. + pFix->pParse = pParse;
  448. + pFix->zDb = db->aDb[iDb].zName;
  449. + pFix->zType = zType;
  450. + pFix->pName = pName;
  451. + return 1;
  452. +}
  453. +
  454. +/*
  455. +** The following set of routines walk through the parse tree and assign
  456. +** a specific database to all table references where the database name
  457. +** was left unspecified in the original SQL statement. The pFix structure
  458. +** must have been initialized by a prior call to sqliteFixInit().
  459. +**
  460. +** These routines are used to make sure that an index, trigger, or
  461. +** view in one database does not refer to objects in a different database.
  462. +** (Exception: indices, triggers, and views in the TEMP database are
  463. +** allowed to refer to anything.) If a reference is explicitly made
  464. +** to an object in a different database, an error message is added to
  465. +** pParse->zErrMsg and these routines return non-zero. If everything
  466. +** checks out, these routines return 0.
  467. +*/
  468. +int sqliteFixSrcList(
  469. + DbFixer *pFix, /* Context of the fixation */
  470. + SrcList *pList /* The Source list to check and modify */
  471. +){
  472. + int i;
  473. + const char *zDb;
  474. +
  475. + if( pList==0 ) return 0;
  476. + zDb = pFix->zDb;
  477. + for(i=0; i<pList->nSrc; i++){
  478. + if( pList->a[i].zDatabase==0 ){
  479. + pList->a[i].zDatabase = sqliteStrDup(zDb);
  480. + }else if( sqliteStrICmp(pList->a[i].zDatabase,zDb)!=0 ){
  481. + sqliteErrorMsg(pFix->pParse,
  482. + "%s %z cannot reference objects in database %s",
  483. + pFix->zType, sqliteStrNDup(pFix->pName->z, pFix->pName->n),
  484. + pList->a[i].zDatabase);
  485. + return 1;
  486. + }
  487. + if( sqliteFixSelect(pFix, pList->a[i].pSelect) ) return 1;
  488. + if( sqliteFixExpr(pFix, pList->a[i].pOn) ) return 1;
  489. + }
  490. + return 0;
  491. +}
  492. +int sqliteFixSelect(
  493. + DbFixer *pFix, /* Context of the fixation */
  494. + Select *pSelect /* The SELECT statement to be fixed to one database */
  495. +){
  496. + while( pSelect ){
  497. + if( sqliteFixExprList(pFix, pSelect->pEList) ){
  498. + return 1;
  499. + }
  500. + if( sqliteFixSrcList(pFix, pSelect->pSrc) ){
  501. + return 1;
  502. + }
  503. + if( sqliteFixExpr(pFix, pSelect->pWhere) ){
  504. + return 1;
  505. + }
  506. + if( sqliteFixExpr(pFix, pSelect->pHaving) ){
  507. + return 1;
  508. + }
  509. + pSelect = pSelect->pPrior;
  510. + }
  511. + return 0;
  512. +}
  513. +int sqliteFixExpr(
  514. + DbFixer *pFix, /* Context of the fixation */
  515. + Expr *pExpr /* The expression to be fixed to one database */
  516. +){
  517. + while( pExpr ){
  518. + if( sqliteFixSelect(pFix, pExpr->pSelect) ){
  519. + return 1;
  520. + }
  521. + if( sqliteFixExprList(pFix, pExpr->pList) ){
  522. + return 1;
  523. + }
  524. + if( sqliteFixExpr(pFix, pExpr->pRight) ){
  525. + return 1;
  526. + }
  527. + pExpr = pExpr->pLeft;
  528. + }
  529. + return 0;
  530. +}
  531. +int sqliteFixExprList(
  532. + DbFixer *pFix, /* Context of the fixation */
  533. + ExprList *pList /* The expression to be fixed to one database */
  534. +){
  535. + int i;
  536. + if( pList==0 ) return 0;
  537. + for(i=0; i<pList->nExpr; i++){
  538. + if( sqliteFixExpr(pFix, pList->a[i].pExpr) ){
  539. + return 1;
  540. + }
  541. + }
  542. + return 0;
  543. +}
  544. +int sqliteFixTriggerStep(
  545. + DbFixer *pFix, /* Context of the fixation */
  546. + TriggerStep *pStep /* The trigger step be fixed to one database */
  547. +){
  548. + while( pStep ){
  549. + if( sqliteFixSelect(pFix, pStep->pSelect) ){
  550. + return 1;
  551. + }
  552. + if( sqliteFixExpr(pFix, pStep->pWhere) ){
  553. + return 1;
  554. + }
  555. + if( sqliteFixExprList(pFix, pStep->pExprList) ){
  556. + return 1;
  557. + }
  558. + pStep = pStep->pNext;
  559. + }
  560. + return 0;
  561. +}
  562. --- /dev/null
  563. +++ b/ext/sqlite/libsqlite/src/auth.c
  564. @@ -0,0 +1,219 @@
  565. +/*
  566. +** 2003 January 11
  567. +**
  568. +** The author disclaims copyright to this source code. In place of
  569. +** a legal notice, here is a blessing:
  570. +**
  571. +** May you do good and not evil.
  572. +** May you find forgiveness for yourself and forgive others.
  573. +** May you share freely, never taking more than you give.
  574. +**
  575. +*************************************************************************
  576. +** This file contains code used to implement the sqlite_set_authorizer()
  577. +** API. This facility is an optional feature of the library. Embedded
  578. +** systems that do not need this facility may omit it by recompiling
  579. +** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  580. +**
  581. +** $Id$
  582. +*/
  583. +#include "sqliteInt.h"
  584. +
  585. +/*
  586. +** All of the code in this file may be omitted by defining a single
  587. +** macro.
  588. +*/
  589. +#ifndef SQLITE_OMIT_AUTHORIZATION
  590. +
  591. +/*
  592. +** Set or clear the access authorization function.
  593. +**
  594. +** The access authorization function is be called during the compilation
  595. +** phase to verify that the user has read and/or write access permission on
  596. +** various fields of the database. The first argument to the auth function
  597. +** is a copy of the 3rd argument to this routine. The second argument
  598. +** to the auth function is one of these constants:
  599. +**
  600. +** SQLITE_COPY
  601. +** SQLITE_CREATE_INDEX
  602. +** SQLITE_CREATE_TABLE
  603. +** SQLITE_CREATE_TEMP_INDEX
  604. +** SQLITE_CREATE_TEMP_TABLE
  605. +** SQLITE_CREATE_TEMP_TRIGGER
  606. +** SQLITE_CREATE_TEMP_VIEW
  607. +** SQLITE_CREATE_TRIGGER
  608. +** SQLITE_CREATE_VIEW
  609. +** SQLITE_DELETE
  610. +** SQLITE_DROP_INDEX
  611. +** SQLITE_DROP_TABLE
  612. +** SQLITE_DROP_TEMP_INDEX
  613. +** SQLITE_DROP_TEMP_TABLE
  614. +** SQLITE_DROP_TEMP_TRIGGER
  615. +** SQLITE_DROP_TEMP_VIEW
  616. +** SQLITE_DROP_TRIGGER
  617. +** SQLITE_DROP_VIEW
  618. +** SQLITE_INSERT
  619. +** SQLITE_PRAGMA
  620. +** SQLITE_READ
  621. +** SQLITE_SELECT
  622. +** SQLITE_TRANSACTION
  623. +** SQLITE_UPDATE
  624. +**
  625. +** The third and fourth arguments to the auth function are the name of
  626. +** the table and the column that are being accessed. The auth function
  627. +** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  628. +** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  629. +** means that the SQL statement will never-run - the sqlite_exec() call
  630. +** will return with an error. SQLITE_IGNORE means that the SQL statement
  631. +** should run but attempts to read the specified column will return NULL
  632. +** and attempts to write the column will be ignored.
  633. +**
  634. +** Setting the auth function to NULL disables this hook. The default
  635. +** setting of the auth function is NULL.
  636. +*/
  637. +int sqlite_set_authorizer(
  638. + sqlite *db,
  639. + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  640. + void *pArg
  641. +){
  642. + db->xAuth = xAuth;
  643. + db->pAuthArg = pArg;
  644. + return SQLITE_OK;
  645. +}
  646. +
  647. +/*
  648. +** Write an error message into pParse->zErrMsg that explains that the
  649. +** user-supplied authorization function returned an illegal value.
  650. +*/
  651. +static void sqliteAuthBadReturnCode(Parse *pParse, int rc){
  652. + sqliteErrorMsg(pParse, "illegal return value (%d) from the "
  653. + "authorization function - should be SQLITE_OK, SQLITE_IGNORE, "
  654. + "or SQLITE_DENY", rc);
  655. + pParse->rc = SQLITE_MISUSE;
  656. +}
  657. +
  658. +/*
  659. +** The pExpr should be a TK_COLUMN expression. The table referred to
  660. +** is in pTabList or else it is the NEW or OLD table of a trigger.
  661. +** Check to see if it is OK to read this particular column.
  662. +**
  663. +** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  664. +** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  665. +** then generate an error.
  666. +*/
  667. +void sqliteAuthRead(
  668. + Parse *pParse, /* The parser context */
  669. + Expr *pExpr, /* The expression to check authorization on */
  670. + SrcList *pTabList /* All table that pExpr might refer to */
  671. +){
  672. + sqlite *db = pParse->db;
  673. + int rc;
  674. + Table *pTab; /* The table being read */
  675. + const char *zCol; /* Name of the column of the table */
  676. + int iSrc; /* Index in pTabList->a[] of table being read */
  677. + const char *zDBase; /* Name of database being accessed */
  678. + TriggerStack *pStack; /* The stack of current triggers */
  679. +
  680. + if( db->xAuth==0 ) return;
  681. + assert( pExpr->op==TK_COLUMN );
  682. + for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
  683. + if( pExpr->iTable==pTabList->a[iSrc].iCursor ) break;
  684. + }
  685. + if( iSrc>=0 && iSrc<pTabList->nSrc ){
  686. + pTab = pTabList->a[iSrc].pTab;
  687. + }else if( (pStack = pParse->trigStack)!=0 ){
  688. + /* This must be an attempt to read the NEW or OLD pseudo-tables
  689. + ** of a trigger.
  690. + */
  691. + assert( pExpr->iTable==pStack->newIdx || pExpr->iTable==pStack->oldIdx );
  692. + pTab = pStack->pTab;
  693. + }else{
  694. + return;
  695. + }
  696. + if( pTab==0 ) return;
  697. + if( pExpr->iColumn>=0 ){
  698. + assert( pExpr->iColumn<pTab->nCol );
  699. + zCol = pTab->aCol[pExpr->iColumn].zName;
  700. + }else if( pTab->iPKey>=0 ){
  701. + assert( pTab->iPKey<pTab->nCol );
  702. + zCol = pTab->aCol[pTab->iPKey].zName;
  703. + }else{
  704. + zCol = "ROWID";
  705. + }
  706. + assert( pExpr->iDb<db->nDb );
  707. + zDBase = db->aDb[pExpr->iDb].zName;
  708. + rc = db->xAuth(db->pAuthArg, SQLITE_READ, pTab->zName, zCol, zDBase,
  709. + pParse->zAuthContext);
  710. + if( rc==SQLITE_IGNORE ){
  711. + pExpr->op = TK_NULL;
  712. + }else if( rc==SQLITE_DENY ){
  713. + if( db->nDb>2 || pExpr->iDb!=0 ){
  714. + sqliteErrorMsg(pParse, "access to %s.%s.%s is prohibited",
  715. + zDBase, pTab->zName, zCol);
  716. + }else{
  717. + sqliteErrorMsg(pParse, "access to %s.%s is prohibited", pTab->zName,zCol);
  718. + }
  719. + pParse->rc = SQLITE_AUTH;
  720. + }else if( rc!=SQLITE_OK ){
  721. + sqliteAuthBadReturnCode(pParse, rc);
  722. + }
  723. +}
  724. +
  725. +/*
  726. +** Do an authorization check using the code and arguments given. Return
  727. +** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  728. +** is returned, then the error count and error message in pParse are
  729. +** modified appropriately.
  730. +*/
  731. +int sqliteAuthCheck(
  732. + Parse *pParse,
  733. + int code,
  734. + const char *zArg1,
  735. + const char *zArg2,
  736. + const char *zArg3
  737. +){
  738. + sqlite *db = pParse->db;
  739. + int rc;
  740. +
  741. + if( db->init.busy || db->xAuth==0 ){
  742. + return SQLITE_OK;
  743. + }
  744. + rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
  745. + if( rc==SQLITE_DENY ){
  746. + sqliteErrorMsg(pParse, "not authorized");
  747. + pParse->rc = SQLITE_AUTH;
  748. + }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  749. + rc = SQLITE_DENY;
  750. + sqliteAuthBadReturnCode(pParse, rc);
  751. + }
  752. + return rc;
  753. +}
  754. +
  755. +/*
  756. +** Push an authorization context. After this routine is called, the
  757. +** zArg3 argument to authorization callbacks will be zContext until
  758. +** popped. Or if pParse==0, this routine is a no-op.
  759. +*/
  760. +void sqliteAuthContextPush(
  761. + Parse *pParse,
  762. + AuthContext *pContext,
  763. + const char *zContext
  764. +){
  765. + pContext->pParse = pParse;
  766. + if( pParse ){
  767. + pContext->zAuthContext = pParse->zAuthContext;
  768. + pParse->zAuthContext = zContext;
  769. + }
  770. +}
  771. +
  772. +/*
  773. +** Pop an authorization context that was previously pushed
  774. +** by sqliteAuthContextPush
  775. +*/
  776. +void sqliteAuthContextPop(AuthContext *pContext){
  777. + if( pContext->pParse ){
  778. + pContext->pParse->zAuthContext = pContext->zAuthContext;
  779. + pContext->pParse = 0;
  780. + }
  781. +}
  782. +
  783. +#endif /* SQLITE_OMIT_AUTHORIZATION */
  784. --- /dev/null
  785. +++ b/ext/sqlite/libsqlite/src/btree.c
  786. @@ -0,0 +1,3584 @@
  787. +/*
  788. +** 2001 September 15
  789. +**
  790. +** The author disclaims copyright to this source code. In place of
  791. +** a legal notice, here is a blessing:
  792. +**
  793. +** May you do good and not evil.
  794. +** May you find forgiveness for yourself and forgive others.
  795. +** May you share freely, never taking more than you give.
  796. +**
  797. +*************************************************************************
  798. +** $Id$
  799. +**
  800. +** This file implements a external (disk-based) database using BTrees.
  801. +** For a detailed discussion of BTrees, refer to
  802. +**
  803. +** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  804. +** "Sorting And Searching", pages 473-480. Addison-Wesley
  805. +** Publishing Company, Reading, Massachusetts.
  806. +**
  807. +** The basic idea is that each page of the file contains N database
  808. +** entries and N+1 pointers to subpages.
  809. +**
  810. +** ----------------------------------------------------------------
  811. +** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N) | Ptr(N+1) |
  812. +** ----------------------------------------------------------------
  813. +**
  814. +** All of the keys on the page that Ptr(0) points to have values less
  815. +** than Key(0). All of the keys on page Ptr(1) and its subpages have
  816. +** values greater than Key(0) and less than Key(1). All of the keys
  817. +** on Ptr(N+1) and its subpages have values greater than Key(N). And
  818. +** so forth.
  819. +**
  820. +** Finding a particular key requires reading O(log(M)) pages from the
  821. +** disk where M is the number of entries in the tree.
  822. +**
  823. +** In this implementation, a single file can hold one or more separate
  824. +** BTrees. Each BTree is identified by the index of its root page. The
  825. +** key and data for any entry are combined to form the "payload". Up to
  826. +** MX_LOCAL_PAYLOAD bytes of payload can be carried directly on the
  827. +** database page. If the payload is larger than MX_LOCAL_PAYLOAD bytes
  828. +** then surplus bytes are stored on overflow pages. The payload for an
  829. +** entry and the preceding pointer are combined to form a "Cell". Each
  830. +** page has a small header which contains the Ptr(N+1) pointer.
  831. +**
  832. +** The first page of the file contains a magic string used to verify that
  833. +** the file really is a valid BTree database, a pointer to a list of unused
  834. +** pages in the file, and some meta information. The root of the first
  835. +** BTree begins on page 2 of the file. (Pages are numbered beginning with
  836. +** 1, not 0.) Thus a minimum database contains 2 pages.
  837. +*/
  838. +#include "sqliteInt.h"
  839. +#include "pager.h"
  840. +#include "btree.h"
  841. +#include <assert.h>
  842. +
  843. +/* Forward declarations */
  844. +static BtOps sqliteBtreeOps;
  845. +static BtCursorOps sqliteBtreeCursorOps;
  846. +
  847. +/*
  848. +** Macros used for byteswapping. B is a pointer to the Btree
  849. +** structure. This is needed to access the Btree.needSwab boolean
  850. +** in order to tell if byte swapping is needed or not.
  851. +** X is an unsigned integer. SWAB16 byte swaps a 16-bit integer.
  852. +** SWAB32 byteswaps a 32-bit integer.
  853. +*/
  854. +#define SWAB16(B,X) ((B)->needSwab? swab16((u16)X) : ((u16)X))
  855. +#define SWAB32(B,X) ((B)->needSwab? swab32(X) : (X))
  856. +#define SWAB_ADD(B,X,A) \
  857. + if((B)->needSwab){ X=swab32(swab32(X)+A); }else{ X += (A); }
  858. +
  859. +/*
  860. +** The following global variable - available only if SQLITE_TEST is
  861. +** defined - is used to determine whether new databases are created in
  862. +** native byte order or in non-native byte order. Non-native byte order
  863. +** databases are created for testing purposes only. Under normal operation,
  864. +** only native byte-order databases should be created, but we should be
  865. +** able to read or write existing databases regardless of the byteorder.
  866. +*/
  867. +#ifdef SQLITE_TEST
  868. +int btree_native_byte_order = 1;
  869. +#else
  870. +# define btree_native_byte_order 1
  871. +#endif
  872. +
  873. +/*
  874. +** Forward declarations of structures used only in this file.
  875. +*/
  876. +typedef struct PageOne PageOne;
  877. +typedef struct MemPage MemPage;
  878. +typedef struct PageHdr PageHdr;
  879. +typedef struct Cell Cell;
  880. +typedef struct CellHdr CellHdr;
  881. +typedef struct FreeBlk FreeBlk;
  882. +typedef struct OverflowPage OverflowPage;
  883. +typedef struct FreelistInfo FreelistInfo;
  884. +
  885. +/*
  886. +** All structures on a database page are aligned to 4-byte boundries.
  887. +** This routine rounds up a number of bytes to the next multiple of 4.
  888. +**
  889. +** This might need to change for computer architectures that require
  890. +** and 8-byte alignment boundry for structures.
  891. +*/
  892. +#define ROUNDUP(X) ((X+3) & ~3)
  893. +
  894. +/*
  895. +** This is a magic string that appears at the beginning of every
  896. +** SQLite database in order to identify the file as a real database.
  897. +*/
  898. +static const char zMagicHeader[] =
  899. + "** This file contains an SQLite 2.1 database **";
  900. +#define MAGIC_SIZE (sizeof(zMagicHeader))
  901. +
  902. +/*
  903. +** This is a magic integer also used to test the integrity of the database
  904. +** file. This integer is used in addition to the string above so that
  905. +** if the file is written on a little-endian architecture and read
  906. +** on a big-endian architectures (or vice versa) we can detect the
  907. +** problem.
  908. +**
  909. +** The number used was obtained at random and has no special
  910. +** significance other than the fact that it represents a different
  911. +** integer on little-endian and big-endian machines.
  912. +*/
  913. +#define MAGIC 0xdae37528
  914. +
  915. +/*
  916. +** The first page of the database file contains a magic header string
  917. +** to identify the file as an SQLite database file. It also contains
  918. +** a pointer to the first free page of the file. Page 2 contains the
  919. +** root of the principle BTree. The file might contain other BTrees
  920. +** rooted on pages above 2.
  921. +**
  922. +** The first page also contains SQLITE_N_BTREE_META integers that
  923. +** can be used by higher-level routines.
  924. +**
  925. +** Remember that pages are numbered beginning with 1. (See pager.c
  926. +** for additional information.) Page 0 does not exist and a page
  927. +** number of 0 is used to mean "no such page".
  928. +*/
  929. +struct PageOne {
  930. + char zMagic[MAGIC_SIZE]; /* String that identifies the file as a database */
  931. + int iMagic; /* Integer to verify correct byte order */
  932. + Pgno freeList; /* First free page in a list of all free pages */
  933. + int nFree; /* Number of pages on the free list */
  934. + int aMeta[SQLITE_N_BTREE_META-1]; /* User defined integers */
  935. +};
  936. +
  937. +/*
  938. +** Each database page has a header that is an instance of this
  939. +** structure.
  940. +**
  941. +** PageHdr.firstFree is 0 if there is no free space on this page.
  942. +** Otherwise, PageHdr.firstFree is the index in MemPage.u.aDisk[] of a
  943. +** FreeBlk structure that describes the first block of free space.
  944. +** All free space is defined by a linked list of FreeBlk structures.
  945. +**
  946. +** Data is stored in a linked list of Cell structures. PageHdr.firstCell
  947. +** is the index into MemPage.u.aDisk[] of the first cell on the page. The
  948. +** Cells are kept in sorted order.
  949. +**
  950. +** A Cell contains all information about a database entry and a pointer
  951. +** to a child page that contains other entries less than itself. In
  952. +** other words, the i-th Cell contains both Ptr(i) and Key(i). The
  953. +** right-most pointer of the page is contained in PageHdr.rightChild.
  954. +*/
  955. +struct PageHdr {
  956. + Pgno rightChild; /* Child page that comes after all cells on this page */
  957. + u16 firstCell; /* Index in MemPage.u.aDisk[] of the first cell */
  958. + u16 firstFree; /* Index in MemPage.u.aDisk[] of the first free block */
  959. +};
  960. +
  961. +/*
  962. +** Entries on a page of the database are called "Cells". Each Cell
  963. +** has a header and data. This structure defines the header. The
  964. +** key and data (collectively the "payload") follow this header on
  965. +** the database page.
  966. +**
  967. +** A definition of the complete Cell structure is given below. The
  968. +** header for the cell must be defined first in order to do some
  969. +** of the sizing #defines that follow.
  970. +*/
  971. +struct CellHdr {
  972. + Pgno leftChild; /* Child page that comes before this cell */
  973. + u16 nKey; /* Number of bytes in the key */
  974. + u16 iNext; /* Index in MemPage.u.aDisk[] of next cell in sorted order */
  975. + u8 nKeyHi; /* Upper 8 bits of key size for keys larger than 64K bytes */
  976. + u8 nDataHi; /* Upper 8 bits of data size when the size is more than 64K */
  977. + u16 nData; /* Number of bytes of data */
  978. +};
  979. +
  980. +/*
  981. +** The key and data size are split into a lower 16-bit segment and an
  982. +** upper 8-bit segment in order to pack them together into a smaller
  983. +** space. The following macros reassembly a key or data size back
  984. +** into an integer.
  985. +*/
  986. +#define NKEY(b,h) (SWAB16(b,h.nKey) + h.nKeyHi*65536)
  987. +#define NDATA(b,h) (SWAB16(b,h.nData) + h.nDataHi*65536)
  988. +
  989. +/*
  990. +** The minimum size of a complete Cell. The Cell must contain a header
  991. +** and at least 4 bytes of payload.
  992. +*/
  993. +#define MIN_CELL_SIZE (sizeof(CellHdr)+4)
  994. +
  995. +/*
  996. +** The maximum number of database entries that can be held in a single
  997. +** page of the database.
  998. +*/
  999. +#define MX_CELL ((SQLITE_USABLE_SIZE-sizeof(PageHdr))/MIN_CELL_SIZE)
  1000. +
  1001. +/*
  1002. +** The amount of usable space on a single page of the BTree. This is the
  1003. +** page size minus the overhead of the page header.
  1004. +*/
  1005. +#define USABLE_SPACE (SQLITE_USABLE_SIZE - sizeof(PageHdr))
  1006. +
  1007. +/*
  1008. +** The maximum amount of payload (in bytes) that can be stored locally for
  1009. +** a database entry. If the entry contains more data than this, the
  1010. +** extra goes onto overflow pages.
  1011. +**
  1012. +** This number is chosen so that at least 4 cells will fit on every page.
  1013. +*/
  1014. +#define MX_LOCAL_PAYLOAD ((USABLE_SPACE/4-(sizeof(CellHdr)+sizeof(Pgno)))&~3)
  1015. +
  1016. +/*
  1017. +** Data on a database page is stored as a linked list of Cell structures.
  1018. +** Both the key and the data are stored in aPayload[]. The key always comes
  1019. +** first. The aPayload[] field grows as necessary to hold the key and data,
  1020. +** up to a maximum of MX_LOCAL_PAYLOAD bytes. If the size of the key and
  1021. +** data combined exceeds MX_LOCAL_PAYLOAD bytes, then Cell.ovfl is the
  1022. +** page number of the first overflow page.
  1023. +**
  1024. +** Though this structure is fixed in size, the Cell on the database
  1025. +** page varies in size. Every cell has a CellHdr and at least 4 bytes
  1026. +** of payload space. Additional payload bytes (up to the maximum of
  1027. +** MX_LOCAL_PAYLOAD) and the Cell.ovfl value are allocated only as
  1028. +** needed.
  1029. +*/
  1030. +struct Cell {
  1031. + CellHdr h; /* The cell header */
  1032. + char aPayload[MX_LOCAL_PAYLOAD]; /* Key and data */
  1033. + Pgno ovfl; /* The first overflow page */
  1034. +};
  1035. +
  1036. +/*
  1037. +** Free space on a page is remembered using a linked list of the FreeBlk
  1038. +** structures. Space on a database page is allocated in increments of
  1039. +** at least 4 bytes and is always aligned to a 4-byte boundry. The
  1040. +** linked list of FreeBlks is always kept in order by address.
  1041. +*/
  1042. +struct FreeBlk {
  1043. + u16 iSize; /* Number of bytes in this block of free space */
  1044. + u16 iNext; /* Index in MemPage.u.aDisk[] of the next free block */
  1045. +};
  1046. +
  1047. +/*
  1048. +** The number of bytes of payload that will fit on a single overflow page.
  1049. +*/
  1050. +#define OVERFLOW_SIZE (SQLITE_USABLE_SIZE-sizeof(Pgno))
  1051. +
  1052. +/*
  1053. +** When the key and data for a single entry in the BTree will not fit in
  1054. +** the MX_LOCAL_PAYLOAD bytes of space available on the database page,
  1055. +** then all extra bytes are written to a linked list of overflow pages.
  1056. +** Each overflow page is an instance of the following structure.
  1057. +**
  1058. +** Unused pages in the database are also represented by instances of
  1059. +** the OverflowPage structure. The PageOne.freeList field is the
  1060. +** page number of the first page in a linked list of unused database
  1061. +** pages.
  1062. +*/
  1063. +struct OverflowPage {
  1064. + Pgno iNext;
  1065. + char aPayload[OVERFLOW_SIZE];
  1066. +};
  1067. +
  1068. +/*
  1069. +** The PageOne.freeList field points to a linked list of overflow pages
  1070. +** hold information about free pages. The aPayload section of each
  1071. +** overflow page contains an instance of the following structure. The
  1072. +** aFree[] array holds the page number of nFree unused pages in the disk
  1073. +** file.
  1074. +*/
  1075. +struct FreelistInfo {
  1076. + int nFree;
  1077. + Pgno aFree[(OVERFLOW_SIZE-sizeof(int))/sizeof(Pgno)];
  1078. +};
  1079. +
  1080. +/*
  1081. +** For every page in the database file, an instance of the following structure
  1082. +** is stored in memory. The u.aDisk[] array contains the raw bits read from
  1083. +** the disk. The rest is auxiliary information held in memory only. The
  1084. +** auxiliary info is only valid for regular database pages - it is not
  1085. +** used for overflow pages and pages on the freelist.
  1086. +**
  1087. +** Of particular interest in the auxiliary info is the apCell[] entry. Each
  1088. +** apCell[] entry is a pointer to a Cell structure in u.aDisk[]. The cells are
  1089. +** put in this array so that they can be accessed in constant time, rather
  1090. +** than in linear time which would be needed if we had to walk the linked
  1091. +** list on every access.
  1092. +**
  1093. +** Note that apCell[] contains enough space to hold up to two more Cells
  1094. +** than can possibly fit on one page. In the steady state, every apCell[]
  1095. +** points to memory inside u.aDisk[]. But in the middle of an insert
  1096. +** operation, some apCell[] entries may temporarily point to data space
  1097. +** outside of u.aDisk[]. This is a transient situation that is quickly
  1098. +** resolved. But while it is happening, it is possible for a database
  1099. +** page to hold as many as two more cells than it might otherwise hold.
  1100. +** The extra two entries in apCell[] are an allowance for this situation.
  1101. +**
  1102. +** The pParent field points back to the parent page. This allows us to
  1103. +** walk up the BTree from any leaf to the root. Care must be taken to
  1104. +** unref() the parent page pointer when this page is no longer referenced.
  1105. +** The pageDestructor() routine handles that chore.
  1106. +*/
  1107. +struct MemPage {
  1108. + union u_page_data {
  1109. + char aDisk[SQLITE_PAGE_SIZE]; /* Page data stored on disk */
  1110. + PageHdr hdr; /* Overlay page header */
  1111. + } u;
  1112. + u8 isInit; /* True if auxiliary data is initialized */
  1113. + u8 idxShift; /* True if apCell[] indices have changed */
  1114. + u8 isOverfull; /* Some apCell[] points outside u.aDisk[] */
  1115. + MemPage *pParent; /* The parent of this page. NULL for root */
  1116. + int idxParent; /* Index in pParent->apCell[] of this node */
  1117. + int nFree; /* Number of free bytes in u.aDisk[] */
  1118. + int nCell; /* Number of entries on this page */
  1119. + Cell *apCell[MX_CELL+2]; /* All data entires in sorted order */
  1120. +};
  1121. +
  1122. +/*
  1123. +** The in-memory image of a disk page has the auxiliary information appended
  1124. +** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  1125. +** that extra information.
  1126. +*/
  1127. +#define EXTRA_SIZE (sizeof(MemPage)-sizeof(union u_page_data))
  1128. +
  1129. +/*
  1130. +** Everything we need to know about an open database
  1131. +*/
  1132. +struct Btree {
  1133. + BtOps *pOps; /* Function table */
  1134. + Pager *pPager; /* The page cache */
  1135. + BtCursor *pCursor; /* A list of all open cursors */
  1136. + PageOne *page1; /* First page of the database */
  1137. + u8 inTrans; /* True if a transaction is in progress */
  1138. + u8 inCkpt; /* True if there is a checkpoint on the transaction */
  1139. + u8 readOnly; /* True if the underlying file is readonly */
  1140. + u8 needSwab; /* Need to byte-swapping */
  1141. +};
  1142. +typedef Btree Bt;
  1143. +
  1144. +/*
  1145. +** A cursor is a pointer to a particular entry in the BTree.
  1146. +** The entry is identified by its MemPage and the index in
  1147. +** MemPage.apCell[] of the entry.
  1148. +*/
  1149. +struct BtCursor {
  1150. + BtCursorOps *pOps; /* Function table */
  1151. + Btree *pBt; /* The Btree to which this cursor belongs */
  1152. + BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  1153. + BtCursor *pShared; /* Loop of cursors with the same root page */
  1154. + Pgno pgnoRoot; /* The root page of this tree */
  1155. + MemPage *pPage; /* Page that contains the entry */
  1156. + int idx; /* Index of the entry in pPage->apCell[] */
  1157. + u8 wrFlag; /* True if writable */
  1158. + u8 eSkip; /* Determines if next step operation is a no-op */
  1159. + u8 iMatch; /* compare result from last sqliteBtreeMoveto() */
  1160. +};
  1161. +
  1162. +/*
  1163. +** Legal values for BtCursor.eSkip.
  1164. +*/
  1165. +#define SKIP_NONE 0 /* Always step the cursor */
  1166. +#define SKIP_NEXT 1 /* The next sqliteBtreeNext() is a no-op */
  1167. +#define SKIP_PREV 2 /* The next sqliteBtreePrevious() is a no-op */
  1168. +#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
  1169. +
  1170. +/* Forward declarations */
  1171. +static int fileBtreeCloseCursor(BtCursor *pCur);
  1172. +
  1173. +/*
  1174. +** Routines for byte swapping.
  1175. +*/
  1176. +u16 swab16(u16 x){
  1177. + return ((x & 0xff)<<8) | ((x>>8)&0xff);
  1178. +}
  1179. +u32 swab32(u32 x){
  1180. + return ((x & 0xff)<<24) | ((x & 0xff00)<<8) |
  1181. + ((x>>8) & 0xff00) | ((x>>24)&0xff);
  1182. +}
  1183. +
  1184. +/*
  1185. +** Compute the total number of bytes that a Cell needs on the main
  1186. +** database page. The number returned includes the Cell header,
  1187. +** local payload storage, and the pointer to overflow pages (if
  1188. +** applicable). Additional space allocated on overflow pages
  1189. +** is NOT included in the value returned from this routine.
  1190. +*/
  1191. +static int cellSize(Btree *pBt, Cell *pCell){
  1192. + int n = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
  1193. + if( n>MX_LOCAL_PAYLOAD ){
  1194. + n = MX_LOCAL_PAYLOAD + sizeof(Pgno);
  1195. + }else{
  1196. + n = ROUNDUP(n);
  1197. + }
  1198. + n += sizeof(CellHdr);
  1199. + return n;
  1200. +}
  1201. +
  1202. +/*
  1203. +** Defragment the page given. All Cells are moved to the
  1204. +** beginning of the page and all free space is collected
  1205. +** into one big FreeBlk at the end of the page.
  1206. +*/
  1207. +static void defragmentPage(Btree *pBt, MemPage *pPage){
  1208. + int pc, i, n;
  1209. + FreeBlk *pFBlk;
  1210. + char newPage[SQLITE_USABLE_SIZE];
  1211. +
  1212. + assert( sqlitepager_iswriteable(pPage) );
  1213. + assert( pPage->isInit );
  1214. + pc = sizeof(PageHdr);
  1215. + pPage->u.hdr.firstCell = SWAB16(pBt, pc);
  1216. + memcpy(newPage, pPage->u.aDisk, pc);
  1217. + for(i=0; i<pPage->nCell; i++){
  1218. + Cell *pCell = pPage->apCell[i];
  1219. +
  1220. + /* This routine should never be called on an overfull page. The
  1221. + ** following asserts verify that constraint. */
  1222. + assert( Addr(pCell) > Addr(pPage) );
  1223. + assert( Addr(pCell) < Addr(pPage) + SQLITE_USABLE_SIZE );
  1224. +
  1225. + n = cellSize(pBt, pCell);
  1226. + pCell->h.iNext = SWAB16(pBt, pc + n);
  1227. + memcpy(&newPage[pc], pCell, n);
  1228. + pPage->apCell[i] = (Cell*)&pPage->u.aDisk[pc];
  1229. + pc += n;
  1230. + }
  1231. + assert( pPage->nFree==SQLITE_USABLE_SIZE-pc );
  1232. + memcpy(pPage->u.aDisk, newPage, pc);
  1233. + if( pPage->nCell>0 ){
  1234. + pPage->apCell[pPage->nCell-1]->h.iNext = 0;
  1235. + }
  1236. + pFBlk = (FreeBlk*)&pPage->u.aDisk[pc];
  1237. + pFBlk->iSize = SWAB16(pBt, SQLITE_USABLE_SIZE - pc);
  1238. + pFBlk->iNext = 0;
  1239. + pPage->u.hdr.firstFree = SWAB16(pBt, pc);
  1240. + memset(&pFBlk[1], 0, SQLITE_USABLE_SIZE - pc - sizeof(FreeBlk));
  1241. +}
  1242. +
  1243. +/*
  1244. +** Allocate nByte bytes of space on a page. nByte must be a
  1245. +** multiple of 4.
  1246. +**
  1247. +** Return the index into pPage->u.aDisk[] of the first byte of
  1248. +** the new allocation. Or return 0 if there is not enough free
  1249. +** space on the page to satisfy the allocation request.
  1250. +**
  1251. +** If the page contains nBytes of free space but does not contain
  1252. +** nBytes of contiguous free space, then this routine automatically
  1253. +** calls defragementPage() to consolidate all free space before
  1254. +** allocating the new chunk.
  1255. +*/
  1256. +static int allocateSpace(Btree *pBt, MemPage *pPage, int nByte){
  1257. + FreeBlk *p;
  1258. + u16 *pIdx;
  1259. + int start;
  1260. + int iSize;
  1261. +#ifndef NDEBUG
  1262. + int cnt = 0;
  1263. +#endif
  1264. +
  1265. + assert( sqlitepager_iswriteable(pPage) );
  1266. + assert( nByte==ROUNDUP(nByte) );
  1267. + assert( pPage->isInit );
  1268. + if( pPage->nFree<nByte || pPage->isOverfull ) return 0;
  1269. + pIdx = &pPage->u.hdr.firstFree;
  1270. + p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
  1271. + while( (iSize = SWAB16(pBt, p->iSize))<nByte ){
  1272. + assert( cnt++ < SQLITE_USABLE_SIZE/4 );
  1273. + if( p->iNext==0 ){
  1274. + defragmentPage(pBt, pPage);
  1275. + pIdx = &pPage->u.hdr.firstFree;
  1276. + }else{
  1277. + pIdx = &p->iNext;
  1278. + }
  1279. + p = (FreeBlk*)&pPage->u.aDisk[SWAB16(pBt, *pIdx)];
  1280. + }
  1281. + if( iSize==nByte ){
  1282. + start = SWAB16(pBt, *pIdx);
  1283. + *pIdx = p->iNext;
  1284. + }else{
  1285. + FreeBlk *pNew;
  1286. + start = SWAB16(pBt, *pIdx);
  1287. + pNew = (FreeBlk*)&pPage->u.aDisk[start + nByte];
  1288. + pNew->iNext = p->iNext;
  1289. + pNew->iSize = SWAB16(pBt, iSize - nByte);
  1290. + *pIdx = SWAB16(pBt, start + nByte);
  1291. + }
  1292. + pPage->nFree -= nByte;
  1293. + return start;
  1294. +}
  1295. +
  1296. +/*
  1297. +** Return a section of the MemPage.u.aDisk[] to the freelist.
  1298. +** The first byte of the new free block is pPage->u.aDisk[start]
  1299. +** and the size of the block is "size" bytes. Size must be
  1300. +** a multiple of 4.
  1301. +**
  1302. +** Most of the effort here is involved in coalesing adjacent
  1303. +** free blocks into a single big free block.
  1304. +*/
  1305. +static void freeSpace(Btree *pBt, MemPage *pPage, int start, int size){
  1306. + int end = start + size;
  1307. + u16 *pIdx, idx;
  1308. + FreeBlk *pFBlk;
  1309. + FreeBlk *pNew;
  1310. + FreeBlk *pNext;
  1311. + int iSize;
  1312. +
  1313. + assert( sqlitepager_iswriteable(pPage) );
  1314. + assert( size == ROUNDUP(size) );
  1315. + assert( start == ROUNDUP(start) );
  1316. + assert( pPage->isInit );
  1317. + pIdx = &pPage->u.hdr.firstFree;
  1318. + idx = SWAB16(pBt, *pIdx);
  1319. + while( idx!=0 && idx<start ){
  1320. + pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
  1321. + iSize = SWAB16(pBt, pFBlk->iSize);
  1322. + if( idx + iSize == start ){
  1323. + pFBlk->iSize = SWAB16(pBt, iSize + size);
  1324. + if( idx + iSize + size == SWAB16(pBt, pFBlk->iNext) ){
  1325. + pNext = (FreeBlk*)&pPage->u.aDisk[idx + iSize + size];
  1326. + if( pBt->needSwab ){
  1327. + pFBlk->iSize = swab16((u16)swab16(pNext->iSize)+iSize+size);
  1328. + }else{
  1329. + pFBlk->iSize += pNext->iSize;
  1330. + }
  1331. + pFBlk->iNext = pNext->iNext;
  1332. + }
  1333. + pPage->nFree += size;
  1334. + return;
  1335. + }
  1336. + pIdx = &pFBlk->iNext;
  1337. + idx = SWAB16(pBt, *pIdx);
  1338. + }
  1339. + pNew = (FreeBlk*)&pPage->u.aDisk[start];
  1340. + if( idx != end ){
  1341. + pNew->iSize = SWAB16(pBt, size);
  1342. + pNew->iNext = SWAB16(pBt, idx);
  1343. + }else{
  1344. + pNext = (FreeBlk*)&pPage->u.aDisk[idx];
  1345. + pNew->iSize = SWAB16(pBt, size + SWAB16(pBt, pNext->iSize));
  1346. + pNew->iNext = pNext->iNext;
  1347. + }
  1348. + *pIdx = SWAB16(pBt, start);
  1349. + pPage->nFree += size;
  1350. +}
  1351. +
  1352. +/*
  1353. +** Initialize the auxiliary information for a disk block.
  1354. +**
  1355. +** The pParent parameter must be a pointer to the MemPage which
  1356. +** is the parent of the page being initialized. The root of the
  1357. +** BTree (usually page 2) has no parent and so for that page,
  1358. +** pParent==NULL.
  1359. +**
  1360. +** Return SQLITE_OK on success. If we see that the page does
  1361. +** not contain a well-formed database page, then return
  1362. +** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  1363. +** guarantee that the page is well-formed. It only shows that
  1364. +** we failed to detect any corruption.
  1365. +*/
  1366. +static int initPage(Bt *pBt, MemPage *pPage, Pgno pgnoThis, MemPage *pParent){
  1367. + int idx; /* An index into pPage->u.aDisk[] */
  1368. + Cell *pCell; /* A pointer to a Cell in pPage->u.aDisk[] */
  1369. + FreeBlk *pFBlk; /* A pointer to a free block in pPage->u.aDisk[] */
  1370. + int sz; /* The size of a Cell in bytes */
  1371. + int freeSpace; /* Amount of free space on the page */
  1372. +
  1373. + if( pPage->pParent ){
  1374. + assert( pPage->pParent==pParent );
  1375. + return SQLITE_OK;
  1376. + }
  1377. + if( pParent ){
  1378. + pPage->pParent = pParent;
  1379. + sqlitepager_ref(pParent);
  1380. + }
  1381. + if( pPage->isInit ) return SQLITE_OK;
  1382. + pPage->isInit = 1;
  1383. + pPage->nCell = 0;
  1384. + freeSpace = USABLE_SPACE;
  1385. + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
  1386. + while( idx!=0 ){
  1387. + if( idx>SQLITE_USABLE_SIZE-MIN_CELL_SIZE ) goto page_format_error;
  1388. + if( idx<sizeof(PageHdr) ) goto page_format_error;
  1389. + if( idx!=ROUNDUP(idx) ) goto page_format_error;
  1390. + pCell = (Cell*)&pPage->u.aDisk[idx];
  1391. + sz = cellSize(pBt, pCell);
  1392. + if( idx+sz > SQLITE_USABLE_SIZE ) goto page_format_error;
  1393. + freeSpace -= sz;
  1394. + pPage->apCell[pPage->nCell++] = pCell;
  1395. + idx = SWAB16(pBt, pCell->h.iNext);
  1396. + }
  1397. + pPage->nFree = 0;
  1398. + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
  1399. + while( idx!=0 ){
  1400. + int iNext;
  1401. + if( idx>SQLITE_USABLE_SIZE-sizeof(FreeBlk) ) goto page_format_error;
  1402. + if( idx<sizeof(PageHdr) ) goto page_format_error;
  1403. + pFBlk = (FreeBlk*)&pPage->u.aDisk[idx];
  1404. + pPage->nFree += SWAB16(pBt, pFBlk->iSize);
  1405. + iNext = SWAB16(pBt, pFBlk->iNext);
  1406. + if( iNext>0 && iNext <= idx ) goto page_format_error;
  1407. + idx = iNext;
  1408. + }
  1409. + if( pPage->nCell==0 && pPage->nFree==0 ){
  1410. + /* As a special case, an uninitialized root page appears to be
  1411. + ** an empty database */
  1412. + return SQLITE_OK;
  1413. + }
  1414. + if( pPage->nFree!=freeSpace ) goto page_format_error;
  1415. + return SQLITE_OK;
  1416. +
  1417. +page_format_error:
  1418. + return SQLITE_CORRUPT;
  1419. +}
  1420. +
  1421. +/*
  1422. +** Set up a raw page so that it looks like a database page holding
  1423. +** no entries.
  1424. +*/
  1425. +static void zeroPage(Btree *pBt, MemPage *pPage){
  1426. + PageHdr *pHdr;
  1427. + FreeBlk *pFBlk;
  1428. + assert( sqlitepager_iswriteable(pPage) );
  1429. + memset(pPage, 0, SQLITE_USABLE_SIZE);
  1430. + pHdr = &pPage->u.hdr;
  1431. + pHdr->firstCell = 0;
  1432. + pHdr->firstFree = SWAB16(pBt, sizeof(*pHdr));
  1433. + pFBlk = (FreeBlk*)&pHdr[1];
  1434. + pFBlk->iNext = 0;
  1435. + pPage->nFree = SQLITE_USABLE_SIZE - sizeof(*pHdr);
  1436. + pFBlk->iSize = SWAB16(pBt, pPage->nFree);
  1437. + pPage->nCell = 0;
  1438. + pPage->isOverfull = 0;
  1439. +}
  1440. +
  1441. +/*
  1442. +** This routine is called when the reference count for a page
  1443. +** reaches zero. We need to unref the pParent pointer when that
  1444. +** happens.
  1445. +*/
  1446. +static void pageDestructor(void *pData){
  1447. + MemPage *pPage = (MemPage*)pData;
  1448. + if( pPage->pParent ){
  1449. + MemPage *pParent = pPage->pParent;
  1450. + pPage->pParent = 0;
  1451. + sqlitepager_unref(pParent);
  1452. + }
  1453. +}
  1454. +
  1455. +/*
  1456. +** Open a new database.
  1457. +**
  1458. +** Actually, this routine just sets up the internal data structures
  1459. +** for accessing the database. We do not open the database file
  1460. +** until the first page is loaded.
  1461. +**
  1462. +** zFilename is the name of the database file. If zFilename is NULL
  1463. +** a new database with a random name is created. This randomly named
  1464. +** database file will be deleted when sqliteBtreeClose() is called.
  1465. +*/
  1466. +int sqliteBtreeOpen(
  1467. + const char *zFilename, /* Name of the file containing the BTree database */
  1468. + int omitJournal, /* if TRUE then do not journal this file */
  1469. + int nCache, /* How many pages in the page cache */
  1470. + Btree **ppBtree /* Pointer to new Btree object written here */
  1471. +){
  1472. + Btree *pBt;
  1473. + int rc;
  1474. +
  1475. + /*
  1476. + ** The following asserts make sure that structures used by the btree are
  1477. + ** the right size. This is to guard against size changes that result
  1478. + ** when compiling on a different architecture.
  1479. + */
  1480. + assert( sizeof(u32)==4 );
  1481. + assert( sizeof(u16)==2 );
  1482. + assert( sizeof(Pgno)==4 );
  1483. + assert( sizeof(PageHdr)==8 );
  1484. + assert( sizeof(CellHdr)==12 );
  1485. + assert( sizeof(FreeBlk)==4 );
  1486. + assert( sizeof(OverflowPage)==SQLITE_USABLE_SIZE );
  1487. + assert( sizeof(FreelistInfo)==OVERFLOW_SIZE );
  1488. + assert( sizeof(ptr)==sizeof(char*) );
  1489. + assert( sizeof(uptr)==sizeof(ptr) );
  1490. +
  1491. + pBt = sqliteMalloc( sizeof(*pBt) );
  1492. + if( pBt==0 ){
  1493. + *ppBtree = 0;
  1494. + return SQLITE_NOMEM;
  1495. + }
  1496. + if( nCache<10 ) nCache = 10;
  1497. + rc = sqlitepager_open(&pBt->pPager, zFilename, nCache, EXTRA_SIZE,
  1498. + !omitJournal);
  1499. + if( rc!=SQLITE_OK ){
  1500. + if( pBt->pPager ) sqlitepager_close(pBt->pPager);
  1501. + sqliteFree(pBt);
  1502. + *ppBtree = 0;
  1503. + return rc;
  1504. + }
  1505. + sqlitepager_set_destructor(pBt->pPager, pageDestructor);
  1506. + pBt->pCursor = 0;
  1507. + pBt->page1 = 0;
  1508. + pBt->readOnly = sqlitepager_isreadonly(pBt->pPager);
  1509. + pBt->pOps = &sqliteBtreeOps;
  1510. + *ppBtree = pBt;
  1511. + return SQLITE_OK;
  1512. +}
  1513. +
  1514. +/*
  1515. +** Close an open database and invalidate all cursors.
  1516. +*/
  1517. +static int fileBtreeClose(Btree *pBt){
  1518. + while( pBt->pCursor ){
  1519. + fileBtreeCloseCursor(pBt->pCursor);
  1520. + }
  1521. + sqlitepager_close(pBt->pPager);
  1522. + sqliteFree(pBt);
  1523. + return SQLITE_OK;
  1524. +}
  1525. +
  1526. +/*
  1527. +** Change the limit on the number of pages allowed in the cache.
  1528. +**
  1529. +** The maximum number of cache pages is set to the absolute
  1530. +** value of mxPage. If mxPage is negative, the pager will
  1531. +** operate asynchronously - it will not stop to do fsync()s
  1532. +** to insure data is written to the disk surface before
  1533. +** continuing. Transactions still work if synchronous is off,
  1534. +** and the database cannot be corrupted if this program
  1535. +** crashes. But if the operating system crashes or there is
  1536. +** an abrupt power failure when synchronous is off, the database
  1537. +** could be left in an inconsistent and unrecoverable state.
  1538. +** Synchronous is on by default so database corruption is not
  1539. +** normally a worry.
  1540. +*/
  1541. +static int fileBtreeSetCacheSize(Btree *pBt, int mxPage){
  1542. + sqlitepager_set_cachesize(pBt->pPager, mxPage);
  1543. + return SQLITE_OK;
  1544. +}
  1545. +
  1546. +/*
  1547. +** Change the way data is synced to disk in order to increase or decrease
  1548. +** how well the database resists damage due to OS crashes and power
  1549. +** failures. Level 1 is the same as asynchronous (no syncs() occur and
  1550. +** there is a high probability of damage) Level 2 is the default. There
  1551. +** is a very low but non-zero probability of damage. Level 3 reduces the
  1552. +** probability of damage to near zero but with a write performance reduction.
  1553. +*/
  1554. +static int fileBtreeSetSafetyLevel(Btree *pBt, int level){
  1555. + sqlitepager_set_safety_level(pBt->pPager, level);
  1556. + return SQLITE_OK;
  1557. +}
  1558. +
  1559. +/*
  1560. +** Get a reference to page1 of the database file. This will
  1561. +** also acquire a readlock on that file.
  1562. +**
  1563. +** SQLITE_OK is returned on success. If the file is not a
  1564. +** well-formed database file, then SQLITE_CORRUPT is returned.
  1565. +** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  1566. +** is returned if we run out of memory. SQLITE_PROTOCOL is returned
  1567. +** if there is a locking protocol violation.
  1568. +*/
  1569. +static int lockBtree(Btree *pBt){
  1570. + int rc;
  1571. + if( pBt->page1 ) return SQLITE_OK;
  1572. + rc = sqlitepager_get(pBt->pPager, 1, (void**)&pBt->page1);
  1573. + if( rc!=SQLITE_OK ) return rc;
  1574. +
  1575. + /* Do some checking to help insure the file we opened really is
  1576. + ** a valid database file.
  1577. + */
  1578. + if( sqlitepager_pagecount(pBt->pPager)>0 ){
  1579. + PageOne *pP1 = pBt->page1;
  1580. + if( strcmp(pP1->zMagic,zMagicHeader)!=0 ||
  1581. + (pP1->iMagic!=MAGIC && swab32(pP1->iMagic)!=MAGIC) ){
  1582. + rc = SQLITE_NOTADB;
  1583. + goto page1_init_failed;
  1584. + }
  1585. + pBt->needSwab = pP1->iMagic!=MAGIC;
  1586. + }
  1587. + return rc;
  1588. +
  1589. +page1_init_failed:
  1590. + sqlitepager_unref(pBt->page1);
  1591. + pBt->page1 = 0;
  1592. + return rc;
  1593. +}
  1594. +
  1595. +/*
  1596. +** If there are no outstanding cursors and we are not in the middle
  1597. +** of a transaction but there is a read lock on the database, then
  1598. +** this routine unrefs the first page of the database file which
  1599. +** has the effect of releasing the read lock.
  1600. +**
  1601. +** If there are any outstanding cursors, this routine is a no-op.
  1602. +**
  1603. +** If there is a transaction in progress, this routine is a no-op.
  1604. +*/
  1605. +static void unlockBtreeIfUnused(Btree *pBt){
  1606. + if( pBt->inTrans==0 && pBt->pCursor==0 && pBt->page1!=0 ){
  1607. + sqlitepager_unref(pBt->page1);
  1608. + pBt->page1 = 0;
  1609. + pBt->inTrans = 0;
  1610. + pBt->inCkpt = 0;
  1611. + }
  1612. +}
  1613. +
  1614. +/*
  1615. +** Create a new database by initializing the first two pages of the
  1616. +** file.
  1617. +*/
  1618. +static int newDatabase(Btree *pBt){
  1619. + MemPage *pRoot;
  1620. + PageOne *pP1;
  1621. + int rc;
  1622. + if( sqlitepager_pagecount(pBt->pPager)>1 ) return SQLITE_OK;
  1623. + pP1 = pBt->page1;
  1624. + rc = sqlitepager_write(pBt->page1);
  1625. + if( rc ) return rc;
  1626. + rc = sqlitepager_get(pBt->pPager, 2, (void**)&pRoot);
  1627. + if( rc ) return rc;
  1628. + rc = sqlitepager_write(pRoot);
  1629. + if( rc ){
  1630. + sqlitepager_unref(pRoot);
  1631. + return rc;
  1632. + }
  1633. + strcpy(pP1->zMagic, zMagicHeader);
  1634. + if( btree_native_byte_order ){
  1635. + pP1->iMagic = MAGIC;
  1636. + pBt->needSwab = 0;
  1637. + }else{
  1638. + pP1->iMagic = swab32(MAGIC);
  1639. + pBt->needSwab = 1;
  1640. + }
  1641. + zeroPage(pBt, pRoot);
  1642. + sqlitepager_unref(pRoot);
  1643. + return SQLITE_OK;
  1644. +}
  1645. +
  1646. +/*
  1647. +** Attempt to start a new transaction.
  1648. +**
  1649. +** A transaction must be started before attempting any changes
  1650. +** to the database. None of the following routines will work
  1651. +** unless a transaction is started first:
  1652. +**
  1653. +** sqliteBtreeCreateTable()
  1654. +** sqliteBtreeCreateIndex()
  1655. +** sqliteBtreeClearTable()
  1656. +** sqliteBtreeDropTable()
  1657. +** sqliteBtreeInsert()
  1658. +** sqliteBtreeDelete()
  1659. +** sqliteBtreeUpdateMeta()
  1660. +*/
  1661. +static int fileBtreeBeginTrans(Btree *pBt){
  1662. + int rc;
  1663. + if( pBt->inTrans ) return SQLITE_ERROR;
  1664. + if( pBt->readOnly ) return SQLITE_READONLY;
  1665. + if( pBt->page1==0 ){
  1666. + rc = lockBtree(pBt);
  1667. + if( rc!=SQLITE_OK ){
  1668. + return rc;
  1669. + }
  1670. + }
  1671. + rc = sqlitepager_begin(pBt->page1);
  1672. + if( rc==SQLITE_OK ){
  1673. + rc = newDatabase(pBt);
  1674. + }
  1675. + if( rc==SQLITE_OK ){
  1676. + pBt->inTrans = 1;
  1677. + pBt->inCkpt = 0;
  1678. + }else{
  1679. + unlockBtreeIfUnused(pBt);
  1680. + }
  1681. + return rc;
  1682. +}
  1683. +
  1684. +/*
  1685. +** Commit the transaction currently in progress.
  1686. +**
  1687. +** This will release the write lock on the database file. If there
  1688. +** are no active cursors, it also releases the read lock.
  1689. +*/
  1690. +static int fileBtreeCommit(Btree *pBt){
  1691. + int rc;
  1692. + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_commit(pBt->pPager);
  1693. + pBt->inTrans = 0;
  1694. + pBt->inCkpt = 0;
  1695. + unlockBtreeIfUnused(pBt);
  1696. + return rc;
  1697. +}
  1698. +
  1699. +/*
  1700. +** Rollback the transaction in progress. All cursors will be
  1701. +** invalided by this operation. Any attempt to use a cursor
  1702. +** that was open at the beginning of this operation will result
  1703. +** in an error.
  1704. +**
  1705. +** This will release the write lock on the database file. If there
  1706. +** are no active cursors, it also releases the read lock.
  1707. +*/
  1708. +static int fileBtreeRollback(Btree *pBt){
  1709. + int rc;
  1710. + BtCursor *pCur;
  1711. + if( pBt->inTrans==0 ) return SQLITE_OK;
  1712. + pBt->inTrans = 0;
  1713. + pBt->inCkpt = 0;
  1714. + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_rollback(pBt->pPager);
  1715. + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  1716. + if( pCur->pPage && pCur->pPage->isInit==0 ){
  1717. + sqlitepager_unref(pCur->pPage);
  1718. + pCur->pPage = 0;
  1719. + }
  1720. + }
  1721. + unlockBtreeIfUnused(pBt);
  1722. + return rc;
  1723. +}
  1724. +
  1725. +/*
  1726. +** Set the checkpoint for the current transaction. The checkpoint serves
  1727. +** as a sub-transaction that can be rolled back independently of the
  1728. +** main transaction. You must start a transaction before starting a
  1729. +** checkpoint. The checkpoint is ended automatically if the transaction
  1730. +** commits or rolls back.
  1731. +**
  1732. +** Only one checkpoint may be active at a time. It is an error to try
  1733. +** to start a new checkpoint if another checkpoint is already active.
  1734. +*/
  1735. +static int fileBtreeBeginCkpt(Btree *pBt){
  1736. + int rc;
  1737. + if( !pBt->inTrans || pBt->inCkpt ){
  1738. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  1739. + }
  1740. + rc = pBt->readOnly ? SQLITE_OK : sqlitepager_ckpt_begin(pBt->pPager);
  1741. + pBt->inCkpt = 1;
  1742. + return rc;
  1743. +}
  1744. +
  1745. +
  1746. +/*
  1747. +** Commit a checkpoint to transaction currently in progress. If no
  1748. +** checkpoint is active, this is a no-op.
  1749. +*/
  1750. +static int fileBtreeCommitCkpt(Btree *pBt){
  1751. + int rc;
  1752. + if( pBt->inCkpt && !pBt->readOnly ){
  1753. + rc = sqlitepager_ckpt_commit(pBt->pPager);
  1754. + }else{
  1755. + rc = SQLITE_OK;
  1756. + }
  1757. + pBt->inCkpt = 0;
  1758. + return rc;
  1759. +}
  1760. +
  1761. +/*
  1762. +** Rollback the checkpoint to the current transaction. If there
  1763. +** is no active checkpoint or transaction, this routine is a no-op.
  1764. +**
  1765. +** All cursors will be invalided by this operation. Any attempt
  1766. +** to use a cursor that was open at the beginning of this operation
  1767. +** will result in an error.
  1768. +*/
  1769. +static int fileBtreeRollbackCkpt(Btree *pBt){
  1770. + int rc;
  1771. + BtCursor *pCur;
  1772. + if( pBt->inCkpt==0 || pBt->readOnly ) return SQLITE_OK;
  1773. + rc = sqlitepager_ckpt_rollback(pBt->pPager);
  1774. + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  1775. + if( pCur->pPage && pCur->pPage->isInit==0 ){
  1776. + sqlitepager_unref(pCur->pPage);
  1777. + pCur->pPage = 0;
  1778. + }
  1779. + }
  1780. + pBt->inCkpt = 0;
  1781. + return rc;
  1782. +}
  1783. +
  1784. +/*
  1785. +** Create a new cursor for the BTree whose root is on the page
  1786. +** iTable. The act of acquiring a cursor gets a read lock on
  1787. +** the database file.
  1788. +**
  1789. +** If wrFlag==0, then the cursor can only be used for reading.
  1790. +** If wrFlag==1, then the cursor can be used for reading or for
  1791. +** writing if other conditions for writing are also met. These
  1792. +** are the conditions that must be met in order for writing to
  1793. +** be allowed:
  1794. +**
  1795. +** 1: The cursor must have been opened with wrFlag==1
  1796. +**
  1797. +** 2: No other cursors may be open with wrFlag==0 on the same table
  1798. +**
  1799. +** 3: The database must be writable (not on read-only media)
  1800. +**
  1801. +** 4: There must be an active transaction.
  1802. +**
  1803. +** Condition 2 warrants further discussion. If any cursor is opened
  1804. +** on a table with wrFlag==0, that prevents all other cursors from
  1805. +** writing to that table. This is a kind of "read-lock". When a cursor
  1806. +** is opened with wrFlag==0 it is guaranteed that the table will not
  1807. +** change as long as the cursor is open. This allows the cursor to
  1808. +** do a sequential scan of the table without having to worry about
  1809. +** entries being inserted or deleted during the scan. Cursors should
  1810. +** be opened with wrFlag==0 only if this read-lock property is needed.
  1811. +** That is to say, cursors should be opened with wrFlag==0 only if they
  1812. +** intend to use the sqliteBtreeNext() system call. All other cursors
  1813. +** should be opened with wrFlag==1 even if they never really intend
  1814. +** to write.
  1815. +**
  1816. +** No checking is done to make sure that page iTable really is the
  1817. +** root page of a b-tree. If it is not, then the cursor acquired
  1818. +** will not work correctly.
  1819. +*/
  1820. +static
  1821. +int fileBtreeCursor(Btree *pBt, int iTable, int wrFlag, BtCursor **ppCur){
  1822. + int rc;
  1823. + BtCursor *pCur, *pRing;
  1824. +
  1825. + if( pBt->readOnly && wrFlag ){
  1826. + *ppCur = 0;
  1827. + return SQLITE_READONLY;
  1828. + }
  1829. + if( pBt->page1==0 ){
  1830. + rc = lockBtree(pBt);
  1831. + if( rc!=SQLITE_OK ){
  1832. + *ppCur = 0;
  1833. + return rc;
  1834. + }
  1835. + }
  1836. + pCur = sqliteMalloc( sizeof(*pCur) );
  1837. + if( pCur==0 ){
  1838. + rc = SQLITE_NOMEM;
  1839. + goto create_cursor_exception;
  1840. + }
  1841. + pCur->pgnoRoot = (Pgno)iTable;
  1842. + rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pCur->pPage);
  1843. + if( rc!=SQLITE_OK ){
  1844. + goto create_cursor_exception;
  1845. + }
  1846. + rc = initPage(pBt, pCur->pPage, pCur->pgnoRoot, 0);
  1847. + if( rc!=SQLITE_OK ){
  1848. + goto create_cursor_exception;
  1849. + }
  1850. + pCur->pOps = &sqliteBtreeCursorOps;
  1851. + pCur->pBt = pBt;
  1852. + pCur->wrFlag = wrFlag;
  1853. + pCur->idx = 0;
  1854. + pCur->eSkip = SKIP_INVALID;
  1855. + pCur->pNext = pBt->pCursor;
  1856. + if( pCur->pNext ){
  1857. + pCur->pNext->pPrev = pCur;
  1858. + }
  1859. + pCur->pPrev = 0;
  1860. + pRing = pBt->pCursor;
  1861. + while( pRing && pRing->pgnoRoot!=pCur->pgnoRoot ){ pRing = pRing->pNext; }
  1862. + if( pRing ){
  1863. + pCur->pShared = pRing->pShared;
  1864. + pRing->pShared = pCur;
  1865. + }else{
  1866. + pCur->pShared = pCur;
  1867. + }
  1868. + pBt->pCursor = pCur;
  1869. + *ppCur = pCur;
  1870. + return SQLITE_OK;
  1871. +
  1872. +create_cursor_exception:
  1873. + *ppCur = 0;
  1874. + if( pCur ){
  1875. + if( pCur->pPage ) sqlitepager_unref(pCur->pPage);
  1876. + sqliteFree(pCur);
  1877. + }
  1878. + unlockBtreeIfUnused(pBt);
  1879. + return rc;
  1880. +}
  1881. +
  1882. +/*
  1883. +** Close a cursor. The read lock on the database file is released
  1884. +** when the last cursor is closed.
  1885. +*/
  1886. +static int fileBtreeCloseCursor(BtCursor *pCur){
  1887. + Btree *pBt = pCur->pBt;
  1888. + if( pCur->pPrev ){
  1889. + pCur->pPrev->pNext = pCur->pNext;
  1890. + }else{
  1891. + pBt->pCursor = pCur->pNext;
  1892. + }
  1893. + if( pCur->pNext ){
  1894. + pCur->pNext->pPrev = pCur->pPrev;
  1895. + }
  1896. + if( pCur->pPage ){
  1897. + sqlitepager_unref(pCur->pPage);
  1898. + }
  1899. + if( pCur->pShared!=pCur ){
  1900. + BtCursor *pRing = pCur->pShared;
  1901. + while( pRing->pShared!=pCur ){ pRing = pRing->pShared; }
  1902. + pRing->pShared = pCur->pShared;
  1903. + }
  1904. + unlockBtreeIfUnused(pBt);
  1905. + sqliteFree(pCur);
  1906. + return SQLITE_OK;
  1907. +}
  1908. +
  1909. +/*
  1910. +** Make a temporary cursor by filling in the fields of pTempCur.
  1911. +** The temporary cursor is not on the cursor list for the Btree.
  1912. +*/
  1913. +static void getTempCursor(BtCursor *pCur, BtCursor *pTempCur){
  1914. + memcpy(pTempCur, pCur, sizeof(*pCur));
  1915. + pTempCur->pNext = 0;
  1916. + pTempCur->pPrev = 0;
  1917. + if( pTempCur->pPage ){
  1918. + sqlitepager_ref(pTempCur->pPage);
  1919. + }
  1920. +}
  1921. +
  1922. +/*
  1923. +** Delete a temporary cursor such as was made by the CreateTemporaryCursor()
  1924. +** function above.
  1925. +*/
  1926. +static void releaseTempCursor(BtCursor *pCur){
  1927. + if( pCur->pPage ){
  1928. + sqlitepager_unref(pCur->pPage);
  1929. + }
  1930. +}
  1931. +
  1932. +/*
  1933. +** Set *pSize to the number of bytes of key in the entry the
  1934. +** cursor currently points to. Always return SQLITE_OK.
  1935. +** Failure is not possible. If the cursor is not currently
  1936. +** pointing to an entry (which can happen, for example, if
  1937. +** the database is empty) then *pSize is set to 0.
  1938. +*/
  1939. +static int fileBtreeKeySize(BtCursor *pCur, int *pSize){
  1940. + Cell *pCell;
  1941. + MemPage *pPage;
  1942. +
  1943. + pPage = pCur->pPage;
  1944. + assert( pPage!=0 );
  1945. + if( pCur->idx >= pPage->nCell ){
  1946. + *pSize = 0;
  1947. + }else{
  1948. + pCell = pPage->apCell[pCur->idx];
  1949. + *pSize = NKEY(pCur->pBt, pCell->h);
  1950. + }
  1951. + return SQLITE_OK;
  1952. +}
  1953. +
  1954. +/*
  1955. +** Read payload information from the entry that the pCur cursor is
  1956. +** pointing to. Begin reading the payload at "offset" and read
  1957. +** a total of "amt" bytes. Put the result in zBuf.
  1958. +**
  1959. +** This routine does not make a distinction between key and data.
  1960. +** It just reads bytes from the payload area.
  1961. +*/
  1962. +static int getPayload(BtCursor *pCur, int offset, int amt, char *zBuf){
  1963. + char *aPayload;
  1964. + Pgno nextPage;
  1965. + int rc;
  1966. + Btree *pBt = pCur->pBt;
  1967. + assert( pCur!=0 && pCur->pPage!=0 );
  1968. + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
  1969. + aPayload = pCur->pPage->apCell[pCur->idx]->aPayload;
  1970. + if( offset<MX_LOCAL_PAYLOAD ){
  1971. + int a = amt;
  1972. + if( a+offset>MX_LOCAL_PAYLOAD ){
  1973. + a = MX_LOCAL_PAYLOAD - offset;
  1974. + }
  1975. + memcpy(zBuf, &aPayload[offset], a);
  1976. + if( a==amt ){
  1977. + return SQLITE_OK;
  1978. + }
  1979. + offset = 0;
  1980. + zBuf += a;
  1981. + amt -= a;
  1982. + }else{
  1983. + offset -= MX_LOCAL_PAYLOAD;
  1984. + }
  1985. + if( amt>0 ){
  1986. + nextPage = SWAB32(pBt, pCur->pPage->apCell[pCur->idx]->ovfl);
  1987. + }
  1988. + while( amt>0 && nextPage ){
  1989. + OverflowPage *pOvfl;
  1990. + rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
  1991. + if( rc!=0 ){
  1992. + return rc;
  1993. + }
  1994. + nextPage = SWAB32(pBt, pOvfl->iNext);
  1995. + if( offset<OVERFLOW_SIZE ){
  1996. + int a = amt;
  1997. + if( a + offset > OVERFLOW_SIZE ){
  1998. + a = OVERFLOW_SIZE - offset;
  1999. + }
  2000. + memcpy(zBuf, &pOvfl->aPayload[offset], a);
  2001. + offset = 0;
  2002. + amt -= a;
  2003. + zBuf += a;
  2004. + }else{
  2005. + offset -= OVERFLOW_SIZE;
  2006. + }
  2007. + sqlitepager_unref(pOvfl);
  2008. + }
  2009. + if( amt>0 ){
  2010. + return SQLITE_CORRUPT;
  2011. + }
  2012. + return SQLITE_OK;
  2013. +}
  2014. +
  2015. +/*
  2016. +** Read part of the key associated with cursor pCur. A maximum
  2017. +** of "amt" bytes will be transfered into zBuf[]. The transfer
  2018. +** begins at "offset". The number of bytes actually read is
  2019. +** returned.
  2020. +**
  2021. +** Change: It used to be that the amount returned will be smaller
  2022. +** than the amount requested if there are not enough bytes in the key
  2023. +** to satisfy the request. But now, it must be the case that there
  2024. +** is enough data available to satisfy the request. If not, an exception
  2025. +** is raised. The change was made in an effort to boost performance
  2026. +** by eliminating unneeded tests.
  2027. +*/
  2028. +static int fileBtreeKey(BtCursor *pCur, int offset, int amt, char *zBuf){
  2029. + MemPage *pPage;
  2030. +
  2031. + assert( amt>=0 );
  2032. + assert( offset>=0 );
  2033. + assert( pCur->pPage!=0 );
  2034. + pPage = pCur->pPage;
  2035. + if( pCur->idx >= pPage->nCell ){
  2036. + return 0;
  2037. + }
  2038. + assert( amt+offset <= NKEY(pCur->pBt, pPage->apCell[pCur->idx]->h) );
  2039. + getPayload(pCur, offset, amt, zBuf);
  2040. + return amt;
  2041. +}
  2042. +
  2043. +/*
  2044. +** Set *pSize to the number of bytes of data in the entry the
  2045. +** cursor currently points to. Always return SQLITE_OK.
  2046. +** Failure is not possible. If the cursor is not currently
  2047. +** pointing to an entry (which can happen, for example, if
  2048. +** the database is empty) then *pSize is set to 0.
  2049. +*/
  2050. +static int fileBtreeDataSize(BtCursor *pCur, int *pSize){
  2051. + Cell *pCell;
  2052. + MemPage *pPage;
  2053. +
  2054. + pPage = pCur->pPage;
  2055. + assert( pPage!=0 );
  2056. + if( pCur->idx >= pPage->nCell ){
  2057. + *pSize = 0;
  2058. + }else{
  2059. + pCell = pPage->apCell[pCur->idx];
  2060. + *pSize = NDATA(pCur->pBt, pCell->h);
  2061. + }
  2062. + return SQLITE_OK;
  2063. +}
  2064. +
  2065. +/*
  2066. +** Read part of the data associated with cursor pCur. A maximum
  2067. +** of "amt" bytes will be transfered into zBuf[]. The transfer
  2068. +** begins at "offset". The number of bytes actually read is
  2069. +** returned. The amount returned will be smaller than the
  2070. +** amount requested if there are not enough bytes in the data
  2071. +** to satisfy the request.
  2072. +*/
  2073. +static int fileBtreeData(BtCursor *pCur, int offset, int amt, char *zBuf){
  2074. + Cell *pCell;
  2075. + MemPage *pPage;
  2076. +
  2077. + assert( amt>=0 );
  2078. + assert( offset>=0 );
  2079. + assert( pCur->pPage!=0 );
  2080. + pPage = pCur->pPage;
  2081. + if( pCur->idx >= pPage->nCell ){
  2082. + return 0;
  2083. + }
  2084. + pCell = pPage->apCell[pCur->idx];
  2085. + assert( amt+offset <= NDATA(pCur->pBt, pCell->h) );
  2086. + getPayload(pCur, offset + NKEY(pCur->pBt, pCell->h), amt, zBuf);
  2087. + return amt;
  2088. +}
  2089. +
  2090. +/*
  2091. +** Compare an external key against the key on the entry that pCur points to.
  2092. +**
  2093. +** The external key is pKey and is nKey bytes long. The last nIgnore bytes
  2094. +** of the key associated with pCur are ignored, as if they do not exist.
  2095. +** (The normal case is for nIgnore to be zero in which case the entire
  2096. +** internal key is used in the comparison.)
  2097. +**
  2098. +** The comparison result is written to *pRes as follows:
  2099. +**
  2100. +** *pRes<0 This means pCur<pKey
  2101. +**
  2102. +** *pRes==0 This means pCur==pKey for all nKey bytes
  2103. +**
  2104. +** *pRes>0 This means pCur>pKey
  2105. +**
  2106. +** When one key is an exact prefix of the other, the shorter key is
  2107. +** considered less than the longer one. In order to be equal the
  2108. +** keys must be exactly the same length. (The length of the pCur key
  2109. +** is the actual key length minus nIgnore bytes.)
  2110. +*/
  2111. +static int fileBtreeKeyCompare(
  2112. + BtCursor *pCur, /* Pointer to entry to compare against */
  2113. + const void *pKey, /* Key to compare against entry that pCur points to */
  2114. + int nKey, /* Number of bytes in pKey */
  2115. + int nIgnore, /* Ignore this many bytes at the end of pCur */
  2116. + int *pResult /* Write the result here */
  2117. +){
  2118. + Pgno nextPage;
  2119. + int n, c, rc, nLocal;
  2120. + Cell *pCell;
  2121. + Btree *pBt = pCur->pBt;
  2122. + const char *zKey = (const char*)pKey;
  2123. +
  2124. + assert( pCur->pPage );
  2125. + assert( pCur->idx>=0 && pCur->idx<pCur->pPage->nCell );
  2126. + pCell = pCur->pPage->apCell[pCur->idx];
  2127. + nLocal = NKEY(pBt, pCell->h) - nIgnore;
  2128. + if( nLocal<0 ) nLocal = 0;
  2129. + n = nKey<nLocal ? nKey : nLocal;
  2130. + if( n>MX_LOCAL_PAYLOAD ){
  2131. + n = MX_LOCAL_PAYLOAD;
  2132. + }
  2133. + c = memcmp(pCell->aPayload, zKey, n);
  2134. + if( c!=0 ){
  2135. + *pResult = c;
  2136. + return SQLITE_OK;
  2137. + }
  2138. + zKey += n;
  2139. + nKey -= n;
  2140. + nLocal -= n;
  2141. + nextPage = SWAB32(pBt, pCell->ovfl);
  2142. + while( nKey>0 && nLocal>0 ){
  2143. + OverflowPage *pOvfl;
  2144. + if( nextPage==0 ){
  2145. + return SQLITE_CORRUPT;
  2146. + }
  2147. + rc = sqlitepager_get(pBt->pPager, nextPage, (void**)&pOvfl);
  2148. + if( rc ){
  2149. + return rc;
  2150. + }
  2151. + nextPage = SWAB32(pBt, pOvfl->iNext);
  2152. + n = nKey<nLocal ? nKey : nLocal;
  2153. + if( n>OVERFLOW_SIZE ){
  2154. + n = OVERFLOW_SIZE;
  2155. + }
  2156. + c = memcmp(pOvfl->aPayload, zKey, n);
  2157. + sqlitepager_unref(pOvfl);
  2158. + if( c!=0 ){
  2159. + *pResult = c;
  2160. + return SQLITE_OK;
  2161. + }
  2162. + nKey -= n;
  2163. + nLocal -= n;
  2164. + zKey += n;
  2165. + }
  2166. + if( c==0 ){
  2167. + c = nLocal - nKey;
  2168. + }
  2169. + *pResult = c;
  2170. + return SQLITE_OK;
  2171. +}
  2172. +
  2173. +/*
  2174. +** Move the cursor down to a new child page. The newPgno argument is the
  2175. +** page number of the child page in the byte order of the disk image.
  2176. +*/
  2177. +static int moveToChild(BtCursor *pCur, int newPgno){
  2178. + int rc;
  2179. + MemPage *pNewPage;
  2180. + Btree *pBt = pCur->pBt;
  2181. +
  2182. + newPgno = SWAB32(pBt, newPgno);
  2183. + rc = sqlitepager_get(pBt->pPager, newPgno, (void**)&pNewPage);
  2184. + if( rc ) return rc;
  2185. + rc = initPage(pBt, pNewPage, newPgno, pCur->pPage);
  2186. + if( rc ) return rc;
  2187. + assert( pCur->idx>=pCur->pPage->nCell
  2188. + || pCur->pPage->apCell[pCur->idx]->h.leftChild==SWAB32(pBt,newPgno) );
  2189. + assert( pCur->idx<pCur->pPage->nCell
  2190. + || pCur->pPage->u.hdr.rightChild==SWAB32(pBt,newPgno) );
  2191. + pNewPage->idxParent = pCur->idx;
  2192. + pCur->pPage->idxShift = 0;
  2193. + sqlitepager_unref(pCur->pPage);
  2194. + pCur->pPage = pNewPage;
  2195. + pCur->idx = 0;
  2196. + if( pNewPage->nCell<1 ){
  2197. + return SQLITE_CORRUPT;
  2198. + }
  2199. + return SQLITE_OK;
  2200. +}
  2201. +
  2202. +/*
  2203. +** Move the cursor up to the parent page.
  2204. +**
  2205. +** pCur->idx is set to the cell index that contains the pointer
  2206. +** to the page we are coming from. If we are coming from the
  2207. +** right-most child page then pCur->idx is set to one more than
  2208. +** the largest cell index.
  2209. +*/
  2210. +static void moveToParent(BtCursor *pCur){
  2211. + Pgno oldPgno;
  2212. + MemPage *pParent;
  2213. + MemPage *pPage;
  2214. + int idxParent;
  2215. + pPage = pCur->pPage;
  2216. + assert( pPage!=0 );
  2217. + pParent = pPage->pParent;
  2218. + assert( pParent!=0 );
  2219. + idxParent = pPage->idxParent;
  2220. + sqlitepager_ref(pParent);
  2221. + sqlitepager_unref(pPage);
  2222. + pCur->pPage = pParent;
  2223. + assert( pParent->idxShift==0 );
  2224. + if( pParent->idxShift==0 ){
  2225. + pCur->idx = idxParent;
  2226. +#ifndef NDEBUG
  2227. + /* Verify that pCur->idx is the correct index to point back to the child
  2228. + ** page we just came from
  2229. + */
  2230. + oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
  2231. + if( pCur->idx<pParent->nCell ){
  2232. + assert( pParent->apCell[idxParent]->h.leftChild==oldPgno );
  2233. + }else{
  2234. + assert( pParent->u.hdr.rightChild==oldPgno );
  2235. + }
  2236. +#endif
  2237. + }else{
  2238. + /* The MemPage.idxShift flag indicates that cell indices might have
  2239. + ** changed since idxParent was set and hence idxParent might be out
  2240. + ** of date. So recompute the parent cell index by scanning all cells
  2241. + ** and locating the one that points to the child we just came from.
  2242. + */
  2243. + int i;
  2244. + pCur->idx = pParent->nCell;
  2245. + oldPgno = SWAB32(pCur->pBt, sqlitepager_pagenumber(pPage));
  2246. + for(i=0; i<pParent->nCell; i++){
  2247. + if( pParent->apCell[i]->h.leftChild==oldPgno ){
  2248. + pCur->idx = i;
  2249. + break;
  2250. + }
  2251. + }
  2252. + }
  2253. +}
  2254. +
  2255. +/*
  2256. +** Move the cursor to the root page
  2257. +*/
  2258. +static int moveToRoot(BtCursor *pCur){
  2259. + MemPage *pNew;
  2260. + int rc;
  2261. + Btree *pBt = pCur->pBt;
  2262. +
  2263. + rc = sqlitepager_get(pBt->pPager, pCur->pgnoRoot, (void**)&pNew);
  2264. + if( rc ) return rc;
  2265. + rc = initPage(pBt, pNew, pCur->pgnoRoot, 0);
  2266. + if( rc ) return rc;
  2267. + sqlitepager_unref(pCur->pPage);
  2268. + pCur->pPage = pNew;
  2269. + pCur->idx = 0;
  2270. + return SQLITE_OK;
  2271. +}
  2272. +
  2273. +/*
  2274. +** Move the cursor down to the left-most leaf entry beneath the
  2275. +** entry to which it is currently pointing.
  2276. +*/
  2277. +static int moveToLeftmost(BtCursor *pCur){
  2278. + Pgno pgno;
  2279. + int rc;
  2280. +
  2281. + while( (pgno = pCur->pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
  2282. + rc = moveToChild(pCur, pgno);
  2283. + if( rc ) return rc;
  2284. + }
  2285. + return SQLITE_OK;
  2286. +}
  2287. +
  2288. +/*
  2289. +** Move the cursor down to the right-most leaf entry beneath the
  2290. +** page to which it is currently pointing. Notice the difference
  2291. +** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  2292. +** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  2293. +** finds the right-most entry beneath the *page*.
  2294. +*/
  2295. +static int moveToRightmost(BtCursor *pCur){
  2296. + Pgno pgno;
  2297. + int rc;
  2298. +
  2299. + while( (pgno = pCur->pPage->u.hdr.rightChild)!=0 ){
  2300. + pCur->idx = pCur->pPage->nCell;
  2301. + rc = moveToChild(pCur, pgno);
  2302. + if( rc ) return rc;
  2303. + }
  2304. + pCur->idx = pCur->pPage->nCell - 1;
  2305. + return SQLITE_OK;
  2306. +}
  2307. +
  2308. +/* Move the cursor to the first entry in the table. Return SQLITE_OK
  2309. +** on success. Set *pRes to 0 if the cursor actually points to something
  2310. +** or set *pRes to 1 if the table is empty.
  2311. +*/
  2312. +static int fileBtreeFirst(BtCursor *pCur, int *pRes){
  2313. + int rc;
  2314. + if( pCur->pPage==0 ) return SQLITE_ABORT;
  2315. + rc = moveToRoot(pCur);
  2316. + if( rc ) return rc;
  2317. + if( pCur->pPage->nCell==0 ){
  2318. + *pRes = 1;
  2319. + return SQLITE_OK;
  2320. + }
  2321. + *pRes = 0;
  2322. + rc = moveToLeftmost(pCur);
  2323. + pCur->eSkip = SKIP_NONE;
  2324. + return rc;
  2325. +}
  2326. +
  2327. +/* Move the cursor to the last entry in the table. Return SQLITE_OK
  2328. +** on success. Set *pRes to 0 if the cursor actually points to something
  2329. +** or set *pRes to 1 if the table is empty.
  2330. +*/
  2331. +static int fileBtreeLast(BtCursor *pCur, int *pRes){
  2332. + int rc;
  2333. + if( pCur->pPage==0 ) return SQLITE_ABORT;
  2334. + rc = moveToRoot(pCur);
  2335. + if( rc ) return rc;
  2336. + assert( pCur->pPage->isInit );
  2337. + if( pCur->pPage->nCell==0 ){
  2338. + *pRes = 1;
  2339. + return SQLITE_OK;
  2340. + }
  2341. + *pRes = 0;
  2342. + rc = moveToRightmost(pCur);
  2343. + pCur->eSkip = SKIP_NONE;
  2344. + return rc;
  2345. +}
  2346. +
  2347. +/* Move the cursor so that it points to an entry near pKey.
  2348. +** Return a success code.
  2349. +**
  2350. +** If an exact match is not found, then the cursor is always
  2351. +** left pointing at a leaf page which would hold the entry if it
  2352. +** were present. The cursor might point to an entry that comes
  2353. +** before or after the key.
  2354. +**
  2355. +** The result of comparing the key with the entry to which the
  2356. +** cursor is left pointing is stored in pCur->iMatch. The same
  2357. +** value is also written to *pRes if pRes!=NULL. The meaning of
  2358. +** this value is as follows:
  2359. +**
  2360. +** *pRes<0 The cursor is left pointing at an entry that
  2361. +** is smaller than pKey or if the table is empty
  2362. +** and the cursor is therefore left point to nothing.
  2363. +**
  2364. +** *pRes==0 The cursor is left pointing at an entry that
  2365. +** exactly matches pKey.
  2366. +**
  2367. +** *pRes>0 The cursor is left pointing at an entry that
  2368. +** is larger than pKey.
  2369. +*/
  2370. +static
  2371. +int fileBtreeMoveto(BtCursor *pCur, const void *pKey, int nKey, int *pRes){
  2372. + int rc;
  2373. + if( pCur->pPage==0 ) return SQLITE_ABORT;
  2374. + pCur->eSkip = SKIP_NONE;
  2375. + rc = moveToRoot(pCur);
  2376. + if( rc ) return rc;
  2377. + for(;;){
  2378. + int lwr, upr;
  2379. + Pgno chldPg;
  2380. + MemPage *pPage = pCur->pPage;
  2381. + int c = -1; /* pRes return if table is empty must be -1 */
  2382. + lwr = 0;
  2383. + upr = pPage->nCell-1;
  2384. + while( lwr<=upr ){
  2385. + pCur->idx = (lwr+upr)/2;
  2386. + rc = fileBtreeKeyCompare(pCur, pKey, nKey, 0, &c);
  2387. + if( rc ) return rc;
  2388. + if( c==0 ){
  2389. + pCur->iMatch = c;
  2390. + if( pRes ) *pRes = 0;
  2391. + return SQLITE_OK;
  2392. + }
  2393. + if( c<0 ){
  2394. + lwr = pCur->idx+1;
  2395. + }else{
  2396. + upr = pCur->idx-1;
  2397. + }
  2398. + }
  2399. + assert( lwr==upr+1 );
  2400. + assert( pPage->isInit );
  2401. + if( lwr>=pPage->nCell ){
  2402. + chldPg = pPage->u.hdr.rightChild;
  2403. + }else{
  2404. + chldPg = pPage->apCell[lwr]->h.leftChild;
  2405. + }
  2406. + if( chldPg==0 ){
  2407. + pCur->iMatch = c;
  2408. + if( pRes ) *pRes = c;
  2409. + return SQLITE_OK;
  2410. + }
  2411. + pCur->idx = lwr;
  2412. + rc = moveToChild(pCur, chldPg);
  2413. + if( rc ) return rc;
  2414. + }
  2415. + /* NOT REACHED */
  2416. +}
  2417. +
  2418. +/*
  2419. +** Advance the cursor to the next entry in the database. If
  2420. +** successful then set *pRes=0. If the cursor
  2421. +** was already pointing to the last entry in the database before
  2422. +** this routine was called, then set *pRes=1.
  2423. +*/
  2424. +static int fileBtreeNext(BtCursor *pCur, int *pRes){
  2425. + int rc;
  2426. + MemPage *pPage = pCur->pPage;
  2427. + assert( pRes!=0 );
  2428. + if( pPage==0 ){
  2429. + *pRes = 1;
  2430. + return SQLITE_ABORT;
  2431. + }
  2432. + assert( pPage->isInit );
  2433. + assert( pCur->eSkip!=SKIP_INVALID );
  2434. + if( pPage->nCell==0 ){
  2435. + *pRes = 1;
  2436. + return SQLITE_OK;
  2437. + }
  2438. + assert( pCur->idx<pPage->nCell );
  2439. + if( pCur->eSkip==SKIP_NEXT ){
  2440. + pCur->eSkip = SKIP_NONE;
  2441. + *pRes = 0;
  2442. + return SQLITE_OK;
  2443. + }
  2444. + pCur->eSkip = SKIP_NONE;
  2445. + pCur->idx++;
  2446. + if( pCur->idx>=pPage->nCell ){
  2447. + if( pPage->u.hdr.rightChild ){
  2448. + rc = moveToChild(pCur, pPage->u.hdr.rightChild);
  2449. + if( rc ) return rc;
  2450. + rc = moveToLeftmost(pCur);
  2451. + *pRes = 0;
  2452. + return rc;
  2453. + }
  2454. + do{
  2455. + if( pPage->pParent==0 ){
  2456. + *pRes = 1;
  2457. + return SQLITE_OK;
  2458. + }
  2459. + moveToParent(pCur);
  2460. + pPage = pCur->pPage;
  2461. + }while( pCur->idx>=pPage->nCell );
  2462. + *pRes = 0;
  2463. + return SQLITE_OK;
  2464. + }
  2465. + *pRes = 0;
  2466. + if( pPage->u.hdr.rightChild==0 ){
  2467. + return SQLITE_OK;
  2468. + }
  2469. + rc = moveToLeftmost(pCur);
  2470. + return rc;
  2471. +}
  2472. +
  2473. +/*
  2474. +** Step the cursor to the back to the previous entry in the database. If
  2475. +** successful then set *pRes=0. If the cursor
  2476. +** was already pointing to the first entry in the database before
  2477. +** this routine was called, then set *pRes=1.
  2478. +*/
  2479. +static int fileBtreePrevious(BtCursor *pCur, int *pRes){
  2480. + int rc;
  2481. + Pgno pgno;
  2482. + MemPage *pPage;
  2483. + pPage = pCur->pPage;
  2484. + if( pPage==0 ){
  2485. + *pRes = 1;
  2486. + return SQLITE_ABORT;
  2487. + }
  2488. + assert( pPage->isInit );
  2489. + assert( pCur->eSkip!=SKIP_INVALID );
  2490. + if( pPage->nCell==0 ){
  2491. + *pRes = 1;
  2492. + return SQLITE_OK;
  2493. + }
  2494. + if( pCur->eSkip==SKIP_PREV ){
  2495. + pCur->eSkip = SKIP_NONE;
  2496. + *pRes = 0;
  2497. + return SQLITE_OK;
  2498. + }
  2499. + pCur->eSkip = SKIP_NONE;
  2500. + assert( pCur->idx>=0 );
  2501. + if( (pgno = pPage->apCell[pCur->idx]->h.leftChild)!=0 ){
  2502. + rc = moveToChild(pCur, pgno);
  2503. + if( rc ) return rc;
  2504. + rc = moveToRightmost(pCur);
  2505. + }else{
  2506. + while( pCur->idx==0 ){
  2507. + if( pPage->pParent==0 ){
  2508. + if( pRes ) *pRes = 1;
  2509. + return SQLITE_OK;
  2510. + }
  2511. + moveToParent(pCur);
  2512. + pPage = pCur->pPage;
  2513. + }
  2514. + pCur->idx--;
  2515. + rc = SQLITE_OK;
  2516. + }
  2517. + *pRes = 0;
  2518. + return rc;
  2519. +}
  2520. +
  2521. +/*
  2522. +** Allocate a new page from the database file.
  2523. +**
  2524. +** The new page is marked as dirty. (In other words, sqlitepager_write()
  2525. +** has already been called on the new page.) The new page has also
  2526. +** been referenced and the calling routine is responsible for calling
  2527. +** sqlitepager_unref() on the new page when it is done.
  2528. +**
  2529. +** SQLITE_OK is returned on success. Any other return value indicates
  2530. +** an error. *ppPage and *pPgno are undefined in the event of an error.
  2531. +** Do not invoke sqlitepager_unref() on *ppPage if an error is returned.
  2532. +**
  2533. +** If the "nearby" parameter is not 0, then a (feeble) effort is made to
  2534. +** locate a page close to the page number "nearby". This can be used in an
  2535. +** attempt to keep related pages close to each other in the database file,
  2536. +** which in turn can make database access faster.
  2537. +*/
  2538. +static int allocatePage(Btree *pBt, MemPage **ppPage, Pgno *pPgno, Pgno nearby){
  2539. + PageOne *pPage1 = pBt->page1;
  2540. + int rc;
  2541. + if( pPage1->freeList ){
  2542. + OverflowPage *pOvfl;
  2543. + FreelistInfo *pInfo;
  2544. +
  2545. + rc = sqlitepager_write(pPage1);
  2546. + if( rc ) return rc;
  2547. + SWAB_ADD(pBt, pPage1->nFree, -1);
  2548. + rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
  2549. + (void**)&pOvfl);
  2550. + if( rc ) return rc;
  2551. + rc = sqlitepager_write(pOvfl);
  2552. + if( rc ){
  2553. + sqlitepager_unref(pOvfl);
  2554. + return rc;
  2555. + }
  2556. + pInfo = (FreelistInfo*)pOvfl->aPayload;
  2557. + if( pInfo->nFree==0 ){
  2558. + *pPgno = SWAB32(pBt, pPage1->freeList);
  2559. + pPage1->freeList = pOvfl->iNext;
  2560. + *ppPage = (MemPage*)pOvfl;
  2561. + }else{
  2562. + int closest, n;
  2563. + n = SWAB32(pBt, pInfo->nFree);
  2564. + if( n>1 && nearby>0 ){
  2565. + int i, dist;
  2566. + closest = 0;
  2567. + dist = SWAB32(pBt, pInfo->aFree[0]) - nearby;
  2568. + if( dist<0 ) dist = -dist;
  2569. + for(i=1; i<n; i++){
  2570. + int d2 = SWAB32(pBt, pInfo->aFree[i]) - nearby;
  2571. + if( d2<0 ) d2 = -d2;
  2572. + if( d2<dist ) closest = i;
  2573. + }
  2574. + }else{
  2575. + closest = 0;
  2576. + }
  2577. + SWAB_ADD(pBt, pInfo->nFree, -1);
  2578. + *pPgno = SWAB32(pBt, pInfo->aFree[closest]);
  2579. + pInfo->aFree[closest] = pInfo->aFree[n-1];
  2580. + rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
  2581. + sqlitepager_unref(pOvfl);
  2582. + if( rc==SQLITE_OK ){
  2583. + sqlitepager_dont_rollback(*ppPage);
  2584. + rc = sqlitepager_write(*ppPage);
  2585. + }
  2586. + }
  2587. + }else{
  2588. + *pPgno = sqlitepager_pagecount(pBt->pPager) + 1;
  2589. + rc = sqlitepager_get(pBt->pPager, *pPgno, (void**)ppPage);
  2590. + if( rc ) return rc;
  2591. + rc = sqlitepager_write(*ppPage);
  2592. + }
  2593. + return rc;
  2594. +}
  2595. +
  2596. +/*
  2597. +** Add a page of the database file to the freelist. Either pgno or
  2598. +** pPage but not both may be 0.
  2599. +**
  2600. +** sqlitepager_unref() is NOT called for pPage.
  2601. +*/
  2602. +static int freePage(Btree *pBt, void *pPage, Pgno pgno){
  2603. + PageOne *pPage1 = pBt->page1;
  2604. + OverflowPage *pOvfl = (OverflowPage*)pPage;
  2605. + int rc;
  2606. + int needUnref = 0;
  2607. + MemPage *pMemPage;
  2608. +
  2609. + if( pgno==0 ){
  2610. + assert( pOvfl!=0 );
  2611. + pgno = sqlitepager_pagenumber(pOvfl);
  2612. + }
  2613. + assert( pgno>2 );
  2614. + assert( sqlitepager_pagenumber(pOvfl)==pgno );
  2615. + pMemPage = (MemPage*)pPage;
  2616. + pMemPage->isInit = 0;
  2617. + if( pMemPage->pParent ){
  2618. + sqlitepager_unref(pMemPage->pParent);
  2619. + pMemPage->pParent = 0;
  2620. + }
  2621. + rc = sqlitepager_write(pPage1);
  2622. + if( rc ){
  2623. + return rc;
  2624. + }
  2625. + SWAB_ADD(pBt, pPage1->nFree, 1);
  2626. + if( pPage1->nFree!=0 && pPage1->freeList!=0 ){
  2627. + OverflowPage *pFreeIdx;
  2628. + rc = sqlitepager_get(pBt->pPager, SWAB32(pBt, pPage1->freeList),
  2629. + (void**)&pFreeIdx);
  2630. + if( rc==SQLITE_OK ){
  2631. + FreelistInfo *pInfo = (FreelistInfo*)pFreeIdx->aPayload;
  2632. + int n = SWAB32(pBt, pInfo->nFree);
  2633. + if( n<(sizeof(pInfo->aFree)/sizeof(pInfo->aFree[0])) ){
  2634. + rc = sqlitepager_write(pFreeIdx);
  2635. + if( rc==SQLITE_OK ){
  2636. + pInfo->aFree[n] = SWAB32(pBt, pgno);
  2637. + SWAB_ADD(pBt, pInfo->nFree, 1);
  2638. + sqlitepager_unref(pFreeIdx);
  2639. + sqlitepager_dont_write(pBt->pPager, pgno);
  2640. + return rc;
  2641. + }
  2642. + }
  2643. + sqlitepager_unref(pFreeIdx);
  2644. + }
  2645. + }
  2646. + if( pOvfl==0 ){
  2647. + assert( pgno>0 );
  2648. + rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pOvfl);
  2649. + if( rc ) return rc;
  2650. + needUnref = 1;
  2651. + }
  2652. + rc = sqlitepager_write(pOvfl);
  2653. + if( rc ){
  2654. + if( needUnref ) sqlitepager_unref(pOvfl);
  2655. + return rc;
  2656. + }
  2657. + pOvfl->iNext = pPage1->freeList;
  2658. + pPage1->freeList = SWAB32(pBt, pgno);
  2659. + memset(pOvfl->aPayload, 0, OVERFLOW_SIZE);
  2660. + if( needUnref ) rc = sqlitepager_unref(pOvfl);
  2661. + return rc;
  2662. +}
  2663. +
  2664. +/*
  2665. +** Erase all the data out of a cell. This involves returning overflow
  2666. +** pages back the freelist.
  2667. +*/
  2668. +static int clearCell(Btree *pBt, Cell *pCell){
  2669. + Pager *pPager = pBt->pPager;
  2670. + OverflowPage *pOvfl;
  2671. + Pgno ovfl, nextOvfl;
  2672. + int rc;
  2673. +
  2674. + if( NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h) <= MX_LOCAL_PAYLOAD ){
  2675. + return SQLITE_OK;
  2676. + }
  2677. + ovfl = SWAB32(pBt, pCell->ovfl);
  2678. + pCell->ovfl = 0;
  2679. + while( ovfl ){
  2680. + rc = sqlitepager_get(pPager, ovfl, (void**)&pOvfl);
  2681. + if( rc ) return rc;
  2682. + nextOvfl = SWAB32(pBt, pOvfl->iNext);
  2683. + rc = freePage(pBt, pOvfl, ovfl);
  2684. + if( rc ) return rc;
  2685. + sqlitepager_unref(pOvfl);
  2686. + ovfl = nextOvfl;
  2687. + }
  2688. + return SQLITE_OK;
  2689. +}
  2690. +
  2691. +/*
  2692. +** Create a new cell from key and data. Overflow pages are allocated as
  2693. +** necessary and linked to this cell.
  2694. +*/
  2695. +static int fillInCell(
  2696. + Btree *pBt, /* The whole Btree. Needed to allocate pages */
  2697. + Cell *pCell, /* Populate this Cell structure */
  2698. + const void *pKey, int nKey, /* The key */
  2699. + const void *pData,int nData /* The data */
  2700. +){
  2701. + OverflowPage *pOvfl, *pPrior;
  2702. + Pgno *pNext;
  2703. + int spaceLeft;
  2704. + int n, rc;
  2705. + int nPayload;
  2706. + const char *pPayload;
  2707. + char *pSpace;
  2708. + Pgno nearby = 0;
  2709. +
  2710. + pCell->h.leftChild = 0;
  2711. + pCell->h.nKey = SWAB16(pBt, nKey & 0xffff);
  2712. + pCell->h.nKeyHi = nKey >> 16;
  2713. + pCell->h.nData = SWAB16(pBt, nData & 0xffff);
  2714. + pCell->h.nDataHi = nData >> 16;
  2715. + pCell->h.iNext = 0;
  2716. +
  2717. + pNext = &pCell->ovfl;
  2718. + pSpace = pCell->aPayload;
  2719. + spaceLeft = MX_LOCAL_PAYLOAD;
  2720. + pPayload = pKey;
  2721. + pKey = 0;
  2722. + nPayload = nKey;
  2723. + pPrior = 0;
  2724. + while( nPayload>0 ){
  2725. + if( spaceLeft==0 ){
  2726. + rc = allocatePage(pBt, (MemPage**)&pOvfl, pNext, nearby);
  2727. + if( rc ){
  2728. + *pNext = 0;
  2729. + }else{
  2730. + nearby = *pNext;
  2731. + }
  2732. + if( pPrior ) sqlitepager_unref(pPrior);
  2733. + if( rc ){
  2734. + clearCell(pBt, pCell);
  2735. + return rc;
  2736. + }
  2737. + if( pBt->needSwab ) *pNext = swab32(*pNext);
  2738. + pPrior = pOvfl;
  2739. + spaceLeft = OVERFLOW_SIZE;
  2740. + pSpace = pOvfl->aPayload;
  2741. + pNext = &pOvfl->iNext;
  2742. + }
  2743. + n = nPayload;
  2744. + if( n>spaceLeft ) n = spaceLeft;
  2745. + memcpy(pSpace, pPayload, n);
  2746. + nPayload -= n;
  2747. + if( nPayload==0 && pData ){
  2748. + pPayload = pData;
  2749. + nPayload = nData;
  2750. + pData = 0;
  2751. + }else{
  2752. + pPayload += n;
  2753. + }
  2754. + spaceLeft -= n;
  2755. + pSpace += n;
  2756. + }
  2757. + *pNext = 0;
  2758. + if( pPrior ){
  2759. + sqlitepager_unref(pPrior);
  2760. + }
  2761. + return SQLITE_OK;
  2762. +}
  2763. +
  2764. +/*
  2765. +** Change the MemPage.pParent pointer on the page whose number is
  2766. +** given in the second argument so that MemPage.pParent holds the
  2767. +** pointer in the third argument.
  2768. +*/
  2769. +static void reparentPage(Pager *pPager, Pgno pgno, MemPage *pNewParent,int idx){
  2770. + MemPage *pThis;
  2771. +
  2772. + if( pgno==0 ) return;
  2773. + assert( pPager!=0 );
  2774. + pThis = sqlitepager_lookup(pPager, pgno);
  2775. + if( pThis && pThis->isInit ){
  2776. + if( pThis->pParent!=pNewParent ){
  2777. + if( pThis->pParent ) sqlitepager_unref(pThis->pParent);
  2778. + pThis->pParent = pNewParent;
  2779. + if( pNewParent ) sqlitepager_ref(pNewParent);
  2780. + }
  2781. + pThis->idxParent = idx;
  2782. + sqlitepager_unref(pThis);
  2783. + }
  2784. +}
  2785. +
  2786. +/*
  2787. +** Reparent all children of the given page to be the given page.
  2788. +** In other words, for every child of pPage, invoke reparentPage()
  2789. +** to make sure that each child knows that pPage is its parent.
  2790. +**
  2791. +** This routine gets called after you memcpy() one page into
  2792. +** another.
  2793. +*/
  2794. +static void reparentChildPages(Btree *pBt, MemPage *pPage){
  2795. + int i;
  2796. + Pager *pPager = pBt->pPager;
  2797. + for(i=0; i<pPage->nCell; i++){
  2798. + reparentPage(pPager, SWAB32(pBt, pPage->apCell[i]->h.leftChild), pPage, i);
  2799. + }
  2800. + reparentPage(pPager, SWAB32(pBt, pPage->u.hdr.rightChild), pPage, i);
  2801. + pPage->idxShift = 0;
  2802. +}
  2803. +
  2804. +/*
  2805. +** Remove the i-th cell from pPage. This routine effects pPage only.
  2806. +** The cell content is not freed or deallocated. It is assumed that
  2807. +** the cell content has been copied someplace else. This routine just
  2808. +** removes the reference to the cell from pPage.
  2809. +**
  2810. +** "sz" must be the number of bytes in the cell.
  2811. +**
  2812. +** Do not bother maintaining the integrity of the linked list of Cells.
  2813. +** Only the pPage->apCell[] array is important. The relinkCellList()
  2814. +** routine will be called soon after this routine in order to rebuild
  2815. +** the linked list.
  2816. +*/
  2817. +static void dropCell(Btree *pBt, MemPage *pPage, int idx, int sz){
  2818. + int j;
  2819. + assert( idx>=0 && idx<pPage->nCell );
  2820. + assert( sz==cellSize(pBt, pPage->apCell[idx]) );
  2821. + assert( sqlitepager_iswriteable(pPage) );
  2822. + freeSpace(pBt, pPage, Addr(pPage->apCell[idx]) - Addr(pPage), sz);
  2823. + for(j=idx; j<pPage->nCell-1; j++){
  2824. + pPage->apCell[j] = pPage->apCell[j+1];
  2825. + }
  2826. + pPage->nCell--;
  2827. + pPage->idxShift = 1;
  2828. +}
  2829. +
  2830. +/*
  2831. +** Insert a new cell on pPage at cell index "i". pCell points to the
  2832. +** content of the cell.
  2833. +**
  2834. +** If the cell content will fit on the page, then put it there. If it
  2835. +** will not fit, then just make pPage->apCell[i] point to the content
  2836. +** and set pPage->isOverfull.
  2837. +**
  2838. +** Do not bother maintaining the integrity of the linked list of Cells.
  2839. +** Only the pPage->apCell[] array is important. The relinkCellList()
  2840. +** routine will be called soon after this routine in order to rebuild
  2841. +** the linked list.
  2842. +*/
  2843. +static void insertCell(Btree *pBt, MemPage *pPage, int i, Cell *pCell, int sz){
  2844. + int idx, j;
  2845. + assert( i>=0 && i<=pPage->nCell );
  2846. + assert( sz==cellSize(pBt, pCell) );
  2847. + assert( sqlitepager_iswriteable(pPage) );
  2848. + idx = allocateSpace(pBt, pPage, sz);
  2849. + for(j=pPage->nCell; j>i; j--){
  2850. + pPage->apCell[j] = pPage->apCell[j-1];
  2851. + }
  2852. + pPage->nCell++;
  2853. + if( idx<=0 ){
  2854. + pPage->isOverfull = 1;
  2855. + pPage->apCell[i] = pCell;
  2856. + }else{
  2857. + memcpy(&pPage->u.aDisk[idx], pCell, sz);
  2858. + pPage->apCell[i] = (Cell*)&pPage->u.aDisk[idx];
  2859. + }
  2860. + pPage->idxShift = 1;
  2861. +}
  2862. +
  2863. +/*
  2864. +** Rebuild the linked list of cells on a page so that the cells
  2865. +** occur in the order specified by the pPage->apCell[] array.
  2866. +** Invoke this routine once to repair damage after one or more
  2867. +** invocations of either insertCell() or dropCell().
  2868. +*/
  2869. +static void relinkCellList(Btree *pBt, MemPage *pPage){
  2870. + int i;
  2871. + u16 *pIdx;
  2872. + assert( sqlitepager_iswriteable(pPage) );
  2873. + pIdx = &pPage->u.hdr.firstCell;
  2874. + for(i=0; i<pPage->nCell; i++){
  2875. + int idx = Addr(pPage->apCell[i]) - Addr(pPage);
  2876. + assert( idx>0 && idx<SQLITE_USABLE_SIZE );
  2877. + *pIdx = SWAB16(pBt, idx);
  2878. + pIdx = &pPage->apCell[i]->h.iNext;
  2879. + }
  2880. + *pIdx = 0;
  2881. +}
  2882. +
  2883. +/*
  2884. +** Make a copy of the contents of pFrom into pTo. The pFrom->apCell[]
  2885. +** pointers that point into pFrom->u.aDisk[] must be adjusted to point
  2886. +** into pTo->u.aDisk[] instead. But some pFrom->apCell[] entries might
  2887. +** not point to pFrom->u.aDisk[]. Those are unchanged.
  2888. +*/
  2889. +static void copyPage(MemPage *pTo, MemPage *pFrom){
  2890. + uptr from, to;
  2891. + int i;
  2892. + memcpy(pTo->u.aDisk, pFrom->u.aDisk, SQLITE_USABLE_SIZE);
  2893. + pTo->pParent = 0;
  2894. + pTo->isInit = 1;
  2895. + pTo->nCell = pFrom->nCell;
  2896. + pTo->nFree = pFrom->nFree;
  2897. + pTo->isOverfull = pFrom->isOverfull;
  2898. + to = Addr(pTo);
  2899. + from = Addr(pFrom);
  2900. + for(i=0; i<pTo->nCell; i++){
  2901. + uptr x = Addr(pFrom->apCell[i]);
  2902. + if( x>from && x<from+SQLITE_USABLE_SIZE ){
  2903. + *((uptr*)&pTo->apCell[i]) = x + to - from;
  2904. + }else{
  2905. + pTo->apCell[i] = pFrom->apCell[i];
  2906. + }
  2907. + }
  2908. +}
  2909. +
  2910. +/*
  2911. +** The following parameters determine how many adjacent pages get involved
  2912. +** in a balancing operation. NN is the number of neighbors on either side
  2913. +** of the page that participate in the balancing operation. NB is the
  2914. +** total number of pages that participate, including the target page and
  2915. +** NN neighbors on either side.
  2916. +**
  2917. +** The minimum value of NN is 1 (of course). Increasing NN above 1
  2918. +** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  2919. +** in exchange for a larger degradation in INSERT and UPDATE performance.
  2920. +** The value of NN appears to give the best results overall.
  2921. +*/
  2922. +#define NN 1 /* Number of neighbors on either side of pPage */
  2923. +#define NB (NN*2+1) /* Total pages involved in the balance */
  2924. +
  2925. +/*
  2926. +** This routine redistributes Cells on pPage and up to two siblings
  2927. +** of pPage so that all pages have about the same amount of free space.
  2928. +** Usually one sibling on either side of pPage is used in the balancing,
  2929. +** though both siblings might come from one side if pPage is the first
  2930. +** or last child of its parent. If pPage has fewer than two siblings
  2931. +** (something which can only happen if pPage is the root page or a
  2932. +** child of root) then all available siblings participate in the balancing.
  2933. +**
  2934. +** The number of siblings of pPage might be increased or decreased by
  2935. +** one in an effort to keep pages between 66% and 100% full. The root page
  2936. +** is special and is allowed to be less than 66% full. If pPage is
  2937. +** the root page, then the depth of the tree might be increased
  2938. +** or decreased by one, as necessary, to keep the root page from being
  2939. +** overfull or empty.
  2940. +**
  2941. +** This routine calls relinkCellList() on its input page regardless of
  2942. +** whether or not it does any real balancing. Client routines will typically
  2943. +** invoke insertCell() or dropCell() before calling this routine, so we
  2944. +** need to call relinkCellList() to clean up the mess that those other
  2945. +** routines left behind.
  2946. +**
  2947. +** pCur is left pointing to the same cell as when this routine was called
  2948. +** even if that cell gets moved to a different page. pCur may be NULL.
  2949. +** Set the pCur parameter to NULL if you do not care about keeping track
  2950. +** of a cell as that will save this routine the work of keeping track of it.
  2951. +**
  2952. +** Note that when this routine is called, some of the Cells on pPage
  2953. +** might not actually be stored in pPage->u.aDisk[]. This can happen
  2954. +** if the page is overfull. Part of the job of this routine is to
  2955. +** make sure all Cells for pPage once again fit in pPage->u.aDisk[].
  2956. +**
  2957. +** In the course of balancing the siblings of pPage, the parent of pPage
  2958. +** might become overfull or underfull. If that happens, then this routine
  2959. +** is called recursively on the parent.
  2960. +**
  2961. +** If this routine fails for any reason, it might leave the database
  2962. +** in a corrupted state. So if this routine fails, the database should
  2963. +** be rolled back.
  2964. +*/
  2965. +static int balance(Btree *pBt, MemPage *pPage, BtCursor *pCur){
  2966. + MemPage *pParent; /* The parent of pPage */
  2967. + int nCell; /* Number of cells in apCell[] */
  2968. + int nOld; /* Number of pages in apOld[] */
  2969. + int nNew; /* Number of pages in apNew[] */
  2970. + int nDiv; /* Number of cells in apDiv[] */
  2971. + int i, j, k; /* Loop counters */
  2972. + int idx; /* Index of pPage in pParent->apCell[] */
  2973. + int nxDiv; /* Next divider slot in pParent->apCell[] */
  2974. + int rc; /* The return code */
  2975. + int iCur; /* apCell[iCur] is the cell of the cursor */
  2976. + MemPage *pOldCurPage; /* The cursor originally points to this page */
  2977. + int subtotal; /* Subtotal of bytes in cells on one page */
  2978. + MemPage *extraUnref = 0; /* A page that needs to be unref-ed */
  2979. + MemPage *apOld[NB]; /* pPage and up to two siblings */
  2980. + Pgno pgnoOld[NB]; /* Page numbers for each page in apOld[] */
  2981. + MemPage *apNew[NB+1]; /* pPage and up to NB siblings after balancing */
  2982. + Pgno pgnoNew[NB+1]; /* Page numbers for each page in apNew[] */
  2983. + int idxDiv[NB]; /* Indices of divider cells in pParent */
  2984. + Cell *apDiv[NB]; /* Divider cells in pParent */
  2985. + Cell aTemp[NB]; /* Temporary holding area for apDiv[] */
  2986. + int cntNew[NB+1]; /* Index in apCell[] of cell after i-th page */
  2987. + int szNew[NB+1]; /* Combined size of cells place on i-th page */
  2988. + MemPage aOld[NB]; /* Temporary copies of pPage and its siblings */
  2989. + Cell *apCell[(MX_CELL+2)*NB]; /* All cells from pages being balanced */
  2990. + int szCell[(MX_CELL+2)*NB]; /* Local size of all cells */
  2991. +
  2992. + /*
  2993. + ** Return without doing any work if pPage is neither overfull nor
  2994. + ** underfull.
  2995. + */
  2996. + assert( sqlitepager_iswriteable(pPage) );
  2997. + if( !pPage->isOverfull && pPage->nFree<SQLITE_USABLE_SIZE/2
  2998. + && pPage->nCell>=2){
  2999. + relinkCellList(pBt, pPage);
  3000. + return SQLITE_OK;
  3001. + }
  3002. +
  3003. + /*
  3004. + ** Find the parent of the page to be balanceed.
  3005. + ** If there is no parent, it means this page is the root page and
  3006. + ** special rules apply.
  3007. + */
  3008. + pParent = pPage->pParent;
  3009. + if( pParent==0 ){
  3010. + Pgno pgnoChild;
  3011. + MemPage *pChild;
  3012. + assert( pPage->isInit );
  3013. + if( pPage->nCell==0 ){
  3014. + if( pPage->u.hdr.rightChild ){
  3015. + /*
  3016. + ** The root page is empty. Copy the one child page
  3017. + ** into the root page and return. This reduces the depth
  3018. + ** of the BTree by one.
  3019. + */
  3020. + pgnoChild = SWAB32(pBt, pPage->u.hdr.rightChild);
  3021. + rc = sqlitepager_get(pBt->pPager, pgnoChild, (void**)&pChild);
  3022. + if( rc ) return rc;
  3023. + memcpy(pPage, pChild, SQLITE_USABLE_SIZE);
  3024. + pPage->isInit = 0;
  3025. + rc = initPage(pBt, pPage, sqlitepager_pagenumber(pPage), 0);
  3026. + assert( rc==SQLITE_OK );
  3027. + reparentChildPages(pBt, pPage);
  3028. + if( pCur && pCur->pPage==pChild ){
  3029. + sqlitepager_unref(pChild);
  3030. + pCur->pPage = pPage;
  3031. + sqlitepager_ref(pPage);
  3032. + }
  3033. + freePage(pBt, pChild, pgnoChild);
  3034. + sqlitepager_unref(pChild);
  3035. + }else{
  3036. + relinkCellList(pBt, pPage);
  3037. + }
  3038. + return SQLITE_OK;
  3039. + }
  3040. + if( !pPage->isOverfull ){
  3041. + /* It is OK for the root page to be less than half full.
  3042. + */
  3043. + relinkCellList(pBt, pPage);
  3044. + return SQLITE_OK;
  3045. + }
  3046. + /*
  3047. + ** If we get to here, it means the root page is overfull.
  3048. + ** When this happens, Create a new child page and copy the
  3049. + ** contents of the root into the child. Then make the root
  3050. + ** page an empty page with rightChild pointing to the new
  3051. + ** child. Then fall thru to the code below which will cause
  3052. + ** the overfull child page to be split.
  3053. + */
  3054. + rc = sqlitepager_write(pPage);
  3055. + if( rc ) return rc;
  3056. + rc = allocatePage(pBt, &pChild, &pgnoChild, sqlitepager_pagenumber(pPage));
  3057. + if( rc ) return rc;
  3058. + assert( sqlitepager_iswriteable(pChild) );
  3059. + copyPage(pChild, pPage);
  3060. + pChild->pParent = pPage;
  3061. + pChild->idxParent = 0;
  3062. + sqlitepager_ref(pPage);
  3063. + pChild->isOverfull = 1;
  3064. + if( pCur && pCur->pPage==pPage ){
  3065. + sqlitepager_unref(pPage);
  3066. + pCur->pPage = pChild;
  3067. + }else{
  3068. + extraUnref = pChild;
  3069. + }
  3070. + zeroPage(pBt, pPage);
  3071. + pPage->u.hdr.rightChild = SWAB32(pBt, pgnoChild);
  3072. + pParent = pPage;
  3073. + pPage = pChild;
  3074. + }
  3075. + rc = sqlitepager_write(pParent);
  3076. + if( rc ) return rc;
  3077. + assert( pParent->isInit );
  3078. +
  3079. + /*
  3080. + ** Find the Cell in the parent page whose h.leftChild points back
  3081. + ** to pPage. The "idx" variable is the index of that cell. If pPage
  3082. + ** is the rightmost child of pParent then set idx to pParent->nCell
  3083. + */
  3084. + if( pParent->idxShift ){
  3085. + Pgno pgno, swabPgno;
  3086. + pgno = sqlitepager_pagenumber(pPage);
  3087. + swabPgno = SWAB32(pBt, pgno);
  3088. + for(idx=0; idx<pParent->nCell; idx++){
  3089. + if( pParent->apCell[idx]->h.leftChild==swabPgno ){
  3090. + break;
  3091. + }
  3092. + }
  3093. + assert( idx<pParent->nCell || pParent->u.hdr.rightChild==swabPgno );
  3094. + }else{
  3095. + idx = pPage->idxParent;
  3096. + }
  3097. +
  3098. + /*
  3099. + ** Initialize variables so that it will be safe to jump
  3100. + ** directly to balance_cleanup at any moment.
  3101. + */
  3102. + nOld = nNew = 0;
  3103. + sqlitepager_ref(pParent);
  3104. +
  3105. + /*
  3106. + ** Find sibling pages to pPage and the Cells in pParent that divide
  3107. + ** the siblings. An attempt is made to find NN siblings on either
  3108. + ** side of pPage. More siblings are taken from one side, however, if
  3109. + ** pPage there are fewer than NN siblings on the other side. If pParent
  3110. + ** has NB or fewer children then all children of pParent are taken.
  3111. + */
  3112. + nxDiv = idx - NN;
  3113. + if( nxDiv + NB > pParent->nCell ){
  3114. + nxDiv = pParent->nCell - NB + 1;
  3115. + }
  3116. + if( nxDiv<0 ){
  3117. + nxDiv = 0;
  3118. + }
  3119. + nDiv = 0;
  3120. + for(i=0, k=nxDiv; i<NB; i++, k++){
  3121. + if( k<pParent->nCell ){
  3122. + idxDiv[i] = k;
  3123. + apDiv[i] = pParent->apCell[k];
  3124. + nDiv++;
  3125. + pgnoOld[i] = SWAB32(pBt, apDiv[i]->h.leftChild);
  3126. + }else if( k==pParent->nCell ){
  3127. + pgnoOld[i] = SWAB32(pBt, pParent->u.hdr.rightChild);
  3128. + }else{
  3129. + break;
  3130. + }
  3131. + rc = sqlitepager_get(pBt->pPager, pgnoOld[i], (void**)&apOld[i]);
  3132. + if( rc ) goto balance_cleanup;
  3133. + rc = initPage(pBt, apOld[i], pgnoOld[i], pParent);
  3134. + if( rc ) goto balance_cleanup;
  3135. + apOld[i]->idxParent = k;
  3136. + nOld++;
  3137. + }
  3138. +
  3139. + /*
  3140. + ** Set iCur to be the index in apCell[] of the cell that the cursor
  3141. + ** is pointing to. We will need this later on in order to keep the
  3142. + ** cursor pointing at the same cell. If pCur points to a page that
  3143. + ** has no involvement with this rebalancing, then set iCur to a large
  3144. + ** number so that the iCur==j tests always fail in the main cell
  3145. + ** distribution loop below.
  3146. + */
  3147. + if( pCur ){
  3148. + iCur = 0;
  3149. + for(i=0; i<nOld; i++){
  3150. + if( pCur->pPage==apOld[i] ){
  3151. + iCur += pCur->idx;
  3152. + break;
  3153. + }
  3154. + iCur += apOld[i]->nCell;
  3155. + if( i<nOld-1 && pCur->pPage==pParent && pCur->idx==idxDiv[i] ){
  3156. + break;
  3157. + }
  3158. + iCur++;
  3159. + }
  3160. + pOldCurPage = pCur->pPage;
  3161. + }
  3162. +
  3163. + /*
  3164. + ** Make copies of the content of pPage and its siblings into aOld[].
  3165. + ** The rest of this function will use data from the copies rather
  3166. + ** that the original pages since the original pages will be in the
  3167. + ** process of being overwritten.
  3168. + */
  3169. + for(i=0; i<nOld; i++){
  3170. + copyPage(&aOld[i], apOld[i]);
  3171. + }
  3172. +
  3173. + /*
  3174. + ** Load pointers to all cells on sibling pages and the divider cells
  3175. + ** into the local apCell[] array. Make copies of the divider cells
  3176. + ** into aTemp[] and remove the the divider Cells from pParent.
  3177. + */
  3178. + nCell = 0;
  3179. + for(i=0; i<nOld; i++){
  3180. + MemPage *pOld = &aOld[i];
  3181. + for(j=0; j<pOld->nCell; j++){
  3182. + apCell[nCell] = pOld->apCell[j];
  3183. + szCell[nCell] = cellSize(pBt, apCell[nCell]);
  3184. + nCell++;
  3185. + }
  3186. + if( i<nOld-1 ){
  3187. + szCell[nCell] = cellSize(pBt, apDiv[i]);
  3188. + memcpy(&aTemp[i], apDiv[i], szCell[nCell]);
  3189. + apCell[nCell] = &aTemp[i];
  3190. + dropCell(pBt, pParent, nxDiv, szCell[nCell]);
  3191. + assert( SWAB32(pBt, apCell[nCell]->h.leftChild)==pgnoOld[i] );
  3192. + apCell[nCell]->h.leftChild = pOld->u.hdr.rightChild;
  3193. + nCell++;
  3194. + }
  3195. + }
  3196. +
  3197. + /*
  3198. + ** Figure out the number of pages needed to hold all nCell cells.
  3199. + ** Store this number in "k". Also compute szNew[] which is the total
  3200. + ** size of all cells on the i-th page and cntNew[] which is the index
  3201. + ** in apCell[] of the cell that divides path i from path i+1.
  3202. + ** cntNew[k] should equal nCell.
  3203. + **
  3204. + ** This little patch of code is critical for keeping the tree
  3205. + ** balanced.
  3206. + */
  3207. + for(subtotal=k=i=0; i<nCell; i++){
  3208. + subtotal += szCell[i];
  3209. + if( subtotal > USABLE_SPACE ){
  3210. + szNew[k] = subtotal - szCell[i];
  3211. + cntNew[k] = i;
  3212. + subtotal = 0;
  3213. + k++;
  3214. + }
  3215. + }
  3216. + szNew[k] = subtotal;
  3217. + cntNew[k] = nCell;
  3218. + k++;
  3219. + for(i=k-1; i>0; i--){
  3220. + while( szNew[i]<USABLE_SPACE/2 ){
  3221. + cntNew[i-1]--;
  3222. + assert( cntNew[i-1]>0 );
  3223. + szNew[i] += szCell[cntNew[i-1]];
  3224. + szNew[i-1] -= szCell[cntNew[i-1]-1];
  3225. + }
  3226. + }
  3227. + assert( cntNew[0]>0 );
  3228. +
  3229. + /*
  3230. + ** Allocate k new pages. Reuse old pages where possible.
  3231. + */
  3232. + for(i=0; i<k; i++){
  3233. + if( i<nOld ){
  3234. + apNew[i] = apOld[i];
  3235. + pgnoNew[i] = pgnoOld[i];
  3236. + apOld[i] = 0;
  3237. + sqlitepager_write(apNew[i]);
  3238. + }else{
  3239. + rc = allocatePage(pBt, &apNew[i], &pgnoNew[i], pgnoNew[i-1]);
  3240. + if( rc ) goto balance_cleanup;
  3241. + }
  3242. + nNew++;
  3243. + zeroPage(pBt, apNew[i]);
  3244. + apNew[i]->isInit = 1;
  3245. + }
  3246. +
  3247. + /* Free any old pages that were not reused as new pages.
  3248. + */
  3249. + while( i<nOld ){
  3250. + rc = freePage(pBt, apOld[i], pgnoOld[i]);
  3251. + if( rc ) goto balance_cleanup;
  3252. + sqlitepager_unref(apOld[i]);
  3253. + apOld[i] = 0;
  3254. + i++;
  3255. + }
  3256. +
  3257. + /*
  3258. + ** Put the new pages in accending order. This helps to
  3259. + ** keep entries in the disk file in order so that a scan
  3260. + ** of the table is a linear scan through the file. That
  3261. + ** in turn helps the operating system to deliver pages
  3262. + ** from the disk more rapidly.
  3263. + **
  3264. + ** An O(n^2) insertion sort algorithm is used, but since
  3265. + ** n is never more than NB (a small constant), that should
  3266. + ** not be a problem.
  3267. + **
  3268. + ** When NB==3, this one optimization makes the database
  3269. + ** about 25% faster for large insertions and deletions.
  3270. + */
  3271. + for(i=0; i<k-1; i++){
  3272. + int minV = pgnoNew[i];
  3273. + int minI = i;
  3274. + for(j=i+1; j<k; j++){
  3275. + if( pgnoNew[j]<(unsigned)minV ){
  3276. + minI = j;
  3277. + minV = pgnoNew[j];
  3278. + }
  3279. + }
  3280. + if( minI>i ){
  3281. + int t;
  3282. + MemPage *pT;
  3283. + t = pgnoNew[i];
  3284. + pT = apNew[i];
  3285. + pgnoNew[i] = pgnoNew[minI];
  3286. + apNew[i] = apNew[minI];
  3287. + pgnoNew[minI] = t;
  3288. + apNew[minI] = pT;
  3289. + }
  3290. + }
  3291. +
  3292. + /*
  3293. + ** Evenly distribute the data in apCell[] across the new pages.
  3294. + ** Insert divider cells into pParent as necessary.
  3295. + */
  3296. + j = 0;
  3297. + for(i=0; i<nNew; i++){
  3298. + MemPage *pNew = apNew[i];
  3299. + while( j<cntNew[i] ){
  3300. + assert( pNew->nFree>=szCell[j] );
  3301. + if( pCur && iCur==j ){ pCur->pPage = pNew; pCur->idx = pNew->nCell; }
  3302. + insertCell(pBt, pNew, pNew->nCell, apCell[j], szCell[j]);
  3303. + j++;
  3304. + }
  3305. + assert( pNew->nCell>0 );
  3306. + assert( !pNew->isOverfull );
  3307. + relinkCellList(pBt, pNew);
  3308. + if( i<nNew-1 && j<nCell ){
  3309. + pNew->u.hdr.rightChild = apCell[j]->h.leftChild;
  3310. + apCell[j]->h.leftChild = SWAB32(pBt, pgnoNew[i]);
  3311. + if( pCur && iCur==j ){ pCur->pPage = pParent; pCur->idx = nxDiv; }
  3312. + insertCell(pBt, pParent, nxDiv, apCell[j], szCell[j]);
  3313. + j++;
  3314. + nxDiv++;
  3315. + }
  3316. + }
  3317. + assert( j==nCell );
  3318. + apNew[nNew-1]->u.hdr.rightChild = aOld[nOld-1].u.hdr.rightChild;
  3319. + if( nxDiv==pParent->nCell ){
  3320. + pParent->u.hdr.rightChild = SWAB32(pBt, pgnoNew[nNew-1]);
  3321. + }else{
  3322. + pParent->apCell[nxDiv]->h.leftChild = SWAB32(pBt, pgnoNew[nNew-1]);
  3323. + }
  3324. + if( pCur ){
  3325. + if( j<=iCur && pCur->pPage==pParent && pCur->idx>idxDiv[nOld-1] ){
  3326. + assert( pCur->pPage==pOldCurPage );
  3327. + pCur->idx += nNew - nOld;
  3328. + }else{
  3329. + assert( pOldCurPage!=0 );
  3330. + sqlitepager_ref(pCur->pPage);
  3331. + sqlitepager_unref(pOldCurPage);
  3332. + }
  3333. + }
  3334. +
  3335. + /*
  3336. + ** Reparent children of all cells.
  3337. + */
  3338. + for(i=0; i<nNew; i++){
  3339. + reparentChildPages(pBt, apNew[i]);
  3340. + }
  3341. + reparentChildPages(pBt, pParent);
  3342. +
  3343. + /*
  3344. + ** balance the parent page.
  3345. + */
  3346. + rc = balance(pBt, pParent, pCur);
  3347. +
  3348. + /*
  3349. + ** Cleanup before returning.
  3350. + */
  3351. +balance_cleanup:
  3352. + if( extraUnref ){
  3353. + sqlitepager_unref(extraUnref);
  3354. + }
  3355. + for(i=0; i<nOld; i++){
  3356. + if( apOld[i]!=0 && apOld[i]!=&aOld[i] ) sqlitepager_unref(apOld[i]);
  3357. + }
  3358. + for(i=0; i<nNew; i++){
  3359. + sqlitepager_unref(apNew[i]);
  3360. + }
  3361. + if( pCur && pCur->pPage==0 ){
  3362. + pCur->pPage = pParent;
  3363. + pCur->idx = 0;
  3364. + }else{
  3365. + sqlitepager_unref(pParent);
  3366. + }
  3367. + return rc;
  3368. +}
  3369. +
  3370. +/*
  3371. +** This routine checks all cursors that point to the same table
  3372. +** as pCur points to. If any of those cursors were opened with
  3373. +** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
  3374. +** cursors point to the same table were opened with wrFlag==1
  3375. +** then this routine returns SQLITE_OK.
  3376. +**
  3377. +** In addition to checking for read-locks (where a read-lock
  3378. +** means a cursor opened with wrFlag==0) this routine also moves
  3379. +** all cursors other than pCur so that they are pointing to the
  3380. +** first Cell on root page. This is necessary because an insert
  3381. +** or delete might change the number of cells on a page or delete
  3382. +** a page entirely and we do not want to leave any cursors
  3383. +** pointing to non-existant pages or cells.
  3384. +*/
  3385. +static int checkReadLocks(BtCursor *pCur){
  3386. + BtCursor *p;
  3387. + assert( pCur->wrFlag );
  3388. + for(p=pCur->pShared; p!=pCur; p=p->pShared){
  3389. + assert( p );
  3390. + assert( p->pgnoRoot==pCur->pgnoRoot );
  3391. + if( p->wrFlag==0 ) return SQLITE_LOCKED;
  3392. + if( sqlitepager_pagenumber(p->pPage)!=p->pgnoRoot ){
  3393. + moveToRoot(p);
  3394. + }
  3395. + }
  3396. + return SQLITE_OK;
  3397. +}
  3398. +
  3399. +/*
  3400. +** Insert a new record into the BTree. The key is given by (pKey,nKey)
  3401. +** and the data is given by (pData,nData). The cursor is used only to
  3402. +** define what database the record should be inserted into. The cursor
  3403. +** is left pointing at the new record.
  3404. +*/
  3405. +static int fileBtreeInsert(
  3406. + BtCursor *pCur, /* Insert data into the table of this cursor */
  3407. + const void *pKey, int nKey, /* The key of the new record */
  3408. + const void *pData, int nData /* The data of the new record */
  3409. +){
  3410. + Cell newCell;
  3411. + int rc;
  3412. + int loc;
  3413. + int szNew;
  3414. + MemPage *pPage;
  3415. + Btree *pBt = pCur->pBt;
  3416. +
  3417. + if( pCur->pPage==0 ){
  3418. + return SQLITE_ABORT; /* A rollback destroyed this cursor */
  3419. + }
  3420. + if( !pBt->inTrans || nKey+nData==0 ){
  3421. + /* Must start a transaction before doing an insert */
  3422. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3423. + }
  3424. + assert( !pBt->readOnly );
  3425. + if( !pCur->wrFlag ){
  3426. + return SQLITE_PERM; /* Cursor not open for writing */
  3427. + }
  3428. + if( checkReadLocks(pCur) ){
  3429. + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  3430. + }
  3431. + rc = fileBtreeMoveto(pCur, pKey, nKey, &loc);
  3432. + if( rc ) return rc;
  3433. + pPage = pCur->pPage;
  3434. + assert( pPage->isInit );
  3435. + rc = sqlitepager_write(pPage);
  3436. + if( rc ) return rc;
  3437. + rc = fillInCell(pBt, &newCell, pKey, nKey, pData, nData);
  3438. + if( rc ) return rc;
  3439. + szNew = cellSize(pBt, &newCell);
  3440. + if( loc==0 ){
  3441. + newCell.h.leftChild = pPage->apCell[pCur->idx]->h.leftChild;
  3442. + rc = clearCell(pBt, pPage->apCell[pCur->idx]);
  3443. + if( rc ) return rc;
  3444. + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pPage->apCell[pCur->idx]));
  3445. + }else if( loc<0 && pPage->nCell>0 ){
  3446. + assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
  3447. + pCur->idx++;
  3448. + }else{
  3449. + assert( pPage->u.hdr.rightChild==0 ); /* Must be a leaf page */
  3450. + }
  3451. + insertCell(pBt, pPage, pCur->idx, &newCell, szNew);
  3452. + rc = balance(pCur->pBt, pPage, pCur);
  3453. + /* sqliteBtreePageDump(pCur->pBt, pCur->pgnoRoot, 1); */
  3454. + /* fflush(stdout); */
  3455. + pCur->eSkip = SKIP_INVALID;
  3456. + return rc;
  3457. +}
  3458. +
  3459. +/*
  3460. +** Delete the entry that the cursor is pointing to.
  3461. +**
  3462. +** The cursor is left pointing at either the next or the previous
  3463. +** entry. If the cursor is left pointing to the next entry, then
  3464. +** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
  3465. +** sqliteBtreeNext() to be a no-op. That way, you can always call
  3466. +** sqliteBtreeNext() after a delete and the cursor will be left
  3467. +** pointing to the first entry after the deleted entry. Similarly,
  3468. +** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
  3469. +** the entry prior to the deleted entry so that a subsequent call to
  3470. +** sqliteBtreePrevious() will always leave the cursor pointing at the
  3471. +** entry immediately before the one that was deleted.
  3472. +*/
  3473. +static int fileBtreeDelete(BtCursor *pCur){
  3474. + MemPage *pPage = pCur->pPage;
  3475. + Cell *pCell;
  3476. + int rc;
  3477. + Pgno pgnoChild;
  3478. + Btree *pBt = pCur->pBt;
  3479. +
  3480. + assert( pPage->isInit );
  3481. + if( pCur->pPage==0 ){
  3482. + return SQLITE_ABORT; /* A rollback destroyed this cursor */
  3483. + }
  3484. + if( !pBt->inTrans ){
  3485. + /* Must start a transaction before doing a delete */
  3486. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3487. + }
  3488. + assert( !pBt->readOnly );
  3489. + if( pCur->idx >= pPage->nCell ){
  3490. + return SQLITE_ERROR; /* The cursor is not pointing to anything */
  3491. + }
  3492. + if( !pCur->wrFlag ){
  3493. + return SQLITE_PERM; /* Did not open this cursor for writing */
  3494. + }
  3495. + if( checkReadLocks(pCur) ){
  3496. + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  3497. + }
  3498. + rc = sqlitepager_write(pPage);
  3499. + if( rc ) return rc;
  3500. + pCell = pPage->apCell[pCur->idx];
  3501. + pgnoChild = SWAB32(pBt, pCell->h.leftChild);
  3502. + clearCell(pBt, pCell);
  3503. + if( pgnoChild ){
  3504. + /*
  3505. + ** The entry we are about to delete is not a leaf so if we do not
  3506. + ** do something we will leave a hole on an internal page.
  3507. + ** We have to fill the hole by moving in a cell from a leaf. The
  3508. + ** next Cell after the one to be deleted is guaranteed to exist and
  3509. + ** to be a leaf so we can use it.
  3510. + */
  3511. + BtCursor leafCur;
  3512. + Cell *pNext;
  3513. + int szNext;
  3514. + int notUsed;
  3515. + getTempCursor(pCur, &leafCur);
  3516. + rc = fileBtreeNext(&leafCur, &notUsed);
  3517. + if( rc!=SQLITE_OK ){
  3518. + if( rc!=SQLITE_NOMEM ) rc = SQLITE_CORRUPT;
  3519. + return rc;
  3520. + }
  3521. + rc = sqlitepager_write(leafCur.pPage);
  3522. + if( rc ) return rc;
  3523. + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
  3524. + pNext = leafCur.pPage->apCell[leafCur.idx];
  3525. + szNext = cellSize(pBt, pNext);
  3526. + pNext->h.leftChild = SWAB32(pBt, pgnoChild);
  3527. + insertCell(pBt, pPage, pCur->idx, pNext, szNext);
  3528. + rc = balance(pBt, pPage, pCur);
  3529. + if( rc ) return rc;
  3530. + pCur->eSkip = SKIP_NEXT;
  3531. + dropCell(pBt, leafCur.pPage, leafCur.idx, szNext);
  3532. + rc = balance(pBt, leafCur.pPage, pCur);
  3533. + releaseTempCursor(&leafCur);
  3534. + }else{
  3535. + dropCell(pBt, pPage, pCur->idx, cellSize(pBt, pCell));
  3536. + if( pCur->idx>=pPage->nCell ){
  3537. + pCur->idx = pPage->nCell-1;
  3538. + if( pCur->idx<0 ){
  3539. + pCur->idx = 0;
  3540. + pCur->eSkip = SKIP_NEXT;
  3541. + }else{
  3542. + pCur->eSkip = SKIP_PREV;
  3543. + }
  3544. + }else{
  3545. + pCur->eSkip = SKIP_NEXT;
  3546. + }
  3547. + rc = balance(pBt, pPage, pCur);
  3548. + }
  3549. + return rc;
  3550. +}
  3551. +
  3552. +/*
  3553. +** Create a new BTree table. Write into *piTable the page
  3554. +** number for the root page of the new table.
  3555. +**
  3556. +** In the current implementation, BTree tables and BTree indices are the
  3557. +** the same. In the future, we may change this so that BTree tables
  3558. +** are restricted to having a 4-byte integer key and arbitrary data and
  3559. +** BTree indices are restricted to having an arbitrary key and no data.
  3560. +** But for now, this routine also serves to create indices.
  3561. +*/
  3562. +static int fileBtreeCreateTable(Btree *pBt, int *piTable){
  3563. + MemPage *pRoot;
  3564. + Pgno pgnoRoot;
  3565. + int rc;
  3566. + if( !pBt->inTrans ){
  3567. + /* Must start a transaction first */
  3568. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3569. + }
  3570. + if( pBt->readOnly ){
  3571. + return SQLITE_READONLY;
  3572. + }
  3573. + rc = allocatePage(pBt, &pRoot, &pgnoRoot, 0);
  3574. + if( rc ) return rc;
  3575. + assert( sqlitepager_iswriteable(pRoot) );
  3576. + zeroPage(pBt, pRoot);
  3577. + sqlitepager_unref(pRoot);
  3578. + *piTable = (int)pgnoRoot;
  3579. + return SQLITE_OK;
  3580. +}
  3581. +
  3582. +/*
  3583. +** Erase the given database page and all its children. Return
  3584. +** the page to the freelist.
  3585. +*/
  3586. +static int clearDatabasePage(Btree *pBt, Pgno pgno, int freePageFlag){
  3587. + MemPage *pPage;
  3588. + int rc;
  3589. + Cell *pCell;
  3590. + int idx;
  3591. +
  3592. + rc = sqlitepager_get(pBt->pPager, pgno, (void**)&pPage);
  3593. + if( rc ) return rc;
  3594. + rc = sqlitepager_write(pPage);
  3595. + if( rc ) return rc;
  3596. + rc = initPage(pBt, pPage, pgno, 0);
  3597. + if( rc ) return rc;
  3598. + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
  3599. + while( idx>0 ){
  3600. + pCell = (Cell*)&pPage->u.aDisk[idx];
  3601. + idx = SWAB16(pBt, pCell->h.iNext);
  3602. + if( pCell->h.leftChild ){
  3603. + rc = clearDatabasePage(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
  3604. + if( rc ) return rc;
  3605. + }
  3606. + rc = clearCell(pBt, pCell);
  3607. + if( rc ) return rc;
  3608. + }
  3609. + if( pPage->u.hdr.rightChild ){
  3610. + rc = clearDatabasePage(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
  3611. + if( rc ) return rc;
  3612. + }
  3613. + if( freePageFlag ){
  3614. + rc = freePage(pBt, pPage, pgno);
  3615. + }else{
  3616. + zeroPage(pBt, pPage);
  3617. + }
  3618. + sqlitepager_unref(pPage);
  3619. + return rc;
  3620. +}
  3621. +
  3622. +/*
  3623. +** Delete all information from a single table in the database.
  3624. +*/
  3625. +static int fileBtreeClearTable(Btree *pBt, int iTable){
  3626. + int rc;
  3627. + BtCursor *pCur;
  3628. + if( !pBt->inTrans ){
  3629. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3630. + }
  3631. + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  3632. + if( pCur->pgnoRoot==(Pgno)iTable ){
  3633. + if( pCur->wrFlag==0 ) return SQLITE_LOCKED;
  3634. + moveToRoot(pCur);
  3635. + }
  3636. + }
  3637. + rc = clearDatabasePage(pBt, (Pgno)iTable, 0);
  3638. + if( rc ){
  3639. + fileBtreeRollback(pBt);
  3640. + }
  3641. + return rc;
  3642. +}
  3643. +
  3644. +/*
  3645. +** Erase all information in a table and add the root of the table to
  3646. +** the freelist. Except, the root of the principle table (the one on
  3647. +** page 2) is never added to the freelist.
  3648. +*/
  3649. +static int fileBtreeDropTable(Btree *pBt, int iTable){
  3650. + int rc;
  3651. + MemPage *pPage;
  3652. + BtCursor *pCur;
  3653. + if( !pBt->inTrans ){
  3654. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3655. + }
  3656. + for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  3657. + if( pCur->pgnoRoot==(Pgno)iTable ){
  3658. + return SQLITE_LOCKED; /* Cannot drop a table that has a cursor */
  3659. + }
  3660. + }
  3661. + rc = sqlitepager_get(pBt->pPager, (Pgno)iTable, (void**)&pPage);
  3662. + if( rc ) return rc;
  3663. + rc = fileBtreeClearTable(pBt, iTable);
  3664. + if( rc ) return rc;
  3665. + if( iTable>2 ){
  3666. + rc = freePage(pBt, pPage, iTable);
  3667. + }else{
  3668. + zeroPage(pBt, pPage);
  3669. + }
  3670. + sqlitepager_unref(pPage);
  3671. + return rc;
  3672. +}
  3673. +
  3674. +#if 0 /* UNTESTED */
  3675. +/*
  3676. +** Copy all cell data from one database file into another.
  3677. +** pages back the freelist.
  3678. +*/
  3679. +static int copyCell(Btree *pBtFrom, BTree *pBtTo, Cell *pCell){
  3680. + Pager *pFromPager = pBtFrom->pPager;
  3681. + OverflowPage *pOvfl;
  3682. + Pgno ovfl, nextOvfl;
  3683. + Pgno *pPrev;
  3684. + int rc = SQLITE_OK;
  3685. + MemPage *pNew, *pPrevPg;
  3686. + Pgno new;
  3687. +
  3688. + if( NKEY(pBtTo, pCell->h) + NDATA(pBtTo, pCell->h) <= MX_LOCAL_PAYLOAD ){
  3689. + return SQLITE_OK;
  3690. + }
  3691. + pPrev = &pCell->ovfl;
  3692. + pPrevPg = 0;
  3693. + ovfl = SWAB32(pBtTo, pCell->ovfl);
  3694. + while( ovfl && rc==SQLITE_OK ){
  3695. + rc = sqlitepager_get(pFromPager, ovfl, (void**)&pOvfl);
  3696. + if( rc ) return rc;
  3697. + nextOvfl = SWAB32(pBtFrom, pOvfl->iNext);
  3698. + rc = allocatePage(pBtTo, &pNew, &new, 0);
  3699. + if( rc==SQLITE_OK ){
  3700. + rc = sqlitepager_write(pNew);
  3701. + if( rc==SQLITE_OK ){
  3702. + memcpy(pNew, pOvfl, SQLITE_USABLE_SIZE);
  3703. + *pPrev = SWAB32(pBtTo, new);
  3704. + if( pPrevPg ){
  3705. + sqlitepager_unref(pPrevPg);
  3706. + }
  3707. + pPrev = &pOvfl->iNext;
  3708. + pPrevPg = pNew;
  3709. + }
  3710. + }
  3711. + sqlitepager_unref(pOvfl);
  3712. + ovfl = nextOvfl;
  3713. + }
  3714. + if( pPrevPg ){
  3715. + sqlitepager_unref(pPrevPg);
  3716. + }
  3717. + return rc;
  3718. +}
  3719. +#endif
  3720. +
  3721. +
  3722. +#if 0 /* UNTESTED */
  3723. +/*
  3724. +** Copy a page of data from one database over to another.
  3725. +*/
  3726. +static int copyDatabasePage(
  3727. + Btree *pBtFrom,
  3728. + Pgno pgnoFrom,
  3729. + Btree *pBtTo,
  3730. + Pgno *pTo
  3731. +){
  3732. + MemPage *pPageFrom, *pPage;
  3733. + Pgno to;
  3734. + int rc;
  3735. + Cell *pCell;
  3736. + int idx;
  3737. +
  3738. + rc = sqlitepager_get(pBtFrom->pPager, pgno, (void**)&pPageFrom);
  3739. + if( rc ) return rc;
  3740. + rc = allocatePage(pBt, &pPage, pTo, 0);
  3741. + if( rc==SQLITE_OK ){
  3742. + rc = sqlitepager_write(pPage);
  3743. + }
  3744. + if( rc==SQLITE_OK ){
  3745. + memcpy(pPage, pPageFrom, SQLITE_USABLE_SIZE);
  3746. + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
  3747. + while( idx>0 ){
  3748. + pCell = (Cell*)&pPage->u.aDisk[idx];
  3749. + idx = SWAB16(pBt, pCell->h.iNext);
  3750. + if( pCell->h.leftChild ){
  3751. + Pgno newChld;
  3752. + rc = copyDatabasePage(pBtFrom, SWAB32(pBtFrom, pCell->h.leftChild),
  3753. + pBtTo, &newChld);
  3754. + if( rc ) return rc;
  3755. + pCell->h.leftChild = SWAB32(pBtFrom, newChld);
  3756. + }
  3757. + rc = copyCell(pBtFrom, pBtTo, pCell);
  3758. + if( rc ) return rc;
  3759. + }
  3760. + if( pPage->u.hdr.rightChild ){
  3761. + Pgno newChld;
  3762. + rc = copyDatabasePage(pBtFrom, SWAB32(pBtFrom, pPage->u.hdr.rightChild),
  3763. + pBtTo, &newChld);
  3764. + if( rc ) return rc;
  3765. + pPage->u.hdr.rightChild = SWAB32(pBtTo, newChild);
  3766. + }
  3767. + }
  3768. + sqlitepager_unref(pPage);
  3769. + return rc;
  3770. +}
  3771. +#endif
  3772. +
  3773. +/*
  3774. +** Read the meta-information out of a database file.
  3775. +*/
  3776. +static int fileBtreeGetMeta(Btree *pBt, int *aMeta){
  3777. + PageOne *pP1;
  3778. + int rc;
  3779. + int i;
  3780. +
  3781. + rc = sqlitepager_get(pBt->pPager, 1, (void**)&pP1);
  3782. + if( rc ) return rc;
  3783. + aMeta[0] = SWAB32(pBt, pP1->nFree);
  3784. + for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
  3785. + aMeta[i+1] = SWAB32(pBt, pP1->aMeta[i]);
  3786. + }
  3787. + sqlitepager_unref(pP1);
  3788. + return SQLITE_OK;
  3789. +}
  3790. +
  3791. +/*
  3792. +** Write meta-information back into the database.
  3793. +*/
  3794. +static int fileBtreeUpdateMeta(Btree *pBt, int *aMeta){
  3795. + PageOne *pP1;
  3796. + int rc, i;
  3797. + if( !pBt->inTrans ){
  3798. + return pBt->readOnly ? SQLITE_READONLY : SQLITE_ERROR;
  3799. + }
  3800. + pP1 = pBt->page1;
  3801. + rc = sqlitepager_write(pP1);
  3802. + if( rc ) return rc;
  3803. + for(i=0; i<sizeof(pP1->aMeta)/sizeof(pP1->aMeta[0]); i++){
  3804. + pP1->aMeta[i] = SWAB32(pBt, aMeta[i+1]);
  3805. + }
  3806. + return SQLITE_OK;
  3807. +}
  3808. +
  3809. +/******************************************************************************
  3810. +** The complete implementation of the BTree subsystem is above this line.
  3811. +** All the code the follows is for testing and troubleshooting the BTree
  3812. +** subsystem. None of the code that follows is used during normal operation.
  3813. +******************************************************************************/
  3814. +
  3815. +/*
  3816. +** Print a disassembly of the given page on standard output. This routine
  3817. +** is used for debugging and testing only.
  3818. +*/
  3819. +#ifdef SQLITE_TEST
  3820. +static int fileBtreePageDump(Btree *pBt, int pgno, int recursive){
  3821. + int rc;
  3822. + MemPage *pPage;
  3823. + int i, j;
  3824. + int nFree;
  3825. + u16 idx;
  3826. + char range[20];
  3827. + unsigned char payload[20];
  3828. + rc = sqlitepager_get(pBt->pPager, (Pgno)pgno, (void**)&pPage);
  3829. + if( rc ){
  3830. + return rc;
  3831. + }
  3832. + if( recursive ) printf("PAGE %d:\n", pgno);
  3833. + i = 0;
  3834. + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
  3835. + while( idx>0 && idx<=SQLITE_USABLE_SIZE-MIN_CELL_SIZE ){
  3836. + Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
  3837. + int sz = cellSize(pBt, pCell);
  3838. + sprintf(range,"%d..%d", idx, idx+sz-1);
  3839. + sz = NKEY(pBt, pCell->h) + NDATA(pBt, pCell->h);
  3840. + if( sz>sizeof(payload)-1 ) sz = sizeof(payload)-1;
  3841. + memcpy(payload, pCell->aPayload, sz);
  3842. + for(j=0; j<sz; j++){
  3843. + if( payload[j]<0x20 || payload[j]>0x7f ) payload[j] = '.';
  3844. + }
  3845. + payload[sz] = 0;
  3846. + printf(
  3847. + "cell %2d: i=%-10s chld=%-4d nk=%-4d nd=%-4d payload=%s\n",
  3848. + i, range, (int)pCell->h.leftChild,
  3849. + NKEY(pBt, pCell->h), NDATA(pBt, pCell->h),
  3850. + payload
  3851. + );
  3852. + if( pPage->isInit && pPage->apCell[i]!=pCell ){
  3853. + printf("**** apCell[%d] does not match on prior entry ****\n", i);
  3854. + }
  3855. + i++;
  3856. + idx = SWAB16(pBt, pCell->h.iNext);
  3857. + }
  3858. + if( idx!=0 ){
  3859. + printf("ERROR: next cell index out of range: %d\n", idx);
  3860. + }
  3861. + printf("right_child: %d\n", SWAB32(pBt, pPage->u.hdr.rightChild));
  3862. + nFree = 0;
  3863. + i = 0;
  3864. + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
  3865. + while( idx>0 && idx<SQLITE_USABLE_SIZE ){
  3866. + FreeBlk *p = (FreeBlk*)&pPage->u.aDisk[idx];
  3867. + sprintf(range,"%d..%d", idx, idx+p->iSize-1);
  3868. + nFree += SWAB16(pBt, p->iSize);
  3869. + printf("freeblock %2d: i=%-10s size=%-4d total=%d\n",
  3870. + i, range, SWAB16(pBt, p->iSize), nFree);
  3871. + idx = SWAB16(pBt, p->iNext);
  3872. + i++;
  3873. + }
  3874. + if( idx!=0 ){
  3875. + printf("ERROR: next freeblock index out of range: %d\n", idx);
  3876. + }
  3877. + if( recursive && pPage->u.hdr.rightChild!=0 ){
  3878. + idx = SWAB16(pBt, pPage->u.hdr.firstCell);
  3879. + while( idx>0 && idx<SQLITE_USABLE_SIZE-MIN_CELL_SIZE ){
  3880. + Cell *pCell = (Cell*)&pPage->u.aDisk[idx];
  3881. + fileBtreePageDump(pBt, SWAB32(pBt, pCell->h.leftChild), 1);
  3882. + idx = SWAB16(pBt, pCell->h.iNext);
  3883. + }
  3884. + fileBtreePageDump(pBt, SWAB32(pBt, pPage->u.hdr.rightChild), 1);
  3885. + }
  3886. + sqlitepager_unref(pPage);
  3887. + return SQLITE_OK;
  3888. +}
  3889. +#endif
  3890. +
  3891. +#ifdef SQLITE_TEST
  3892. +/*
  3893. +** Fill aResult[] with information about the entry and page that the
  3894. +** cursor is pointing to.
  3895. +**
  3896. +** aResult[0] = The page number
  3897. +** aResult[1] = The entry number
  3898. +** aResult[2] = Total number of entries on this page
  3899. +** aResult[3] = Size of this entry
  3900. +** aResult[4] = Number of free bytes on this page
  3901. +** aResult[5] = Number of free blocks on the page
  3902. +** aResult[6] = Page number of the left child of this entry
  3903. +** aResult[7] = Page number of the right child for the whole page
  3904. +**
  3905. +** This routine is used for testing and debugging only.
  3906. +*/
  3907. +static int fileBtreeCursorDump(BtCursor *pCur, int *aResult){
  3908. + int cnt, idx;
  3909. + MemPage *pPage = pCur->pPage;
  3910. + Btree *pBt = pCur->pBt;
  3911. + aResult[0] = sqlitepager_pagenumber(pPage);
  3912. + aResult[1] = pCur->idx;
  3913. + aResult[2] = pPage->nCell;
  3914. + if( pCur->idx>=0 && pCur->idx<pPage->nCell ){
  3915. + aResult[3] = cellSize(pBt, pPage->apCell[pCur->idx]);
  3916. + aResult[6] = SWAB32(pBt, pPage->apCell[pCur->idx]->h.leftChild);
  3917. + }else{
  3918. + aResult[3] = 0;
  3919. + aResult[6] = 0;
  3920. + }
  3921. + aResult[4] = pPage->nFree;
  3922. + cnt = 0;
  3923. + idx = SWAB16(pBt, pPage->u.hdr.firstFree);
  3924. + while( idx>0 && idx<SQLITE_USABLE_SIZE ){
  3925. + cnt++;
  3926. + idx = SWAB16(pBt, ((FreeBlk*)&pPage->u.aDisk[idx])->iNext);
  3927. + }
  3928. + aResult[5] = cnt;
  3929. + aResult[7] = SWAB32(pBt, pPage->u.hdr.rightChild);
  3930. + return SQLITE_OK;
  3931. +}
  3932. +#endif
  3933. +
  3934. +/*
  3935. +** Return the pager associated with a BTree. This routine is used for
  3936. +** testing and debugging only.
  3937. +*/
  3938. +static Pager *fileBtreePager(Btree *pBt){
  3939. + return pBt->pPager;
  3940. +}
  3941. +
  3942. +/*
  3943. +** This structure is passed around through all the sanity checking routines
  3944. +** in order to keep track of some global state information.
  3945. +*/
  3946. +typedef struct IntegrityCk IntegrityCk;
  3947. +struct IntegrityCk {
  3948. + Btree *pBt; /* The tree being checked out */
  3949. + Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  3950. + int nPage; /* Number of pages in the database */
  3951. + int *anRef; /* Number of times each page is referenced */
  3952. + char *zErrMsg; /* An error message. NULL of no errors seen. */
  3953. +};
  3954. +
  3955. +/*
  3956. +** Append a message to the error message string.
  3957. +*/
  3958. +static void checkAppendMsg(IntegrityCk *pCheck, char *zMsg1, char *zMsg2){
  3959. + if( pCheck->zErrMsg ){
  3960. + char *zOld = pCheck->zErrMsg;
  3961. + pCheck->zErrMsg = 0;
  3962. + sqliteSetString(&pCheck->zErrMsg, zOld, "\n", zMsg1, zMsg2, (char*)0);
  3963. + sqliteFree(zOld);
  3964. + }else{
  3965. + sqliteSetString(&pCheck->zErrMsg, zMsg1, zMsg2, (char*)0);
  3966. + }
  3967. +}
  3968. +
  3969. +/*
  3970. +** Add 1 to the reference count for page iPage. If this is the second
  3971. +** reference to the page, add an error message to pCheck->zErrMsg.
  3972. +** Return 1 if there are 2 ore more references to the page and 0 if
  3973. +** if this is the first reference to the page.
  3974. +**
  3975. +** Also check that the page number is in bounds.
  3976. +*/
  3977. +static int checkRef(IntegrityCk *pCheck, int iPage, char *zContext){
  3978. + if( iPage==0 ) return 1;
  3979. + if( iPage>pCheck->nPage || iPage<0 ){
  3980. + char zBuf[100];
  3981. + sprintf(zBuf, "invalid page number %d", iPage);
  3982. + checkAppendMsg(pCheck, zContext, zBuf);
  3983. + return 1;
  3984. + }
  3985. + if( pCheck->anRef[iPage]==1 ){
  3986. + char zBuf[100];
  3987. + sprintf(zBuf, "2nd reference to page %d", iPage);
  3988. + checkAppendMsg(pCheck, zContext, zBuf);
  3989. + return 1;
  3990. + }
  3991. + return (pCheck->anRef[iPage]++)>1;
  3992. +}
  3993. +
  3994. +/*
  3995. +** Check the integrity of the freelist or of an overflow page list.
  3996. +** Verify that the number of pages on the list is N.
  3997. +*/
  3998. +static void checkList(
  3999. + IntegrityCk *pCheck, /* Integrity checking context */
  4000. + int isFreeList, /* True for a freelist. False for overflow page list */
  4001. + int iPage, /* Page number for first page in the list */
  4002. + int N, /* Expected number of pages in the list */
  4003. + char *zContext /* Context for error messages */
  4004. +){
  4005. + int i;
  4006. + char zMsg[100];
  4007. + while( N-- > 0 ){
  4008. + OverflowPage *pOvfl;
  4009. + if( iPage<1 ){
  4010. + sprintf(zMsg, "%d pages missing from overflow list", N+1);
  4011. + checkAppendMsg(pCheck, zContext, zMsg);
  4012. + break;
  4013. + }
  4014. + if( checkRef(pCheck, iPage, zContext) ) break;
  4015. + if( sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pOvfl) ){
  4016. + sprintf(zMsg, "failed to get page %d", iPage);
  4017. + checkAppendMsg(pCheck, zContext, zMsg);
  4018. + break;
  4019. + }
  4020. + if( isFreeList ){
  4021. + FreelistInfo *pInfo = (FreelistInfo*)pOvfl->aPayload;
  4022. + int n = SWAB32(pCheck->pBt, pInfo->nFree);
  4023. + for(i=0; i<n; i++){
  4024. + checkRef(pCheck, SWAB32(pCheck->pBt, pInfo->aFree[i]), zContext);
  4025. + }
  4026. + N -= n;
  4027. + }
  4028. + iPage = SWAB32(pCheck->pBt, pOvfl->iNext);
  4029. + sqlitepager_unref(pOvfl);
  4030. + }
  4031. +}
  4032. +
  4033. +/*
  4034. +** Return negative if zKey1<zKey2.
  4035. +** Return zero if zKey1==zKey2.
  4036. +** Return positive if zKey1>zKey2.
  4037. +*/
  4038. +static int keyCompare(
  4039. + const char *zKey1, int nKey1,
  4040. + const char *zKey2, int nKey2
  4041. +){
  4042. + int min = nKey1>nKey2 ? nKey2 : nKey1;
  4043. + int c = memcmp(zKey1, zKey2, min);
  4044. + if( c==0 ){
  4045. + c = nKey1 - nKey2;
  4046. + }
  4047. + return c;
  4048. +}
  4049. +
  4050. +/*
  4051. +** Do various sanity checks on a single page of a tree. Return
  4052. +** the tree depth. Root pages return 0. Parents of root pages
  4053. +** return 1, and so forth.
  4054. +**
  4055. +** These checks are done:
  4056. +**
  4057. +** 1. Make sure that cells and freeblocks do not overlap
  4058. +** but combine to completely cover the page.
  4059. +** 2. Make sure cell keys are in order.
  4060. +** 3. Make sure no key is less than or equal to zLowerBound.
  4061. +** 4. Make sure no key is greater than or equal to zUpperBound.
  4062. +** 5. Check the integrity of overflow pages.
  4063. +** 6. Recursively call checkTreePage on all children.
  4064. +** 7. Verify that the depth of all children is the same.
  4065. +** 8. Make sure this page is at least 33% full or else it is
  4066. +** the root of the tree.
  4067. +*/
  4068. +static int checkTreePage(
  4069. + IntegrityCk *pCheck, /* Context for the sanity check */
  4070. + int iPage, /* Page number of the page to check */
  4071. + MemPage *pParent, /* Parent page */
  4072. + char *zParentContext, /* Parent context */
  4073. + char *zLowerBound, /* All keys should be greater than this, if not NULL */
  4074. + int nLower, /* Number of characters in zLowerBound */
  4075. + char *zUpperBound, /* All keys should be less than this, if not NULL */
  4076. + int nUpper /* Number of characters in zUpperBound */
  4077. +){
  4078. + MemPage *pPage;
  4079. + int i, rc, depth, d2, pgno;
  4080. + char *zKey1, *zKey2;
  4081. + int nKey1, nKey2;
  4082. + BtCursor cur;
  4083. + Btree *pBt;
  4084. + char zMsg[100];
  4085. + char zContext[100];
  4086. + char hit[SQLITE_USABLE_SIZE];
  4087. +
  4088. + /* Check that the page exists
  4089. + */
  4090. + cur.pBt = pBt = pCheck->pBt;
  4091. + if( iPage==0 ) return 0;
  4092. + if( checkRef(pCheck, iPage, zParentContext) ) return 0;
  4093. + sprintf(zContext, "On tree page %d: ", iPage);
  4094. + if( (rc = sqlitepager_get(pCheck->pPager, (Pgno)iPage, (void**)&pPage))!=0 ){
  4095. + sprintf(zMsg, "unable to get the page. error code=%d", rc);
  4096. + checkAppendMsg(pCheck, zContext, zMsg);
  4097. + return 0;
  4098. + }
  4099. + if( (rc = initPage(pBt, pPage, (Pgno)iPage, pParent))!=0 ){
  4100. + sprintf(zMsg, "initPage() returns error code %d", rc);
  4101. + checkAppendMsg(pCheck, zContext, zMsg);
  4102. + sqlitepager_unref(pPage);
  4103. + return 0;
  4104. + }
  4105. +
  4106. + /* Check out all the cells.
  4107. + */
  4108. + depth = 0;
  4109. + if( zLowerBound ){
  4110. + zKey1 = sqliteMalloc( nLower+1 );
  4111. + memcpy(zKey1, zLowerBound, nLower);
  4112. + zKey1[nLower] = 0;
  4113. + }else{
  4114. + zKey1 = 0;
  4115. + }
  4116. + nKey1 = nLower;
  4117. + cur.pPage = pPage;
  4118. + for(i=0; i<pPage->nCell; i++){
  4119. + Cell *pCell = pPage->apCell[i];
  4120. + int sz;
  4121. +
  4122. + /* Check payload overflow pages
  4123. + */
  4124. + nKey2 = NKEY(pBt, pCell->h);
  4125. + sz = nKey2 + NDATA(pBt, pCell->h);
  4126. + sprintf(zContext, "On page %d cell %d: ", iPage, i);
  4127. + if( sz>MX_LOCAL_PAYLOAD ){
  4128. + int nPage = (sz - MX_LOCAL_PAYLOAD + OVERFLOW_SIZE - 1)/OVERFLOW_SIZE;
  4129. + checkList(pCheck, 0, SWAB32(pBt, pCell->ovfl), nPage, zContext);
  4130. + }
  4131. +
  4132. + /* Check that keys are in the right order
  4133. + */
  4134. + cur.idx = i;
  4135. + zKey2 = sqliteMallocRaw( nKey2+1 );
  4136. + getPayload(&cur, 0, nKey2, zKey2);
  4137. + if( zKey1 && keyCompare(zKey1, nKey1, zKey2, nKey2)>=0 ){
  4138. + checkAppendMsg(pCheck, zContext, "Key is out of order");
  4139. + }
  4140. +
  4141. + /* Check sanity of left child page.
  4142. + */
  4143. + pgno = SWAB32(pBt, pCell->h.leftChild);
  4144. + d2 = checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zKey2,nKey2);
  4145. + if( i>0 && d2!=depth ){
  4146. + checkAppendMsg(pCheck, zContext, "Child page depth differs");
  4147. + }
  4148. + depth = d2;
  4149. + sqliteFree(zKey1);
  4150. + zKey1 = zKey2;
  4151. + nKey1 = nKey2;
  4152. + }
  4153. + pgno = SWAB32(pBt, pPage->u.hdr.rightChild);
  4154. + sprintf(zContext, "On page %d at right child: ", iPage);
  4155. + checkTreePage(pCheck, pgno, pPage, zContext, zKey1,nKey1,zUpperBound,nUpper);
  4156. + sqliteFree(zKey1);
  4157. +
  4158. + /* Check for complete coverage of the page
  4159. + */
  4160. + memset(hit, 0, sizeof(hit));
  4161. + memset(hit, 1, sizeof(PageHdr));
  4162. + for(i=SWAB16(pBt, pPage->u.hdr.firstCell); i>0 && i<SQLITE_USABLE_SIZE; ){
  4163. + Cell *pCell = (Cell*)&pPage->u.aDisk[i];
  4164. + int j;
  4165. + for(j=i+cellSize(pBt, pCell)-1; j>=i; j--) hit[j]++;
  4166. + i = SWAB16(pBt, pCell->h.iNext);
  4167. + }
  4168. + for(i=SWAB16(pBt,pPage->u.hdr.firstFree); i>0 && i<SQLITE_USABLE_SIZE; ){
  4169. + FreeBlk *pFBlk = (FreeBlk*)&pPage->u.aDisk[i];
  4170. + int j;
  4171. + for(j=i+SWAB16(pBt,pFBlk->iSize)-1; j>=i; j--) hit[j]++;
  4172. + i = SWAB16(pBt,pFBlk->iNext);
  4173. + }
  4174. + for(i=0; i<SQLITE_USABLE_SIZE; i++){
  4175. + if( hit[i]==0 ){
  4176. + sprintf(zMsg, "Unused space at byte %d of page %d", i, iPage);
  4177. + checkAppendMsg(pCheck, zMsg, 0);
  4178. + break;
  4179. + }else if( hit[i]>1 ){
  4180. + sprintf(zMsg, "Multiple uses for byte %d of page %d", i, iPage);
  4181. + checkAppendMsg(pCheck, zMsg, 0);
  4182. + break;
  4183. + }
  4184. + }
  4185. +
  4186. + /* Check that free space is kept to a minimum
  4187. + */
  4188. +#if 0
  4189. + if( pParent && pParent->nCell>2 && pPage->nFree>3*SQLITE_USABLE_SIZE/4 ){
  4190. + sprintf(zMsg, "free space (%d) greater than max (%d)", pPage->nFree,
  4191. + SQLITE_USABLE_SIZE/3);
  4192. + checkAppendMsg(pCheck, zContext, zMsg);
  4193. + }
  4194. +#endif
  4195. +
  4196. + sqlitepager_unref(pPage);
  4197. + return depth;
  4198. +}
  4199. +
  4200. +/*
  4201. +** This routine does a complete check of the given BTree file. aRoot[] is
  4202. +** an array of pages numbers were each page number is the root page of
  4203. +** a table. nRoot is the number of entries in aRoot.
  4204. +**
  4205. +** If everything checks out, this routine returns NULL. If something is
  4206. +** amiss, an error message is written into memory obtained from malloc()
  4207. +** and a pointer to that error message is returned. The calling function
  4208. +** is responsible for freeing the error message when it is done.
  4209. +*/
  4210. +char *fileBtreeIntegrityCheck(Btree *pBt, int *aRoot, int nRoot){
  4211. + int i;
  4212. + int nRef;
  4213. + IntegrityCk sCheck;
  4214. +
  4215. + nRef = *sqlitepager_stats(pBt->pPager);
  4216. + if( lockBtree(pBt)!=SQLITE_OK ){
  4217. + return sqliteStrDup("Unable to acquire a read lock on the database");
  4218. + }
  4219. + sCheck.pBt = pBt;
  4220. + sCheck.pPager = pBt->pPager;
  4221. + sCheck.nPage = sqlitepager_pagecount(sCheck.pPager);
  4222. + if( sCheck.nPage==0 ){
  4223. + unlockBtreeIfUnused(pBt);
  4224. + return 0;
  4225. + }
  4226. + sCheck.anRef = sqliteMallocRaw( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
  4227. + sCheck.anRef[1] = 1;
  4228. + for(i=2; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
  4229. + sCheck.zErrMsg = 0;
  4230. +
  4231. + /* Check the integrity of the freelist
  4232. + */
  4233. + checkList(&sCheck, 1, SWAB32(pBt, pBt->page1->freeList),
  4234. + SWAB32(pBt, pBt->page1->nFree), "Main freelist: ");
  4235. +
  4236. + /* Check all the tables.
  4237. + */
  4238. + for(i=0; i<nRoot; i++){
  4239. + if( aRoot[i]==0 ) continue;
  4240. + checkTreePage(&sCheck, aRoot[i], 0, "List of tree roots: ", 0,0,0,0);
  4241. + }
  4242. +
  4243. + /* Make sure every page in the file is referenced
  4244. + */
  4245. + for(i=1; i<=sCheck.nPage; i++){
  4246. + if( sCheck.anRef[i]==0 ){
  4247. + char zBuf[100];
  4248. + sprintf(zBuf, "Page %d is never used", i);
  4249. + checkAppendMsg(&sCheck, zBuf, 0);
  4250. + }
  4251. + }
  4252. +
  4253. + /* Make sure this analysis did not leave any unref() pages
  4254. + */
  4255. + unlockBtreeIfUnused(pBt);
  4256. + if( nRef != *sqlitepager_stats(pBt->pPager) ){
  4257. + char zBuf[100];
  4258. + sprintf(zBuf,
  4259. + "Outstanding page count goes from %d to %d during this analysis",
  4260. + nRef, *sqlitepager_stats(pBt->pPager)
  4261. + );
  4262. + checkAppendMsg(&sCheck, zBuf, 0);
  4263. + }
  4264. +
  4265. + /* Clean up and report errors.
  4266. + */
  4267. + sqliteFree(sCheck.anRef);
  4268. + return sCheck.zErrMsg;
  4269. +}
  4270. +
  4271. +/*
  4272. +** Return the full pathname of the underlying database file.
  4273. +*/
  4274. +static const char *fileBtreeGetFilename(Btree *pBt){
  4275. + assert( pBt->pPager!=0 );
  4276. + return sqlitepager_filename(pBt->pPager);
  4277. +}
  4278. +
  4279. +/*
  4280. +** Copy the complete content of pBtFrom into pBtTo. A transaction
  4281. +** must be active for both files.
  4282. +**
  4283. +** The size of file pBtFrom may be reduced by this operation.
  4284. +** If anything goes wrong, the transaction on pBtFrom is rolled back.
  4285. +*/
  4286. +static int fileBtreeCopyFile(Btree *pBtTo, Btree *pBtFrom){
  4287. + int rc = SQLITE_OK;
  4288. + Pgno i, nPage, nToPage;
  4289. +
  4290. + if( !pBtTo->inTrans || !pBtFrom->inTrans ) return SQLITE_ERROR;
  4291. + if( pBtTo->needSwab!=pBtFrom->needSwab ) return SQLITE_ERROR;
  4292. + if( pBtTo->pCursor ) return SQLITE_BUSY;
  4293. + memcpy(pBtTo->page1, pBtFrom->page1, SQLITE_USABLE_SIZE);
  4294. + rc = sqlitepager_overwrite(pBtTo->pPager, 1, pBtFrom->page1);
  4295. + nToPage = sqlitepager_pagecount(pBtTo->pPager);
  4296. + nPage = sqlitepager_pagecount(pBtFrom->pPager);
  4297. + for(i=2; rc==SQLITE_OK && i<=nPage; i++){
  4298. + void *pPage;
  4299. + rc = sqlitepager_get(pBtFrom->pPager, i, &pPage);
  4300. + if( rc ) break;
  4301. + rc = sqlitepager_overwrite(pBtTo->pPager, i, pPage);
  4302. + if( rc ) break;
  4303. + sqlitepager_unref(pPage);
  4304. + }
  4305. + for(i=nPage+1; rc==SQLITE_OK && i<=nToPage; i++){
  4306. + void *pPage;
  4307. + rc = sqlitepager_get(pBtTo->pPager, i, &pPage);
  4308. + if( rc ) break;
  4309. + rc = sqlitepager_write(pPage);
  4310. + sqlitepager_unref(pPage);
  4311. + sqlitepager_dont_write(pBtTo->pPager, i);
  4312. + }
  4313. + if( !rc && nPage<nToPage ){
  4314. + rc = sqlitepager_truncate(pBtTo->pPager, nPage);
  4315. + }
  4316. + if( rc ){
  4317. + fileBtreeRollback(pBtTo);
  4318. + }
  4319. + return rc;
  4320. +}
  4321. +
  4322. +/*
  4323. +** The following tables contain pointers to all of the interface
  4324. +** routines for this implementation of the B*Tree backend. To
  4325. +** substitute a different implemention of the backend, one has merely
  4326. +** to provide pointers to alternative functions in similar tables.
  4327. +*/
  4328. +static BtOps sqliteBtreeOps = {
  4329. + fileBtreeClose,
  4330. + fileBtreeSetCacheSize,
  4331. + fileBtreeSetSafetyLevel,
  4332. + fileBtreeBeginTrans,
  4333. + fileBtreeCommit,
  4334. + fileBtreeRollback,
  4335. + fileBtreeBeginCkpt,
  4336. + fileBtreeCommitCkpt,
  4337. + fileBtreeRollbackCkpt,
  4338. + fileBtreeCreateTable,
  4339. + fileBtreeCreateTable, /* Really sqliteBtreeCreateIndex() */
  4340. + fileBtreeDropTable,
  4341. + fileBtreeClearTable,
  4342. + fileBtreeCursor,
  4343. + fileBtreeGetMeta,
  4344. + fileBtreeUpdateMeta,
  4345. + fileBtreeIntegrityCheck,
  4346. + fileBtreeGetFilename,
  4347. + fileBtreeCopyFile,
  4348. + fileBtreePager,
  4349. +#ifdef SQLITE_TEST
  4350. + fileBtreePageDump,
  4351. +#endif
  4352. +};
  4353. +static BtCursorOps sqliteBtreeCursorOps = {
  4354. + fileBtreeMoveto,
  4355. + fileBtreeDelete,
  4356. + fileBtreeInsert,
  4357. + fileBtreeFirst,
  4358. + fileBtreeLast,
  4359. + fileBtreeNext,
  4360. + fileBtreePrevious,
  4361. + fileBtreeKeySize,
  4362. + fileBtreeKey,
  4363. + fileBtreeKeyCompare,
  4364. + fileBtreeDataSize,
  4365. + fileBtreeData,
  4366. + fileBtreeCloseCursor,
  4367. +#ifdef SQLITE_TEST
  4368. + fileBtreeCursorDump,
  4369. +#endif
  4370. +};
  4371. --- /dev/null
  4372. +++ b/ext/sqlite/libsqlite/src/btree.h
  4373. @@ -0,0 +1,156 @@
  4374. +/*
  4375. +** 2001 September 15
  4376. +**
  4377. +** The author disclaims copyright to this source code. In place of
  4378. +** a legal notice, here is a blessing:
  4379. +**
  4380. +** May you do good and not evil.
  4381. +** May you find forgiveness for yourself and forgive others.
  4382. +** May you share freely, never taking more than you give.
  4383. +**
  4384. +*************************************************************************
  4385. +** This header file defines the interface that the sqlite B-Tree file
  4386. +** subsystem. See comments in the source code for a detailed description
  4387. +** of what each interface routine does.
  4388. +**
  4389. +** @(#) $Id$
  4390. +*/
  4391. +#ifndef _BTREE_H_
  4392. +#define _BTREE_H_
  4393. +
  4394. +/*
  4395. +** Forward declarations of structure
  4396. +*/
  4397. +typedef struct Btree Btree;
  4398. +typedef struct BtCursor BtCursor;
  4399. +typedef struct BtOps BtOps;
  4400. +typedef struct BtCursorOps BtCursorOps;
  4401. +
  4402. +
  4403. +/*
  4404. +** An instance of the following structure contains pointers to all
  4405. +** methods against an open BTree. Alternative BTree implementations
  4406. +** (examples: file based versus in-memory) can be created by substituting
  4407. +** different methods. Users of the BTree cannot tell the difference.
  4408. +**
  4409. +** In C++ we could do this by defining a virtual base class and then
  4410. +** creating subclasses for each different implementation. But this is
  4411. +** C not C++ so we have to be a little more explicit.
  4412. +*/
  4413. +struct BtOps {
  4414. + int (*Close)(Btree*);
  4415. + int (*SetCacheSize)(Btree*, int);
  4416. + int (*SetSafetyLevel)(Btree*, int);
  4417. + int (*BeginTrans)(Btree*);
  4418. + int (*Commit)(Btree*);
  4419. + int (*Rollback)(Btree*);
  4420. + int (*BeginCkpt)(Btree*);
  4421. + int (*CommitCkpt)(Btree*);
  4422. + int (*RollbackCkpt)(Btree*);
  4423. + int (*CreateTable)(Btree*, int*);
  4424. + int (*CreateIndex)(Btree*, int*);
  4425. + int (*DropTable)(Btree*, int);
  4426. + int (*ClearTable)(Btree*, int);
  4427. + int (*Cursor)(Btree*, int iTable, int wrFlag, BtCursor **ppCur);
  4428. + int (*GetMeta)(Btree*, int*);
  4429. + int (*UpdateMeta)(Btree*, int*);
  4430. + char *(*IntegrityCheck)(Btree*, int*, int);
  4431. + const char *(*GetFilename)(Btree*);
  4432. + int (*Copyfile)(Btree*,Btree*);
  4433. + struct Pager *(*Pager)(Btree*);
  4434. +#ifdef SQLITE_TEST
  4435. + int (*PageDump)(Btree*, int, int);
  4436. +#endif
  4437. +};
  4438. +
  4439. +/*
  4440. +** An instance of this structure defines all of the methods that can
  4441. +** be executed against a cursor.
  4442. +*/
  4443. +struct BtCursorOps {
  4444. + int (*Moveto)(BtCursor*, const void *pKey, int nKey, int *pRes);
  4445. + int (*Delete)(BtCursor*);
  4446. + int (*Insert)(BtCursor*, const void *pKey, int nKey,
  4447. + const void *pData, int nData);
  4448. + int (*First)(BtCursor*, int *pRes);
  4449. + int (*Last)(BtCursor*, int *pRes);
  4450. + int (*Next)(BtCursor*, int *pRes);
  4451. + int (*Previous)(BtCursor*, int *pRes);
  4452. + int (*KeySize)(BtCursor*, int *pSize);
  4453. + int (*Key)(BtCursor*, int offset, int amt, char *zBuf);
  4454. + int (*KeyCompare)(BtCursor*, const void *pKey, int nKey,
  4455. + int nIgnore, int *pRes);
  4456. + int (*DataSize)(BtCursor*, int *pSize);
  4457. + int (*Data)(BtCursor*, int offset, int amt, char *zBuf);
  4458. + int (*CloseCursor)(BtCursor*);
  4459. +#ifdef SQLITE_TEST
  4460. + int (*CursorDump)(BtCursor*, int*);
  4461. +#endif
  4462. +};
  4463. +
  4464. +/*
  4465. +** The number of 4-byte "meta" values contained on the first page of each
  4466. +** database file.
  4467. +*/
  4468. +#define SQLITE_N_BTREE_META 10
  4469. +
  4470. +int sqliteBtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
  4471. +int sqliteRbtreeOpen(const char *zFilename, int mode, int nPg, Btree **ppBtree);
  4472. +
  4473. +#define btOps(pBt) (*((BtOps **)(pBt)))
  4474. +#define btCOps(pCur) (*((BtCursorOps **)(pCur)))
  4475. +
  4476. +#define sqliteBtreeClose(pBt) (btOps(pBt)->Close(pBt))
  4477. +#define sqliteBtreeSetCacheSize(pBt, sz) (btOps(pBt)->SetCacheSize(pBt, sz))
  4478. +#define sqliteBtreeSetSafetyLevel(pBt, sl) (btOps(pBt)->SetSafetyLevel(pBt, sl))
  4479. +#define sqliteBtreeBeginTrans(pBt) (btOps(pBt)->BeginTrans(pBt))
  4480. +#define sqliteBtreeCommit(pBt) (btOps(pBt)->Commit(pBt))
  4481. +#define sqliteBtreeRollback(pBt) (btOps(pBt)->Rollback(pBt))
  4482. +#define sqliteBtreeBeginCkpt(pBt) (btOps(pBt)->BeginCkpt(pBt))
  4483. +#define sqliteBtreeCommitCkpt(pBt) (btOps(pBt)->CommitCkpt(pBt))
  4484. +#define sqliteBtreeRollbackCkpt(pBt) (btOps(pBt)->RollbackCkpt(pBt))
  4485. +#define sqliteBtreeCreateTable(pBt,piTable)\
  4486. + (btOps(pBt)->CreateTable(pBt,piTable))
  4487. +#define sqliteBtreeCreateIndex(pBt, piIndex)\
  4488. + (btOps(pBt)->CreateIndex(pBt, piIndex))
  4489. +#define sqliteBtreeDropTable(pBt, iTable) (btOps(pBt)->DropTable(pBt, iTable))
  4490. +#define sqliteBtreeClearTable(pBt, iTable)\
  4491. + (btOps(pBt)->ClearTable(pBt, iTable))
  4492. +#define sqliteBtreeCursor(pBt, iTable, wrFlag, ppCur)\
  4493. + (btOps(pBt)->Cursor(pBt, iTable, wrFlag, ppCur))
  4494. +#define sqliteBtreeMoveto(pCur, pKey, nKey, pRes)\
  4495. + (btCOps(pCur)->Moveto(pCur, pKey, nKey, pRes))
  4496. +#define sqliteBtreeDelete(pCur) (btCOps(pCur)->Delete(pCur))
  4497. +#define sqliteBtreeInsert(pCur, pKey, nKey, pData, nData) \
  4498. + (btCOps(pCur)->Insert(pCur, pKey, nKey, pData, nData))
  4499. +#define sqliteBtreeFirst(pCur, pRes) (btCOps(pCur)->First(pCur, pRes))
  4500. +#define sqliteBtreeLast(pCur, pRes) (btCOps(pCur)->Last(pCur, pRes))
  4501. +#define sqliteBtreeNext(pCur, pRes) (btCOps(pCur)->Next(pCur, pRes))
  4502. +#define sqliteBtreePrevious(pCur, pRes) (btCOps(pCur)->Previous(pCur, pRes))
  4503. +#define sqliteBtreeKeySize(pCur, pSize) (btCOps(pCur)->KeySize(pCur, pSize) )
  4504. +#define sqliteBtreeKey(pCur, offset, amt, zBuf)\
  4505. + (btCOps(pCur)->Key(pCur, offset, amt, zBuf))
  4506. +#define sqliteBtreeKeyCompare(pCur, pKey, nKey, nIgnore, pRes)\
  4507. + (btCOps(pCur)->KeyCompare(pCur, pKey, nKey, nIgnore, pRes))
  4508. +#define sqliteBtreeDataSize(pCur, pSize) (btCOps(pCur)->DataSize(pCur, pSize))
  4509. +#define sqliteBtreeData(pCur, offset, amt, zBuf)\
  4510. + (btCOps(pCur)->Data(pCur, offset, amt, zBuf))
  4511. +#define sqliteBtreeCloseCursor(pCur) (btCOps(pCur)->CloseCursor(pCur))
  4512. +#define sqliteBtreeGetMeta(pBt, aMeta) (btOps(pBt)->GetMeta(pBt, aMeta))
  4513. +#define sqliteBtreeUpdateMeta(pBt, aMeta) (btOps(pBt)->UpdateMeta(pBt, aMeta))
  4514. +#define sqliteBtreeIntegrityCheck(pBt, aRoot, nRoot)\
  4515. + (btOps(pBt)->IntegrityCheck(pBt, aRoot, nRoot))
  4516. +#define sqliteBtreeGetFilename(pBt) (btOps(pBt)->GetFilename(pBt))
  4517. +#define sqliteBtreeCopyFile(pBt1, pBt2) (btOps(pBt1)->Copyfile(pBt1, pBt2))
  4518. +#define sqliteBtreePager(pBt) (btOps(pBt)->Pager(pBt))
  4519. +
  4520. +#ifdef SQLITE_TEST
  4521. +#define sqliteBtreePageDump(pBt, pgno, recursive)\
  4522. + (btOps(pBt)->PageDump(pBt, pgno, recursive))
  4523. +#define sqliteBtreeCursorDump(pCur, aResult)\
  4524. + (btCOps(pCur)->CursorDump(pCur, aResult))
  4525. +int btree_native_byte_order;
  4526. +#endif /* SQLITE_TEST */
  4527. +
  4528. +
  4529. +#endif /* _BTREE_H_ */
  4530. --- /dev/null
  4531. +++ b/ext/sqlite/libsqlite/src/btree_rb.c
  4532. @@ -0,0 +1,1488 @@
  4533. +/*
  4534. +** 2003 Feb 4
  4535. +**
  4536. +** The author disclaims copyright to this source code. In place of
  4537. +** a legal notice, here is a blessing:
  4538. +**
  4539. +** May you do good and not evil.
  4540. +** May you find forgiveness for yourself and forgive others.
  4541. +** May you share freely, never taking more than you give.
  4542. +**
  4543. +*************************************************************************
  4544. +** $Id$
  4545. +**
  4546. +** This file implements an in-core database using Red-Black balanced
  4547. +** binary trees.
  4548. +**
  4549. +** It was contributed to SQLite by anonymous on 2003-Feb-04 23:24:49 UTC.
  4550. +*/
  4551. +#include "btree.h"
  4552. +#include "sqliteInt.h"
  4553. +#include <assert.h>
  4554. +
  4555. +/*
  4556. +** Omit this whole file if the SQLITE_OMIT_INMEMORYDB macro is
  4557. +** defined. This allows a lot of code to be omitted for installations
  4558. +** that do not need it.
  4559. +*/
  4560. +#ifndef SQLITE_OMIT_INMEMORYDB
  4561. +
  4562. +
  4563. +typedef struct BtRbTree BtRbTree;
  4564. +typedef struct BtRbNode BtRbNode;
  4565. +typedef struct BtRollbackOp BtRollbackOp;
  4566. +typedef struct Rbtree Rbtree;
  4567. +typedef struct RbtCursor RbtCursor;
  4568. +
  4569. +/* Forward declarations */
  4570. +static BtOps sqliteRbtreeOps;
  4571. +static BtCursorOps sqliteRbtreeCursorOps;
  4572. +
  4573. +/*
  4574. + * During each transaction (or checkpoint), a linked-list of
  4575. + * "rollback-operations" is accumulated. If the transaction is rolled back,
  4576. + * then the list of operations must be executed (to restore the database to
  4577. + * it's state before the transaction started). If the transaction is to be
  4578. + * committed, just delete the list.
  4579. + *
  4580. + * Each operation is represented as follows, depending on the value of eOp:
  4581. + *
  4582. + * ROLLBACK_INSERT -> Need to insert (pKey, pData) into table iTab.
  4583. + * ROLLBACK_DELETE -> Need to delete the record (pKey) into table iTab.
  4584. + * ROLLBACK_CREATE -> Need to create table iTab.
  4585. + * ROLLBACK_DROP -> Need to drop table iTab.
  4586. + */
  4587. +struct BtRollbackOp {
  4588. + u8 eOp;
  4589. + int iTab;
  4590. + int nKey;
  4591. + void *pKey;
  4592. + int nData;
  4593. + void *pData;
  4594. + BtRollbackOp *pNext;
  4595. +};
  4596. +
  4597. +/*
  4598. +** Legal values for BtRollbackOp.eOp:
  4599. +*/
  4600. +#define ROLLBACK_INSERT 1 /* Insert a record */
  4601. +#define ROLLBACK_DELETE 2 /* Delete a record */
  4602. +#define ROLLBACK_CREATE 3 /* Create a table */
  4603. +#define ROLLBACK_DROP 4 /* Drop a table */
  4604. +
  4605. +struct Rbtree {
  4606. + BtOps *pOps; /* Function table */
  4607. + int aMetaData[SQLITE_N_BTREE_META];
  4608. +
  4609. + int next_idx; /* next available table index */
  4610. + Hash tblHash; /* All created tables, by index */
  4611. + u8 isAnonymous; /* True if this Rbtree is to be deleted when closed */
  4612. + u8 eTransState; /* State of this Rbtree wrt transactions */
  4613. +
  4614. + BtRollbackOp *pTransRollback;
  4615. + BtRollbackOp *pCheckRollback;
  4616. + BtRollbackOp *pCheckRollbackTail;
  4617. +};
  4618. +
  4619. +/*
  4620. +** Legal values for Rbtree.eTransState.
  4621. +*/
  4622. +#define TRANS_NONE 0 /* No transaction is in progress */
  4623. +#define TRANS_INTRANSACTION 1 /* A transaction is in progress */
  4624. +#define TRANS_INCHECKPOINT 2 /* A checkpoint is in progress */
  4625. +#define TRANS_ROLLBACK 3 /* We are currently rolling back a checkpoint or
  4626. + * transaction. */
  4627. +
  4628. +struct RbtCursor {
  4629. + BtCursorOps *pOps; /* Function table */
  4630. + Rbtree *pRbtree;
  4631. + BtRbTree *pTree;
  4632. + int iTree; /* Index of pTree in pRbtree */
  4633. + BtRbNode *pNode;
  4634. + RbtCursor *pShared; /* List of all cursors on the same Rbtree */
  4635. + u8 eSkip; /* Determines if next step operation is a no-op */
  4636. + u8 wrFlag; /* True if this cursor is open for writing */
  4637. +};
  4638. +
  4639. +/*
  4640. +** Legal values for RbtCursor.eSkip.
  4641. +*/
  4642. +#define SKIP_NONE 0 /* Always step the cursor */
  4643. +#define SKIP_NEXT 1 /* The next sqliteRbtreeNext() is a no-op */
  4644. +#define SKIP_PREV 2 /* The next sqliteRbtreePrevious() is a no-op */
  4645. +#define SKIP_INVALID 3 /* Calls to Next() and Previous() are invalid */
  4646. +
  4647. +struct BtRbTree {
  4648. + RbtCursor *pCursors; /* All cursors pointing to this tree */
  4649. + BtRbNode *pHead; /* Head of the tree, or NULL */
  4650. +};
  4651. +
  4652. +struct BtRbNode {
  4653. + int nKey;
  4654. + void *pKey;
  4655. + int nData;
  4656. + void *pData;
  4657. + u8 isBlack; /* true for a black node, 0 for a red node */
  4658. + BtRbNode *pParent; /* Nodes parent node, NULL for the tree head */
  4659. + BtRbNode *pLeft; /* Nodes left child, or NULL */
  4660. + BtRbNode *pRight; /* Nodes right child, or NULL */
  4661. +
  4662. + int nBlackHeight; /* Only used during the red-black integrity check */
  4663. +};
  4664. +
  4665. +/* Forward declarations */
  4666. +static int memRbtreeMoveto(
  4667. + RbtCursor* pCur,
  4668. + const void *pKey,
  4669. + int nKey,
  4670. + int *pRes
  4671. +);
  4672. +static int memRbtreeClearTable(Rbtree* tree, int n);
  4673. +static int memRbtreeNext(RbtCursor* pCur, int *pRes);
  4674. +static int memRbtreeLast(RbtCursor* pCur, int *pRes);
  4675. +static int memRbtreePrevious(RbtCursor* pCur, int *pRes);
  4676. +
  4677. +
  4678. +/*
  4679. +** This routine checks all cursors that point to the same table
  4680. +** as pCur points to. If any of those cursors were opened with
  4681. +** wrFlag==0 then this routine returns SQLITE_LOCKED. If all
  4682. +** cursors point to the same table were opened with wrFlag==1
  4683. +** then this routine returns SQLITE_OK.
  4684. +**
  4685. +** In addition to checking for read-locks (where a read-lock
  4686. +** means a cursor opened with wrFlag==0) this routine also NULLs
  4687. +** out the pNode field of all other cursors.
  4688. +** This is necessary because an insert
  4689. +** or delete might change erase the node out from under
  4690. +** another cursor.
  4691. +*/
  4692. +static int checkReadLocks(RbtCursor *pCur){
  4693. + RbtCursor *p;
  4694. + assert( pCur->wrFlag );
  4695. + for(p=pCur->pTree->pCursors; p; p=p->pShared){
  4696. + if( p!=pCur ){
  4697. + if( p->wrFlag==0 ) return SQLITE_LOCKED;
  4698. + p->pNode = 0;
  4699. + }
  4700. + }
  4701. + return SQLITE_OK;
  4702. +}
  4703. +
  4704. +/*
  4705. + * The key-compare function for the red-black trees. Returns as follows:
  4706. + *
  4707. + * (key1 < key2) -1
  4708. + * (key1 == key2) 0
  4709. + * (key1 > key2) 1
  4710. + *
  4711. + * Keys are compared using memcmp(). If one key is an exact prefix of the
  4712. + * other, then the shorter key is less than the longer key.
  4713. + */
  4714. +static int key_compare(void const*pKey1, int nKey1, void const*pKey2, int nKey2)
  4715. +{
  4716. + int mcmp = memcmp(pKey1, pKey2, (nKey1 <= nKey2)?nKey1:nKey2);
  4717. + if( mcmp == 0){
  4718. + if( nKey1 == nKey2 ) return 0;
  4719. + return ((nKey1 < nKey2)?-1:1);
  4720. + }
  4721. + return ((mcmp>0)?1:-1);
  4722. +}
  4723. +
  4724. +/*
  4725. + * Perform the LEFT-rotate transformation on node X of tree pTree. This
  4726. + * transform is part of the red-black balancing code.
  4727. + *
  4728. + * | |
  4729. + * X Y
  4730. + * / \ / \
  4731. + * a Y X c
  4732. + * / \ / \
  4733. + * b c a b
  4734. + *
  4735. + * BEFORE AFTER
  4736. + */
  4737. +static void leftRotate(BtRbTree *pTree, BtRbNode *pX)
  4738. +{
  4739. + BtRbNode *pY;
  4740. + BtRbNode *pb;
  4741. + pY = pX->pRight;
  4742. + pb = pY->pLeft;
  4743. +
  4744. + pY->pParent = pX->pParent;
  4745. + if( pX->pParent ){
  4746. + if( pX->pParent->pLeft == pX ) pX->pParent->pLeft = pY;
  4747. + else pX->pParent->pRight = pY;
  4748. + }
  4749. + pY->pLeft = pX;
  4750. + pX->pParent = pY;
  4751. + pX->pRight = pb;
  4752. + if( pb ) pb->pParent = pX;
  4753. + if( pTree->pHead == pX ) pTree->pHead = pY;
  4754. +}
  4755. +
  4756. +/*
  4757. + * Perform the RIGHT-rotate transformation on node X of tree pTree. This
  4758. + * transform is part of the red-black balancing code.
  4759. + *
  4760. + * | |
  4761. + * X Y
  4762. + * / \ / \
  4763. + * Y c a X
  4764. + * / \ / \
  4765. + * a b b c
  4766. + *
  4767. + * BEFORE AFTER
  4768. + */
  4769. +static void rightRotate(BtRbTree *pTree, BtRbNode *pX)
  4770. +{
  4771. + BtRbNode *pY;
  4772. + BtRbNode *pb;
  4773. + pY = pX->pLeft;
  4774. + pb = pY->pRight;
  4775. +
  4776. + pY->pParent = pX->pParent;
  4777. + if( pX->pParent ){
  4778. + if( pX->pParent->pLeft == pX ) pX->pParent->pLeft = pY;
  4779. + else pX->pParent->pRight = pY;
  4780. + }
  4781. + pY->pRight = pX;
  4782. + pX->pParent = pY;
  4783. + pX->pLeft = pb;
  4784. + if( pb ) pb->pParent = pX;
  4785. + if( pTree->pHead == pX ) pTree->pHead = pY;
  4786. +}
  4787. +
  4788. +/*
  4789. + * A string-manipulation helper function for check_redblack_tree(). If (orig ==
  4790. + * NULL) a copy of val is returned. If (orig != NULL) then a copy of the *
  4791. + * concatenation of orig and val is returned. The original orig is deleted
  4792. + * (using sqliteFree()).
  4793. + */
  4794. +static char *append_val(char * orig, char const * val){
  4795. + char *z;
  4796. + if( !orig ){
  4797. + z = sqliteStrDup( val );
  4798. + } else{
  4799. + z = 0;
  4800. + sqliteSetString(&z, orig, val, (char*)0);
  4801. + sqliteFree( orig );
  4802. + }
  4803. + return z;
  4804. +}
  4805. +
  4806. +/*
  4807. + * Append a string representation of the entire node to orig and return it.
  4808. + * This is used to produce debugging information if check_redblack_tree() finds
  4809. + * a problem with a red-black binary tree.
  4810. + */
  4811. +static char *append_node(char * orig, BtRbNode *pNode, int indent)
  4812. +{
  4813. + char buf[128];
  4814. + int i;
  4815. +
  4816. + for( i=0; i<indent; i++ ){
  4817. + orig = append_val(orig, " ");
  4818. + }
  4819. +
  4820. + sprintf(buf, "%p", pNode);
  4821. + orig = append_val(orig, buf);
  4822. +
  4823. + if( pNode ){
  4824. + indent += 3;
  4825. + if( pNode->isBlack ){
  4826. + orig = append_val(orig, " B \n");
  4827. + }else{
  4828. + orig = append_val(orig, " R \n");
  4829. + }
  4830. + orig = append_node( orig, pNode->pLeft, indent );
  4831. + orig = append_node( orig, pNode->pRight, indent );
  4832. + }else{
  4833. + orig = append_val(orig, "\n");
  4834. + }
  4835. + return orig;
  4836. +}
  4837. +
  4838. +/*
  4839. + * Print a representation of a node to stdout. This function is only included
  4840. + * so you can call it from within a debugger if things get really bad. It
  4841. + * is not called from anyplace in the code.
  4842. + */
  4843. +static void print_node(BtRbNode *pNode)
  4844. +{
  4845. + char * str = append_node(0, pNode, 0);
  4846. + printf("%s", str);
  4847. +
  4848. + /* Suppress a warning message about print_node() being unused */
  4849. + (void)print_node;
  4850. +}
  4851. +
  4852. +/*
  4853. + * Check the following properties of the red-black tree:
  4854. + * (1) - If a node is red, both of it's children are black
  4855. + * (2) - Each path from a given node to a leaf (NULL) node passes thru the
  4856. + * same number of black nodes
  4857. + *
  4858. + * If there is a problem, append a description (using append_val() ) to *msg.
  4859. + */
  4860. +static void check_redblack_tree(BtRbTree * tree, char ** msg)
  4861. +{
  4862. + BtRbNode *pNode;
  4863. +
  4864. + /* 0 -> came from parent
  4865. + * 1 -> came from left
  4866. + * 2 -> came from right */
  4867. + int prev_step = 0;
  4868. +
  4869. + pNode = tree->pHead;
  4870. + while( pNode ){
  4871. + switch( prev_step ){
  4872. + case 0:
  4873. + if( pNode->pLeft ){
  4874. + pNode = pNode->pLeft;
  4875. + }else{
  4876. + prev_step = 1;
  4877. + }
  4878. + break;
  4879. + case 1:
  4880. + if( pNode->pRight ){
  4881. + pNode = pNode->pRight;
  4882. + prev_step = 0;
  4883. + }else{
  4884. + prev_step = 2;
  4885. + }
  4886. + break;
  4887. + case 2:
  4888. + /* Check red-black property (1) */
  4889. + if( !pNode->isBlack &&
  4890. + ( (pNode->pLeft && !pNode->pLeft->isBlack) ||
  4891. + (pNode->pRight && !pNode->pRight->isBlack) )
  4892. + ){
  4893. + char buf[128];
  4894. + sprintf(buf, "Red node with red child at %p\n", pNode);
  4895. + *msg = append_val(*msg, buf);
  4896. + *msg = append_node(*msg, tree->pHead, 0);
  4897. + *msg = append_val(*msg, "\n");
  4898. + }
  4899. +
  4900. + /* Check red-black property (2) */
  4901. + {
  4902. + int leftHeight = 0;
  4903. + int rightHeight = 0;
  4904. + if( pNode->pLeft ){
  4905. + leftHeight += pNode->pLeft->nBlackHeight;
  4906. + leftHeight += (pNode->pLeft->isBlack?1:0);
  4907. + }
  4908. + if( pNode->pRight ){
  4909. + rightHeight += pNode->pRight->nBlackHeight;
  4910. + rightHeight += (pNode->pRight->isBlack?1:0);
  4911. + }
  4912. + if( leftHeight != rightHeight ){
  4913. + char buf[128];
  4914. + sprintf(buf, "Different black-heights at %p\n", pNode);
  4915. + *msg = append_val(*msg, buf);
  4916. + *msg = append_node(*msg, tree->pHead, 0);
  4917. + *msg = append_val(*msg, "\n");
  4918. + }
  4919. + pNode->nBlackHeight = leftHeight;
  4920. + }
  4921. +
  4922. + if( pNode->pParent ){
  4923. + if( pNode == pNode->pParent->pLeft ) prev_step = 1;
  4924. + else prev_step = 2;
  4925. + }
  4926. + pNode = pNode->pParent;
  4927. + break;
  4928. + default: assert(0);
  4929. + }
  4930. + }
  4931. +}
  4932. +
  4933. +/*
  4934. + * Node pX has just been inserted into pTree (by code in sqliteRbtreeInsert()).
  4935. + * It is possible that pX is a red node with a red parent, which is a violation
  4936. + * of the red-black tree properties. This function performs rotations and
  4937. + * color changes to rebalance the tree
  4938. + */
  4939. +static void do_insert_balancing(BtRbTree *pTree, BtRbNode *pX)
  4940. +{
  4941. + /* In the first iteration of this loop, pX points to the red node just
  4942. + * inserted in the tree. If the parent of pX exists (pX is not the root
  4943. + * node) and is red, then the properties of the red-black tree are
  4944. + * violated.
  4945. + *
  4946. + * At the start of any subsequent iterations, pX points to a red node
  4947. + * with a red parent. In all other respects the tree is a legal red-black
  4948. + * binary tree. */
  4949. + while( pX != pTree->pHead && !pX->pParent->isBlack ){
  4950. + BtRbNode *pUncle;
  4951. + BtRbNode *pGrandparent;
  4952. +
  4953. + /* Grandparent of pX must exist and must be black. */
  4954. + pGrandparent = pX->pParent->pParent;
  4955. + assert( pGrandparent );
  4956. + assert( pGrandparent->isBlack );
  4957. +
  4958. + /* Uncle of pX may or may not exist. */
  4959. + if( pX->pParent == pGrandparent->pLeft )
  4960. + pUncle = pGrandparent->pRight;
  4961. + else
  4962. + pUncle = pGrandparent->pLeft;
  4963. +
  4964. + /* If the uncle of pX exists and is red, we do the following:
  4965. + * | |
  4966. + * G(b) G(r)
  4967. + * / \ / \
  4968. + * U(r) P(r) U(b) P(b)
  4969. + * \ \
  4970. + * X(r) X(r)
  4971. + *
  4972. + * BEFORE AFTER
  4973. + * pX is then set to G. If the parent of G is red, then the while loop
  4974. + * will run again. */
  4975. + if( pUncle && !pUncle->isBlack ){
  4976. + pGrandparent->isBlack = 0;
  4977. + pUncle->isBlack = 1;
  4978. + pX->pParent->isBlack = 1;
  4979. + pX = pGrandparent;
  4980. + }else{
  4981. +
  4982. + if( pX->pParent == pGrandparent->pLeft ){
  4983. + if( pX == pX->pParent->pRight ){
  4984. + /* If pX is a right-child, do the following transform, essentially
  4985. + * to change pX into a left-child:
  4986. + * | |
  4987. + * G(b) G(b)
  4988. + * / \ / \
  4989. + * P(r) U(b) X(r) U(b)
  4990. + * \ /
  4991. + * X(r) P(r) <-- new X
  4992. + *
  4993. + * BEFORE AFTER
  4994. + */
  4995. + pX = pX->pParent;
  4996. + leftRotate(pTree, pX);
  4997. + }
  4998. +
  4999. + /* Do the following transform, which balances the tree :)
  5000. + * | |
  5001. + * G(b) P(b)
  5002. + * / \ / \
  5003. + * P(r) U(b) X(r) G(r)
  5004. + * / \
  5005. + * X(r) U(b)
  5006. + *
  5007. + * BEFORE AFTER
  5008. + */
  5009. + assert( pGrandparent == pX->pParent->pParent );
  5010. + pGrandparent->isBlack = 0;
  5011. + pX->pParent->isBlack = 1;
  5012. + rightRotate( pTree, pGrandparent );
  5013. +
  5014. + }else{
  5015. + /* This code is symetric to the illustrated case above. */
  5016. + if( pX == pX->pParent->pLeft ){
  5017. + pX = pX->pParent;
  5018. + rightRotate(pTree, pX);
  5019. + }
  5020. + assert( pGrandparent == pX->pParent->pParent );
  5021. + pGrandparent->isBlack = 0;
  5022. + pX->pParent->isBlack = 1;
  5023. + leftRotate( pTree, pGrandparent );
  5024. + }
  5025. + }
  5026. + }
  5027. + pTree->pHead->isBlack = 1;
  5028. +}
  5029. +
  5030. +/*
  5031. + * A child of pParent, which in turn had child pX, has just been removed from
  5032. + * pTree (the figure below depicts the operation, Z is being removed). pParent
  5033. + * or pX, or both may be NULL.
  5034. + * | |
  5035. + * P P
  5036. + * / \ / \
  5037. + * Z X
  5038. + * / \
  5039. + * X nil
  5040. + *
  5041. + * This function is only called if Z was black. In this case the red-black tree
  5042. + * properties have been violated, and pX has an "extra black". This function
  5043. + * performs rotations and color-changes to re-balance the tree.
  5044. + */
  5045. +static
  5046. +void do_delete_balancing(BtRbTree *pTree, BtRbNode *pX, BtRbNode *pParent)
  5047. +{
  5048. + BtRbNode *pSib;
  5049. +
  5050. + /* TODO: Comment this code! */
  5051. + while( pX != pTree->pHead && (!pX || pX->isBlack) ){
  5052. + if( pX == pParent->pLeft ){
  5053. + pSib = pParent->pRight;
  5054. + if( pSib && !(pSib->isBlack) ){
  5055. + pSib->isBlack = 1;
  5056. + pParent->isBlack = 0;
  5057. + leftRotate(pTree, pParent);
  5058. + pSib = pParent->pRight;
  5059. + }
  5060. + if( !pSib ){
  5061. + pX = pParent;
  5062. + }else if(
  5063. + (!pSib->pLeft || pSib->pLeft->isBlack) &&
  5064. + (!pSib->pRight || pSib->pRight->isBlack) ) {
  5065. + pSib->isBlack = 0;
  5066. + pX = pParent;
  5067. + }else{
  5068. + if( (!pSib->pRight || pSib->pRight->isBlack) ){
  5069. + if( pSib->pLeft ) pSib->pLeft->isBlack = 1;
  5070. + pSib->isBlack = 0;
  5071. + rightRotate( pTree, pSib );
  5072. + pSib = pParent->pRight;
  5073. + }
  5074. + pSib->isBlack = pParent->isBlack;
  5075. + pParent->isBlack = 1;
  5076. + if( pSib->pRight ) pSib->pRight->isBlack = 1;
  5077. + leftRotate(pTree, pParent);
  5078. + pX = pTree->pHead;
  5079. + }
  5080. + }else{
  5081. + pSib = pParent->pLeft;
  5082. + if( pSib && !(pSib->isBlack) ){
  5083. + pSib->isBlack = 1;
  5084. + pParent->isBlack = 0;
  5085. + rightRotate(pTree, pParent);
  5086. + pSib = pParent->pLeft;
  5087. + }
  5088. + if( !pSib ){
  5089. + pX = pParent;
  5090. + }else if(
  5091. + (!pSib->pLeft || pSib->pLeft->isBlack) &&
  5092. + (!pSib->pRight || pSib->pRight->isBlack) ){
  5093. + pSib->isBlack = 0;
  5094. + pX = pParent;
  5095. + }else{
  5096. + if( (!pSib->pLeft || pSib->pLeft->isBlack) ){
  5097. + if( pSib->pRight ) pSib->pRight->isBlack = 1;
  5098. + pSib->isBlack = 0;
  5099. + leftRotate( pTree, pSib );
  5100. + pSib = pParent->pLeft;
  5101. + }
  5102. + pSib->isBlack = pParent->isBlack;
  5103. + pParent->isBlack = 1;
  5104. + if( pSib->pLeft ) pSib->pLeft->isBlack = 1;
  5105. + rightRotate(pTree, pParent);
  5106. + pX = pTree->pHead;
  5107. + }
  5108. + }
  5109. + pParent = pX->pParent;
  5110. + }
  5111. + if( pX ) pX->isBlack = 1;
  5112. +}
  5113. +
  5114. +/*
  5115. + * Create table n in tree pRbtree. Table n must not exist.
  5116. + */
  5117. +static void btreeCreateTable(Rbtree* pRbtree, int n)
  5118. +{
  5119. + BtRbTree *pNewTbl = sqliteMalloc(sizeof(BtRbTree));
  5120. + sqliteHashInsert(&pRbtree->tblHash, 0, n, pNewTbl);
  5121. +}
  5122. +
  5123. +/*
  5124. + * Log a single "rollback-op" for the given Rbtree. See comments for struct
  5125. + * BtRollbackOp.
  5126. + */
  5127. +static void btreeLogRollbackOp(Rbtree* pRbtree, BtRollbackOp *pRollbackOp)
  5128. +{
  5129. + assert( pRbtree->eTransState == TRANS_INCHECKPOINT ||
  5130. + pRbtree->eTransState == TRANS_INTRANSACTION );
  5131. + if( pRbtree->eTransState == TRANS_INTRANSACTION ){
  5132. + pRollbackOp->pNext = pRbtree->pTransRollback;
  5133. + pRbtree->pTransRollback = pRollbackOp;
  5134. + }
  5135. + if( pRbtree->eTransState == TRANS_INCHECKPOINT ){
  5136. + if( !pRbtree->pCheckRollback ){
  5137. + pRbtree->pCheckRollbackTail = pRollbackOp;
  5138. + }
  5139. + pRollbackOp->pNext = pRbtree->pCheckRollback;
  5140. + pRbtree->pCheckRollback = pRollbackOp;
  5141. + }
  5142. +}
  5143. +
  5144. +int sqliteRbtreeOpen(
  5145. + const char *zFilename,
  5146. + int mode,
  5147. + int nPg,
  5148. + Btree **ppBtree
  5149. +){
  5150. + Rbtree **ppRbtree = (Rbtree**)ppBtree;
  5151. + *ppRbtree = (Rbtree *)sqliteMalloc(sizeof(Rbtree));
  5152. + if( sqlite_malloc_failed ) goto open_no_mem;
  5153. + sqliteHashInit(&(*ppRbtree)->tblHash, SQLITE_HASH_INT, 0);
  5154. +
  5155. + /* Create a binary tree for the SQLITE_MASTER table at location 2 */
  5156. + btreeCreateTable(*ppRbtree, 2);
  5157. + if( sqlite_malloc_failed ) goto open_no_mem;
  5158. + (*ppRbtree)->next_idx = 3;
  5159. + (*ppRbtree)->pOps = &sqliteRbtreeOps;
  5160. + /* Set file type to 4; this is so that "attach ':memory:' as ...." does not
  5161. + ** think that the database in uninitialised and refuse to attach
  5162. + */
  5163. + (*ppRbtree)->aMetaData[2] = 4;
  5164. +
  5165. + return SQLITE_OK;
  5166. +
  5167. +open_no_mem:
  5168. + *ppBtree = 0;
  5169. + return SQLITE_NOMEM;
  5170. +}
  5171. +
  5172. +/*
  5173. + * Create a new table in the supplied Rbtree. Set *n to the new table number.
  5174. + * Return SQLITE_OK if the operation is a success.
  5175. + */
  5176. +static int memRbtreeCreateTable(Rbtree* tree, int* n)
  5177. +{
  5178. + assert( tree->eTransState != TRANS_NONE );
  5179. +
  5180. + *n = tree->next_idx++;
  5181. + btreeCreateTable(tree, *n);
  5182. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5183. +
  5184. + /* Set up the rollback structure (if we are not doing this as part of a
  5185. + * rollback) */
  5186. + if( tree->eTransState != TRANS_ROLLBACK ){
  5187. + BtRollbackOp *pRollbackOp = sqliteMalloc(sizeof(BtRollbackOp));
  5188. + if( pRollbackOp==0 ) return SQLITE_NOMEM;
  5189. + pRollbackOp->eOp = ROLLBACK_DROP;
  5190. + pRollbackOp->iTab = *n;
  5191. + btreeLogRollbackOp(tree, pRollbackOp);
  5192. + }
  5193. +
  5194. + return SQLITE_OK;
  5195. +}
  5196. +
  5197. +/*
  5198. + * Delete table n from the supplied Rbtree.
  5199. + */
  5200. +static int memRbtreeDropTable(Rbtree* tree, int n)
  5201. +{
  5202. + BtRbTree *pTree;
  5203. + assert( tree->eTransState != TRANS_NONE );
  5204. +
  5205. + memRbtreeClearTable(tree, n);
  5206. + pTree = sqliteHashInsert(&tree->tblHash, 0, n, 0);
  5207. + assert(pTree);
  5208. + assert( pTree->pCursors==0 );
  5209. + sqliteFree(pTree);
  5210. +
  5211. + if( tree->eTransState != TRANS_ROLLBACK ){
  5212. + BtRollbackOp *pRollbackOp = sqliteMalloc(sizeof(BtRollbackOp));
  5213. + if( pRollbackOp==0 ) return SQLITE_NOMEM;
  5214. + pRollbackOp->eOp = ROLLBACK_CREATE;
  5215. + pRollbackOp->iTab = n;
  5216. + btreeLogRollbackOp(tree, pRollbackOp);
  5217. + }
  5218. +
  5219. + return SQLITE_OK;
  5220. +}
  5221. +
  5222. +static int memRbtreeKeyCompare(RbtCursor* pCur, const void *pKey, int nKey,
  5223. + int nIgnore, int *pRes)
  5224. +{
  5225. + assert(pCur);
  5226. +
  5227. + if( !pCur->pNode ) {
  5228. + *pRes = -1;
  5229. + } else {
  5230. + if( (pCur->pNode->nKey - nIgnore) < 0 ){
  5231. + *pRes = -1;
  5232. + }else{
  5233. + *pRes = key_compare(pCur->pNode->pKey, pCur->pNode->nKey-nIgnore,
  5234. + pKey, nKey);
  5235. + }
  5236. + }
  5237. + return SQLITE_OK;
  5238. +}
  5239. +
  5240. +/*
  5241. + * Get a new cursor for table iTable of the supplied Rbtree. The wrFlag
  5242. + * parameter indicates that the cursor is open for writing.
  5243. + *
  5244. + * Note that RbtCursor.eSkip and RbtCursor.pNode both initialize to 0.
  5245. + */
  5246. +static int memRbtreeCursor(
  5247. + Rbtree* tree,
  5248. + int iTable,
  5249. + int wrFlag,
  5250. + RbtCursor **ppCur
  5251. +){
  5252. + RbtCursor *pCur;
  5253. + assert(tree);
  5254. + pCur = *ppCur = sqliteMalloc(sizeof(RbtCursor));
  5255. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5256. + pCur->pTree = sqliteHashFind(&tree->tblHash, 0, iTable);
  5257. + assert( pCur->pTree );
  5258. + pCur->pRbtree = tree;
  5259. + pCur->iTree = iTable;
  5260. + pCur->pOps = &sqliteRbtreeCursorOps;
  5261. + pCur->wrFlag = wrFlag;
  5262. + pCur->pShared = pCur->pTree->pCursors;
  5263. + pCur->pTree->pCursors = pCur;
  5264. +
  5265. + assert( (*ppCur)->pTree );
  5266. + return SQLITE_OK;
  5267. +}
  5268. +
  5269. +/*
  5270. + * Insert a new record into the Rbtree. The key is given by (pKey,nKey)
  5271. + * and the data is given by (pData,nData). The cursor is used only to
  5272. + * define what database the record should be inserted into. The cursor
  5273. + * is left pointing at the new record.
  5274. + *
  5275. + * If the key exists already in the tree, just replace the data.
  5276. + */
  5277. +static int memRbtreeInsert(
  5278. + RbtCursor* pCur,
  5279. + const void *pKey,
  5280. + int nKey,
  5281. + const void *pDataInput,
  5282. + int nData
  5283. +){
  5284. + void * pData;
  5285. + int match;
  5286. +
  5287. + /* It is illegal to call sqliteRbtreeInsert() if we are
  5288. + ** not in a transaction */
  5289. + assert( pCur->pRbtree->eTransState != TRANS_NONE );
  5290. +
  5291. + /* Make sure some other cursor isn't trying to read this same table */
  5292. + if( checkReadLocks(pCur) ){
  5293. + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  5294. + }
  5295. +
  5296. + /* Take a copy of the input data now, in case we need it for the
  5297. + * replace case */
  5298. + pData = sqliteMallocRaw(nData);
  5299. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5300. + memcpy(pData, pDataInput, nData);
  5301. +
  5302. + /* Move the cursor to a node near the key to be inserted. If the key already
  5303. + * exists in the table, then (match == 0). In this case we can just replace
  5304. + * the data associated with the entry, we don't need to manipulate the tree.
  5305. + *
  5306. + * If there is no exact match, then the cursor points at what would be either
  5307. + * the predecessor (match == -1) or successor (match == 1) of the
  5308. + * searched-for key, were it to be inserted. The new node becomes a child of
  5309. + * this node.
  5310. + *
  5311. + * The new node is initially red.
  5312. + */
  5313. + memRbtreeMoveto( pCur, pKey, nKey, &match);
  5314. + if( match ){
  5315. + BtRbNode *pNode = sqliteMalloc(sizeof(BtRbNode));
  5316. + if( pNode==0 ) return SQLITE_NOMEM;
  5317. + pNode->nKey = nKey;
  5318. + pNode->pKey = sqliteMallocRaw(nKey);
  5319. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5320. + memcpy(pNode->pKey, pKey, nKey);
  5321. + pNode->nData = nData;
  5322. + pNode->pData = pData;
  5323. + if( pCur->pNode ){
  5324. + switch( match ){
  5325. + case -1:
  5326. + assert( !pCur->pNode->pRight );
  5327. + pNode->pParent = pCur->pNode;
  5328. + pCur->pNode->pRight = pNode;
  5329. + break;
  5330. + case 1:
  5331. + assert( !pCur->pNode->pLeft );
  5332. + pNode->pParent = pCur->pNode;
  5333. + pCur->pNode->pLeft = pNode;
  5334. + break;
  5335. + default:
  5336. + assert(0);
  5337. + }
  5338. + }else{
  5339. + pCur->pTree->pHead = pNode;
  5340. + }
  5341. +
  5342. + /* Point the cursor at the node just inserted, as per SQLite requirements */
  5343. + pCur->pNode = pNode;
  5344. +
  5345. + /* A new node has just been inserted, so run the balancing code */
  5346. + do_insert_balancing(pCur->pTree, pNode);
  5347. +
  5348. + /* Set up a rollback-op in case we have to roll this operation back */
  5349. + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
  5350. + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
  5351. + if( pOp==0 ) return SQLITE_NOMEM;
  5352. + pOp->eOp = ROLLBACK_DELETE;
  5353. + pOp->iTab = pCur->iTree;
  5354. + pOp->nKey = pNode->nKey;
  5355. + pOp->pKey = sqliteMallocRaw( pOp->nKey );
  5356. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5357. + memcpy( pOp->pKey, pNode->pKey, pOp->nKey );
  5358. + btreeLogRollbackOp(pCur->pRbtree, pOp);
  5359. + }
  5360. +
  5361. + }else{
  5362. + /* No need to insert a new node in the tree, as the key already exists.
  5363. + * Just clobber the current nodes data. */
  5364. +
  5365. + /* Set up a rollback-op in case we have to roll this operation back */
  5366. + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
  5367. + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
  5368. + if( pOp==0 ) return SQLITE_NOMEM;
  5369. + pOp->iTab = pCur->iTree;
  5370. + pOp->nKey = pCur->pNode->nKey;
  5371. + pOp->pKey = sqliteMallocRaw( pOp->nKey );
  5372. + if( sqlite_malloc_failed ) return SQLITE_NOMEM;
  5373. + memcpy( pOp->pKey, pCur->pNode->pKey, pOp->nKey );
  5374. + pOp->nData = pCur->pNode->nData;
  5375. + pOp->pData = pCur->pNode->pData;
  5376. + pOp->eOp = ROLLBACK_INSERT;
  5377. + btreeLogRollbackOp(pCur->pRbtree, pOp);
  5378. + }else{
  5379. + sqliteFree( pCur->pNode->pData );
  5380. + }
  5381. +
  5382. + /* Actually clobber the nodes data */
  5383. + pCur->pNode->pData = pData;
  5384. + pCur->pNode->nData = nData;
  5385. + }
  5386. +
  5387. + return SQLITE_OK;
  5388. +}
  5389. +
  5390. +/* Move the cursor so that it points to an entry near pKey.
  5391. +** Return a success code.
  5392. +**
  5393. +** *pRes<0 The cursor is left pointing at an entry that
  5394. +** is smaller than pKey or if the table is empty
  5395. +** and the cursor is therefore left point to nothing.
  5396. +**
  5397. +** *pRes==0 The cursor is left pointing at an entry that
  5398. +** exactly matches pKey.
  5399. +**
  5400. +** *pRes>0 The cursor is left pointing at an entry that
  5401. +** is larger than pKey.
  5402. +*/
  5403. +static int memRbtreeMoveto(
  5404. + RbtCursor* pCur,
  5405. + const void *pKey,
  5406. + int nKey,
  5407. + int *pRes
  5408. +){
  5409. + BtRbNode *pTmp = 0;
  5410. +
  5411. + pCur->pNode = pCur->pTree->pHead;
  5412. + *pRes = -1;
  5413. + while( pCur->pNode && *pRes ) {
  5414. + *pRes = key_compare(pCur->pNode->pKey, pCur->pNode->nKey, pKey, nKey);
  5415. + pTmp = pCur->pNode;
  5416. + switch( *pRes ){
  5417. + case 1: /* cursor > key */
  5418. + pCur->pNode = pCur->pNode->pLeft;
  5419. + break;
  5420. + case -1: /* cursor < key */
  5421. + pCur->pNode = pCur->pNode->pRight;
  5422. + break;
  5423. + }
  5424. + }
  5425. +
  5426. + /* If (pCur->pNode == NULL), then we have failed to find a match. Set
  5427. + * pCur->pNode to pTmp, which is either NULL (if the tree is empty) or the
  5428. + * last node traversed in the search. In either case the relation ship
  5429. + * between pTmp and the searched for key is already stored in *pRes. pTmp is
  5430. + * either the successor or predecessor of the key we tried to move to. */
  5431. + if( !pCur->pNode ) pCur->pNode = pTmp;
  5432. + pCur->eSkip = SKIP_NONE;
  5433. +
  5434. + return SQLITE_OK;
  5435. +}
  5436. +
  5437. +
  5438. +/*
  5439. +** Delete the entry that the cursor is pointing to.
  5440. +**
  5441. +** The cursor is left pointing at either the next or the previous
  5442. +** entry. If the cursor is left pointing to the next entry, then
  5443. +** the pCur->eSkip flag is set to SKIP_NEXT which forces the next call to
  5444. +** sqliteRbtreeNext() to be a no-op. That way, you can always call
  5445. +** sqliteRbtreeNext() after a delete and the cursor will be left
  5446. +** pointing to the first entry after the deleted entry. Similarly,
  5447. +** pCur->eSkip is set to SKIP_PREV is the cursor is left pointing to
  5448. +** the entry prior to the deleted entry so that a subsequent call to
  5449. +** sqliteRbtreePrevious() will always leave the cursor pointing at the
  5450. +** entry immediately before the one that was deleted.
  5451. +*/
  5452. +static int memRbtreeDelete(RbtCursor* pCur)
  5453. +{
  5454. + BtRbNode *pZ; /* The one being deleted */
  5455. + BtRbNode *pChild; /* The child of the spliced out node */
  5456. +
  5457. + /* It is illegal to call sqliteRbtreeDelete() if we are
  5458. + ** not in a transaction */
  5459. + assert( pCur->pRbtree->eTransState != TRANS_NONE );
  5460. +
  5461. + /* Make sure some other cursor isn't trying to read this same table */
  5462. + if( checkReadLocks(pCur) ){
  5463. + return SQLITE_LOCKED; /* The table pCur points to has a read lock */
  5464. + }
  5465. +
  5466. + pZ = pCur->pNode;
  5467. + if( !pZ ){
  5468. + return SQLITE_OK;
  5469. + }
  5470. +
  5471. + /* If we are not currently doing a rollback, set up a rollback op for this
  5472. + * deletion */
  5473. + if( pCur->pRbtree->eTransState != TRANS_ROLLBACK ){
  5474. + BtRollbackOp *pOp = sqliteMalloc( sizeof(BtRollbackOp) );
  5475. + if( pOp==0 ) return SQLITE_NOMEM;
  5476. + pOp->iTab = pCur->iTree;
  5477. + pOp->nKey = pZ->nKey;
  5478. + pOp->pKey = pZ->pKey;
  5479. + pOp->nData = pZ->nData;
  5480. + pOp->pData = pZ->pData;
  5481. + pOp->eOp = ROLLBACK_INSERT;
  5482. + btreeLogRollbackOp(pCur->pRbtree, pOp);
  5483. + }
  5484. +
  5485. + /* First do a standard binary-tree delete (node pZ is to be deleted). How
  5486. + * to do this depends on how many children pZ has:
  5487. + *
  5488. + * If pZ has no children or one child, then splice out pZ. If pZ has two
  5489. + * children, splice out the successor of pZ and replace the key and data of
  5490. + * pZ with the key and data of the spliced out successor. */
  5491. + if( pZ->pLeft && pZ->pRight ){
  5492. + BtRbNode *pTmp;
  5493. + int dummy;
  5494. + pCur->eSkip = SKIP_NONE;
  5495. + memRbtreeNext(pCur, &dummy);
  5496. + assert( dummy == 0 );
  5497. + if( pCur->pRbtree->eTransState == TRANS_ROLLBACK ){
  5498. + sqliteFree(pZ->pKey);
  5499. + sqliteFree(pZ->pData);
  5500. + }
  5501. + pZ->pData = pCur->pNode->pData;
  5502. + pZ->nData = pCur->pNode->nData;
  5503. + pZ->pKey = pCur->pNode->pKey;
  5504. + pZ->nKey = pCur->pNode->nKey;
  5505. + pTmp = pZ;
  5506. + pZ = pCur->pNode;
  5507. + pCur->pNode = pTmp;
  5508. + pCur->eSkip = SKIP_NEXT;
  5509. + }else{
  5510. + int res;
  5511. + pCur->eSkip = SKIP_NONE;
  5512. + memRbtreeNext(pCur, &res);
  5513. + pCur->eSkip = SKIP_NEXT;
  5514. + if( res ){
  5515. + memRbtreeLast(pCur, &res);
  5516. + memRbtreePrevious(pCur, &res);
  5517. + pCur->eSkip = SKIP_PREV;
  5518. + }
  5519. + if( pCur->pRbtree->eTransState == TRANS_ROLLBACK ){
  5520. + sqliteFree(pZ->pKey);
  5521. + sqliteFree(pZ->pData);
  5522. + }
  5523. + }
  5524. +
  5525. + /* pZ now points at the node to be spliced out. This block does the
  5526. + * splicing. */
  5527. + {
  5528. + BtRbNode **ppParentSlot = 0;
  5529. + assert( !pZ->pLeft || !pZ->pRight ); /* pZ has at most one child */
  5530. + pChild = ((pZ->pLeft)?pZ->pLeft:pZ->pRight);
  5531. + if( pZ->pParent ){
  5532. + assert( pZ == pZ->pParent->pLeft || pZ == pZ->pParent->pRight );
  5533. + ppParentSlot = ((pZ == pZ->pParent->pLeft)
  5534. + ?&pZ->pParent->pLeft:&pZ->pParent->pRight);
  5535. + *ppParentSlot = pChild;
  5536. + }else{
  5537. + pCur->pTree->pHead = pChild;
  5538. + }
  5539. + if( pChild ) pChild->pParent = pZ->pParent;
  5540. + }
  5541. +
  5542. + /* pZ now points at the spliced out node. pChild is the only child of pZ, or
  5543. + * NULL if pZ has no children. If pZ is black, and not the tree root, then we
  5544. + * will have violated the "same number of black nodes in every path to a
  5545. + * leaf" property of the red-black tree. The code in do_delete_balancing()
  5546. + * repairs this. */
  5547. + if( pZ->isBlack ){
  5548. + do_delete_balancing(pCur->pTree, pChild, pZ->pParent);
  5549. + }
  5550. +
  5551. + sqliteFree(pZ);
  5552. + return SQLITE_OK;
  5553. +}
  5554. +
  5555. +/*
  5556. + * Empty table n of the Rbtree.
  5557. + */
  5558. +static int memRbtreeClearTable(Rbtree* tree, int n)
  5559. +{
  5560. + BtRbTree *pTree;
  5561. + BtRbNode *pNode;
  5562. +
  5563. + pTree = sqliteHashFind(&tree->tblHash, 0, n);
  5564. + assert(pTree);
  5565. +
  5566. + pNode = pTree->pHead;
  5567. + while( pNode ){
  5568. + if( pNode->pLeft ){
  5569. + pNode = pNode->pLeft;
  5570. + }
  5571. + else if( pNode->pRight ){
  5572. + pNode = pNode->pRight;
  5573. + }
  5574. + else {
  5575. + BtRbNode *pTmp = pNode->pParent;
  5576. + if( tree->eTransState == TRANS_ROLLBACK ){
  5577. + sqliteFree( pNode->pKey );
  5578. + sqliteFree( pNode->pData );
  5579. + }else{
  5580. + BtRollbackOp *pRollbackOp = sqliteMallocRaw(sizeof(BtRollbackOp));
  5581. + if( pRollbackOp==0 ) return SQLITE_NOMEM;
  5582. + pRollbackOp->eOp = ROLLBACK_INSERT;
  5583. + pRollbackOp->iTab = n;
  5584. + pRollbackOp->nKey = pNode->nKey;
  5585. + pRollbackOp->pKey = pNode->pKey;
  5586. + pRollbackOp->nData = pNode->nData;
  5587. + pRollbackOp->pData = pNode->pData;
  5588. + btreeLogRollbackOp(tree, pRollbackOp);
  5589. + }
  5590. + sqliteFree( pNode );
  5591. + if( pTmp ){
  5592. + if( pTmp->pLeft == pNode ) pTmp->pLeft = 0;
  5593. + else if( pTmp->pRight == pNode ) pTmp->pRight = 0;
  5594. + }
  5595. + pNode = pTmp;
  5596. + }
  5597. + }
  5598. +
  5599. + pTree->pHead = 0;
  5600. + return SQLITE_OK;
  5601. +}
  5602. +
  5603. +static int memRbtreeFirst(RbtCursor* pCur, int *pRes)
  5604. +{
  5605. + if( pCur->pTree->pHead ){
  5606. + pCur->pNode = pCur->pTree->pHead;
  5607. + while( pCur->pNode->pLeft ){
  5608. + pCur->pNode = pCur->pNode->pLeft;
  5609. + }
  5610. + }
  5611. + if( pCur->pNode ){
  5612. + *pRes = 0;
  5613. + }else{
  5614. + *pRes = 1;
  5615. + }
  5616. + pCur->eSkip = SKIP_NONE;
  5617. + return SQLITE_OK;
  5618. +}
  5619. +
  5620. +static int memRbtreeLast(RbtCursor* pCur, int *pRes)
  5621. +{
  5622. + if( pCur->pTree->pHead ){
  5623. + pCur->pNode = pCur->pTree->pHead;
  5624. + while( pCur->pNode->pRight ){
  5625. + pCur->pNode = pCur->pNode->pRight;
  5626. + }
  5627. + }
  5628. + if( pCur->pNode ){
  5629. + *pRes = 0;
  5630. + }else{
  5631. + *pRes = 1;
  5632. + }
  5633. + pCur->eSkip = SKIP_NONE;
  5634. + return SQLITE_OK;
  5635. +}
  5636. +
  5637. +/*
  5638. +** Advance the cursor to the next entry in the database. If
  5639. +** successful then set *pRes=0. If the cursor
  5640. +** was already pointing to the last entry in the database before
  5641. +** this routine was called, then set *pRes=1.
  5642. +*/
  5643. +static int memRbtreeNext(RbtCursor* pCur, int *pRes)
  5644. +{
  5645. + if( pCur->pNode && pCur->eSkip != SKIP_NEXT ){
  5646. + if( pCur->pNode->pRight ){
  5647. + pCur->pNode = pCur->pNode->pRight;
  5648. + while( pCur->pNode->pLeft )
  5649. + pCur->pNode = pCur->pNode->pLeft;
  5650. + }else{
  5651. + BtRbNode * pX = pCur->pNode;
  5652. + pCur->pNode = pX->pParent;
  5653. + while( pCur->pNode && (pCur->pNode->pRight == pX) ){
  5654. + pX = pCur->pNode;
  5655. + pCur->pNode = pX->pParent;
  5656. + }
  5657. + }
  5658. + }
  5659. + pCur->eSkip = SKIP_NONE;
  5660. +
  5661. + if( !pCur->pNode ){
  5662. + *pRes = 1;
  5663. + }else{
  5664. + *pRes = 0;
  5665. + }
  5666. +
  5667. + return SQLITE_OK;
  5668. +}
  5669. +
  5670. +static int memRbtreePrevious(RbtCursor* pCur, int *pRes)
  5671. +{
  5672. + if( pCur->pNode && pCur->eSkip != SKIP_PREV ){
  5673. + if( pCur->pNode->pLeft ){
  5674. + pCur->pNode = pCur->pNode->pLeft;
  5675. + while( pCur->pNode->pRight )
  5676. + pCur->pNode = pCur->pNode->pRight;
  5677. + }else{
  5678. + BtRbNode * pX = pCur->pNode;
  5679. + pCur->pNode = pX->pParent;
  5680. + while( pCur->pNode && (pCur->pNode->pLeft == pX) ){
  5681. + pX = pCur->pNode;
  5682. + pCur->pNode = pX->pParent;
  5683. + }
  5684. + }
  5685. + }
  5686. + pCur->eSkip = SKIP_NONE;
  5687. +
  5688. + if( !pCur->pNode ){
  5689. + *pRes = 1;
  5690. + }else{
  5691. + *pRes = 0;
  5692. + }
  5693. +
  5694. + return SQLITE_OK;
  5695. +}
  5696. +
  5697. +static int memRbtreeKeySize(RbtCursor* pCur, int *pSize)
  5698. +{
  5699. + if( pCur->pNode ){
  5700. + *pSize = pCur->pNode->nKey;
  5701. + }else{
  5702. + *pSize = 0;
  5703. + }
  5704. + return SQLITE_OK;
  5705. +}
  5706. +
  5707. +static int memRbtreeKey(RbtCursor* pCur, int offset, int amt, char *zBuf)
  5708. +{
  5709. + if( !pCur->pNode ) return 0;
  5710. + if( !pCur->pNode->pKey || ((amt + offset) <= pCur->pNode->nKey) ){
  5711. + memcpy(zBuf, ((char*)pCur->pNode->pKey)+offset, amt);
  5712. + }else{
  5713. + memcpy(zBuf, ((char*)pCur->pNode->pKey)+offset, pCur->pNode->nKey-offset);
  5714. + amt = pCur->pNode->nKey-offset;
  5715. + }
  5716. + return amt;
  5717. +}
  5718. +
  5719. +static int memRbtreeDataSize(RbtCursor* pCur, int *pSize)
  5720. +{
  5721. + if( pCur->pNode ){
  5722. + *pSize = pCur->pNode->nData;
  5723. + }else{
  5724. + *pSize = 0;
  5725. + }
  5726. + return SQLITE_OK;
  5727. +}
  5728. +
  5729. +static int memRbtreeData(RbtCursor *pCur, int offset, int amt, char *zBuf)
  5730. +{
  5731. + if( !pCur->pNode ) return 0;
  5732. + if( (amt + offset) <= pCur->pNode->nData ){
  5733. + memcpy(zBuf, ((char*)pCur->pNode->pData)+offset, amt);
  5734. + }else{
  5735. + memcpy(zBuf, ((char*)pCur->pNode->pData)+offset ,pCur->pNode->nData-offset);
  5736. + amt = pCur->pNode->nData-offset;
  5737. + }
  5738. + return amt;
  5739. +}
  5740. +
  5741. +static int memRbtreeCloseCursor(RbtCursor* pCur)
  5742. +{
  5743. + if( pCur->pTree->pCursors==pCur ){
  5744. + pCur->pTree->pCursors = pCur->pShared;
  5745. + }else{
  5746. + RbtCursor *p = pCur->pTree->pCursors;
  5747. + while( p && p->pShared!=pCur ){ p = p->pShared; }
  5748. + assert( p!=0 );
  5749. + if( p ){
  5750. + p->pShared = pCur->pShared;
  5751. + }
  5752. + }
  5753. + sqliteFree(pCur);
  5754. + return SQLITE_OK;
  5755. +}
  5756. +
  5757. +static int memRbtreeGetMeta(Rbtree* tree, int* aMeta)
  5758. +{
  5759. + memcpy( aMeta, tree->aMetaData, sizeof(int) * SQLITE_N_BTREE_META );
  5760. + return SQLITE_OK;
  5761. +}
  5762. +
  5763. +static int memRbtreeUpdateMeta(Rbtree* tree, int* aMeta)
  5764. +{
  5765. + memcpy( tree->aMetaData, aMeta, sizeof(int) * SQLITE_N_BTREE_META );
  5766. + return SQLITE_OK;
  5767. +}
  5768. +
  5769. +/*
  5770. + * Check that each table in the Rbtree meets the requirements for a red-black
  5771. + * binary tree. If an error is found, return an explanation of the problem in
  5772. + * memory obtained from sqliteMalloc(). Parameters aRoot and nRoot are ignored.
  5773. + */
  5774. +static char *memRbtreeIntegrityCheck(Rbtree* tree, int* aRoot, int nRoot)
  5775. +{
  5776. + char * msg = 0;
  5777. + HashElem *p;
  5778. +
  5779. + for(p=sqliteHashFirst(&tree->tblHash); p; p=sqliteHashNext(p)){
  5780. + BtRbTree *pTree = sqliteHashData(p);
  5781. + check_redblack_tree(pTree, &msg);
  5782. + }
  5783. +
  5784. + return msg;
  5785. +}
  5786. +
  5787. +static int memRbtreeSetCacheSize(Rbtree* tree, int sz)
  5788. +{
  5789. + return SQLITE_OK;
  5790. +}
  5791. +
  5792. +static int memRbtreeSetSafetyLevel(Rbtree *pBt, int level){
  5793. + return SQLITE_OK;
  5794. +}
  5795. +
  5796. +static int memRbtreeBeginTrans(Rbtree* tree)
  5797. +{
  5798. + if( tree->eTransState != TRANS_NONE )
  5799. + return SQLITE_ERROR;
  5800. +
  5801. + assert( tree->pTransRollback == 0 );
  5802. + tree->eTransState = TRANS_INTRANSACTION;
  5803. + return SQLITE_OK;
  5804. +}
  5805. +
  5806. +/*
  5807. +** Delete a linked list of BtRollbackOp structures.
  5808. +*/
  5809. +static void deleteRollbackList(BtRollbackOp *pOp){
  5810. + while( pOp ){
  5811. + BtRollbackOp *pTmp = pOp->pNext;
  5812. + sqliteFree(pOp->pData);
  5813. + sqliteFree(pOp->pKey);
  5814. + sqliteFree(pOp);
  5815. + pOp = pTmp;
  5816. + }
  5817. +}
  5818. +
  5819. +static int memRbtreeCommit(Rbtree* tree){
  5820. + /* Just delete pTransRollback and pCheckRollback */
  5821. + deleteRollbackList(tree->pCheckRollback);
  5822. + deleteRollbackList(tree->pTransRollback);
  5823. + tree->pTransRollback = 0;
  5824. + tree->pCheckRollback = 0;
  5825. + tree->pCheckRollbackTail = 0;
  5826. + tree->eTransState = TRANS_NONE;
  5827. + return SQLITE_OK;
  5828. +}
  5829. +
  5830. +/*
  5831. + * Close the supplied Rbtree. Delete everything associated with it.
  5832. + */
  5833. +static int memRbtreeClose(Rbtree* tree)
  5834. +{
  5835. + HashElem *p;
  5836. + memRbtreeCommit(tree);
  5837. + while( (p=sqliteHashFirst(&tree->tblHash))!=0 ){
  5838. + tree->eTransState = TRANS_ROLLBACK;
  5839. + memRbtreeDropTable(tree, sqliteHashKeysize(p));
  5840. + }
  5841. + sqliteHashClear(&tree->tblHash);
  5842. + sqliteFree(tree);
  5843. + return SQLITE_OK;
  5844. +}
  5845. +
  5846. +/*
  5847. + * Execute and delete the supplied rollback-list on pRbtree.
  5848. + */
  5849. +static void execute_rollback_list(Rbtree *pRbtree, BtRollbackOp *pList)
  5850. +{
  5851. + BtRollbackOp *pTmp;
  5852. + RbtCursor cur;
  5853. + int res;
  5854. +
  5855. + cur.pRbtree = pRbtree;
  5856. + cur.wrFlag = 1;
  5857. + while( pList ){
  5858. + switch( pList->eOp ){
  5859. + case ROLLBACK_INSERT:
  5860. + cur.pTree = sqliteHashFind( &pRbtree->tblHash, 0, pList->iTab );
  5861. + assert(cur.pTree);
  5862. + cur.iTree = pList->iTab;
  5863. + cur.eSkip = SKIP_NONE;
  5864. + memRbtreeInsert( &cur, pList->pKey,
  5865. + pList->nKey, pList->pData, pList->nData );
  5866. + break;
  5867. + case ROLLBACK_DELETE:
  5868. + cur.pTree = sqliteHashFind( &pRbtree->tblHash, 0, pList->iTab );
  5869. + assert(cur.pTree);
  5870. + cur.iTree = pList->iTab;
  5871. + cur.eSkip = SKIP_NONE;
  5872. + memRbtreeMoveto(&cur, pList->pKey, pList->nKey, &res);
  5873. + assert(res == 0);
  5874. + memRbtreeDelete( &cur );
  5875. + break;
  5876. + case ROLLBACK_CREATE:
  5877. + btreeCreateTable(pRbtree, pList->iTab);
  5878. + break;
  5879. + case ROLLBACK_DROP:
  5880. + memRbtreeDropTable(pRbtree, pList->iTab);
  5881. + break;
  5882. + default:
  5883. + assert(0);
  5884. + }
  5885. + sqliteFree(pList->pKey);
  5886. + sqliteFree(pList->pData);
  5887. + pTmp = pList->pNext;
  5888. + sqliteFree(pList);
  5889. + pList = pTmp;
  5890. + }
  5891. +}
  5892. +
  5893. +static int memRbtreeRollback(Rbtree* tree)
  5894. +{
  5895. + tree->eTransState = TRANS_ROLLBACK;
  5896. + execute_rollback_list(tree, tree->pCheckRollback);
  5897. + execute_rollback_list(tree, tree->pTransRollback);
  5898. + tree->pTransRollback = 0;
  5899. + tree->pCheckRollback = 0;
  5900. + tree->pCheckRollbackTail = 0;
  5901. + tree->eTransState = TRANS_NONE;
  5902. + return SQLITE_OK;
  5903. +}
  5904. +
  5905. +static int memRbtreeBeginCkpt(Rbtree* tree)
  5906. +{
  5907. + if( tree->eTransState != TRANS_INTRANSACTION )
  5908. + return SQLITE_ERROR;
  5909. +
  5910. + assert( tree->pCheckRollback == 0 );
  5911. + assert( tree->pCheckRollbackTail == 0 );
  5912. + tree->eTransState = TRANS_INCHECKPOINT;
  5913. + return SQLITE_OK;
  5914. +}
  5915. +
  5916. +static int memRbtreeCommitCkpt(Rbtree* tree)
  5917. +{
  5918. + if( tree->eTransState == TRANS_INCHECKPOINT ){
  5919. + if( tree->pCheckRollback ){
  5920. + tree->pCheckRollbackTail->pNext = tree->pTransRollback;
  5921. + tree->pTransRollback = tree->pCheckRollback;
  5922. + tree->pCheckRollback = 0;
  5923. + tree->pCheckRollbackTail = 0;
  5924. + }
  5925. + tree->eTransState = TRANS_INTRANSACTION;
  5926. + }
  5927. + return SQLITE_OK;
  5928. +}
  5929. +
  5930. +static int memRbtreeRollbackCkpt(Rbtree* tree)
  5931. +{
  5932. + if( tree->eTransState != TRANS_INCHECKPOINT ) return SQLITE_OK;
  5933. + tree->eTransState = TRANS_ROLLBACK;
  5934. + execute_rollback_list(tree, tree->pCheckRollback);
  5935. + tree->pCheckRollback = 0;
  5936. + tree->pCheckRollbackTail = 0;
  5937. + tree->eTransState = TRANS_INTRANSACTION;
  5938. + return SQLITE_OK;
  5939. +}
  5940. +
  5941. +#ifdef SQLITE_TEST
  5942. +static int memRbtreePageDump(Rbtree* tree, int pgno, int rec)
  5943. +{
  5944. + assert(!"Cannot call sqliteRbtreePageDump");
  5945. + return SQLITE_OK;
  5946. +}
  5947. +
  5948. +static int memRbtreeCursorDump(RbtCursor* pCur, int* aRes)
  5949. +{
  5950. + assert(!"Cannot call sqliteRbtreeCursorDump");
  5951. + return SQLITE_OK;
  5952. +}
  5953. +#endif
  5954. +
  5955. +static struct Pager *memRbtreePager(Rbtree* tree)
  5956. +{
  5957. + return 0;
  5958. +}
  5959. +
  5960. +/*
  5961. +** Return the full pathname of the underlying database file.
  5962. +*/
  5963. +static const char *memRbtreeGetFilename(Rbtree *pBt){
  5964. + return 0; /* A NULL return indicates there is no underlying file */
  5965. +}
  5966. +
  5967. +/*
  5968. +** The copy file function is not implemented for the in-memory database
  5969. +*/
  5970. +static int memRbtreeCopyFile(Rbtree *pBt, Rbtree *pBt2){
  5971. + return SQLITE_INTERNAL; /* Not implemented */
  5972. +}
  5973. +
  5974. +static BtOps sqliteRbtreeOps = {
  5975. + (int(*)(Btree*)) memRbtreeClose,
  5976. + (int(*)(Btree*,int)) memRbtreeSetCacheSize,
  5977. + (int(*)(Btree*,int)) memRbtreeSetSafetyLevel,
  5978. + (int(*)(Btree*)) memRbtreeBeginTrans,
  5979. + (int(*)(Btree*)) memRbtreeCommit,
  5980. + (int(*)(Btree*)) memRbtreeRollback,
  5981. + (int(*)(Btree*)) memRbtreeBeginCkpt,
  5982. + (int(*)(Btree*)) memRbtreeCommitCkpt,
  5983. + (int(*)(Btree*)) memRbtreeRollbackCkpt,
  5984. + (int(*)(Btree*,int*)) memRbtreeCreateTable,
  5985. + (int(*)(Btree*,int*)) memRbtreeCreateTable,
  5986. + (int(*)(Btree*,int)) memRbtreeDropTable,
  5987. + (int(*)(Btree*,int)) memRbtreeClearTable,
  5988. + (int(*)(Btree*,int,int,BtCursor**)) memRbtreeCursor,
  5989. + (int(*)(Btree*,int*)) memRbtreeGetMeta,
  5990. + (int(*)(Btree*,int*)) memRbtreeUpdateMeta,
  5991. + (char*(*)(Btree*,int*,int)) memRbtreeIntegrityCheck,
  5992. + (const char*(*)(Btree*)) memRbtreeGetFilename,
  5993. + (int(*)(Btree*,Btree*)) memRbtreeCopyFile,
  5994. + (struct Pager*(*)(Btree*)) memRbtreePager,
  5995. +#ifdef SQLITE_TEST
  5996. + (int(*)(Btree*,int,int)) memRbtreePageDump,
  5997. +#endif
  5998. +};
  5999. +
  6000. +static BtCursorOps sqliteRbtreeCursorOps = {
  6001. + (int(*)(BtCursor*,const void*,int,int*)) memRbtreeMoveto,
  6002. + (int(*)(BtCursor*)) memRbtreeDelete,
  6003. + (int(*)(BtCursor*,const void*,int,const void*,int)) memRbtreeInsert,
  6004. + (int(*)(BtCursor*,int*)) memRbtreeFirst,
  6005. + (int(*)(BtCursor*,int*)) memRbtreeLast,
  6006. + (int(*)(BtCursor*,int*)) memRbtreeNext,
  6007. + (int(*)(BtCursor*,int*)) memRbtreePrevious,
  6008. + (int(*)(BtCursor*,int*)) memRbtreeKeySize,
  6009. + (int(*)(BtCursor*,int,int,char*)) memRbtreeKey,
  6010. + (int(*)(BtCursor*,const void*,int,int,int*)) memRbtreeKeyCompare,
  6011. + (int(*)(BtCursor*,int*)) memRbtreeDataSize,
  6012. + (int(*)(BtCursor*,int,int,char*)) memRbtreeData,
  6013. + (int(*)(BtCursor*)) memRbtreeCloseCursor,
  6014. +#ifdef SQLITE_TEST
  6015. + (int(*)(BtCursor*,int*)) memRbtreeCursorDump,
  6016. +#endif
  6017. +
  6018. +};
  6019. +
  6020. +#endif /* SQLITE_OMIT_INMEMORYDB */
  6021. --- /dev/null
  6022. +++ b/ext/sqlite/libsqlite/src/build.c
  6023. @@ -0,0 +1,2156 @@
  6024. +/*
  6025. +** 2001 September 15
  6026. +**
  6027. +** The author disclaims copyright to this source code. In place of
  6028. +** a legal notice, here is a blessing:
  6029. +**
  6030. +** May you do good and not evil.
  6031. +** May you find forgiveness for yourself and forgive others.
  6032. +** May you share freely, never taking more than you give.
  6033. +**
  6034. +*************************************************************************
  6035. +** This file contains C code routines that are called by the SQLite parser
  6036. +** when syntax rules are reduced. The routines in this file handle the
  6037. +** following kinds of SQL syntax:
  6038. +**
  6039. +** CREATE TABLE
  6040. +** DROP TABLE
  6041. +** CREATE INDEX
  6042. +** DROP INDEX
  6043. +** creating ID lists
  6044. +** BEGIN TRANSACTION
  6045. +** COMMIT
  6046. +** ROLLBACK
  6047. +** PRAGMA
  6048. +**
  6049. +** $Id$
  6050. +*/
  6051. +#include "sqliteInt.h"
  6052. +#include <ctype.h>
  6053. +
  6054. +/*
  6055. +** This routine is called when a new SQL statement is beginning to
  6056. +** be parsed. Check to see if the schema for the database needs
  6057. +** to be read from the SQLITE_MASTER and SQLITE_TEMP_MASTER tables.
  6058. +** If it does, then read it.
  6059. +*/
  6060. +void sqliteBeginParse(Parse *pParse, int explainFlag){
  6061. + sqlite *db = pParse->db;
  6062. + int i;
  6063. + pParse->explain = explainFlag;
  6064. + if((db->flags & SQLITE_Initialized)==0 && db->init.busy==0 ){
  6065. + int rc = sqliteInit(db, &pParse->zErrMsg);
  6066. + if( rc!=SQLITE_OK ){
  6067. + pParse->rc = rc;
  6068. + pParse->nErr++;
  6069. + }
  6070. + }
  6071. + for(i=0; i<db->nDb; i++){
  6072. + DbClearProperty(db, i, DB_Locked);
  6073. + if( !db->aDb[i].inTrans ){
  6074. + DbClearProperty(db, i, DB_Cookie);
  6075. + }
  6076. + }
  6077. + pParse->nVar = 0;
  6078. +}
  6079. +
  6080. +/*
  6081. +** This routine is called after a single SQL statement has been
  6082. +** parsed and we want to execute the VDBE code to implement
  6083. +** that statement. Prior action routines should have already
  6084. +** constructed VDBE code to do the work of the SQL statement.
  6085. +** This routine just has to execute the VDBE code.
  6086. +**
  6087. +** Note that if an error occurred, it might be the case that
  6088. +** no VDBE code was generated.
  6089. +*/
  6090. +void sqliteExec(Parse *pParse){
  6091. + sqlite *db = pParse->db;
  6092. + Vdbe *v = pParse->pVdbe;
  6093. +
  6094. + if( v==0 && (v = sqliteGetVdbe(pParse))!=0 ){
  6095. + sqliteVdbeAddOp(v, OP_Halt, 0, 0);
  6096. + }
  6097. + if( sqlite_malloc_failed ) return;
  6098. + if( v && pParse->nErr==0 ){
  6099. + FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
  6100. + sqliteVdbeTrace(v, trace);
  6101. + sqliteVdbeMakeReady(v, pParse->nVar, pParse->explain);
  6102. + pParse->rc = pParse->nErr ? SQLITE_ERROR : SQLITE_DONE;
  6103. + pParse->colNamesSet = 0;
  6104. + }else if( pParse->rc==SQLITE_OK ){
  6105. + pParse->rc = SQLITE_ERROR;
  6106. + }
  6107. + pParse->nTab = 0;
  6108. + pParse->nMem = 0;
  6109. + pParse->nSet = 0;
  6110. + pParse->nAgg = 0;
  6111. + pParse->nVar = 0;
  6112. +}
  6113. +
  6114. +/*
  6115. +** Locate the in-memory structure that describes
  6116. +** a particular database table given the name
  6117. +** of that table and (optionally) the name of the database
  6118. +** containing the table. Return NULL if not found.
  6119. +**
  6120. +** If zDatabase is 0, all databases are searched for the
  6121. +** table and the first matching table is returned. (No checking
  6122. +** for duplicate table names is done.) The search order is
  6123. +** TEMP first, then MAIN, then any auxiliary databases added
  6124. +** using the ATTACH command.
  6125. +**
  6126. +** See also sqliteLocateTable().
  6127. +*/
  6128. +Table *sqliteFindTable(sqlite *db, const char *zName, const char *zDatabase){
  6129. + Table *p = 0;
  6130. + int i;
  6131. + for(i=0; i<db->nDb; i++){
  6132. + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  6133. + if( zDatabase!=0 && sqliteStrICmp(zDatabase, db->aDb[j].zName) ) continue;
  6134. + p = sqliteHashFind(&db->aDb[j].tblHash, zName, strlen(zName)+1);
  6135. + if( p ) break;
  6136. + }
  6137. + return p;
  6138. +}
  6139. +
  6140. +/*
  6141. +** Locate the in-memory structure that describes
  6142. +** a particular database table given the name
  6143. +** of that table and (optionally) the name of the database
  6144. +** containing the table. Return NULL if not found.
  6145. +** Also leave an error message in pParse->zErrMsg.
  6146. +**
  6147. +** The difference between this routine and sqliteFindTable()
  6148. +** is that this routine leaves an error message in pParse->zErrMsg
  6149. +** where sqliteFindTable() does not.
  6150. +*/
  6151. +Table *sqliteLocateTable(Parse *pParse, const char *zName, const char *zDbase){
  6152. + Table *p;
  6153. +
  6154. + p = sqliteFindTable(pParse->db, zName, zDbase);
  6155. + if( p==0 ){
  6156. + if( zDbase ){
  6157. + sqliteErrorMsg(pParse, "no such table: %s.%s", zDbase, zName);
  6158. + }else if( sqliteFindTable(pParse->db, zName, 0)!=0 ){
  6159. + sqliteErrorMsg(pParse, "table \"%s\" is not in database \"%s\"",
  6160. + zName, zDbase);
  6161. + }else{
  6162. + sqliteErrorMsg(pParse, "no such table: %s", zName);
  6163. + }
  6164. + }
  6165. + return p;
  6166. +}
  6167. +
  6168. +/*
  6169. +** Locate the in-memory structure that describes
  6170. +** a particular index given the name of that index
  6171. +** and the name of the database that contains the index.
  6172. +** Return NULL if not found.
  6173. +**
  6174. +** If zDatabase is 0, all databases are searched for the
  6175. +** table and the first matching index is returned. (No checking
  6176. +** for duplicate index names is done.) The search order is
  6177. +** TEMP first, then MAIN, then any auxiliary databases added
  6178. +** using the ATTACH command.
  6179. +*/
  6180. +Index *sqliteFindIndex(sqlite *db, const char *zName, const char *zDb){
  6181. + Index *p = 0;
  6182. + int i;
  6183. + for(i=0; i<db->nDb; i++){
  6184. + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  6185. + if( zDb && sqliteStrICmp(zDb, db->aDb[j].zName) ) continue;
  6186. + p = sqliteHashFind(&db->aDb[j].idxHash, zName, strlen(zName)+1);
  6187. + if( p ) break;
  6188. + }
  6189. + return p;
  6190. +}
  6191. +
  6192. +/*
  6193. +** Remove the given index from the index hash table, and free
  6194. +** its memory structures.
  6195. +**
  6196. +** The index is removed from the database hash tables but
  6197. +** it is not unlinked from the Table that it indexes.
  6198. +** Unlinking from the Table must be done by the calling function.
  6199. +*/
  6200. +static void sqliteDeleteIndex(sqlite *db, Index *p){
  6201. + Index *pOld;
  6202. +
  6203. + assert( db!=0 && p->zName!=0 );
  6204. + pOld = sqliteHashInsert(&db->aDb[p->iDb].idxHash, p->zName,
  6205. + strlen(p->zName)+1, 0);
  6206. + if( pOld!=0 && pOld!=p ){
  6207. + sqliteHashInsert(&db->aDb[p->iDb].idxHash, pOld->zName,
  6208. + strlen(pOld->zName)+1, pOld);
  6209. + }
  6210. + sqliteFree(p);
  6211. +}
  6212. +
  6213. +/*
  6214. +** Unlink the given index from its table, then remove
  6215. +** the index from the index hash table and free its memory
  6216. +** structures.
  6217. +*/
  6218. +void sqliteUnlinkAndDeleteIndex(sqlite *db, Index *pIndex){
  6219. + if( pIndex->pTable->pIndex==pIndex ){
  6220. + pIndex->pTable->pIndex = pIndex->pNext;
  6221. + }else{
  6222. + Index *p;
  6223. + for(p=pIndex->pTable->pIndex; p && p->pNext!=pIndex; p=p->pNext){}
  6224. + if( p && p->pNext==pIndex ){
  6225. + p->pNext = pIndex->pNext;
  6226. + }
  6227. + }
  6228. + sqliteDeleteIndex(db, pIndex);
  6229. +}
  6230. +
  6231. +/*
  6232. +** Erase all schema information from the in-memory hash tables of
  6233. +** database connection. This routine is called to reclaim memory
  6234. +** before the connection closes. It is also called during a rollback
  6235. +** if there were schema changes during the transaction.
  6236. +**
  6237. +** If iDb<=0 then reset the internal schema tables for all database
  6238. +** files. If iDb>=2 then reset the internal schema for only the
  6239. +** single file indicated.
  6240. +*/
  6241. +void sqliteResetInternalSchema(sqlite *db, int iDb){
  6242. + HashElem *pElem;
  6243. + Hash temp1;
  6244. + Hash temp2;
  6245. + int i, j;
  6246. +
  6247. + assert( iDb>=0 && iDb<db->nDb );
  6248. + db->flags &= ~SQLITE_Initialized;
  6249. + for(i=iDb; i<db->nDb; i++){
  6250. + Db *pDb = &db->aDb[i];
  6251. + temp1 = pDb->tblHash;
  6252. + temp2 = pDb->trigHash;
  6253. + sqliteHashInit(&pDb->trigHash, SQLITE_HASH_STRING, 0);
  6254. + sqliteHashClear(&pDb->aFKey);
  6255. + sqliteHashClear(&pDb->idxHash);
  6256. + for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  6257. + Trigger *pTrigger = sqliteHashData(pElem);
  6258. + sqliteDeleteTrigger(pTrigger);
  6259. + }
  6260. + sqliteHashClear(&temp2);
  6261. + sqliteHashInit(&pDb->tblHash, SQLITE_HASH_STRING, 0);
  6262. + for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  6263. + Table *pTab = sqliteHashData(pElem);
  6264. + sqliteDeleteTable(db, pTab);
  6265. + }
  6266. + sqliteHashClear(&temp1);
  6267. + DbClearProperty(db, i, DB_SchemaLoaded);
  6268. + if( iDb>0 ) return;
  6269. + }
  6270. + assert( iDb==0 );
  6271. + db->flags &= ~SQLITE_InternChanges;
  6272. +
  6273. + /* If one or more of the auxiliary database files has been closed,
  6274. + ** then remove then from the auxiliary database list. We take the
  6275. + ** opportunity to do this here since we have just deleted all of the
  6276. + ** schema hash tables and therefore do not have to make any changes
  6277. + ** to any of those tables.
  6278. + */
  6279. + for(i=0; i<db->nDb; i++){
  6280. + struct Db *pDb = &db->aDb[i];
  6281. + if( pDb->pBt==0 ){
  6282. + if( pDb->pAux && pDb->xFreeAux ) pDb->xFreeAux(pDb->pAux);
  6283. + pDb->pAux = 0;
  6284. + }
  6285. + }
  6286. + for(i=j=2; i<db->nDb; i++){
  6287. + struct Db *pDb = &db->aDb[i];
  6288. + if( pDb->pBt==0 ){
  6289. + sqliteFree(pDb->zName);
  6290. + pDb->zName = 0;
  6291. + continue;
  6292. + }
  6293. + if( j<i ){
  6294. + db->aDb[j] = db->aDb[i];
  6295. + }
  6296. + j++;
  6297. + }
  6298. + memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  6299. + db->nDb = j;
  6300. + if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  6301. + memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  6302. + sqliteFree(db->aDb);
  6303. + db->aDb = db->aDbStatic;
  6304. + }
  6305. +}
  6306. +
  6307. +/*
  6308. +** This routine is called whenever a rollback occurs. If there were
  6309. +** schema changes during the transaction, then we have to reset the
  6310. +** internal hash tables and reload them from disk.
  6311. +*/
  6312. +void sqliteRollbackInternalChanges(sqlite *db){
  6313. + if( db->flags & SQLITE_InternChanges ){
  6314. + sqliteResetInternalSchema(db, 0);
  6315. + }
  6316. +}
  6317. +
  6318. +/*
  6319. +** This routine is called when a commit occurs.
  6320. +*/
  6321. +void sqliteCommitInternalChanges(sqlite *db){
  6322. + db->aDb[0].schema_cookie = db->next_cookie;
  6323. + db->flags &= ~SQLITE_InternChanges;
  6324. +}
  6325. +
  6326. +/*
  6327. +** Remove the memory data structures associated with the given
  6328. +** Table. No changes are made to disk by this routine.
  6329. +**
  6330. +** This routine just deletes the data structure. It does not unlink
  6331. +** the table data structure from the hash table. Nor does it remove
  6332. +** foreign keys from the sqlite.aFKey hash table. But it does destroy
  6333. +** memory structures of the indices and foreign keys associated with
  6334. +** the table.
  6335. +**
  6336. +** Indices associated with the table are unlinked from the "db"
  6337. +** data structure if db!=NULL. If db==NULL, indices attached to
  6338. +** the table are deleted, but it is assumed they have already been
  6339. +** unlinked.
  6340. +*/
  6341. +void sqliteDeleteTable(sqlite *db, Table *pTable){
  6342. + int i;
  6343. + Index *pIndex, *pNext;
  6344. + FKey *pFKey, *pNextFKey;
  6345. +
  6346. + if( pTable==0 ) return;
  6347. +
  6348. + /* Delete all indices associated with this table
  6349. + */
  6350. + for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  6351. + pNext = pIndex->pNext;
  6352. + assert( pIndex->iDb==pTable->iDb || (pTable->iDb==0 && pIndex->iDb==1) );
  6353. + sqliteDeleteIndex(db, pIndex);
  6354. + }
  6355. +
  6356. + /* Delete all foreign keys associated with this table. The keys
  6357. + ** should have already been unlinked from the db->aFKey hash table
  6358. + */
  6359. + for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){
  6360. + pNextFKey = pFKey->pNextFrom;
  6361. + assert( pTable->iDb<db->nDb );
  6362. + assert( sqliteHashFind(&db->aDb[pTable->iDb].aFKey,
  6363. + pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey );
  6364. + sqliteFree(pFKey);
  6365. + }
  6366. +
  6367. + /* Delete the Table structure itself.
  6368. + */
  6369. + for(i=0; i<pTable->nCol; i++){
  6370. + sqliteFree(pTable->aCol[i].zName);
  6371. + sqliteFree(pTable->aCol[i].zDflt);
  6372. + sqliteFree(pTable->aCol[i].zType);
  6373. + }
  6374. + sqliteFree(pTable->zName);
  6375. + sqliteFree(pTable->aCol);
  6376. + sqliteSelectDelete(pTable->pSelect);
  6377. + sqliteFree(pTable);
  6378. +}
  6379. +
  6380. +/*
  6381. +** Unlink the given table from the hash tables and the delete the
  6382. +** table structure with all its indices and foreign keys.
  6383. +*/
  6384. +static void sqliteUnlinkAndDeleteTable(sqlite *db, Table *p){
  6385. + Table *pOld;
  6386. + FKey *pF1, *pF2;
  6387. + int i = p->iDb;
  6388. + assert( db!=0 );
  6389. + pOld = sqliteHashInsert(&db->aDb[i].tblHash, p->zName, strlen(p->zName)+1, 0);
  6390. + assert( pOld==0 || pOld==p );
  6391. + for(pF1=p->pFKey; pF1; pF1=pF1->pNextFrom){
  6392. + int nTo = strlen(pF1->zTo) + 1;
  6393. + pF2 = sqliteHashFind(&db->aDb[i].aFKey, pF1->zTo, nTo);
  6394. + if( pF2==pF1 ){
  6395. + sqliteHashInsert(&db->aDb[i].aFKey, pF1->zTo, nTo, pF1->pNextTo);
  6396. + }else{
  6397. + while( pF2 && pF2->pNextTo!=pF1 ){ pF2=pF2->pNextTo; }
  6398. + if( pF2 ){
  6399. + pF2->pNextTo = pF1->pNextTo;
  6400. + }
  6401. + }
  6402. + }
  6403. + sqliteDeleteTable(db, p);
  6404. +}
  6405. +
  6406. +/*
  6407. +** Construct the name of a user table or index from a token.
  6408. +**
  6409. +** Space to hold the name is obtained from sqliteMalloc() and must
  6410. +** be freed by the calling function.
  6411. +*/
  6412. +char *sqliteTableNameFromToken(Token *pName){
  6413. + char *zName = sqliteStrNDup(pName->z, pName->n);
  6414. + sqliteDequote(zName);
  6415. + return zName;
  6416. +}
  6417. +
  6418. +/*
  6419. +** Generate code to open the appropriate master table. The table
  6420. +** opened will be SQLITE_MASTER for persistent tables and
  6421. +** SQLITE_TEMP_MASTER for temporary tables. The table is opened
  6422. +** on cursor 0.
  6423. +*/
  6424. +void sqliteOpenMasterTable(Vdbe *v, int isTemp){
  6425. + sqliteVdbeAddOp(v, OP_Integer, isTemp, 0);
  6426. + sqliteVdbeAddOp(v, OP_OpenWrite, 0, 2);
  6427. +}
  6428. +
  6429. +/*
  6430. +** Begin constructing a new table representation in memory. This is
  6431. +** the first of several action routines that get called in response
  6432. +** to a CREATE TABLE statement. In particular, this routine is called
  6433. +** after seeing tokens "CREATE" and "TABLE" and the table name. The
  6434. +** pStart token is the CREATE and pName is the table name. The isTemp
  6435. +** flag is true if the table should be stored in the auxiliary database
  6436. +** file instead of in the main database file. This is normally the case
  6437. +** when the "TEMP" or "TEMPORARY" keyword occurs in between
  6438. +** CREATE and TABLE.
  6439. +**
  6440. +** The new table record is initialized and put in pParse->pNewTable.
  6441. +** As more of the CREATE TABLE statement is parsed, additional action
  6442. +** routines will be called to add more information to this record.
  6443. +** At the end of the CREATE TABLE statement, the sqliteEndTable() routine
  6444. +** is called to complete the construction of the new table record.
  6445. +*/
  6446. +void sqliteStartTable(
  6447. + Parse *pParse, /* Parser context */
  6448. + Token *pStart, /* The "CREATE" token */
  6449. + Token *pName, /* Name of table or view to create */
  6450. + int isTemp, /* True if this is a TEMP table */
  6451. + int isView /* True if this is a VIEW */
  6452. +){
  6453. + Table *pTable;
  6454. + Index *pIdx;
  6455. + char *zName;
  6456. + sqlite *db = pParse->db;
  6457. + Vdbe *v;
  6458. + int iDb;
  6459. +
  6460. + pParse->sFirstToken = *pStart;
  6461. + zName = sqliteTableNameFromToken(pName);
  6462. + if( zName==0 ) return;
  6463. + if( db->init.iDb==1 ) isTemp = 1;
  6464. +#ifndef SQLITE_OMIT_AUTHORIZATION
  6465. + assert( (isTemp & 1)==isTemp );
  6466. + {
  6467. + int code;
  6468. + char *zDb = isTemp ? "temp" : "main";
  6469. + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  6470. + sqliteFree(zName);
  6471. + return;
  6472. + }
  6473. + if( isView ){
  6474. + if( isTemp ){
  6475. + code = SQLITE_CREATE_TEMP_VIEW;
  6476. + }else{
  6477. + code = SQLITE_CREATE_VIEW;
  6478. + }
  6479. + }else{
  6480. + if( isTemp ){
  6481. + code = SQLITE_CREATE_TEMP_TABLE;
  6482. + }else{
  6483. + code = SQLITE_CREATE_TABLE;
  6484. + }
  6485. + }
  6486. + if( sqliteAuthCheck(pParse, code, zName, 0, zDb) ){
  6487. + sqliteFree(zName);
  6488. + return;
  6489. + }
  6490. + }
  6491. +#endif
  6492. +
  6493. +
  6494. + /* Before trying to create a temporary table, make sure the Btree for
  6495. + ** holding temporary tables is open.
  6496. + */
  6497. + if( isTemp && db->aDb[1].pBt==0 && !pParse->explain ){
  6498. + int rc = sqliteBtreeFactory(db, 0, 0, MAX_PAGES, &db->aDb[1].pBt);
  6499. + if( rc!=SQLITE_OK ){
  6500. + sqliteErrorMsg(pParse, "unable to open a temporary database "
  6501. + "file for storing temporary tables");
  6502. + pParse->nErr++;
  6503. + return;
  6504. + }
  6505. + if( db->flags & SQLITE_InTrans ){
  6506. + rc = sqliteBtreeBeginTrans(db->aDb[1].pBt);
  6507. + if( rc!=SQLITE_OK ){
  6508. + sqliteErrorMsg(pParse, "unable to get a write lock on "
  6509. + "the temporary database file");
  6510. + return;
  6511. + }
  6512. + }
  6513. + }
  6514. +
  6515. + /* Make sure the new table name does not collide with an existing
  6516. + ** index or table name. Issue an error message if it does.
  6517. + **
  6518. + ** If we are re-reading the sqlite_master table because of a schema
  6519. + ** change and a new permanent table is found whose name collides with
  6520. + ** an existing temporary table, that is not an error.
  6521. + */
  6522. + pTable = sqliteFindTable(db, zName, 0);
  6523. + iDb = isTemp ? 1 : db->init.iDb;
  6524. + if( pTable!=0 && (pTable->iDb==iDb || !db->init.busy) ){
  6525. + sqliteErrorMsg(pParse, "table %T already exists", pName);
  6526. + sqliteFree(zName);
  6527. + return;
  6528. + }
  6529. + if( (pIdx = sqliteFindIndex(db, zName, 0))!=0 &&
  6530. + (pIdx->iDb==0 || !db->init.busy) ){
  6531. + sqliteErrorMsg(pParse, "there is already an index named %s", zName);
  6532. + sqliteFree(zName);
  6533. + return;
  6534. + }
  6535. + pTable = sqliteMalloc( sizeof(Table) );
  6536. + if( pTable==0 ){
  6537. + sqliteFree(zName);
  6538. + return;
  6539. + }
  6540. + pTable->zName = zName;
  6541. + pTable->nCol = 0;
  6542. + pTable->aCol = 0;
  6543. + pTable->iPKey = -1;
  6544. + pTable->pIndex = 0;
  6545. + pTable->iDb = iDb;
  6546. + if( pParse->pNewTable ) sqliteDeleteTable(db, pParse->pNewTable);
  6547. + pParse->pNewTable = pTable;
  6548. +
  6549. + /* Begin generating the code that will insert the table record into
  6550. + ** the SQLITE_MASTER table. Note in particular that we must go ahead
  6551. + ** and allocate the record number for the table entry now. Before any
  6552. + ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  6553. + ** indices to be created and the table record must come before the
  6554. + ** indices. Hence, the record number for the table must be allocated
  6555. + ** now.
  6556. + */
  6557. + if( !db->init.busy && (v = sqliteGetVdbe(pParse))!=0 ){
  6558. + sqliteBeginWriteOperation(pParse, 0, isTemp);
  6559. + if( !isTemp ){
  6560. + sqliteVdbeAddOp(v, OP_Integer, db->file_format, 0);
  6561. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 1);
  6562. + }
  6563. + sqliteOpenMasterTable(v, isTemp);
  6564. + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
  6565. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  6566. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  6567. + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
  6568. + }
  6569. +}
  6570. +
  6571. +/*
  6572. +** Add a new column to the table currently being constructed.
  6573. +**
  6574. +** The parser calls this routine once for each column declaration
  6575. +** in a CREATE TABLE statement. sqliteStartTable() gets called
  6576. +** first to get things going. Then this routine is called for each
  6577. +** column.
  6578. +*/
  6579. +void sqliteAddColumn(Parse *pParse, Token *pName){
  6580. + Table *p;
  6581. + int i;
  6582. + char *z = 0;
  6583. + Column *pCol;
  6584. + if( (p = pParse->pNewTable)==0 ) return;
  6585. + sqliteSetNString(&z, pName->z, pName->n, 0);
  6586. + if( z==0 ) return;
  6587. + sqliteDequote(z);
  6588. + for(i=0; i<p->nCol; i++){
  6589. + if( sqliteStrICmp(z, p->aCol[i].zName)==0 ){
  6590. + sqliteErrorMsg(pParse, "duplicate column name: %s", z);
  6591. + sqliteFree(z);
  6592. + return;
  6593. + }
  6594. + }
  6595. + if( (p->nCol & 0x7)==0 ){
  6596. + Column *aNew;
  6597. + aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0]));
  6598. + if( aNew==0 ) return;
  6599. + p->aCol = aNew;
  6600. + }
  6601. + pCol = &p->aCol[p->nCol];
  6602. + memset(pCol, 0, sizeof(p->aCol[0]));
  6603. + pCol->zName = z;
  6604. + pCol->sortOrder = SQLITE_SO_NUM;
  6605. + p->nCol++;
  6606. +}
  6607. +
  6608. +/*
  6609. +** This routine is called by the parser while in the middle of
  6610. +** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  6611. +** been seen on a column. This routine sets the notNull flag on
  6612. +** the column currently under construction.
  6613. +*/
  6614. +void sqliteAddNotNull(Parse *pParse, int onError){
  6615. + Table *p;
  6616. + int i;
  6617. + if( (p = pParse->pNewTable)==0 ) return;
  6618. + i = p->nCol-1;
  6619. + if( i>=0 ) p->aCol[i].notNull = onError;
  6620. +}
  6621. +
  6622. +/*
  6623. +** This routine is called by the parser while in the middle of
  6624. +** parsing a CREATE TABLE statement. The pFirst token is the first
  6625. +** token in the sequence of tokens that describe the type of the
  6626. +** column currently under construction. pLast is the last token
  6627. +** in the sequence. Use this information to construct a string
  6628. +** that contains the typename of the column and store that string
  6629. +** in zType.
  6630. +*/
  6631. +void sqliteAddColumnType(Parse *pParse, Token *pFirst, Token *pLast){
  6632. + Table *p;
  6633. + int i, j;
  6634. + int n;
  6635. + char *z, **pz;
  6636. + Column *pCol;
  6637. + if( (p = pParse->pNewTable)==0 ) return;
  6638. + i = p->nCol-1;
  6639. + if( i<0 ) return;
  6640. + pCol = &p->aCol[i];
  6641. + pz = &pCol->zType;
  6642. + n = pLast->n + Addr(pLast->z) - Addr(pFirst->z);
  6643. + sqliteSetNString(pz, pFirst->z, n, 0);
  6644. + z = *pz;
  6645. + if( z==0 ) return;
  6646. + for(i=j=0; z[i]; i++){
  6647. + int c = z[i];
  6648. + if( isspace(c) ) continue;
  6649. + z[j++] = c;
  6650. + }
  6651. + z[j] = 0;
  6652. + if( pParse->db->file_format>=4 ){
  6653. + pCol->sortOrder = sqliteCollateType(z, n);
  6654. + }else{
  6655. + pCol->sortOrder = SQLITE_SO_NUM;
  6656. + }
  6657. +}
  6658. +
  6659. +/*
  6660. +** The given token is the default value for the last column added to
  6661. +** the table currently under construction. If "minusFlag" is true, it
  6662. +** means the value token was preceded by a minus sign.
  6663. +**
  6664. +** This routine is called by the parser while in the middle of
  6665. +** parsing a CREATE TABLE statement.
  6666. +*/
  6667. +void sqliteAddDefaultValue(Parse *pParse, Token *pVal, int minusFlag){
  6668. + Table *p;
  6669. + int i;
  6670. + char **pz;
  6671. + if( (p = pParse->pNewTable)==0 ) return;
  6672. + i = p->nCol-1;
  6673. + if( i<0 ) return;
  6674. + pz = &p->aCol[i].zDflt;
  6675. + if( minusFlag ){
  6676. + sqliteSetNString(pz, "-", 1, pVal->z, pVal->n, 0);
  6677. + }else{
  6678. + sqliteSetNString(pz, pVal->z, pVal->n, 0);
  6679. + }
  6680. + sqliteDequote(*pz);
  6681. +}
  6682. +
  6683. +/*
  6684. +** Designate the PRIMARY KEY for the table. pList is a list of names
  6685. +** of columns that form the primary key. If pList is NULL, then the
  6686. +** most recently added column of the table is the primary key.
  6687. +**
  6688. +** A table can have at most one primary key. If the table already has
  6689. +** a primary key (and this is the second primary key) then create an
  6690. +** error.
  6691. +**
  6692. +** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  6693. +** then we will try to use that column as the row id. (Exception:
  6694. +** For backwards compatibility with older databases, do not do this
  6695. +** if the file format version number is less than 1.) Set the Table.iPKey
  6696. +** field of the table under construction to be the index of the
  6697. +** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  6698. +** no INTEGER PRIMARY KEY.
  6699. +**
  6700. +** If the key is not an INTEGER PRIMARY KEY, then create a unique
  6701. +** index for the key. No index is created for INTEGER PRIMARY KEYs.
  6702. +*/
  6703. +void sqliteAddPrimaryKey(Parse *pParse, IdList *pList, int onError){
  6704. + Table *pTab = pParse->pNewTable;
  6705. + char *zType = 0;
  6706. + int iCol = -1, i;
  6707. + if( pTab==0 ) goto primary_key_exit;
  6708. + if( pTab->hasPrimKey ){
  6709. + sqliteErrorMsg(pParse,
  6710. + "table \"%s\" has more than one primary key", pTab->zName);
  6711. + goto primary_key_exit;
  6712. + }
  6713. + pTab->hasPrimKey = 1;
  6714. + if( pList==0 ){
  6715. + iCol = pTab->nCol - 1;
  6716. + pTab->aCol[iCol].isPrimKey = 1;
  6717. + }else{
  6718. + for(i=0; i<pList->nId; i++){
  6719. + for(iCol=0; iCol<pTab->nCol; iCol++){
  6720. + if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ) break;
  6721. + }
  6722. + if( iCol<pTab->nCol ) pTab->aCol[iCol].isPrimKey = 1;
  6723. + }
  6724. + if( pList->nId>1 ) iCol = -1;
  6725. + }
  6726. + if( iCol>=0 && iCol<pTab->nCol ){
  6727. + zType = pTab->aCol[iCol].zType;
  6728. + }
  6729. + if( pParse->db->file_format>=1 &&
  6730. + zType && sqliteStrICmp(zType, "INTEGER")==0 ){
  6731. + pTab->iPKey = iCol;
  6732. + pTab->keyConf = onError;
  6733. + }else{
  6734. + sqliteCreateIndex(pParse, 0, 0, pList, onError, 0, 0);
  6735. + pList = 0;
  6736. + }
  6737. +
  6738. +primary_key_exit:
  6739. + sqliteIdListDelete(pList);
  6740. + return;
  6741. +}
  6742. +
  6743. +/*
  6744. +** Return the appropriate collating type given a type name.
  6745. +**
  6746. +** The collation type is text (SQLITE_SO_TEXT) if the type
  6747. +** name contains the character stream "text" or "blob" or
  6748. +** "clob". Any other type name is collated as numeric
  6749. +** (SQLITE_SO_NUM).
  6750. +*/
  6751. +int sqliteCollateType(const char *zType, int nType){
  6752. + int i;
  6753. + for(i=0; i<nType-3; i++){
  6754. + int c = *(zType++) | 0x60;
  6755. + if( (c=='b' || c=='c') && sqliteStrNICmp(zType, "lob", 3)==0 ){
  6756. + return SQLITE_SO_TEXT;
  6757. + }
  6758. + if( c=='c' && sqliteStrNICmp(zType, "har", 3)==0 ){
  6759. + return SQLITE_SO_TEXT;
  6760. + }
  6761. + if( c=='t' && sqliteStrNICmp(zType, "ext", 3)==0 ){
  6762. + return SQLITE_SO_TEXT;
  6763. + }
  6764. + }
  6765. + return SQLITE_SO_NUM;
  6766. +}
  6767. +
  6768. +/*
  6769. +** This routine is called by the parser while in the middle of
  6770. +** parsing a CREATE TABLE statement. A "COLLATE" clause has
  6771. +** been seen on a column. This routine sets the Column.sortOrder on
  6772. +** the column currently under construction.
  6773. +*/
  6774. +void sqliteAddCollateType(Parse *pParse, int collType){
  6775. + Table *p;
  6776. + int i;
  6777. + if( (p = pParse->pNewTable)==0 ) return;
  6778. + i = p->nCol-1;
  6779. + if( i>=0 ) p->aCol[i].sortOrder = collType;
  6780. +}
  6781. +
  6782. +/*
  6783. +** Come up with a new random value for the schema cookie. Make sure
  6784. +** the new value is different from the old.
  6785. +**
  6786. +** The schema cookie is used to determine when the schema for the
  6787. +** database changes. After each schema change, the cookie value
  6788. +** changes. When a process first reads the schema it records the
  6789. +** cookie. Thereafter, whenever it goes to access the database,
  6790. +** it checks the cookie to make sure the schema has not changed
  6791. +** since it was last read.
  6792. +**
  6793. +** This plan is not completely bullet-proof. It is possible for
  6794. +** the schema to change multiple times and for the cookie to be
  6795. +** set back to prior value. But schema changes are infrequent
  6796. +** and the probability of hitting the same cookie value is only
  6797. +** 1 chance in 2^32. So we're safe enough.
  6798. +*/
  6799. +void sqliteChangeCookie(sqlite *db, Vdbe *v){
  6800. + if( db->next_cookie==db->aDb[0].schema_cookie ){
  6801. + unsigned char r;
  6802. + sqliteRandomness(1, &r);
  6803. + db->next_cookie = db->aDb[0].schema_cookie + r + 1;
  6804. + db->flags |= SQLITE_InternChanges;
  6805. + sqliteVdbeAddOp(v, OP_Integer, db->next_cookie, 0);
  6806. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 0);
  6807. + }
  6808. +}
  6809. +
  6810. +/*
  6811. +** Measure the number of characters needed to output the given
  6812. +** identifier. The number returned includes any quotes used
  6813. +** but does not include the null terminator.
  6814. +*/
  6815. +static int identLength(const char *z){
  6816. + int n;
  6817. + int needQuote = 0;
  6818. + for(n=0; *z; n++, z++){
  6819. + if( *z=='\'' ){ n++; needQuote=1; }
  6820. + }
  6821. + return n + needQuote*2;
  6822. +}
  6823. +
  6824. +/*
  6825. +** Write an identifier onto the end of the given string. Add
  6826. +** quote characters as needed.
  6827. +*/
  6828. +static void identPut(char *z, int *pIdx, char *zIdent){
  6829. + int i, j, needQuote;
  6830. + i = *pIdx;
  6831. + for(j=0; zIdent[j]; j++){
  6832. + if( !isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  6833. + }
  6834. + needQuote = zIdent[j]!=0 || isdigit(zIdent[0])
  6835. + || sqliteKeywordCode(zIdent, j)!=TK_ID;
  6836. + if( needQuote ) z[i++] = '\'';
  6837. + for(j=0; zIdent[j]; j++){
  6838. + z[i++] = zIdent[j];
  6839. + if( zIdent[j]=='\'' ) z[i++] = '\'';
  6840. + }
  6841. + if( needQuote ) z[i++] = '\'';
  6842. + z[i] = 0;
  6843. + *pIdx = i;
  6844. +}
  6845. +
  6846. +/*
  6847. +** Generate a CREATE TABLE statement appropriate for the given
  6848. +** table. Memory to hold the text of the statement is obtained
  6849. +** from sqliteMalloc() and must be freed by the calling function.
  6850. +*/
  6851. +static char *createTableStmt(Table *p){
  6852. + int i, k, n;
  6853. + char *zStmt;
  6854. + char *zSep, *zSep2, *zEnd;
  6855. + n = 0;
  6856. + for(i=0; i<p->nCol; i++){
  6857. + n += identLength(p->aCol[i].zName);
  6858. + }
  6859. + n += identLength(p->zName);
  6860. + if( n<40 ){
  6861. + zSep = "";
  6862. + zSep2 = ",";
  6863. + zEnd = ")";
  6864. + }else{
  6865. + zSep = "\n ";
  6866. + zSep2 = ",\n ";
  6867. + zEnd = "\n)";
  6868. + }
  6869. + n += 35 + 6*p->nCol;
  6870. + zStmt = sqliteMallocRaw( n );
  6871. + if( zStmt==0 ) return 0;
  6872. + strcpy(zStmt, p->iDb==1 ? "CREATE TEMP TABLE " : "CREATE TABLE ");
  6873. + k = strlen(zStmt);
  6874. + identPut(zStmt, &k, p->zName);
  6875. + zStmt[k++] = '(';
  6876. + for(i=0; i<p->nCol; i++){
  6877. + strcpy(&zStmt[k], zSep);
  6878. + k += strlen(&zStmt[k]);
  6879. + zSep = zSep2;
  6880. + identPut(zStmt, &k, p->aCol[i].zName);
  6881. + }
  6882. + strcpy(&zStmt[k], zEnd);
  6883. + return zStmt;
  6884. +}
  6885. +
  6886. +/*
  6887. +** This routine is called to report the final ")" that terminates
  6888. +** a CREATE TABLE statement.
  6889. +**
  6890. +** The table structure that other action routines have been building
  6891. +** is added to the internal hash tables, assuming no errors have
  6892. +** occurred.
  6893. +**
  6894. +** An entry for the table is made in the master table on disk, unless
  6895. +** this is a temporary table or db->init.busy==1. When db->init.busy==1
  6896. +** it means we are reading the sqlite_master table because we just
  6897. +** connected to the database or because the sqlite_master table has
  6898. +** recently changes, so the entry for this table already exists in
  6899. +** the sqlite_master table. We do not want to create it again.
  6900. +**
  6901. +** If the pSelect argument is not NULL, it means that this routine
  6902. +** was called to create a table generated from a
  6903. +** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  6904. +** the new table will match the result set of the SELECT.
  6905. +*/
  6906. +void sqliteEndTable(Parse *pParse, Token *pEnd, Select *pSelect){
  6907. + Table *p;
  6908. + sqlite *db = pParse->db;
  6909. +
  6910. + if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite_malloc_failed ) return;
  6911. + p = pParse->pNewTable;
  6912. + if( p==0 ) return;
  6913. +
  6914. + /* If the table is generated from a SELECT, then construct the
  6915. + ** list of columns and the text of the table.
  6916. + */
  6917. + if( pSelect ){
  6918. + Table *pSelTab = sqliteResultSetOfSelect(pParse, 0, pSelect);
  6919. + if( pSelTab==0 ) return;
  6920. + assert( p->aCol==0 );
  6921. + p->nCol = pSelTab->nCol;
  6922. + p->aCol = pSelTab->aCol;
  6923. + pSelTab->nCol = 0;
  6924. + pSelTab->aCol = 0;
  6925. + sqliteDeleteTable(0, pSelTab);
  6926. + }
  6927. +
  6928. + /* If the db->init.busy is 1 it means we are reading the SQL off the
  6929. + ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  6930. + ** So do not write to the disk again. Extract the root page number
  6931. + ** for the table from the db->init.newTnum field. (The page number
  6932. + ** should have been put there by the sqliteOpenCb routine.)
  6933. + */
  6934. + if( db->init.busy ){
  6935. + p->tnum = db->init.newTnum;
  6936. + }
  6937. +
  6938. + /* If not initializing, then create a record for the new table
  6939. + ** in the SQLITE_MASTER table of the database. The record number
  6940. + ** for the new table entry should already be on the stack.
  6941. + **
  6942. + ** If this is a TEMPORARY table, write the entry into the auxiliary
  6943. + ** file instead of into the main database file.
  6944. + */
  6945. + if( !db->init.busy ){
  6946. + int n;
  6947. + Vdbe *v;
  6948. +
  6949. + v = sqliteGetVdbe(pParse);
  6950. + if( v==0 ) return;
  6951. + if( p->pSelect==0 ){
  6952. + /* A regular table */
  6953. + sqliteVdbeOp3(v, OP_CreateTable, 0, p->iDb, (char*)&p->tnum, P3_POINTER);
  6954. + }else{
  6955. + /* A view */
  6956. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  6957. + }
  6958. + p->tnum = 0;
  6959. + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
  6960. + sqliteVdbeOp3(v, OP_String, 0, 0, p->pSelect==0?"table":"view", P3_STATIC);
  6961. + sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
  6962. + sqliteVdbeOp3(v, OP_String, 0, 0, p->zName, 0);
  6963. + sqliteVdbeAddOp(v, OP_Dup, 4, 0);
  6964. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  6965. + if( pSelect ){
  6966. + char *z = createTableStmt(p);
  6967. + n = z ? strlen(z) : 0;
  6968. + sqliteVdbeChangeP3(v, -1, z, n);
  6969. + sqliteFree(z);
  6970. + }else{
  6971. + assert( pEnd!=0 );
  6972. + n = Addr(pEnd->z) - Addr(pParse->sFirstToken.z) + 1;
  6973. + sqliteVdbeChangeP3(v, -1, pParse->sFirstToken.z, n);
  6974. + }
  6975. + sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
  6976. + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
  6977. + if( !p->iDb ){
  6978. + sqliteChangeCookie(db, v);
  6979. + }
  6980. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  6981. + if( pSelect ){
  6982. + sqliteVdbeAddOp(v, OP_Integer, p->iDb, 0);
  6983. + sqliteVdbeAddOp(v, OP_OpenWrite, 1, 0);
  6984. + pParse->nTab = 2;
  6985. + sqliteSelect(pParse, pSelect, SRT_Table, 1, 0, 0, 0);
  6986. + }
  6987. + sqliteEndWriteOperation(pParse);
  6988. + }
  6989. +
  6990. + /* Add the table to the in-memory representation of the database.
  6991. + */
  6992. + if( pParse->explain==0 && pParse->nErr==0 ){
  6993. + Table *pOld;
  6994. + FKey *pFKey;
  6995. + pOld = sqliteHashInsert(&db->aDb[p->iDb].tblHash,
  6996. + p->zName, strlen(p->zName)+1, p);
  6997. + if( pOld ){
  6998. + assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  6999. + return;
  7000. + }
  7001. + for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  7002. + int nTo = strlen(pFKey->zTo) + 1;
  7003. + pFKey->pNextTo = sqliteHashFind(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo);
  7004. + sqliteHashInsert(&db->aDb[p->iDb].aFKey, pFKey->zTo, nTo, pFKey);
  7005. + }
  7006. + pParse->pNewTable = 0;
  7007. + db->nTable++;
  7008. + db->flags |= SQLITE_InternChanges;
  7009. + }
  7010. +}
  7011. +
  7012. +/*
  7013. +** The parser calls this routine in order to create a new VIEW
  7014. +*/
  7015. +void sqliteCreateView(
  7016. + Parse *pParse, /* The parsing context */
  7017. + Token *pBegin, /* The CREATE token that begins the statement */
  7018. + Token *pName, /* The token that holds the name of the view */
  7019. + Select *pSelect, /* A SELECT statement that will become the new view */
  7020. + int isTemp /* TRUE for a TEMPORARY view */
  7021. +){
  7022. + Table *p;
  7023. + int n;
  7024. + const char *z;
  7025. + Token sEnd;
  7026. + DbFixer sFix;
  7027. +
  7028. + sqliteStartTable(pParse, pBegin, pName, isTemp, 1);
  7029. + p = pParse->pNewTable;
  7030. + if( p==0 || pParse->nErr ){
  7031. + sqliteSelectDelete(pSelect);
  7032. + return;
  7033. + }
  7034. + if( sqliteFixInit(&sFix, pParse, p->iDb, "view", pName)
  7035. + && sqliteFixSelect(&sFix, pSelect)
  7036. + ){
  7037. + sqliteSelectDelete(pSelect);
  7038. + return;
  7039. + }
  7040. +
  7041. + /* Make a copy of the entire SELECT statement that defines the view.
  7042. + ** This will force all the Expr.token.z values to be dynamically
  7043. + ** allocated rather than point to the input string - which means that
  7044. + ** they will persist after the current sqlite_exec() call returns.
  7045. + */
  7046. + p->pSelect = sqliteSelectDup(pSelect);
  7047. + sqliteSelectDelete(pSelect);
  7048. + if( !pParse->db->init.busy ){
  7049. + sqliteViewGetColumnNames(pParse, p);
  7050. + }
  7051. +
  7052. + /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  7053. + ** the end.
  7054. + */
  7055. + sEnd = pParse->sLastToken;
  7056. + if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){
  7057. + sEnd.z += sEnd.n;
  7058. + }
  7059. + sEnd.n = 0;
  7060. + n = sEnd.z - pBegin->z;
  7061. + z = pBegin->z;
  7062. + while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; }
  7063. + sEnd.z = &z[n-1];
  7064. + sEnd.n = 1;
  7065. +
  7066. + /* Use sqliteEndTable() to add the view to the SQLITE_MASTER table */
  7067. + sqliteEndTable(pParse, &sEnd, 0);
  7068. + return;
  7069. +}
  7070. +
  7071. +/*
  7072. +** The Table structure pTable is really a VIEW. Fill in the names of
  7073. +** the columns of the view in the pTable structure. Return the number
  7074. +** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  7075. +*/
  7076. +int sqliteViewGetColumnNames(Parse *pParse, Table *pTable){
  7077. + ExprList *pEList;
  7078. + Select *pSel;
  7079. + Table *pSelTab;
  7080. + int nErr = 0;
  7081. +
  7082. + assert( pTable );
  7083. +
  7084. + /* A positive nCol means the columns names for this view are
  7085. + ** already known.
  7086. + */
  7087. + if( pTable->nCol>0 ) return 0;
  7088. +
  7089. + /* A negative nCol is a special marker meaning that we are currently
  7090. + ** trying to compute the column names. If we enter this routine with
  7091. + ** a negative nCol, it means two or more views form a loop, like this:
  7092. + **
  7093. + ** CREATE VIEW one AS SELECT * FROM two;
  7094. + ** CREATE VIEW two AS SELECT * FROM one;
  7095. + **
  7096. + ** Actually, this error is caught previously and so the following test
  7097. + ** should always fail. But we will leave it in place just to be safe.
  7098. + */
  7099. + if( pTable->nCol<0 ){
  7100. + sqliteErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  7101. + return 1;
  7102. + }
  7103. +
  7104. + /* If we get this far, it means we need to compute the table names.
  7105. + */
  7106. + assert( pTable->pSelect ); /* If nCol==0, then pTable must be a VIEW */
  7107. + pSel = pTable->pSelect;
  7108. +
  7109. + /* Note that the call to sqliteResultSetOfSelect() will expand any
  7110. + ** "*" elements in this list. But we will need to restore the list
  7111. + ** back to its original configuration afterwards, so we save a copy of
  7112. + ** the original in pEList.
  7113. + */
  7114. + pEList = pSel->pEList;
  7115. + pSel->pEList = sqliteExprListDup(pEList);
  7116. + if( pSel->pEList==0 ){
  7117. + pSel->pEList = pEList;
  7118. + return 1; /* Malloc failed */
  7119. + }
  7120. + pTable->nCol = -1;
  7121. + pSelTab = sqliteResultSetOfSelect(pParse, 0, pSel);
  7122. + if( pSelTab ){
  7123. + assert( pTable->aCol==0 );
  7124. + pTable->nCol = pSelTab->nCol;
  7125. + pTable->aCol = pSelTab->aCol;
  7126. + pSelTab->nCol = 0;
  7127. + pSelTab->aCol = 0;
  7128. + sqliteDeleteTable(0, pSelTab);
  7129. + DbSetProperty(pParse->db, pTable->iDb, DB_UnresetViews);
  7130. + }else{
  7131. + pTable->nCol = 0;
  7132. + nErr++;
  7133. + }
  7134. + sqliteSelectUnbind(pSel);
  7135. + sqliteExprListDelete(pSel->pEList);
  7136. + pSel->pEList = pEList;
  7137. + return nErr;
  7138. +}
  7139. +
  7140. +/*
  7141. +** Clear the column names from the VIEW pTable.
  7142. +**
  7143. +** This routine is called whenever any other table or view is modified.
  7144. +** The view passed into this routine might depend directly or indirectly
  7145. +** on the modified or deleted table so we need to clear the old column
  7146. +** names so that they will be recomputed.
  7147. +*/
  7148. +static void sqliteViewResetColumnNames(Table *pTable){
  7149. + int i;
  7150. + Column *pCol;
  7151. + assert( pTable!=0 && pTable->pSelect!=0 );
  7152. + for(i=0, pCol=pTable->aCol; i<pTable->nCol; i++, pCol++){
  7153. + sqliteFree(pCol->zName);
  7154. + sqliteFree(pCol->zDflt);
  7155. + sqliteFree(pCol->zType);
  7156. + }
  7157. + sqliteFree(pTable->aCol);
  7158. + pTable->aCol = 0;
  7159. + pTable->nCol = 0;
  7160. +}
  7161. +
  7162. +/*
  7163. +** Clear the column names from every VIEW in database idx.
  7164. +*/
  7165. +static void sqliteViewResetAll(sqlite *db, int idx){
  7166. + HashElem *i;
  7167. + if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  7168. + for(i=sqliteHashFirst(&db->aDb[idx].tblHash); i; i=sqliteHashNext(i)){
  7169. + Table *pTab = sqliteHashData(i);
  7170. + if( pTab->pSelect ){
  7171. + sqliteViewResetColumnNames(pTab);
  7172. + }
  7173. + }
  7174. + DbClearProperty(db, idx, DB_UnresetViews);
  7175. +}
  7176. +
  7177. +/*
  7178. +** Given a token, look up a table with that name. If not found, leave
  7179. +** an error for the parser to find and return NULL.
  7180. +*/
  7181. +Table *sqliteTableFromToken(Parse *pParse, Token *pTok){
  7182. + char *zName;
  7183. + Table *pTab;
  7184. + zName = sqliteTableNameFromToken(pTok);
  7185. + if( zName==0 ) return 0;
  7186. + pTab = sqliteFindTable(pParse->db, zName, 0);
  7187. + sqliteFree(zName);
  7188. + if( pTab==0 ){
  7189. + sqliteErrorMsg(pParse, "no such table: %T", pTok);
  7190. + }
  7191. + return pTab;
  7192. +}
  7193. +
  7194. +/*
  7195. +** This routine is called to do the work of a DROP TABLE statement.
  7196. +** pName is the name of the table to be dropped.
  7197. +*/
  7198. +void sqliteDropTable(Parse *pParse, Token *pName, int isView){
  7199. + Table *pTable;
  7200. + Vdbe *v;
  7201. + int base;
  7202. + sqlite *db = pParse->db;
  7203. + int iDb;
  7204. +
  7205. + if( pParse->nErr || sqlite_malloc_failed ) return;
  7206. + pTable = sqliteTableFromToken(pParse, pName);
  7207. + if( pTable==0 ) return;
  7208. + iDb = pTable->iDb;
  7209. + assert( iDb>=0 && iDb<db->nDb );
  7210. +#ifndef SQLITE_OMIT_AUTHORIZATION
  7211. + {
  7212. + int code;
  7213. + const char *zTab = SCHEMA_TABLE(pTable->iDb);
  7214. + const char *zDb = db->aDb[pTable->iDb].zName;
  7215. + if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  7216. + return;
  7217. + }
  7218. + if( isView ){
  7219. + if( iDb==1 ){
  7220. + code = SQLITE_DROP_TEMP_VIEW;
  7221. + }else{
  7222. + code = SQLITE_DROP_VIEW;
  7223. + }
  7224. + }else{
  7225. + if( iDb==1 ){
  7226. + code = SQLITE_DROP_TEMP_TABLE;
  7227. + }else{
  7228. + code = SQLITE_DROP_TABLE;
  7229. + }
  7230. + }
  7231. + if( sqliteAuthCheck(pParse, code, pTable->zName, 0, zDb) ){
  7232. + return;
  7233. + }
  7234. + if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTable->zName, 0, zDb) ){
  7235. + return;
  7236. + }
  7237. + }
  7238. +#endif
  7239. + if( pTable->readOnly ){
  7240. + sqliteErrorMsg(pParse, "table %s may not be dropped", pTable->zName);
  7241. + pParse->nErr++;
  7242. + return;
  7243. + }
  7244. + if( isView && pTable->pSelect==0 ){
  7245. + sqliteErrorMsg(pParse, "use DROP TABLE to delete table %s", pTable->zName);
  7246. + return;
  7247. + }
  7248. + if( !isView && pTable->pSelect ){
  7249. + sqliteErrorMsg(pParse, "use DROP VIEW to delete view %s", pTable->zName);
  7250. + return;
  7251. + }
  7252. +
  7253. + /* Generate code to remove the table from the master table
  7254. + ** on disk.
  7255. + */
  7256. + v = sqliteGetVdbe(pParse);
  7257. + if( v ){
  7258. + static VdbeOpList dropTable[] = {
  7259. + { OP_Rewind, 0, ADDR(8), 0},
  7260. + { OP_String, 0, 0, 0}, /* 1 */
  7261. + { OP_MemStore, 1, 1, 0},
  7262. + { OP_MemLoad, 1, 0, 0}, /* 3 */
  7263. + { OP_Column, 0, 2, 0},
  7264. + { OP_Ne, 0, ADDR(7), 0},
  7265. + { OP_Delete, 0, 0, 0},
  7266. + { OP_Next, 0, ADDR(3), 0}, /* 7 */
  7267. + };
  7268. + Index *pIdx;
  7269. + Trigger *pTrigger;
  7270. + sqliteBeginWriteOperation(pParse, 0, pTable->iDb);
  7271. +
  7272. + /* Drop all triggers associated with the table being dropped */
  7273. + pTrigger = pTable->pTrigger;
  7274. + while( pTrigger ){
  7275. + assert( pTrigger->iDb==pTable->iDb || pTrigger->iDb==1 );
  7276. + sqliteDropTriggerPtr(pParse, pTrigger, 1);
  7277. + if( pParse->explain ){
  7278. + pTrigger = pTrigger->pNext;
  7279. + }else{
  7280. + pTrigger = pTable->pTrigger;
  7281. + }
  7282. + }
  7283. +
  7284. + /* Drop all SQLITE_MASTER entries that refer to the table */
  7285. + sqliteOpenMasterTable(v, pTable->iDb);
  7286. + base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
  7287. + sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
  7288. +
  7289. + /* Drop all SQLITE_TEMP_MASTER entries that refer to the table */
  7290. + if( pTable->iDb!=1 ){
  7291. + sqliteOpenMasterTable(v, 1);
  7292. + base = sqliteVdbeAddOpList(v, ArraySize(dropTable), dropTable);
  7293. + sqliteVdbeChangeP3(v, base+1, pTable->zName, 0);
  7294. + }
  7295. +
  7296. + if( pTable->iDb==0 ){
  7297. + sqliteChangeCookie(db, v);
  7298. + }
  7299. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  7300. + if( !isView ){
  7301. + sqliteVdbeAddOp(v, OP_Destroy, pTable->tnum, pTable->iDb);
  7302. + for(pIdx=pTable->pIndex; pIdx; pIdx=pIdx->pNext){
  7303. + sqliteVdbeAddOp(v, OP_Destroy, pIdx->tnum, pIdx->iDb);
  7304. + }
  7305. + }
  7306. + sqliteEndWriteOperation(pParse);
  7307. + }
  7308. +
  7309. + /* Delete the in-memory description of the table.
  7310. + **
  7311. + ** Exception: if the SQL statement began with the EXPLAIN keyword,
  7312. + ** then no changes should be made.
  7313. + */
  7314. + if( !pParse->explain ){
  7315. + sqliteUnlinkAndDeleteTable(db, pTable);
  7316. + db->flags |= SQLITE_InternChanges;
  7317. + }
  7318. + sqliteViewResetAll(db, iDb);
  7319. +}
  7320. +
  7321. +/*
  7322. +** This routine constructs a P3 string suitable for an OP_MakeIdxKey
  7323. +** opcode and adds that P3 string to the most recently inserted instruction
  7324. +** in the virtual machine. The P3 string consists of a single character
  7325. +** for each column in the index pIdx of table pTab. If the column uses
  7326. +** a numeric sort order, then the P3 string character corresponding to
  7327. +** that column is 'n'. If the column uses a text sort order, then the
  7328. +** P3 string is 't'. See the OP_MakeIdxKey opcode documentation for
  7329. +** additional information. See also the sqliteAddKeyType() routine.
  7330. +*/
  7331. +void sqliteAddIdxKeyType(Vdbe *v, Index *pIdx){
  7332. + char *zType;
  7333. + Table *pTab;
  7334. + int i, n;
  7335. + assert( pIdx!=0 && pIdx->pTable!=0 );
  7336. + pTab = pIdx->pTable;
  7337. + n = pIdx->nColumn;
  7338. + zType = sqliteMallocRaw( n+1 );
  7339. + if( zType==0 ) return;
  7340. + for(i=0; i<n; i++){
  7341. + int iCol = pIdx->aiColumn[i];
  7342. + assert( iCol>=0 && iCol<pTab->nCol );
  7343. + if( (pTab->aCol[iCol].sortOrder & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
  7344. + zType[i] = 't';
  7345. + }else{
  7346. + zType[i] = 'n';
  7347. + }
  7348. + }
  7349. + zType[n] = 0;
  7350. + sqliteVdbeChangeP3(v, -1, zType, n);
  7351. + sqliteFree(zType);
  7352. +}
  7353. +
  7354. +/*
  7355. +** This routine is called to create a new foreign key on the table
  7356. +** currently under construction. pFromCol determines which columns
  7357. +** in the current table point to the foreign key. If pFromCol==0 then
  7358. +** connect the key to the last column inserted. pTo is the name of
  7359. +** the table referred to. pToCol is a list of tables in the other
  7360. +** pTo table that the foreign key points to. flags contains all
  7361. +** information about the conflict resolution algorithms specified
  7362. +** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  7363. +**
  7364. +** An FKey structure is created and added to the table currently
  7365. +** under construction in the pParse->pNewTable field. The new FKey
  7366. +** is not linked into db->aFKey at this point - that does not happen
  7367. +** until sqliteEndTable().
  7368. +**
  7369. +** The foreign key is set for IMMEDIATE processing. A subsequent call
  7370. +** to sqliteDeferForeignKey() might change this to DEFERRED.
  7371. +*/
  7372. +void sqliteCreateForeignKey(
  7373. + Parse *pParse, /* Parsing context */
  7374. + IdList *pFromCol, /* Columns in this table that point to other table */
  7375. + Token *pTo, /* Name of the other table */
  7376. + IdList *pToCol, /* Columns in the other table */
  7377. + int flags /* Conflict resolution algorithms. */
  7378. +){
  7379. + Table *p = pParse->pNewTable;
  7380. + int nByte;
  7381. + int i;
  7382. + int nCol;
  7383. + char *z;
  7384. + FKey *pFKey = 0;
  7385. +
  7386. + assert( pTo!=0 );
  7387. + if( p==0 || pParse->nErr ) goto fk_end;
  7388. + if( pFromCol==0 ){
  7389. + int iCol = p->nCol-1;
  7390. + if( iCol<0 ) goto fk_end;
  7391. + if( pToCol && pToCol->nId!=1 ){
  7392. + sqliteErrorMsg(pParse, "foreign key on %s"
  7393. + " should reference only one column of table %T",
  7394. + p->aCol[iCol].zName, pTo);
  7395. + goto fk_end;
  7396. + }
  7397. + nCol = 1;
  7398. + }else if( pToCol && pToCol->nId!=pFromCol->nId ){
  7399. + sqliteErrorMsg(pParse,
  7400. + "number of columns in foreign key does not match the number of "
  7401. + "columns in the referenced table");
  7402. + goto fk_end;
  7403. + }else{
  7404. + nCol = pFromCol->nId;
  7405. + }
  7406. + nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  7407. + if( pToCol ){
  7408. + for(i=0; i<pToCol->nId; i++){
  7409. + nByte += strlen(pToCol->a[i].zName) + 1;
  7410. + }
  7411. + }
  7412. + pFKey = sqliteMalloc( nByte );
  7413. + if( pFKey==0 ) goto fk_end;
  7414. + pFKey->pFrom = p;
  7415. + pFKey->pNextFrom = p->pFKey;
  7416. + z = (char*)&pFKey[1];
  7417. + pFKey->aCol = (struct sColMap*)z;
  7418. + z += sizeof(struct sColMap)*nCol;
  7419. + pFKey->zTo = z;
  7420. + memcpy(z, pTo->z, pTo->n);
  7421. + z[pTo->n] = 0;
  7422. + z += pTo->n+1;
  7423. + pFKey->pNextTo = 0;
  7424. + pFKey->nCol = nCol;
  7425. + if( pFromCol==0 ){
  7426. + pFKey->aCol[0].iFrom = p->nCol-1;
  7427. + }else{
  7428. + for(i=0; i<nCol; i++){
  7429. + int j;
  7430. + for(j=0; j<p->nCol; j++){
  7431. + if( sqliteStrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  7432. + pFKey->aCol[i].iFrom = j;
  7433. + break;
  7434. + }
  7435. + }
  7436. + if( j>=p->nCol ){
  7437. + sqliteErrorMsg(pParse,
  7438. + "unknown column \"%s\" in foreign key definition",
  7439. + pFromCol->a[i].zName);
  7440. + goto fk_end;
  7441. + }
  7442. + }
  7443. + }
  7444. + if( pToCol ){
  7445. + for(i=0; i<nCol; i++){
  7446. + int n = strlen(pToCol->a[i].zName);
  7447. + pFKey->aCol[i].zCol = z;
  7448. + memcpy(z, pToCol->a[i].zName, n);
  7449. + z[n] = 0;
  7450. + z += n+1;
  7451. + }
  7452. + }
  7453. + pFKey->isDeferred = 0;
  7454. + pFKey->deleteConf = flags & 0xff;
  7455. + pFKey->updateConf = (flags >> 8 ) & 0xff;
  7456. + pFKey->insertConf = (flags >> 16 ) & 0xff;
  7457. +
  7458. + /* Link the foreign key to the table as the last step.
  7459. + */
  7460. + p->pFKey = pFKey;
  7461. + pFKey = 0;
  7462. +
  7463. +fk_end:
  7464. + sqliteFree(pFKey);
  7465. + sqliteIdListDelete(pFromCol);
  7466. + sqliteIdListDelete(pToCol);
  7467. +}
  7468. +
  7469. +/*
  7470. +** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  7471. +** clause is seen as part of a foreign key definition. The isDeferred
  7472. +** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  7473. +** The behavior of the most recently created foreign key is adjusted
  7474. +** accordingly.
  7475. +*/
  7476. +void sqliteDeferForeignKey(Parse *pParse, int isDeferred){
  7477. + Table *pTab;
  7478. + FKey *pFKey;
  7479. + if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  7480. + pFKey->isDeferred = isDeferred;
  7481. +}
  7482. +
  7483. +/*
  7484. +** Create a new index for an SQL table. pIndex is the name of the index
  7485. +** and pTable is the name of the table that is to be indexed. Both will
  7486. +** be NULL for a primary key or an index that is created to satisfy a
  7487. +** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  7488. +** as the table to be indexed. pParse->pNewTable is a table that is
  7489. +** currently being constructed by a CREATE TABLE statement.
  7490. +**
  7491. +** pList is a list of columns to be indexed. pList will be NULL if this
  7492. +** is a primary key or unique-constraint on the most recent column added
  7493. +** to the table currently under construction.
  7494. +*/
  7495. +void sqliteCreateIndex(
  7496. + Parse *pParse, /* All information about this parse */
  7497. + Token *pName, /* Name of the index. May be NULL */
  7498. + SrcList *pTable, /* Name of the table to index. Use pParse->pNewTable if 0 */
  7499. + IdList *pList, /* A list of columns to be indexed */
  7500. + int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  7501. + Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */
  7502. + Token *pEnd /* The ")" that closes the CREATE INDEX statement */
  7503. +){
  7504. + Table *pTab; /* Table to be indexed */
  7505. + Index *pIndex; /* The index to be created */
  7506. + char *zName = 0;
  7507. + int i, j;
  7508. + Token nullId; /* Fake token for an empty ID list */
  7509. + DbFixer sFix; /* For assigning database names to pTable */
  7510. + int isTemp; /* True for a temporary index */
  7511. + sqlite *db = pParse->db;
  7512. +
  7513. + if( pParse->nErr || sqlite_malloc_failed ) goto exit_create_index;
  7514. + if( db->init.busy
  7515. + && sqliteFixInit(&sFix, pParse, db->init.iDb, "index", pName)
  7516. + && sqliteFixSrcList(&sFix, pTable)
  7517. + ){
  7518. + goto exit_create_index;
  7519. + }
  7520. +
  7521. + /*
  7522. + ** Find the table that is to be indexed. Return early if not found.
  7523. + */
  7524. + if( pTable!=0 ){
  7525. + assert( pName!=0 );
  7526. + assert( pTable->nSrc==1 );
  7527. + pTab = sqliteSrcListLookup(pParse, pTable);
  7528. + }else{
  7529. + assert( pName==0 );
  7530. + pTab = pParse->pNewTable;
  7531. + }
  7532. + if( pTab==0 || pParse->nErr ) goto exit_create_index;
  7533. + if( pTab->readOnly ){
  7534. + sqliteErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  7535. + goto exit_create_index;
  7536. + }
  7537. + if( pTab->iDb>=2 && db->init.busy==0 ){
  7538. + sqliteErrorMsg(pParse, "table %s may not have indices added", pTab->zName);
  7539. + goto exit_create_index;
  7540. + }
  7541. + if( pTab->pSelect ){
  7542. + sqliteErrorMsg(pParse, "views may not be indexed");
  7543. + goto exit_create_index;
  7544. + }
  7545. + isTemp = pTab->iDb==1;
  7546. +
  7547. + /*
  7548. + ** Find the name of the index. Make sure there is not already another
  7549. + ** index or table with the same name.
  7550. + **
  7551. + ** Exception: If we are reading the names of permanent indices from the
  7552. + ** sqlite_master table (because some other process changed the schema) and
  7553. + ** one of the index names collides with the name of a temporary table or
  7554. + ** index, then we will continue to process this index.
  7555. + **
  7556. + ** If pName==0 it means that we are
  7557. + ** dealing with a primary key or UNIQUE constraint. We have to invent our
  7558. + ** own name.
  7559. + */
  7560. + if( pName && !db->init.busy ){
  7561. + Index *pISameName; /* Another index with the same name */
  7562. + Table *pTSameName; /* A table with same name as the index */
  7563. + zName = sqliteTableNameFromToken(pName);
  7564. + if( zName==0 ) goto exit_create_index;
  7565. + if( (pISameName = sqliteFindIndex(db, zName, 0))!=0 ){
  7566. + sqliteErrorMsg(pParse, "index %s already exists", zName);
  7567. + goto exit_create_index;
  7568. + }
  7569. + if( (pTSameName = sqliteFindTable(db, zName, 0))!=0 ){
  7570. + sqliteErrorMsg(pParse, "there is already a table named %s", zName);
  7571. + goto exit_create_index;
  7572. + }
  7573. + }else if( pName==0 ){
  7574. + char zBuf[30];
  7575. + int n;
  7576. + Index *pLoop;
  7577. + for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  7578. + sprintf(zBuf,"%d)",n);
  7579. + zName = 0;
  7580. + sqliteSetString(&zName, "(", pTab->zName, " autoindex ", zBuf, (char*)0);
  7581. + if( zName==0 ) goto exit_create_index;
  7582. + }else{
  7583. + zName = sqliteTableNameFromToken(pName);
  7584. + }
  7585. +
  7586. + /* Check for authorization to create an index.
  7587. + */
  7588. +#ifndef SQLITE_OMIT_AUTHORIZATION
  7589. + {
  7590. + const char *zDb = db->aDb[pTab->iDb].zName;
  7591. +
  7592. + assert( pTab->iDb==db->init.iDb || isTemp );
  7593. + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  7594. + goto exit_create_index;
  7595. + }
  7596. + i = SQLITE_CREATE_INDEX;
  7597. + if( isTemp ) i = SQLITE_CREATE_TEMP_INDEX;
  7598. + if( sqliteAuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  7599. + goto exit_create_index;
  7600. + }
  7601. + }
  7602. +#endif
  7603. +
  7604. + /* If pList==0, it means this routine was called to make a primary
  7605. + ** key out of the last column added to the table under construction.
  7606. + ** So create a fake list to simulate this.
  7607. + */
  7608. + if( pList==0 ){
  7609. + nullId.z = pTab->aCol[pTab->nCol-1].zName;
  7610. + nullId.n = strlen(nullId.z);
  7611. + pList = sqliteIdListAppend(0, &nullId);
  7612. + if( pList==0 ) goto exit_create_index;
  7613. + }
  7614. +
  7615. + /*
  7616. + ** Allocate the index structure.
  7617. + */
  7618. + pIndex = sqliteMalloc( sizeof(Index) + strlen(zName) + 1 +
  7619. + sizeof(int)*pList->nId );
  7620. + if( pIndex==0 ) goto exit_create_index;
  7621. + pIndex->aiColumn = (int*)&pIndex[1];
  7622. + pIndex->zName = (char*)&pIndex->aiColumn[pList->nId];
  7623. + strcpy(pIndex->zName, zName);
  7624. + pIndex->pTable = pTab;
  7625. + pIndex->nColumn = pList->nId;
  7626. + pIndex->onError = onError;
  7627. + pIndex->autoIndex = pName==0;
  7628. + pIndex->iDb = isTemp ? 1 : db->init.iDb;
  7629. +
  7630. + /* Scan the names of the columns of the table to be indexed and
  7631. + ** load the column indices into the Index structure. Report an error
  7632. + ** if any column is not found.
  7633. + */
  7634. + for(i=0; i<pList->nId; i++){
  7635. + for(j=0; j<pTab->nCol; j++){
  7636. + if( sqliteStrICmp(pList->a[i].zName, pTab->aCol[j].zName)==0 ) break;
  7637. + }
  7638. + if( j>=pTab->nCol ){
  7639. + sqliteErrorMsg(pParse, "table %s has no column named %s",
  7640. + pTab->zName, pList->a[i].zName);
  7641. + sqliteFree(pIndex);
  7642. + goto exit_create_index;
  7643. + }
  7644. + pIndex->aiColumn[i] = j;
  7645. + }
  7646. +
  7647. + /* Link the new Index structure to its table and to the other
  7648. + ** in-memory database structures.
  7649. + */
  7650. + if( !pParse->explain ){
  7651. + Index *p;
  7652. + p = sqliteHashInsert(&db->aDb[pIndex->iDb].idxHash,
  7653. + pIndex->zName, strlen(pIndex->zName)+1, pIndex);
  7654. + if( p ){
  7655. + assert( p==pIndex ); /* Malloc must have failed */
  7656. + sqliteFree(pIndex);
  7657. + goto exit_create_index;
  7658. + }
  7659. + db->flags |= SQLITE_InternChanges;
  7660. + }
  7661. +
  7662. + /* When adding an index to the list of indices for a table, make
  7663. + ** sure all indices labeled OE_Replace come after all those labeled
  7664. + ** OE_Ignore. This is necessary for the correct operation of UPDATE
  7665. + ** and INSERT.
  7666. + */
  7667. + if( onError!=OE_Replace || pTab->pIndex==0
  7668. + || pTab->pIndex->onError==OE_Replace){
  7669. + pIndex->pNext = pTab->pIndex;
  7670. + pTab->pIndex = pIndex;
  7671. + }else{
  7672. + Index *pOther = pTab->pIndex;
  7673. + while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  7674. + pOther = pOther->pNext;
  7675. + }
  7676. + pIndex->pNext = pOther->pNext;
  7677. + pOther->pNext = pIndex;
  7678. + }
  7679. +
  7680. + /* If the db->init.busy is 1 it means we are reading the SQL off the
  7681. + ** "sqlite_master" table on the disk. So do not write to the disk
  7682. + ** again. Extract the table number from the db->init.newTnum field.
  7683. + */
  7684. + if( db->init.busy && pTable!=0 ){
  7685. + pIndex->tnum = db->init.newTnum;
  7686. + }
  7687. +
  7688. + /* If the db->init.busy is 0 then create the index on disk. This
  7689. + ** involves writing the index into the master table and filling in the
  7690. + ** index with the current table contents.
  7691. + **
  7692. + ** The db->init.busy is 0 when the user first enters a CREATE INDEX
  7693. + ** command. db->init.busy is 1 when a database is opened and
  7694. + ** CREATE INDEX statements are read out of the master table. In
  7695. + ** the latter case the index already exists on disk, which is why
  7696. + ** we don't want to recreate it.
  7697. + **
  7698. + ** If pTable==0 it means this index is generated as a primary key
  7699. + ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
  7700. + ** has just been created, it contains no data and the index initialization
  7701. + ** step can be skipped.
  7702. + */
  7703. + else if( db->init.busy==0 ){
  7704. + int n;
  7705. + Vdbe *v;
  7706. + int lbl1, lbl2;
  7707. + int i;
  7708. + int addr;
  7709. +
  7710. + v = sqliteGetVdbe(pParse);
  7711. + if( v==0 ) goto exit_create_index;
  7712. + if( pTable!=0 ){
  7713. + sqliteBeginWriteOperation(pParse, 0, isTemp);
  7714. + sqliteOpenMasterTable(v, isTemp);
  7715. + }
  7716. + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
  7717. + sqliteVdbeOp3(v, OP_String, 0, 0, "index", P3_STATIC);
  7718. + sqliteVdbeOp3(v, OP_String, 0, 0, pIndex->zName, 0);
  7719. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->zName, 0);
  7720. + sqliteVdbeOp3(v, OP_CreateIndex, 0, isTemp,(char*)&pIndex->tnum,P3_POINTER);
  7721. + pIndex->tnum = 0;
  7722. + if( pTable ){
  7723. + sqliteVdbeCode(v,
  7724. + OP_Dup, 0, 0,
  7725. + OP_Integer, isTemp, 0,
  7726. + OP_OpenWrite, 1, 0,
  7727. + 0);
  7728. + }
  7729. + addr = sqliteVdbeAddOp(v, OP_String, 0, 0);
  7730. + if( pStart && pEnd ){
  7731. + n = Addr(pEnd->z) - Addr(pStart->z) + 1;
  7732. + sqliteVdbeChangeP3(v, addr, pStart->z, n);
  7733. + }
  7734. + sqliteVdbeAddOp(v, OP_MakeRecord, 5, 0);
  7735. + sqliteVdbeAddOp(v, OP_PutIntKey, 0, 0);
  7736. + if( pTable ){
  7737. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  7738. + sqliteVdbeOp3(v, OP_OpenRead, 2, pTab->tnum, pTab->zName, 0);
  7739. + lbl2 = sqliteVdbeMakeLabel(v);
  7740. + sqliteVdbeAddOp(v, OP_Rewind, 2, lbl2);
  7741. + lbl1 = sqliteVdbeAddOp(v, OP_Recno, 2, 0);
  7742. + for(i=0; i<pIndex->nColumn; i++){
  7743. + int iCol = pIndex->aiColumn[i];
  7744. + if( pTab->iPKey==iCol ){
  7745. + sqliteVdbeAddOp(v, OP_Dup, i, 0);
  7746. + }else{
  7747. + sqliteVdbeAddOp(v, OP_Column, 2, iCol);
  7748. + }
  7749. + }
  7750. + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIndex->nColumn, 0);
  7751. + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIndex);
  7752. + sqliteVdbeOp3(v, OP_IdxPut, 1, pIndex->onError!=OE_None,
  7753. + "indexed columns are not unique", P3_STATIC);
  7754. + sqliteVdbeAddOp(v, OP_Next, 2, lbl1);
  7755. + sqliteVdbeResolveLabel(v, lbl2);
  7756. + sqliteVdbeAddOp(v, OP_Close, 2, 0);
  7757. + sqliteVdbeAddOp(v, OP_Close, 1, 0);
  7758. + }
  7759. + if( pTable!=0 ){
  7760. + if( !isTemp ){
  7761. + sqliteChangeCookie(db, v);
  7762. + }
  7763. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  7764. + sqliteEndWriteOperation(pParse);
  7765. + }
  7766. + }
  7767. +
  7768. + /* Clean up before exiting */
  7769. +exit_create_index:
  7770. + sqliteIdListDelete(pList);
  7771. + sqliteSrcListDelete(pTable);
  7772. + sqliteFree(zName);
  7773. + return;
  7774. +}
  7775. +
  7776. +/*
  7777. +** This routine will drop an existing named index. This routine
  7778. +** implements the DROP INDEX statement.
  7779. +*/
  7780. +void sqliteDropIndex(Parse *pParse, SrcList *pName){
  7781. + Index *pIndex;
  7782. + Vdbe *v;
  7783. + sqlite *db = pParse->db;
  7784. +
  7785. + if( pParse->nErr || sqlite_malloc_failed ) return;
  7786. + assert( pName->nSrc==1 );
  7787. + pIndex = sqliteFindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  7788. + if( pIndex==0 ){
  7789. + sqliteErrorMsg(pParse, "no such index: %S", pName, 0);
  7790. + goto exit_drop_index;
  7791. + }
  7792. + if( pIndex->autoIndex ){
  7793. + sqliteErrorMsg(pParse, "index associated with UNIQUE "
  7794. + "or PRIMARY KEY constraint cannot be dropped", 0);
  7795. + goto exit_drop_index;
  7796. + }
  7797. + if( pIndex->iDb>1 ){
  7798. + sqliteErrorMsg(pParse, "cannot alter schema of attached "
  7799. + "databases", 0);
  7800. + goto exit_drop_index;
  7801. + }
  7802. +#ifndef SQLITE_OMIT_AUTHORIZATION
  7803. + {
  7804. + int code = SQLITE_DROP_INDEX;
  7805. + Table *pTab = pIndex->pTable;
  7806. + const char *zDb = db->aDb[pIndex->iDb].zName;
  7807. + const char *zTab = SCHEMA_TABLE(pIndex->iDb);
  7808. + if( sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  7809. + goto exit_drop_index;
  7810. + }
  7811. + if( pIndex->iDb ) code = SQLITE_DROP_TEMP_INDEX;
  7812. + if( sqliteAuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  7813. + goto exit_drop_index;
  7814. + }
  7815. + }
  7816. +#endif
  7817. +
  7818. + /* Generate code to remove the index and from the master table */
  7819. + v = sqliteGetVdbe(pParse);
  7820. + if( v ){
  7821. + static VdbeOpList dropIndex[] = {
  7822. + { OP_Rewind, 0, ADDR(9), 0},
  7823. + { OP_String, 0, 0, 0}, /* 1 */
  7824. + { OP_MemStore, 1, 1, 0},
  7825. + { OP_MemLoad, 1, 0, 0}, /* 3 */
  7826. + { OP_Column, 0, 1, 0},
  7827. + { OP_Eq, 0, ADDR(8), 0},
  7828. + { OP_Next, 0, ADDR(3), 0},
  7829. + { OP_Goto, 0, ADDR(9), 0},
  7830. + { OP_Delete, 0, 0, 0}, /* 8 */
  7831. + };
  7832. + int base;
  7833. +
  7834. + sqliteBeginWriteOperation(pParse, 0, pIndex->iDb);
  7835. + sqliteOpenMasterTable(v, pIndex->iDb);
  7836. + base = sqliteVdbeAddOpList(v, ArraySize(dropIndex), dropIndex);
  7837. + sqliteVdbeChangeP3(v, base+1, pIndex->zName, 0);
  7838. + if( pIndex->iDb==0 ){
  7839. + sqliteChangeCookie(db, v);
  7840. + }
  7841. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  7842. + sqliteVdbeAddOp(v, OP_Destroy, pIndex->tnum, pIndex->iDb);
  7843. + sqliteEndWriteOperation(pParse);
  7844. + }
  7845. +
  7846. + /* Delete the in-memory description of this index.
  7847. + */
  7848. + if( !pParse->explain ){
  7849. + sqliteUnlinkAndDeleteIndex(db, pIndex);
  7850. + db->flags |= SQLITE_InternChanges;
  7851. + }
  7852. +
  7853. +exit_drop_index:
  7854. + sqliteSrcListDelete(pName);
  7855. +}
  7856. +
  7857. +/*
  7858. +** Append a new element to the given IdList. Create a new IdList if
  7859. +** need be.
  7860. +**
  7861. +** A new IdList is returned, or NULL if malloc() fails.
  7862. +*/
  7863. +IdList *sqliteIdListAppend(IdList *pList, Token *pToken){
  7864. + if( pList==0 ){
  7865. + pList = sqliteMalloc( sizeof(IdList) );
  7866. + if( pList==0 ) return 0;
  7867. + pList->nAlloc = 0;
  7868. + }
  7869. + if( pList->nId>=pList->nAlloc ){
  7870. + struct IdList_item *a;
  7871. + pList->nAlloc = pList->nAlloc*2 + 5;
  7872. + a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]) );
  7873. + if( a==0 ){
  7874. + sqliteIdListDelete(pList);
  7875. + return 0;
  7876. + }
  7877. + pList->a = a;
  7878. + }
  7879. + memset(&pList->a[pList->nId], 0, sizeof(pList->a[0]));
  7880. + if( pToken ){
  7881. + char **pz = &pList->a[pList->nId].zName;
  7882. + sqliteSetNString(pz, pToken->z, pToken->n, 0);
  7883. + if( *pz==0 ){
  7884. + sqliteIdListDelete(pList);
  7885. + return 0;
  7886. + }else{
  7887. + sqliteDequote(*pz);
  7888. + }
  7889. + }
  7890. + pList->nId++;
  7891. + return pList;
  7892. +}
  7893. +
  7894. +/*
  7895. +** Append a new table name to the given SrcList. Create a new SrcList if
  7896. +** need be. A new entry is created in the SrcList even if pToken is NULL.
  7897. +**
  7898. +** A new SrcList is returned, or NULL if malloc() fails.
  7899. +**
  7900. +** If pDatabase is not null, it means that the table has an optional
  7901. +** database name prefix. Like this: "database.table". The pDatabase
  7902. +** points to the table name and the pTable points to the database name.
  7903. +** The SrcList.a[].zName field is filled with the table name which might
  7904. +** come from pTable (if pDatabase is NULL) or from pDatabase.
  7905. +** SrcList.a[].zDatabase is filled with the database name from pTable,
  7906. +** or with NULL if no database is specified.
  7907. +**
  7908. +** In other words, if call like this:
  7909. +**
  7910. +** sqliteSrcListAppend(A,B,0);
  7911. +**
  7912. +** Then B is a table name and the database name is unspecified. If called
  7913. +** like this:
  7914. +**
  7915. +** sqliteSrcListAppend(A,B,C);
  7916. +**
  7917. +** Then C is the table name and B is the database name.
  7918. +*/
  7919. +SrcList *sqliteSrcListAppend(SrcList *pList, Token *pTable, Token *pDatabase){
  7920. + if( pList==0 ){
  7921. + pList = sqliteMalloc( sizeof(SrcList) );
  7922. + if( pList==0 ) return 0;
  7923. + pList->nAlloc = 1;
  7924. + }
  7925. + if( pList->nSrc>=pList->nAlloc ){
  7926. + SrcList *pNew;
  7927. + pList->nAlloc *= 2;
  7928. + pNew = sqliteRealloc(pList,
  7929. + sizeof(*pList) + (pList->nAlloc-1)*sizeof(pList->a[0]) );
  7930. + if( pNew==0 ){
  7931. + sqliteSrcListDelete(pList);
  7932. + return 0;
  7933. + }
  7934. + pList = pNew;
  7935. + }
  7936. + memset(&pList->a[pList->nSrc], 0, sizeof(pList->a[0]));
  7937. + if( pDatabase && pDatabase->z==0 ){
  7938. + pDatabase = 0;
  7939. + }
  7940. + if( pDatabase && pTable ){
  7941. + Token *pTemp = pDatabase;
  7942. + pDatabase = pTable;
  7943. + pTable = pTemp;
  7944. + }
  7945. + if( pTable ){
  7946. + char **pz = &pList->a[pList->nSrc].zName;
  7947. + sqliteSetNString(pz, pTable->z, pTable->n, 0);
  7948. + if( *pz==0 ){
  7949. + sqliteSrcListDelete(pList);
  7950. + return 0;
  7951. + }else{
  7952. + sqliteDequote(*pz);
  7953. + }
  7954. + }
  7955. + if( pDatabase ){
  7956. + char **pz = &pList->a[pList->nSrc].zDatabase;
  7957. + sqliteSetNString(pz, pDatabase->z, pDatabase->n, 0);
  7958. + if( *pz==0 ){
  7959. + sqliteSrcListDelete(pList);
  7960. + return 0;
  7961. + }else{
  7962. + sqliteDequote(*pz);
  7963. + }
  7964. + }
  7965. + pList->a[pList->nSrc].iCursor = -1;
  7966. + pList->nSrc++;
  7967. + return pList;
  7968. +}
  7969. +
  7970. +/*
  7971. +** Assign cursors to all tables in a SrcList
  7972. +*/
  7973. +void sqliteSrcListAssignCursors(Parse *pParse, SrcList *pList){
  7974. + int i;
  7975. + for(i=0; i<pList->nSrc; i++){
  7976. + if( pList->a[i].iCursor<0 ){
  7977. + pList->a[i].iCursor = pParse->nTab++;
  7978. + }
  7979. + }
  7980. +}
  7981. +
  7982. +/*
  7983. +** Add an alias to the last identifier on the given identifier list.
  7984. +*/
  7985. +void sqliteSrcListAddAlias(SrcList *pList, Token *pToken){
  7986. + if( pList && pList->nSrc>0 ){
  7987. + int i = pList->nSrc - 1;
  7988. + sqliteSetNString(&pList->a[i].zAlias, pToken->z, pToken->n, 0);
  7989. + sqliteDequote(pList->a[i].zAlias);
  7990. + }
  7991. +}
  7992. +
  7993. +/*
  7994. +** Delete an IdList.
  7995. +*/
  7996. +void sqliteIdListDelete(IdList *pList){
  7997. + int i;
  7998. + if( pList==0 ) return;
  7999. + for(i=0; i<pList->nId; i++){
  8000. + sqliteFree(pList->a[i].zName);
  8001. + }
  8002. + sqliteFree(pList->a);
  8003. + sqliteFree(pList);
  8004. +}
  8005. +
  8006. +/*
  8007. +** Return the index in pList of the identifier named zId. Return -1
  8008. +** if not found.
  8009. +*/
  8010. +int sqliteIdListIndex(IdList *pList, const char *zName){
  8011. + int i;
  8012. + if( pList==0 ) return -1;
  8013. + for(i=0; i<pList->nId; i++){
  8014. + if( sqliteStrICmp(pList->a[i].zName, zName)==0 ) return i;
  8015. + }
  8016. + return -1;
  8017. +}
  8018. +
  8019. +/*
  8020. +** Delete an entire SrcList including all its substructure.
  8021. +*/
  8022. +void sqliteSrcListDelete(SrcList *pList){
  8023. + int i;
  8024. + if( pList==0 ) return;
  8025. + for(i=0; i<pList->nSrc; i++){
  8026. + sqliteFree(pList->a[i].zDatabase);
  8027. + sqliteFree(pList->a[i].zName);
  8028. + sqliteFree(pList->a[i].zAlias);
  8029. + if( pList->a[i].pTab && pList->a[i].pTab->isTransient ){
  8030. + sqliteDeleteTable(0, pList->a[i].pTab);
  8031. + }
  8032. + sqliteSelectDelete(pList->a[i].pSelect);
  8033. + sqliteExprDelete(pList->a[i].pOn);
  8034. + sqliteIdListDelete(pList->a[i].pUsing);
  8035. + }
  8036. + sqliteFree(pList);
  8037. +}
  8038. +
  8039. +/*
  8040. +** Begin a transaction
  8041. +*/
  8042. +void sqliteBeginTransaction(Parse *pParse, int onError){
  8043. + sqlite *db;
  8044. +
  8045. + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  8046. + if( pParse->nErr || sqlite_malloc_failed ) return;
  8047. + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ) return;
  8048. + if( db->flags & SQLITE_InTrans ){
  8049. + sqliteErrorMsg(pParse, "cannot start a transaction within a transaction");
  8050. + return;
  8051. + }
  8052. + sqliteBeginWriteOperation(pParse, 0, 0);
  8053. + if( !pParse->explain ){
  8054. + db->flags |= SQLITE_InTrans;
  8055. + db->onError = onError;
  8056. + }
  8057. +}
  8058. +
  8059. +/*
  8060. +** Commit a transaction
  8061. +*/
  8062. +void sqliteCommitTransaction(Parse *pParse){
  8063. + sqlite *db;
  8064. +
  8065. + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  8066. + if( pParse->nErr || sqlite_malloc_failed ) return;
  8067. + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ) return;
  8068. + if( (db->flags & SQLITE_InTrans)==0 ){
  8069. + sqliteErrorMsg(pParse, "cannot commit - no transaction is active");
  8070. + return;
  8071. + }
  8072. + if( !pParse->explain ){
  8073. + db->flags &= ~SQLITE_InTrans;
  8074. + }
  8075. + sqliteEndWriteOperation(pParse);
  8076. + if( !pParse->explain ){
  8077. + db->onError = OE_Default;
  8078. + }
  8079. +}
  8080. +
  8081. +/*
  8082. +** Rollback a transaction
  8083. +*/
  8084. +void sqliteRollbackTransaction(Parse *pParse){
  8085. + sqlite *db;
  8086. + Vdbe *v;
  8087. +
  8088. + if( pParse==0 || (db=pParse->db)==0 || db->aDb[0].pBt==0 ) return;
  8089. + if( pParse->nErr || sqlite_malloc_failed ) return;
  8090. + if( sqliteAuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ) return;
  8091. + if( (db->flags & SQLITE_InTrans)==0 ){
  8092. + sqliteErrorMsg(pParse, "cannot rollback - no transaction is active");
  8093. + return;
  8094. + }
  8095. + v = sqliteGetVdbe(pParse);
  8096. + if( v ){
  8097. + sqliteVdbeAddOp(v, OP_Rollback, 0, 0);
  8098. + }
  8099. + if( !pParse->explain ){
  8100. + db->flags &= ~SQLITE_InTrans;
  8101. + db->onError = OE_Default;
  8102. + }
  8103. +}
  8104. +
  8105. +/*
  8106. +** Generate VDBE code that will verify the schema cookie for all
  8107. +** named database files.
  8108. +*/
  8109. +void sqliteCodeVerifySchema(Parse *pParse, int iDb){
  8110. + sqlite *db = pParse->db;
  8111. + Vdbe *v = sqliteGetVdbe(pParse);
  8112. + assert( iDb>=0 && iDb<db->nDb );
  8113. + assert( db->aDb[iDb].pBt!=0 );
  8114. + if( iDb!=1 && !DbHasProperty(db, iDb, DB_Cookie) ){
  8115. + sqliteVdbeAddOp(v, OP_VerifyCookie, iDb, db->aDb[iDb].schema_cookie);
  8116. + DbSetProperty(db, iDb, DB_Cookie);
  8117. + }
  8118. +}
  8119. +
  8120. +/*
  8121. +** Generate VDBE code that prepares for doing an operation that
  8122. +** might change the database.
  8123. +**
  8124. +** This routine starts a new transaction if we are not already within
  8125. +** a transaction. If we are already within a transaction, then a checkpoint
  8126. +** is set if the setCheckpoint parameter is true. A checkpoint should
  8127. +** be set for operations that might fail (due to a constraint) part of
  8128. +** the way through and which will need to undo some writes without having to
  8129. +** rollback the whole transaction. For operations where all constraints
  8130. +** can be checked before any changes are made to the database, it is never
  8131. +** necessary to undo a write and the checkpoint should not be set.
  8132. +**
  8133. +** Only database iDb and the temp database are made writable by this call.
  8134. +** If iDb==0, then the main and temp databases are made writable. If
  8135. +** iDb==1 then only the temp database is made writable. If iDb>1 then the
  8136. +** specified auxiliary database and the temp database are made writable.
  8137. +*/
  8138. +void sqliteBeginWriteOperation(Parse *pParse, int setCheckpoint, int iDb){
  8139. + Vdbe *v;
  8140. + sqlite *db = pParse->db;
  8141. + if( DbHasProperty(db, iDb, DB_Locked) ) return;
  8142. + v = sqliteGetVdbe(pParse);
  8143. + if( v==0 ) return;
  8144. + if( !db->aDb[iDb].inTrans ){
  8145. + sqliteVdbeAddOp(v, OP_Transaction, iDb, 0);
  8146. + DbSetProperty(db, iDb, DB_Locked);
  8147. + sqliteCodeVerifySchema(pParse, iDb);
  8148. + if( iDb!=1 ){
  8149. + sqliteBeginWriteOperation(pParse, setCheckpoint, 1);
  8150. + }
  8151. + }else if( setCheckpoint ){
  8152. + sqliteVdbeAddOp(v, OP_Checkpoint, iDb, 0);
  8153. + DbSetProperty(db, iDb, DB_Locked);
  8154. + }
  8155. +}
  8156. +
  8157. +/*
  8158. +** Generate code that concludes an operation that may have changed
  8159. +** the database. If a statement transaction was started, then emit
  8160. +** an OP_Commit that will cause the changes to be committed to disk.
  8161. +**
  8162. +** Note that checkpoints are automatically committed at the end of
  8163. +** a statement. Note also that there can be multiple calls to
  8164. +** sqliteBeginWriteOperation() but there should only be a single
  8165. +** call to sqliteEndWriteOperation() at the conclusion of the statement.
  8166. +*/
  8167. +void sqliteEndWriteOperation(Parse *pParse){
  8168. + Vdbe *v;
  8169. + sqlite *db = pParse->db;
  8170. + if( pParse->trigStack ) return; /* if this is in a trigger */
  8171. + v = sqliteGetVdbe(pParse);
  8172. + if( v==0 ) return;
  8173. + if( db->flags & SQLITE_InTrans ){
  8174. + /* A BEGIN has executed. Do not commit until we see an explicit
  8175. + ** COMMIT statement. */
  8176. + }else{
  8177. + sqliteVdbeAddOp(v, OP_Commit, 0, 0);
  8178. + }
  8179. +}
  8180. --- /dev/null
  8181. +++ b/ext/sqlite/libsqlite/src/config_static.w32.h
  8182. @@ -0,0 +1 @@
  8183. +#define SQLITE_PTR_SZ 4
  8184. \ No newline at end of file
  8185. --- /dev/null
  8186. +++ b/ext/sqlite/libsqlite/src/copy.c
  8187. @@ -0,0 +1,110 @@
  8188. +/*
  8189. +** 2003 April 6
  8190. +**
  8191. +** The author disclaims copyright to this source code. In place of
  8192. +** a legal notice, here is a blessing:
  8193. +**
  8194. +** May you do good and not evil.
  8195. +** May you find forgiveness for yourself and forgive others.
  8196. +** May you share freely, never taking more than you give.
  8197. +**
  8198. +*************************************************************************
  8199. +** This file contains code used to implement the COPY command.
  8200. +**
  8201. +** $Id$
  8202. +*/
  8203. +#include "sqliteInt.h"
  8204. +
  8205. +/*
  8206. +** The COPY command is for compatibility with PostgreSQL and specificially
  8207. +** for the ability to read the output of pg_dump. The format is as
  8208. +** follows:
  8209. +**
  8210. +** COPY table FROM file [USING DELIMITERS string]
  8211. +**
  8212. +** "table" is an existing table name. We will read lines of code from
  8213. +** file to fill this table with data. File might be "stdin". The optional
  8214. +** delimiter string identifies the field separators. The default is a tab.
  8215. +*/
  8216. +void sqliteCopy(
  8217. + Parse *pParse, /* The parser context */
  8218. + SrcList *pTableName, /* The name of the table into which we will insert */
  8219. + Token *pFilename, /* The file from which to obtain information */
  8220. + Token *pDelimiter, /* Use this as the field delimiter */
  8221. + int onError /* What to do if a constraint fails */
  8222. +){
  8223. + Table *pTab;
  8224. + int i;
  8225. + Vdbe *v;
  8226. + int addr, end;
  8227. + char *zFile = 0;
  8228. + const char *zDb;
  8229. + sqlite *db = pParse->db;
  8230. +
  8231. +
  8232. + if( sqlite_malloc_failed ) goto copy_cleanup;
  8233. + assert( pTableName->nSrc==1 );
  8234. + pTab = sqliteSrcListLookup(pParse, pTableName);
  8235. + if( pTab==0 || sqliteIsReadOnly(pParse, pTab, 0) ) goto copy_cleanup;
  8236. + zFile = sqliteStrNDup(pFilename->z, pFilename->n);
  8237. + sqliteDequote(zFile);
  8238. + assert( pTab->iDb<db->nDb );
  8239. + zDb = db->aDb[pTab->iDb].zName;
  8240. + if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb)
  8241. + || sqliteAuthCheck(pParse, SQLITE_COPY, pTab->zName, zFile, zDb) ){
  8242. + goto copy_cleanup;
  8243. + }
  8244. + v = sqliteGetVdbe(pParse);
  8245. + if( v ){
  8246. + sqliteBeginWriteOperation(pParse, 1, pTab->iDb);
  8247. + addr = sqliteVdbeOp3(v, OP_FileOpen, 0, 0, pFilename->z, pFilename->n);
  8248. + sqliteVdbeDequoteP3(v, addr);
  8249. + sqliteOpenTableAndIndices(pParse, pTab, 0);
  8250. + if( db->flags & SQLITE_CountRows ){
  8251. + sqliteVdbeAddOp(v, OP_Integer, 0, 0); /* Initialize the row count */
  8252. + }
  8253. + end = sqliteVdbeMakeLabel(v);
  8254. + addr = sqliteVdbeAddOp(v, OP_FileRead, pTab->nCol, end);
  8255. + if( pDelimiter ){
  8256. + sqliteVdbeChangeP3(v, addr, pDelimiter->z, pDelimiter->n);
  8257. + sqliteVdbeDequoteP3(v, addr);
  8258. + }else{
  8259. + sqliteVdbeChangeP3(v, addr, "\t", 1);
  8260. + }
  8261. + if( pTab->iPKey>=0 ){
  8262. + sqliteVdbeAddOp(v, OP_FileColumn, pTab->iPKey, 0);
  8263. + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
  8264. + }else{
  8265. + sqliteVdbeAddOp(v, OP_NewRecno, 0, 0);
  8266. + }
  8267. + for(i=0; i<pTab->nCol; i++){
  8268. + if( i==pTab->iPKey ){
  8269. + /* The integer primary key column is filled with NULL since its
  8270. + ** value is always pulled from the record number */
  8271. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  8272. + }else{
  8273. + sqliteVdbeAddOp(v, OP_FileColumn, i, 0);
  8274. + }
  8275. + }
  8276. + sqliteGenerateConstraintChecks(pParse, pTab, 0, 0, pTab->iPKey>=0,
  8277. + 0, onError, addr);
  8278. + sqliteCompleteInsertion(pParse, pTab, 0, 0, 0, 0, -1);
  8279. + if( (db->flags & SQLITE_CountRows)!=0 ){
  8280. + sqliteVdbeAddOp(v, OP_AddImm, 1, 0); /* Increment row count */
  8281. + }
  8282. + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
  8283. + sqliteVdbeResolveLabel(v, end);
  8284. + sqliteVdbeAddOp(v, OP_Noop, 0, 0);
  8285. + sqliteEndWriteOperation(pParse);
  8286. + if( db->flags & SQLITE_CountRows ){
  8287. + sqliteVdbeAddOp(v, OP_ColumnName, 0, 1);
  8288. + sqliteVdbeChangeP3(v, -1, "rows inserted", P3_STATIC);
  8289. + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
  8290. + }
  8291. + }
  8292. +
  8293. +copy_cleanup:
  8294. + sqliteSrcListDelete(pTableName);
  8295. + sqliteFree(zFile);
  8296. + return;
  8297. +}
  8298. --- /dev/null
  8299. +++ b/ext/sqlite/libsqlite/src/date.c
  8300. @@ -0,0 +1,881 @@
  8301. +/*
  8302. +** 2003 October 31
  8303. +**
  8304. +** The author disclaims copyright to this source code. In place of
  8305. +** a legal notice, here is a blessing:
  8306. +**
  8307. +** May you do good and not evil.
  8308. +** May you find forgiveness for yourself and forgive others.
  8309. +** May you share freely, never taking more than you give.
  8310. +**
  8311. +*************************************************************************
  8312. +** This file contains the C functions that implement date and time
  8313. +** functions for SQLite.
  8314. +**
  8315. +** There is only one exported symbol in this file - the function
  8316. +** sqliteRegisterDateTimeFunctions() found at the bottom of the file.
  8317. +** All other code has file scope.
  8318. +**
  8319. +** $Id$
  8320. +**
  8321. +** NOTES:
  8322. +**
  8323. +** SQLite processes all times and dates as Julian Day numbers. The
  8324. +** dates and times are stored as the number of days since noon
  8325. +** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  8326. +** calendar system.
  8327. +**
  8328. +** 1970-01-01 00:00:00 is JD 2440587.5
  8329. +** 2000-01-01 00:00:00 is JD 2451544.5
  8330. +**
  8331. +** This implemention requires years to be expressed as a 4-digit number
  8332. +** which means that only dates between 0000-01-01 and 9999-12-31 can
  8333. +** be represented, even though julian day numbers allow a much wider
  8334. +** range of dates.
  8335. +**
  8336. +** The Gregorian calendar system is used for all dates and times,
  8337. +** even those that predate the Gregorian calendar. Historians usually
  8338. +** use the Julian calendar for dates prior to 1582-10-15 and for some
  8339. +** dates afterwards, depending on locale. Beware of this difference.
  8340. +**
  8341. +** The conversion algorithms are implemented based on descriptions
  8342. +** in the following text:
  8343. +**
  8344. +** Jean Meeus
  8345. +** Astronomical Algorithms, 2nd Edition, 1998
  8346. +** ISBM 0-943396-61-1
  8347. +** Willmann-Bell, Inc
  8348. +** Richmond, Virginia (USA)
  8349. +*/
  8350. +#include "os.h"
  8351. +#include "sqliteInt.h"
  8352. +#include <ctype.h>
  8353. +#include <stdlib.h>
  8354. +#include <assert.h>
  8355. +#include <time.h>
  8356. +#ifndef PHP_WIN32
  8357. +#include "main/php_reentrancy.h"
  8358. +#endif
  8359. +
  8360. +#ifndef SQLITE_OMIT_DATETIME_FUNCS
  8361. +
  8362. +/*
  8363. +** A structure for holding a single date and time.
  8364. +*/
  8365. +typedef struct DateTime DateTime;
  8366. +struct DateTime {
  8367. + double rJD; /* The julian day number */
  8368. + int Y, M, D; /* Year, month, and day */
  8369. + int h, m; /* Hour and minutes */
  8370. + int tz; /* Timezone offset in minutes */
  8371. + double s; /* Seconds */
  8372. + char validYMD; /* True if Y,M,D are valid */
  8373. + char validHMS; /* True if h,m,s are valid */
  8374. + char validJD; /* True if rJD is valid */
  8375. + char validTZ; /* True if tz is valid */
  8376. +};
  8377. +
  8378. +
  8379. +/*
  8380. +** Convert zDate into one or more integers. Additional arguments
  8381. +** come in groups of 5 as follows:
  8382. +**
  8383. +** N number of digits in the integer
  8384. +** min minimum allowed value of the integer
  8385. +** max maximum allowed value of the integer
  8386. +** nextC first character after the integer
  8387. +** pVal where to write the integers value.
  8388. +**
  8389. +** Conversions continue until one with nextC==0 is encountered.
  8390. +** The function returns the number of successful conversions.
  8391. +*/
  8392. +static int getDigits(const char *zDate, ...){
  8393. + va_list ap;
  8394. + int val;
  8395. + int N;
  8396. + int min;
  8397. + int max;
  8398. + int nextC;
  8399. + int *pVal;
  8400. + int cnt = 0;
  8401. + va_start(ap, zDate);
  8402. + do{
  8403. + N = va_arg(ap, int);
  8404. + min = va_arg(ap, int);
  8405. + max = va_arg(ap, int);
  8406. + nextC = va_arg(ap, int);
  8407. + pVal = va_arg(ap, int*);
  8408. + val = 0;
  8409. + while( N-- ){
  8410. + if( !isdigit(*zDate) ){
  8411. + return cnt;
  8412. + }
  8413. + val = val*10 + *zDate - '0';
  8414. + zDate++;
  8415. + }
  8416. + if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  8417. + return cnt;
  8418. + }
  8419. + *pVal = val;
  8420. + zDate++;
  8421. + cnt++;
  8422. + }while( nextC );
  8423. + return cnt;
  8424. +}
  8425. +
  8426. +/*
  8427. +** Read text from z[] and convert into a floating point number. Return
  8428. +** the number of digits converted.
  8429. +*/
  8430. +static int getValue(const char *z, double *pR){
  8431. + const char *zEnd;
  8432. + *pR = sqliteAtoF(z, &zEnd);
  8433. + return zEnd - z;
  8434. +}
  8435. +
  8436. +/*
  8437. +** Parse a timezone extension on the end of a date-time.
  8438. +** The extension is of the form:
  8439. +**
  8440. +** (+/-)HH:MM
  8441. +**
  8442. +** If the parse is successful, write the number of minutes
  8443. +** of change in *pnMin and return 0. If a parser error occurs,
  8444. +** return 0.
  8445. +**
  8446. +** A missing specifier is not considered an error.
  8447. +*/
  8448. +static int parseTimezone(const char *zDate, DateTime *p){
  8449. + int sgn = 0;
  8450. + int nHr, nMn;
  8451. + while( isspace(*zDate) ){ zDate++; }
  8452. + p->tz = 0;
  8453. + if( *zDate=='-' ){
  8454. + sgn = -1;
  8455. + }else if( *zDate=='+' ){
  8456. + sgn = +1;
  8457. + }else{
  8458. + return *zDate!=0;
  8459. + }
  8460. + zDate++;
  8461. + if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  8462. + return 1;
  8463. + }
  8464. + zDate += 5;
  8465. + p->tz = sgn*(nMn + nHr*60);
  8466. + while( isspace(*zDate) ){ zDate++; }
  8467. + return *zDate!=0;
  8468. +}
  8469. +
  8470. +/*
  8471. +** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  8472. +** The HH, MM, and SS must each be exactly 2 digits. The
  8473. +** fractional seconds FFFF can be one or more digits.
  8474. +**
  8475. +** Return 1 if there is a parsing error and 0 on success.
  8476. +*/
  8477. +static int parseHhMmSs(const char *zDate, DateTime *p){
  8478. + int h, m, s;
  8479. + double ms = 0.0;
  8480. + if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  8481. + return 1;
  8482. + }
  8483. + zDate += 5;
  8484. + if( *zDate==':' ){
  8485. + zDate++;
  8486. + if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  8487. + return 1;
  8488. + }
  8489. + zDate += 2;
  8490. + if( *zDate=='.' && isdigit(zDate[1]) ){
  8491. + double rScale = 1.0;
  8492. + zDate++;
  8493. + while( isdigit(*zDate) ){
  8494. + ms = ms*10.0 + *zDate - '0';
  8495. + rScale *= 10.0;
  8496. + zDate++;
  8497. + }
  8498. + ms /= rScale;
  8499. + }
  8500. + }else{
  8501. + s = 0;
  8502. + }
  8503. + p->validJD = 0;
  8504. + p->validHMS = 1;
  8505. + p->h = h;
  8506. + p->m = m;
  8507. + p->s = s + ms;
  8508. + if( parseTimezone(zDate, p) ) return 1;
  8509. + p->validTZ = p->tz!=0;
  8510. + return 0;
  8511. +}
  8512. +
  8513. +/*
  8514. +** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  8515. +** that the YYYY-MM-DD is according to the Gregorian calendar.
  8516. +**
  8517. +** Reference: Meeus page 61
  8518. +*/
  8519. +static void computeJD(DateTime *p){
  8520. + int Y, M, D, A, B, X1, X2;
  8521. +
  8522. + if( p->validJD ) return;
  8523. + if( p->validYMD ){
  8524. + Y = p->Y;
  8525. + M = p->M;
  8526. + D = p->D;
  8527. + }else{
  8528. + Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  8529. + M = 1;
  8530. + D = 1;
  8531. + }
  8532. + if( M<=2 ){
  8533. + Y--;
  8534. + M += 12;
  8535. + }
  8536. + A = Y/100;
  8537. + B = 2 - A + (A/4);
  8538. + X1 = 365.25*(Y+4716);
  8539. + X2 = 30.6001*(M+1);
  8540. + p->rJD = X1 + X2 + D + B - 1524.5;
  8541. + p->validJD = 1;
  8542. + p->validYMD = 0;
  8543. + if( p->validHMS ){
  8544. + p->rJD += (p->h*3600.0 + p->m*60.0 + p->s)/86400.0;
  8545. + if( p->validTZ ){
  8546. + p->rJD += p->tz*60/86400.0;
  8547. + p->validHMS = 0;
  8548. + p->validTZ = 0;
  8549. + }
  8550. + }
  8551. +}
  8552. +
  8553. +/*
  8554. +** Parse dates of the form
  8555. +**
  8556. +** YYYY-MM-DD HH:MM:SS.FFF
  8557. +** YYYY-MM-DD HH:MM:SS
  8558. +** YYYY-MM-DD HH:MM
  8559. +** YYYY-MM-DD
  8560. +**
  8561. +** Write the result into the DateTime structure and return 0
  8562. +** on success and 1 if the input string is not a well-formed
  8563. +** date.
  8564. +*/
  8565. +static int parseYyyyMmDd(const char *zDate, DateTime *p){
  8566. + int Y, M, D, neg;
  8567. +
  8568. + if( zDate[0]=='-' ){
  8569. + zDate++;
  8570. + neg = 1;
  8571. + }else{
  8572. + neg = 0;
  8573. + }
  8574. + if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  8575. + return 1;
  8576. + }
  8577. + zDate += 10;
  8578. + while( isspace(*zDate) ){ zDate++; }
  8579. + if( parseHhMmSs(zDate, p)==0 ){
  8580. + /* We got the time */
  8581. + }else if( *zDate==0 ){
  8582. + p->validHMS = 0;
  8583. + }else{
  8584. + return 1;
  8585. + }
  8586. + p->validJD = 0;
  8587. + p->validYMD = 1;
  8588. + p->Y = neg ? -Y : Y;
  8589. + p->M = M;
  8590. + p->D = D;
  8591. + if( p->validTZ ){
  8592. + computeJD(p);
  8593. + }
  8594. + return 0;
  8595. +}
  8596. +
  8597. +/*
  8598. +** Attempt to parse the given string into a Julian Day Number. Return
  8599. +** the number of errors.
  8600. +**
  8601. +** The following are acceptable forms for the input string:
  8602. +**
  8603. +** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  8604. +** DDDD.DD
  8605. +** now
  8606. +**
  8607. +** In the first form, the +/-HH:MM is always optional. The fractional
  8608. +** seconds extension (the ".FFF") is optional. The seconds portion
  8609. +** (":SS.FFF") is option. The year and date can be omitted as long
  8610. +** as there is a time string. The time string can be omitted as long
  8611. +** as there is a year and date.
  8612. +*/
  8613. +static int parseDateOrTime(const char *zDate, DateTime *p){
  8614. + memset(p, 0, sizeof(*p));
  8615. + if( parseYyyyMmDd(zDate,p)==0 ){
  8616. + return 0;
  8617. + }else if( parseHhMmSs(zDate, p)==0 ){
  8618. + return 0;
  8619. + }else if( sqliteStrICmp(zDate,"now")==0){
  8620. + double r;
  8621. + if( sqliteOsCurrentTime(&r)==0 ){
  8622. + p->rJD = r;
  8623. + p->validJD = 1;
  8624. + return 0;
  8625. + }
  8626. + return 1;
  8627. + }else if( sqliteIsNumber(zDate) ){
  8628. + p->rJD = sqliteAtoF(zDate, 0);
  8629. + p->validJD = 1;
  8630. + return 0;
  8631. + }
  8632. + return 1;
  8633. +}
  8634. +
  8635. +/*
  8636. +** Compute the Year, Month, and Day from the julian day number.
  8637. +*/
  8638. +static void computeYMD(DateTime *p){
  8639. + int Z, A, B, C, D, E, X1;
  8640. + if( p->validYMD ) return;
  8641. + if( !p->validJD ){
  8642. + p->Y = 2000;
  8643. + p->M = 1;
  8644. + p->D = 1;
  8645. + }else{
  8646. + Z = p->rJD + 0.5;
  8647. + A = (Z - 1867216.25)/36524.25;
  8648. + A = Z + 1 + A - (A/4);
  8649. + B = A + 1524;
  8650. + C = (B - 122.1)/365.25;
  8651. + D = 365.25*C;
  8652. + E = (B-D)/30.6001;
  8653. + X1 = 30.6001*E;
  8654. + p->D = B - D - X1;
  8655. + p->M = E<14 ? E-1 : E-13;
  8656. + p->Y = p->M>2 ? C - 4716 : C - 4715;
  8657. + }
  8658. + p->validYMD = 1;
  8659. +}
  8660. +
  8661. +/*
  8662. +** Compute the Hour, Minute, and Seconds from the julian day number.
  8663. +*/
  8664. +static void computeHMS(DateTime *p){
  8665. + int Z, s;
  8666. + if( p->validHMS ) return;
  8667. + Z = p->rJD + 0.5;
  8668. + s = (p->rJD + 0.5 - Z)*86400000.0 + 0.5;
  8669. + p->s = 0.001*s;
  8670. + s = p->s;
  8671. + p->s -= s;
  8672. + p->h = s/3600;
  8673. + s -= p->h*3600;
  8674. + p->m = s/60;
  8675. + p->s += s - p->m*60;
  8676. + p->validHMS = 1;
  8677. +}
  8678. +
  8679. +/*
  8680. +** Compute both YMD and HMS
  8681. +*/
  8682. +static void computeYMD_HMS(DateTime *p){
  8683. + computeYMD(p);
  8684. + computeHMS(p);
  8685. +}
  8686. +
  8687. +/*
  8688. +** Clear the YMD and HMS and the TZ
  8689. +*/
  8690. +static void clearYMD_HMS_TZ(DateTime *p){
  8691. + p->validYMD = 0;
  8692. + p->validHMS = 0;
  8693. + p->validTZ = 0;
  8694. +}
  8695. +
  8696. +/*
  8697. +** Compute the difference (in days) between localtime and UTC (a.k.a. GMT)
  8698. +** for the time value p where p is in UTC.
  8699. +*/
  8700. +static double localtimeOffset(DateTime *p){
  8701. + DateTime x, y;
  8702. + time_t t;
  8703. + struct tm *pTm, tmbuf;
  8704. + x = *p;
  8705. + computeYMD_HMS(&x);
  8706. + if( x.Y<1971 || x.Y>=2038 ){
  8707. + x.Y = 2000;
  8708. + x.M = 1;
  8709. + x.D = 1;
  8710. + x.h = 0;
  8711. + x.m = 0;
  8712. + x.s = 0.0;
  8713. + } else {
  8714. + int s = x.s + 0.5;
  8715. + x.s = s;
  8716. + }
  8717. + x.tz = 0;
  8718. + x.validJD = 0;
  8719. + computeJD(&x);
  8720. + t = (x.rJD-2440587.5)*86400.0 + 0.5;
  8721. + sqliteOsEnterMutex();
  8722. + pTm = php_localtime_r(&t, &tmbuf);
  8723. + if (!pTm) {
  8724. + return 0;
  8725. + }
  8726. + y.Y = pTm->tm_year + 1900;
  8727. + y.M = pTm->tm_mon + 1;
  8728. + y.D = pTm->tm_mday;
  8729. + y.h = pTm->tm_hour;
  8730. + y.m = pTm->tm_min;
  8731. + y.s = pTm->tm_sec;
  8732. + sqliteOsLeaveMutex();
  8733. + y.validYMD = 1;
  8734. + y.validHMS = 1;
  8735. + y.validJD = 0;
  8736. + y.validTZ = 0;
  8737. + computeJD(&y);
  8738. + return y.rJD - x.rJD;
  8739. +}
  8740. +
  8741. +/*
  8742. +** Process a modifier to a date-time stamp. The modifiers are
  8743. +** as follows:
  8744. +**
  8745. +** NNN days
  8746. +** NNN hours
  8747. +** NNN minutes
  8748. +** NNN.NNNN seconds
  8749. +** NNN months
  8750. +** NNN years
  8751. +** start of month
  8752. +** start of year
  8753. +** start of week
  8754. +** start of day
  8755. +** weekday N
  8756. +** unixepoch
  8757. +** localtime
  8758. +** utc
  8759. +**
  8760. +** Return 0 on success and 1 if there is any kind of error.
  8761. +*/
  8762. +static int parseModifier(const char *zMod, DateTime *p){
  8763. + int rc = 1;
  8764. + int n;
  8765. + double r;
  8766. + char *z, zBuf[30];
  8767. + z = zBuf;
  8768. + for(n=0; n<sizeof(zBuf)-1 && zMod[n]; n++){
  8769. + z[n] = tolower(zMod[n]);
  8770. + }
  8771. + z[n] = 0;
  8772. + switch( z[0] ){
  8773. + case 'l': {
  8774. + /* localtime
  8775. + **
  8776. + ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  8777. + ** show local time.
  8778. + */
  8779. + if( strcmp(z, "localtime")==0 ){
  8780. + computeJD(p);
  8781. + p->rJD += localtimeOffset(p);
  8782. + clearYMD_HMS_TZ(p);
  8783. + rc = 0;
  8784. + }
  8785. + break;
  8786. + }
  8787. + case 'u': {
  8788. + /*
  8789. + ** unixepoch
  8790. + **
  8791. + ** Treat the current value of p->rJD as the number of
  8792. + ** seconds since 1970. Convert to a real julian day number.
  8793. + */
  8794. + if( strcmp(z, "unixepoch")==0 && p->validJD ){
  8795. + p->rJD = p->rJD/86400.0 + 2440587.5;
  8796. + clearYMD_HMS_TZ(p);
  8797. + rc = 0;
  8798. + }else if( strcmp(z, "utc")==0 ){
  8799. + double c1;
  8800. + computeJD(p);
  8801. + c1 = localtimeOffset(p);
  8802. + p->rJD -= c1;
  8803. + clearYMD_HMS_TZ(p);
  8804. + p->rJD += c1 - localtimeOffset(p);
  8805. + rc = 0;
  8806. + }
  8807. + break;
  8808. + }
  8809. + case 'w': {
  8810. + /*
  8811. + ** weekday N
  8812. + **
  8813. + ** Move the date to the same time on the next occurrance of
  8814. + ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  8815. + ** date is already on the appropriate weekday, this is a no-op.
  8816. + */
  8817. + if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
  8818. + && (n=r)==r && n>=0 && r<7 ){
  8819. + int Z;
  8820. + computeYMD_HMS(p);
  8821. + p->validTZ = 0;
  8822. + p->validJD = 0;
  8823. + computeJD(p);
  8824. + Z = p->rJD + 1.5;
  8825. + Z %= 7;
  8826. + if( Z>n ) Z -= 7;
  8827. + p->rJD += n - Z;
  8828. + clearYMD_HMS_TZ(p);
  8829. + rc = 0;
  8830. + }
  8831. + break;
  8832. + }
  8833. + case 's': {
  8834. + /*
  8835. + ** start of TTTTT
  8836. + **
  8837. + ** Move the date backwards to the beginning of the current day,
  8838. + ** or month or year.
  8839. + */
  8840. + if( strncmp(z, "start of ", 9)!=0 ) break;
  8841. + z += 9;
  8842. + computeYMD(p);
  8843. + p->validHMS = 1;
  8844. + p->h = p->m = 0;
  8845. + p->s = 0.0;
  8846. + p->validTZ = 0;
  8847. + p->validJD = 0;
  8848. + if( strcmp(z,"month")==0 ){
  8849. + p->D = 1;
  8850. + rc = 0;
  8851. + }else if( strcmp(z,"year")==0 ){
  8852. + computeYMD(p);
  8853. + p->M = 1;
  8854. + p->D = 1;
  8855. + rc = 0;
  8856. + }else if( strcmp(z,"day")==0 ){
  8857. + rc = 0;
  8858. + }
  8859. + break;
  8860. + }
  8861. + case '+':
  8862. + case '-':
  8863. + case '0':
  8864. + case '1':
  8865. + case '2':
  8866. + case '3':
  8867. + case '4':
  8868. + case '5':
  8869. + case '6':
  8870. + case '7':
  8871. + case '8':
  8872. + case '9': {
  8873. + n = getValue(z, &r);
  8874. + if( n<=0 ) break;
  8875. + if( z[n]==':' ){
  8876. + /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  8877. + ** specified number of hours, minutes, seconds, and fractional seconds
  8878. + ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  8879. + ** omitted.
  8880. + */
  8881. + const char *z2 = z;
  8882. + DateTime tx;
  8883. + int day;
  8884. + if( !isdigit(*z2) ) z2++;
  8885. + memset(&tx, 0, sizeof(tx));
  8886. + if( parseHhMmSs(z2, &tx) ) break;
  8887. + computeJD(&tx);
  8888. + tx.rJD -= 0.5;
  8889. + day = (int)tx.rJD;
  8890. + tx.rJD -= day;
  8891. + if( z[0]=='-' ) tx.rJD = -tx.rJD;
  8892. + computeJD(p);
  8893. + clearYMD_HMS_TZ(p);
  8894. + p->rJD += tx.rJD;
  8895. + rc = 0;
  8896. + break;
  8897. + }
  8898. + z += n;
  8899. + while( isspace(z[0]) ) z++;
  8900. + n = strlen(z);
  8901. + if( n>10 || n<3 ) break;
  8902. + if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  8903. + computeJD(p);
  8904. + rc = 0;
  8905. + if( n==3 && strcmp(z,"day")==0 ){
  8906. + p->rJD += r;
  8907. + }else if( n==4 && strcmp(z,"hour")==0 ){
  8908. + p->rJD += r/24.0;
  8909. + }else if( n==6 && strcmp(z,"minute")==0 ){
  8910. + p->rJD += r/(24.0*60.0);
  8911. + }else if( n==6 && strcmp(z,"second")==0 ){
  8912. + p->rJD += r/(24.0*60.0*60.0);
  8913. + }else if( n==5 && strcmp(z,"month")==0 ){
  8914. + int x, y;
  8915. + computeYMD_HMS(p);
  8916. + p->M += r;
  8917. + x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  8918. + p->Y += x;
  8919. + p->M -= x*12;
  8920. + p->validJD = 0;
  8921. + computeJD(p);
  8922. + y = r;
  8923. + if( y!=r ){
  8924. + p->rJD += (r - y)*30.0;
  8925. + }
  8926. + }else if( n==4 && strcmp(z,"year")==0 ){
  8927. + computeYMD_HMS(p);
  8928. + p->Y += r;
  8929. + p->validJD = 0;
  8930. + computeJD(p);
  8931. + }else{
  8932. + rc = 1;
  8933. + }
  8934. + clearYMD_HMS_TZ(p);
  8935. + break;
  8936. + }
  8937. + default: {
  8938. + break;
  8939. + }
  8940. + }
  8941. + return rc;
  8942. +}
  8943. +
  8944. +/*
  8945. +** Process time function arguments. argv[0] is a date-time stamp.
  8946. +** argv[1] and following are modifiers. Parse them all and write
  8947. +** the resulting time into the DateTime structure p. Return 0
  8948. +** on success and 1 if there are any errors.
  8949. +*/
  8950. +static int isDate(int argc, const char **argv, DateTime *p){
  8951. + int i;
  8952. + if( argc==0 ) return 1;
  8953. + if( argv[0]==0 || parseDateOrTime(argv[0], p) ) return 1;
  8954. + for(i=1; i<argc; i++){
  8955. + if( argv[i]==0 || parseModifier(argv[i], p) ) return 1;
  8956. + }
  8957. + return 0;
  8958. +}
  8959. +
  8960. +
  8961. +/*
  8962. +** The following routines implement the various date and time functions
  8963. +** of SQLite.
  8964. +*/
  8965. +
  8966. +/*
  8967. +** julianday( TIMESTRING, MOD, MOD, ...)
  8968. +**
  8969. +** Return the julian day number of the date specified in the arguments
  8970. +*/
  8971. +static void juliandayFunc(sqlite_func *context, int argc, const char **argv){
  8972. + DateTime x;
  8973. + if( isDate(argc, argv, &x)==0 ){
  8974. + computeJD(&x);
  8975. + sqlite_set_result_double(context, x.rJD);
  8976. + }
  8977. +}
  8978. +
  8979. +/*
  8980. +** datetime( TIMESTRING, MOD, MOD, ...)
  8981. +**
  8982. +** Return YYYY-MM-DD HH:MM:SS
  8983. +*/
  8984. +static void datetimeFunc(sqlite_func *context, int argc, const char **argv){
  8985. + DateTime x;
  8986. + if( isDate(argc, argv, &x)==0 ){
  8987. + char zBuf[100];
  8988. + computeYMD_HMS(&x);
  8989. + sprintf(zBuf, "%04d-%02d-%02d %02d:%02d:%02d",x.Y, x.M, x.D, x.h, x.m,
  8990. + (int)(x.s));
  8991. + sqlite_set_result_string(context, zBuf, -1);
  8992. + }
  8993. +}
  8994. +
  8995. +/*
  8996. +** time( TIMESTRING, MOD, MOD, ...)
  8997. +**
  8998. +** Return HH:MM:SS
  8999. +*/
  9000. +static void timeFunc(sqlite_func *context, int argc, const char **argv){
  9001. + DateTime x;
  9002. + if( isDate(argc, argv, &x)==0 ){
  9003. + char zBuf[100];
  9004. + computeHMS(&x);
  9005. + sprintf(zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  9006. + sqlite_set_result_string(context, zBuf, -1);
  9007. + }
  9008. +}
  9009. +
  9010. +/*
  9011. +** date( TIMESTRING, MOD, MOD, ...)
  9012. +**
  9013. +** Return YYYY-MM-DD
  9014. +*/
  9015. +static void dateFunc(sqlite_func *context, int argc, const char **argv){
  9016. + DateTime x;
  9017. + if( isDate(argc, argv, &x)==0 ){
  9018. + char zBuf[100];
  9019. + computeYMD(&x);
  9020. + sprintf(zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  9021. + sqlite_set_result_string(context, zBuf, -1);
  9022. + }
  9023. +}
  9024. +
  9025. +/*
  9026. +** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  9027. +**
  9028. +** Return a string described by FORMAT. Conversions as follows:
  9029. +**
  9030. +** %d day of month
  9031. +** %f ** fractional seconds SS.SSS
  9032. +** %H hour 00-24
  9033. +** %j day of year 000-366
  9034. +** %J ** Julian day number
  9035. +** %m month 01-12
  9036. +** %M minute 00-59
  9037. +** %s seconds since 1970-01-01
  9038. +** %S seconds 00-59
  9039. +** %w day of week 0-6 sunday==0
  9040. +** %W week of year 00-53
  9041. +** %Y year 0000-9999
  9042. +** %% %
  9043. +*/
  9044. +static void strftimeFunc(sqlite_func *context, int argc, const char **argv){
  9045. + DateTime x;
  9046. + int n, i, j;
  9047. + char *z;
  9048. + const char *zFmt = argv[0];
  9049. + char zBuf[100];
  9050. + if( argv[0]==0 || isDate(argc-1, argv+1, &x) ) return;
  9051. + for(i=0, n=1; zFmt[i]; i++, n++){
  9052. + if( zFmt[i]=='%' ){
  9053. + switch( zFmt[i+1] ){
  9054. + case 'd':
  9055. + case 'H':
  9056. + case 'm':
  9057. + case 'M':
  9058. + case 'S':
  9059. + case 'W':
  9060. + n++;
  9061. + /* fall thru */
  9062. + case 'w':
  9063. + case '%':
  9064. + break;
  9065. + case 'f':
  9066. + n += 8;
  9067. + break;
  9068. + case 'j':
  9069. + n += 3;
  9070. + break;
  9071. + case 'Y':
  9072. + n += 8;
  9073. + break;
  9074. + case 's':
  9075. + case 'J':
  9076. + n += 50;
  9077. + break;
  9078. + default:
  9079. + return; /* ERROR. return a NULL */
  9080. + }
  9081. + i++;
  9082. + }
  9083. + }
  9084. + if( n<sizeof(zBuf) ){
  9085. + z = zBuf;
  9086. + }else{
  9087. + z = sqliteMalloc( n );
  9088. + if( z==0 ) return;
  9089. + }
  9090. + computeJD(&x);
  9091. + computeYMD_HMS(&x);
  9092. + for(i=j=0; zFmt[i]; i++){
  9093. + if( zFmt[i]!='%' ){
  9094. + z[j++] = zFmt[i];
  9095. + }else{
  9096. + i++;
  9097. + switch( zFmt[i] ){
  9098. + case 'd': sprintf(&z[j],"%02d",x.D); j+=2; break;
  9099. + case 'f': {
  9100. + int s = x.s;
  9101. + int ms = (x.s - s)*1000.0;
  9102. + sprintf(&z[j],"%02d.%03d",s,ms);
  9103. + j += strlen(&z[j]);
  9104. + break;
  9105. + }
  9106. + case 'H': sprintf(&z[j],"%02d",x.h); j+=2; break;
  9107. + case 'W': /* Fall thru */
  9108. + case 'j': {
  9109. + int n; /* Number of days since 1st day of year */
  9110. + DateTime y = x;
  9111. + y.validJD = 0;
  9112. + y.M = 1;
  9113. + y.D = 1;
  9114. + computeJD(&y);
  9115. + n = x.rJD - y.rJD;
  9116. + if( zFmt[i]=='W' ){
  9117. + int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  9118. + wd = ((int)(x.rJD+0.5)) % 7;
  9119. + sprintf(&z[j],"%02d",(n+7-wd)/7);
  9120. + j += 2;
  9121. + }else{
  9122. + sprintf(&z[j],"%03d",n+1);
  9123. + j += 3;
  9124. + }
  9125. + break;
  9126. + }
  9127. + case 'J': sprintf(&z[j],"%.16g",x.rJD); j+=strlen(&z[j]); break;
  9128. + case 'm': sprintf(&z[j],"%02d",x.M); j+=2; break;
  9129. + case 'M': sprintf(&z[j],"%02d",x.m); j+=2; break;
  9130. + case 's': {
  9131. + sprintf(&z[j],"%d",(int)((x.rJD-2440587.5)*86400.0 + 0.5));
  9132. + j += strlen(&z[j]);
  9133. + break;
  9134. + }
  9135. + case 'S': sprintf(&z[j],"%02d",(int)(x.s+0.5)); j+=2; break;
  9136. + case 'w': z[j++] = (((int)(x.rJD+1.5)) % 7) + '0'; break;
  9137. + case 'Y': sprintf(&z[j],"%04d",x.Y); j+=strlen(&z[j]); break;
  9138. + case '%': z[j++] = '%'; break;
  9139. + }
  9140. + }
  9141. + }
  9142. + z[j] = 0;
  9143. + sqlite_set_result_string(context, z, -1);
  9144. + if( z!=zBuf ){
  9145. + sqliteFree(z);
  9146. + }
  9147. +}
  9148. +
  9149. +
  9150. +#endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  9151. +
  9152. +/*
  9153. +** This function registered all of the above C functions as SQL
  9154. +** functions. This should be the only routine in this file with
  9155. +** external linkage.
  9156. +*/
  9157. +void sqliteRegisterDateTimeFunctions(sqlite *db){
  9158. +#ifndef SQLITE_OMIT_DATETIME_FUNCS
  9159. + static struct {
  9160. + char *zName;
  9161. + int nArg;
  9162. + int dataType;
  9163. + void (*xFunc)(sqlite_func*,int,const char**);
  9164. + } aFuncs[] = {
  9165. + { "julianday", -1, SQLITE_NUMERIC, juliandayFunc },
  9166. + { "date", -1, SQLITE_TEXT, dateFunc },
  9167. + { "time", -1, SQLITE_TEXT, timeFunc },
  9168. + { "datetime", -1, SQLITE_TEXT, datetimeFunc },
  9169. + { "strftime", -1, SQLITE_TEXT, strftimeFunc },
  9170. + };
  9171. + int i;
  9172. +
  9173. + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
  9174. + sqlite_create_function(db, aFuncs[i].zName,
  9175. + aFuncs[i].nArg, aFuncs[i].xFunc, 0);
  9176. + if( aFuncs[i].xFunc ){
  9177. + sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
  9178. + }
  9179. + }
  9180. +#endif
  9181. +}
  9182. --- /dev/null
  9183. +++ b/ext/sqlite/libsqlite/src/delete.c
  9184. @@ -0,0 +1,393 @@
  9185. +/*
  9186. +** 2001 September 15
  9187. +**
  9188. +** The author disclaims copyright to this source code. In place of
  9189. +** a legal notice, here is a blessing:
  9190. +**
  9191. +** May you do good and not evil.
  9192. +** May you find forgiveness for yourself and forgive others.
  9193. +** May you share freely, never taking more than you give.
  9194. +**
  9195. +*************************************************************************
  9196. +** This file contains C code routines that are called by the parser
  9197. +** to handle DELETE FROM statements.
  9198. +**
  9199. +** $Id$
  9200. +*/
  9201. +#include "sqliteInt.h"
  9202. +
  9203. +/*
  9204. +** Look up every table that is named in pSrc. If any table is not found,
  9205. +** add an error message to pParse->zErrMsg and return NULL. If all tables
  9206. +** are found, return a pointer to the last table.
  9207. +*/
  9208. +Table *sqliteSrcListLookup(Parse *pParse, SrcList *pSrc){
  9209. + Table *pTab = 0;
  9210. + int i;
  9211. + for(i=0; i<pSrc->nSrc; i++){
  9212. + const char *zTab = pSrc->a[i].zName;
  9213. + const char *zDb = pSrc->a[i].zDatabase;
  9214. + pTab = sqliteLocateTable(pParse, zTab, zDb);
  9215. + pSrc->a[i].pTab = pTab;
  9216. + }
  9217. + return pTab;
  9218. +}
  9219. +
  9220. +/*
  9221. +** Check to make sure the given table is writable. If it is not
  9222. +** writable, generate an error message and return 1. If it is
  9223. +** writable return 0;
  9224. +*/
  9225. +int sqliteIsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  9226. + if( pTab->readOnly ){
  9227. + sqliteErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  9228. + return 1;
  9229. + }
  9230. + if( !viewOk && pTab->pSelect ){
  9231. + sqliteErrorMsg(pParse, "cannot modify %s because it is a view",pTab->zName);
  9232. + return 1;
  9233. + }
  9234. + return 0;
  9235. +}
  9236. +
  9237. +/*
  9238. +** Process a DELETE FROM statement.
  9239. +*/
  9240. +void sqliteDeleteFrom(
  9241. + Parse *pParse, /* The parser context */
  9242. + SrcList *pTabList, /* The table from which we should delete things */
  9243. + Expr *pWhere /* The WHERE clause. May be null */
  9244. +){
  9245. + Vdbe *v; /* The virtual database engine */
  9246. + Table *pTab; /* The table from which records will be deleted */
  9247. + const char *zDb; /* Name of database holding pTab */
  9248. + int end, addr; /* A couple addresses of generated code */
  9249. + int i; /* Loop counter */
  9250. + WhereInfo *pWInfo; /* Information about the WHERE clause */
  9251. + Index *pIdx; /* For looping over indices of the table */
  9252. + int iCur; /* VDBE Cursor number for pTab */
  9253. + sqlite *db; /* Main database structure */
  9254. + int isView; /* True if attempting to delete from a view */
  9255. + AuthContext sContext; /* Authorization context */
  9256. +
  9257. + int row_triggers_exist = 0; /* True if any triggers exist */
  9258. + int before_triggers; /* True if there are BEFORE triggers */
  9259. + int after_triggers; /* True if there are AFTER triggers */
  9260. + int oldIdx = -1; /* Cursor for the OLD table of AFTER triggers */
  9261. +
  9262. + sContext.pParse = 0;
  9263. + if( pParse->nErr || sqlite_malloc_failed ){
  9264. + pTabList = 0;
  9265. + goto delete_from_cleanup;
  9266. + }
  9267. + db = pParse->db;
  9268. + assert( pTabList->nSrc==1 );
  9269. +
  9270. + /* Locate the table which we want to delete. This table has to be
  9271. + ** put in an SrcList structure because some of the subroutines we
  9272. + ** will be calling are designed to work with multiple tables and expect
  9273. + ** an SrcList* parameter instead of just a Table* parameter.
  9274. + */
  9275. + pTab = sqliteSrcListLookup(pParse, pTabList);
  9276. + if( pTab==0 ) goto delete_from_cleanup;
  9277. + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
  9278. + TK_DELETE, TK_BEFORE, TK_ROW, 0);
  9279. + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
  9280. + TK_DELETE, TK_AFTER, TK_ROW, 0);
  9281. + row_triggers_exist = before_triggers || after_triggers;
  9282. + isView = pTab->pSelect!=0;
  9283. + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
  9284. + goto delete_from_cleanup;
  9285. + }
  9286. + assert( pTab->iDb<db->nDb );
  9287. + zDb = db->aDb[pTab->iDb].zName;
  9288. + if( sqliteAuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  9289. + goto delete_from_cleanup;
  9290. + }
  9291. +
  9292. + /* If pTab is really a view, make sure it has been initialized.
  9293. + */
  9294. + if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
  9295. + goto delete_from_cleanup;
  9296. + }
  9297. +
  9298. + /* Allocate a cursor used to store the old.* data for a trigger.
  9299. + */
  9300. + if( row_triggers_exist ){
  9301. + oldIdx = pParse->nTab++;
  9302. + }
  9303. +
  9304. + /* Resolve the column names in all the expressions.
  9305. + */
  9306. + assert( pTabList->nSrc==1 );
  9307. + iCur = pTabList->a[0].iCursor = pParse->nTab++;
  9308. + if( pWhere ){
  9309. + if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
  9310. + goto delete_from_cleanup;
  9311. + }
  9312. + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
  9313. + goto delete_from_cleanup;
  9314. + }
  9315. + }
  9316. +
  9317. + /* Start the view context
  9318. + */
  9319. + if( isView ){
  9320. + sqliteAuthContextPush(pParse, &sContext, pTab->zName);
  9321. + }
  9322. +
  9323. + /* Begin generating code.
  9324. + */
  9325. + v = sqliteGetVdbe(pParse);
  9326. + if( v==0 ){
  9327. + goto delete_from_cleanup;
  9328. + }
  9329. + sqliteBeginWriteOperation(pParse, row_triggers_exist, pTab->iDb);
  9330. +
  9331. + /* If we are trying to delete from a view, construct that view into
  9332. + ** a temporary table.
  9333. + */
  9334. + if( isView ){
  9335. + Select *pView = sqliteSelectDup(pTab->pSelect);
  9336. + sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
  9337. + sqliteSelectDelete(pView);
  9338. + }
  9339. +
  9340. + /* Initialize the counter of the number of rows deleted, if
  9341. + ** we are counting rows.
  9342. + */
  9343. + if( db->flags & SQLITE_CountRows ){
  9344. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  9345. + }
  9346. +
  9347. + /* Special case: A DELETE without a WHERE clause deletes everything.
  9348. + ** It is easier just to erase the whole table. Note, however, that
  9349. + ** this means that the row change count will be incorrect.
  9350. + */
  9351. + if( pWhere==0 && !row_triggers_exist ){
  9352. + if( db->flags & SQLITE_CountRows ){
  9353. + /* If counting rows deleted, just count the total number of
  9354. + ** entries in the table. */
  9355. + int endOfLoop = sqliteVdbeMakeLabel(v);
  9356. + int addr;
  9357. + if( !isView ){
  9358. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  9359. + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
  9360. + }
  9361. + sqliteVdbeAddOp(v, OP_Rewind, iCur, sqliteVdbeCurrentAddr(v)+2);
  9362. + addr = sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
  9363. + sqliteVdbeAddOp(v, OP_Next, iCur, addr);
  9364. + sqliteVdbeResolveLabel(v, endOfLoop);
  9365. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  9366. + }
  9367. + if( !isView ){
  9368. + sqliteVdbeAddOp(v, OP_Clear, pTab->tnum, pTab->iDb);
  9369. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  9370. + sqliteVdbeAddOp(v, OP_Clear, pIdx->tnum, pIdx->iDb);
  9371. + }
  9372. + }
  9373. + }
  9374. +
  9375. + /* The usual case: There is a WHERE clause so we have to scan through
  9376. + ** the table and pick which records to delete.
  9377. + */
  9378. + else{
  9379. + /* Begin the database scan
  9380. + */
  9381. + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
  9382. + if( pWInfo==0 ) goto delete_from_cleanup;
  9383. +
  9384. + /* Remember the key of every item to be deleted.
  9385. + */
  9386. + sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
  9387. + if( db->flags & SQLITE_CountRows ){
  9388. + sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
  9389. + }
  9390. +
  9391. + /* End the database scan loop.
  9392. + */
  9393. + sqliteWhereEnd(pWInfo);
  9394. +
  9395. + /* Open the pseudo-table used to store OLD if there are triggers.
  9396. + */
  9397. + if( row_triggers_exist ){
  9398. + sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
  9399. + }
  9400. +
  9401. + /* Delete every item whose key was written to the list during the
  9402. + ** database scan. We have to delete items after the scan is complete
  9403. + ** because deleting an item can change the scan order.
  9404. + */
  9405. + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
  9406. + end = sqliteVdbeMakeLabel(v);
  9407. +
  9408. + /* This is the beginning of the delete loop when there are
  9409. + ** row triggers.
  9410. + */
  9411. + if( row_triggers_exist ){
  9412. + addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
  9413. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  9414. + if( !isView ){
  9415. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  9416. + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
  9417. + }
  9418. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  9419. +
  9420. + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
  9421. + sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
  9422. + sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
  9423. + if( !isView ){
  9424. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  9425. + }
  9426. +
  9427. + sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_BEFORE, pTab, -1,
  9428. + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
  9429. + addr);
  9430. + }
  9431. +
  9432. + if( !isView ){
  9433. + /* Open cursors for the table we are deleting from and all its
  9434. + ** indices. If there are row triggers, this happens inside the
  9435. + ** OP_ListRead loop because the cursor have to all be closed
  9436. + ** before the trigger fires. If there are no row triggers, the
  9437. + ** cursors are opened only once on the outside the loop.
  9438. + */
  9439. + pParse->nTab = iCur + 1;
  9440. + sqliteOpenTableAndIndices(pParse, pTab, iCur);
  9441. +
  9442. + /* This is the beginning of the delete loop when there are no
  9443. + ** row triggers */
  9444. + if( !row_triggers_exist ){
  9445. + addr = sqliteVdbeAddOp(v, OP_ListRead, 0, end);
  9446. + }
  9447. +
  9448. + /* Delete the row */
  9449. + sqliteGenerateRowDelete(db, v, pTab, iCur, pParse->trigStack==0);
  9450. + }
  9451. +
  9452. + /* If there are row triggers, close all cursors then invoke
  9453. + ** the AFTER triggers
  9454. + */
  9455. + if( row_triggers_exist ){
  9456. + if( !isView ){
  9457. + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  9458. + sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
  9459. + }
  9460. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  9461. + }
  9462. + sqliteCodeRowTrigger(pParse, TK_DELETE, 0, TK_AFTER, pTab, -1,
  9463. + oldIdx, (pParse->trigStack)?pParse->trigStack->orconf:OE_Default,
  9464. + addr);
  9465. + }
  9466. +
  9467. + /* End of the delete loop */
  9468. + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
  9469. + sqliteVdbeResolveLabel(v, end);
  9470. + sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
  9471. +
  9472. + /* Close the cursors after the loop if there are no row triggers */
  9473. + if( !row_triggers_exist ){
  9474. + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  9475. + sqliteVdbeAddOp(v, OP_Close, iCur + i, pIdx->tnum);
  9476. + }
  9477. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  9478. + pParse->nTab = iCur;
  9479. + }
  9480. + }
  9481. + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
  9482. + sqliteEndWriteOperation(pParse);
  9483. +
  9484. + /*
  9485. + ** Return the number of rows that were deleted.
  9486. + */
  9487. + if( db->flags & SQLITE_CountRows ){
  9488. + sqliteVdbeAddOp(v, OP_ColumnName, 0, 1);
  9489. + sqliteVdbeChangeP3(v, -1, "rows deleted", P3_STATIC);
  9490. + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
  9491. + }
  9492. +
  9493. +delete_from_cleanup:
  9494. + sqliteAuthContextPop(&sContext);
  9495. + sqliteSrcListDelete(pTabList);
  9496. + sqliteExprDelete(pWhere);
  9497. + return;
  9498. +}
  9499. +
  9500. +/*
  9501. +** This routine generates VDBE code that causes a single row of a
  9502. +** single table to be deleted.
  9503. +**
  9504. +** The VDBE must be in a particular state when this routine is called.
  9505. +** These are the requirements:
  9506. +**
  9507. +** 1. A read/write cursor pointing to pTab, the table containing the row
  9508. +** to be deleted, must be opened as cursor number "base".
  9509. +**
  9510. +** 2. Read/write cursors for all indices of pTab must be open as
  9511. +** cursor number base+i for the i-th index.
  9512. +**
  9513. +** 3. The record number of the row to be deleted must be on the top
  9514. +** of the stack.
  9515. +**
  9516. +** This routine pops the top of the stack to remove the record number
  9517. +** and then generates code to remove both the table record and all index
  9518. +** entries that point to that record.
  9519. +*/
  9520. +void sqliteGenerateRowDelete(
  9521. + sqlite *db, /* The database containing the index */
  9522. + Vdbe *v, /* Generate code into this VDBE */
  9523. + Table *pTab, /* Table containing the row to be deleted */
  9524. + int iCur, /* Cursor number for the table */
  9525. + int count /* Increment the row change counter */
  9526. +){
  9527. + int addr;
  9528. + addr = sqliteVdbeAddOp(v, OP_NotExists, iCur, 0);
  9529. + sqliteGenerateRowIndexDelete(db, v, pTab, iCur, 0);
  9530. + sqliteVdbeAddOp(v, OP_Delete, iCur,
  9531. + (count?OPFLAG_NCHANGE:0) | OPFLAG_CSCHANGE);
  9532. + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
  9533. +}
  9534. +
  9535. +/*
  9536. +** This routine generates VDBE code that causes the deletion of all
  9537. +** index entries associated with a single row of a single table.
  9538. +**
  9539. +** The VDBE must be in a particular state when this routine is called.
  9540. +** These are the requirements:
  9541. +**
  9542. +** 1. A read/write cursor pointing to pTab, the table containing the row
  9543. +** to be deleted, must be opened as cursor number "iCur".
  9544. +**
  9545. +** 2. Read/write cursors for all indices of pTab must be open as
  9546. +** cursor number iCur+i for the i-th index.
  9547. +**
  9548. +** 3. The "iCur" cursor must be pointing to the row that is to be
  9549. +** deleted.
  9550. +*/
  9551. +void sqliteGenerateRowIndexDelete(
  9552. + sqlite *db, /* The database containing the index */
  9553. + Vdbe *v, /* Generate code into this VDBE */
  9554. + Table *pTab, /* Table containing the row to be deleted */
  9555. + int iCur, /* Cursor number for the table */
  9556. + char *aIdxUsed /* Only delete if aIdxUsed!=0 && aIdxUsed[i]!=0 */
  9557. +){
  9558. + int i;
  9559. + Index *pIdx;
  9560. +
  9561. + for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  9562. + int j;
  9563. + if( aIdxUsed!=0 && aIdxUsed[i-1]==0 ) continue;
  9564. + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
  9565. + for(j=0; j<pIdx->nColumn; j++){
  9566. + int idx = pIdx->aiColumn[j];
  9567. + if( idx==pTab->iPKey ){
  9568. + sqliteVdbeAddOp(v, OP_Dup, j, 0);
  9569. + }else{
  9570. + sqliteVdbeAddOp(v, OP_Column, iCur, idx);
  9571. + }
  9572. + }
  9573. + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
  9574. + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
  9575. + sqliteVdbeAddOp(v, OP_IdxDelete, iCur+i, 0);
  9576. + }
  9577. +}
  9578. --- /dev/null
  9579. +++ b/ext/sqlite/libsqlite/src/encode.c
  9580. @@ -0,0 +1,257 @@
  9581. +/*
  9582. +** 2002 April 25
  9583. +**
  9584. +** The author disclaims copyright to this source code. In place of
  9585. +** a legal notice, here is a blessing:
  9586. +**
  9587. +** May you do good and not evil.
  9588. +** May you find forgiveness for yourself and forgive others.
  9589. +** May you share freely, never taking more than you give.
  9590. +**
  9591. +*************************************************************************
  9592. +** This file contains helper routines used to translate binary data into
  9593. +** a null-terminated string (suitable for use in SQLite) and back again.
  9594. +** These are convenience routines for use by people who want to store binary
  9595. +** data in an SQLite database. The code in this file is not used by any other
  9596. +** part of the SQLite library.
  9597. +**
  9598. +** $Id$
  9599. +*/
  9600. +#include <string.h>
  9601. +#include <assert.h>
  9602. +
  9603. +/*
  9604. +** How This Encoder Works
  9605. +**
  9606. +** The output is allowed to contain any character except 0x27 (') and
  9607. +** 0x00. This is accomplished by using an escape character to encode
  9608. +** 0x27 and 0x00 as a two-byte sequence. The escape character is always
  9609. +** 0x01. An 0x00 is encoded as the two byte sequence 0x01 0x01. The
  9610. +** 0x27 character is encoded as the two byte sequence 0x01 0x28. Finally,
  9611. +** the escape character itself is encoded as the two-character sequence
  9612. +** 0x01 0x02.
  9613. +**
  9614. +** To summarize, the encoder works by using an escape sequences as follows:
  9615. +**
  9616. +** 0x00 -> 0x01 0x01
  9617. +** 0x01 -> 0x01 0x02
  9618. +** 0x27 -> 0x01 0x28
  9619. +**
  9620. +** If that were all the encoder did, it would work, but in certain cases
  9621. +** it could double the size of the encoded string. For example, to
  9622. +** encode a string of 100 0x27 characters would require 100 instances of
  9623. +** the 0x01 0x03 escape sequence resulting in a 200-character output.
  9624. +** We would prefer to keep the size of the encoded string smaller than
  9625. +** this.
  9626. +**
  9627. +** To minimize the encoding size, we first add a fixed offset value to each
  9628. +** byte in the sequence. The addition is modulo 256. (That is to say, if
  9629. +** the sum of the original character value and the offset exceeds 256, then
  9630. +** the higher order bits are truncated.) The offset is chosen to minimize
  9631. +** the number of characters in the string that need to be escaped. For
  9632. +** example, in the case above where the string was composed of 100 0x27
  9633. +** characters, the offset might be 0x01. Each of the 0x27 characters would
  9634. +** then be converted into an 0x28 character which would not need to be
  9635. +** escaped at all and so the 100 character input string would be converted
  9636. +** into just 100 characters of output. Actually 101 characters of output -
  9637. +** we have to record the offset used as the first byte in the sequence so
  9638. +** that the string can be decoded. Since the offset value is stored as
  9639. +** part of the output string and the output string is not allowed to contain
  9640. +** characters 0x00 or 0x27, the offset cannot be 0x00 or 0x27.
  9641. +**
  9642. +** Here, then, are the encoding steps:
  9643. +**
  9644. +** (1) Choose an offset value and make it the first character of
  9645. +** output.
  9646. +**
  9647. +** (2) Copy each input character into the output buffer, one by
  9648. +** one, adding the offset value as you copy.
  9649. +**
  9650. +** (3) If the value of an input character plus offset is 0x00, replace
  9651. +** that one character by the two-character sequence 0x01 0x01.
  9652. +** If the sum is 0x01, replace it with 0x01 0x02. If the sum
  9653. +** is 0x27, replace it with 0x01 0x03.
  9654. +**
  9655. +** (4) Put a 0x00 terminator at the end of the output.
  9656. +**
  9657. +** Decoding is obvious:
  9658. +**
  9659. +** (5) Copy encoded characters except the first into the decode
  9660. +** buffer. Set the first encoded character aside for use as
  9661. +** the offset in step 7 below.
  9662. +**
  9663. +** (6) Convert each 0x01 0x01 sequence into a single character 0x00.
  9664. +** Convert 0x01 0x02 into 0x01. Convert 0x01 0x28 into 0x27.
  9665. +**
  9666. +** (7) Subtract the offset value that was the first character of
  9667. +** the encoded buffer from all characters in the output buffer.
  9668. +**
  9669. +** The only tricky part is step (1) - how to compute an offset value to
  9670. +** minimize the size of the output buffer. This is accomplished by testing
  9671. +** all offset values and picking the one that results in the fewest number
  9672. +** of escapes. To do that, we first scan the entire input and count the
  9673. +** number of occurances of each character value in the input. Suppose
  9674. +** the number of 0x00 characters is N(0), the number of occurances of 0x01
  9675. +** is N(1), and so forth up to the number of occurances of 0xff is N(255).
  9676. +** An offset of 0 is not allowed so we don't have to test it. The number
  9677. +** of escapes required for an offset of 1 is N(1)+N(2)+N(40). The number
  9678. +** of escapes required for an offset of 2 is N(2)+N(3)+N(41). And so forth.
  9679. +** In this way we find the offset that gives the minimum number of escapes,
  9680. +** and thus minimizes the length of the output string.
  9681. +*/
  9682. +
  9683. +/*
  9684. +** Encode a binary buffer "in" of size n bytes so that it contains
  9685. +** no instances of characters '\'' or '\000'. The output is
  9686. +** null-terminated and can be used as a string value in an INSERT
  9687. +** or UPDATE statement. Use sqlite_decode_binary() to convert the
  9688. +** string back into its original binary.
  9689. +**
  9690. +** The result is written into a preallocated output buffer "out".
  9691. +** "out" must be able to hold at least 2 +(257*n)/254 bytes.
  9692. +** In other words, the output will be expanded by as much as 3
  9693. +** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
  9694. +** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
  9695. +**
  9696. +** The return value is the number of characters in the encoded
  9697. +** string, excluding the "\000" terminator.
  9698. +**
  9699. +** If out==NULL then no output is generated but the routine still returns
  9700. +** the number of characters that would have been generated if out had
  9701. +** not been NULL.
  9702. +*/
  9703. +int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out){
  9704. + int i, j, e, m;
  9705. + unsigned char x;
  9706. + int cnt[256];
  9707. + if( n<=0 ){
  9708. + if( out ){
  9709. + out[0] = 'x';
  9710. + out[1] = 0;
  9711. + }
  9712. + return 1;
  9713. + }
  9714. + memset(cnt, 0, sizeof(cnt));
  9715. + for(i=n-1; i>=0; i--){ cnt[in[i]]++; }
  9716. + m = n;
  9717. + for(i=1; i<256; i++){
  9718. + int sum;
  9719. + if( i=='\'' ) continue;
  9720. + sum = cnt[i] + cnt[(i+1)&0xff] + cnt[(i+'\'')&0xff];
  9721. + if( sum<m ){
  9722. + m = sum;
  9723. + e = i;
  9724. + if( m==0 ) break;
  9725. + }
  9726. + }
  9727. + if( out==0 ){
  9728. + return n+m+1;
  9729. + }
  9730. + out[0] = e;
  9731. + j = 1;
  9732. + for(i=0; i<n; i++){
  9733. + x = in[i] - e;
  9734. + if( x==0 || x==1 || x=='\''){
  9735. + out[j++] = 1;
  9736. + x++;
  9737. + }
  9738. + out[j++] = x;
  9739. + }
  9740. + out[j] = 0;
  9741. + assert( j==n+m+1 );
  9742. + return j;
  9743. +}
  9744. +
  9745. +/*
  9746. +** Decode the string "in" into binary data and write it into "out".
  9747. +** This routine reverses the encoding created by sqlite_encode_binary().
  9748. +** The output will always be a few bytes less than the input. The number
  9749. +** of bytes of output is returned. If the input is not a well-formed
  9750. +** encoding, -1 is returned.
  9751. +**
  9752. +** The "in" and "out" parameters may point to the same buffer in order
  9753. +** to decode a string in place.
  9754. +*/
  9755. +int sqlite_decode_binary(const unsigned char *in, unsigned char *out){
  9756. + int i, e;
  9757. + unsigned char c;
  9758. + e = *(in++);
  9759. + if (e == 0) {
  9760. + return 0;
  9761. + }
  9762. + i = 0;
  9763. + while( (c = *(in++))!=0 ){
  9764. + if (c == 1) {
  9765. + c = *(in++) - 1;
  9766. + }
  9767. + out[i++] = c + e;
  9768. + }
  9769. + return i;
  9770. +}
  9771. +
  9772. +#ifdef ENCODER_TEST
  9773. +#include <stdio.h>
  9774. +/*
  9775. +** The subroutines above are not tested by the usual test suite. To test
  9776. +** these routines, compile just this one file with a -DENCODER_TEST=1 option
  9777. +** and run the result.
  9778. +*/
  9779. +int main(int argc, char **argv){
  9780. + int i, j, n, m, nOut, nByteIn, nByteOut;
  9781. + unsigned char in[30000];
  9782. + unsigned char out[33000];
  9783. +
  9784. + nByteIn = nByteOut = 0;
  9785. + for(i=0; i<sizeof(in); i++){
  9786. + printf("Test %d: ", i+1);
  9787. + n = rand() % (i+1);
  9788. + if( i%100==0 ){
  9789. + int k;
  9790. + for(j=k=0; j<n; j++){
  9791. + /* if( k==0 || k=='\'' ) k++; */
  9792. + in[j] = k;
  9793. + k = (k+1)&0xff;
  9794. + }
  9795. + }else{
  9796. + for(j=0; j<n; j++) in[j] = rand() & 0xff;
  9797. + }
  9798. + nByteIn += n;
  9799. + nOut = sqlite_encode_binary(in, n, out);
  9800. + nByteOut += nOut;
  9801. + if( nOut!=strlen(out) ){
  9802. + printf(" ERROR return value is %d instead of %d\n", nOut, strlen(out));
  9803. + exit(1);
  9804. + }
  9805. + if( nOut!=sqlite_encode_binary(in, n, 0) ){
  9806. + printf(" ERROR actual output size disagrees with predicted size\n");
  9807. + exit(1);
  9808. + }
  9809. + m = (256*n + 1262)/253;
  9810. + printf("size %d->%d (max %d)", n, strlen(out)+1, m);
  9811. + if( strlen(out)+1>m ){
  9812. + printf(" ERROR output too big\n");
  9813. + exit(1);
  9814. + }
  9815. + for(j=0; out[j]; j++){
  9816. + if( out[j]=='\'' ){
  9817. + printf(" ERROR contains (')\n");
  9818. + exit(1);
  9819. + }
  9820. + }
  9821. + j = sqlite_decode_binary(out, out);
  9822. + if( j!=n ){
  9823. + printf(" ERROR decode size %d\n", j);
  9824. + exit(1);
  9825. + }
  9826. + if( memcmp(in, out, n)!=0 ){
  9827. + printf(" ERROR decode mismatch\n");
  9828. + exit(1);
  9829. + }
  9830. + printf(" OK\n");
  9831. + }
  9832. + fprintf(stderr,"Finished. Total encoding: %d->%d bytes\n",
  9833. + nByteIn, nByteOut);
  9834. + fprintf(stderr,"Avg size increase: %.3f%%\n",
  9835. + (nByteOut-nByteIn)*100.0/(double)nByteIn);
  9836. +}
  9837. +#endif /* ENCODER_TEST */
  9838. --- /dev/null
  9839. +++ b/ext/sqlite/libsqlite/src/expr.c
  9840. @@ -0,0 +1,1662 @@
  9841. +/*
  9842. +** 2001 September 15
  9843. +**
  9844. +** The author disclaims copyright to this source code. In place of
  9845. +** a legal notice, here is a blessing:
  9846. +**
  9847. +** May you do good and not evil.
  9848. +** May you find forgiveness for yourself and forgive others.
  9849. +** May you share freely, never taking more than you give.
  9850. +**
  9851. +*************************************************************************
  9852. +** This file contains routines used for analyzing expressions and
  9853. +** for generating VDBE code that evaluates expressions in SQLite.
  9854. +**
  9855. +** $Id$
  9856. +*/
  9857. +#include "sqliteInt.h"
  9858. +#include <ctype.h>
  9859. +
  9860. +/*
  9861. +** Construct a new expression node and return a pointer to it. Memory
  9862. +** for this node is obtained from sqliteMalloc(). The calling function
  9863. +** is responsible for making sure the node eventually gets freed.
  9864. +*/
  9865. +Expr *sqliteExpr(int op, Expr *pLeft, Expr *pRight, Token *pToken){
  9866. + Expr *pNew;
  9867. + pNew = sqliteMalloc( sizeof(Expr) );
  9868. + if( pNew==0 ){
  9869. + /* When malloc fails, we leak memory from pLeft and pRight */
  9870. + return 0;
  9871. + }
  9872. + pNew->op = op;
  9873. + pNew->pLeft = pLeft;
  9874. + pNew->pRight = pRight;
  9875. + if( pToken ){
  9876. + assert( pToken->dyn==0 );
  9877. + pNew->token = *pToken;
  9878. + pNew->span = *pToken;
  9879. + }else{
  9880. + assert( pNew->token.dyn==0 );
  9881. + assert( pNew->token.z==0 );
  9882. + assert( pNew->token.n==0 );
  9883. + if( pLeft && pRight ){
  9884. + sqliteExprSpan(pNew, &pLeft->span, &pRight->span);
  9885. + }else{
  9886. + pNew->span = pNew->token;
  9887. + }
  9888. + }
  9889. + return pNew;
  9890. +}
  9891. +
  9892. +/*
  9893. +** Set the Expr.span field of the given expression to span all
  9894. +** text between the two given tokens.
  9895. +*/
  9896. +void sqliteExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
  9897. + assert( pRight!=0 );
  9898. + assert( pLeft!=0 );
  9899. + /* Note: pExpr might be NULL due to a prior malloc failure */
  9900. + if( pExpr && pRight->z && pLeft->z ){
  9901. + if( pLeft->dyn==0 && pRight->dyn==0 ){
  9902. + pExpr->span.z = pLeft->z;
  9903. + pExpr->span.n = pRight->n + Addr(pRight->z) - Addr(pLeft->z);
  9904. + }else{
  9905. + pExpr->span.z = 0;
  9906. + }
  9907. + }
  9908. +}
  9909. +
  9910. +/*
  9911. +** Construct a new expression node for a function with multiple
  9912. +** arguments.
  9913. +*/
  9914. +Expr *sqliteExprFunction(ExprList *pList, Token *pToken){
  9915. + Expr *pNew;
  9916. + pNew = sqliteMalloc( sizeof(Expr) );
  9917. + if( pNew==0 ){
  9918. + /* sqliteExprListDelete(pList); // Leak pList when malloc fails */
  9919. + return 0;
  9920. + }
  9921. + pNew->op = TK_FUNCTION;
  9922. + pNew->pList = pList;
  9923. + if( pToken ){
  9924. + assert( pToken->dyn==0 );
  9925. + pNew->token = *pToken;
  9926. + }else{
  9927. + pNew->token.z = 0;
  9928. + }
  9929. + pNew->span = pNew->token;
  9930. + return pNew;
  9931. +}
  9932. +
  9933. +/*
  9934. +** Recursively delete an expression tree.
  9935. +*/
  9936. +void sqliteExprDelete(Expr *p){
  9937. + if( p==0 ) return;
  9938. + if( p->span.dyn ) sqliteFree((char*)p->span.z);
  9939. + if( p->token.dyn ) sqliteFree((char*)p->token.z);
  9940. + sqliteExprDelete(p->pLeft);
  9941. + sqliteExprDelete(p->pRight);
  9942. + sqliteExprListDelete(p->pList);
  9943. + sqliteSelectDelete(p->pSelect);
  9944. + sqliteFree(p);
  9945. +}
  9946. +
  9947. +
  9948. +/*
  9949. +** The following group of routines make deep copies of expressions,
  9950. +** expression lists, ID lists, and select statements. The copies can
  9951. +** be deleted (by being passed to their respective ...Delete() routines)
  9952. +** without effecting the originals.
  9953. +**
  9954. +** The expression list, ID, and source lists return by sqliteExprListDup(),
  9955. +** sqliteIdListDup(), and sqliteSrcListDup() can not be further expanded
  9956. +** by subsequent calls to sqlite*ListAppend() routines.
  9957. +**
  9958. +** Any tables that the SrcList might point to are not duplicated.
  9959. +*/
  9960. +Expr *sqliteExprDup(Expr *p){
  9961. + Expr *pNew;
  9962. + if( p==0 ) return 0;
  9963. + pNew = sqliteMallocRaw( sizeof(*p) );
  9964. + if( pNew==0 ) return 0;
  9965. + memcpy(pNew, p, sizeof(*pNew));
  9966. + if( p->token.z!=0 ){
  9967. + pNew->token.z = sqliteStrNDup(p->token.z, p->token.n);
  9968. + pNew->token.dyn = 1;
  9969. + }else{
  9970. + assert( pNew->token.z==0 );
  9971. + }
  9972. + pNew->span.z = 0;
  9973. + pNew->pLeft = sqliteExprDup(p->pLeft);
  9974. + pNew->pRight = sqliteExprDup(p->pRight);
  9975. + pNew->pList = sqliteExprListDup(p->pList);
  9976. + pNew->pSelect = sqliteSelectDup(p->pSelect);
  9977. + return pNew;
  9978. +}
  9979. +void sqliteTokenCopy(Token *pTo, Token *pFrom){
  9980. + if( pTo->dyn ) sqliteFree((char*)pTo->z);
  9981. + if( pFrom->z ){
  9982. + pTo->n = pFrom->n;
  9983. + pTo->z = sqliteStrNDup(pFrom->z, pFrom->n);
  9984. + pTo->dyn = 1;
  9985. + }else{
  9986. + pTo->z = 0;
  9987. + }
  9988. +}
  9989. +ExprList *sqliteExprListDup(ExprList *p){
  9990. + ExprList *pNew;
  9991. + struct ExprList_item *pItem;
  9992. + int i;
  9993. + if( p==0 ) return 0;
  9994. + pNew = sqliteMalloc( sizeof(*pNew) );
  9995. + if( pNew==0 ) return 0;
  9996. + pNew->nExpr = pNew->nAlloc = p->nExpr;
  9997. + pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
  9998. + if( pItem==0 ){
  9999. + sqliteFree(pNew);
  10000. + return 0;
  10001. + }
  10002. + for(i=0; i<p->nExpr; i++, pItem++){
  10003. + Expr *pNewExpr, *pOldExpr;
  10004. + pItem->pExpr = pNewExpr = sqliteExprDup(pOldExpr = p->a[i].pExpr);
  10005. + if( pOldExpr->span.z!=0 && pNewExpr ){
  10006. + /* Always make a copy of the span for top-level expressions in the
  10007. + ** expression list. The logic in SELECT processing that determines
  10008. + ** the names of columns in the result set needs this information */
  10009. + sqliteTokenCopy(&pNewExpr->span, &pOldExpr->span);
  10010. + }
  10011. + assert( pNewExpr==0 || pNewExpr->span.z!=0
  10012. + || pOldExpr->span.z==0 || sqlite_malloc_failed );
  10013. + pItem->zName = sqliteStrDup(p->a[i].zName);
  10014. + pItem->sortOrder = p->a[i].sortOrder;
  10015. + pItem->isAgg = p->a[i].isAgg;
  10016. + pItem->done = 0;
  10017. + }
  10018. + return pNew;
  10019. +}
  10020. +SrcList *sqliteSrcListDup(SrcList *p){
  10021. + SrcList *pNew;
  10022. + int i;
  10023. + int nByte;
  10024. + if( p==0 ) return 0;
  10025. + nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  10026. + pNew = sqliteMallocRaw( nByte );
  10027. + if( pNew==0 ) return 0;
  10028. + pNew->nSrc = pNew->nAlloc = p->nSrc;
  10029. + for(i=0; i<p->nSrc; i++){
  10030. + struct SrcList_item *pNewItem = &pNew->a[i];
  10031. + struct SrcList_item *pOldItem = &p->a[i];
  10032. + pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
  10033. + pNewItem->zName = sqliteStrDup(pOldItem->zName);
  10034. + pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
  10035. + pNewItem->jointype = pOldItem->jointype;
  10036. + pNewItem->iCursor = pOldItem->iCursor;
  10037. + pNewItem->pTab = 0;
  10038. + pNewItem->pSelect = sqliteSelectDup(pOldItem->pSelect);
  10039. + pNewItem->pOn = sqliteExprDup(pOldItem->pOn);
  10040. + pNewItem->pUsing = sqliteIdListDup(pOldItem->pUsing);
  10041. + }
  10042. + return pNew;
  10043. +}
  10044. +IdList *sqliteIdListDup(IdList *p){
  10045. + IdList *pNew;
  10046. + int i;
  10047. + if( p==0 ) return 0;
  10048. + pNew = sqliteMallocRaw( sizeof(*pNew) );
  10049. + if( pNew==0 ) return 0;
  10050. + pNew->nId = pNew->nAlloc = p->nId;
  10051. + pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
  10052. + if( pNew->a==0 ) return 0;
  10053. + for(i=0; i<p->nId; i++){
  10054. + struct IdList_item *pNewItem = &pNew->a[i];
  10055. + struct IdList_item *pOldItem = &p->a[i];
  10056. + pNewItem->zName = sqliteStrDup(pOldItem->zName);
  10057. + pNewItem->idx = pOldItem->idx;
  10058. + }
  10059. + return pNew;
  10060. +}
  10061. +Select *sqliteSelectDup(Select *p){
  10062. + Select *pNew;
  10063. + if( p==0 ) return 0;
  10064. + pNew = sqliteMallocRaw( sizeof(*p) );
  10065. + if( pNew==0 ) return 0;
  10066. + pNew->isDistinct = p->isDistinct;
  10067. + pNew->pEList = sqliteExprListDup(p->pEList);
  10068. + pNew->pSrc = sqliteSrcListDup(p->pSrc);
  10069. + pNew->pWhere = sqliteExprDup(p->pWhere);
  10070. + pNew->pGroupBy = sqliteExprListDup(p->pGroupBy);
  10071. + pNew->pHaving = sqliteExprDup(p->pHaving);
  10072. + pNew->pOrderBy = sqliteExprListDup(p->pOrderBy);
  10073. + pNew->op = p->op;
  10074. + pNew->pPrior = sqliteSelectDup(p->pPrior);
  10075. + pNew->nLimit = p->nLimit;
  10076. + pNew->nOffset = p->nOffset;
  10077. + pNew->zSelect = 0;
  10078. + pNew->iLimit = -1;
  10079. + pNew->iOffset = -1;
  10080. + return pNew;
  10081. +}
  10082. +
  10083. +
  10084. +/*
  10085. +** Add a new element to the end of an expression list. If pList is
  10086. +** initially NULL, then create a new expression list.
  10087. +*/
  10088. +ExprList *sqliteExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
  10089. + if( pList==0 ){
  10090. + pList = sqliteMalloc( sizeof(ExprList) );
  10091. + if( pList==0 ){
  10092. + /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
  10093. + return 0;
  10094. + }
  10095. + assert( pList->nAlloc==0 );
  10096. + }
  10097. + if( pList->nAlloc<=pList->nExpr ){
  10098. + pList->nAlloc = pList->nAlloc*2 + 4;
  10099. + pList->a = sqliteRealloc(pList->a, pList->nAlloc*sizeof(pList->a[0]));
  10100. + if( pList->a==0 ){
  10101. + /* sqliteExprDelete(pExpr); // Leak memory if malloc fails */
  10102. + pList->nExpr = pList->nAlloc = 0;
  10103. + return pList;
  10104. + }
  10105. + }
  10106. + assert( pList->a!=0 );
  10107. + if( pExpr || pName ){
  10108. + struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  10109. + memset(pItem, 0, sizeof(*pItem));
  10110. + pItem->pExpr = pExpr;
  10111. + if( pName ){
  10112. + sqliteSetNString(&pItem->zName, pName->z, pName->n, 0);
  10113. + sqliteDequote(pItem->zName);
  10114. + }
  10115. + }
  10116. + return pList;
  10117. +}
  10118. +
  10119. +/*
  10120. +** Delete an entire expression list.
  10121. +*/
  10122. +void sqliteExprListDelete(ExprList *pList){
  10123. + int i;
  10124. + if( pList==0 ) return;
  10125. + assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
  10126. + assert( pList->nExpr<=pList->nAlloc );
  10127. + for(i=0; i<pList->nExpr; i++){
  10128. + sqliteExprDelete(pList->a[i].pExpr);
  10129. + sqliteFree(pList->a[i].zName);
  10130. + }
  10131. + sqliteFree(pList->a);
  10132. + sqliteFree(pList);
  10133. +}
  10134. +
  10135. +/*
  10136. +** Walk an expression tree. Return 1 if the expression is constant
  10137. +** and 0 if it involves variables.
  10138. +**
  10139. +** For the purposes of this function, a double-quoted string (ex: "abc")
  10140. +** is considered a variable but a single-quoted string (ex: 'abc') is
  10141. +** a constant.
  10142. +*/
  10143. +int sqliteExprIsConstant(Expr *p){
  10144. + switch( p->op ){
  10145. + case TK_ID:
  10146. + case TK_COLUMN:
  10147. + case TK_DOT:
  10148. + case TK_FUNCTION:
  10149. + return 0;
  10150. + case TK_NULL:
  10151. + case TK_STRING:
  10152. + case TK_INTEGER:
  10153. + case TK_FLOAT:
  10154. + case TK_VARIABLE:
  10155. + return 1;
  10156. + default: {
  10157. + if( p->pLeft && !sqliteExprIsConstant(p->pLeft) ) return 0;
  10158. + if( p->pRight && !sqliteExprIsConstant(p->pRight) ) return 0;
  10159. + if( p->pList ){
  10160. + int i;
  10161. + for(i=0; i<p->pList->nExpr; i++){
  10162. + if( !sqliteExprIsConstant(p->pList->a[i].pExpr) ) return 0;
  10163. + }
  10164. + }
  10165. + return p->pLeft!=0 || p->pRight!=0 || (p->pList && p->pList->nExpr>0);
  10166. + }
  10167. + }
  10168. + return 0;
  10169. +}
  10170. +
  10171. +/*
  10172. +** If the given expression codes a constant integer that is small enough
  10173. +** to fit in a 32-bit integer, return 1 and put the value of the integer
  10174. +** in *pValue. If the expression is not an integer or if it is too big
  10175. +** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  10176. +*/
  10177. +int sqliteExprIsInteger(Expr *p, int *pValue){
  10178. + switch( p->op ){
  10179. + case TK_INTEGER: {
  10180. + if( sqliteFitsIn32Bits(p->token.z) ){
  10181. + *pValue = atoi(p->token.z);
  10182. + return 1;
  10183. + }
  10184. + break;
  10185. + }
  10186. + case TK_STRING: {
  10187. + const char *z = p->token.z;
  10188. + int n = p->token.n;
  10189. + if( n>0 && z[0]=='-' ){ z++; n--; }
  10190. + while( n>0 && *z && isdigit(*z) ){ z++; n--; }
  10191. + if( n==0 && sqliteFitsIn32Bits(p->token.z) ){
  10192. + *pValue = atoi(p->token.z);
  10193. + return 1;
  10194. + }
  10195. + break;
  10196. + }
  10197. + case TK_UPLUS: {
  10198. + return sqliteExprIsInteger(p->pLeft, pValue);
  10199. + }
  10200. + case TK_UMINUS: {
  10201. + int v;
  10202. + if( sqliteExprIsInteger(p->pLeft, &v) ){
  10203. + *pValue = -v;
  10204. + return 1;
  10205. + }
  10206. + break;
  10207. + }
  10208. + default: break;
  10209. + }
  10210. + return 0;
  10211. +}
  10212. +
  10213. +/*
  10214. +** Return TRUE if the given string is a row-id column name.
  10215. +*/
  10216. +int sqliteIsRowid(const char *z){
  10217. + if( sqliteStrICmp(z, "_ROWID_")==0 ) return 1;
  10218. + if( sqliteStrICmp(z, "ROWID")==0 ) return 1;
  10219. + if( sqliteStrICmp(z, "OID")==0 ) return 1;
  10220. + return 0;
  10221. +}
  10222. +
  10223. +/*
  10224. +** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  10225. +** that name in the set of source tables in pSrcList and make the pExpr
  10226. +** expression node refer back to that source column. The following changes
  10227. +** are made to pExpr:
  10228. +**
  10229. +** pExpr->iDb Set the index in db->aDb[] of the database holding
  10230. +** the table.
  10231. +** pExpr->iTable Set to the cursor number for the table obtained
  10232. +** from pSrcList.
  10233. +** pExpr->iColumn Set to the column number within the table.
  10234. +** pExpr->dataType Set to the appropriate data type for the column.
  10235. +** pExpr->op Set to TK_COLUMN.
  10236. +** pExpr->pLeft Any expression this points to is deleted
  10237. +** pExpr->pRight Any expression this points to is deleted.
  10238. +**
  10239. +** The pDbToken is the name of the database (the "X"). This value may be
  10240. +** NULL meaning that name is of the form Y.Z or Z. Any available database
  10241. +** can be used. The pTableToken is the name of the table (the "Y"). This
  10242. +** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
  10243. +** means that the form of the name is Z and that columns from any table
  10244. +** can be used.
  10245. +**
  10246. +** If the name cannot be resolved unambiguously, leave an error message
  10247. +** in pParse and return non-zero. Return zero on success.
  10248. +*/
  10249. +static int lookupName(
  10250. + Parse *pParse, /* The parsing context */
  10251. + Token *pDbToken, /* Name of the database containing table, or NULL */
  10252. + Token *pTableToken, /* Name of table containing column, or NULL */
  10253. + Token *pColumnToken, /* Name of the column. */
  10254. + SrcList *pSrcList, /* List of tables used to resolve column names */
  10255. + ExprList *pEList, /* List of expressions used to resolve "AS" */
  10256. + Expr *pExpr /* Make this EXPR node point to the selected column */
  10257. +){
  10258. + char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
  10259. + char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
  10260. + char *zCol = 0; /* Name of the column. The "Z" */
  10261. + int i, j; /* Loop counters */
  10262. + int cnt = 0; /* Number of matching column names */
  10263. + int cntTab = 0; /* Number of matching table names */
  10264. + sqlite *db = pParse->db; /* The database */
  10265. +
  10266. + assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
  10267. + if( pDbToken && pDbToken->z ){
  10268. + zDb = sqliteStrNDup(pDbToken->z, pDbToken->n);
  10269. + sqliteDequote(zDb);
  10270. + }else{
  10271. + zDb = 0;
  10272. + }
  10273. + if( pTableToken && pTableToken->z ){
  10274. + zTab = sqliteStrNDup(pTableToken->z, pTableToken->n);
  10275. + sqliteDequote(zTab);
  10276. + }else{
  10277. + assert( zDb==0 );
  10278. + zTab = 0;
  10279. + }
  10280. + zCol = sqliteStrNDup(pColumnToken->z, pColumnToken->n);
  10281. + sqliteDequote(zCol);
  10282. + if( sqlite_malloc_failed ){
  10283. + return 1; /* Leak memory (zDb and zTab) if malloc fails */
  10284. + }
  10285. + assert( zTab==0 || pEList==0 );
  10286. +
  10287. + pExpr->iTable = -1;
  10288. + for(i=0; i<pSrcList->nSrc; i++){
  10289. + struct SrcList_item *pItem = &pSrcList->a[i];
  10290. + Table *pTab = pItem->pTab;
  10291. + Column *pCol;
  10292. +
  10293. + if( pTab==0 ) continue;
  10294. + assert( pTab->nCol>0 );
  10295. + if( zTab ){
  10296. + if( pItem->zAlias ){
  10297. + char *zTabName = pItem->zAlias;
  10298. + if( sqliteStrICmp(zTabName, zTab)!=0 ) continue;
  10299. + }else{
  10300. + char *zTabName = pTab->zName;
  10301. + if( zTabName==0 || sqliteStrICmp(zTabName, zTab)!=0 ) continue;
  10302. + if( zDb!=0 && sqliteStrICmp(db->aDb[pTab->iDb].zName, zDb)!=0 ){
  10303. + continue;
  10304. + }
  10305. + }
  10306. + }
  10307. + if( 0==(cntTab++) ){
  10308. + pExpr->iTable = pItem->iCursor;
  10309. + pExpr->iDb = pTab->iDb;
  10310. + }
  10311. + for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  10312. + if( sqliteStrICmp(pCol->zName, zCol)==0 ){
  10313. + cnt++;
  10314. + pExpr->iTable = pItem->iCursor;
  10315. + pExpr->iDb = pTab->iDb;
  10316. + /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  10317. + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
  10318. + pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
  10319. + break;
  10320. + }
  10321. + }
  10322. + }
  10323. +
  10324. + /* If we have not already resolved the name, then maybe
  10325. + ** it is a new.* or old.* trigger argument reference
  10326. + */
  10327. + if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
  10328. + TriggerStack *pTriggerStack = pParse->trigStack;
  10329. + Table *pTab = 0;
  10330. + if( pTriggerStack->newIdx != -1 && sqliteStrICmp("new", zTab) == 0 ){
  10331. + pExpr->iTable = pTriggerStack->newIdx;
  10332. + assert( pTriggerStack->pTab );
  10333. + pTab = pTriggerStack->pTab;
  10334. + }else if( pTriggerStack->oldIdx != -1 && sqliteStrICmp("old", zTab) == 0 ){
  10335. + pExpr->iTable = pTriggerStack->oldIdx;
  10336. + assert( pTriggerStack->pTab );
  10337. + pTab = pTriggerStack->pTab;
  10338. + }
  10339. +
  10340. + if( pTab ){
  10341. + int j;
  10342. + Column *pCol = pTab->aCol;
  10343. +
  10344. + pExpr->iDb = pTab->iDb;
  10345. + cntTab++;
  10346. + for(j=0; j < pTab->nCol; j++, pCol++) {
  10347. + if( sqliteStrICmp(pCol->zName, zCol)==0 ){
  10348. + cnt++;
  10349. + pExpr->iColumn = j==pTab->iPKey ? -1 : j;
  10350. + pExpr->dataType = pCol->sortOrder & SQLITE_SO_TYPEMASK;
  10351. + break;
  10352. + }
  10353. + }
  10354. + }
  10355. + }
  10356. +
  10357. + /*
  10358. + ** Perhaps the name is a reference to the ROWID
  10359. + */
  10360. + if( cnt==0 && cntTab==1 && sqliteIsRowid(zCol) ){
  10361. + cnt = 1;
  10362. + pExpr->iColumn = -1;
  10363. + pExpr->dataType = SQLITE_SO_NUM;
  10364. + }
  10365. +
  10366. + /*
  10367. + ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  10368. + ** might refer to an result-set alias. This happens, for example, when
  10369. + ** we are resolving names in the WHERE clause of the following command:
  10370. + **
  10371. + ** SELECT a+b AS x FROM table WHERE x<10;
  10372. + **
  10373. + ** In cases like this, replace pExpr with a copy of the expression that
  10374. + ** forms the result set entry ("a+b" in the example) and return immediately.
  10375. + ** Note that the expression in the result set should have already been
  10376. + ** resolved by the time the WHERE clause is resolved.
  10377. + */
  10378. + if( cnt==0 && pEList!=0 ){
  10379. + for(j=0; j<pEList->nExpr; j++){
  10380. + char *zAs = pEList->a[j].zName;
  10381. + if( zAs!=0 && sqliteStrICmp(zAs, zCol)==0 ){
  10382. + assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  10383. + pExpr->op = TK_AS;
  10384. + pExpr->iColumn = j;
  10385. + pExpr->pLeft = sqliteExprDup(pEList->a[j].pExpr);
  10386. + sqliteFree(zCol);
  10387. + assert( zTab==0 && zDb==0 );
  10388. + return 0;
  10389. + }
  10390. + }
  10391. + }
  10392. +
  10393. + /*
  10394. + ** If X and Y are NULL (in other words if only the column name Z is
  10395. + ** supplied) and the value of Z is enclosed in double-quotes, then
  10396. + ** Z is a string literal if it doesn't match any column names. In that
  10397. + ** case, we need to return right away and not make any changes to
  10398. + ** pExpr.
  10399. + */
  10400. + if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
  10401. + sqliteFree(zCol);
  10402. + return 0;
  10403. + }
  10404. +
  10405. + /*
  10406. + ** cnt==0 means there was not match. cnt>1 means there were two or
  10407. + ** more matches. Either way, we have an error.
  10408. + */
  10409. + if( cnt!=1 ){
  10410. + char *z = 0;
  10411. + char *zErr;
  10412. + zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
  10413. + if( zDb ){
  10414. + sqliteSetString(&z, zDb, ".", zTab, ".", zCol, 0);
  10415. + }else if( zTab ){
  10416. + sqliteSetString(&z, zTab, ".", zCol, 0);
  10417. + }else{
  10418. + z = sqliteStrDup(zCol);
  10419. + }
  10420. + sqliteErrorMsg(pParse, zErr, z);
  10421. + sqliteFree(z);
  10422. + }
  10423. +
  10424. + /* Clean up and return
  10425. + */
  10426. + sqliteFree(zDb);
  10427. + sqliteFree(zTab);
  10428. + sqliteFree(zCol);
  10429. + sqliteExprDelete(pExpr->pLeft);
  10430. + pExpr->pLeft = 0;
  10431. + sqliteExprDelete(pExpr->pRight);
  10432. + pExpr->pRight = 0;
  10433. + pExpr->op = TK_COLUMN;
  10434. + sqliteAuthRead(pParse, pExpr, pSrcList);
  10435. + return cnt!=1;
  10436. +}
  10437. +
  10438. +/*
  10439. +** This routine walks an expression tree and resolves references to
  10440. +** table columns. Nodes of the form ID.ID or ID resolve into an
  10441. +** index to the table in the table list and a column offset. The
  10442. +** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
  10443. +** value is changed to the index of the referenced table in pTabList
  10444. +** plus the "base" value. The base value will ultimately become the
  10445. +** VDBE cursor number for a cursor that is pointing into the referenced
  10446. +** table. The Expr.iColumn value is changed to the index of the column
  10447. +** of the referenced table. The Expr.iColumn value for the special
  10448. +** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
  10449. +** alias for ROWID.
  10450. +**
  10451. +** We also check for instances of the IN operator. IN comes in two
  10452. +** forms:
  10453. +**
  10454. +** expr IN (exprlist)
  10455. +** and
  10456. +** expr IN (SELECT ...)
  10457. +**
  10458. +** The first form is handled by creating a set holding the list
  10459. +** of allowed values. The second form causes the SELECT to generate
  10460. +** a temporary table.
  10461. +**
  10462. +** This routine also looks for scalar SELECTs that are part of an expression.
  10463. +** If it finds any, it generates code to write the value of that select
  10464. +** into a memory cell.
  10465. +**
  10466. +** Unknown columns or tables provoke an error. The function returns
  10467. +** the number of errors seen and leaves an error message on pParse->zErrMsg.
  10468. +*/
  10469. +int sqliteExprResolveIds(
  10470. + Parse *pParse, /* The parser context */
  10471. + SrcList *pSrcList, /* List of tables used to resolve column names */
  10472. + ExprList *pEList, /* List of expressions used to resolve "AS" */
  10473. + Expr *pExpr /* The expression to be analyzed. */
  10474. +){
  10475. + int i;
  10476. +
  10477. + if( pExpr==0 || pSrcList==0 ) return 0;
  10478. + for(i=0; i<pSrcList->nSrc; i++){
  10479. + assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab );
  10480. + }
  10481. + switch( pExpr->op ){
  10482. + /* Double-quoted strings (ex: "abc") are used as identifiers if
  10483. + ** possible. Otherwise they remain as strings. Single-quoted
  10484. + ** strings (ex: 'abc') are always string literals.
  10485. + */
  10486. + case TK_STRING: {
  10487. + if( pExpr->token.z[0]=='\'' ) break;
  10488. + /* Fall thru into the TK_ID case if this is a double-quoted string */
  10489. + }
  10490. + /* A lone identifier is the name of a columnd.
  10491. + */
  10492. + case TK_ID: {
  10493. + if( lookupName(pParse, 0, 0, &pExpr->token, pSrcList, pEList, pExpr) ){
  10494. + return 1;
  10495. + }
  10496. + break;
  10497. + }
  10498. +
  10499. + /* A table name and column name: ID.ID
  10500. + ** Or a database, table and column: ID.ID.ID
  10501. + */
  10502. + case TK_DOT: {
  10503. + Token *pColumn;
  10504. + Token *pTable;
  10505. + Token *pDb;
  10506. + Expr *pRight;
  10507. +
  10508. + pRight = pExpr->pRight;
  10509. + if( pRight->op==TK_ID ){
  10510. + pDb = 0;
  10511. + pTable = &pExpr->pLeft->token;
  10512. + pColumn = &pRight->token;
  10513. + }else{
  10514. + assert( pRight->op==TK_DOT );
  10515. + pDb = &pExpr->pLeft->token;
  10516. + pTable = &pRight->pLeft->token;
  10517. + pColumn = &pRight->pRight->token;
  10518. + }
  10519. + if( lookupName(pParse, pDb, pTable, pColumn, pSrcList, 0, pExpr) ){
  10520. + return 1;
  10521. + }
  10522. + break;
  10523. + }
  10524. +
  10525. + case TK_IN: {
  10526. + Vdbe *v = sqliteGetVdbe(pParse);
  10527. + if( v==0 ) return 1;
  10528. + if( sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
  10529. + return 1;
  10530. + }
  10531. + if( pExpr->pSelect ){
  10532. + /* Case 1: expr IN (SELECT ...)
  10533. + **
  10534. + ** Generate code to write the results of the select into a temporary
  10535. + ** table. The cursor number of the temporary table has already
  10536. + ** been put in iTable by sqliteExprResolveInSelect().
  10537. + */
  10538. + pExpr->iTable = pParse->nTab++;
  10539. + sqliteVdbeAddOp(v, OP_OpenTemp, pExpr->iTable, 1);
  10540. + sqliteSelect(pParse, pExpr->pSelect, SRT_Set, pExpr->iTable, 0,0,0);
  10541. + }else if( pExpr->pList ){
  10542. + /* Case 2: expr IN (exprlist)
  10543. + **
  10544. + ** Create a set to put the exprlist values in. The Set id is stored
  10545. + ** in iTable.
  10546. + */
  10547. + int i, iSet;
  10548. + for(i=0; i<pExpr->pList->nExpr; i++){
  10549. + Expr *pE2 = pExpr->pList->a[i].pExpr;
  10550. + if( !sqliteExprIsConstant(pE2) ){
  10551. + sqliteErrorMsg(pParse,
  10552. + "right-hand side of IN operator must be constant");
  10553. + return 1;
  10554. + }
  10555. + if( sqliteExprCheck(pParse, pE2, 0, 0) ){
  10556. + return 1;
  10557. + }
  10558. + }
  10559. + iSet = pExpr->iTable = pParse->nSet++;
  10560. + for(i=0; i<pExpr->pList->nExpr; i++){
  10561. + Expr *pE2 = pExpr->pList->a[i].pExpr;
  10562. + switch( pE2->op ){
  10563. + case TK_FLOAT:
  10564. + case TK_INTEGER:
  10565. + case TK_STRING: {
  10566. + int addr;
  10567. + assert( pE2->token.z );
  10568. + addr = sqliteVdbeOp3(v, OP_SetInsert, iSet, 0,
  10569. + pE2->token.z, pE2->token.n);
  10570. + sqliteVdbeDequoteP3(v, addr);
  10571. + break;
  10572. + }
  10573. + default: {
  10574. + sqliteExprCode(pParse, pE2);
  10575. + sqliteVdbeAddOp(v, OP_SetInsert, iSet, 0);
  10576. + break;
  10577. + }
  10578. + }
  10579. + }
  10580. + }
  10581. + break;
  10582. + }
  10583. +
  10584. + case TK_SELECT: {
  10585. + /* This has to be a scalar SELECT. Generate code to put the
  10586. + ** value of this select in a memory cell and record the number
  10587. + ** of the memory cell in iColumn.
  10588. + */
  10589. + pExpr->iColumn = pParse->nMem++;
  10590. + if( sqliteSelect(pParse, pExpr->pSelect, SRT_Mem, pExpr->iColumn,0,0,0) ){
  10591. + return 1;
  10592. + }
  10593. + break;
  10594. + }
  10595. +
  10596. + /* For all else, just recursively walk the tree */
  10597. + default: {
  10598. + if( pExpr->pLeft
  10599. + && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pLeft) ){
  10600. + return 1;
  10601. + }
  10602. + if( pExpr->pRight
  10603. + && sqliteExprResolveIds(pParse, pSrcList, pEList, pExpr->pRight) ){
  10604. + return 1;
  10605. + }
  10606. + if( pExpr->pList ){
  10607. + int i;
  10608. + ExprList *pList = pExpr->pList;
  10609. + for(i=0; i<pList->nExpr; i++){
  10610. + Expr *pArg = pList->a[i].pExpr;
  10611. + if( sqliteExprResolveIds(pParse, pSrcList, pEList, pArg) ){
  10612. + return 1;
  10613. + }
  10614. + }
  10615. + }
  10616. + }
  10617. + }
  10618. + return 0;
  10619. +}
  10620. +
  10621. +/*
  10622. +** pExpr is a node that defines a function of some kind. It might
  10623. +** be a syntactic function like "count(x)" or it might be a function
  10624. +** that implements an operator, like "a LIKE b".
  10625. +**
  10626. +** This routine makes *pzName point to the name of the function and
  10627. +** *pnName hold the number of characters in the function name.
  10628. +*/
  10629. +static void getFunctionName(Expr *pExpr, const char **pzName, int *pnName){
  10630. + switch( pExpr->op ){
  10631. + case TK_FUNCTION: {
  10632. + *pzName = pExpr->token.z;
  10633. + *pnName = pExpr->token.n;
  10634. + break;
  10635. + }
  10636. + case TK_LIKE: {
  10637. + *pzName = "like";
  10638. + *pnName = 4;
  10639. + break;
  10640. + }
  10641. + case TK_GLOB: {
  10642. + *pzName = "glob";
  10643. + *pnName = 4;
  10644. + break;
  10645. + }
  10646. + default: {
  10647. + *pzName = "can't happen";
  10648. + *pnName = 12;
  10649. + break;
  10650. + }
  10651. + }
  10652. +}
  10653. +
  10654. +/*
  10655. +** Error check the functions in an expression. Make sure all
  10656. +** function names are recognized and all functions have the correct
  10657. +** number of arguments. Leave an error message in pParse->zErrMsg
  10658. +** if anything is amiss. Return the number of errors.
  10659. +**
  10660. +** if pIsAgg is not null and this expression is an aggregate function
  10661. +** (like count(*) or max(value)) then write a 1 into *pIsAgg.
  10662. +*/
  10663. +int sqliteExprCheck(Parse *pParse, Expr *pExpr, int allowAgg, int *pIsAgg){
  10664. + int nErr = 0;
  10665. + if( pExpr==0 ) return 0;
  10666. + switch( pExpr->op ){
  10667. + case TK_GLOB:
  10668. + case TK_LIKE:
  10669. + case TK_FUNCTION: {
  10670. + int n = pExpr->pList ? pExpr->pList->nExpr : 0; /* Number of arguments */
  10671. + int no_such_func = 0; /* True if no such function exists */
  10672. + int wrong_num_args = 0; /* True if wrong number of arguments */
  10673. + int is_agg = 0; /* True if is an aggregate function */
  10674. + int i;
  10675. + int nId; /* Number of characters in function name */
  10676. + const char *zId; /* The function name. */
  10677. + FuncDef *pDef;
  10678. +
  10679. + getFunctionName(pExpr, &zId, &nId);
  10680. + pDef = sqliteFindFunction(pParse->db, zId, nId, n, 0);
  10681. + if( pDef==0 ){
  10682. + pDef = sqliteFindFunction(pParse->db, zId, nId, -1, 0);
  10683. + if( pDef==0 ){
  10684. + no_such_func = 1;
  10685. + }else{
  10686. + wrong_num_args = 1;
  10687. + }
  10688. + }else{
  10689. + is_agg = pDef->xFunc==0;
  10690. + }
  10691. + if( is_agg && !allowAgg ){
  10692. + sqliteErrorMsg(pParse, "misuse of aggregate function %.*s()", nId, zId);
  10693. + nErr++;
  10694. + is_agg = 0;
  10695. + }else if( no_such_func ){
  10696. + sqliteErrorMsg(pParse, "no such function: %.*s", nId, zId);
  10697. + nErr++;
  10698. + }else if( wrong_num_args ){
  10699. + sqliteErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  10700. + nId, zId);
  10701. + nErr++;
  10702. + }
  10703. + if( is_agg ){
  10704. + pExpr->op = TK_AGG_FUNCTION;
  10705. + if( pIsAgg ) *pIsAgg = 1;
  10706. + }
  10707. + for(i=0; nErr==0 && i<n; i++){
  10708. + nErr = sqliteExprCheck(pParse, pExpr->pList->a[i].pExpr,
  10709. + allowAgg && !is_agg, pIsAgg);
  10710. + }
  10711. + if( pDef==0 ){
  10712. + /* Already reported an error */
  10713. + }else if( pDef->dataType>=0 ){
  10714. + if( pDef->dataType<n ){
  10715. + pExpr->dataType =
  10716. + sqliteExprType(pExpr->pList->a[pDef->dataType].pExpr);
  10717. + }else{
  10718. + pExpr->dataType = SQLITE_SO_NUM;
  10719. + }
  10720. + }else if( pDef->dataType==SQLITE_ARGS ){
  10721. + pDef->dataType = SQLITE_SO_TEXT;
  10722. + for(i=0; i<n; i++){
  10723. + if( sqliteExprType(pExpr->pList->a[i].pExpr)==SQLITE_SO_NUM ){
  10724. + pExpr->dataType = SQLITE_SO_NUM;
  10725. + break;
  10726. + }
  10727. + }
  10728. + }else if( pDef->dataType==SQLITE_NUMERIC ){
  10729. + pExpr->dataType = SQLITE_SO_NUM;
  10730. + }else{
  10731. + pExpr->dataType = SQLITE_SO_TEXT;
  10732. + }
  10733. + }
  10734. + default: {
  10735. + if( pExpr->pLeft ){
  10736. + nErr = sqliteExprCheck(pParse, pExpr->pLeft, allowAgg, pIsAgg);
  10737. + }
  10738. + if( nErr==0 && pExpr->pRight ){
  10739. + nErr = sqliteExprCheck(pParse, pExpr->pRight, allowAgg, pIsAgg);
  10740. + }
  10741. + if( nErr==0 && pExpr->pList ){
  10742. + int n = pExpr->pList->nExpr;
  10743. + int i;
  10744. + for(i=0; nErr==0 && i<n; i++){
  10745. + Expr *pE2 = pExpr->pList->a[i].pExpr;
  10746. + nErr = sqliteExprCheck(pParse, pE2, allowAgg, pIsAgg);
  10747. + }
  10748. + }
  10749. + break;
  10750. + }
  10751. + }
  10752. + return nErr;
  10753. +}
  10754. +
  10755. +/*
  10756. +** Return either SQLITE_SO_NUM or SQLITE_SO_TEXT to indicate whether the
  10757. +** given expression should sort as numeric values or as text.
  10758. +**
  10759. +** The sqliteExprResolveIds() and sqliteExprCheck() routines must have
  10760. +** both been called on the expression before it is passed to this routine.
  10761. +*/
  10762. +int sqliteExprType(Expr *p){
  10763. + if( p==0 ) return SQLITE_SO_NUM;
  10764. + while( p ) switch( p->op ){
  10765. + case TK_PLUS:
  10766. + case TK_MINUS:
  10767. + case TK_STAR:
  10768. + case TK_SLASH:
  10769. + case TK_AND:
  10770. + case TK_OR:
  10771. + case TK_ISNULL:
  10772. + case TK_NOTNULL:
  10773. + case TK_NOT:
  10774. + case TK_UMINUS:
  10775. + case TK_UPLUS:
  10776. + case TK_BITAND:
  10777. + case TK_BITOR:
  10778. + case TK_BITNOT:
  10779. + case TK_LSHIFT:
  10780. + case TK_RSHIFT:
  10781. + case TK_REM:
  10782. + case TK_INTEGER:
  10783. + case TK_FLOAT:
  10784. + case TK_IN:
  10785. + case TK_BETWEEN:
  10786. + case TK_GLOB:
  10787. + case TK_LIKE:
  10788. + return SQLITE_SO_NUM;
  10789. +
  10790. + case TK_STRING:
  10791. + case TK_NULL:
  10792. + case TK_CONCAT:
  10793. + case TK_VARIABLE:
  10794. + return SQLITE_SO_TEXT;
  10795. +
  10796. + case TK_LT:
  10797. + case TK_LE:
  10798. + case TK_GT:
  10799. + case TK_GE:
  10800. + case TK_NE:
  10801. + case TK_EQ:
  10802. + if( sqliteExprType(p->pLeft)==SQLITE_SO_NUM ){
  10803. + return SQLITE_SO_NUM;
  10804. + }
  10805. + p = p->pRight;
  10806. + break;
  10807. +
  10808. + case TK_AS:
  10809. + p = p->pLeft;
  10810. + break;
  10811. +
  10812. + case TK_COLUMN:
  10813. + case TK_FUNCTION:
  10814. + case TK_AGG_FUNCTION:
  10815. + return p->dataType;
  10816. +
  10817. + case TK_SELECT:
  10818. + assert( p->pSelect );
  10819. + assert( p->pSelect->pEList );
  10820. + assert( p->pSelect->pEList->nExpr>0 );
  10821. + p = p->pSelect->pEList->a[0].pExpr;
  10822. + break;
  10823. +
  10824. + case TK_CASE: {
  10825. + if( p->pRight && sqliteExprType(p->pRight)==SQLITE_SO_NUM ){
  10826. + return SQLITE_SO_NUM;
  10827. + }
  10828. + if( p->pList ){
  10829. + int i;
  10830. + ExprList *pList = p->pList;
  10831. + for(i=1; i<pList->nExpr; i+=2){
  10832. + if( sqliteExprType(pList->a[i].pExpr)==SQLITE_SO_NUM ){
  10833. + return SQLITE_SO_NUM;
  10834. + }
  10835. + }
  10836. + }
  10837. + return SQLITE_SO_TEXT;
  10838. + }
  10839. +
  10840. + default:
  10841. + assert( p->op==TK_ABORT ); /* Can't Happen */
  10842. + break;
  10843. + }
  10844. + return SQLITE_SO_NUM;
  10845. +}
  10846. +
  10847. +/*
  10848. +** Generate code into the current Vdbe to evaluate the given
  10849. +** expression and leave the result on the top of stack.
  10850. +*/
  10851. +void sqliteExprCode(Parse *pParse, Expr *pExpr){
  10852. + Vdbe *v = pParse->pVdbe;
  10853. + int op;
  10854. + if( v==0 || pExpr==0 ) return;
  10855. + switch( pExpr->op ){
  10856. + case TK_PLUS: op = OP_Add; break;
  10857. + case TK_MINUS: op = OP_Subtract; break;
  10858. + case TK_STAR: op = OP_Multiply; break;
  10859. + case TK_SLASH: op = OP_Divide; break;
  10860. + case TK_AND: op = OP_And; break;
  10861. + case TK_OR: op = OP_Or; break;
  10862. + case TK_LT: op = OP_Lt; break;
  10863. + case TK_LE: op = OP_Le; break;
  10864. + case TK_GT: op = OP_Gt; break;
  10865. + case TK_GE: op = OP_Ge; break;
  10866. + case TK_NE: op = OP_Ne; break;
  10867. + case TK_EQ: op = OP_Eq; break;
  10868. + case TK_ISNULL: op = OP_IsNull; break;
  10869. + case TK_NOTNULL: op = OP_NotNull; break;
  10870. + case TK_NOT: op = OP_Not; break;
  10871. + case TK_UMINUS: op = OP_Negative; break;
  10872. + case TK_BITAND: op = OP_BitAnd; break;
  10873. + case TK_BITOR: op = OP_BitOr; break;
  10874. + case TK_BITNOT: op = OP_BitNot; break;
  10875. + case TK_LSHIFT: op = OP_ShiftLeft; break;
  10876. + case TK_RSHIFT: op = OP_ShiftRight; break;
  10877. + case TK_REM: op = OP_Remainder; break;
  10878. + default: break;
  10879. + }
  10880. + switch( pExpr->op ){
  10881. + case TK_COLUMN: {
  10882. + if( pParse->useAgg ){
  10883. + sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
  10884. + }else if( pExpr->iColumn>=0 ){
  10885. + sqliteVdbeAddOp(v, OP_Column, pExpr->iTable, pExpr->iColumn);
  10886. + }else{
  10887. + sqliteVdbeAddOp(v, OP_Recno, pExpr->iTable, 0);
  10888. + }
  10889. + break;
  10890. + }
  10891. + case TK_STRING:
  10892. + case TK_FLOAT:
  10893. + case TK_INTEGER: {
  10894. + if( pExpr->op==TK_INTEGER && sqliteFitsIn32Bits(pExpr->token.z) ){
  10895. + sqliteVdbeAddOp(v, OP_Integer, atoi(pExpr->token.z), 0);
  10896. + }else{
  10897. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  10898. + }
  10899. + assert( pExpr->token.z );
  10900. + sqliteVdbeChangeP3(v, -1, pExpr->token.z, pExpr->token.n);
  10901. + sqliteVdbeDequoteP3(v, -1);
  10902. + break;
  10903. + }
  10904. + case TK_NULL: {
  10905. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  10906. + break;
  10907. + }
  10908. + case TK_VARIABLE: {
  10909. + sqliteVdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
  10910. + break;
  10911. + }
  10912. + case TK_LT:
  10913. + case TK_LE:
  10914. + case TK_GT:
  10915. + case TK_GE:
  10916. + case TK_NE:
  10917. + case TK_EQ: {
  10918. + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
  10919. + op += 6; /* Convert numeric opcodes to text opcodes */
  10920. + }
  10921. + /* Fall through into the next case */
  10922. + }
  10923. + case TK_AND:
  10924. + case TK_OR:
  10925. + case TK_PLUS:
  10926. + case TK_STAR:
  10927. + case TK_MINUS:
  10928. + case TK_REM:
  10929. + case TK_BITAND:
  10930. + case TK_BITOR:
  10931. + case TK_SLASH: {
  10932. + sqliteExprCode(pParse, pExpr->pLeft);
  10933. + sqliteExprCode(pParse, pExpr->pRight);
  10934. + sqliteVdbeAddOp(v, op, 0, 0);
  10935. + break;
  10936. + }
  10937. + case TK_LSHIFT:
  10938. + case TK_RSHIFT: {
  10939. + sqliteExprCode(pParse, pExpr->pRight);
  10940. + sqliteExprCode(pParse, pExpr->pLeft);
  10941. + sqliteVdbeAddOp(v, op, 0, 0);
  10942. + break;
  10943. + }
  10944. + case TK_CONCAT: {
  10945. + sqliteExprCode(pParse, pExpr->pLeft);
  10946. + sqliteExprCode(pParse, pExpr->pRight);
  10947. + sqliteVdbeAddOp(v, OP_Concat, 2, 0);
  10948. + break;
  10949. + }
  10950. + case TK_UMINUS: {
  10951. + assert( pExpr->pLeft );
  10952. + if( pExpr->pLeft->op==TK_FLOAT || pExpr->pLeft->op==TK_INTEGER ){
  10953. + Token *p = &pExpr->pLeft->token;
  10954. + char *z = sqliteMalloc( p->n + 2 );
  10955. + sprintf(z, "-%.*s", p->n, p->z);
  10956. + if( pExpr->pLeft->op==TK_INTEGER && sqliteFitsIn32Bits(z) ){
  10957. + sqliteVdbeAddOp(v, OP_Integer, atoi(z), 0);
  10958. + }else{
  10959. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  10960. + }
  10961. + sqliteVdbeChangeP3(v, -1, z, p->n+1);
  10962. + sqliteFree(z);
  10963. + break;
  10964. + }
  10965. + /* Fall through into TK_NOT */
  10966. + }
  10967. + case TK_BITNOT:
  10968. + case TK_NOT: {
  10969. + sqliteExprCode(pParse, pExpr->pLeft);
  10970. + sqliteVdbeAddOp(v, op, 0, 0);
  10971. + break;
  10972. + }
  10973. + case TK_ISNULL:
  10974. + case TK_NOTNULL: {
  10975. + int dest;
  10976. + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
  10977. + sqliteExprCode(pParse, pExpr->pLeft);
  10978. + dest = sqliteVdbeCurrentAddr(v) + 2;
  10979. + sqliteVdbeAddOp(v, op, 1, dest);
  10980. + sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
  10981. + break;
  10982. + }
  10983. + case TK_AGG_FUNCTION: {
  10984. + sqliteVdbeAddOp(v, OP_AggGet, 0, pExpr->iAgg);
  10985. + break;
  10986. + }
  10987. + case TK_GLOB:
  10988. + case TK_LIKE:
  10989. + case TK_FUNCTION: {
  10990. + ExprList *pList = pExpr->pList;
  10991. + int nExpr = pList ? pList->nExpr : 0;
  10992. + FuncDef *pDef;
  10993. + int nId;
  10994. + const char *zId;
  10995. + getFunctionName(pExpr, &zId, &nId);
  10996. + pDef = sqliteFindFunction(pParse->db, zId, nId, nExpr, 0);
  10997. + assert( pDef!=0 );
  10998. + nExpr = sqliteExprCodeExprList(pParse, pList, pDef->includeTypes);
  10999. + sqliteVdbeOp3(v, OP_Function, nExpr, 0, (char*)pDef, P3_POINTER);
  11000. + break;
  11001. + }
  11002. + case TK_SELECT: {
  11003. + sqliteVdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
  11004. + break;
  11005. + }
  11006. + case TK_IN: {
  11007. + int addr;
  11008. + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
  11009. + sqliteExprCode(pParse, pExpr->pLeft);
  11010. + addr = sqliteVdbeCurrentAddr(v);
  11011. + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+4);
  11012. + sqliteVdbeAddOp(v, OP_Pop, 2, 0);
  11013. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  11014. + sqliteVdbeAddOp(v, OP_Goto, 0, addr+6);
  11015. + if( pExpr->pSelect ){
  11016. + sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, addr+6);
  11017. + }else{
  11018. + sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, addr+6);
  11019. + }
  11020. + sqliteVdbeAddOp(v, OP_AddImm, -1, 0);
  11021. + break;
  11022. + }
  11023. + case TK_BETWEEN: {
  11024. + sqliteExprCode(pParse, pExpr->pLeft);
  11025. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  11026. + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
  11027. + sqliteVdbeAddOp(v, OP_Ge, 0, 0);
  11028. + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
  11029. + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
  11030. + sqliteVdbeAddOp(v, OP_Le, 0, 0);
  11031. + sqliteVdbeAddOp(v, OP_And, 0, 0);
  11032. + break;
  11033. + }
  11034. + case TK_UPLUS:
  11035. + case TK_AS: {
  11036. + sqliteExprCode(pParse, pExpr->pLeft);
  11037. + break;
  11038. + }
  11039. + case TK_CASE: {
  11040. + int expr_end_label;
  11041. + int jumpInst;
  11042. + int addr;
  11043. + int nExpr;
  11044. + int i;
  11045. +
  11046. + assert(pExpr->pList);
  11047. + assert((pExpr->pList->nExpr % 2) == 0);
  11048. + assert(pExpr->pList->nExpr > 0);
  11049. + nExpr = pExpr->pList->nExpr;
  11050. + expr_end_label = sqliteVdbeMakeLabel(v);
  11051. + if( pExpr->pLeft ){
  11052. + sqliteExprCode(pParse, pExpr->pLeft);
  11053. + }
  11054. + for(i=0; i<nExpr; i=i+2){
  11055. + sqliteExprCode(pParse, pExpr->pList->a[i].pExpr);
  11056. + if( pExpr->pLeft ){
  11057. + sqliteVdbeAddOp(v, OP_Dup, 1, 1);
  11058. + jumpInst = sqliteVdbeAddOp(v, OP_Ne, 1, 0);
  11059. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11060. + }else{
  11061. + jumpInst = sqliteVdbeAddOp(v, OP_IfNot, 1, 0);
  11062. + }
  11063. + sqliteExprCode(pParse, pExpr->pList->a[i+1].pExpr);
  11064. + sqliteVdbeAddOp(v, OP_Goto, 0, expr_end_label);
  11065. + addr = sqliteVdbeCurrentAddr(v);
  11066. + sqliteVdbeChangeP2(v, jumpInst, addr);
  11067. + }
  11068. + if( pExpr->pLeft ){
  11069. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11070. + }
  11071. + if( pExpr->pRight ){
  11072. + sqliteExprCode(pParse, pExpr->pRight);
  11073. + }else{
  11074. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  11075. + }
  11076. + sqliteVdbeResolveLabel(v, expr_end_label);
  11077. + break;
  11078. + }
  11079. + case TK_RAISE: {
  11080. + if( !pParse->trigStack ){
  11081. + sqliteErrorMsg(pParse,
  11082. + "RAISE() may only be used within a trigger-program");
  11083. + pParse->nErr++;
  11084. + return;
  11085. + }
  11086. + if( pExpr->iColumn == OE_Rollback ||
  11087. + pExpr->iColumn == OE_Abort ||
  11088. + pExpr->iColumn == OE_Fail ){
  11089. + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
  11090. + pExpr->token.z, pExpr->token.n);
  11091. + sqliteVdbeDequoteP3(v, -1);
  11092. + } else {
  11093. + assert( pExpr->iColumn == OE_Ignore );
  11094. + sqliteVdbeOp3(v, OP_Goto, 0, pParse->trigStack->ignoreJump,
  11095. + "(IGNORE jump)", 0);
  11096. + }
  11097. + }
  11098. + break;
  11099. + }
  11100. +}
  11101. +
  11102. +/*
  11103. +** Generate code that pushes the value of every element of the given
  11104. +** expression list onto the stack. If the includeTypes flag is true,
  11105. +** then also push a string that is the datatype of each element onto
  11106. +** the stack after the value.
  11107. +**
  11108. +** Return the number of elements pushed onto the stack.
  11109. +*/
  11110. +int sqliteExprCodeExprList(
  11111. + Parse *pParse, /* Parsing context */
  11112. + ExprList *pList, /* The expression list to be coded */
  11113. + int includeTypes /* TRUE to put datatypes on the stack too */
  11114. +){
  11115. + struct ExprList_item *pItem;
  11116. + int i, n;
  11117. + Vdbe *v;
  11118. + if( pList==0 ) return 0;
  11119. + v = sqliteGetVdbe(pParse);
  11120. + n = pList->nExpr;
  11121. + for(pItem=pList->a, i=0; i<n; i++, pItem++){
  11122. + sqliteExprCode(pParse, pItem->pExpr);
  11123. + if( includeTypes ){
  11124. + sqliteVdbeOp3(v, OP_String, 0, 0,
  11125. + sqliteExprType(pItem->pExpr)==SQLITE_SO_NUM ? "numeric" : "text",
  11126. + P3_STATIC);
  11127. + }
  11128. + }
  11129. + return includeTypes ? n*2 : n;
  11130. +}
  11131. +
  11132. +/*
  11133. +** Generate code for a boolean expression such that a jump is made
  11134. +** to the label "dest" if the expression is true but execution
  11135. +** continues straight thru if the expression is false.
  11136. +**
  11137. +** If the expression evaluates to NULL (neither true nor false), then
  11138. +** take the jump if the jumpIfNull flag is true.
  11139. +*/
  11140. +void sqliteExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  11141. + Vdbe *v = pParse->pVdbe;
  11142. + int op = 0;
  11143. + if( v==0 || pExpr==0 ) return;
  11144. + switch( pExpr->op ){
  11145. + case TK_LT: op = OP_Lt; break;
  11146. + case TK_LE: op = OP_Le; break;
  11147. + case TK_GT: op = OP_Gt; break;
  11148. + case TK_GE: op = OP_Ge; break;
  11149. + case TK_NE: op = OP_Ne; break;
  11150. + case TK_EQ: op = OP_Eq; break;
  11151. + case TK_ISNULL: op = OP_IsNull; break;
  11152. + case TK_NOTNULL: op = OP_NotNull; break;
  11153. + default: break;
  11154. + }
  11155. + switch( pExpr->op ){
  11156. + case TK_AND: {
  11157. + int d2 = sqliteVdbeMakeLabel(v);
  11158. + sqliteExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
  11159. + sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  11160. + sqliteVdbeResolveLabel(v, d2);
  11161. + break;
  11162. + }
  11163. + case TK_OR: {
  11164. + sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  11165. + sqliteExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  11166. + break;
  11167. + }
  11168. + case TK_NOT: {
  11169. + sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  11170. + break;
  11171. + }
  11172. + case TK_LT:
  11173. + case TK_LE:
  11174. + case TK_GT:
  11175. + case TK_GE:
  11176. + case TK_NE:
  11177. + case TK_EQ: {
  11178. + sqliteExprCode(pParse, pExpr->pLeft);
  11179. + sqliteExprCode(pParse, pExpr->pRight);
  11180. + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
  11181. + op += 6; /* Convert numeric opcodes to text opcodes */
  11182. + }
  11183. + sqliteVdbeAddOp(v, op, jumpIfNull, dest);
  11184. + break;
  11185. + }
  11186. + case TK_ISNULL:
  11187. + case TK_NOTNULL: {
  11188. + sqliteExprCode(pParse, pExpr->pLeft);
  11189. + sqliteVdbeAddOp(v, op, 1, dest);
  11190. + break;
  11191. + }
  11192. + case TK_IN: {
  11193. + int addr;
  11194. + sqliteExprCode(pParse, pExpr->pLeft);
  11195. + addr = sqliteVdbeCurrentAddr(v);
  11196. + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
  11197. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11198. + sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
  11199. + if( pExpr->pSelect ){
  11200. + sqliteVdbeAddOp(v, OP_Found, pExpr->iTable, dest);
  11201. + }else{
  11202. + sqliteVdbeAddOp(v, OP_SetFound, pExpr->iTable, dest);
  11203. + }
  11204. + break;
  11205. + }
  11206. + case TK_BETWEEN: {
  11207. + int addr;
  11208. + sqliteExprCode(pParse, pExpr->pLeft);
  11209. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  11210. + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
  11211. + addr = sqliteVdbeAddOp(v, OP_Lt, !jumpIfNull, 0);
  11212. + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
  11213. + sqliteVdbeAddOp(v, OP_Le, jumpIfNull, dest);
  11214. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  11215. + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
  11216. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11217. + break;
  11218. + }
  11219. + default: {
  11220. + sqliteExprCode(pParse, pExpr);
  11221. + sqliteVdbeAddOp(v, OP_If, jumpIfNull, dest);
  11222. + break;
  11223. + }
  11224. + }
  11225. +}
  11226. +
  11227. +/*
  11228. +** Generate code for a boolean expression such that a jump is made
  11229. +** to the label "dest" if the expression is false but execution
  11230. +** continues straight thru if the expression is true.
  11231. +**
  11232. +** If the expression evaluates to NULL (neither true nor false) then
  11233. +** jump if jumpIfNull is true or fall through if jumpIfNull is false.
  11234. +*/
  11235. +void sqliteExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  11236. + Vdbe *v = pParse->pVdbe;
  11237. + int op = 0;
  11238. + if( v==0 || pExpr==0 ) return;
  11239. + switch( pExpr->op ){
  11240. + case TK_LT: op = OP_Ge; break;
  11241. + case TK_LE: op = OP_Gt; break;
  11242. + case TK_GT: op = OP_Le; break;
  11243. + case TK_GE: op = OP_Lt; break;
  11244. + case TK_NE: op = OP_Eq; break;
  11245. + case TK_EQ: op = OP_Ne; break;
  11246. + case TK_ISNULL: op = OP_NotNull; break;
  11247. + case TK_NOTNULL: op = OP_IsNull; break;
  11248. + default: break;
  11249. + }
  11250. + switch( pExpr->op ){
  11251. + case TK_AND: {
  11252. + sqliteExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  11253. + sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  11254. + break;
  11255. + }
  11256. + case TK_OR: {
  11257. + int d2 = sqliteVdbeMakeLabel(v);
  11258. + sqliteExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
  11259. + sqliteExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  11260. + sqliteVdbeResolveLabel(v, d2);
  11261. + break;
  11262. + }
  11263. + case TK_NOT: {
  11264. + sqliteExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  11265. + break;
  11266. + }
  11267. + case TK_LT:
  11268. + case TK_LE:
  11269. + case TK_GT:
  11270. + case TK_GE:
  11271. + case TK_NE:
  11272. + case TK_EQ: {
  11273. + if( pParse->db->file_format>=4 && sqliteExprType(pExpr)==SQLITE_SO_TEXT ){
  11274. + /* Convert numeric comparison opcodes into text comparison opcodes.
  11275. + ** This step depends on the fact that the text comparision opcodes are
  11276. + ** always 6 greater than their corresponding numeric comparison
  11277. + ** opcodes.
  11278. + */
  11279. + assert( OP_Eq+6 == OP_StrEq );
  11280. + op += 6;
  11281. + }
  11282. + sqliteExprCode(pParse, pExpr->pLeft);
  11283. + sqliteExprCode(pParse, pExpr->pRight);
  11284. + sqliteVdbeAddOp(v, op, jumpIfNull, dest);
  11285. + break;
  11286. + }
  11287. + case TK_ISNULL:
  11288. + case TK_NOTNULL: {
  11289. + sqliteExprCode(pParse, pExpr->pLeft);
  11290. + sqliteVdbeAddOp(v, op, 1, dest);
  11291. + break;
  11292. + }
  11293. + case TK_IN: {
  11294. + int addr;
  11295. + sqliteExprCode(pParse, pExpr->pLeft);
  11296. + addr = sqliteVdbeCurrentAddr(v);
  11297. + sqliteVdbeAddOp(v, OP_NotNull, -1, addr+3);
  11298. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11299. + sqliteVdbeAddOp(v, OP_Goto, 0, jumpIfNull ? dest : addr+4);
  11300. + if( pExpr->pSelect ){
  11301. + sqliteVdbeAddOp(v, OP_NotFound, pExpr->iTable, dest);
  11302. + }else{
  11303. + sqliteVdbeAddOp(v, OP_SetNotFound, pExpr->iTable, dest);
  11304. + }
  11305. + break;
  11306. + }
  11307. + case TK_BETWEEN: {
  11308. + int addr;
  11309. + sqliteExprCode(pParse, pExpr->pLeft);
  11310. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  11311. + sqliteExprCode(pParse, pExpr->pList->a[0].pExpr);
  11312. + addr = sqliteVdbeCurrentAddr(v);
  11313. + sqliteVdbeAddOp(v, OP_Ge, !jumpIfNull, addr+3);
  11314. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  11315. + sqliteVdbeAddOp(v, OP_Goto, 0, dest);
  11316. + sqliteExprCode(pParse, pExpr->pList->a[1].pExpr);
  11317. + sqliteVdbeAddOp(v, OP_Gt, jumpIfNull, dest);
  11318. + break;
  11319. + }
  11320. + default: {
  11321. + sqliteExprCode(pParse, pExpr);
  11322. + sqliteVdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
  11323. + break;
  11324. + }
  11325. + }
  11326. +}
  11327. +
  11328. +/*
  11329. +** Do a deep comparison of two expression trees. Return TRUE (non-zero)
  11330. +** if they are identical and return FALSE if they differ in any way.
  11331. +*/
  11332. +int sqliteExprCompare(Expr *pA, Expr *pB){
  11333. + int i;
  11334. + if( pA==0 ){
  11335. + return pB==0;
  11336. + }else if( pB==0 ){
  11337. + return 0;
  11338. + }
  11339. + if( pA->op!=pB->op ) return 0;
  11340. + if( !sqliteExprCompare(pA->pLeft, pB->pLeft) ) return 0;
  11341. + if( !sqliteExprCompare(pA->pRight, pB->pRight) ) return 0;
  11342. + if( pA->pList ){
  11343. + if( pB->pList==0 ) return 0;
  11344. + if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
  11345. + for(i=0; i<pA->pList->nExpr; i++){
  11346. + if( !sqliteExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
  11347. + return 0;
  11348. + }
  11349. + }
  11350. + }else if( pB->pList ){
  11351. + return 0;
  11352. + }
  11353. + if( pA->pSelect || pB->pSelect ) return 0;
  11354. + if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
  11355. + if( pA->token.z ){
  11356. + if( pB->token.z==0 ) return 0;
  11357. + if( pB->token.n!=pA->token.n ) return 0;
  11358. + if( sqliteStrNICmp(pA->token.z, pB->token.z, pB->token.n)!=0 ) return 0;
  11359. + }
  11360. + return 1;
  11361. +}
  11362. +
  11363. +/*
  11364. +** Add a new element to the pParse->aAgg[] array and return its index.
  11365. +*/
  11366. +static int appendAggInfo(Parse *pParse){
  11367. + if( (pParse->nAgg & 0x7)==0 ){
  11368. + int amt = pParse->nAgg + 8;
  11369. + AggExpr *aAgg = sqliteRealloc(pParse->aAgg, amt*sizeof(pParse->aAgg[0]));
  11370. + if( aAgg==0 ){
  11371. + return -1;
  11372. + }
  11373. + pParse->aAgg = aAgg;
  11374. + }
  11375. + memset(&pParse->aAgg[pParse->nAgg], 0, sizeof(pParse->aAgg[0]));
  11376. + return pParse->nAgg++;
  11377. +}
  11378. +
  11379. +/*
  11380. +** Analyze the given expression looking for aggregate functions and
  11381. +** for variables that need to be added to the pParse->aAgg[] array.
  11382. +** Make additional entries to the pParse->aAgg[] array as necessary.
  11383. +**
  11384. +** This routine should only be called after the expression has been
  11385. +** analyzed by sqliteExprResolveIds() and sqliteExprCheck().
  11386. +**
  11387. +** If errors are seen, leave an error message in zErrMsg and return
  11388. +** the number of errors.
  11389. +*/
  11390. +int sqliteExprAnalyzeAggregates(Parse *pParse, Expr *pExpr){
  11391. + int i;
  11392. + AggExpr *aAgg;
  11393. + int nErr = 0;
  11394. +
  11395. + if( pExpr==0 ) return 0;
  11396. + switch( pExpr->op ){
  11397. + case TK_COLUMN: {
  11398. + aAgg = pParse->aAgg;
  11399. + for(i=0; i<pParse->nAgg; i++){
  11400. + if( aAgg[i].isAgg ) continue;
  11401. + if( aAgg[i].pExpr->iTable==pExpr->iTable
  11402. + && aAgg[i].pExpr->iColumn==pExpr->iColumn ){
  11403. + break;
  11404. + }
  11405. + }
  11406. + if( i>=pParse->nAgg ){
  11407. + i = appendAggInfo(pParse);
  11408. + if( i<0 ) return 1;
  11409. + pParse->aAgg[i].isAgg = 0;
  11410. + pParse->aAgg[i].pExpr = pExpr;
  11411. + }
  11412. + pExpr->iAgg = i;
  11413. + break;
  11414. + }
  11415. + case TK_AGG_FUNCTION: {
  11416. + aAgg = pParse->aAgg;
  11417. + for(i=0; i<pParse->nAgg; i++){
  11418. + if( !aAgg[i].isAgg ) continue;
  11419. + if( sqliteExprCompare(aAgg[i].pExpr, pExpr) ){
  11420. + break;
  11421. + }
  11422. + }
  11423. + if( i>=pParse->nAgg ){
  11424. + i = appendAggInfo(pParse);
  11425. + if( i<0 ) return 1;
  11426. + pParse->aAgg[i].isAgg = 1;
  11427. + pParse->aAgg[i].pExpr = pExpr;
  11428. + pParse->aAgg[i].pFunc = sqliteFindFunction(pParse->db,
  11429. + pExpr->token.z, pExpr->token.n,
  11430. + pExpr->pList ? pExpr->pList->nExpr : 0, 0);
  11431. + }
  11432. + pExpr->iAgg = i;
  11433. + break;
  11434. + }
  11435. + default: {
  11436. + if( pExpr->pLeft ){
  11437. + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pLeft);
  11438. + }
  11439. + if( nErr==0 && pExpr->pRight ){
  11440. + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pRight);
  11441. + }
  11442. + if( nErr==0 && pExpr->pList ){
  11443. + int n = pExpr->pList->nExpr;
  11444. + int i;
  11445. + for(i=0; nErr==0 && i<n; i++){
  11446. + nErr = sqliteExprAnalyzeAggregates(pParse, pExpr->pList->a[i].pExpr);
  11447. + }
  11448. + }
  11449. + break;
  11450. + }
  11451. + }
  11452. + return nErr;
  11453. +}
  11454. +
  11455. +/*
  11456. +** Locate a user function given a name and a number of arguments.
  11457. +** Return a pointer to the FuncDef structure that defines that
  11458. +** function, or return NULL if the function does not exist.
  11459. +**
  11460. +** If the createFlag argument is true, then a new (blank) FuncDef
  11461. +** structure is created and liked into the "db" structure if a
  11462. +** no matching function previously existed. When createFlag is true
  11463. +** and the nArg parameter is -1, then only a function that accepts
  11464. +** any number of arguments will be returned.
  11465. +**
  11466. +** If createFlag is false and nArg is -1, then the first valid
  11467. +** function found is returned. A function is valid if either xFunc
  11468. +** or xStep is non-zero.
  11469. +*/
  11470. +FuncDef *sqliteFindFunction(
  11471. + sqlite *db, /* An open database */
  11472. + const char *zName, /* Name of the function. Not null-terminated */
  11473. + int nName, /* Number of characters in the name */
  11474. + int nArg, /* Number of arguments. -1 means any number */
  11475. + int createFlag /* Create new entry if true and does not otherwise exist */
  11476. +){
  11477. + FuncDef *pFirst, *p, *pMaybe;
  11478. + pFirst = p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, nName);
  11479. + if( p && !createFlag && nArg<0 ){
  11480. + while( p && p->xFunc==0 && p->xStep==0 ){ p = p->pNext; }
  11481. + return p;
  11482. + }
  11483. + pMaybe = 0;
  11484. + while( p && p->nArg!=nArg ){
  11485. + if( p->nArg<0 && !createFlag && (p->xFunc || p->xStep) ) pMaybe = p;
  11486. + p = p->pNext;
  11487. + }
  11488. + if( p && !createFlag && p->xFunc==0 && p->xStep==0 ){
  11489. + return 0;
  11490. + }
  11491. + if( p==0 && pMaybe ){
  11492. + assert( createFlag==0 );
  11493. + return pMaybe;
  11494. + }
  11495. + if( p==0 && createFlag && (p = sqliteMalloc(sizeof(*p)))!=0 ){
  11496. + p->nArg = nArg;
  11497. + p->pNext = pFirst;
  11498. + p->dataType = pFirst ? pFirst->dataType : SQLITE_NUMERIC;
  11499. + sqliteHashInsert(&db->aFunc, zName, nName, (void*)p);
  11500. + }
  11501. + return p;
  11502. +}
  11503. --- /dev/null
  11504. +++ b/ext/sqlite/libsqlite/src/func.c
  11505. @@ -0,0 +1,658 @@
  11506. +/*
  11507. +** 2002 February 23
  11508. +**
  11509. +** The author disclaims copyright to this source code. In place of
  11510. +** a legal notice, here is a blessing:
  11511. +**
  11512. +** May you do good and not evil.
  11513. +** May you find forgiveness for yourself and forgive others.
  11514. +** May you share freely, never taking more than you give.
  11515. +**
  11516. +*************************************************************************
  11517. +** This file contains the C functions that implement various SQL
  11518. +** functions of SQLite.
  11519. +**
  11520. +** There is only one exported symbol in this file - the function
  11521. +** sqliteRegisterBuildinFunctions() found at the bottom of the file.
  11522. +** All other code has file scope.
  11523. +**
  11524. +** $Id$
  11525. +*/
  11526. +#include <ctype.h>
  11527. +#include <math.h>
  11528. +#include <stdlib.h>
  11529. +#include <assert.h>
  11530. +#include "sqliteInt.h"
  11531. +#include "os.h"
  11532. +
  11533. +/*
  11534. +** Implementation of the non-aggregate min() and max() functions
  11535. +*/
  11536. +static void minmaxFunc(sqlite_func *context, int argc, const char **argv){
  11537. + const char *zBest;
  11538. + int i;
  11539. + int (*xCompare)(const char*, const char*);
  11540. + int mask; /* 0 for min() or 0xffffffff for max() */
  11541. +
  11542. + if( argc==0 ) return;
  11543. + mask = (int)sqlite_user_data(context);
  11544. + zBest = argv[0];
  11545. + if( zBest==0 ) return;
  11546. + if( argv[1][0]=='n' ){
  11547. + xCompare = sqliteCompare;
  11548. + }else{
  11549. + xCompare = strcmp;
  11550. + }
  11551. + for(i=2; i<argc; i+=2){
  11552. + if( argv[i]==0 ) return;
  11553. + if( (xCompare(argv[i], zBest)^mask)<0 ){
  11554. + zBest = argv[i];
  11555. + }
  11556. + }
  11557. + sqlite_set_result_string(context, zBest, -1);
  11558. +}
  11559. +
  11560. +/*
  11561. +** Return the type of the argument.
  11562. +*/
  11563. +static void typeofFunc(sqlite_func *context, int argc, const char **argv){
  11564. + assert( argc==2 );
  11565. + sqlite_set_result_string(context, argv[1], -1);
  11566. +}
  11567. +
  11568. +/*
  11569. +** Implementation of the length() function
  11570. +*/
  11571. +static void lengthFunc(sqlite_func *context, int argc, const char **argv){
  11572. + const char *z;
  11573. + int len;
  11574. +
  11575. + assert( argc==1 );
  11576. + z = argv[0];
  11577. + if( z==0 ) return;
  11578. +#ifdef SQLITE_UTF8
  11579. + for(len=0; *z; z++){ if( (0xc0&*z)!=0x80 ) len++; }
  11580. +#else
  11581. + len = strlen(z);
  11582. +#endif
  11583. + sqlite_set_result_int(context, len);
  11584. +}
  11585. +
  11586. +/*
  11587. +** Implementation of the abs() function
  11588. +*/
  11589. +static void absFunc(sqlite_func *context, int argc, const char **argv){
  11590. + const char *z;
  11591. + assert( argc==1 );
  11592. + z = argv[0];
  11593. + if( z==0 ) return;
  11594. + if( z[0]=='-' && isdigit(z[1]) ) z++;
  11595. + sqlite_set_result_string(context, z, -1);
  11596. +}
  11597. +
  11598. +/*
  11599. +** Implementation of the substr() function
  11600. +*/
  11601. +static void substrFunc(sqlite_func *context, int argc, const char **argv){
  11602. + const char *z;
  11603. +#ifdef SQLITE_UTF8
  11604. + const char *z2;
  11605. + int i;
  11606. +#endif
  11607. + int p1, p2, len;
  11608. + assert( argc==3 );
  11609. + z = argv[0];
  11610. + if( z==0 ) return;
  11611. + p1 = atoi(argv[1]?argv[1]:0);
  11612. + p2 = atoi(argv[2]?argv[2]:0);
  11613. +#ifdef SQLITE_UTF8
  11614. + for(len=0, z2=z; *z2; z2++){ if( (0xc0&*z2)!=0x80 ) len++; }
  11615. +#else
  11616. + len = strlen(z);
  11617. +#endif
  11618. + if( p1<0 ){
  11619. + p1 += len;
  11620. + if( p1<0 ){
  11621. + p2 += p1;
  11622. + p1 = 0;
  11623. + }
  11624. + }else if( p1>0 ){
  11625. + p1--;
  11626. + }
  11627. + if( p1+p2>len ){
  11628. + p2 = len-p1;
  11629. + }
  11630. +#ifdef SQLITE_UTF8
  11631. + for(i=0; i<p1 && z[i]; i++){
  11632. + if( (z[i]&0xc0)==0x80 ) p1++;
  11633. + }
  11634. + while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p1++; }
  11635. + for(; i<p1+p2 && z[i]; i++){
  11636. + if( (z[i]&0xc0)==0x80 ) p2++;
  11637. + }
  11638. + while( z[i] && (z[i]&0xc0)==0x80 ){ i++; p2++; }
  11639. +#endif
  11640. + if( p2<0 ) p2 = 0;
  11641. + sqlite_set_result_string(context, &z[p1], p2);
  11642. +}
  11643. +
  11644. +/*
  11645. +** Implementation of the round() function
  11646. +*/
  11647. +static void roundFunc(sqlite_func *context, int argc, const char **argv){
  11648. + int n;
  11649. + double r;
  11650. + char zBuf[100];
  11651. + assert( argc==1 || argc==2 );
  11652. + if( argv[0]==0 || (argc==2 && argv[1]==0) ) return;
  11653. + n = argc==2 ? atoi(argv[1]) : 0;
  11654. + if( n>30 ) n = 30;
  11655. + if( n<0 ) n = 0;
  11656. + r = sqliteAtoF(argv[0], 0);
  11657. + sprintf(zBuf,"%.*f",n,r);
  11658. + sqlite_set_result_string(context, zBuf, -1);
  11659. +}
  11660. +
  11661. +/*
  11662. +** Implementation of the upper() and lower() SQL functions.
  11663. +*/
  11664. +static void upperFunc(sqlite_func *context, int argc, const char **argv){
  11665. + unsigned char *z;
  11666. + int i;
  11667. + if( argc<1 || argv[0]==0 ) return;
  11668. + z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
  11669. + if( z==0 ) return;
  11670. + for(i=0; z[i]; i++){
  11671. + if( islower(z[i]) ) z[i] = toupper(z[i]);
  11672. + }
  11673. +}
  11674. +static void lowerFunc(sqlite_func *context, int argc, const char **argv){
  11675. + unsigned char *z;
  11676. + int i;
  11677. + if( argc<1 || argv[0]==0 ) return;
  11678. + z = (unsigned char*)sqlite_set_result_string(context, argv[0], -1);
  11679. + if( z==0 ) return;
  11680. + for(i=0; z[i]; i++){
  11681. + if( isupper(z[i]) ) z[i] = tolower(z[i]);
  11682. + }
  11683. +}
  11684. +
  11685. +/*
  11686. +** Implementation of the IFNULL(), NVL(), and COALESCE() functions.
  11687. +** All three do the same thing. They return the first non-NULL
  11688. +** argument.
  11689. +*/
  11690. +static void ifnullFunc(sqlite_func *context, int argc, const char **argv){
  11691. + int i;
  11692. + for(i=0; i<argc; i++){
  11693. + if( argv[i] ){
  11694. + sqlite_set_result_string(context, argv[i], -1);
  11695. + break;
  11696. + }
  11697. + }
  11698. +}
  11699. +
  11700. +/*
  11701. +** Implementation of random(). Return a random integer.
  11702. +*/
  11703. +static void randomFunc(sqlite_func *context, int argc, const char **argv){
  11704. + int r;
  11705. + sqliteRandomness(sizeof(r), &r);
  11706. + sqlite_set_result_int(context, r);
  11707. +}
  11708. +
  11709. +/*
  11710. +** Implementation of the last_insert_rowid() SQL function. The return
  11711. +** value is the same as the sqlite_last_insert_rowid() API function.
  11712. +*/
  11713. +static void last_insert_rowid(sqlite_func *context, int arg, const char **argv){
  11714. + sqlite *db = sqlite_user_data(context);
  11715. + sqlite_set_result_int(context, sqlite_last_insert_rowid(db));
  11716. +}
  11717. +
  11718. +/*
  11719. +** Implementation of the change_count() SQL function. The return
  11720. +** value is the same as the sqlite_changes() API function.
  11721. +*/
  11722. +static void change_count(sqlite_func *context, int arg, const char **argv){
  11723. + sqlite *db = sqlite_user_data(context);
  11724. + sqlite_set_result_int(context, sqlite_changes(db));
  11725. +}
  11726. +
  11727. +/*
  11728. +** Implementation of the last_statement_change_count() SQL function. The
  11729. +** return value is the same as the sqlite_last_statement_changes() API function.
  11730. +*/
  11731. +static void last_statement_change_count(sqlite_func *context, int arg,
  11732. + const char **argv){
  11733. + sqlite *db = sqlite_user_data(context);
  11734. + sqlite_set_result_int(context, sqlite_last_statement_changes(db));
  11735. +}
  11736. +
  11737. +/*
  11738. +** Implementation of the like() SQL function. This function implements
  11739. +** the build-in LIKE operator. The first argument to the function is the
  11740. +** string and the second argument is the pattern. So, the SQL statements:
  11741. +**
  11742. +** A LIKE B
  11743. +**
  11744. +** is implemented as like(A,B).
  11745. +*/
  11746. +static void likeFunc(sqlite_func *context, int arg, const char **argv){
  11747. + if( argv[0]==0 || argv[1]==0 ) return;
  11748. + sqlite_set_result_int(context,
  11749. + sqliteLikeCompare((const unsigned char*)argv[0],
  11750. + (const unsigned char*)argv[1]));
  11751. +}
  11752. +
  11753. +/*
  11754. +** Implementation of the glob() SQL function. This function implements
  11755. +** the build-in GLOB operator. The first argument to the function is the
  11756. +** string and the second argument is the pattern. So, the SQL statements:
  11757. +**
  11758. +** A GLOB B
  11759. +**
  11760. +** is implemented as glob(A,B).
  11761. +*/
  11762. +static void globFunc(sqlite_func *context, int arg, const char **argv){
  11763. + if( argv[0]==0 || argv[1]==0 ) return;
  11764. + sqlite_set_result_int(context,
  11765. + sqliteGlobCompare((const unsigned char*)argv[0],
  11766. + (const unsigned char*)argv[1]));
  11767. +}
  11768. +
  11769. +/*
  11770. +** Implementation of the NULLIF(x,y) function. The result is the first
  11771. +** argument if the arguments are different. The result is NULL if the
  11772. +** arguments are equal to each other.
  11773. +*/
  11774. +static void nullifFunc(sqlite_func *context, int argc, const char **argv){
  11775. + if( argv[0]!=0 && sqliteCompare(argv[0],argv[1])!=0 ){
  11776. + sqlite_set_result_string(context, argv[0], -1);
  11777. + }
  11778. +}
  11779. +
  11780. +/*
  11781. +** Implementation of the VERSION(*) function. The result is the version
  11782. +** of the SQLite library that is running.
  11783. +*/
  11784. +static void versionFunc(sqlite_func *context, int argc, const char **argv){
  11785. + sqlite_set_result_string(context, sqlite_version, -1);
  11786. +}
  11787. +
  11788. +/*
  11789. +** EXPERIMENTAL - This is not an official function. The interface may
  11790. +** change. This function may disappear. Do not write code that depends
  11791. +** on this function.
  11792. +**
  11793. +** Implementation of the QUOTE() function. This function takes a single
  11794. +** argument. If the argument is numeric, the return value is the same as
  11795. +** the argument. If the argument is NULL, the return value is the string
  11796. +** "NULL". Otherwise, the argument is enclosed in single quotes with
  11797. +** single-quote escapes.
  11798. +*/
  11799. +static void quoteFunc(sqlite_func *context, int argc, const char **argv){
  11800. + if( argc<1 ) return;
  11801. + if( argv[0]==0 ){
  11802. + sqlite_set_result_string(context, "NULL", 4);
  11803. + }else if( sqliteIsNumber(argv[0]) ){
  11804. + sqlite_set_result_string(context, argv[0], -1);
  11805. + }else{
  11806. + int i,j,n;
  11807. + char *z;
  11808. + for(i=n=0; argv[0][i]; i++){ if( argv[0][i]=='\'' ) n++; }
  11809. + z = sqliteMalloc( i+n+3 );
  11810. + if( z==0 ) return;
  11811. + z[0] = '\'';
  11812. + for(i=0, j=1; argv[0][i]; i++){
  11813. + z[j++] = argv[0][i];
  11814. + if( argv[0][i]=='\'' ){
  11815. + z[j++] = '\'';
  11816. + }
  11817. + }
  11818. + z[j++] = '\'';
  11819. + z[j] = 0;
  11820. + sqlite_set_result_string(context, z, j);
  11821. + sqliteFree(z);
  11822. + }
  11823. +}
  11824. +
  11825. +#ifdef SQLITE_SOUNDEX
  11826. +/*
  11827. +** Compute the soundex encoding of a word.
  11828. +*/
  11829. +static void soundexFunc(sqlite_func *context, int argc, const char **argv){
  11830. + char zResult[8];
  11831. + const char *zIn;
  11832. + int i, j;
  11833. + static const unsigned char iCode[] = {
  11834. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11835. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11836. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11837. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  11838. + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  11839. + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  11840. + 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  11841. + 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  11842. + };
  11843. + assert( argc==1 );
  11844. + zIn = argv[0];
  11845. + for(i=0; zIn[i] && !isalpha(zIn[i]); i++){}
  11846. + if( zIn[i] ){
  11847. + zResult[0] = toupper(zIn[i]);
  11848. + for(j=1; j<4 && zIn[i]; i++){
  11849. + int code = iCode[zIn[i]&0x7f];
  11850. + if( code>0 ){
  11851. + zResult[j++] = code + '0';
  11852. + }
  11853. + }
  11854. + while( j<4 ){
  11855. + zResult[j++] = '0';
  11856. + }
  11857. + zResult[j] = 0;
  11858. + sqlite_set_result_string(context, zResult, 4);
  11859. + }else{
  11860. + sqlite_set_result_string(context, "?000", 4);
  11861. + }
  11862. +}
  11863. +#endif
  11864. +
  11865. +#ifdef SQLITE_TEST
  11866. +/*
  11867. +** This function generates a string of random characters. Used for
  11868. +** generating test data.
  11869. +*/
  11870. +static void randStr(sqlite_func *context, int argc, const char **argv){
  11871. + static const unsigned char zSrc[] =
  11872. + "abcdefghijklmnopqrstuvwxyz"
  11873. + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  11874. + "0123456789"
  11875. + ".-!,:*^+=_|?/<> ";
  11876. + int iMin, iMax, n, r, i;
  11877. + unsigned char zBuf[1000];
  11878. + if( argc>=1 ){
  11879. + iMin = atoi(argv[0]);
  11880. + if( iMin<0 ) iMin = 0;
  11881. + if( iMin>=sizeof(zBuf) ) iMin = sizeof(zBuf)-1;
  11882. + }else{
  11883. + iMin = 1;
  11884. + }
  11885. + if( argc>=2 ){
  11886. + iMax = atoi(argv[1]);
  11887. + if( iMax<iMin ) iMax = iMin;
  11888. + if( iMax>=sizeof(zBuf) ) iMax = sizeof(zBuf)-1;
  11889. + }else{
  11890. + iMax = 50;
  11891. + }
  11892. + n = iMin;
  11893. + if( iMax>iMin ){
  11894. + sqliteRandomness(sizeof(r), &r);
  11895. + r &= 0x7fffffff;
  11896. + n += r%(iMax + 1 - iMin);
  11897. + }
  11898. + assert( n<sizeof(zBuf) );
  11899. + sqliteRandomness(n, zBuf);
  11900. + for(i=0; i<n; i++){
  11901. + zBuf[i] = zSrc[zBuf[i]%(sizeof(zSrc)-1)];
  11902. + }
  11903. + zBuf[n] = 0;
  11904. + sqlite_set_result_string(context, zBuf, n);
  11905. +}
  11906. +#endif
  11907. +
  11908. +/*
  11909. +** An instance of the following structure holds the context of a
  11910. +** sum() or avg() aggregate computation.
  11911. +*/
  11912. +typedef struct SumCtx SumCtx;
  11913. +struct SumCtx {
  11914. + double sum; /* Sum of terms */
  11915. + int cnt; /* Number of elements summed */
  11916. +};
  11917. +
  11918. +/*
  11919. +** Routines used to compute the sum or average.
  11920. +*/
  11921. +static void sumStep(sqlite_func *context, int argc, const char **argv){
  11922. + SumCtx *p;
  11923. + if( argc<1 ) return;
  11924. + p = sqlite_aggregate_context(context, sizeof(*p));
  11925. + if( p && argv[0] ){
  11926. + p->sum += sqliteAtoF(argv[0], 0);
  11927. + p->cnt++;
  11928. + }
  11929. +}
  11930. +static void sumFinalize(sqlite_func *context){
  11931. + SumCtx *p;
  11932. + p = sqlite_aggregate_context(context, sizeof(*p));
  11933. + sqlite_set_result_double(context, p ? p->sum : 0.0);
  11934. +}
  11935. +static void avgFinalize(sqlite_func *context){
  11936. + SumCtx *p;
  11937. + p = sqlite_aggregate_context(context, sizeof(*p));
  11938. + if( p && p->cnt>0 ){
  11939. + sqlite_set_result_double(context, p->sum/(double)p->cnt);
  11940. + }
  11941. +}
  11942. +
  11943. +/*
  11944. +** An instance of the following structure holds the context of a
  11945. +** variance or standard deviation computation.
  11946. +*/
  11947. +typedef struct StdDevCtx StdDevCtx;
  11948. +struct StdDevCtx {
  11949. + double sum; /* Sum of terms */
  11950. + double sum2; /* Sum of the squares of terms */
  11951. + int cnt; /* Number of terms counted */
  11952. +};
  11953. +
  11954. +#if 0 /* Omit because math library is required */
  11955. +/*
  11956. +** Routines used to compute the standard deviation as an aggregate.
  11957. +*/
  11958. +static void stdDevStep(sqlite_func *context, int argc, const char **argv){
  11959. + StdDevCtx *p;
  11960. + double x;
  11961. + if( argc<1 ) return;
  11962. + p = sqlite_aggregate_context(context, sizeof(*p));
  11963. + if( p && argv[0] ){
  11964. + x = sqliteAtoF(argv[0], 0);
  11965. + p->sum += x;
  11966. + p->sum2 += x*x;
  11967. + p->cnt++;
  11968. + }
  11969. +}
  11970. +static void stdDevFinalize(sqlite_func *context){
  11971. + double rN = sqlite_aggregate_count(context);
  11972. + StdDevCtx *p = sqlite_aggregate_context(context, sizeof(*p));
  11973. + if( p && p->cnt>1 ){
  11974. + double rCnt = cnt;
  11975. + sqlite_set_result_double(context,
  11976. + sqrt((p->sum2 - p->sum*p->sum/rCnt)/(rCnt-1.0)));
  11977. + }
  11978. +}
  11979. +#endif
  11980. +
  11981. +/*
  11982. +** The following structure keeps track of state information for the
  11983. +** count() aggregate function.
  11984. +*/
  11985. +typedef struct CountCtx CountCtx;
  11986. +struct CountCtx {
  11987. + int n;
  11988. +};
  11989. +
  11990. +/*
  11991. +** Routines to implement the count() aggregate function.
  11992. +*/
  11993. +static void countStep(sqlite_func *context, int argc, const char **argv){
  11994. + CountCtx *p;
  11995. + p = sqlite_aggregate_context(context, sizeof(*p));
  11996. + if( (argc==0 || argv[0]) && p ){
  11997. + p->n++;
  11998. + }
  11999. +}
  12000. +static void countFinalize(sqlite_func *context){
  12001. + CountCtx *p;
  12002. + p = sqlite_aggregate_context(context, sizeof(*p));
  12003. + sqlite_set_result_int(context, p ? p->n : 0);
  12004. +}
  12005. +
  12006. +/*
  12007. +** This function tracks state information for the min() and max()
  12008. +** aggregate functions.
  12009. +*/
  12010. +typedef struct MinMaxCtx MinMaxCtx;
  12011. +struct MinMaxCtx {
  12012. + char *z; /* The best so far */
  12013. + char zBuf[28]; /* Space that can be used for storage */
  12014. +};
  12015. +
  12016. +/*
  12017. +** Routines to implement min() and max() aggregate functions.
  12018. +*/
  12019. +static void minmaxStep(sqlite_func *context, int argc, const char **argv){
  12020. + MinMaxCtx *p;
  12021. + int (*xCompare)(const char*, const char*);
  12022. + int mask; /* 0 for min() or 0xffffffff for max() */
  12023. +
  12024. + assert( argc==2 );
  12025. + if( argv[0]==0 ) return; /* Ignore NULL values */
  12026. + if( argv[1][0]=='n' ){
  12027. + xCompare = sqliteCompare;
  12028. + }else{
  12029. + xCompare = strcmp;
  12030. + }
  12031. + mask = (int)sqlite_user_data(context);
  12032. + assert( mask==0 || mask==-1 );
  12033. + p = sqlite_aggregate_context(context, sizeof(*p));
  12034. + if( p==0 || argc<1 ) return;
  12035. + if( p->z==0 || (xCompare(argv[0],p->z)^mask)<0 ){
  12036. + int len;
  12037. + if( p->zBuf[0] ){
  12038. + sqliteFree(p->z);
  12039. + }
  12040. + len = strlen(argv[0]);
  12041. + if( len < sizeof(p->zBuf)-1 ){
  12042. + p->z = &p->zBuf[1];
  12043. + p->zBuf[0] = 0;
  12044. + }else{
  12045. + p->z = sqliteMalloc( len+1 );
  12046. + p->zBuf[0] = 1;
  12047. + if( p->z==0 ) return;
  12048. + }
  12049. + strcpy(p->z, argv[0]);
  12050. + }
  12051. +}
  12052. +static void minMaxFinalize(sqlite_func *context){
  12053. + MinMaxCtx *p;
  12054. + p = sqlite_aggregate_context(context, sizeof(*p));
  12055. + if( p && p->z && p->zBuf[0]<2 ){
  12056. + sqlite_set_result_string(context, p->z, strlen(p->z));
  12057. + }
  12058. + if( p && p->zBuf[0] ){
  12059. + sqliteFree(p->z);
  12060. + }
  12061. +}
  12062. +
  12063. +/*
  12064. +** This function registered all of the above C functions as SQL
  12065. +** functions. This should be the only routine in this file with
  12066. +** external linkage.
  12067. +*/
  12068. +void sqliteRegisterBuiltinFunctions(sqlite *db){
  12069. + static struct {
  12070. + char *zName;
  12071. + signed char nArg;
  12072. + signed char dataType;
  12073. + u8 argType; /* 0: none. 1: db 2: (-1) */
  12074. + void (*xFunc)(sqlite_func*,int,const char**);
  12075. + } aFuncs[] = {
  12076. + { "min", -1, SQLITE_ARGS, 0, minmaxFunc },
  12077. + { "min", 0, 0, 0, 0 },
  12078. + { "max", -1, SQLITE_ARGS, 2, minmaxFunc },
  12079. + { "max", 0, 0, 2, 0 },
  12080. + { "typeof", 1, SQLITE_TEXT, 0, typeofFunc },
  12081. + { "length", 1, SQLITE_NUMERIC, 0, lengthFunc },
  12082. + { "substr", 3, SQLITE_TEXT, 0, substrFunc },
  12083. + { "abs", 1, SQLITE_NUMERIC, 0, absFunc },
  12084. + { "round", 1, SQLITE_NUMERIC, 0, roundFunc },
  12085. + { "round", 2, SQLITE_NUMERIC, 0, roundFunc },
  12086. + { "upper", 1, SQLITE_TEXT, 0, upperFunc },
  12087. + { "lower", 1, SQLITE_TEXT, 0, lowerFunc },
  12088. + { "coalesce", -1, SQLITE_ARGS, 0, ifnullFunc },
  12089. + { "coalesce", 0, 0, 0, 0 },
  12090. + { "coalesce", 1, 0, 0, 0 },
  12091. + { "ifnull", 2, SQLITE_ARGS, 0, ifnullFunc },
  12092. + { "random", -1, SQLITE_NUMERIC, 0, randomFunc },
  12093. + { "like", 2, SQLITE_NUMERIC, 0, likeFunc },
  12094. + { "glob", 2, SQLITE_NUMERIC, 0, globFunc },
  12095. + { "nullif", 2, SQLITE_ARGS, 0, nullifFunc },
  12096. + { "sqlite_version",0,SQLITE_TEXT, 0, versionFunc},
  12097. + { "quote", 1, SQLITE_ARGS, 0, quoteFunc },
  12098. + { "last_insert_rowid", 0, SQLITE_NUMERIC, 1, last_insert_rowid },
  12099. + { "change_count", 0, SQLITE_NUMERIC, 1, change_count },
  12100. + { "last_statement_change_count",
  12101. + 0, SQLITE_NUMERIC, 1, last_statement_change_count },
  12102. +#ifdef SQLITE_SOUNDEX
  12103. + { "soundex", 1, SQLITE_TEXT, 0, soundexFunc},
  12104. +#endif
  12105. +#ifdef SQLITE_TEST
  12106. + { "randstr", 2, SQLITE_TEXT, 0, randStr },
  12107. +#endif
  12108. + };
  12109. + static struct {
  12110. + char *zName;
  12111. + signed char nArg;
  12112. + signed char dataType;
  12113. + u8 argType;
  12114. + void (*xStep)(sqlite_func*,int,const char**);
  12115. + void (*xFinalize)(sqlite_func*);
  12116. + } aAggs[] = {
  12117. + { "min", 1, 0, 0, minmaxStep, minMaxFinalize },
  12118. + { "max", 1, 0, 2, minmaxStep, minMaxFinalize },
  12119. + { "sum", 1, SQLITE_NUMERIC, 0, sumStep, sumFinalize },
  12120. + { "avg", 1, SQLITE_NUMERIC, 0, sumStep, avgFinalize },
  12121. + { "count", 0, SQLITE_NUMERIC, 0, countStep, countFinalize },
  12122. + { "count", 1, SQLITE_NUMERIC, 0, countStep, countFinalize },
  12123. +#if 0
  12124. + { "stddev", 1, SQLITE_NUMERIC, 0, stdDevStep, stdDevFinalize },
  12125. +#endif
  12126. + };
  12127. + static const char *azTypeFuncs[] = { "min", "max", "typeof" };
  12128. + int i;
  12129. +
  12130. + for(i=0; i<sizeof(aFuncs)/sizeof(aFuncs[0]); i++){
  12131. + void *pArg;
  12132. + switch( aFuncs[i].argType ){
  12133. + case 0: pArg = 0; break;
  12134. + case 1: pArg = db; break;
  12135. + case 2: pArg = (void*)(-1); break;
  12136. + }
  12137. + sqlite_create_function(db, aFuncs[i].zName,
  12138. + aFuncs[i].nArg, aFuncs[i].xFunc, pArg);
  12139. + if( aFuncs[i].xFunc ){
  12140. + sqlite_function_type(db, aFuncs[i].zName, aFuncs[i].dataType);
  12141. + }
  12142. + }
  12143. + for(i=0; i<sizeof(aAggs)/sizeof(aAggs[0]); i++){
  12144. + void *pArg;
  12145. + switch( aAggs[i].argType ){
  12146. + case 0: pArg = 0; break;
  12147. + case 1: pArg = db; break;
  12148. + case 2: pArg = (void*)(-1); break;
  12149. + }
  12150. + sqlite_create_aggregate(db, aAggs[i].zName,
  12151. + aAggs[i].nArg, aAggs[i].xStep, aAggs[i].xFinalize, pArg);
  12152. + sqlite_function_type(db, aAggs[i].zName, aAggs[i].dataType);
  12153. + }
  12154. + for(i=0; i<sizeof(azTypeFuncs)/sizeof(azTypeFuncs[0]); i++){
  12155. + int n = strlen(azTypeFuncs[i]);
  12156. + FuncDef *p = sqliteHashFind(&db->aFunc, azTypeFuncs[i], n);
  12157. + while( p ){
  12158. + p->includeTypes = 1;
  12159. + p = p->pNext;
  12160. + }
  12161. + }
  12162. + sqliteRegisterDateTimeFunctions(db);
  12163. +}
  12164. --- /dev/null
  12165. +++ b/ext/sqlite/libsqlite/src/hash.c
  12166. @@ -0,0 +1,356 @@
  12167. +/*
  12168. +** 2001 September 22
  12169. +**
  12170. +** The author disclaims copyright to this source code. In place of
  12171. +** a legal notice, here is a blessing:
  12172. +**
  12173. +** May you do good and not evil.
  12174. +** May you find forgiveness for yourself and forgive others.
  12175. +** May you share freely, never taking more than you give.
  12176. +**
  12177. +*************************************************************************
  12178. +** This is the implementation of generic hash-tables
  12179. +** used in SQLite.
  12180. +**
  12181. +** $Id$
  12182. +*/
  12183. +#include "sqliteInt.h"
  12184. +#include <assert.h>
  12185. +
  12186. +/* Turn bulk memory into a hash table object by initializing the
  12187. +** fields of the Hash structure.
  12188. +**
  12189. +** "new" is a pointer to the hash table that is to be initialized.
  12190. +** keyClass is one of the constants SQLITE_HASH_INT, SQLITE_HASH_POINTER,
  12191. +** SQLITE_HASH_BINARY, or SQLITE_HASH_STRING. The value of keyClass
  12192. +** determines what kind of key the hash table will use. "copyKey" is
  12193. +** true if the hash table should make its own private copy of keys and
  12194. +** false if it should just use the supplied pointer. CopyKey only makes
  12195. +** sense for SQLITE_HASH_STRING and SQLITE_HASH_BINARY and is ignored
  12196. +** for other key classes.
  12197. +*/
  12198. +void sqliteHashInit(Hash *new, int keyClass, int copyKey){
  12199. + assert( new!=0 );
  12200. + assert( keyClass>=SQLITE_HASH_INT && keyClass<=SQLITE_HASH_BINARY );
  12201. + new->keyClass = keyClass;
  12202. + new->copyKey = copyKey &&
  12203. + (keyClass==SQLITE_HASH_STRING || keyClass==SQLITE_HASH_BINARY);
  12204. + new->first = 0;
  12205. + new->count = 0;
  12206. + new->htsize = 0;
  12207. + new->ht = 0;
  12208. +}
  12209. +
  12210. +/* Remove all entries from a hash table. Reclaim all memory.
  12211. +** Call this routine to delete a hash table or to reset a hash table
  12212. +** to the empty state.
  12213. +*/
  12214. +void sqliteHashClear(Hash *pH){
  12215. + HashElem *elem; /* For looping over all elements of the table */
  12216. +
  12217. + assert( pH!=0 );
  12218. + elem = pH->first;
  12219. + pH->first = 0;
  12220. + if( pH->ht ) sqliteFree(pH->ht);
  12221. + pH->ht = 0;
  12222. + pH->htsize = 0;
  12223. + while( elem ){
  12224. + HashElem *next_elem = elem->next;
  12225. + if( pH->copyKey && elem->pKey ){
  12226. + sqliteFree(elem->pKey);
  12227. + }
  12228. + sqliteFree(elem);
  12229. + elem = next_elem;
  12230. + }
  12231. + pH->count = 0;
  12232. +}
  12233. +
  12234. +/*
  12235. +** Hash and comparison functions when the mode is SQLITE_HASH_INT
  12236. +*/
  12237. +static int intHash(const void *pKey, int nKey){
  12238. + return nKey ^ (nKey<<8) ^ (nKey>>8);
  12239. +}
  12240. +static int intCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  12241. + return n2 - n1;
  12242. +}
  12243. +
  12244. +#if 0 /* NOT USED */
  12245. +/*
  12246. +** Hash and comparison functions when the mode is SQLITE_HASH_POINTER
  12247. +*/
  12248. +static int ptrHash(const void *pKey, int nKey){
  12249. + uptr x = Addr(pKey);
  12250. + return x ^ (x<<8) ^ (x>>8);
  12251. +}
  12252. +static int ptrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  12253. + if( pKey1==pKey2 ) return 0;
  12254. + if( pKey1<pKey2 ) return -1;
  12255. + return 1;
  12256. +}
  12257. +#endif
  12258. +
  12259. +/*
  12260. +** Hash and comparison functions when the mode is SQLITE_HASH_STRING
  12261. +*/
  12262. +static int strHash(const void *pKey, int nKey){
  12263. + return sqliteHashNoCase((const char*)pKey, nKey);
  12264. +}
  12265. +static int strCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  12266. + if( n1!=n2 ) return n2-n1;
  12267. + return sqliteStrNICmp((const char*)pKey1,(const char*)pKey2,n1);
  12268. +}
  12269. +
  12270. +/*
  12271. +** Hash and comparison functions when the mode is SQLITE_HASH_BINARY
  12272. +*/
  12273. +static int binHash(const void *pKey, int nKey){
  12274. + int h = 0;
  12275. + const char *z = (const char *)pKey;
  12276. + while( nKey-- > 0 ){
  12277. + h = (h<<3) ^ h ^ *(z++);
  12278. + }
  12279. + return h & 0x7fffffff;
  12280. +}
  12281. +static int binCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  12282. + if( n1!=n2 ) return n2-n1;
  12283. + return memcmp(pKey1,pKey2,n1);
  12284. +}
  12285. +
  12286. +/*
  12287. +** Return a pointer to the appropriate hash function given the key class.
  12288. +**
  12289. +** The C syntax in this function definition may be unfamilar to some
  12290. +** programmers, so we provide the following additional explanation:
  12291. +**
  12292. +** The name of the function is "hashFunction". The function takes a
  12293. +** single parameter "keyClass". The return value of hashFunction()
  12294. +** is a pointer to another function. Specifically, the return value
  12295. +** of hashFunction() is a pointer to a function that takes two parameters
  12296. +** with types "const void*" and "int" and returns an "int".
  12297. +*/
  12298. +static int (*hashFunction(int keyClass))(const void*,int){
  12299. + switch( keyClass ){
  12300. + case SQLITE_HASH_INT: return &intHash;
  12301. + /* case SQLITE_HASH_POINTER: return &ptrHash; // NOT USED */
  12302. + case SQLITE_HASH_STRING: return &strHash;
  12303. + case SQLITE_HASH_BINARY: return &binHash;;
  12304. + default: break;
  12305. + }
  12306. + return 0;
  12307. +}
  12308. +
  12309. +/*
  12310. +** Return a pointer to the appropriate hash function given the key class.
  12311. +**
  12312. +** For help in interpreted the obscure C code in the function definition,
  12313. +** see the header comment on the previous function.
  12314. +*/
  12315. +static int (*compareFunction(int keyClass))(const void*,int,const void*,int){
  12316. + switch( keyClass ){
  12317. + case SQLITE_HASH_INT: return &intCompare;
  12318. + /* case SQLITE_HASH_POINTER: return &ptrCompare; // NOT USED */
  12319. + case SQLITE_HASH_STRING: return &strCompare;
  12320. + case SQLITE_HASH_BINARY: return &binCompare;
  12321. + default: break;
  12322. + }
  12323. + return 0;
  12324. +}
  12325. +
  12326. +
  12327. +/* Resize the hash table so that it cantains "new_size" buckets.
  12328. +** "new_size" must be a power of 2. The hash table might fail
  12329. +** to resize if sqliteMalloc() fails.
  12330. +*/
  12331. +static void rehash(Hash *pH, int new_size){
  12332. + struct _ht *new_ht; /* The new hash table */
  12333. + HashElem *elem, *next_elem; /* For looping over existing elements */
  12334. + HashElem *x; /* Element being copied to new hash table */
  12335. + int (*xHash)(const void*,int); /* The hash function */
  12336. +
  12337. + assert( (new_size & (new_size-1))==0 );
  12338. + new_ht = (struct _ht *)sqliteMalloc( new_size*sizeof(struct _ht) );
  12339. + if( new_ht==0 ) return;
  12340. + if( pH->ht ) sqliteFree(pH->ht);
  12341. + pH->ht = new_ht;
  12342. + pH->htsize = new_size;
  12343. + xHash = hashFunction(pH->keyClass);
  12344. + for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  12345. + int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  12346. + next_elem = elem->next;
  12347. + x = new_ht[h].chain;
  12348. + if( x ){
  12349. + elem->next = x;
  12350. + elem->prev = x->prev;
  12351. + if( x->prev ) x->prev->next = elem;
  12352. + else pH->first = elem;
  12353. + x->prev = elem;
  12354. + }else{
  12355. + elem->next = pH->first;
  12356. + if( pH->first ) pH->first->prev = elem;
  12357. + elem->prev = 0;
  12358. + pH->first = elem;
  12359. + }
  12360. + new_ht[h].chain = elem;
  12361. + new_ht[h].count++;
  12362. + }
  12363. +}
  12364. +
  12365. +/* This function (for internal use only) locates an element in an
  12366. +** hash table that matches the given key. The hash for this key has
  12367. +** already been computed and is passed as the 4th parameter.
  12368. +*/
  12369. +static HashElem *findElementGivenHash(
  12370. + const Hash *pH, /* The pH to be searched */
  12371. + const void *pKey, /* The key we are searching for */
  12372. + int nKey,
  12373. + int h /* The hash for this key. */
  12374. +){
  12375. + HashElem *elem; /* Used to loop thru the element list */
  12376. + int count; /* Number of elements left to test */
  12377. + int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  12378. +
  12379. + if( pH->ht ){
  12380. + elem = pH->ht[h].chain;
  12381. + count = pH->ht[h].count;
  12382. + xCompare = compareFunction(pH->keyClass);
  12383. + while( count-- && elem ){
  12384. + if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  12385. + return elem;
  12386. + }
  12387. + elem = elem->next;
  12388. + }
  12389. + }
  12390. + return 0;
  12391. +}
  12392. +
  12393. +/* Remove a single entry from the hash table given a pointer to that
  12394. +** element and a hash on the element's key.
  12395. +*/
  12396. +static void removeElementGivenHash(
  12397. + Hash *pH, /* The pH containing "elem" */
  12398. + HashElem* elem, /* The element to be removed from the pH */
  12399. + int h /* Hash value for the element */
  12400. +){
  12401. + if( elem->prev ){
  12402. + elem->prev->next = elem->next;
  12403. + }else{
  12404. + pH->first = elem->next;
  12405. + }
  12406. + if( elem->next ){
  12407. + elem->next->prev = elem->prev;
  12408. + }
  12409. + if( pH->ht[h].chain==elem ){
  12410. + pH->ht[h].chain = elem->next;
  12411. + }
  12412. + pH->ht[h].count--;
  12413. + if( pH->ht[h].count<=0 ){
  12414. + pH->ht[h].chain = 0;
  12415. + }
  12416. + if( pH->copyKey && elem->pKey ){
  12417. + sqliteFree(elem->pKey);
  12418. + }
  12419. + sqliteFree( elem );
  12420. + pH->count--;
  12421. +}
  12422. +
  12423. +/* Attempt to locate an element of the hash table pH with a key
  12424. +** that matches pKey,nKey. Return the data for this element if it is
  12425. +** found, or NULL if there is no match.
  12426. +*/
  12427. +void *sqliteHashFind(const Hash *pH, const void *pKey, int nKey){
  12428. + int h; /* A hash on key */
  12429. + HashElem *elem; /* The element that matches key */
  12430. + int (*xHash)(const void*,int); /* The hash function */
  12431. +
  12432. + if( pH==0 || pH->ht==0 ) return 0;
  12433. + xHash = hashFunction(pH->keyClass);
  12434. + assert( xHash!=0 );
  12435. + h = (*xHash)(pKey,nKey);
  12436. + assert( (pH->htsize & (pH->htsize-1))==0 );
  12437. + elem = findElementGivenHash(pH,pKey,nKey, h & (pH->htsize-1));
  12438. + return elem ? elem->data : 0;
  12439. +}
  12440. +
  12441. +/* Insert an element into the hash table pH. The key is pKey,nKey
  12442. +** and the data is "data".
  12443. +**
  12444. +** If no element exists with a matching key, then a new
  12445. +** element is created. A copy of the key is made if the copyKey
  12446. +** flag is set. NULL is returned.
  12447. +**
  12448. +** If another element already exists with the same key, then the
  12449. +** new data replaces the old data and the old data is returned.
  12450. +** The key is not copied in this instance. If a malloc fails, then
  12451. +** the new data is returned and the hash table is unchanged.
  12452. +**
  12453. +** If the "data" parameter to this function is NULL, then the
  12454. +** element corresponding to "key" is removed from the hash table.
  12455. +*/
  12456. +void *sqliteHashInsert(Hash *pH, const void *pKey, int nKey, void *data){
  12457. + int hraw; /* Raw hash value of the key */
  12458. + int h; /* the hash of the key modulo hash table size */
  12459. + HashElem *elem; /* Used to loop thru the element list */
  12460. + HashElem *new_elem; /* New element added to the pH */
  12461. + int (*xHash)(const void*,int); /* The hash function */
  12462. +
  12463. + assert( pH!=0 );
  12464. + xHash = hashFunction(pH->keyClass);
  12465. + assert( xHash!=0 );
  12466. + hraw = (*xHash)(pKey, nKey);
  12467. + assert( (pH->htsize & (pH->htsize-1))==0 );
  12468. + h = hraw & (pH->htsize-1);
  12469. + elem = findElementGivenHash(pH,pKey,nKey,h);
  12470. + if( elem ){
  12471. + void *old_data = elem->data;
  12472. + if( data==0 ){
  12473. + removeElementGivenHash(pH,elem,h);
  12474. + }else{
  12475. + elem->data = data;
  12476. + }
  12477. + return old_data;
  12478. + }
  12479. + if( data==0 ) return 0;
  12480. + new_elem = (HashElem*)sqliteMalloc( sizeof(HashElem) );
  12481. + if( new_elem==0 ) return data;
  12482. + if( pH->copyKey && pKey!=0 ){
  12483. + new_elem->pKey = sqliteMallocRaw( nKey );
  12484. + if( new_elem->pKey==0 ){
  12485. + sqliteFree(new_elem);
  12486. + return data;
  12487. + }
  12488. + memcpy((void*)new_elem->pKey, pKey, nKey);
  12489. + }else{
  12490. + new_elem->pKey = (void*)pKey;
  12491. + }
  12492. + new_elem->nKey = nKey;
  12493. + pH->count++;
  12494. + if( pH->htsize==0 ) rehash(pH,8);
  12495. + if( pH->htsize==0 ){
  12496. + pH->count = 0;
  12497. + sqliteFree(new_elem);
  12498. + return data;
  12499. + }
  12500. + if( pH->count > pH->htsize ){
  12501. + rehash(pH,pH->htsize*2);
  12502. + }
  12503. + assert( (pH->htsize & (pH->htsize-1))==0 );
  12504. + h = hraw & (pH->htsize-1);
  12505. + elem = pH->ht[h].chain;
  12506. + if( elem ){
  12507. + new_elem->next = elem;
  12508. + new_elem->prev = elem->prev;
  12509. + if( elem->prev ){ elem->prev->next = new_elem; }
  12510. + else { pH->first = new_elem; }
  12511. + elem->prev = new_elem;
  12512. + }else{
  12513. + new_elem->next = pH->first;
  12514. + new_elem->prev = 0;
  12515. + if( pH->first ){ pH->first->prev = new_elem; }
  12516. + pH->first = new_elem;
  12517. + }
  12518. + pH->ht[h].count++;
  12519. + pH->ht[h].chain = new_elem;
  12520. + new_elem->data = data;
  12521. + return 0;
  12522. +}
  12523. --- /dev/null
  12524. +++ b/ext/sqlite/libsqlite/src/hash.h
  12525. @@ -0,0 +1,109 @@
  12526. +/*
  12527. +** 2001 September 22
  12528. +**
  12529. +** The author disclaims copyright to this source code. In place of
  12530. +** a legal notice, here is a blessing:
  12531. +**
  12532. +** May you do good and not evil.
  12533. +** May you find forgiveness for yourself and forgive others.
  12534. +** May you share freely, never taking more than you give.
  12535. +**
  12536. +*************************************************************************
  12537. +** This is the header file for the generic hash-table implemenation
  12538. +** used in SQLite.
  12539. +**
  12540. +** $Id$
  12541. +*/
  12542. +#ifndef _SQLITE_HASH_H_
  12543. +#define _SQLITE_HASH_H_
  12544. +
  12545. +/* Forward declarations of structures. */
  12546. +typedef struct Hash Hash;
  12547. +typedef struct HashElem HashElem;
  12548. +
  12549. +/* A complete hash table is an instance of the following structure.
  12550. +** The internals of this structure are intended to be opaque -- client
  12551. +** code should not attempt to access or modify the fields of this structure
  12552. +** directly. Change this structure only by using the routines below.
  12553. +** However, many of the "procedures" and "functions" for modifying and
  12554. +** accessing this structure are really macros, so we can't really make
  12555. +** this structure opaque.
  12556. +*/
  12557. +struct Hash {
  12558. + char keyClass; /* SQLITE_HASH_INT, _POINTER, _STRING, _BINARY */
  12559. + char copyKey; /* True if copy of key made on insert */
  12560. + int count; /* Number of entries in this table */
  12561. + HashElem *first; /* The first element of the array */
  12562. + int htsize; /* Number of buckets in the hash table */
  12563. + struct _ht { /* the hash table */
  12564. + int count; /* Number of entries with this hash */
  12565. + HashElem *chain; /* Pointer to first entry with this hash */
  12566. + } *ht;
  12567. +};
  12568. +
  12569. +/* Each element in the hash table is an instance of the following
  12570. +** structure. All elements are stored on a single doubly-linked list.
  12571. +**
  12572. +** Again, this structure is intended to be opaque, but it can't really
  12573. +** be opaque because it is used by macros.
  12574. +*/
  12575. +struct HashElem {
  12576. + HashElem *next, *prev; /* Next and previous elements in the table */
  12577. + void *data; /* Data associated with this element */
  12578. + void *pKey; int nKey; /* Key associated with this element */
  12579. +};
  12580. +
  12581. +/*
  12582. +** There are 4 different modes of operation for a hash table:
  12583. +**
  12584. +** SQLITE_HASH_INT nKey is used as the key and pKey is ignored.
  12585. +**
  12586. +** SQLITE_HASH_POINTER pKey is used as the key and nKey is ignored.
  12587. +**
  12588. +** SQLITE_HASH_STRING pKey points to a string that is nKey bytes long
  12589. +** (including the null-terminator, if any). Case
  12590. +** is ignored in comparisons.
  12591. +**
  12592. +** SQLITE_HASH_BINARY pKey points to binary data nKey bytes long.
  12593. +** memcmp() is used to compare keys.
  12594. +**
  12595. +** A copy of the key is made for SQLITE_HASH_STRING and SQLITE_HASH_BINARY
  12596. +** if the copyKey parameter to HashInit is 1.
  12597. +*/
  12598. +#define SQLITE_HASH_INT 1
  12599. +/* #define SQLITE_HASH_POINTER 2 // NOT USED */
  12600. +#define SQLITE_HASH_STRING 3
  12601. +#define SQLITE_HASH_BINARY 4
  12602. +
  12603. +/*
  12604. +** Access routines. To delete, insert a NULL pointer.
  12605. +*/
  12606. +void sqliteHashInit(Hash*, int keytype, int copyKey);
  12607. +void *sqliteHashInsert(Hash*, const void *pKey, int nKey, void *pData);
  12608. +void *sqliteHashFind(const Hash*, const void *pKey, int nKey);
  12609. +void sqliteHashClear(Hash*);
  12610. +
  12611. +/*
  12612. +** Macros for looping over all elements of a hash table. The idiom is
  12613. +** like this:
  12614. +**
  12615. +** Hash h;
  12616. +** HashElem *p;
  12617. +** ...
  12618. +** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  12619. +** SomeStructure *pData = sqliteHashData(p);
  12620. +** // do something with pData
  12621. +** }
  12622. +*/
  12623. +#define sqliteHashFirst(H) ((H)->first)
  12624. +#define sqliteHashNext(E) ((E)->next)
  12625. +#define sqliteHashData(E) ((E)->data)
  12626. +#define sqliteHashKey(E) ((E)->pKey)
  12627. +#define sqliteHashKeysize(E) ((E)->nKey)
  12628. +
  12629. +/*
  12630. +** Number of entries in a hash table
  12631. +*/
  12632. +#define sqliteHashCount(H) ((H)->count)
  12633. +
  12634. +#endif /* _SQLITE_HASH_H_ */
  12635. --- /dev/null
  12636. +++ b/ext/sqlite/libsqlite/src/insert.c
  12637. @@ -0,0 +1,919 @@
  12638. +/*
  12639. +** 2001 September 15
  12640. +**
  12641. +** The author disclaims copyright to this source code. In place of
  12642. +** a legal notice, here is a blessing:
  12643. +**
  12644. +** May you do good and not evil.
  12645. +** May you find forgiveness for yourself and forgive others.
  12646. +** May you share freely, never taking more than you give.
  12647. +**
  12648. +*************************************************************************
  12649. +** This file contains C code routines that are called by the parser
  12650. +** to handle INSERT statements in SQLite.
  12651. +**
  12652. +** $Id$
  12653. +*/
  12654. +#include "sqliteInt.h"
  12655. +
  12656. +/*
  12657. +** This routine is call to handle SQL of the following forms:
  12658. +**
  12659. +** insert into TABLE (IDLIST) values(EXPRLIST)
  12660. +** insert into TABLE (IDLIST) select
  12661. +**
  12662. +** The IDLIST following the table name is always optional. If omitted,
  12663. +** then a list of all columns for the table is substituted. The IDLIST
  12664. +** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  12665. +**
  12666. +** The pList parameter holds EXPRLIST in the first form of the INSERT
  12667. +** statement above, and pSelect is NULL. For the second form, pList is
  12668. +** NULL and pSelect is a pointer to the select statement used to generate
  12669. +** data for the insert.
  12670. +**
  12671. +** The code generated follows one of three templates. For a simple
  12672. +** select with data coming from a VALUES clause, the code executes
  12673. +** once straight down through. The template looks like this:
  12674. +**
  12675. +** open write cursor to <table> and its indices
  12676. +** puts VALUES clause expressions onto the stack
  12677. +** write the resulting record into <table>
  12678. +** cleanup
  12679. +**
  12680. +** If the statement is of the form
  12681. +**
  12682. +** INSERT INTO <table> SELECT ...
  12683. +**
  12684. +** And the SELECT clause does not read from <table> at any time, then
  12685. +** the generated code follows this template:
  12686. +**
  12687. +** goto B
  12688. +** A: setup for the SELECT
  12689. +** loop over the tables in the SELECT
  12690. +** gosub C
  12691. +** end loop
  12692. +** cleanup after the SELECT
  12693. +** goto D
  12694. +** B: open write cursor to <table> and its indices
  12695. +** goto A
  12696. +** C: insert the select result into <table>
  12697. +** return
  12698. +** D: cleanup
  12699. +**
  12700. +** The third template is used if the insert statement takes its
  12701. +** values from a SELECT but the data is being inserted into a table
  12702. +** that is also read as part of the SELECT. In the third form,
  12703. +** we have to use a intermediate table to store the results of
  12704. +** the select. The template is like this:
  12705. +**
  12706. +** goto B
  12707. +** A: setup for the SELECT
  12708. +** loop over the tables in the SELECT
  12709. +** gosub C
  12710. +** end loop
  12711. +** cleanup after the SELECT
  12712. +** goto D
  12713. +** C: insert the select result into the intermediate table
  12714. +** return
  12715. +** B: open a cursor to an intermediate table
  12716. +** goto A
  12717. +** D: open write cursor to <table> and its indices
  12718. +** loop over the intermediate table
  12719. +** transfer values form intermediate table into <table>
  12720. +** end the loop
  12721. +** cleanup
  12722. +*/
  12723. +void sqliteInsert(
  12724. + Parse *pParse, /* Parser context */
  12725. + SrcList *pTabList, /* Name of table into which we are inserting */
  12726. + ExprList *pList, /* List of values to be inserted */
  12727. + Select *pSelect, /* A SELECT statement to use as the data source */
  12728. + IdList *pColumn, /* Column names corresponding to IDLIST. */
  12729. + int onError /* How to handle constraint errors */
  12730. +){
  12731. + Table *pTab; /* The table to insert into */
  12732. + char *zTab; /* Name of the table into which we are inserting */
  12733. + const char *zDb; /* Name of the database holding this table */
  12734. + int i, j, idx; /* Loop counters */
  12735. + Vdbe *v; /* Generate code into this virtual machine */
  12736. + Index *pIdx; /* For looping over indices of the table */
  12737. + int nColumn; /* Number of columns in the data */
  12738. + int base; /* VDBE Cursor number for pTab */
  12739. + int iCont, iBreak; /* Beginning and end of the loop over srcTab */
  12740. + sqlite *db; /* The main database structure */
  12741. + int keyColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  12742. + int endOfLoop; /* Label for the end of the insertion loop */
  12743. + int useTempTable; /* Store SELECT results in intermediate table */
  12744. + int srcTab; /* Data comes from this temporary cursor if >=0 */
  12745. + int iSelectLoop; /* Address of code that implements the SELECT */
  12746. + int iCleanup; /* Address of the cleanup code */
  12747. + int iInsertBlock; /* Address of the subroutine used to insert data */
  12748. + int iCntMem; /* Memory cell used for the row counter */
  12749. + int isView; /* True if attempting to insert into a view */
  12750. +
  12751. + int row_triggers_exist = 0; /* True if there are FOR EACH ROW triggers */
  12752. + int before_triggers; /* True if there are BEFORE triggers */
  12753. + int after_triggers; /* True if there are AFTER triggers */
  12754. + int newIdx = -1; /* Cursor for the NEW table */
  12755. +
  12756. + if( pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
  12757. + db = pParse->db;
  12758. +
  12759. + /* Locate the table into which we will be inserting new information.
  12760. + */
  12761. + assert( pTabList->nSrc==1 );
  12762. + zTab = pTabList->a[0].zName;
  12763. + if( zTab==0 ) goto insert_cleanup;
  12764. + pTab = sqliteSrcListLookup(pParse, pTabList);
  12765. + if( pTab==0 ){
  12766. + goto insert_cleanup;
  12767. + }
  12768. + assert( pTab->iDb<db->nDb );
  12769. + zDb = db->aDb[pTab->iDb].zName;
  12770. + if( sqliteAuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  12771. + goto insert_cleanup;
  12772. + }
  12773. +
  12774. + /* Ensure that:
  12775. + * (a) the table is not read-only,
  12776. + * (b) that if it is a view then ON INSERT triggers exist
  12777. + */
  12778. + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
  12779. + TK_BEFORE, TK_ROW, 0);
  12780. + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger, TK_INSERT,
  12781. + TK_AFTER, TK_ROW, 0);
  12782. + row_triggers_exist = before_triggers || after_triggers;
  12783. + isView = pTab->pSelect!=0;
  12784. + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
  12785. + goto insert_cleanup;
  12786. + }
  12787. + if( pTab==0 ) goto insert_cleanup;
  12788. +
  12789. + /* If pTab is really a view, make sure it has been initialized.
  12790. + */
  12791. + if( isView && sqliteViewGetColumnNames(pParse, pTab) ){
  12792. + goto insert_cleanup;
  12793. + }
  12794. +
  12795. + /* Allocate a VDBE
  12796. + */
  12797. + v = sqliteGetVdbe(pParse);
  12798. + if( v==0 ) goto insert_cleanup;
  12799. + sqliteBeginWriteOperation(pParse, pSelect || row_triggers_exist, pTab->iDb);
  12800. +
  12801. + /* if there are row triggers, allocate a temp table for new.* references. */
  12802. + if( row_triggers_exist ){
  12803. + newIdx = pParse->nTab++;
  12804. + }
  12805. +
  12806. + /* Figure out how many columns of data are supplied. If the data
  12807. + ** is coming from a SELECT statement, then this step also generates
  12808. + ** all the code to implement the SELECT statement and invoke a subroutine
  12809. + ** to process each row of the result. (Template 2.) If the SELECT
  12810. + ** statement uses the the table that is being inserted into, then the
  12811. + ** subroutine is also coded here. That subroutine stores the SELECT
  12812. + ** results in a temporary table. (Template 3.)
  12813. + */
  12814. + if( pSelect ){
  12815. + /* Data is coming from a SELECT. Generate code to implement that SELECT
  12816. + */
  12817. + int rc, iInitCode;
  12818. + iInitCode = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
  12819. + iSelectLoop = sqliteVdbeCurrentAddr(v);
  12820. + iInsertBlock = sqliteVdbeMakeLabel(v);
  12821. + rc = sqliteSelect(pParse, pSelect, SRT_Subroutine, iInsertBlock, 0,0,0);
  12822. + if( rc || pParse->nErr || sqlite_malloc_failed ) goto insert_cleanup;
  12823. + iCleanup = sqliteVdbeMakeLabel(v);
  12824. + sqliteVdbeAddOp(v, OP_Goto, 0, iCleanup);
  12825. + assert( pSelect->pEList );
  12826. + nColumn = pSelect->pEList->nExpr;
  12827. +
  12828. + /* Set useTempTable to TRUE if the result of the SELECT statement
  12829. + ** should be written into a temporary table. Set to FALSE if each
  12830. + ** row of the SELECT can be written directly into the result table.
  12831. + **
  12832. + ** A temp table must be used if the table being updated is also one
  12833. + ** of the tables being read by the SELECT statement. Also use a
  12834. + ** temp table in the case of row triggers.
  12835. + */
  12836. + if( row_triggers_exist ){
  12837. + useTempTable = 1;
  12838. + }else{
  12839. + int addr = sqliteVdbeFindOp(v, OP_OpenRead, pTab->tnum);
  12840. + useTempTable = 0;
  12841. + if( addr>0 ){
  12842. + VdbeOp *pOp = sqliteVdbeGetOp(v, addr-2);
  12843. + if( pOp->opcode==OP_Integer && pOp->p1==pTab->iDb ){
  12844. + useTempTable = 1;
  12845. + }
  12846. + }
  12847. + }
  12848. +
  12849. + if( useTempTable ){
  12850. + /* Generate the subroutine that SELECT calls to process each row of
  12851. + ** the result. Store the result in a temporary table
  12852. + */
  12853. + srcTab = pParse->nTab++;
  12854. + sqliteVdbeResolveLabel(v, iInsertBlock);
  12855. + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  12856. + sqliteVdbeAddOp(v, OP_NewRecno, srcTab, 0);
  12857. + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
  12858. + sqliteVdbeAddOp(v, OP_PutIntKey, srcTab, 0);
  12859. + sqliteVdbeAddOp(v, OP_Return, 0, 0);
  12860. +
  12861. + /* The following code runs first because the GOTO at the very top
  12862. + ** of the program jumps to it. Create the temporary table, then jump
  12863. + ** back up and execute the SELECT code above.
  12864. + */
  12865. + sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
  12866. + sqliteVdbeAddOp(v, OP_OpenTemp, srcTab, 0);
  12867. + sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
  12868. + sqliteVdbeResolveLabel(v, iCleanup);
  12869. + }else{
  12870. + sqliteVdbeChangeP2(v, iInitCode, sqliteVdbeCurrentAddr(v));
  12871. + }
  12872. + }else{
  12873. + /* This is the case if the data for the INSERT is coming from a VALUES
  12874. + ** clause
  12875. + */
  12876. + SrcList dummy;
  12877. + assert( pList!=0 );
  12878. + srcTab = -1;
  12879. + useTempTable = 0;
  12880. + assert( pList );
  12881. + nColumn = pList->nExpr;
  12882. + dummy.nSrc = 0;
  12883. + for(i=0; i<nColumn; i++){
  12884. + if( sqliteExprResolveIds(pParse, &dummy, 0, pList->a[i].pExpr) ){
  12885. + goto insert_cleanup;
  12886. + }
  12887. + if( sqliteExprCheck(pParse, pList->a[i].pExpr, 0, 0) ){
  12888. + goto insert_cleanup;
  12889. + }
  12890. + }
  12891. + }
  12892. +
  12893. + /* Make sure the number of columns in the source data matches the number
  12894. + ** of columns to be inserted into the table.
  12895. + */
  12896. + if( pColumn==0 && nColumn!=pTab->nCol ){
  12897. + sqliteErrorMsg(pParse,
  12898. + "table %S has %d columns but %d values were supplied",
  12899. + pTabList, 0, pTab->nCol, nColumn);
  12900. + goto insert_cleanup;
  12901. + }
  12902. + if( pColumn!=0 && nColumn!=pColumn->nId ){
  12903. + sqliteErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  12904. + goto insert_cleanup;
  12905. + }
  12906. +
  12907. + /* If the INSERT statement included an IDLIST term, then make sure
  12908. + ** all elements of the IDLIST really are columns of the table and
  12909. + ** remember the column indices.
  12910. + **
  12911. + ** If the table has an INTEGER PRIMARY KEY column and that column
  12912. + ** is named in the IDLIST, then record in the keyColumn variable
  12913. + ** the index into IDLIST of the primary key column. keyColumn is
  12914. + ** the index of the primary key as it appears in IDLIST, not as
  12915. + ** is appears in the original table. (The index of the primary
  12916. + ** key in the original table is pTab->iPKey.)
  12917. + */
  12918. + if( pColumn ){
  12919. + for(i=0; i<pColumn->nId; i++){
  12920. + pColumn->a[i].idx = -1;
  12921. + }
  12922. + for(i=0; i<pColumn->nId; i++){
  12923. + for(j=0; j<pTab->nCol; j++){
  12924. + if( sqliteStrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  12925. + pColumn->a[i].idx = j;
  12926. + if( j==pTab->iPKey ){
  12927. + keyColumn = i;
  12928. + }
  12929. + break;
  12930. + }
  12931. + }
  12932. + if( j>=pTab->nCol ){
  12933. + if( sqliteIsRowid(pColumn->a[i].zName) ){
  12934. + keyColumn = i;
  12935. + }else{
  12936. + sqliteErrorMsg(pParse, "table %S has no column named %s",
  12937. + pTabList, 0, pColumn->a[i].zName);
  12938. + pParse->nErr++;
  12939. + goto insert_cleanup;
  12940. + }
  12941. + }
  12942. + }
  12943. + }
  12944. +
  12945. + /* If there is no IDLIST term but the table has an integer primary
  12946. + ** key, the set the keyColumn variable to the primary key column index
  12947. + ** in the original table definition.
  12948. + */
  12949. + if( pColumn==0 ){
  12950. + keyColumn = pTab->iPKey;
  12951. + }
  12952. +
  12953. + /* Open the temp table for FOR EACH ROW triggers
  12954. + */
  12955. + if( row_triggers_exist ){
  12956. + sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
  12957. + }
  12958. +
  12959. + /* Initialize the count of rows to be inserted
  12960. + */
  12961. + if( db->flags & SQLITE_CountRows ){
  12962. + iCntMem = pParse->nMem++;
  12963. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  12964. + sqliteVdbeAddOp(v, OP_MemStore, iCntMem, 1);
  12965. + }
  12966. +
  12967. + /* Open tables and indices if there are no row triggers */
  12968. + if( !row_triggers_exist ){
  12969. + base = pParse->nTab;
  12970. + idx = sqliteOpenTableAndIndices(pParse, pTab, base);
  12971. + pParse->nTab += idx;
  12972. + }
  12973. +
  12974. + /* If the data source is a temporary table, then we have to create
  12975. + ** a loop because there might be multiple rows of data. If the data
  12976. + ** source is a subroutine call from the SELECT statement, then we need
  12977. + ** to launch the SELECT statement processing.
  12978. + */
  12979. + if( useTempTable ){
  12980. + iBreak = sqliteVdbeMakeLabel(v);
  12981. + sqliteVdbeAddOp(v, OP_Rewind, srcTab, iBreak);
  12982. + iCont = sqliteVdbeCurrentAddr(v);
  12983. + }else if( pSelect ){
  12984. + sqliteVdbeAddOp(v, OP_Goto, 0, iSelectLoop);
  12985. + sqliteVdbeResolveLabel(v, iInsertBlock);
  12986. + }
  12987. +
  12988. + /* Run the BEFORE and INSTEAD OF triggers, if there are any
  12989. + */
  12990. + endOfLoop = sqliteVdbeMakeLabel(v);
  12991. + if( before_triggers ){
  12992. +
  12993. + /* build the NEW.* reference row. Note that if there is an INTEGER
  12994. + ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  12995. + ** translated into a unique ID for the row. But on a BEFORE trigger,
  12996. + ** we do not know what the unique ID will be (because the insert has
  12997. + ** not happened yet) so we substitute a rowid of -1
  12998. + */
  12999. + if( keyColumn<0 ){
  13000. + sqliteVdbeAddOp(v, OP_Integer, -1, 0);
  13001. + }else if( useTempTable ){
  13002. + sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
  13003. + }else if( pSelect ){
  13004. + sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
  13005. + }else{
  13006. + sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
  13007. + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
  13008. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  13009. + sqliteVdbeAddOp(v, OP_Integer, -1, 0);
  13010. + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
  13011. + }
  13012. +
  13013. + /* Create the new column data
  13014. + */
  13015. + for(i=0; i<pTab->nCol; i++){
  13016. + if( pColumn==0 ){
  13017. + j = i;
  13018. + }else{
  13019. + for(j=0; j<pColumn->nId; j++){
  13020. + if( pColumn->a[j].idx==i ) break;
  13021. + }
  13022. + }
  13023. + if( pColumn && j>=pColumn->nId ){
  13024. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
  13025. + }else if( useTempTable ){
  13026. + sqliteVdbeAddOp(v, OP_Column, srcTab, j);
  13027. + }else if( pSelect ){
  13028. + sqliteVdbeAddOp(v, OP_Dup, nColumn-j-1, 1);
  13029. + }else{
  13030. + sqliteExprCode(pParse, pList->a[j].pExpr);
  13031. + }
  13032. + }
  13033. + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  13034. + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
  13035. +
  13036. + /* Fire BEFORE or INSTEAD OF triggers */
  13037. + if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_BEFORE, pTab,
  13038. + newIdx, -1, onError, endOfLoop) ){
  13039. + goto insert_cleanup;
  13040. + }
  13041. + }
  13042. +
  13043. + /* If any triggers exists, the opening of tables and indices is deferred
  13044. + ** until now.
  13045. + */
  13046. + if( row_triggers_exist && !isView ){
  13047. + base = pParse->nTab;
  13048. + idx = sqliteOpenTableAndIndices(pParse, pTab, base);
  13049. + pParse->nTab += idx;
  13050. + }
  13051. +
  13052. + /* Push the record number for the new entry onto the stack. The
  13053. + ** record number is a randomly generate integer created by NewRecno
  13054. + ** except when the table has an INTEGER PRIMARY KEY column, in which
  13055. + ** case the record number is the same as that column.
  13056. + */
  13057. + if( !isView ){
  13058. + if( keyColumn>=0 ){
  13059. + if( useTempTable ){
  13060. + sqliteVdbeAddOp(v, OP_Column, srcTab, keyColumn);
  13061. + }else if( pSelect ){
  13062. + sqliteVdbeAddOp(v, OP_Dup, nColumn - keyColumn - 1, 1);
  13063. + }else{
  13064. + sqliteExprCode(pParse, pList->a[keyColumn].pExpr);
  13065. + }
  13066. + /* If the PRIMARY KEY expression is NULL, then use OP_NewRecno
  13067. + ** to generate a unique primary key value.
  13068. + */
  13069. + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
  13070. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  13071. + sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
  13072. + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
  13073. + }else{
  13074. + sqliteVdbeAddOp(v, OP_NewRecno, base, 0);
  13075. + }
  13076. +
  13077. + /* Push onto the stack, data for all columns of the new entry, beginning
  13078. + ** with the first column.
  13079. + */
  13080. + for(i=0; i<pTab->nCol; i++){
  13081. + if( i==pTab->iPKey ){
  13082. + /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  13083. + ** Whenever this column is read, the record number will be substituted
  13084. + ** in its place. So will fill this column with a NULL to avoid
  13085. + ** taking up data space with information that will never be used. */
  13086. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  13087. + continue;
  13088. + }
  13089. + if( pColumn==0 ){
  13090. + j = i;
  13091. + }else{
  13092. + for(j=0; j<pColumn->nId; j++){
  13093. + if( pColumn->a[j].idx==i ) break;
  13094. + }
  13095. + }
  13096. + if( pColumn && j>=pColumn->nId ){
  13097. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
  13098. + }else if( useTempTable ){
  13099. + sqliteVdbeAddOp(v, OP_Column, srcTab, j);
  13100. + }else if( pSelect ){
  13101. + sqliteVdbeAddOp(v, OP_Dup, i+nColumn-j, 1);
  13102. + }else{
  13103. + sqliteExprCode(pParse, pList->a[j].pExpr);
  13104. + }
  13105. + }
  13106. +
  13107. + /* Generate code to check constraints and generate index keys and
  13108. + ** do the insertion.
  13109. + */
  13110. + sqliteGenerateConstraintChecks(pParse, pTab, base, 0, keyColumn>=0,
  13111. + 0, onError, endOfLoop);
  13112. + sqliteCompleteInsertion(pParse, pTab, base, 0,0,0,
  13113. + after_triggers ? newIdx : -1);
  13114. + }
  13115. +
  13116. + /* Update the count of rows that are inserted
  13117. + */
  13118. + if( (db->flags & SQLITE_CountRows)!=0 ){
  13119. + sqliteVdbeAddOp(v, OP_MemIncr, iCntMem, 0);
  13120. + }
  13121. +
  13122. + if( row_triggers_exist ){
  13123. + /* Close all tables opened */
  13124. + if( !isView ){
  13125. + sqliteVdbeAddOp(v, OP_Close, base, 0);
  13126. + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  13127. + sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
  13128. + }
  13129. + }
  13130. +
  13131. + /* Code AFTER triggers */
  13132. + if( sqliteCodeRowTrigger(pParse, TK_INSERT, 0, TK_AFTER, pTab, newIdx, -1,
  13133. + onError, endOfLoop) ){
  13134. + goto insert_cleanup;
  13135. + }
  13136. + }
  13137. +
  13138. + /* The bottom of the loop, if the data source is a SELECT statement
  13139. + */
  13140. + sqliteVdbeResolveLabel(v, endOfLoop);
  13141. + if( useTempTable ){
  13142. + sqliteVdbeAddOp(v, OP_Next, srcTab, iCont);
  13143. + sqliteVdbeResolveLabel(v, iBreak);
  13144. + sqliteVdbeAddOp(v, OP_Close, srcTab, 0);
  13145. + }else if( pSelect ){
  13146. + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
  13147. + sqliteVdbeAddOp(v, OP_Return, 0, 0);
  13148. + sqliteVdbeResolveLabel(v, iCleanup);
  13149. + }
  13150. +
  13151. + if( !row_triggers_exist ){
  13152. + /* Close all tables opened */
  13153. + sqliteVdbeAddOp(v, OP_Close, base, 0);
  13154. + for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  13155. + sqliteVdbeAddOp(v, OP_Close, idx+base, 0);
  13156. + }
  13157. + }
  13158. +
  13159. + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
  13160. + sqliteEndWriteOperation(pParse);
  13161. +
  13162. + /*
  13163. + ** Return the number of rows inserted.
  13164. + */
  13165. + if( db->flags & SQLITE_CountRows ){
  13166. + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows inserted", P3_STATIC);
  13167. + sqliteVdbeAddOp(v, OP_MemLoad, iCntMem, 0);
  13168. + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
  13169. + }
  13170. +
  13171. +insert_cleanup:
  13172. + sqliteSrcListDelete(pTabList);
  13173. + if( pList ) sqliteExprListDelete(pList);
  13174. + if( pSelect ) sqliteSelectDelete(pSelect);
  13175. + sqliteIdListDelete(pColumn);
  13176. +}
  13177. +
  13178. +/*
  13179. +** Generate code to do a constraint check prior to an INSERT or an UPDATE.
  13180. +**
  13181. +** When this routine is called, the stack contains (from bottom to top)
  13182. +** the following values:
  13183. +**
  13184. +** 1. The recno of the row to be updated before the update. This
  13185. +** value is omitted unless we are doing an UPDATE that involves a
  13186. +** change to the record number.
  13187. +**
  13188. +** 2. The recno of the row after the update.
  13189. +**
  13190. +** 3. The data in the first column of the entry after the update.
  13191. +**
  13192. +** i. Data from middle columns...
  13193. +**
  13194. +** N. The data in the last column of the entry after the update.
  13195. +**
  13196. +** The old recno shown as entry (1) above is omitted unless both isUpdate
  13197. +** and recnoChng are 1. isUpdate is true for UPDATEs and false for
  13198. +** INSERTs and recnoChng is true if the record number is being changed.
  13199. +**
  13200. +** The code generated by this routine pushes additional entries onto
  13201. +** the stack which are the keys for new index entries for the new record.
  13202. +** The order of index keys is the same as the order of the indices on
  13203. +** the pTable->pIndex list. A key is only created for index i if
  13204. +** aIdxUsed!=0 and aIdxUsed[i]!=0.
  13205. +**
  13206. +** This routine also generates code to check constraints. NOT NULL,
  13207. +** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  13208. +** then the appropriate action is performed. There are five possible
  13209. +** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  13210. +**
  13211. +** Constraint type Action What Happens
  13212. +** --------------- ---------- ----------------------------------------
  13213. +** any ROLLBACK The current transaction is rolled back and
  13214. +** sqlite_exec() returns immediately with a
  13215. +** return code of SQLITE_CONSTRAINT.
  13216. +**
  13217. +** any ABORT Back out changes from the current command
  13218. +** only (do not do a complete rollback) then
  13219. +** cause sqlite_exec() to return immediately
  13220. +** with SQLITE_CONSTRAINT.
  13221. +**
  13222. +** any FAIL Sqlite_exec() returns immediately with a
  13223. +** return code of SQLITE_CONSTRAINT. The
  13224. +** transaction is not rolled back and any
  13225. +** prior changes are retained.
  13226. +**
  13227. +** any IGNORE The record number and data is popped from
  13228. +** the stack and there is an immediate jump
  13229. +** to label ignoreDest.
  13230. +**
  13231. +** NOT NULL REPLACE The NULL value is replace by the default
  13232. +** value for that column. If the default value
  13233. +** is NULL, the action is the same as ABORT.
  13234. +**
  13235. +** UNIQUE REPLACE The other row that conflicts with the row
  13236. +** being inserted is removed.
  13237. +**
  13238. +** CHECK REPLACE Illegal. The results in an exception.
  13239. +**
  13240. +** Which action to take is determined by the overrideError parameter.
  13241. +** Or if overrideError==OE_Default, then the pParse->onError parameter
  13242. +** is used. Or if pParse->onError==OE_Default then the onError value
  13243. +** for the constraint is used.
  13244. +**
  13245. +** The calling routine must open a read/write cursor for pTab with
  13246. +** cursor number "base". All indices of pTab must also have open
  13247. +** read/write cursors with cursor number base+i for the i-th cursor.
  13248. +** Except, if there is no possibility of a REPLACE action then
  13249. +** cursors do not need to be open for indices where aIdxUsed[i]==0.
  13250. +**
  13251. +** If the isUpdate flag is true, it means that the "base" cursor is
  13252. +** initially pointing to an entry that is being updated. The isUpdate
  13253. +** flag causes extra code to be generated so that the "base" cursor
  13254. +** is still pointing at the same entry after the routine returns.
  13255. +** Without the isUpdate flag, the "base" cursor might be moved.
  13256. +*/
  13257. +void sqliteGenerateConstraintChecks(
  13258. + Parse *pParse, /* The parser context */
  13259. + Table *pTab, /* the table into which we are inserting */
  13260. + int base, /* Index of a read/write cursor pointing at pTab */
  13261. + char *aIdxUsed, /* Which indices are used. NULL means all are used */
  13262. + int recnoChng, /* True if the record number will change */
  13263. + int isUpdate, /* True for UPDATE, False for INSERT */
  13264. + int overrideError, /* Override onError to this if not OE_Default */
  13265. + int ignoreDest /* Jump to this label on an OE_Ignore resolution */
  13266. +){
  13267. + int i;
  13268. + Vdbe *v;
  13269. + int nCol;
  13270. + int onError;
  13271. + int addr;
  13272. + int extra;
  13273. + int iCur;
  13274. + Index *pIdx;
  13275. + int seenReplace = 0;
  13276. + int jumpInst1, jumpInst2;
  13277. + int contAddr;
  13278. + int hasTwoRecnos = (isUpdate && recnoChng);
  13279. +
  13280. + v = sqliteGetVdbe(pParse);
  13281. + assert( v!=0 );
  13282. + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  13283. + nCol = pTab->nCol;
  13284. +
  13285. + /* Test all NOT NULL constraints.
  13286. + */
  13287. + for(i=0; i<nCol; i++){
  13288. + if( i==pTab->iPKey ){
  13289. + continue;
  13290. + }
  13291. + onError = pTab->aCol[i].notNull;
  13292. + if( onError==OE_None ) continue;
  13293. + if( overrideError!=OE_Default ){
  13294. + onError = overrideError;
  13295. + }else if( pParse->db->onError!=OE_Default ){
  13296. + onError = pParse->db->onError;
  13297. + }else if( onError==OE_Default ){
  13298. + onError = OE_Abort;
  13299. + }
  13300. + if( onError==OE_Replace && pTab->aCol[i].zDflt==0 ){
  13301. + onError = OE_Abort;
  13302. + }
  13303. + sqliteVdbeAddOp(v, OP_Dup, nCol-1-i, 1);
  13304. + addr = sqliteVdbeAddOp(v, OP_NotNull, 1, 0);
  13305. + switch( onError ){
  13306. + case OE_Rollback:
  13307. + case OE_Abort:
  13308. + case OE_Fail: {
  13309. + char *zMsg = 0;
  13310. + sqliteVdbeAddOp(v, OP_Halt, SQLITE_CONSTRAINT, onError);
  13311. + sqliteSetString(&zMsg, pTab->zName, ".", pTab->aCol[i].zName,
  13312. + " may not be NULL", (char*)0);
  13313. + sqliteVdbeChangeP3(v, -1, zMsg, P3_DYNAMIC);
  13314. + break;
  13315. + }
  13316. + case OE_Ignore: {
  13317. + sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
  13318. + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
  13319. + break;
  13320. + }
  13321. + case OE_Replace: {
  13322. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zDflt, P3_STATIC);
  13323. + sqliteVdbeAddOp(v, OP_Push, nCol-i, 0);
  13324. + break;
  13325. + }
  13326. + default: assert(0);
  13327. + }
  13328. + sqliteVdbeChangeP2(v, addr, sqliteVdbeCurrentAddr(v));
  13329. + }
  13330. +
  13331. + /* Test all CHECK constraints
  13332. + */
  13333. + /**** TBD ****/
  13334. +
  13335. + /* If we have an INTEGER PRIMARY KEY, make sure the primary key
  13336. + ** of the new record does not previously exist. Except, if this
  13337. + ** is an UPDATE and the primary key is not changing, that is OK.
  13338. + */
  13339. + if( recnoChng ){
  13340. + onError = pTab->keyConf;
  13341. + if( overrideError!=OE_Default ){
  13342. + onError = overrideError;
  13343. + }else if( pParse->db->onError!=OE_Default ){
  13344. + onError = pParse->db->onError;
  13345. + }else if( onError==OE_Default ){
  13346. + onError = OE_Abort;
  13347. + }
  13348. +
  13349. + if( isUpdate ){
  13350. + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
  13351. + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
  13352. + jumpInst1 = sqliteVdbeAddOp(v, OP_Eq, 0, 0);
  13353. + }
  13354. + sqliteVdbeAddOp(v, OP_Dup, nCol, 1);
  13355. + jumpInst2 = sqliteVdbeAddOp(v, OP_NotExists, base, 0);
  13356. + switch( onError ){
  13357. + default: {
  13358. + onError = OE_Abort;
  13359. + /* Fall thru into the next case */
  13360. + }
  13361. + case OE_Rollback:
  13362. + case OE_Abort:
  13363. + case OE_Fail: {
  13364. + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError,
  13365. + "PRIMARY KEY must be unique", P3_STATIC);
  13366. + break;
  13367. + }
  13368. + case OE_Replace: {
  13369. + sqliteGenerateRowIndexDelete(pParse->db, v, pTab, base, 0);
  13370. + if( isUpdate ){
  13371. + sqliteVdbeAddOp(v, OP_Dup, nCol+hasTwoRecnos, 1);
  13372. + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
  13373. + }
  13374. + seenReplace = 1;
  13375. + break;
  13376. + }
  13377. + case OE_Ignore: {
  13378. + assert( seenReplace==0 );
  13379. + sqliteVdbeAddOp(v, OP_Pop, nCol+1+hasTwoRecnos, 0);
  13380. + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
  13381. + break;
  13382. + }
  13383. + }
  13384. + contAddr = sqliteVdbeCurrentAddr(v);
  13385. + sqliteVdbeChangeP2(v, jumpInst2, contAddr);
  13386. + if( isUpdate ){
  13387. + sqliteVdbeChangeP2(v, jumpInst1, contAddr);
  13388. + sqliteVdbeAddOp(v, OP_Dup, nCol+1, 1);
  13389. + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
  13390. + }
  13391. + }
  13392. +
  13393. + /* Test all UNIQUE constraints by creating entries for each UNIQUE
  13394. + ** index and making sure that duplicate entries do not already exist.
  13395. + ** Add the new records to the indices as we go.
  13396. + */
  13397. + extra = -1;
  13398. + for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
  13399. + if( aIdxUsed && aIdxUsed[iCur]==0 ) continue; /* Skip unused indices */
  13400. + extra++;
  13401. +
  13402. + /* Create a key for accessing the index entry */
  13403. + sqliteVdbeAddOp(v, OP_Dup, nCol+extra, 1);
  13404. + for(i=0; i<pIdx->nColumn; i++){
  13405. + int idx = pIdx->aiColumn[i];
  13406. + if( idx==pTab->iPKey ){
  13407. + sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol+1, 1);
  13408. + }else{
  13409. + sqliteVdbeAddOp(v, OP_Dup, i+extra+nCol-idx, 1);
  13410. + }
  13411. + }
  13412. + jumpInst1 = sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
  13413. + if( pParse->db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
  13414. +
  13415. + /* Find out what action to take in case there is an indexing conflict */
  13416. + onError = pIdx->onError;
  13417. + if( onError==OE_None ) continue; /* pIdx is not a UNIQUE index */
  13418. + if( overrideError!=OE_Default ){
  13419. + onError = overrideError;
  13420. + }else if( pParse->db->onError!=OE_Default ){
  13421. + onError = pParse->db->onError;
  13422. + }else if( onError==OE_Default ){
  13423. + onError = OE_Abort;
  13424. + }
  13425. + if( seenReplace ){
  13426. + if( onError==OE_Ignore ) onError = OE_Replace;
  13427. + else if( onError==OE_Fail ) onError = OE_Abort;
  13428. + }
  13429. +
  13430. +
  13431. + /* Check to see if the new index entry will be unique */
  13432. + sqliteVdbeAddOp(v, OP_Dup, extra+nCol+1+hasTwoRecnos, 1);
  13433. + jumpInst2 = sqliteVdbeAddOp(v, OP_IsUnique, base+iCur+1, 0);
  13434. +
  13435. + /* Generate code that executes if the new index entry is not unique */
  13436. + switch( onError ){
  13437. + case OE_Rollback:
  13438. + case OE_Abort:
  13439. + case OE_Fail: {
  13440. + int j, n1, n2;
  13441. + char zErrMsg[200];
  13442. + strcpy(zErrMsg, pIdx->nColumn>1 ? "columns " : "column ");
  13443. + n1 = strlen(zErrMsg);
  13444. + for(j=0; j<pIdx->nColumn && n1<sizeof(zErrMsg)-30; j++){
  13445. + char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  13446. + n2 = strlen(zCol);
  13447. + if( j>0 ){
  13448. + strcpy(&zErrMsg[n1], ", ");
  13449. + n1 += 2;
  13450. + }
  13451. + if( n1+n2>sizeof(zErrMsg)-30 ){
  13452. + strcpy(&zErrMsg[n1], "...");
  13453. + n1 += 3;
  13454. + break;
  13455. + }else{
  13456. + strcpy(&zErrMsg[n1], zCol);
  13457. + n1 += n2;
  13458. + }
  13459. + }
  13460. + strcpy(&zErrMsg[n1],
  13461. + pIdx->nColumn>1 ? " are not unique" : " is not unique");
  13462. + sqliteVdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, onError, zErrMsg, 0);
  13463. + break;
  13464. + }
  13465. + case OE_Ignore: {
  13466. + assert( seenReplace==0 );
  13467. + sqliteVdbeAddOp(v, OP_Pop, nCol+extra+3+hasTwoRecnos, 0);
  13468. + sqliteVdbeAddOp(v, OP_Goto, 0, ignoreDest);
  13469. + break;
  13470. + }
  13471. + case OE_Replace: {
  13472. + sqliteGenerateRowDelete(pParse->db, v, pTab, base, 0);
  13473. + if( isUpdate ){
  13474. + sqliteVdbeAddOp(v, OP_Dup, nCol+extra+1+hasTwoRecnos, 1);
  13475. + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
  13476. + }
  13477. + seenReplace = 1;
  13478. + break;
  13479. + }
  13480. + default: assert(0);
  13481. + }
  13482. + contAddr = sqliteVdbeCurrentAddr(v);
  13483. +#if NULL_DISTINCT_FOR_UNIQUE
  13484. + sqliteVdbeChangeP2(v, jumpInst1, contAddr);
  13485. +#endif
  13486. + sqliteVdbeChangeP2(v, jumpInst2, contAddr);
  13487. + }
  13488. +}
  13489. +
  13490. +/*
  13491. +** This routine generates code to finish the INSERT or UPDATE operation
  13492. +** that was started by a prior call to sqliteGenerateConstraintChecks.
  13493. +** The stack must contain keys for all active indices followed by data
  13494. +** and the recno for the new entry. This routine creates the new
  13495. +** entries in all indices and in the main table.
  13496. +**
  13497. +** The arguments to this routine should be the same as the first six
  13498. +** arguments to sqliteGenerateConstraintChecks.
  13499. +*/
  13500. +void sqliteCompleteInsertion(
  13501. + Parse *pParse, /* The parser context */
  13502. + Table *pTab, /* the table into which we are inserting */
  13503. + int base, /* Index of a read/write cursor pointing at pTab */
  13504. + char *aIdxUsed, /* Which indices are used. NULL means all are used */
  13505. + int recnoChng, /* True if the record number will change */
  13506. + int isUpdate, /* True for UPDATE, False for INSERT */
  13507. + int newIdx /* Index of NEW table for triggers. -1 if none */
  13508. +){
  13509. + int i;
  13510. + Vdbe *v;
  13511. + int nIdx;
  13512. + Index *pIdx;
  13513. +
  13514. + v = sqliteGetVdbe(pParse);
  13515. + assert( v!=0 );
  13516. + assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  13517. + for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
  13518. + for(i=nIdx-1; i>=0; i--){
  13519. + if( aIdxUsed && aIdxUsed[i]==0 ) continue;
  13520. + sqliteVdbeAddOp(v, OP_IdxPut, base+i+1, 0);
  13521. + }
  13522. + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  13523. + if( newIdx>=0 ){
  13524. + sqliteVdbeAddOp(v, OP_Dup, 1, 0);
  13525. + sqliteVdbeAddOp(v, OP_Dup, 1, 0);
  13526. + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
  13527. + }
  13528. + sqliteVdbeAddOp(v, OP_PutIntKey, base,
  13529. + (pParse->trigStack?0:OPFLAG_NCHANGE) |
  13530. + (isUpdate?0:OPFLAG_LASTROWID) | OPFLAG_CSCHANGE);
  13531. + if( isUpdate && recnoChng ){
  13532. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  13533. + }
  13534. +}
  13535. +
  13536. +/*
  13537. +** Generate code that will open write cursors for a table and for all
  13538. +** indices of that table. The "base" parameter is the cursor number used
  13539. +** for the table. Indices are opened on subsequent cursors.
  13540. +**
  13541. +** Return the total number of cursors opened. This is always at least
  13542. +** 1 (for the main table) plus more for each cursor.
  13543. +*/
  13544. +int sqliteOpenTableAndIndices(Parse *pParse, Table *pTab, int base){
  13545. + int i;
  13546. + Index *pIdx;
  13547. + Vdbe *v = sqliteGetVdbe(pParse);
  13548. + assert( v!=0 );
  13549. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  13550. + sqliteVdbeOp3(v, OP_OpenWrite, base, pTab->tnum, pTab->zName, P3_STATIC);
  13551. + for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  13552. + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
  13553. + sqliteVdbeOp3(v, OP_OpenWrite, i+base, pIdx->tnum, pIdx->zName, P3_STATIC);
  13554. + }
  13555. + return i;
  13556. +}
  13557. --- /dev/null
  13558. +++ b/ext/sqlite/libsqlite/src/libsqlite.dsp
  13559. @@ -0,0 +1,353 @@
  13560. +# Microsoft Developer Studio Project File - Name="libsqlite" - Package Owner=<4>
  13561. +# Microsoft Developer Studio Generated Build File, Format Version 6.00
  13562. +# ** DO NOT EDIT **
  13563. +
  13564. +# TARGTYPE "Win32 (x86) Static Library" 0x0104
  13565. +
  13566. +CFG=libsqlite - Win32 Debug_TS
  13567. +!MESSAGE This is not a valid makefile. To build this project using NMAKE,
  13568. +!MESSAGE use the Export Makefile command and run
  13569. +!MESSAGE
  13570. +!MESSAGE NMAKE /f "libsqlite.mak".
  13571. +!MESSAGE
  13572. +!MESSAGE You can specify a configuration when running NMAKE
  13573. +!MESSAGE by defining the macro CFG on the command line. For example:
  13574. +!MESSAGE
  13575. +!MESSAGE NMAKE /f "libsqlite.mak" CFG="libsqlite - Win32 Debug_TS"
  13576. +!MESSAGE
  13577. +!MESSAGE Possible choices for configuration are:
  13578. +!MESSAGE
  13579. +!MESSAGE "libsqlite - Win32 Debug_TS" (based on "Win32 (x86) Static Library")
  13580. +!MESSAGE "libsqlite - Win32 Release_TS" (based on "Win32 (x86) Static Library")
  13581. +!MESSAGE "libsqlite - Win32 Release_TSDbg" (based on "Win32 (x86) Static Library")
  13582. +!MESSAGE
  13583. +
  13584. +# Begin Project
  13585. +# PROP AllowPerConfigDependencies 0
  13586. +# PROP Scc_ProjName ""
  13587. +# PROP Scc_LocalPath ""
  13588. +CPP=cl.exe
  13589. +RSC=rc.exe
  13590. +
  13591. +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
  13592. +
  13593. +# PROP BASE Use_MFC 0
  13594. +# PROP BASE Use_Debug_Libraries 1
  13595. +# PROP BASE Output_Dir "Debug_TS"
  13596. +# PROP BASE Intermediate_Dir "Debug_TS"
  13597. +# PROP BASE Target_Dir ""
  13598. +# PROP Use_MFC 0
  13599. +# PROP Use_Debug_Libraries 1
  13600. +# PROP Output_Dir "..\..\Debug_TS"
  13601. +# PROP Intermediate_Dir "..\..\Debug_TS"
  13602. +# PROP Target_Dir ""
  13603. +# ADD BASE CPP /nologo /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /YX /FD /GZ /c
  13604. +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /GZ /c
  13605. +# ADD BASE RSC /l 0x406 /d "_DEBUG"
  13606. +# ADD RSC /l 0x406 /d "_DEBUG"
  13607. +BSC32=bscmake.exe
  13608. +# ADD BASE BSC32 /nologo
  13609. +# ADD BSC32 /nologo
  13610. +LIB32=link.exe -lib
  13611. +# ADD BASE LIB32 /nologo
  13612. +# ADD LIB32 /nologo
  13613. +
  13614. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
  13615. +
  13616. +# PROP BASE Use_MFC 0
  13617. +# PROP BASE Use_Debug_Libraries 0
  13618. +# PROP BASE Output_Dir "Release_TS"
  13619. +# PROP BASE Intermediate_Dir "Release_TS"
  13620. +# PROP BASE Target_Dir ""
  13621. +# PROP Use_MFC 0
  13622. +# PROP Use_Debug_Libraries 0
  13623. +# PROP Output_Dir "..\..\Release_TS"
  13624. +# PROP Intermediate_Dir "..\..\Release_TS"
  13625. +# PROP Target_Dir ""
  13626. +# ADD BASE CPP /nologo /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /YX /FD /c
  13627. +# ADD CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
  13628. +# ADD BASE RSC /l 0x406 /d "NDEBUG"
  13629. +# ADD RSC /l 0x406 /d "NDEBUG"
  13630. +BSC32=bscmake.exe
  13631. +# ADD BASE BSC32 /nologo
  13632. +# ADD BSC32 /nologo
  13633. +LIB32=link.exe -lib
  13634. +# ADD BASE LIB32 /nologo
  13635. +# ADD LIB32 /nologo
  13636. +
  13637. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
  13638. +
  13639. +# PROP BASE Use_MFC 0
  13640. +# PROP BASE Use_Debug_Libraries 0
  13641. +# PROP BASE Output_Dir "libsqlite___Win32_Release_TSDbg"
  13642. +# PROP BASE Intermediate_Dir "libsqlite___Win32_Release_TSDbg"
  13643. +# PROP BASE Target_Dir ""
  13644. +# PROP Use_MFC 0
  13645. +# PROP Use_Debug_Libraries 0
  13646. +# PROP Output_Dir "..\..\Release_TSDbg"
  13647. +# PROP Intermediate_Dir "..\..\Release_TSDbg"
  13648. +# PROP Target_Dir ""
  13649. +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
  13650. +# ADD CPP /nologo /MD /W3 /GX /Zi /Od /D "WIN32" /D "NDEBUG" /D "_MBCS" /D "_LIB" /D THREADSAFE=1 /YX /FD /c
  13651. +# ADD BASE RSC /l 0x406 /d "NDEBUG"
  13652. +# ADD RSC /l 0x406 /d "NDEBUG"
  13653. +BSC32=bscmake.exe
  13654. +# ADD BASE BSC32 /nologo
  13655. +# ADD BSC32 /nologo
  13656. +LIB32=link.exe -lib
  13657. +# ADD BASE LIB32 /nologo /out:"Release_TS\libsqlite.lib"
  13658. +# ADD LIB32 /nologo
  13659. +
  13660. +!ENDIF
  13661. +
  13662. +# Begin Target
  13663. +
  13664. +# Name "libsqlite - Win32 Debug_TS"
  13665. +# Name "libsqlite - Win32 Release_TS"
  13666. +# Name "libsqlite - Win32 Release_TSDbg"
  13667. +# Begin Group "Source Files"
  13668. +
  13669. +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
  13670. +# Begin Source File
  13671. +
  13672. +SOURCE=attach.c
  13673. +# End Source File
  13674. +# Begin Source File
  13675. +
  13676. +SOURCE=auth.c
  13677. +# End Source File
  13678. +# Begin Source File
  13679. +
  13680. +SOURCE=btree.c
  13681. +# End Source File
  13682. +# Begin Source File
  13683. +
  13684. +SOURCE=btree_rb.c
  13685. +# End Source File
  13686. +# Begin Source File
  13687. +
  13688. +SOURCE=build.c
  13689. +# End Source File
  13690. +# Begin Source File
  13691. +
  13692. +SOURCE=copy.c
  13693. +# End Source File
  13694. +# Begin Source File
  13695. +
  13696. +SOURCE=.\date.c
  13697. +# End Source File
  13698. +# Begin Source File
  13699. +
  13700. +SOURCE=delete.c
  13701. +# End Source File
  13702. +# Begin Source File
  13703. +
  13704. +SOURCE=encode.c
  13705. +# End Source File
  13706. +# Begin Source File
  13707. +
  13708. +SOURCE=expr.c
  13709. +# End Source File
  13710. +# Begin Source File
  13711. +
  13712. +SOURCE=func.c
  13713. +# End Source File
  13714. +# Begin Source File
  13715. +
  13716. +SOURCE=hash.c
  13717. +# End Source File
  13718. +# Begin Source File
  13719. +
  13720. +SOURCE=insert.c
  13721. +# End Source File
  13722. +# Begin Source File
  13723. +
  13724. +SOURCE=main.c
  13725. +# End Source File
  13726. +# Begin Source File
  13727. +
  13728. +SOURCE=opcodes.c
  13729. +# End Source File
  13730. +# Begin Source File
  13731. +
  13732. +SOURCE=os.c
  13733. +# End Source File
  13734. +# Begin Source File
  13735. +
  13736. +SOURCE=pager.c
  13737. +# End Source File
  13738. +# Begin Source File
  13739. +
  13740. +SOURCE=parse.c
  13741. +# End Source File
  13742. +# Begin Source File
  13743. +
  13744. +SOURCE=pragma.c
  13745. +# End Source File
  13746. +# Begin Source File
  13747. +
  13748. +SOURCE=printf.c
  13749. +# End Source File
  13750. +# Begin Source File
  13751. +
  13752. +SOURCE=random.c
  13753. +# End Source File
  13754. +# Begin Source File
  13755. +
  13756. +SOURCE=select.c
  13757. +# End Source File
  13758. +# Begin Source File
  13759. +
  13760. +SOURCE=table.c
  13761. +# End Source File
  13762. +# Begin Source File
  13763. +
  13764. +SOURCE=tokenize.c
  13765. +# End Source File
  13766. +# Begin Source File
  13767. +
  13768. +SOURCE=trigger.c
  13769. +# End Source File
  13770. +# Begin Source File
  13771. +
  13772. +SOURCE=update.c
  13773. +# End Source File
  13774. +# Begin Source File
  13775. +
  13776. +SOURCE=util.c
  13777. +# End Source File
  13778. +# Begin Source File
  13779. +
  13780. +SOURCE=vacuum.c
  13781. +# End Source File
  13782. +# Begin Source File
  13783. +
  13784. +SOURCE=vdbe.c
  13785. +# End Source File
  13786. +# Begin Source File
  13787. +
  13788. +SOURCE=.\vdbeaux.c
  13789. +# End Source File
  13790. +# Begin Source File
  13791. +
  13792. +SOURCE=where.c
  13793. +# End Source File
  13794. +# End Group
  13795. +# Begin Group "Header Files"
  13796. +
  13797. +# PROP Default_Filter "h;hpp;hxx;hm;inl"
  13798. +# Begin Source File
  13799. +
  13800. +SOURCE=btree.h
  13801. +# End Source File
  13802. +# Begin Source File
  13803. +
  13804. +SOURCE=config_static.w32.h
  13805. +
  13806. +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
  13807. +
  13808. +# Begin Custom Build
  13809. +InputDir=.
  13810. +InputPath=config_static.w32.h
  13811. +
  13812. +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13813. + copy $(InputPath) $(InputDir)\config.h
  13814. +
  13815. +# End Custom Build
  13816. +
  13817. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
  13818. +
  13819. +# Begin Custom Build
  13820. +InputDir=.
  13821. +InputPath=config_static.w32.h
  13822. +
  13823. +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13824. + copy $(InputPath) $(InputDir)\config.h
  13825. +
  13826. +# End Custom Build
  13827. +
  13828. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
  13829. +
  13830. +# Begin Custom Build
  13831. +InputDir=.
  13832. +InputPath=config_static.w32.h
  13833. +
  13834. +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13835. + copy $(InputPath) $(InputDir)\config.h
  13836. +
  13837. +# End Custom Build
  13838. +
  13839. +!ENDIF
  13840. +
  13841. +# End Source File
  13842. +# Begin Source File
  13843. +
  13844. +SOURCE=hash.h
  13845. +# End Source File
  13846. +# Begin Source File
  13847. +
  13848. +SOURCE=opcodes.h
  13849. +# End Source File
  13850. +# Begin Source File
  13851. +
  13852. +SOURCE=os.h
  13853. +# End Source File
  13854. +# Begin Source File
  13855. +
  13856. +SOURCE=pager.h
  13857. +# End Source File
  13858. +# Begin Source File
  13859. +
  13860. +SOURCE=parse.h
  13861. +# End Source File
  13862. +# Begin Source File
  13863. +
  13864. +SOURCE=sqlite.w32.h
  13865. +
  13866. +!IF "$(CFG)" == "libsqlite - Win32 Debug_TS"
  13867. +
  13868. +# Begin Custom Build
  13869. +InputDir=.
  13870. +InputPath=sqlite.w32.h
  13871. +
  13872. +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13873. + copy $(InputPath) $(InputDir)\sqlite.h
  13874. +
  13875. +# End Custom Build
  13876. +
  13877. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TS"
  13878. +
  13879. +# Begin Custom Build
  13880. +InputDir=.
  13881. +InputPath=sqlite.w32.h
  13882. +
  13883. +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13884. + copy $(InputPath) $(InputDir)\sqlite.h
  13885. +
  13886. +# End Custom Build
  13887. +
  13888. +!ELSEIF "$(CFG)" == "libsqlite - Win32 Release_TSDbg"
  13889. +
  13890. +# Begin Custom Build
  13891. +InputDir=.
  13892. +InputPath=sqlite.w32.h
  13893. +
  13894. +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  13895. + copy $(InputPath) $(InputDir)\sqlite.h
  13896. +
  13897. +# End Custom Build
  13898. +
  13899. +!ENDIF
  13900. +
  13901. +# End Source File
  13902. +# Begin Source File
  13903. +
  13904. +SOURCE=sqliteInt.h
  13905. +# End Source File
  13906. +# Begin Source File
  13907. +
  13908. +SOURCE=vdbe.h
  13909. +# End Source File
  13910. +# End Group
  13911. +# End Target
  13912. +# End Project
  13913. --- /dev/null
  13914. +++ b/ext/sqlite/libsqlite/src/main.c
  13915. @@ -0,0 +1,1143 @@
  13916. +/*
  13917. +** 2001 September 15
  13918. +**
  13919. +** The author disclaims copyright to this source code. In place of
  13920. +** a legal notice, here is a blessing:
  13921. +**
  13922. +** May you do good and not evil.
  13923. +** May you find forgiveness for yourself and forgive others.
  13924. +** May you share freely, never taking more than you give.
  13925. +**
  13926. +*************************************************************************
  13927. +** Main file for the SQLite library. The routines in this file
  13928. +** implement the programmer interface to the library. Routines in
  13929. +** other files are for internal use by SQLite and should not be
  13930. +** accessed by users of the library.
  13931. +**
  13932. +** $Id$
  13933. +*/
  13934. +#include "sqliteInt.h"
  13935. +#include "os.h"
  13936. +#include <ctype.h>
  13937. +
  13938. +/*
  13939. +** A pointer to this structure is used to communicate information
  13940. +** from sqliteInit into the sqliteInitCallback.
  13941. +*/
  13942. +typedef struct {
  13943. + sqlite *db; /* The database being initialized */
  13944. + char **pzErrMsg; /* Error message stored here */
  13945. +} InitData;
  13946. +
  13947. +/*
  13948. +** Fill the InitData structure with an error message that indicates
  13949. +** that the database is corrupt.
  13950. +*/
  13951. +static void corruptSchema(InitData *pData, const char *zExtra){
  13952. + sqliteSetString(pData->pzErrMsg, "malformed database schema",
  13953. + zExtra!=0 && zExtra[0]!=0 ? " - " : (char*)0, zExtra, (char*)0);
  13954. +}
  13955. +
  13956. +/*
  13957. +** This is the callback routine for the code that initializes the
  13958. +** database. See sqliteInit() below for additional information.
  13959. +**
  13960. +** Each callback contains the following information:
  13961. +**
  13962. +** argv[0] = "file-format" or "schema-cookie" or "table" or "index"
  13963. +** argv[1] = table or index name or meta statement type.
  13964. +** argv[2] = root page number for table or index. NULL for meta.
  13965. +** argv[3] = SQL text for a CREATE TABLE or CREATE INDEX statement.
  13966. +** argv[4] = "1" for temporary files, "0" for main database, "2" or more
  13967. +** for auxiliary database files.
  13968. +**
  13969. +*/
  13970. +static
  13971. +int sqliteInitCallback(void *pInit, int argc, char **argv, char **azColName){
  13972. + InitData *pData = (InitData*)pInit;
  13973. + int nErr = 0;
  13974. +
  13975. + assert( argc==5 );
  13976. + if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  13977. + if( argv[0]==0 ){
  13978. + corruptSchema(pData, 0);
  13979. + return 1;
  13980. + }
  13981. + switch( argv[0][0] ){
  13982. + case 'v':
  13983. + case 'i':
  13984. + case 't': { /* CREATE TABLE, CREATE INDEX, or CREATE VIEW statements */
  13985. + sqlite *db = pData->db;
  13986. + if( argv[2]==0 || argv[4]==0 ){
  13987. + corruptSchema(pData, 0);
  13988. + return 1;
  13989. + }
  13990. + if( argv[3] && argv[3][0] ){
  13991. + /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  13992. + ** But because db->init.busy is set to 1, no VDBE code is generated
  13993. + ** or executed. All the parser does is build the internal data
  13994. + ** structures that describe the table, index, or view.
  13995. + */
  13996. + char *zErr;
  13997. + assert( db->init.busy );
  13998. + db->init.iDb = atoi(argv[4]);
  13999. + assert( db->init.iDb>=0 && db->init.iDb<db->nDb );
  14000. + db->init.newTnum = atoi(argv[2]);
  14001. + if( sqlite_exec(db, argv[3], 0, 0, &zErr) ){
  14002. + corruptSchema(pData, zErr);
  14003. + sqlite_freemem(zErr);
  14004. + }
  14005. + db->init.iDb = 0;
  14006. + }else{
  14007. + /* If the SQL column is blank it means this is an index that
  14008. + ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  14009. + ** constraint for a CREATE TABLE. The index should have already
  14010. + ** been created when we processed the CREATE TABLE. All we have
  14011. + ** to do here is record the root page number for that index.
  14012. + */
  14013. + int iDb;
  14014. + Index *pIndex;
  14015. +
  14016. + iDb = atoi(argv[4]);
  14017. + assert( iDb>=0 && iDb<db->nDb );
  14018. + pIndex = sqliteFindIndex(db, argv[1], db->aDb[iDb].zName);
  14019. + if( pIndex==0 || pIndex->tnum!=0 ){
  14020. + /* This can occur if there exists an index on a TEMP table which
  14021. + ** has the same name as another index on a permanent index. Since
  14022. + ** the permanent table is hidden by the TEMP table, we can also
  14023. + ** safely ignore the index on the permanent table.
  14024. + */
  14025. + /* Do Nothing */;
  14026. + }else{
  14027. + pIndex->tnum = atoi(argv[2]);
  14028. + }
  14029. + }
  14030. + break;
  14031. + }
  14032. + default: {
  14033. + /* This can not happen! */
  14034. + nErr = 1;
  14035. + assert( nErr==0 );
  14036. + }
  14037. + }
  14038. + return nErr;
  14039. +}
  14040. +
  14041. +/*
  14042. +** This is a callback procedure used to reconstruct a table. The
  14043. +** name of the table to be reconstructed is passed in as argv[0].
  14044. +**
  14045. +** This routine is used to automatically upgrade a database from
  14046. +** format version 1 or 2 to version 3. The correct operation of
  14047. +** this routine relys on the fact that no indices are used when
  14048. +** copying a table out to a temporary file.
  14049. +**
  14050. +** The change from version 2 to version 3 occurred between SQLite
  14051. +** version 2.5.6 and 2.6.0 on 2002-July-18.
  14052. +*/
  14053. +static
  14054. +int upgrade_3_callback(void *pInit, int argc, char **argv, char **NotUsed){
  14055. + InitData *pData = (InitData*)pInit;
  14056. + int rc;
  14057. + Table *pTab;
  14058. + Trigger *pTrig;
  14059. + char *zErr = 0;
  14060. +
  14061. + pTab = sqliteFindTable(pData->db, argv[0], 0);
  14062. + assert( pTab!=0 );
  14063. + assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
  14064. + if( pTab ){
  14065. + pTrig = pTab->pTrigger;
  14066. + pTab->pTrigger = 0; /* Disable all triggers before rebuilding the table */
  14067. + }
  14068. + rc = sqlite_exec_printf(pData->db,
  14069. + "CREATE TEMP TABLE sqlite_x AS SELECT * FROM '%q'; "
  14070. + "DELETE FROM '%q'; "
  14071. + "INSERT INTO '%q' SELECT * FROM sqlite_x; "
  14072. + "DROP TABLE sqlite_x;",
  14073. + 0, 0, &zErr, argv[0], argv[0], argv[0]);
  14074. + if( zErr ){
  14075. + if( *pData->pzErrMsg ) sqlite_freemem(*pData->pzErrMsg);
  14076. + *pData->pzErrMsg = zErr;
  14077. + }
  14078. +
  14079. + /* If an error occurred in the SQL above, then the transaction will
  14080. + ** rollback which will delete the internal symbol tables. This will
  14081. + ** cause the structure that pTab points to be deleted. In case that
  14082. + ** happened, we need to refetch pTab.
  14083. + */
  14084. + pTab = sqliteFindTable(pData->db, argv[0], 0);
  14085. + if( pTab ){
  14086. + assert( sqliteStrICmp(pTab->zName, argv[0])==0 );
  14087. + pTab->pTrigger = pTrig; /* Re-enable triggers */
  14088. + }
  14089. + return rc!=SQLITE_OK;
  14090. +}
  14091. +
  14092. +
  14093. +
  14094. +/*
  14095. +** Attempt to read the database schema and initialize internal
  14096. +** data structures for a single database file. The index of the
  14097. +** database file is given by iDb. iDb==0 is used for the main
  14098. +** database. iDb==1 should never be used. iDb>=2 is used for
  14099. +** auxiliary databases. Return one of the SQLITE_ error codes to
  14100. +** indicate success or failure.
  14101. +*/
  14102. +static int sqliteInitOne(sqlite *db, int iDb, char **pzErrMsg){
  14103. + int rc;
  14104. + BtCursor *curMain;
  14105. + int size;
  14106. + Table *pTab;
  14107. + char const *azArg[6];
  14108. + char zDbNum[30];
  14109. + int meta[SQLITE_N_BTREE_META];
  14110. + InitData initData;
  14111. + char const *zMasterSchema;
  14112. + char const *zMasterName;
  14113. + char *zSql = 0;
  14114. +
  14115. + /*
  14116. + ** The master database table has a structure like this
  14117. + */
  14118. + static char master_schema[] =
  14119. + "CREATE TABLE sqlite_master(\n"
  14120. + " type text,\n"
  14121. + " name text,\n"
  14122. + " tbl_name text,\n"
  14123. + " rootpage integer,\n"
  14124. + " sql text\n"
  14125. + ")"
  14126. + ;
  14127. + static char temp_master_schema[] =
  14128. + "CREATE TEMP TABLE sqlite_temp_master(\n"
  14129. + " type text,\n"
  14130. + " name text,\n"
  14131. + " tbl_name text,\n"
  14132. + " rootpage integer,\n"
  14133. + " sql text\n"
  14134. + ")"
  14135. + ;
  14136. +
  14137. + assert( iDb>=0 && iDb<db->nDb );
  14138. +
  14139. + /* zMasterSchema and zInitScript are set to point at the master schema
  14140. + ** and initialisation script appropriate for the database being
  14141. + ** initialised. zMasterName is the name of the master table.
  14142. + */
  14143. + if( iDb==1 ){
  14144. + zMasterSchema = temp_master_schema;
  14145. + zMasterName = TEMP_MASTER_NAME;
  14146. + }else{
  14147. + zMasterSchema = master_schema;
  14148. + zMasterName = MASTER_NAME;
  14149. + }
  14150. +
  14151. + /* Construct the schema table.
  14152. + */
  14153. + sqliteSafetyOff(db);
  14154. + azArg[0] = "table";
  14155. + azArg[1] = zMasterName;
  14156. + azArg[2] = "2";
  14157. + azArg[3] = zMasterSchema;
  14158. + sprintf(zDbNum, "%d", iDb);
  14159. + azArg[4] = zDbNum;
  14160. + azArg[5] = 0;
  14161. + initData.db = db;
  14162. + initData.pzErrMsg = pzErrMsg;
  14163. + sqliteInitCallback(&initData, 5, (char **)azArg, 0);
  14164. + pTab = sqliteFindTable(db, zMasterName, db->aDb[iDb].zName);
  14165. + if( pTab ){
  14166. + pTab->readOnly = 1;
  14167. + }else{
  14168. + return SQLITE_NOMEM;
  14169. + }
  14170. + sqliteSafetyOn(db);
  14171. +
  14172. + /* Create a cursor to hold the database open
  14173. + */
  14174. + if( db->aDb[iDb].pBt==0 ) return SQLITE_OK;
  14175. + rc = sqliteBtreeCursor(db->aDb[iDb].pBt, 2, 0, &curMain);
  14176. + if( rc ){
  14177. + sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
  14178. + return rc;
  14179. + }
  14180. +
  14181. + /* Get the database meta information
  14182. + */
  14183. + rc = sqliteBtreeGetMeta(db->aDb[iDb].pBt, meta);
  14184. + if( rc ){
  14185. + sqliteSetString(pzErrMsg, sqlite_error_string(rc), (char*)0);
  14186. + sqliteBtreeCloseCursor(curMain);
  14187. + return rc;
  14188. + }
  14189. + db->aDb[iDb].schema_cookie = meta[1];
  14190. + if( iDb==0 ){
  14191. + db->next_cookie = meta[1];
  14192. + db->file_format = meta[2];
  14193. + size = meta[3];
  14194. + if( size==0 ){ size = MAX_PAGES; }
  14195. + db->cache_size = size;
  14196. + db->safety_level = meta[4];
  14197. + if( meta[6]>0 && meta[6]<=2 && db->temp_store==0 ){
  14198. + db->temp_store = meta[6];
  14199. + }
  14200. + if( db->safety_level==0 ) db->safety_level = 2;
  14201. +
  14202. + /*
  14203. + ** file_format==1 Version 2.1.0.
  14204. + ** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
  14205. + ** file_format==3 Version 2.6.0. Fix empty-string index bug.
  14206. + ** file_format==4 Version 2.7.0. Add support for separate numeric and
  14207. + ** text datatypes.
  14208. + */
  14209. + if( db->file_format==0 ){
  14210. + /* This happens if the database was initially empty */
  14211. + db->file_format = 4;
  14212. + }else if( db->file_format>4 ){
  14213. + sqliteBtreeCloseCursor(curMain);
  14214. + sqliteSetString(pzErrMsg, "unsupported file format", (char*)0);
  14215. + return SQLITE_ERROR;
  14216. + }
  14217. + }else if( iDb!=1 && (db->file_format!=meta[2] || db->file_format<4) ){
  14218. + assert( db->file_format>=4 );
  14219. + if( meta[2]==0 ){
  14220. + sqliteSetString(pzErrMsg, "cannot attach empty database: ",
  14221. + db->aDb[iDb].zName, (char*)0);
  14222. + }else{
  14223. + sqliteSetString(pzErrMsg, "incompatible file format in auxiliary "
  14224. + "database: ", db->aDb[iDb].zName, (char*)0);
  14225. + }
  14226. + sqliteBtreeClose(db->aDb[iDb].pBt);
  14227. + db->aDb[iDb].pBt = 0;
  14228. + return SQLITE_FORMAT;
  14229. + }
  14230. + sqliteBtreeSetCacheSize(db->aDb[iDb].pBt, db->cache_size);
  14231. + sqliteBtreeSetSafetyLevel(db->aDb[iDb].pBt, meta[4]==0 ? 2 : meta[4]);
  14232. +
  14233. + /* Read the schema information out of the schema tables
  14234. + */
  14235. + assert( db->init.busy );
  14236. + sqliteSafetyOff(db);
  14237. +
  14238. + /* The following SQL will read the schema from the master tables.
  14239. + ** The first version works with SQLite file formats 2 or greater.
  14240. + ** The second version is for format 1 files.
  14241. + **
  14242. + ** Beginning with file format 2, the rowid for new table entries
  14243. + ** (including entries in sqlite_master) is an increasing integer.
  14244. + ** So for file format 2 and later, we can play back sqlite_master
  14245. + ** and all the CREATE statements will appear in the right order.
  14246. + ** But with file format 1, table entries were random and so we
  14247. + ** have to make sure the CREATE TABLEs occur before their corresponding
  14248. + ** CREATE INDEXs. (We don't have to deal with CREATE VIEW or
  14249. + ** CREATE TRIGGER in file format 1 because those constructs did
  14250. + ** not exist then.)
  14251. + */
  14252. + if( db->file_format>=2 ){
  14253. + sqliteSetString(&zSql,
  14254. + "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
  14255. + db->aDb[iDb].zName, "\".", zMasterName, (char*)0);
  14256. + }else{
  14257. + sqliteSetString(&zSql,
  14258. + "SELECT type, name, rootpage, sql, ", zDbNum, " FROM \"",
  14259. + db->aDb[iDb].zName, "\".", zMasterName,
  14260. + " WHERE type IN ('table', 'index')"
  14261. + " ORDER BY CASE type WHEN 'table' THEN 0 ELSE 1 END", (char*)0);
  14262. + }
  14263. + rc = sqlite_exec(db, zSql, sqliteInitCallback, &initData, 0);
  14264. +
  14265. + sqliteFree(zSql);
  14266. + sqliteSafetyOn(db);
  14267. + sqliteBtreeCloseCursor(curMain);
  14268. + if( sqlite_malloc_failed ){
  14269. + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  14270. + rc = SQLITE_NOMEM;
  14271. + sqliteResetInternalSchema(db, 0);
  14272. + }
  14273. + if( rc==SQLITE_OK ){
  14274. + DbSetProperty(db, iDb, DB_SchemaLoaded);
  14275. + }else{
  14276. + sqliteResetInternalSchema(db, iDb);
  14277. + }
  14278. + return rc;
  14279. +}
  14280. +
  14281. +/*
  14282. +** Initialize all database files - the main database file, the file
  14283. +** used to store temporary tables, and any additional database files
  14284. +** created using ATTACH statements. Return a success code. If an
  14285. +** error occurs, write an error message into *pzErrMsg.
  14286. +**
  14287. +** After the database is initialized, the SQLITE_Initialized
  14288. +** bit is set in the flags field of the sqlite structure. An
  14289. +** attempt is made to initialize the database as soon as it
  14290. +** is opened. If that fails (perhaps because another process
  14291. +** has the sqlite_master table locked) than another attempt
  14292. +** is made the first time the database is accessed.
  14293. +*/
  14294. +int sqliteInit(sqlite *db, char **pzErrMsg){
  14295. + int i, rc;
  14296. +
  14297. + if( db->init.busy ) return SQLITE_OK;
  14298. + assert( (db->flags & SQLITE_Initialized)==0 );
  14299. + rc = SQLITE_OK;
  14300. + db->init.busy = 1;
  14301. + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  14302. + if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  14303. + rc = sqliteInitOne(db, i, pzErrMsg);
  14304. + if( rc ){
  14305. + sqliteResetInternalSchema(db, i);
  14306. + }
  14307. + }
  14308. +
  14309. + /* Once all the other databases have been initialised, load the schema
  14310. + ** for the TEMP database. This is loaded last, as the TEMP database
  14311. + ** schema may contain references to objects in other databases.
  14312. + */
  14313. + if( rc==SQLITE_OK && db->nDb>1 && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  14314. + rc = sqliteInitOne(db, 1, pzErrMsg);
  14315. + if( rc ){
  14316. + sqliteResetInternalSchema(db, 1);
  14317. + }
  14318. + }
  14319. +
  14320. + db->init.busy = 0;
  14321. + if( rc==SQLITE_OK ){
  14322. + db->flags |= SQLITE_Initialized;
  14323. + sqliteCommitInternalChanges(db);
  14324. + }
  14325. +
  14326. + /* If the database is in formats 1 or 2, then upgrade it to
  14327. + ** version 3. This will reconstruct all indices. If the
  14328. + ** upgrade fails for any reason (ex: out of disk space, database
  14329. + ** is read only, interrupt received, etc.) then fail the init.
  14330. + */
  14331. + if( rc==SQLITE_OK && db->file_format<3 ){
  14332. + char *zErr = 0;
  14333. + InitData initData;
  14334. + int meta[SQLITE_N_BTREE_META];
  14335. +
  14336. + db->magic = SQLITE_MAGIC_OPEN;
  14337. + initData.db = db;
  14338. + initData.pzErrMsg = &zErr;
  14339. + db->file_format = 3;
  14340. + rc = sqlite_exec(db,
  14341. + "BEGIN; SELECT name FROM sqlite_master WHERE type='table';",
  14342. + upgrade_3_callback,
  14343. + &initData,
  14344. + &zErr);
  14345. + if( rc==SQLITE_OK ){
  14346. + sqliteBtreeGetMeta(db->aDb[0].pBt, meta);
  14347. + meta[2] = 4;
  14348. + sqliteBtreeUpdateMeta(db->aDb[0].pBt, meta);
  14349. + sqlite_exec(db, "COMMIT", 0, 0, 0);
  14350. + }
  14351. + if( rc!=SQLITE_OK ){
  14352. + sqliteSetString(pzErrMsg,
  14353. + "unable to upgrade database to the version 2.6 format",
  14354. + zErr ? ": " : 0, zErr, (char*)0);
  14355. + }
  14356. + sqlite_freemem(zErr);
  14357. + }
  14358. +
  14359. + if( rc!=SQLITE_OK ){
  14360. + db->flags &= ~SQLITE_Initialized;
  14361. + }
  14362. + return rc;
  14363. +}
  14364. +
  14365. +/*
  14366. +** The version of the library
  14367. +*/
  14368. +const char rcsid[] = "@(#) \044Id: SQLite version " SQLITE_VERSION " $";
  14369. +const char sqlite_version[] = SQLITE_VERSION;
  14370. +
  14371. +/*
  14372. +** Does the library expect data to be encoded as UTF-8 or iso8859? The
  14373. +** following global constant always lets us know.
  14374. +*/
  14375. +#ifdef SQLITE_UTF8
  14376. +const char sqlite_encoding[] = "UTF-8";
  14377. +#else
  14378. +const char sqlite_encoding[] = "iso8859";
  14379. +#endif
  14380. +
  14381. +/*
  14382. +** Open a new SQLite database. Construct an "sqlite" structure to define
  14383. +** the state of this database and return a pointer to that structure.
  14384. +**
  14385. +** An attempt is made to initialize the in-memory data structures that
  14386. +** hold the database schema. But if this fails (because the schema file
  14387. +** is locked) then that step is deferred until the first call to
  14388. +** sqlite_exec().
  14389. +*/
  14390. +sqlite *sqlite_open(const char *zFilename, int mode, char **pzErrMsg){
  14391. + sqlite *db;
  14392. + int rc, i;
  14393. +
  14394. + /* Allocate the sqlite data structure */
  14395. + db = sqliteMalloc( sizeof(sqlite) );
  14396. + if( pzErrMsg ) *pzErrMsg = 0;
  14397. + if( db==0 ) goto no_mem_on_open;
  14398. + db->onError = OE_Default;
  14399. + db->priorNewRowid = 0;
  14400. + db->magic = SQLITE_MAGIC_BUSY;
  14401. + db->nDb = 2;
  14402. + db->aDb = db->aDbStatic;
  14403. + /* db->flags |= SQLITE_ShortColNames; */
  14404. + sqliteHashInit(&db->aFunc, SQLITE_HASH_STRING, 1);
  14405. + for(i=0; i<db->nDb; i++){
  14406. + sqliteHashInit(&db->aDb[i].tblHash, SQLITE_HASH_STRING, 0);
  14407. + sqliteHashInit(&db->aDb[i].idxHash, SQLITE_HASH_STRING, 0);
  14408. + sqliteHashInit(&db->aDb[i].trigHash, SQLITE_HASH_STRING, 0);
  14409. + sqliteHashInit(&db->aDb[i].aFKey, SQLITE_HASH_STRING, 1);
  14410. + }
  14411. +
  14412. + /* Open the backend database driver */
  14413. + if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
  14414. + db->temp_store = 2;
  14415. + }
  14416. + rc = sqliteBtreeFactory(db, zFilename, 0, MAX_PAGES, &db->aDb[0].pBt);
  14417. + if( rc!=SQLITE_OK ){
  14418. + switch( rc ){
  14419. + default: {
  14420. + sqliteSetString(pzErrMsg, "unable to open database: ",
  14421. + zFilename, (char*)0);
  14422. + }
  14423. + }
  14424. + sqliteFree(db);
  14425. + sqliteStrRealloc(pzErrMsg);
  14426. + return 0;
  14427. + }
  14428. + db->aDb[0].zName = "main";
  14429. + db->aDb[1].zName = "temp";
  14430. +
  14431. + /* Attempt to read the schema */
  14432. + sqliteRegisterBuiltinFunctions(db);
  14433. + rc = sqliteInit(db, pzErrMsg);
  14434. + db->magic = SQLITE_MAGIC_OPEN;
  14435. + if( sqlite_malloc_failed ){
  14436. + sqlite_close(db);
  14437. + goto no_mem_on_open;
  14438. + }else if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  14439. + sqlite_close(db);
  14440. + sqliteStrRealloc(pzErrMsg);
  14441. + return 0;
  14442. + }else if( pzErrMsg ){
  14443. + sqliteFree(*pzErrMsg);
  14444. + *pzErrMsg = 0;
  14445. + }
  14446. +
  14447. + /* Return a pointer to the newly opened database structure */
  14448. + return db;
  14449. +
  14450. +no_mem_on_open:
  14451. + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  14452. + sqliteStrRealloc(pzErrMsg);
  14453. + return 0;
  14454. +}
  14455. +
  14456. +/*
  14457. +** Return the ROWID of the most recent insert
  14458. +*/
  14459. +int sqlite_last_insert_rowid(sqlite *db){
  14460. + return db->lastRowid;
  14461. +}
  14462. +
  14463. +/*
  14464. +** Return the number of changes in the most recent call to sqlite_exec().
  14465. +*/
  14466. +int sqlite_changes(sqlite *db){
  14467. + return db->nChange;
  14468. +}
  14469. +
  14470. +/*
  14471. +** Return the number of changes produced by the last INSERT, UPDATE, or
  14472. +** DELETE statement to complete execution. The count does not include
  14473. +** changes due to SQL statements executed in trigger programs that were
  14474. +** triggered by that statement
  14475. +*/
  14476. +int sqlite_last_statement_changes(sqlite *db){
  14477. + return db->lsChange;
  14478. +}
  14479. +
  14480. +/*
  14481. +** Close an existing SQLite database
  14482. +*/
  14483. +void sqlite_close(sqlite *db){
  14484. + HashElem *i;
  14485. + int j;
  14486. + db->want_to_close = 1;
  14487. + if( sqliteSafetyCheck(db) || sqliteSafetyOn(db) ){
  14488. + /* printf("DID NOT CLOSE\n"); fflush(stdout); */
  14489. + return;
  14490. + }
  14491. + db->magic = SQLITE_MAGIC_CLOSED;
  14492. + for(j=0; j<db->nDb; j++){
  14493. + struct Db *pDb = &db->aDb[j];
  14494. + if( pDb->pBt ){
  14495. + sqliteBtreeClose(pDb->pBt);
  14496. + pDb->pBt = 0;
  14497. + }
  14498. + }
  14499. + sqliteResetInternalSchema(db, 0);
  14500. + assert( db->nDb<=2 );
  14501. + assert( db->aDb==db->aDbStatic );
  14502. + for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
  14503. + FuncDef *pFunc, *pNext;
  14504. + for(pFunc = (FuncDef*)sqliteHashData(i); pFunc; pFunc=pNext){
  14505. + pNext = pFunc->pNext;
  14506. + sqliteFree(pFunc);
  14507. + }
  14508. + }
  14509. + sqliteHashClear(&db->aFunc);
  14510. + sqliteFree(db);
  14511. +}
  14512. +
  14513. +/*
  14514. +** Rollback all database files.
  14515. +*/
  14516. +void sqliteRollbackAll(sqlite *db){
  14517. + int i;
  14518. + for(i=0; i<db->nDb; i++){
  14519. + if( db->aDb[i].pBt ){
  14520. + sqliteBtreeRollback(db->aDb[i].pBt);
  14521. + db->aDb[i].inTrans = 0;
  14522. + }
  14523. + }
  14524. + sqliteResetInternalSchema(db, 0);
  14525. + /* sqliteRollbackInternalChanges(db); */
  14526. +}
  14527. +
  14528. +/*
  14529. +** Execute SQL code. Return one of the SQLITE_ success/failure
  14530. +** codes. Also write an error message into memory obtained from
  14531. +** malloc() and make *pzErrMsg point to that message.
  14532. +**
  14533. +** If the SQL is a query, then for each row in the query result
  14534. +** the xCallback() function is called. pArg becomes the first
  14535. +** argument to xCallback(). If xCallback=NULL then no callback
  14536. +** is invoked, even for queries.
  14537. +*/
  14538. +int sqlite_exec(
  14539. + sqlite *db, /* The database on which the SQL executes */
  14540. + const char *zSql, /* The SQL to be executed */
  14541. + sqlite_callback xCallback, /* Invoke this callback routine */
  14542. + void *pArg, /* First argument to xCallback() */
  14543. + char **pzErrMsg /* Write error messages here */
  14544. +){
  14545. + int rc = SQLITE_OK;
  14546. + const char *zLeftover;
  14547. + sqlite_vm *pVm;
  14548. + int nRetry = 0;
  14549. + int nChange = 0;
  14550. + int nCallback;
  14551. +
  14552. + if( zSql==0 ) return SQLITE_OK;
  14553. + while( rc==SQLITE_OK && zSql[0] ){
  14554. + pVm = 0;
  14555. + rc = sqlite_compile(db, zSql, &zLeftover, &pVm, pzErrMsg);
  14556. + if( rc!=SQLITE_OK ){
  14557. + assert( pVm==0 || sqlite_malloc_failed );
  14558. + return rc;
  14559. + }
  14560. + if( pVm==0 ){
  14561. + /* This happens if the zSql input contained only whitespace */
  14562. + break;
  14563. + }
  14564. + db->nChange += nChange;
  14565. + nCallback = 0;
  14566. + while(1){
  14567. + int nArg;
  14568. + char **azArg, **azCol;
  14569. + rc = sqlite_step(pVm, &nArg, (const char***)&azArg,(const char***)&azCol);
  14570. + if( rc==SQLITE_ROW ){
  14571. + if( xCallback!=0 && xCallback(pArg, nArg, azArg, azCol) ){
  14572. + sqlite_finalize(pVm, 0);
  14573. + return SQLITE_ABORT;
  14574. + }
  14575. + nCallback++;
  14576. + }else{
  14577. + if( rc==SQLITE_DONE && nCallback==0
  14578. + && (db->flags & SQLITE_NullCallback)!=0 && xCallback!=0 ){
  14579. + xCallback(pArg, nArg, azArg, azCol);
  14580. + }
  14581. + rc = sqlite_finalize(pVm, pzErrMsg);
  14582. + if( rc==SQLITE_SCHEMA && nRetry<2 ){
  14583. + nRetry++;
  14584. + rc = SQLITE_OK;
  14585. + break;
  14586. + }
  14587. + if( db->pVdbe==0 ){
  14588. + nChange = db->nChange;
  14589. + }
  14590. + nRetry = 0;
  14591. + zSql = zLeftover;
  14592. + while( isspace(zSql[0]) ) zSql++;
  14593. + break;
  14594. + }
  14595. + }
  14596. + }
  14597. + return rc;
  14598. +}
  14599. +
  14600. +
  14601. +/*
  14602. +** Compile a single statement of SQL into a virtual machine. Return one
  14603. +** of the SQLITE_ success/failure codes. Also write an error message into
  14604. +** memory obtained from malloc() and make *pzErrMsg point to that message.
  14605. +*/
  14606. +int sqlite_compile(
  14607. + sqlite *db, /* The database on which the SQL executes */
  14608. + const char *zSql, /* The SQL to be executed */
  14609. + const char **pzTail, /* OUT: Next statement after the first */
  14610. + sqlite_vm **ppVm, /* OUT: The virtual machine */
  14611. + char **pzErrMsg /* OUT: Write error messages here */
  14612. +){
  14613. + Parse sParse;
  14614. +
  14615. + if( pzErrMsg ) *pzErrMsg = 0;
  14616. + if( sqliteSafetyOn(db) ) goto exec_misuse;
  14617. + if( !db->init.busy ){
  14618. + if( (db->flags & SQLITE_Initialized)==0 ){
  14619. + int rc, cnt = 1;
  14620. + while( (rc = sqliteInit(db, pzErrMsg))==SQLITE_BUSY
  14621. + && db->xBusyCallback
  14622. + && db->xBusyCallback(db->pBusyArg, "", cnt++)!=0 ){}
  14623. + if( rc!=SQLITE_OK ){
  14624. + sqliteStrRealloc(pzErrMsg);
  14625. + sqliteSafetyOff(db);
  14626. + return rc;
  14627. + }
  14628. + if( pzErrMsg ){
  14629. + sqliteFree(*pzErrMsg);
  14630. + *pzErrMsg = 0;
  14631. + }
  14632. + }
  14633. + if( db->file_format<3 ){
  14634. + sqliteSafetyOff(db);
  14635. + sqliteSetString(pzErrMsg, "obsolete database file format", (char*)0);
  14636. + return SQLITE_ERROR;
  14637. + }
  14638. + }
  14639. + assert( (db->flags & SQLITE_Initialized)!=0 || db->init.busy );
  14640. + if( db->pVdbe==0 ){ db->nChange = 0; }
  14641. + memset(&sParse, 0, sizeof(sParse));
  14642. + sParse.db = db;
  14643. + sqliteRunParser(&sParse, zSql, pzErrMsg);
  14644. + if( db->xTrace && !db->init.busy ){
  14645. + /* Trace only the statment that was compiled.
  14646. + ** Make a copy of that part of the SQL string since zSQL is const
  14647. + ** and we must pass a zero terminated string to the trace function
  14648. + ** The copy is unnecessary if the tail pointer is pointing at the
  14649. + ** beginnig or end of the SQL string.
  14650. + */
  14651. + if( sParse.zTail && sParse.zTail!=zSql && *sParse.zTail ){
  14652. + char *tmpSql = sqliteStrNDup(zSql, sParse.zTail - zSql);
  14653. + if( tmpSql ){
  14654. + db->xTrace(db->pTraceArg, tmpSql);
  14655. + free(tmpSql);
  14656. + }else{
  14657. + /* If a memory error occurred during the copy,
  14658. + ** trace entire SQL string and fall through to the
  14659. + ** sqlite_malloc_failed test to report the error.
  14660. + */
  14661. + db->xTrace(db->pTraceArg, zSql);
  14662. + }
  14663. + }else{
  14664. + db->xTrace(db->pTraceArg, zSql);
  14665. + }
  14666. + }
  14667. + if( sqlite_malloc_failed ){
  14668. + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  14669. + sParse.rc = SQLITE_NOMEM;
  14670. + sqliteRollbackAll(db);
  14671. + sqliteResetInternalSchema(db, 0);
  14672. + db->flags &= ~SQLITE_InTrans;
  14673. + }
  14674. + if( sParse.rc==SQLITE_DONE ) sParse.rc = SQLITE_OK;
  14675. + if( sParse.rc!=SQLITE_OK && pzErrMsg && *pzErrMsg==0 ){
  14676. + sqliteSetString(pzErrMsg, sqlite_error_string(sParse.rc), (char*)0);
  14677. + }
  14678. + sqliteStrRealloc(pzErrMsg);
  14679. + if( sParse.rc==SQLITE_SCHEMA ){
  14680. + sqliteResetInternalSchema(db, 0);
  14681. + }
  14682. + assert( ppVm );
  14683. + *ppVm = (sqlite_vm*)sParse.pVdbe;
  14684. + if( pzTail ) *pzTail = sParse.zTail;
  14685. + if( sqliteSafetyOff(db) ) goto exec_misuse;
  14686. + return sParse.rc;
  14687. +
  14688. +exec_misuse:
  14689. + if( pzErrMsg ){
  14690. + *pzErrMsg = 0;
  14691. + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
  14692. + sqliteStrRealloc(pzErrMsg);
  14693. + }
  14694. + return SQLITE_MISUSE;
  14695. +}
  14696. +
  14697. +
  14698. +/*
  14699. +** The following routine destroys a virtual machine that is created by
  14700. +** the sqlite_compile() routine.
  14701. +**
  14702. +** The integer returned is an SQLITE_ success/failure code that describes
  14703. +** the result of executing the virtual machine. An error message is
  14704. +** written into memory obtained from malloc and *pzErrMsg is made to
  14705. +** point to that error if pzErrMsg is not NULL. The calling routine
  14706. +** should use sqlite_freemem() to delete the message when it has finished
  14707. +** with it.
  14708. +*/
  14709. +int sqlite_finalize(
  14710. + sqlite_vm *pVm, /* The virtual machine to be destroyed */
  14711. + char **pzErrMsg /* OUT: Write error messages here */
  14712. +){
  14713. + int rc = sqliteVdbeFinalize((Vdbe*)pVm, pzErrMsg);
  14714. + sqliteStrRealloc(pzErrMsg);
  14715. + return rc;
  14716. +}
  14717. +
  14718. +/*
  14719. +** Terminate the current execution of a virtual machine then
  14720. +** reset the virtual machine back to its starting state so that it
  14721. +** can be reused. Any error message resulting from the prior execution
  14722. +** is written into *pzErrMsg. A success code from the prior execution
  14723. +** is returned.
  14724. +*/
  14725. +int sqlite_reset(
  14726. + sqlite_vm *pVm, /* The virtual machine to be destroyed */
  14727. + char **pzErrMsg /* OUT: Write error messages here */
  14728. +){
  14729. + int rc = sqliteVdbeReset((Vdbe*)pVm, pzErrMsg);
  14730. + sqliteVdbeMakeReady((Vdbe*)pVm, -1, 0);
  14731. + sqliteStrRealloc(pzErrMsg);
  14732. + return rc;
  14733. +}
  14734. +
  14735. +/*
  14736. +** Return a static string that describes the kind of error specified in the
  14737. +** argument.
  14738. +*/
  14739. +const char *sqlite_error_string(int rc){
  14740. + const char *z;
  14741. + switch( rc ){
  14742. + case SQLITE_OK: z = "not an error"; break;
  14743. + case SQLITE_ERROR: z = "SQL logic error or missing database"; break;
  14744. + case SQLITE_INTERNAL: z = "internal SQLite implementation flaw"; break;
  14745. + case SQLITE_PERM: z = "access permission denied"; break;
  14746. + case SQLITE_ABORT: z = "callback requested query abort"; break;
  14747. + case SQLITE_BUSY: z = "database is locked"; break;
  14748. + case SQLITE_LOCKED: z = "database table is locked"; break;
  14749. + case SQLITE_NOMEM: z = "out of memory"; break;
  14750. + case SQLITE_READONLY: z = "attempt to write a readonly database"; break;
  14751. + case SQLITE_INTERRUPT: z = "interrupted"; break;
  14752. + case SQLITE_IOERR: z = "disk I/O error"; break;
  14753. + case SQLITE_CORRUPT: z = "database disk image is malformed"; break;
  14754. + case SQLITE_NOTFOUND: z = "table or record not found"; break;
  14755. + case SQLITE_FULL: z = "database is full"; break;
  14756. + case SQLITE_CANTOPEN: z = "unable to open database file"; break;
  14757. + case SQLITE_PROTOCOL: z = "database locking protocol failure"; break;
  14758. + case SQLITE_EMPTY: z = "table contains no data"; break;
  14759. + case SQLITE_SCHEMA: z = "database schema has changed"; break;
  14760. + case SQLITE_TOOBIG: z = "too much data for one table row"; break;
  14761. + case SQLITE_CONSTRAINT: z = "constraint failed"; break;
  14762. + case SQLITE_MISMATCH: z = "datatype mismatch"; break;
  14763. + case SQLITE_MISUSE: z = "library routine called out of sequence";break;
  14764. + case SQLITE_NOLFS: z = "kernel lacks large file support"; break;
  14765. + case SQLITE_AUTH: z = "authorization denied"; break;
  14766. + case SQLITE_FORMAT: z = "auxiliary database format error"; break;
  14767. + case SQLITE_RANGE: z = "bind index out of range"; break;
  14768. + case SQLITE_NOTADB: z = "file is encrypted or is not a database";break;
  14769. + default: z = "unknown error"; break;
  14770. + }
  14771. + return z;
  14772. +}
  14773. +
  14774. +/*
  14775. +** This routine implements a busy callback that sleeps and tries
  14776. +** again until a timeout value is reached. The timeout value is
  14777. +** an integer number of milliseconds passed in as the first
  14778. +** argument.
  14779. +*/
  14780. +static int sqliteDefaultBusyCallback(
  14781. + void *Timeout, /* Maximum amount of time to wait */
  14782. + const char *NotUsed, /* The name of the table that is busy */
  14783. + int count /* Number of times table has been busy */
  14784. +){
  14785. +#if SQLITE_MIN_SLEEP_MS==1
  14786. + static const char delays[] =
  14787. + { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 50, 100};
  14788. + static const short int totals[] =
  14789. + { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228, 287};
  14790. +# define NDELAY (sizeof(delays)/sizeof(delays[0]))
  14791. + int timeout = (int)(long)Timeout;
  14792. + int delay, prior;
  14793. +
  14794. + if( count <= NDELAY ){
  14795. + delay = delays[count-1];
  14796. + prior = totals[count-1];
  14797. + }else{
  14798. + delay = delays[NDELAY-1];
  14799. + prior = totals[NDELAY-1] + delay*(count-NDELAY-1);
  14800. + }
  14801. + if( prior + delay > timeout ){
  14802. + delay = timeout - prior;
  14803. + if( delay<=0 ) return 0;
  14804. + }
  14805. + sqliteOsSleep(delay);
  14806. + return 1;
  14807. +#else
  14808. + int timeout = (int)(long)Timeout;
  14809. + if( (count+1)*1000 > timeout ){
  14810. + return 0;
  14811. + }
  14812. + sqliteOsSleep(1000);
  14813. + return 1;
  14814. +#endif
  14815. +}
  14816. +
  14817. +/*
  14818. +** This routine sets the busy callback for an Sqlite database to the
  14819. +** given callback function with the given argument.
  14820. +*/
  14821. +void sqlite_busy_handler(
  14822. + sqlite *db,
  14823. + int (*xBusy)(void*,const char*,int),
  14824. + void *pArg
  14825. +){
  14826. + db->xBusyCallback = xBusy;
  14827. + db->pBusyArg = pArg;
  14828. +}
  14829. +
  14830. +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  14831. +/*
  14832. +** This routine sets the progress callback for an Sqlite database to the
  14833. +** given callback function with the given argument. The progress callback will
  14834. +** be invoked every nOps opcodes.
  14835. +*/
  14836. +void sqlite_progress_handler(
  14837. + sqlite *db,
  14838. + int nOps,
  14839. + int (*xProgress)(void*),
  14840. + void *pArg
  14841. +){
  14842. + if( nOps>0 ){
  14843. + db->xProgress = xProgress;
  14844. + db->nProgressOps = nOps;
  14845. + db->pProgressArg = pArg;
  14846. + }else{
  14847. + db->xProgress = 0;
  14848. + db->nProgressOps = 0;
  14849. + db->pProgressArg = 0;
  14850. + }
  14851. +}
  14852. +#endif
  14853. +
  14854. +
  14855. +/*
  14856. +** This routine installs a default busy handler that waits for the
  14857. +** specified number of milliseconds before returning 0.
  14858. +*/
  14859. +void sqlite_busy_timeout(sqlite *db, int ms){
  14860. + if( ms>0 ){
  14861. + sqlite_busy_handler(db, sqliteDefaultBusyCallback, (void*)(long)ms);
  14862. + }else{
  14863. + sqlite_busy_handler(db, 0, 0);
  14864. + }
  14865. +}
  14866. +
  14867. +/*
  14868. +** Cause any pending operation to stop at its earliest opportunity.
  14869. +*/
  14870. +void sqlite_interrupt(sqlite *db){
  14871. + db->flags |= SQLITE_Interrupt;
  14872. +}
  14873. +
  14874. +/*
  14875. +** Windows systems should call this routine to free memory that
  14876. +** is returned in the in the errmsg parameter of sqlite_open() when
  14877. +** SQLite is a DLL. For some reason, it does not work to call free()
  14878. +** directly.
  14879. +**
  14880. +** Note that we need to call free() not sqliteFree() here, since every
  14881. +** string that is exported from SQLite should have already passed through
  14882. +** sqliteStrRealloc().
  14883. +*/
  14884. +void sqlite_freemem(void *p){ free(p); }
  14885. +
  14886. +/*
  14887. +** Windows systems need functions to call to return the sqlite_version
  14888. +** and sqlite_encoding strings since they are unable to access constants
  14889. +** within DLLs.
  14890. +*/
  14891. +const char *sqlite_libversion(void){ return sqlite_version; }
  14892. +const char *sqlite_libencoding(void){ return sqlite_encoding; }
  14893. +
  14894. +/*
  14895. +** Create new user-defined functions. The sqlite_create_function()
  14896. +** routine creates a regular function and sqlite_create_aggregate()
  14897. +** creates an aggregate function.
  14898. +**
  14899. +** Passing a NULL xFunc argument or NULL xStep and xFinalize arguments
  14900. +** disables the function. Calling sqlite_create_function() with the
  14901. +** same name and number of arguments as a prior call to
  14902. +** sqlite_create_aggregate() disables the prior call to
  14903. +** sqlite_create_aggregate(), and vice versa.
  14904. +**
  14905. +** If nArg is -1 it means that this function will accept any number
  14906. +** of arguments, including 0. The maximum allowed value of nArg is 127.
  14907. +*/
  14908. +int sqlite_create_function(
  14909. + sqlite *db, /* Add the function to this database connection */
  14910. + const char *zName, /* Name of the function to add */
  14911. + int nArg, /* Number of arguments */
  14912. + void (*xFunc)(sqlite_func*,int,const char**), /* The implementation */
  14913. + void *pUserData /* User data */
  14914. +){
  14915. + FuncDef *p;
  14916. + int nName;
  14917. + if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
  14918. + if( nArg<-1 || nArg>127 ) return 1;
  14919. + nName = strlen(zName);
  14920. + if( nName>255 ) return 1;
  14921. + p = sqliteFindFunction(db, zName, nName, nArg, 1);
  14922. + if( p==0 ) return 1;
  14923. + p->xFunc = xFunc;
  14924. + p->xStep = 0;
  14925. + p->xFinalize = 0;
  14926. + p->pUserData = pUserData;
  14927. + return 0;
  14928. +}
  14929. +int sqlite_create_aggregate(
  14930. + sqlite *db, /* Add the function to this database connection */
  14931. + const char *zName, /* Name of the function to add */
  14932. + int nArg, /* Number of arguments */
  14933. + void (*xStep)(sqlite_func*,int,const char**), /* The step function */
  14934. + void (*xFinalize)(sqlite_func*), /* The finalizer */
  14935. + void *pUserData /* User data */
  14936. +){
  14937. + FuncDef *p;
  14938. + int nName;
  14939. + if( db==0 || zName==0 || sqliteSafetyCheck(db) ) return 1;
  14940. + if( nArg<-1 || nArg>127 ) return 1;
  14941. + nName = strlen(zName);
  14942. + if( nName>255 ) return 1;
  14943. + p = sqliteFindFunction(db, zName, nName, nArg, 1);
  14944. + if( p==0 ) return 1;
  14945. + p->xFunc = 0;
  14946. + p->xStep = xStep;
  14947. + p->xFinalize = xFinalize;
  14948. + p->pUserData = pUserData;
  14949. + return 0;
  14950. +}
  14951. +
  14952. +/*
  14953. +** Change the datatype for all functions with a given name. See the
  14954. +** header comment for the prototype of this function in sqlite.h for
  14955. +** additional information.
  14956. +*/
  14957. +int sqlite_function_type(sqlite *db, const char *zName, int dataType){
  14958. + FuncDef *p = (FuncDef*)sqliteHashFind(&db->aFunc, zName, strlen(zName));
  14959. + while( p ){
  14960. + p->dataType = dataType;
  14961. + p = p->pNext;
  14962. + }
  14963. + return SQLITE_OK;
  14964. +}
  14965. +
  14966. +/*
  14967. +** Register a trace function. The pArg from the previously registered trace
  14968. +** is returned.
  14969. +**
  14970. +** A NULL trace function means that no tracing is executes. A non-NULL
  14971. +** trace is a pointer to a function that is invoked at the start of each
  14972. +** sqlite_exec().
  14973. +*/
  14974. +void *sqlite_trace(sqlite *db, void (*xTrace)(void*,const char*), void *pArg){
  14975. + void *pOld = db->pTraceArg;
  14976. + db->xTrace = xTrace;
  14977. + db->pTraceArg = pArg;
  14978. + return pOld;
  14979. +}
  14980. +
  14981. +/*** EXPERIMENTAL ***
  14982. +**
  14983. +** Register a function to be invoked when a transaction comments.
  14984. +** If either function returns non-zero, then the commit becomes a
  14985. +** rollback.
  14986. +*/
  14987. +void *sqlite_commit_hook(
  14988. + sqlite *db, /* Attach the hook to this database */
  14989. + int (*xCallback)(void*), /* Function to invoke on each commit */
  14990. + void *pArg /* Argument to the function */
  14991. +){
  14992. + void *pOld = db->pCommitArg;
  14993. + db->xCommitCallback = xCallback;
  14994. + db->pCommitArg = pArg;
  14995. + return pOld;
  14996. +}
  14997. +
  14998. +
  14999. +/*
  15000. +** This routine is called to create a connection to a database BTree
  15001. +** driver. If zFilename is the name of a file, then that file is
  15002. +** opened and used. If zFilename is the magic name ":memory:" then
  15003. +** the database is stored in memory (and is thus forgotten as soon as
  15004. +** the connection is closed.) If zFilename is NULL then the database
  15005. +** is for temporary use only and is deleted as soon as the connection
  15006. +** is closed.
  15007. +**
  15008. +** A temporary database can be either a disk file (that is automatically
  15009. +** deleted when the file is closed) or a set of red-black trees held in memory,
  15010. +** depending on the values of the TEMP_STORE compile-time macro and the
  15011. +** db->temp_store variable, according to the following chart:
  15012. +**
  15013. +** TEMP_STORE db->temp_store Location of temporary database
  15014. +** ---------- -------------- ------------------------------
  15015. +** 0 any file
  15016. +** 1 1 file
  15017. +** 1 2 memory
  15018. +** 1 0 file
  15019. +** 2 1 file
  15020. +** 2 2 memory
  15021. +** 2 0 memory
  15022. +** 3 any memory
  15023. +*/
  15024. +int sqliteBtreeFactory(
  15025. + const sqlite *db, /* Main database when opening aux otherwise 0 */
  15026. + const char *zFilename, /* Name of the file containing the BTree database */
  15027. + int omitJournal, /* if TRUE then do not journal this file */
  15028. + int nCache, /* How many pages in the page cache */
  15029. + Btree **ppBtree){ /* Pointer to new Btree object written here */
  15030. +
  15031. + assert( ppBtree != 0);
  15032. +
  15033. +#ifndef SQLITE_OMIT_INMEMORYDB
  15034. + if( zFilename==0 ){
  15035. + if (TEMP_STORE == 0) {
  15036. + /* Always use file based temporary DB */
  15037. + return sqliteBtreeOpen(0, omitJournal, nCache, ppBtree);
  15038. + } else if (TEMP_STORE == 1 || TEMP_STORE == 2) {
  15039. + /* Switch depending on compile-time and/or runtime settings. */
  15040. + int location = db->temp_store==0 ? TEMP_STORE : db->temp_store;
  15041. +
  15042. + if (location == 1) {
  15043. + return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
  15044. + } else {
  15045. + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  15046. + }
  15047. + } else {
  15048. + /* Always use in-core DB */
  15049. + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  15050. + }
  15051. + }else if( zFilename[0]==':' && strcmp(zFilename,":memory:")==0 ){
  15052. + return sqliteRbtreeOpen(0, 0, 0, ppBtree);
  15053. + }else
  15054. +#endif
  15055. + {
  15056. + return sqliteBtreeOpen(zFilename, omitJournal, nCache, ppBtree);
  15057. + }
  15058. +}
  15059. --- /dev/null
  15060. +++ b/ext/sqlite/libsqlite/src/opcodes.c
  15061. @@ -0,0 +1,140 @@
  15062. +/* Automatically generated file. Do not edit */
  15063. +char *sqliteOpcodeNames[] = { "???",
  15064. + "Goto",
  15065. + "Gosub",
  15066. + "Return",
  15067. + "Halt",
  15068. + "Integer",
  15069. + "String",
  15070. + "Variable",
  15071. + "Pop",
  15072. + "Dup",
  15073. + "Pull",
  15074. + "Push",
  15075. + "ColumnName",
  15076. + "Callback",
  15077. + "Concat",
  15078. + "Add",
  15079. + "Subtract",
  15080. + "Multiply",
  15081. + "Divide",
  15082. + "Remainder",
  15083. + "Function",
  15084. + "BitAnd",
  15085. + "BitOr",
  15086. + "ShiftLeft",
  15087. + "ShiftRight",
  15088. + "AddImm",
  15089. + "ForceInt",
  15090. + "MustBeInt",
  15091. + "Eq",
  15092. + "Ne",
  15093. + "Lt",
  15094. + "Le",
  15095. + "Gt",
  15096. + "Ge",
  15097. + "StrEq",
  15098. + "StrNe",
  15099. + "StrLt",
  15100. + "StrLe",
  15101. + "StrGt",
  15102. + "StrGe",
  15103. + "And",
  15104. + "Or",
  15105. + "Negative",
  15106. + "AbsValue",
  15107. + "Not",
  15108. + "BitNot",
  15109. + "Noop",
  15110. + "If",
  15111. + "IfNot",
  15112. + "IsNull",
  15113. + "NotNull",
  15114. + "MakeRecord",
  15115. + "MakeIdxKey",
  15116. + "MakeKey",
  15117. + "IncrKey",
  15118. + "Checkpoint",
  15119. + "Transaction",
  15120. + "Commit",
  15121. + "Rollback",
  15122. + "ReadCookie",
  15123. + "SetCookie",
  15124. + "VerifyCookie",
  15125. + "OpenRead",
  15126. + "OpenWrite",
  15127. + "OpenTemp",
  15128. + "OpenPseudo",
  15129. + "Close",
  15130. + "MoveLt",
  15131. + "MoveTo",
  15132. + "Distinct",
  15133. + "NotFound",
  15134. + "Found",
  15135. + "IsUnique",
  15136. + "NotExists",
  15137. + "NewRecno",
  15138. + "PutIntKey",
  15139. + "PutStrKey",
  15140. + "Delete",
  15141. + "SetCounts",
  15142. + "KeyAsData",
  15143. + "RowKey",
  15144. + "RowData",
  15145. + "Column",
  15146. + "Recno",
  15147. + "FullKey",
  15148. + "NullRow",
  15149. + "Last",
  15150. + "Rewind",
  15151. + "Prev",
  15152. + "Next",
  15153. + "IdxPut",
  15154. + "IdxDelete",
  15155. + "IdxRecno",
  15156. + "IdxLT",
  15157. + "IdxGT",
  15158. + "IdxGE",
  15159. + "IdxIsNull",
  15160. + "Destroy",
  15161. + "Clear",
  15162. + "CreateIndex",
  15163. + "CreateTable",
  15164. + "IntegrityCk",
  15165. + "ListWrite",
  15166. + "ListRewind",
  15167. + "ListRead",
  15168. + "ListReset",
  15169. + "ListPush",
  15170. + "ListPop",
  15171. + "ContextPush",
  15172. + "ContextPop",
  15173. + "SortPut",
  15174. + "SortMakeRec",
  15175. + "SortMakeKey",
  15176. + "Sort",
  15177. + "SortNext",
  15178. + "SortCallback",
  15179. + "SortReset",
  15180. + "FileOpen",
  15181. + "FileRead",
  15182. + "FileColumn",
  15183. + "MemStore",
  15184. + "MemLoad",
  15185. + "MemIncr",
  15186. + "AggReset",
  15187. + "AggInit",
  15188. + "AggFunc",
  15189. + "AggFocus",
  15190. + "AggSet",
  15191. + "AggGet",
  15192. + "AggNext",
  15193. + "SetInsert",
  15194. + "SetFound",
  15195. + "SetNotFound",
  15196. + "SetFirst",
  15197. + "SetNext",
  15198. + "Vacuum",
  15199. + "StackDepth",
  15200. + "StackReset",
  15201. +};
  15202. --- /dev/null
  15203. +++ b/ext/sqlite/libsqlite/src/opcodes.h
  15204. @@ -0,0 +1,138 @@
  15205. +/* Automatically generated file. Do not edit */
  15206. +#define OP_Goto 1
  15207. +#define OP_Gosub 2
  15208. +#define OP_Return 3
  15209. +#define OP_Halt 4
  15210. +#define OP_Integer 5
  15211. +#define OP_String 6
  15212. +#define OP_Variable 7
  15213. +#define OP_Pop 8
  15214. +#define OP_Dup 9
  15215. +#define OP_Pull 10
  15216. +#define OP_Push 11
  15217. +#define OP_ColumnName 12
  15218. +#define OP_Callback 13
  15219. +#define OP_Concat 14
  15220. +#define OP_Add 15
  15221. +#define OP_Subtract 16
  15222. +#define OP_Multiply 17
  15223. +#define OP_Divide 18
  15224. +#define OP_Remainder 19
  15225. +#define OP_Function 20
  15226. +#define OP_BitAnd 21
  15227. +#define OP_BitOr 22
  15228. +#define OP_ShiftLeft 23
  15229. +#define OP_ShiftRight 24
  15230. +#define OP_AddImm 25
  15231. +#define OP_ForceInt 26
  15232. +#define OP_MustBeInt 27
  15233. +#define OP_Eq 28
  15234. +#define OP_Ne 29
  15235. +#define OP_Lt 30
  15236. +#define OP_Le 31
  15237. +#define OP_Gt 32
  15238. +#define OP_Ge 33
  15239. +#define OP_StrEq 34
  15240. +#define OP_StrNe 35
  15241. +#define OP_StrLt 36
  15242. +#define OP_StrLe 37
  15243. +#define OP_StrGt 38
  15244. +#define OP_StrGe 39
  15245. +#define OP_And 40
  15246. +#define OP_Or 41
  15247. +#define OP_Negative 42
  15248. +#define OP_AbsValue 43
  15249. +#define OP_Not 44
  15250. +#define OP_BitNot 45
  15251. +#define OP_Noop 46
  15252. +#define OP_If 47
  15253. +#define OP_IfNot 48
  15254. +#define OP_IsNull 49
  15255. +#define OP_NotNull 50
  15256. +#define OP_MakeRecord 51
  15257. +#define OP_MakeIdxKey 52
  15258. +#define OP_MakeKey 53
  15259. +#define OP_IncrKey 54
  15260. +#define OP_Checkpoint 55
  15261. +#define OP_Transaction 56
  15262. +#define OP_Commit 57
  15263. +#define OP_Rollback 58
  15264. +#define OP_ReadCookie 59
  15265. +#define OP_SetCookie 60
  15266. +#define OP_VerifyCookie 61
  15267. +#define OP_OpenRead 62
  15268. +#define OP_OpenWrite 63
  15269. +#define OP_OpenTemp 64
  15270. +#define OP_OpenPseudo 65
  15271. +#define OP_Close 66
  15272. +#define OP_MoveLt 67
  15273. +#define OP_MoveTo 68
  15274. +#define OP_Distinct 69
  15275. +#define OP_NotFound 70
  15276. +#define OP_Found 71
  15277. +#define OP_IsUnique 72
  15278. +#define OP_NotExists 73
  15279. +#define OP_NewRecno 74
  15280. +#define OP_PutIntKey 75
  15281. +#define OP_PutStrKey 76
  15282. +#define OP_Delete 77
  15283. +#define OP_SetCounts 78
  15284. +#define OP_KeyAsData 79
  15285. +#define OP_RowKey 80
  15286. +#define OP_RowData 81
  15287. +#define OP_Column 82
  15288. +#define OP_Recno 83
  15289. +#define OP_FullKey 84
  15290. +#define OP_NullRow 85
  15291. +#define OP_Last 86
  15292. +#define OP_Rewind 87
  15293. +#define OP_Prev 88
  15294. +#define OP_Next 89
  15295. +#define OP_IdxPut 90
  15296. +#define OP_IdxDelete 91
  15297. +#define OP_IdxRecno 92
  15298. +#define OP_IdxLT 93
  15299. +#define OP_IdxGT 94
  15300. +#define OP_IdxGE 95
  15301. +#define OP_IdxIsNull 96
  15302. +#define OP_Destroy 97
  15303. +#define OP_Clear 98
  15304. +#define OP_CreateIndex 99
  15305. +#define OP_CreateTable 100
  15306. +#define OP_IntegrityCk 101
  15307. +#define OP_ListWrite 102
  15308. +#define OP_ListRewind 103
  15309. +#define OP_ListRead 104
  15310. +#define OP_ListReset 105
  15311. +#define OP_ListPush 106
  15312. +#define OP_ListPop 107
  15313. +#define OP_ContextPush 108
  15314. +#define OP_ContextPop 109
  15315. +#define OP_SortPut 110
  15316. +#define OP_SortMakeRec 111
  15317. +#define OP_SortMakeKey 112
  15318. +#define OP_Sort 113
  15319. +#define OP_SortNext 114
  15320. +#define OP_SortCallback 115
  15321. +#define OP_SortReset 116
  15322. +#define OP_FileOpen 117
  15323. +#define OP_FileRead 118
  15324. +#define OP_FileColumn 119
  15325. +#define OP_MemStore 120
  15326. +#define OP_MemLoad 121
  15327. +#define OP_MemIncr 122
  15328. +#define OP_AggReset 123
  15329. +#define OP_AggInit 124
  15330. +#define OP_AggFunc 125
  15331. +#define OP_AggFocus 126
  15332. +#define OP_AggSet 127
  15333. +#define OP_AggGet 128
  15334. +#define OP_AggNext 129
  15335. +#define OP_SetInsert 130
  15336. +#define OP_SetFound 131
  15337. +#define OP_SetNotFound 132
  15338. +#define OP_SetFirst 133
  15339. +#define OP_SetNext 134
  15340. +#define OP_Vacuum 135
  15341. +#define OP_StackDepth 136
  15342. +#define OP_StackReset 137
  15343. --- /dev/null
  15344. +++ b/ext/sqlite/libsqlite/src/os.c
  15345. @@ -0,0 +1,1850 @@
  15346. +/*
  15347. +** 2001 September 16
  15348. +**
  15349. +** The author disclaims copyright to this source code. In place of
  15350. +** a legal notice, here is a blessing:
  15351. +**
  15352. +** May you do good and not evil.
  15353. +** May you find forgiveness for yourself and forgive others.
  15354. +** May you share freely, never taking more than you give.
  15355. +**
  15356. +******************************************************************************
  15357. +**
  15358. +** This file contains code that is specific to particular operating
  15359. +** systems. The purpose of this file is to provide a uniform abstraction
  15360. +** on which the rest of SQLite can operate.
  15361. +*/
  15362. +#include "os.h" /* Must be first to enable large file support */
  15363. +#include "sqliteInt.h"
  15364. +
  15365. +#if OS_UNIX
  15366. +# include <time.h>
  15367. +# include <errno.h>
  15368. +# include <unistd.h>
  15369. +# ifndef O_LARGEFILE
  15370. +# define O_LARGEFILE 0
  15371. +# endif
  15372. +# ifdef SQLITE_DISABLE_LFS
  15373. +# undef O_LARGEFILE
  15374. +# define O_LARGEFILE 0
  15375. +# endif
  15376. +# ifndef O_NOFOLLOW
  15377. +# define O_NOFOLLOW 0
  15378. +# endif
  15379. +# ifndef O_BINARY
  15380. +# define O_BINARY 0
  15381. +# endif
  15382. +#endif
  15383. +
  15384. +
  15385. +#if OS_WIN
  15386. +# include <winbase.h>
  15387. +#endif
  15388. +
  15389. +#if OS_MAC
  15390. +# include <extras.h>
  15391. +# include <path2fss.h>
  15392. +# include <TextUtils.h>
  15393. +# include <FinderRegistry.h>
  15394. +# include <Folders.h>
  15395. +# include <Timer.h>
  15396. +# include <OSUtils.h>
  15397. +#endif
  15398. +
  15399. +/*
  15400. +** The DJGPP compiler environment looks mostly like Unix, but it
  15401. +** lacks the fcntl() system call. So redefine fcntl() to be something
  15402. +** that always succeeds. This means that locking does not occur under
  15403. +** DJGPP. But its DOS - what did you expect?
  15404. +*/
  15405. +#ifdef __DJGPP__
  15406. +# define fcntl(A,B,C) 0
  15407. +#endif
  15408. +
  15409. +/*
  15410. +** Macros used to determine whether or not to use threads. The
  15411. +** SQLITE_UNIX_THREADS macro is defined if we are synchronizing for
  15412. +** Posix threads and SQLITE_W32_THREADS is defined if we are
  15413. +** synchronizing using Win32 threads.
  15414. +*/
  15415. +#if OS_UNIX && defined(THREADSAFE) && THREADSAFE
  15416. +# include <pthread.h>
  15417. +# define SQLITE_UNIX_THREADS 1
  15418. +#endif
  15419. +#if OS_WIN && defined(THREADSAFE) && THREADSAFE
  15420. +# define SQLITE_W32_THREADS 1
  15421. +#endif
  15422. +#if OS_MAC && defined(THREADSAFE) && THREADSAFE
  15423. +# include <Multiprocessing.h>
  15424. +# define SQLITE_MACOS_MULTITASKING 1
  15425. +#endif
  15426. +
  15427. +/*
  15428. +** Macros for performance tracing. Normally turned off
  15429. +*/
  15430. +#if 0
  15431. +static int last_page = 0;
  15432. +__inline__ unsigned long long int hwtime(void){
  15433. + unsigned long long int x;
  15434. + __asm__("rdtsc\n\t"
  15435. + "mov %%edx, %%ecx\n\t"
  15436. + :"=A" (x));
  15437. + return x;
  15438. +}
  15439. +static unsigned long long int g_start;
  15440. +static unsigned int elapse;
  15441. +#define TIMER_START g_start=hwtime()
  15442. +#define TIMER_END elapse=hwtime()-g_start
  15443. +#define SEEK(X) last_page=(X)
  15444. +#define TRACE1(X) fprintf(stderr,X)
  15445. +#define TRACE2(X,Y) fprintf(stderr,X,Y)
  15446. +#define TRACE3(X,Y,Z) fprintf(stderr,X,Y,Z)
  15447. +#define TRACE4(X,Y,Z,A) fprintf(stderr,X,Y,Z,A)
  15448. +#define TRACE5(X,Y,Z,A,B) fprintf(stderr,X,Y,Z,A,B)
  15449. +#else
  15450. +#define TIMER_START
  15451. +#define TIMER_END
  15452. +#define SEEK(X)
  15453. +#define TRACE1(X)
  15454. +#define TRACE2(X,Y)
  15455. +#define TRACE3(X,Y,Z)
  15456. +#define TRACE4(X,Y,Z,A)
  15457. +#define TRACE5(X,Y,Z,A,B)
  15458. +#endif
  15459. +
  15460. +
  15461. +#if OS_UNIX
  15462. +/*
  15463. +** Here is the dirt on POSIX advisory locks: ANSI STD 1003.1 (1996)
  15464. +** section 6.5.2.2 lines 483 through 490 specify that when a process
  15465. +** sets or clears a lock, that operation overrides any prior locks set
  15466. +** by the same process. It does not explicitly say so, but this implies
  15467. +** that it overrides locks set by the same process using a different
  15468. +** file descriptor. Consider this test case:
  15469. +**
  15470. +** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  15471. +** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  15472. +**
  15473. +** Suppose ./file1 and ./file2 are really the same file (because
  15474. +** one is a hard or symbolic link to the other) then if you set
  15475. +** an exclusive lock on fd1, then try to get an exclusive lock
  15476. +** on fd2, it works. I would have expected the second lock to
  15477. +** fail since there was already a lock on the file due to fd1.
  15478. +** But not so. Since both locks came from the same process, the
  15479. +** second overrides the first, even though they were on different
  15480. +** file descriptors opened on different file names.
  15481. +**
  15482. +** Bummer. If you ask me, this is broken. Badly broken. It means
  15483. +** that we cannot use POSIX locks to synchronize file access among
  15484. +** competing threads of the same process. POSIX locks will work fine
  15485. +** to synchronize access for threads in separate processes, but not
  15486. +** threads within the same process.
  15487. +**
  15488. +** To work around the problem, SQLite has to manage file locks internally
  15489. +** on its own. Whenever a new database is opened, we have to find the
  15490. +** specific inode of the database file (the inode is determined by the
  15491. +** st_dev and st_ino fields of the stat structure that fstat() fills in)
  15492. +** and check for locks already existing on that inode. When locks are
  15493. +** created or removed, we have to look at our own internal record of the
  15494. +** locks to see if another thread has previously set a lock on that same
  15495. +** inode.
  15496. +**
  15497. +** The OsFile structure for POSIX is no longer just an integer file
  15498. +** descriptor. It is now a structure that holds the integer file
  15499. +** descriptor and a pointer to a structure that describes the internal
  15500. +** locks on the corresponding inode. There is one locking structure
  15501. +** per inode, so if the same inode is opened twice, both OsFile structures
  15502. +** point to the same locking structure. The locking structure keeps
  15503. +** a reference count (so we will know when to delete it) and a "cnt"
  15504. +** field that tells us its internal lock status. cnt==0 means the
  15505. +** file is unlocked. cnt==-1 means the file has an exclusive lock.
  15506. +** cnt>0 means there are cnt shared locks on the file.
  15507. +**
  15508. +** Any attempt to lock or unlock a file first checks the locking
  15509. +** structure. The fcntl() system call is only invoked to set a
  15510. +** POSIX lock if the internal lock structure transitions between
  15511. +** a locked and an unlocked state.
  15512. +**
  15513. +** 2004-Jan-11:
  15514. +** More recent discoveries about POSIX advisory locks. (The more
  15515. +** I discover, the more I realize the a POSIX advisory locks are
  15516. +** an abomination.)
  15517. +**
  15518. +** If you close a file descriptor that points to a file that has locks,
  15519. +** all locks on that file that are owned by the current process are
  15520. +** released. To work around this problem, each OsFile structure contains
  15521. +** a pointer to an openCnt structure. There is one openCnt structure
  15522. +** per open inode, which means that multiple OsFiles can point to a single
  15523. +** openCnt. When an attempt is made to close an OsFile, if there are
  15524. +** other OsFiles open on the same inode that are holding locks, the call
  15525. +** to close() the file descriptor is deferred until all of the locks clear.
  15526. +** The openCnt structure keeps a list of file descriptors that need to
  15527. +** be closed and that list is walked (and cleared) when the last lock
  15528. +** clears.
  15529. +**
  15530. +** First, under Linux threads, because each thread has a separate
  15531. +** process ID, lock operations in one thread do not override locks
  15532. +** to the same file in other threads. Linux threads behave like
  15533. +** separate processes in this respect. But, if you close a file
  15534. +** descriptor in linux threads, all locks are cleared, even locks
  15535. +** on other threads and even though the other threads have different
  15536. +** process IDs. Linux threads is inconsistent in this respect.
  15537. +** (I'm beginning to think that linux threads is an abomination too.)
  15538. +** The consequence of this all is that the hash table for the lockInfo
  15539. +** structure has to include the process id as part of its key because
  15540. +** locks in different threads are treated as distinct. But the
  15541. +** openCnt structure should not include the process id in its
  15542. +** key because close() clears lock on all threads, not just the current
  15543. +** thread. Were it not for this goofiness in linux threads, we could
  15544. +** combine the lockInfo and openCnt structures into a single structure.
  15545. +*/
  15546. +
  15547. +/*
  15548. +** An instance of the following structure serves as the key used
  15549. +** to locate a particular lockInfo structure given its inode. Note
  15550. +** that we have to include the process ID as part of the key. On some
  15551. +** threading implementations (ex: linux), each thread has a separate
  15552. +** process ID.
  15553. +*/
  15554. +struct lockKey {
  15555. + dev_t dev; /* Device number */
  15556. + ino_t ino; /* Inode number */
  15557. + pid_t pid; /* Process ID */
  15558. +};
  15559. +
  15560. +/*
  15561. +** An instance of the following structure is allocated for each open
  15562. +** inode on each thread with a different process ID. (Threads have
  15563. +** different process IDs on linux, but not on most other unixes.)
  15564. +**
  15565. +** A single inode can have multiple file descriptors, so each OsFile
  15566. +** structure contains a pointer to an instance of this object and this
  15567. +** object keeps a count of the number of OsFiles pointing to it.
  15568. +*/
  15569. +struct lockInfo {
  15570. + struct lockKey key; /* The lookup key */
  15571. + int cnt; /* 0: unlocked. -1: write lock. 1...: read lock. */
  15572. + int nRef; /* Number of pointers to this structure */
  15573. +};
  15574. +
  15575. +/*
  15576. +** An instance of the following structure serves as the key used
  15577. +** to locate a particular openCnt structure given its inode. This
  15578. +** is the same as the lockKey except that the process ID is omitted.
  15579. +*/
  15580. +struct openKey {
  15581. + dev_t dev; /* Device number */
  15582. + ino_t ino; /* Inode number */
  15583. +};
  15584. +
  15585. +/*
  15586. +** An instance of the following structure is allocated for each open
  15587. +** inode. This structure keeps track of the number of locks on that
  15588. +** inode. If a close is attempted against an inode that is holding
  15589. +** locks, the close is deferred until all locks clear by adding the
  15590. +** file descriptor to be closed to the pending list.
  15591. +*/
  15592. +struct openCnt {
  15593. + struct openKey key; /* The lookup key */
  15594. + int nRef; /* Number of pointers to this structure */
  15595. + int nLock; /* Number of outstanding locks */
  15596. + int nPending; /* Number of pending close() operations */
  15597. + int *aPending; /* Malloced space holding fd's awaiting a close() */
  15598. +};
  15599. +
  15600. +/*
  15601. +** These hash table maps inodes and process IDs into lockInfo and openCnt
  15602. +** structures. Access to these hash tables must be protected by a mutex.
  15603. +*/
  15604. +static Hash lockHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
  15605. +static Hash openHash = { SQLITE_HASH_BINARY, 0, 0, 0, 0, 0 };
  15606. +
  15607. +/*
  15608. +** Release a lockInfo structure previously allocated by findLockInfo().
  15609. +*/
  15610. +static void releaseLockInfo(struct lockInfo *pLock){
  15611. + pLock->nRef--;
  15612. + if( pLock->nRef==0 ){
  15613. + sqliteHashInsert(&lockHash, &pLock->key, sizeof(pLock->key), 0);
  15614. + sqliteFree(pLock);
  15615. + }
  15616. +}
  15617. +
  15618. +/*
  15619. +** Release a openCnt structure previously allocated by findLockInfo().
  15620. +*/
  15621. +static void releaseOpenCnt(struct openCnt *pOpen){
  15622. + pOpen->nRef--;
  15623. + if( pOpen->nRef==0 ){
  15624. + sqliteHashInsert(&openHash, &pOpen->key, sizeof(pOpen->key), 0);
  15625. + sqliteFree(pOpen->aPending);
  15626. + sqliteFree(pOpen);
  15627. + }
  15628. +}
  15629. +
  15630. +/*
  15631. +** Given a file descriptor, locate lockInfo and openCnt structures that
  15632. +** describes that file descriptor. Create a new ones if necessary. The
  15633. +** return values might be unset if an error occurs.
  15634. +**
  15635. +** Return the number of errors.
  15636. +*/
  15637. +int findLockInfo(
  15638. + int fd, /* The file descriptor used in the key */
  15639. + struct lockInfo **ppLock, /* Return the lockInfo structure here */
  15640. + struct openCnt **ppOpen /* Return the openCnt structure here */
  15641. +){
  15642. + int rc;
  15643. + struct lockKey key1;
  15644. + struct openKey key2;
  15645. + struct stat statbuf;
  15646. + struct lockInfo *pLock;
  15647. + struct openCnt *pOpen;
  15648. + rc = fstat(fd, &statbuf);
  15649. + if( rc!=0 ) return 1;
  15650. + memset(&key1, 0, sizeof(key1));
  15651. + key1.dev = statbuf.st_dev;
  15652. + key1.ino = statbuf.st_ino;
  15653. + key1.pid = getpid();
  15654. + memset(&key2, 0, sizeof(key2));
  15655. + key2.dev = statbuf.st_dev;
  15656. + key2.ino = statbuf.st_ino;
  15657. + pLock = (struct lockInfo*)sqliteHashFind(&lockHash, &key1, sizeof(key1));
  15658. + if( pLock==0 ){
  15659. + struct lockInfo *pOld;
  15660. + pLock = sqliteMallocRaw( sizeof(*pLock) );
  15661. + if( pLock==0 ) return 1;
  15662. + pLock->key = key1;
  15663. + pLock->nRef = 1;
  15664. + pLock->cnt = 0;
  15665. + pOld = sqliteHashInsert(&lockHash, &pLock->key, sizeof(key1), pLock);
  15666. + if( pOld!=0 ){
  15667. + assert( pOld==pLock );
  15668. + sqliteFree(pLock);
  15669. + return 1;
  15670. + }
  15671. + }else{
  15672. + pLock->nRef++;
  15673. + }
  15674. + *ppLock = pLock;
  15675. + pOpen = (struct openCnt*)sqliteHashFind(&openHash, &key2, sizeof(key2));
  15676. + if( pOpen==0 ){
  15677. + struct openCnt *pOld;
  15678. + pOpen = sqliteMallocRaw( sizeof(*pOpen) );
  15679. + if( pOpen==0 ){
  15680. + releaseLockInfo(pLock);
  15681. + return 1;
  15682. + }
  15683. + pOpen->key = key2;
  15684. + pOpen->nRef = 1;
  15685. + pOpen->nLock = 0;
  15686. + pOpen->nPending = 0;
  15687. + pOpen->aPending = 0;
  15688. + pOld = sqliteHashInsert(&openHash, &pOpen->key, sizeof(key2), pOpen);
  15689. + if( pOld!=0 ){
  15690. + assert( pOld==pOpen );
  15691. + sqliteFree(pOpen);
  15692. + releaseLockInfo(pLock);
  15693. + return 1;
  15694. + }
  15695. + }else{
  15696. + pOpen->nRef++;
  15697. + }
  15698. + *ppOpen = pOpen;
  15699. + return 0;
  15700. +}
  15701. +
  15702. +#endif /** POSIX advisory lock work-around **/
  15703. +
  15704. +/*
  15705. +** If we compile with the SQLITE_TEST macro set, then the following block
  15706. +** of code will give us the ability to simulate a disk I/O error. This
  15707. +** is used for testing the I/O recovery logic.
  15708. +*/
  15709. +#ifdef SQLITE_TEST
  15710. +int sqlite_io_error_pending = 0;
  15711. +#define SimulateIOError(A) \
  15712. + if( sqlite_io_error_pending ) \
  15713. + if( sqlite_io_error_pending-- == 1 ){ local_ioerr(); return A; }
  15714. +static void local_ioerr(){
  15715. + sqlite_io_error_pending = 0; /* Really just a place to set a breakpoint */
  15716. +}
  15717. +#else
  15718. +#define SimulateIOError(A)
  15719. +#endif
  15720. +
  15721. +/*
  15722. +** When testing, keep a count of the number of open files.
  15723. +*/
  15724. +#ifdef SQLITE_TEST
  15725. +int sqlite_open_file_count = 0;
  15726. +#define OpenCounter(X) sqlite_open_file_count+=(X)
  15727. +#else
  15728. +#define OpenCounter(X)
  15729. +#endif
  15730. +
  15731. +
  15732. +/*
  15733. +** Delete the named file
  15734. +*/
  15735. +int sqliteOsDelete(const char *zFilename){
  15736. +#if OS_UNIX
  15737. + unlink(zFilename);
  15738. +#endif
  15739. +#if OS_WIN
  15740. + DeleteFile(zFilename);
  15741. +#endif
  15742. +#if OS_MAC
  15743. + unlink(zFilename);
  15744. +#endif
  15745. + return SQLITE_OK;
  15746. +}
  15747. +
  15748. +/*
  15749. +** Return TRUE if the named file exists.
  15750. +*/
  15751. +int sqliteOsFileExists(const char *zFilename){
  15752. +#if OS_UNIX
  15753. + return access(zFilename, 0)==0;
  15754. +#endif
  15755. +#if OS_WIN
  15756. + return GetFileAttributes(zFilename) != 0xffffffff;
  15757. +#endif
  15758. +#if OS_MAC
  15759. + return access(zFilename, 0)==0;
  15760. +#endif
  15761. +}
  15762. +
  15763. +
  15764. +#if 0 /* NOT USED */
  15765. +/*
  15766. +** Change the name of an existing file.
  15767. +*/
  15768. +int sqliteOsFileRename(const char *zOldName, const char *zNewName){
  15769. +#if OS_UNIX
  15770. + if( link(zOldName, zNewName) ){
  15771. + return SQLITE_ERROR;
  15772. + }
  15773. + unlink(zOldName);
  15774. + return SQLITE_OK;
  15775. +#endif
  15776. +#if OS_WIN
  15777. + if( !MoveFile(zOldName, zNewName) ){
  15778. + return SQLITE_ERROR;
  15779. + }
  15780. + return SQLITE_OK;
  15781. +#endif
  15782. +#if OS_MAC
  15783. + /**** FIX ME ***/
  15784. + return SQLITE_ERROR;
  15785. +#endif
  15786. +}
  15787. +#endif /* NOT USED */
  15788. +
  15789. +/*
  15790. +** Attempt to open a file for both reading and writing. If that
  15791. +** fails, try opening it read-only. If the file does not exist,
  15792. +** try to create it.
  15793. +**
  15794. +** On success, a handle for the open file is written to *id
  15795. +** and *pReadonly is set to 0 if the file was opened for reading and
  15796. +** writing or 1 if the file was opened read-only. The function returns
  15797. +** SQLITE_OK.
  15798. +**
  15799. +** On failure, the function returns SQLITE_CANTOPEN and leaves
  15800. +** *id and *pReadonly unchanged.
  15801. +*/
  15802. +int sqliteOsOpenReadWrite(
  15803. + const char *zFilename,
  15804. + OsFile *id,
  15805. + int *pReadonly
  15806. +){
  15807. +#if OS_UNIX
  15808. + int rc;
  15809. + id->dirfd = -1;
  15810. + id->fd = open(zFilename, O_RDWR|O_CREAT|O_LARGEFILE|O_BINARY, 0644);
  15811. + if( id->fd<0 ){
  15812. +#ifdef EISDIR
  15813. + if( errno==EISDIR ){
  15814. + return SQLITE_CANTOPEN;
  15815. + }
  15816. +#endif
  15817. + id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  15818. + if( id->fd<0 ){
  15819. + return SQLITE_CANTOPEN;
  15820. + }
  15821. + *pReadonly = 1;
  15822. + }else{
  15823. + *pReadonly = 0;
  15824. + }
  15825. + sqliteOsEnterMutex();
  15826. + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
  15827. + sqliteOsLeaveMutex();
  15828. + if( rc ){
  15829. + close(id->fd);
  15830. + return SQLITE_NOMEM;
  15831. + }
  15832. + id->locked = 0;
  15833. + TRACE3("OPEN %-3d %s\n", id->fd, zFilename);
  15834. + OpenCounter(+1);
  15835. + return SQLITE_OK;
  15836. +#endif
  15837. +#if OS_WIN
  15838. + HANDLE h = CreateFile(zFilename,
  15839. + GENERIC_READ | GENERIC_WRITE,
  15840. + FILE_SHARE_READ | FILE_SHARE_WRITE,
  15841. + NULL,
  15842. + OPEN_ALWAYS,
  15843. + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
  15844. + NULL
  15845. + );
  15846. + if( h==INVALID_HANDLE_VALUE ){
  15847. + h = CreateFile(zFilename,
  15848. + GENERIC_READ,
  15849. + FILE_SHARE_READ,
  15850. + NULL,
  15851. + OPEN_ALWAYS,
  15852. + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
  15853. + NULL
  15854. + );
  15855. + if( h==INVALID_HANDLE_VALUE ){
  15856. + return SQLITE_CANTOPEN;
  15857. + }
  15858. + *pReadonly = 1;
  15859. + }else{
  15860. + *pReadonly = 0;
  15861. + }
  15862. + id->h = h;
  15863. + id->locked = 0;
  15864. + OpenCounter(+1);
  15865. + return SQLITE_OK;
  15866. +#endif
  15867. +#if OS_MAC
  15868. + FSSpec fsSpec;
  15869. +# ifdef _LARGE_FILE
  15870. + HFSUniStr255 dfName;
  15871. + FSRef fsRef;
  15872. + if( __path2fss(zFilename, &fsSpec) != noErr ){
  15873. + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
  15874. + return SQLITE_CANTOPEN;
  15875. + }
  15876. + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
  15877. + return SQLITE_CANTOPEN;
  15878. + FSGetDataForkName(&dfName);
  15879. + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
  15880. + fsRdWrShPerm, &(id->refNum)) != noErr ){
  15881. + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
  15882. + fsRdWrPerm, &(id->refNum)) != noErr ){
  15883. + if (FSOpenFork(&fsRef, dfName.length, dfName.unicode,
  15884. + fsRdPerm, &(id->refNum)) != noErr )
  15885. + return SQLITE_CANTOPEN;
  15886. + else
  15887. + *pReadonly = 1;
  15888. + } else
  15889. + *pReadonly = 0;
  15890. + } else
  15891. + *pReadonly = 0;
  15892. +# else
  15893. + __path2fss(zFilename, &fsSpec);
  15894. + if( !sqliteOsFileExists(zFilename) ){
  15895. + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
  15896. + return SQLITE_CANTOPEN;
  15897. + }
  15898. + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNum)) != noErr ){
  15899. + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr ){
  15900. + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
  15901. + return SQLITE_CANTOPEN;
  15902. + else
  15903. + *pReadonly = 1;
  15904. + } else
  15905. + *pReadonly = 0;
  15906. + } else
  15907. + *pReadonly = 0;
  15908. +# endif
  15909. + if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
  15910. + id->refNumRF = -1;
  15911. + }
  15912. + id->locked = 0;
  15913. + id->delOnClose = 0;
  15914. + OpenCounter(+1);
  15915. + return SQLITE_OK;
  15916. +#endif
  15917. +}
  15918. +
  15919. +
  15920. +/*
  15921. +** Attempt to open a new file for exclusive access by this process.
  15922. +** The file will be opened for both reading and writing. To avoid
  15923. +** a potential security problem, we do not allow the file to have
  15924. +** previously existed. Nor do we allow the file to be a symbolic
  15925. +** link.
  15926. +**
  15927. +** If delFlag is true, then make arrangements to automatically delete
  15928. +** the file when it is closed.
  15929. +**
  15930. +** On success, write the file handle into *id and return SQLITE_OK.
  15931. +**
  15932. +** On failure, return SQLITE_CANTOPEN.
  15933. +*/
  15934. +int sqliteOsOpenExclusive(const char *zFilename, OsFile *id, int delFlag){
  15935. +#if OS_UNIX
  15936. + int rc;
  15937. + if( access(zFilename, 0)==0 ){
  15938. + return SQLITE_CANTOPEN;
  15939. + }
  15940. + id->dirfd = -1;
  15941. + id->fd = open(zFilename,
  15942. + O_RDWR|O_CREAT|O_EXCL|O_NOFOLLOW|O_LARGEFILE|O_BINARY, 0600);
  15943. + if( id->fd<0 ){
  15944. + return SQLITE_CANTOPEN;
  15945. + }
  15946. + sqliteOsEnterMutex();
  15947. + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
  15948. + sqliteOsLeaveMutex();
  15949. + if( rc ){
  15950. + close(id->fd);
  15951. + unlink(zFilename);
  15952. + return SQLITE_NOMEM;
  15953. + }
  15954. + id->locked = 0;
  15955. + if( delFlag ){
  15956. + unlink(zFilename);
  15957. + }
  15958. + TRACE3("OPEN-EX %-3d %s\n", id->fd, zFilename);
  15959. + OpenCounter(+1);
  15960. + return SQLITE_OK;
  15961. +#endif
  15962. +#if OS_WIN
  15963. + HANDLE h;
  15964. + int fileflags;
  15965. + if( delFlag ){
  15966. + fileflags = FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_RANDOM_ACCESS
  15967. + | FILE_FLAG_DELETE_ON_CLOSE;
  15968. + }else{
  15969. + fileflags = FILE_FLAG_RANDOM_ACCESS;
  15970. + }
  15971. + h = CreateFile(zFilename,
  15972. + GENERIC_READ | GENERIC_WRITE,
  15973. + 0,
  15974. + NULL,
  15975. + CREATE_ALWAYS,
  15976. + fileflags,
  15977. + NULL
  15978. + );
  15979. + if( h==INVALID_HANDLE_VALUE ){
  15980. + return SQLITE_CANTOPEN;
  15981. + }
  15982. + id->h = h;
  15983. + id->locked = 0;
  15984. + OpenCounter(+1);
  15985. + return SQLITE_OK;
  15986. +#endif
  15987. +#if OS_MAC
  15988. + FSSpec fsSpec;
  15989. +# ifdef _LARGE_FILE
  15990. + HFSUniStr255 dfName;
  15991. + FSRef fsRef;
  15992. + __path2fss(zFilename, &fsSpec);
  15993. + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
  15994. + return SQLITE_CANTOPEN;
  15995. + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
  15996. + return SQLITE_CANTOPEN;
  15997. + FSGetDataForkName(&dfName);
  15998. + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
  15999. + fsRdWrPerm, &(id->refNum)) != noErr )
  16000. + return SQLITE_CANTOPEN;
  16001. +# else
  16002. + __path2fss(zFilename, &fsSpec);
  16003. + if( HCreate(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, 'SQLI', cDocumentFile) != noErr )
  16004. + return SQLITE_CANTOPEN;
  16005. + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrPerm, &(id->refNum)) != noErr )
  16006. + return SQLITE_CANTOPEN;
  16007. +# endif
  16008. + id->refNumRF = -1;
  16009. + id->locked = 0;
  16010. + id->delOnClose = delFlag;
  16011. + if (delFlag)
  16012. + id->pathToDel = sqliteOsFullPathname(zFilename);
  16013. + OpenCounter(+1);
  16014. + return SQLITE_OK;
  16015. +#endif
  16016. +}
  16017. +
  16018. +/*
  16019. +** Attempt to open a new file for read-only access.
  16020. +**
  16021. +** On success, write the file handle into *id and return SQLITE_OK.
  16022. +**
  16023. +** On failure, return SQLITE_CANTOPEN.
  16024. +*/
  16025. +int sqliteOsOpenReadOnly(const char *zFilename, OsFile *id){
  16026. +#if OS_UNIX
  16027. + int rc;
  16028. + id->dirfd = -1;
  16029. + id->fd = open(zFilename, O_RDONLY|O_LARGEFILE|O_BINARY);
  16030. + if( id->fd<0 ){
  16031. + return SQLITE_CANTOPEN;
  16032. + }
  16033. + sqliteOsEnterMutex();
  16034. + rc = findLockInfo(id->fd, &id->pLock, &id->pOpen);
  16035. + sqliteOsLeaveMutex();
  16036. + if( rc ){
  16037. + close(id->fd);
  16038. + return SQLITE_NOMEM;
  16039. + }
  16040. + id->locked = 0;
  16041. + TRACE3("OPEN-RO %-3d %s\n", id->fd, zFilename);
  16042. + OpenCounter(+1);
  16043. + return SQLITE_OK;
  16044. +#endif
  16045. +#if OS_WIN
  16046. + HANDLE h = CreateFile(zFilename,
  16047. + GENERIC_READ,
  16048. + 0,
  16049. + NULL,
  16050. + OPEN_EXISTING,
  16051. + FILE_ATTRIBUTE_NORMAL | FILE_FLAG_RANDOM_ACCESS,
  16052. + NULL
  16053. + );
  16054. + if( h==INVALID_HANDLE_VALUE ){
  16055. + return SQLITE_CANTOPEN;
  16056. + }
  16057. + id->h = h;
  16058. + id->locked = 0;
  16059. + OpenCounter(+1);
  16060. + return SQLITE_OK;
  16061. +#endif
  16062. +#if OS_MAC
  16063. + FSSpec fsSpec;
  16064. +# ifdef _LARGE_FILE
  16065. + HFSUniStr255 dfName;
  16066. + FSRef fsRef;
  16067. + if( __path2fss(zFilename, &fsSpec) != noErr )
  16068. + return SQLITE_CANTOPEN;
  16069. + if( FSpMakeFSRef(&fsSpec, &fsRef) != noErr )
  16070. + return SQLITE_CANTOPEN;
  16071. + FSGetDataForkName(&dfName);
  16072. + if( FSOpenFork(&fsRef, dfName.length, dfName.unicode,
  16073. + fsRdPerm, &(id->refNum)) != noErr )
  16074. + return SQLITE_CANTOPEN;
  16075. +# else
  16076. + __path2fss(zFilename, &fsSpec);
  16077. + if( HOpenDF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdPerm, &(id->refNum)) != noErr )
  16078. + return SQLITE_CANTOPEN;
  16079. +# endif
  16080. + if( HOpenRF(fsSpec.vRefNum, fsSpec.parID, fsSpec.name, fsRdWrShPerm, &(id->refNumRF)) != noErr){
  16081. + id->refNumRF = -1;
  16082. + }
  16083. + id->locked = 0;
  16084. + id->delOnClose = 0;
  16085. + OpenCounter(+1);
  16086. + return SQLITE_OK;
  16087. +#endif
  16088. +}
  16089. +
  16090. +/*
  16091. +** Attempt to open a file descriptor for the directory that contains a
  16092. +** file. This file descriptor can be used to fsync() the directory
  16093. +** in order to make sure the creation of a new file is actually written
  16094. +** to disk.
  16095. +**
  16096. +** This routine is only meaningful for Unix. It is a no-op under
  16097. +** windows since windows does not support hard links.
  16098. +**
  16099. +** On success, a handle for a previously open file is at *id is
  16100. +** updated with the new directory file descriptor and SQLITE_OK is
  16101. +** returned.
  16102. +**
  16103. +** On failure, the function returns SQLITE_CANTOPEN and leaves
  16104. +** *id unchanged.
  16105. +*/
  16106. +int sqliteOsOpenDirectory(
  16107. + const char *zDirname,
  16108. + OsFile *id
  16109. +){
  16110. +#if OS_UNIX
  16111. + if( id->fd<0 ){
  16112. + /* Do not open the directory if the corresponding file is not already
  16113. + ** open. */
  16114. + return SQLITE_CANTOPEN;
  16115. + }
  16116. + assert( id->dirfd<0 );
  16117. + id->dirfd = open(zDirname, O_RDONLY|O_BINARY, 0644);
  16118. + if( id->dirfd<0 ){
  16119. + return SQLITE_CANTOPEN;
  16120. + }
  16121. + TRACE3("OPENDIR %-3d %s\n", id->dirfd, zDirname);
  16122. +#endif
  16123. + return SQLITE_OK;
  16124. +}
  16125. +
  16126. +/*
  16127. +** If the following global variable points to a string which is the
  16128. +** name of a directory, then that directory will be used to store
  16129. +** temporary files.
  16130. +*/
  16131. +const char *sqlite_temp_directory = 0;
  16132. +
  16133. +/*
  16134. +** Create a temporary file name in zBuf. zBuf must be big enough to
  16135. +** hold at least SQLITE_TEMPNAME_SIZE characters.
  16136. +*/
  16137. +int sqliteOsTempFileName(char *zBuf){
  16138. +#if OS_UNIX
  16139. + static const char *azDirs[] = {
  16140. + 0,
  16141. + "/var/tmp",
  16142. + "/usr/tmp",
  16143. + "/tmp",
  16144. + ".",
  16145. + };
  16146. + static unsigned char zChars[] =
  16147. + "abcdefghijklmnopqrstuvwxyz"
  16148. + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  16149. + "0123456789";
  16150. + int i, j;
  16151. + struct stat buf;
  16152. + const char *zDir = ".";
  16153. + azDirs[0] = sqlite_temp_directory;
  16154. + for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
  16155. + if( azDirs[i]==0 ) continue;
  16156. + if( stat(azDirs[i], &buf) ) continue;
  16157. + if( !S_ISDIR(buf.st_mode) ) continue;
  16158. + if( access(azDirs[i], 07) ) continue;
  16159. + zDir = azDirs[i];
  16160. + break;
  16161. + }
  16162. + do{
  16163. + sprintf(zBuf, "%s/"TEMP_FILE_PREFIX, zDir);
  16164. + j = strlen(zBuf);
  16165. + sqliteRandomness(15, &zBuf[j]);
  16166. + for(i=0; i<15; i++, j++){
  16167. + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  16168. + }
  16169. + zBuf[j] = 0;
  16170. + }while( access(zBuf,0)==0 );
  16171. +#endif
  16172. +#if OS_WIN
  16173. + static char zChars[] =
  16174. + "abcdefghijklmnopqrstuvwxyz"
  16175. + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  16176. + "0123456789";
  16177. + int i, j;
  16178. + const char *zDir;
  16179. + char zTempPath[SQLITE_TEMPNAME_SIZE];
  16180. + if( sqlite_temp_directory==0 ){
  16181. + GetTempPath(SQLITE_TEMPNAME_SIZE-30, zTempPath);
  16182. + for(i=strlen(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
  16183. + zTempPath[i] = 0;
  16184. + zDir = zTempPath;
  16185. + }else{
  16186. + zDir = sqlite_temp_directory;
  16187. + }
  16188. + for(;;){
  16189. + sprintf(zBuf, "%s\\"TEMP_FILE_PREFIX, zDir);
  16190. + j = strlen(zBuf);
  16191. + sqliteRandomness(15, &zBuf[j]);
  16192. + for(i=0; i<15; i++, j++){
  16193. + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  16194. + }
  16195. + zBuf[j] = 0;
  16196. + if( !sqliteOsFileExists(zBuf) ) break;
  16197. + }
  16198. +#endif
  16199. +#if OS_MAC
  16200. + static char zChars[] =
  16201. + "abcdefghijklmnopqrstuvwxyz"
  16202. + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  16203. + "0123456789";
  16204. + int i, j;
  16205. + char *zDir;
  16206. + char zTempPath[SQLITE_TEMPNAME_SIZE];
  16207. + char zdirName[32];
  16208. + CInfoPBRec infoRec;
  16209. + Str31 dirName;
  16210. + memset(&infoRec, 0, sizeof(infoRec));
  16211. + memset(zTempPath, 0, SQLITE_TEMPNAME_SIZE);
  16212. + if( sqlite_temp_directory!=0 ){
  16213. + zDir = sqlite_temp_directory;
  16214. + }else if( FindFolder(kOnSystemDisk, kTemporaryFolderType, kCreateFolder,
  16215. + &(infoRec.dirInfo.ioVRefNum), &(infoRec.dirInfo.ioDrParID)) == noErr ){
  16216. + infoRec.dirInfo.ioNamePtr = dirName;
  16217. + do{
  16218. + infoRec.dirInfo.ioFDirIndex = -1;
  16219. + infoRec.dirInfo.ioDrDirID = infoRec.dirInfo.ioDrParID;
  16220. + if( PBGetCatInfoSync(&infoRec) == noErr ){
  16221. + CopyPascalStringToC(dirName, zdirName);
  16222. + i = strlen(zdirName);
  16223. + memmove(&(zTempPath[i+1]), zTempPath, strlen(zTempPath));
  16224. + strcpy(zTempPath, zdirName);
  16225. + zTempPath[i] = ':';
  16226. + }else{
  16227. + *zTempPath = 0;
  16228. + break;
  16229. + }
  16230. + } while( infoRec.dirInfo.ioDrDirID != fsRtDirID );
  16231. + zDir = zTempPath;
  16232. + }
  16233. + if( zDir[0]==0 ){
  16234. + getcwd(zTempPath, SQLITE_TEMPNAME_SIZE-24);
  16235. + zDir = zTempPath;
  16236. + }
  16237. + for(;;){
  16238. + sprintf(zBuf, "%s"TEMP_FILE_PREFIX, zDir);
  16239. + j = strlen(zBuf);
  16240. + sqliteRandomness(15, &zBuf[j]);
  16241. + for(i=0; i<15; i++, j++){
  16242. + zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  16243. + }
  16244. + zBuf[j] = 0;
  16245. + if( !sqliteOsFileExists(zBuf) ) break;
  16246. + }
  16247. +#endif
  16248. + return SQLITE_OK;
  16249. +}
  16250. +
  16251. +/*
  16252. +** Close a file.
  16253. +*/
  16254. +int sqliteOsClose(OsFile *id){
  16255. +#if OS_UNIX
  16256. + sqliteOsUnlock(id);
  16257. + if( id->dirfd>=0 ) close(id->dirfd);
  16258. + id->dirfd = -1;
  16259. + sqliteOsEnterMutex();
  16260. + if( id->pOpen->nLock ){
  16261. + /* If there are outstanding locks, do not actually close the file just
  16262. + ** yet because that would clear those locks. Instead, add the file
  16263. + ** descriptor to pOpen->aPending. It will be automatically closed when
  16264. + ** the last lock is cleared.
  16265. + */
  16266. + int *aNew;
  16267. + struct openCnt *pOpen = id->pOpen;
  16268. + pOpen->nPending++;
  16269. + aNew = sqliteRealloc( pOpen->aPending, pOpen->nPending*sizeof(int) );
  16270. + if( aNew==0 ){
  16271. + /* If a malloc fails, just leak the file descriptor */
  16272. + }else{
  16273. + pOpen->aPending = aNew;
  16274. + pOpen->aPending[pOpen->nPending-1] = id->fd;
  16275. + }
  16276. + }else{
  16277. + /* There are no outstanding locks so we can close the file immediately */
  16278. + close(id->fd);
  16279. + }
  16280. + releaseLockInfo(id->pLock);
  16281. + releaseOpenCnt(id->pOpen);
  16282. + sqliteOsLeaveMutex();
  16283. + TRACE2("CLOSE %-3d\n", id->fd);
  16284. + OpenCounter(-1);
  16285. + return SQLITE_OK;
  16286. +#endif
  16287. +#if OS_WIN
  16288. + CloseHandle(id->h);
  16289. + OpenCounter(-1);
  16290. + return SQLITE_OK;
  16291. +#endif
  16292. +#if OS_MAC
  16293. + if( id->refNumRF!=-1 )
  16294. + FSClose(id->refNumRF);
  16295. +# ifdef _LARGE_FILE
  16296. + FSCloseFork(id->refNum);
  16297. +# else
  16298. + FSClose(id->refNum);
  16299. +# endif
  16300. + if( id->delOnClose ){
  16301. + unlink(id->pathToDel);
  16302. + sqliteFree(id->pathToDel);
  16303. + }
  16304. + OpenCounter(-1);
  16305. + return SQLITE_OK;
  16306. +#endif
  16307. +}
  16308. +
  16309. +/*
  16310. +** Read data from a file into a buffer. Return SQLITE_OK if all
  16311. +** bytes were read successfully and SQLITE_IOERR if anything goes
  16312. +** wrong.
  16313. +*/
  16314. +int sqliteOsRead(OsFile *id, void *pBuf, int amt){
  16315. +#if OS_UNIX
  16316. + int got;
  16317. + SimulateIOError(SQLITE_IOERR);
  16318. + TIMER_START;
  16319. + got = read(id->fd, pBuf, amt);
  16320. + TIMER_END;
  16321. + TRACE4("READ %-3d %7d %d\n", id->fd, last_page, elapse);
  16322. + SEEK(0);
  16323. + /* if( got<0 ) got = 0; */
  16324. + if( got==amt ){
  16325. + return SQLITE_OK;
  16326. + }else{
  16327. + return SQLITE_IOERR;
  16328. + }
  16329. +#endif
  16330. +#if OS_WIN
  16331. + DWORD got;
  16332. + SimulateIOError(SQLITE_IOERR);
  16333. + TRACE2("READ %d\n", last_page);
  16334. + if( !ReadFile(id->h, pBuf, amt, &got, 0) ){
  16335. + got = 0;
  16336. + }
  16337. + if( got==(DWORD)amt ){
  16338. + return SQLITE_OK;
  16339. + }else{
  16340. + return SQLITE_IOERR;
  16341. + }
  16342. +#endif
  16343. +#if OS_MAC
  16344. + int got;
  16345. + SimulateIOError(SQLITE_IOERR);
  16346. + TRACE2("READ %d\n", last_page);
  16347. +# ifdef _LARGE_FILE
  16348. + FSReadFork(id->refNum, fsAtMark, 0, (ByteCount)amt, pBuf, (ByteCount*)&got);
  16349. +# else
  16350. + got = amt;
  16351. + FSRead(id->refNum, &got, pBuf);
  16352. +# endif
  16353. + if( got==amt ){
  16354. + return SQLITE_OK;
  16355. + }else{
  16356. + return SQLITE_IOERR;
  16357. + }
  16358. +#endif
  16359. +}
  16360. +
  16361. +/*
  16362. +** Write data from a buffer into a file. Return SQLITE_OK on success
  16363. +** or some other error code on failure.
  16364. +*/
  16365. +int sqliteOsWrite(OsFile *id, const void *pBuf, int amt){
  16366. +#if OS_UNIX
  16367. + int wrote = 0;
  16368. + SimulateIOError(SQLITE_IOERR);
  16369. + TIMER_START;
  16370. + while( amt>0 && (wrote = write(id->fd, pBuf, amt))>0 ){
  16371. + amt -= wrote;
  16372. + pBuf = &((char*)pBuf)[wrote];
  16373. + }
  16374. + TIMER_END;
  16375. + TRACE4("WRITE %-3d %7d %d\n", id->fd, last_page, elapse);
  16376. + SEEK(0);
  16377. + if( amt>0 ){
  16378. + return SQLITE_FULL;
  16379. + }
  16380. + return SQLITE_OK;
  16381. +#endif
  16382. +#if OS_WIN
  16383. + int rc;
  16384. + DWORD wrote;
  16385. + SimulateIOError(SQLITE_IOERR);
  16386. + TRACE2("WRITE %d\n", last_page);
  16387. + while( amt>0 && (rc = WriteFile(id->h, pBuf, amt, &wrote, 0))!=0 && wrote>0 ){
  16388. + amt -= wrote;
  16389. + pBuf = &((char*)pBuf)[wrote];
  16390. + }
  16391. + if( !rc || amt>(int)wrote ){
  16392. + return SQLITE_FULL;
  16393. + }
  16394. + return SQLITE_OK;
  16395. +#endif
  16396. +#if OS_MAC
  16397. + OSErr oserr;
  16398. + int wrote = 0;
  16399. + SimulateIOError(SQLITE_IOERR);
  16400. + TRACE2("WRITE %d\n", last_page);
  16401. + while( amt>0 ){
  16402. +# ifdef _LARGE_FILE
  16403. + oserr = FSWriteFork(id->refNum, fsAtMark, 0,
  16404. + (ByteCount)amt, pBuf, (ByteCount*)&wrote);
  16405. +# else
  16406. + wrote = amt;
  16407. + oserr = FSWrite(id->refNum, &wrote, pBuf);
  16408. +# endif
  16409. + if( wrote == 0 || oserr != noErr)
  16410. + break;
  16411. + amt -= wrote;
  16412. + pBuf = &((char*)pBuf)[wrote];
  16413. + }
  16414. + if( oserr != noErr || amt>wrote ){
  16415. + return SQLITE_FULL;
  16416. + }
  16417. + return SQLITE_OK;
  16418. +#endif
  16419. +}
  16420. +
  16421. +/*
  16422. +** Move the read/write pointer in a file.
  16423. +*/
  16424. +int sqliteOsSeek(OsFile *id, off_t offset){
  16425. + SEEK(offset/1024 + 1);
  16426. +#if OS_UNIX
  16427. + lseek(id->fd, offset, SEEK_SET);
  16428. + return SQLITE_OK;
  16429. +#endif
  16430. +#if OS_WIN
  16431. + {
  16432. + LONG upperBits = offset>>32;
  16433. + LONG lowerBits = offset & 0xffffffff;
  16434. + DWORD rc;
  16435. + rc = SetFilePointer(id->h, lowerBits, &upperBits, FILE_BEGIN);
  16436. + /* TRACE3("SEEK rc=0x%x upper=0x%x\n", rc, upperBits); */
  16437. + }
  16438. + return SQLITE_OK;
  16439. +#endif
  16440. +#if OS_MAC
  16441. + {
  16442. + off_t curSize;
  16443. + if( sqliteOsFileSize(id, &curSize) != SQLITE_OK ){
  16444. + return SQLITE_IOERR;
  16445. + }
  16446. + if( offset >= curSize ){
  16447. + if( sqliteOsTruncate(id, offset+1) != SQLITE_OK ){
  16448. + return SQLITE_IOERR;
  16449. + }
  16450. + }
  16451. +# ifdef _LARGE_FILE
  16452. + if( FSSetForkPosition(id->refNum, fsFromStart, offset) != noErr ){
  16453. +# else
  16454. + if( SetFPos(id->refNum, fsFromStart, offset) != noErr ){
  16455. +# endif
  16456. + return SQLITE_IOERR;
  16457. + }else{
  16458. + return SQLITE_OK;
  16459. + }
  16460. + }
  16461. +#endif
  16462. +}
  16463. +
  16464. +#ifdef SQLITE_NOSYNC
  16465. +# define fsync(X) 0
  16466. +#endif
  16467. +
  16468. +/*
  16469. +** Make sure all writes to a particular file are committed to disk.
  16470. +**
  16471. +** Under Unix, also make sure that the directory entry for the file
  16472. +** has been created by fsync-ing the directory that contains the file.
  16473. +** If we do not do this and we encounter a power failure, the directory
  16474. +** entry for the journal might not exist after we reboot. The next
  16475. +** SQLite to access the file will not know that the journal exists (because
  16476. +** the directory entry for the journal was never created) and the transaction
  16477. +** will not roll back - possibly leading to database corruption.
  16478. +*/
  16479. +int sqliteOsSync(OsFile *id){
  16480. +#if OS_UNIX
  16481. + SimulateIOError(SQLITE_IOERR);
  16482. + TRACE2("SYNC %-3d\n", id->fd);
  16483. + if( fsync(id->fd) ){
  16484. + return SQLITE_IOERR;
  16485. + }else{
  16486. + if( id->dirfd>=0 ){
  16487. + TRACE2("DIRSYNC %-3d\n", id->dirfd);
  16488. + fsync(id->dirfd);
  16489. + close(id->dirfd); /* Only need to sync once, so close the directory */
  16490. + id->dirfd = -1; /* when we are done. */
  16491. + }
  16492. + return SQLITE_OK;
  16493. + }
  16494. +#endif
  16495. +#if OS_WIN
  16496. + if( FlushFileBuffers(id->h) ){
  16497. + return SQLITE_OK;
  16498. + }else{
  16499. + return SQLITE_IOERR;
  16500. + }
  16501. +#endif
  16502. +#if OS_MAC
  16503. +# ifdef _LARGE_FILE
  16504. + if( FSFlushFork(id->refNum) != noErr ){
  16505. +# else
  16506. + ParamBlockRec params;
  16507. + memset(&params, 0, sizeof(ParamBlockRec));
  16508. + params.ioParam.ioRefNum = id->refNum;
  16509. + if( PBFlushFileSync(&params) != noErr ){
  16510. +# endif
  16511. + return SQLITE_IOERR;
  16512. + }else{
  16513. + return SQLITE_OK;
  16514. + }
  16515. +#endif
  16516. +}
  16517. +
  16518. +/*
  16519. +** Truncate an open file to a specified size
  16520. +*/
  16521. +int sqliteOsTruncate(OsFile *id, off_t nByte){
  16522. + SimulateIOError(SQLITE_IOERR);
  16523. +#if OS_UNIX
  16524. + return ftruncate(id->fd, nByte)==0 ? SQLITE_OK : SQLITE_IOERR;
  16525. +#endif
  16526. +#if OS_WIN
  16527. + {
  16528. + LONG upperBits = nByte>>32;
  16529. + SetFilePointer(id->h, nByte, &upperBits, FILE_BEGIN);
  16530. + SetEndOfFile(id->h);
  16531. + }
  16532. + return SQLITE_OK;
  16533. +#endif
  16534. +#if OS_MAC
  16535. +# ifdef _LARGE_FILE
  16536. + if( FSSetForkSize(id->refNum, fsFromStart, nByte) != noErr){
  16537. +# else
  16538. + if( SetEOF(id->refNum, nByte) != noErr ){
  16539. +# endif
  16540. + return SQLITE_IOERR;
  16541. + }else{
  16542. + return SQLITE_OK;
  16543. + }
  16544. +#endif
  16545. +}
  16546. +
  16547. +/*
  16548. +** Determine the current size of a file in bytes
  16549. +*/
  16550. +int sqliteOsFileSize(OsFile *id, off_t *pSize){
  16551. +#if OS_UNIX
  16552. + struct stat buf;
  16553. + SimulateIOError(SQLITE_IOERR);
  16554. + if( fstat(id->fd, &buf)!=0 ){
  16555. + return SQLITE_IOERR;
  16556. + }
  16557. + *pSize = buf.st_size;
  16558. + return SQLITE_OK;
  16559. +#endif
  16560. +#if OS_WIN
  16561. + DWORD upperBits, lowerBits;
  16562. + SimulateIOError(SQLITE_IOERR);
  16563. + lowerBits = GetFileSize(id->h, &upperBits);
  16564. + *pSize = (((off_t)upperBits)<<32) + lowerBits;
  16565. + return SQLITE_OK;
  16566. +#endif
  16567. +#if OS_MAC
  16568. +# ifdef _LARGE_FILE
  16569. + if( FSGetForkSize(id->refNum, pSize) != noErr){
  16570. +# else
  16571. + if( GetEOF(id->refNum, pSize) != noErr ){
  16572. +# endif
  16573. + return SQLITE_IOERR;
  16574. + }else{
  16575. + return SQLITE_OK;
  16576. + }
  16577. +#endif
  16578. +}
  16579. +
  16580. +#if OS_WIN
  16581. +/*
  16582. +** Return true (non-zero) if we are running under WinNT, Win2K or WinXP.
  16583. +** Return false (zero) for Win95, Win98, or WinME.
  16584. +**
  16585. +** Here is an interesting observation: Win95, Win98, and WinME lack
  16586. +** the LockFileEx() API. But we can still statically link against that
  16587. +** API as long as we don't call it win running Win95/98/ME. A call to
  16588. +** this routine is used to determine if the host is Win95/98/ME or
  16589. +** WinNT/2K/XP so that we will know whether or not we can safely call
  16590. +** the LockFileEx() API.
  16591. +*/
  16592. +int isNT(void){
  16593. + static int osType = 0; /* 0=unknown 1=win95 2=winNT */
  16594. + if( osType==0 ){
  16595. + OSVERSIONINFO sInfo;
  16596. + sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  16597. + GetVersionEx(&sInfo);
  16598. + osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
  16599. + }
  16600. + return osType==2;
  16601. +}
  16602. +#endif
  16603. +
  16604. +/*
  16605. +** Windows file locking notes: [similar issues apply to MacOS]
  16606. +**
  16607. +** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  16608. +** those functions are not available. So we use only LockFile() and
  16609. +** UnlockFile().
  16610. +**
  16611. +** LockFile() prevents not just writing but also reading by other processes.
  16612. +** (This is a design error on the part of Windows, but there is nothing
  16613. +** we can do about that.) So the region used for locking is at the
  16614. +** end of the file where it is unlikely to ever interfere with an
  16615. +** actual read attempt.
  16616. +**
  16617. +** A database read lock is obtained by locking a single randomly-chosen
  16618. +** byte out of a specific range of bytes. The lock byte is obtained at
  16619. +** random so two separate readers can probably access the file at the
  16620. +** same time, unless they are unlucky and choose the same lock byte.
  16621. +** A database write lock is obtained by locking all bytes in the range.
  16622. +** There can only be one writer.
  16623. +**
  16624. +** A lock is obtained on the first byte of the lock range before acquiring
  16625. +** either a read lock or a write lock. This prevents two processes from
  16626. +** attempting to get a lock at a same time. The semantics of
  16627. +** sqliteOsReadLock() require that if there is already a write lock, that
  16628. +** lock is converted into a read lock atomically. The lock on the first
  16629. +** byte allows us to drop the old write lock and get the read lock without
  16630. +** another process jumping into the middle and messing us up. The same
  16631. +** argument applies to sqliteOsWriteLock().
  16632. +**
  16633. +** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  16634. +** which means we can use reader/writer locks. When reader writer locks
  16635. +** are used, the lock is placed on the same range of bytes that is used
  16636. +** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  16637. +** will support two or more Win95 readers or two or more WinNT readers.
  16638. +** But a single Win95 reader will lock out all WinNT readers and a single
  16639. +** WinNT reader will lock out all other Win95 readers.
  16640. +**
  16641. +** Note: On MacOS we use the resource fork for locking.
  16642. +**
  16643. +** The following #defines specify the range of bytes used for locking.
  16644. +** N_LOCKBYTE is the number of bytes available for doing the locking.
  16645. +** The first byte used to hold the lock while the lock is changing does
  16646. +** not count toward this number. FIRST_LOCKBYTE is the address of
  16647. +** the first byte in the range of bytes used for locking.
  16648. +*/
  16649. +#define N_LOCKBYTE 10239
  16650. +#if OS_MAC
  16651. +# define FIRST_LOCKBYTE (0x000fffff - N_LOCKBYTE)
  16652. +#else
  16653. +# define FIRST_LOCKBYTE (0xffffffff - N_LOCKBYTE)
  16654. +#endif
  16655. +
  16656. +/*
  16657. +** Change the status of the lock on the file "id" to be a readlock.
  16658. +** If the file was write locked, then this reduces the lock to a read.
  16659. +** If the file was read locked, then this acquires a new read lock.
  16660. +**
  16661. +** Return SQLITE_OK on success and SQLITE_BUSY on failure. If this
  16662. +** library was compiled with large file support (LFS) but LFS is not
  16663. +** available on the host, then an SQLITE_NOLFS is returned.
  16664. +*/
  16665. +int sqliteOsReadLock(OsFile *id){
  16666. +#if OS_UNIX
  16667. + int rc;
  16668. + sqliteOsEnterMutex();
  16669. + if( id->pLock->cnt>0 ){
  16670. + if( !id->locked ){
  16671. + id->pLock->cnt++;
  16672. + id->locked = 1;
  16673. + id->pOpen->nLock++;
  16674. + }
  16675. + rc = SQLITE_OK;
  16676. + }else if( id->locked || id->pLock->cnt==0 ){
  16677. + struct flock lock;
  16678. + int s;
  16679. + lock.l_type = F_RDLCK;
  16680. + lock.l_whence = SEEK_SET;
  16681. + lock.l_start = lock.l_len = 0L;
  16682. + s = fcntl(id->fd, F_SETLK, &lock);
  16683. + if( s!=0 ){
  16684. + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  16685. + }else{
  16686. + rc = SQLITE_OK;
  16687. + if( !id->locked ){
  16688. + id->pOpen->nLock++;
  16689. + id->locked = 1;
  16690. + }
  16691. + id->pLock->cnt = 1;
  16692. + }
  16693. + }else{
  16694. + rc = SQLITE_BUSY;
  16695. + }
  16696. + sqliteOsLeaveMutex();
  16697. + return rc;
  16698. +#endif
  16699. +#if OS_WIN
  16700. + int rc;
  16701. + if( id->locked>0 ){
  16702. + rc = SQLITE_OK;
  16703. + }else{
  16704. + int lk;
  16705. + int res;
  16706. + int cnt = 100;
  16707. + sqliteRandomness(sizeof(lk), &lk);
  16708. + lk = (lk & 0x7fffffff)%N_LOCKBYTE + 1;
  16709. + while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
  16710. + Sleep(1);
  16711. + }
  16712. + if( res ){
  16713. + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
  16714. + if( isNT() ){
  16715. + OVERLAPPED ovlp;
  16716. + ovlp.Offset = FIRST_LOCKBYTE+1;
  16717. + ovlp.OffsetHigh = 0;
  16718. + ovlp.hEvent = 0;
  16719. + res = LockFileEx(id->h, LOCKFILE_FAIL_IMMEDIATELY,
  16720. + 0, N_LOCKBYTE, 0, &ovlp);
  16721. + }else{
  16722. + res = LockFile(id->h, FIRST_LOCKBYTE+lk, 0, 1, 0);
  16723. + }
  16724. + UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
  16725. + }
  16726. + if( res ){
  16727. + id->locked = lk;
  16728. + rc = SQLITE_OK;
  16729. + }else{
  16730. + rc = SQLITE_BUSY;
  16731. + }
  16732. + }
  16733. + return rc;
  16734. +#endif
  16735. +#if OS_MAC
  16736. + int rc;
  16737. + if( id->locked>0 || id->refNumRF == -1 ){
  16738. + rc = SQLITE_OK;
  16739. + }else{
  16740. + int lk;
  16741. + OSErr res;
  16742. + int cnt = 5;
  16743. + ParamBlockRec params;
  16744. + sqliteRandomness(sizeof(lk), &lk);
  16745. + lk = (lk & 0x7fffffff)%N_LOCKBYTE + 1;
  16746. + memset(&params, 0, sizeof(params));
  16747. + params.ioParam.ioRefNum = id->refNumRF;
  16748. + params.ioParam.ioPosMode = fsFromStart;
  16749. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
  16750. + params.ioParam.ioReqCount = 1;
  16751. + while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
  16752. + UInt32 finalTicks;
  16753. + Delay(1, &finalTicks); /* 1/60 sec */
  16754. + }
  16755. + if( res == noErr ){
  16756. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
  16757. + params.ioParam.ioReqCount = N_LOCKBYTE;
  16758. + PBUnlockRangeSync(&params);
  16759. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+lk;
  16760. + params.ioParam.ioReqCount = 1;
  16761. + res = PBLockRangeSync(&params);
  16762. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
  16763. + params.ioParam.ioReqCount = 1;
  16764. + PBUnlockRangeSync(&params);
  16765. + }
  16766. + if( res == noErr ){
  16767. + id->locked = lk;
  16768. + rc = SQLITE_OK;
  16769. + }else{
  16770. + rc = SQLITE_BUSY;
  16771. + }
  16772. + }
  16773. + return rc;
  16774. +#endif
  16775. +}
  16776. +
  16777. +/*
  16778. +** Change the lock status to be an exclusive or write lock. Return
  16779. +** SQLITE_OK on success and SQLITE_BUSY on a failure. If this
  16780. +** library was compiled with large file support (LFS) but LFS is not
  16781. +** available on the host, then an SQLITE_NOLFS is returned.
  16782. +*/
  16783. +int sqliteOsWriteLock(OsFile *id){
  16784. +#if OS_UNIX
  16785. + int rc;
  16786. + sqliteOsEnterMutex();
  16787. + if( id->pLock->cnt==0 || (id->pLock->cnt==1 && id->locked==1) ){
  16788. + struct flock lock;
  16789. + int s;
  16790. + lock.l_type = F_WRLCK;
  16791. + lock.l_whence = SEEK_SET;
  16792. + lock.l_start = lock.l_len = 0L;
  16793. + s = fcntl(id->fd, F_SETLK, &lock);
  16794. + if( s!=0 ){
  16795. + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  16796. + }else{
  16797. + rc = SQLITE_OK;
  16798. + if( !id->locked ){
  16799. + id->pOpen->nLock++;
  16800. + id->locked = 1;
  16801. + }
  16802. + id->pLock->cnt = -1;
  16803. + }
  16804. + }else{
  16805. + rc = SQLITE_BUSY;
  16806. + }
  16807. + sqliteOsLeaveMutex();
  16808. + return rc;
  16809. +#endif
  16810. +#if OS_WIN
  16811. + int rc;
  16812. + if( id->locked<0 ){
  16813. + rc = SQLITE_OK;
  16814. + }else{
  16815. + int res;
  16816. + int cnt = 100;
  16817. + while( cnt-->0 && (res = LockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0))==0 ){
  16818. + Sleep(1);
  16819. + }
  16820. + if( res ){
  16821. + if( id->locked>0 ){
  16822. + if( isNT() ){
  16823. + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
  16824. + }else{
  16825. + res = UnlockFile(id->h, FIRST_LOCKBYTE + id->locked, 0, 1, 0);
  16826. + }
  16827. + }
  16828. + if( res ){
  16829. + res = LockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
  16830. + }else{
  16831. + res = 0;
  16832. + }
  16833. + UnlockFile(id->h, FIRST_LOCKBYTE, 0, 1, 0);
  16834. + }
  16835. + if( res ){
  16836. + id->locked = -1;
  16837. + rc = SQLITE_OK;
  16838. + }else{
  16839. + rc = SQLITE_BUSY;
  16840. + }
  16841. + }
  16842. + return rc;
  16843. +#endif
  16844. +#if OS_MAC
  16845. + int rc;
  16846. + if( id->locked<0 || id->refNumRF == -1 ){
  16847. + rc = SQLITE_OK;
  16848. + }else{
  16849. + OSErr res;
  16850. + int cnt = 5;
  16851. + ParamBlockRec params;
  16852. + memset(&params, 0, sizeof(params));
  16853. + params.ioParam.ioRefNum = id->refNumRF;
  16854. + params.ioParam.ioPosMode = fsFromStart;
  16855. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
  16856. + params.ioParam.ioReqCount = 1;
  16857. + while( cnt-->0 && (res = PBLockRangeSync(&params))!=noErr ){
  16858. + UInt32 finalTicks;
  16859. + Delay(1, &finalTicks); /* 1/60 sec */
  16860. + }
  16861. + if( res == noErr ){
  16862. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE + id->locked;
  16863. + params.ioParam.ioReqCount = 1;
  16864. + if( id->locked==0
  16865. + || PBUnlockRangeSync(&params)==noErr ){
  16866. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
  16867. + params.ioParam.ioReqCount = N_LOCKBYTE;
  16868. + res = PBLockRangeSync(&params);
  16869. + }else{
  16870. + res = afpRangeNotLocked;
  16871. + }
  16872. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE;
  16873. + params.ioParam.ioReqCount = 1;
  16874. + PBUnlockRangeSync(&params);
  16875. + }
  16876. + if( res == noErr ){
  16877. + id->locked = -1;
  16878. + rc = SQLITE_OK;
  16879. + }else{
  16880. + rc = SQLITE_BUSY;
  16881. + }
  16882. + }
  16883. + return rc;
  16884. +#endif
  16885. +}
  16886. +
  16887. +/*
  16888. +** Unlock the given file descriptor. If the file descriptor was
  16889. +** not previously locked, then this routine is a no-op. If this
  16890. +** library was compiled with large file support (LFS) but LFS is not
  16891. +** available on the host, then an SQLITE_NOLFS is returned.
  16892. +*/
  16893. +int sqliteOsUnlock(OsFile *id){
  16894. +#if OS_UNIX
  16895. + int rc;
  16896. + if( !id->locked ) return SQLITE_OK;
  16897. + sqliteOsEnterMutex();
  16898. + assert( id->pLock->cnt!=0 );
  16899. + if( id->pLock->cnt>1 ){
  16900. + id->pLock->cnt--;
  16901. + rc = SQLITE_OK;
  16902. + }else{
  16903. + struct flock lock;
  16904. + int s;
  16905. + lock.l_type = F_UNLCK;
  16906. + lock.l_whence = SEEK_SET;
  16907. + lock.l_start = lock.l_len = 0L;
  16908. + s = fcntl(id->fd, F_SETLK, &lock);
  16909. + if( s!=0 ){
  16910. + rc = (errno==EINVAL) ? SQLITE_NOLFS : SQLITE_BUSY;
  16911. + }else{
  16912. + rc = SQLITE_OK;
  16913. + id->pLock->cnt = 0;
  16914. + }
  16915. + }
  16916. + if( rc==SQLITE_OK ){
  16917. + /* Decrement the count of locks against this same file. When the
  16918. + ** count reaches zero, close any other file descriptors whose close
  16919. + ** was deferred because of outstanding locks.
  16920. + */
  16921. + struct openCnt *pOpen = id->pOpen;
  16922. + pOpen->nLock--;
  16923. + assert( pOpen->nLock>=0 );
  16924. + if( pOpen->nLock==0 && pOpen->nPending>0 ){
  16925. + int i;
  16926. + for(i=0; i<pOpen->nPending; i++){
  16927. + close(pOpen->aPending[i]);
  16928. + }
  16929. + sqliteFree(pOpen->aPending);
  16930. + pOpen->nPending = 0;
  16931. + pOpen->aPending = 0;
  16932. + }
  16933. + }
  16934. + sqliteOsLeaveMutex();
  16935. + id->locked = 0;
  16936. + return rc;
  16937. +#endif
  16938. +#if OS_WIN
  16939. + int rc;
  16940. + if( id->locked==0 ){
  16941. + rc = SQLITE_OK;
  16942. + }else if( isNT() || id->locked<0 ){
  16943. + UnlockFile(id->h, FIRST_LOCKBYTE+1, 0, N_LOCKBYTE, 0);
  16944. + rc = SQLITE_OK;
  16945. + id->locked = 0;
  16946. + }else{
  16947. + UnlockFile(id->h, FIRST_LOCKBYTE+id->locked, 0, 1, 0);
  16948. + rc = SQLITE_OK;
  16949. + id->locked = 0;
  16950. + }
  16951. + return rc;
  16952. +#endif
  16953. +#if OS_MAC
  16954. + int rc;
  16955. + ParamBlockRec params;
  16956. + memset(&params, 0, sizeof(params));
  16957. + params.ioParam.ioRefNum = id->refNumRF;
  16958. + params.ioParam.ioPosMode = fsFromStart;
  16959. + if( id->locked==0 || id->refNumRF == -1 ){
  16960. + rc = SQLITE_OK;
  16961. + }else if( id->locked<0 ){
  16962. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+1;
  16963. + params.ioParam.ioReqCount = N_LOCKBYTE;
  16964. + PBUnlockRangeSync(&params);
  16965. + rc = SQLITE_OK;
  16966. + id->locked = 0;
  16967. + }else{
  16968. + params.ioParam.ioPosOffset = FIRST_LOCKBYTE+id->locked;
  16969. + params.ioParam.ioReqCount = 1;
  16970. + PBUnlockRangeSync(&params);
  16971. + rc = SQLITE_OK;
  16972. + id->locked = 0;
  16973. + }
  16974. + return rc;
  16975. +#endif
  16976. +}
  16977. +
  16978. +/*
  16979. +** Get information to seed the random number generator. The seed
  16980. +** is written into the buffer zBuf[256]. The calling function must
  16981. +** supply a sufficiently large buffer.
  16982. +*/
  16983. +int sqliteOsRandomSeed(char *zBuf){
  16984. + /* We have to initialize zBuf to prevent valgrind from reporting
  16985. + ** errors. The reports issued by valgrind are incorrect - we would
  16986. + ** prefer that the randomness be increased by making use of the
  16987. + ** uninitialized space in zBuf - but valgrind errors tend to worry
  16988. + ** some users. Rather than argue, it seems easier just to initialize
  16989. + ** the whole array and silence valgrind, even if that means less randomness
  16990. + ** in the random seed.
  16991. + **
  16992. + ** When testing, initializing zBuf[] to zero is all we do. That means
  16993. + ** that we always use the same random number sequence.* This makes the
  16994. + ** tests repeatable.
  16995. + */
  16996. + memset(zBuf, 0, 256);
  16997. +#if OS_UNIX && !defined(SQLITE_TEST)
  16998. + {
  16999. + int pid;
  17000. + time((time_t*)zBuf);
  17001. + pid = getpid();
  17002. + memcpy(&zBuf[sizeof(time_t)], &pid, sizeof(pid));
  17003. + }
  17004. +#endif
  17005. +#if OS_WIN && !defined(SQLITE_TEST)
  17006. + GetSystemTime((LPSYSTEMTIME)zBuf);
  17007. +#endif
  17008. +#if OS_MAC
  17009. + {
  17010. + int pid;
  17011. + Microseconds((UnsignedWide*)zBuf);
  17012. + pid = getpid();
  17013. + memcpy(&zBuf[sizeof(UnsignedWide)], &pid, sizeof(pid));
  17014. + }
  17015. +#endif
  17016. + return SQLITE_OK;
  17017. +}
  17018. +
  17019. +/*
  17020. +** Sleep for a little while. Return the amount of time slept.
  17021. +*/
  17022. +int sqliteOsSleep(int ms){
  17023. +#if OS_UNIX
  17024. +#if defined(HAVE_USLEEP) && HAVE_USLEEP
  17025. + usleep(ms*1000);
  17026. + return ms;
  17027. +#else
  17028. + sleep((ms+999)/1000);
  17029. + return 1000*((ms+999)/1000);
  17030. +#endif
  17031. +#endif
  17032. +#if OS_WIN
  17033. + Sleep(ms);
  17034. + return ms;
  17035. +#endif
  17036. +#if OS_MAC
  17037. + UInt32 finalTicks;
  17038. + UInt32 ticks = (((UInt32)ms+16)*3)/50; /* 1/60 sec per tick */
  17039. + Delay(ticks, &finalTicks);
  17040. + return (int)((ticks*50)/3);
  17041. +#endif
  17042. +}
  17043. +
  17044. +/*
  17045. +** Static variables used for thread synchronization
  17046. +*/
  17047. +static int inMutex = 0;
  17048. +#ifdef SQLITE_UNIX_THREADS
  17049. + static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  17050. +#endif
  17051. +#ifdef SQLITE_W32_THREADS
  17052. + static CRITICAL_SECTION cs;
  17053. +#endif
  17054. +#ifdef SQLITE_MACOS_MULTITASKING
  17055. + static MPCriticalRegionID criticalRegion;
  17056. +#endif
  17057. +
  17058. +/*
  17059. +** The following pair of routine implement mutual exclusion for
  17060. +** multi-threaded processes. Only a single thread is allowed to
  17061. +** executed code that is surrounded by EnterMutex() and LeaveMutex().
  17062. +**
  17063. +** SQLite uses only a single Mutex. There is not much critical
  17064. +** code and what little there is executes quickly and without blocking.
  17065. +*/
  17066. +void sqliteOsEnterMutex(){
  17067. +#ifdef SQLITE_UNIX_THREADS
  17068. + pthread_mutex_lock(&mutex);
  17069. +#endif
  17070. +#ifdef SQLITE_W32_THREADS
  17071. + static int isInit = 0;
  17072. + while( !isInit ){
  17073. + static long lock = 0;
  17074. + if( InterlockedIncrement(&lock)==1 ){
  17075. + InitializeCriticalSection(&cs);
  17076. + isInit = 1;
  17077. + }else{
  17078. + Sleep(1);
  17079. + }
  17080. + }
  17081. + EnterCriticalSection(&cs);
  17082. +#endif
  17083. +#ifdef SQLITE_MACOS_MULTITASKING
  17084. + static volatile int notInit = 1;
  17085. + if( notInit ){
  17086. + if( notInit == 2 ) /* as close as you can get to thread safe init */
  17087. + MPYield();
  17088. + else{
  17089. + notInit = 2;
  17090. + MPCreateCriticalRegion(&criticalRegion);
  17091. + notInit = 0;
  17092. + }
  17093. + }
  17094. + MPEnterCriticalRegion(criticalRegion, kDurationForever);
  17095. +#endif
  17096. + assert( !inMutex );
  17097. + inMutex = 1;
  17098. +}
  17099. +void sqliteOsLeaveMutex(){
  17100. + assert( inMutex );
  17101. + inMutex = 0;
  17102. +#ifdef SQLITE_UNIX_THREADS
  17103. + pthread_mutex_unlock(&mutex);
  17104. +#endif
  17105. +#ifdef SQLITE_W32_THREADS
  17106. + LeaveCriticalSection(&cs);
  17107. +#endif
  17108. +#ifdef SQLITE_MACOS_MULTITASKING
  17109. + MPExitCriticalRegion(criticalRegion);
  17110. +#endif
  17111. +}
  17112. +
  17113. +/*
  17114. +** Turn a relative pathname into a full pathname. Return a pointer
  17115. +** to the full pathname stored in space obtained from sqliteMalloc().
  17116. +** The calling function is responsible for freeing this space once it
  17117. +** is no longer needed.
  17118. +*/
  17119. +char *sqliteOsFullPathname(const char *zRelative){
  17120. +#if OS_UNIX
  17121. + char *zFull = 0;
  17122. + if( zRelative[0]=='/' ){
  17123. + sqliteSetString(&zFull, zRelative, (char*)0);
  17124. + }else{
  17125. + char zBuf[5000];
  17126. + zBuf[0] = 0;
  17127. + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), "/", zRelative,
  17128. + (char*)0);
  17129. + }
  17130. + return zFull;
  17131. +#endif
  17132. +#if OS_WIN
  17133. + char *zNotUsed;
  17134. + char *zFull;
  17135. + int nByte;
  17136. + nByte = GetFullPathName(zRelative, 0, 0, &zNotUsed) + 1;
  17137. + zFull = sqliteMalloc( nByte );
  17138. + if( zFull==0 ) return 0;
  17139. + GetFullPathName(zRelative, nByte, zFull, &zNotUsed);
  17140. + return zFull;
  17141. +#endif
  17142. +#if OS_MAC
  17143. + char *zFull = 0;
  17144. + if( zRelative[0]==':' ){
  17145. + char zBuf[_MAX_PATH+1];
  17146. + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), &(zRelative[1]),
  17147. + (char*)0);
  17148. + }else{
  17149. + if( strchr(zRelative, ':') ){
  17150. + sqliteSetString(&zFull, zRelative, (char*)0);
  17151. + }else{
  17152. + char zBuf[_MAX_PATH+1];
  17153. + sqliteSetString(&zFull, getcwd(zBuf, sizeof(zBuf)), zRelative, (char*)0);
  17154. + }
  17155. + }
  17156. + return zFull;
  17157. +#endif
  17158. +}
  17159. +
  17160. +/*
  17161. +** The following variable, if set to a non-zero value, becomes the result
  17162. +** returned from sqliteOsCurrentTime(). This is used for testing.
  17163. +*/
  17164. +#ifdef SQLITE_TEST
  17165. +int sqlite_current_time = 0;
  17166. +#endif
  17167. +
  17168. +/*
  17169. +** Find the current time (in Universal Coordinated Time). Write the
  17170. +** current time and date as a Julian Day number into *prNow and
  17171. +** return 0. Return 1 if the time and date cannot be found.
  17172. +*/
  17173. +int sqliteOsCurrentTime(double *prNow){
  17174. +#if OS_UNIX
  17175. + time_t t;
  17176. + time(&t);
  17177. + *prNow = t/86400.0 + 2440587.5;
  17178. +#endif
  17179. +#if OS_WIN
  17180. + FILETIME ft;
  17181. + /* FILETIME structure is a 64-bit value representing the number of
  17182. + 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  17183. + */
  17184. + double now;
  17185. + GetSystemTimeAsFileTime( &ft );
  17186. + now = ((double)ft.dwHighDateTime) * 4294967296.0;
  17187. + *prNow = (now + ft.dwLowDateTime)/864000000000.0 + 2305813.5;
  17188. +#endif
  17189. +#ifdef SQLITE_TEST
  17190. + if( sqlite_current_time ){
  17191. + *prNow = sqlite_current_time/86400.0 + 2440587.5;
  17192. + }
  17193. +#endif
  17194. + return 0;
  17195. +}
  17196. --- /dev/null
  17197. +++ b/ext/sqlite/libsqlite/src/os.h
  17198. @@ -0,0 +1,191 @@
  17199. +/*
  17200. +** 2001 September 16
  17201. +**
  17202. +** The author disclaims copyright to this source code. In place of
  17203. +** a legal notice, here is a blessing:
  17204. +**
  17205. +** May you do good and not evil.
  17206. +** May you find forgiveness for yourself and forgive others.
  17207. +** May you share freely, never taking more than you give.
  17208. +**
  17209. +******************************************************************************
  17210. +**
  17211. +** This header file (together with is companion C source-code file
  17212. +** "os.c") attempt to abstract the underlying operating system so that
  17213. +** the SQLite library will work on both POSIX and windows systems.
  17214. +*/
  17215. +#ifndef _SQLITE_OS_H_
  17216. +#define _SQLITE_OS_H_
  17217. +
  17218. +/*
  17219. +** Helpful hint: To get this to compile on HP/UX, add -D_INCLUDE_POSIX_SOURCE
  17220. +** to the compiler command line.
  17221. +*/
  17222. +
  17223. +/*
  17224. +** These #defines should enable >2GB file support on Posix if the
  17225. +** underlying operating system supports it. If the OS lacks
  17226. +** large file support, or if the OS is windows, these should be no-ops.
  17227. +**
  17228. +** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  17229. +** on the compiler command line. This is necessary if you are compiling
  17230. +** on a recent machine (ex: RedHat 7.2) but you want your code to work
  17231. +** on an older machine (ex: RedHat 6.0). If you compile on RedHat 7.2
  17232. +** without this option, LFS is enable. But LFS does not exist in the kernel
  17233. +** in RedHat 6.0, so the code won't work. Hence, for maximum binary
  17234. +** portability you should omit LFS.
  17235. +**
  17236. +** Similar is true for MacOS. LFS is only supported on MacOS 9 and later.
  17237. +*/
  17238. +#ifndef SQLITE_DISABLE_LFS
  17239. +# define _LARGE_FILE 1
  17240. +# ifndef _FILE_OFFSET_BITS
  17241. +# define _FILE_OFFSET_BITS 64
  17242. +# endif
  17243. +# define _LARGEFILE_SOURCE 1
  17244. +#endif
  17245. +
  17246. +/*
  17247. +** Temporary files are named starting with this prefix followed by 16 random
  17248. +** alphanumeric characters, and no file extension. They are stored in the
  17249. +** OS's standard temporary file directory, and are deleted prior to exit.
  17250. +** If sqlite is being embedded in another program, you may wish to change the
  17251. +** prefix to reflect your program's name, so that if your program exits
  17252. +** prematurely, old temporary files can be easily identified. This can be done
  17253. +** using -DTEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  17254. +*/
  17255. +#ifndef TEMP_FILE_PREFIX
  17256. +# define TEMP_FILE_PREFIX "sqlite_"
  17257. +#endif
  17258. +
  17259. +/*
  17260. +** Figure out if we are dealing with Unix, Windows or MacOS.
  17261. +**
  17262. +** N.B. MacOS means Mac Classic (or Carbon). Treat Darwin (OS X) as Unix.
  17263. +** The MacOS build is designed to use CodeWarrior (tested with v8)
  17264. +*/
  17265. +#ifndef OS_UNIX
  17266. +# ifndef OS_WIN
  17267. +# ifndef OS_MAC
  17268. +# if defined(__MACOS__)
  17269. +# define OS_MAC 1
  17270. +# define OS_WIN 0
  17271. +# define OS_UNIX 0
  17272. +# elif defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
  17273. +# define OS_MAC 0
  17274. +# define OS_WIN 1
  17275. +# define OS_UNIX 0
  17276. +# else
  17277. +# define OS_MAC 0
  17278. +# define OS_WIN 0
  17279. +# define OS_UNIX 1
  17280. +# endif
  17281. +# else
  17282. +# define OS_WIN 0
  17283. +# define OS_UNIX 0
  17284. +# endif
  17285. +# else
  17286. +# define OS_MAC 0
  17287. +# define OS_UNIX 0
  17288. +# endif
  17289. +#else
  17290. +# define OS_MAC 0
  17291. +# ifndef OS_WIN
  17292. +# define OS_WIN 0
  17293. +# endif
  17294. +#endif
  17295. +
  17296. +/*
  17297. +** A handle for an open file is stored in an OsFile object.
  17298. +*/
  17299. +#if OS_UNIX
  17300. +# include <sys/types.h>
  17301. +# include <sys/stat.h>
  17302. +# include <fcntl.h>
  17303. +# include <unistd.h>
  17304. + typedef struct OsFile OsFile;
  17305. + struct OsFile {
  17306. + struct openCnt *pOpen; /* Info about all open fd's on this inode */
  17307. + struct lockInfo *pLock; /* Info about locks on this inode */
  17308. + int fd; /* The file descriptor */
  17309. + int locked; /* True if this instance holds the lock */
  17310. + int dirfd; /* File descriptor for the directory */
  17311. + };
  17312. +# define SQLITE_TEMPNAME_SIZE 200
  17313. +# if defined(HAVE_USLEEP) && HAVE_USLEEP
  17314. +# define SQLITE_MIN_SLEEP_MS 1
  17315. +# else
  17316. +# define SQLITE_MIN_SLEEP_MS 1000
  17317. +# endif
  17318. +#endif
  17319. +
  17320. +#if OS_WIN
  17321. +#include <windows.h>
  17322. +#include <winbase.h>
  17323. + typedef struct OsFile OsFile;
  17324. + struct OsFile {
  17325. + HANDLE h; /* Handle for accessing the file */
  17326. + int locked; /* 0: unlocked, <0: write lock, >0: read lock */
  17327. + };
  17328. +# if defined(_MSC_VER) || defined(__BORLANDC__)
  17329. + typedef __int64 off_t;
  17330. +# else
  17331. +# if !defined(_CYGWIN_TYPES_H)
  17332. + typedef long long off_t;
  17333. +# if defined(__MINGW32__)
  17334. +# define _OFF_T_
  17335. +# endif
  17336. +# endif
  17337. +# endif
  17338. +# define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
  17339. +# define SQLITE_MIN_SLEEP_MS 1
  17340. +#endif
  17341. +
  17342. +#if OS_MAC
  17343. +# include <unistd.h>
  17344. +# include <Files.h>
  17345. + typedef struct OsFile OsFile;
  17346. + struct OsFile {
  17347. + SInt16 refNum; /* Data fork/file reference number */
  17348. + SInt16 refNumRF; /* Resource fork reference number (for locking) */
  17349. + int locked; /* 0: unlocked, <0: write lock, >0: read lock */
  17350. + int delOnClose; /* True if file is to be deleted on close */
  17351. + char *pathToDel; /* Name of file to delete on close */
  17352. + };
  17353. +# ifdef _LARGE_FILE
  17354. + typedef SInt64 off_t;
  17355. +# else
  17356. + typedef SInt32 off_t;
  17357. +# endif
  17358. +# define SQLITE_TEMPNAME_SIZE _MAX_PATH
  17359. +# define SQLITE_MIN_SLEEP_MS 17
  17360. +#endif
  17361. +
  17362. +int sqliteOsDelete(const char*);
  17363. +int sqliteOsFileExists(const char*);
  17364. +int sqliteOsFileRename(const char*, const char*);
  17365. +int sqliteOsOpenReadWrite(const char*, OsFile*, int*);
  17366. +int sqliteOsOpenExclusive(const char*, OsFile*, int);
  17367. +int sqliteOsOpenReadOnly(const char*, OsFile*);
  17368. +int sqliteOsOpenDirectory(const char*, OsFile*);
  17369. +int sqliteOsTempFileName(char*);
  17370. +int sqliteOsClose(OsFile*);
  17371. +int sqliteOsRead(OsFile*, void*, int amt);
  17372. +int sqliteOsWrite(OsFile*, const void*, int amt);
  17373. +int sqliteOsSeek(OsFile*, off_t offset);
  17374. +int sqliteOsSync(OsFile*);
  17375. +int sqliteOsTruncate(OsFile*, off_t size);
  17376. +int sqliteOsFileSize(OsFile*, off_t *pSize);
  17377. +int sqliteOsReadLock(OsFile*);
  17378. +int sqliteOsWriteLock(OsFile*);
  17379. +int sqliteOsUnlock(OsFile*);
  17380. +int sqliteOsRandomSeed(char*);
  17381. +int sqliteOsSleep(int ms);
  17382. +int sqliteOsCurrentTime(double*);
  17383. +void sqliteOsEnterMutex(void);
  17384. +void sqliteOsLeaveMutex(void);
  17385. +char *sqliteOsFullPathname(const char*);
  17386. +
  17387. +
  17388. +
  17389. +#endif /* _SQLITE_OS_H_ */
  17390. --- /dev/null
  17391. +++ b/ext/sqlite/libsqlite/src/pager.c
  17392. @@ -0,0 +1,2220 @@
  17393. +/*
  17394. +** 2001 September 15
  17395. +**
  17396. +** The author disclaims copyright to this source code. In place of
  17397. +** a legal notice, here is a blessing:
  17398. +**
  17399. +** May you do good and not evil.
  17400. +** May you find forgiveness for yourself and forgive others.
  17401. +** May you share freely, never taking more than you give.
  17402. +**
  17403. +*************************************************************************
  17404. +** This is the implementation of the page cache subsystem or "pager".
  17405. +**
  17406. +** The pager is used to access a database disk file. It implements
  17407. +** atomic commit and rollback through the use of a journal file that
  17408. +** is separate from the database file. The pager also implements file
  17409. +** locking to prevent two processes from writing the same database
  17410. +** file simultaneously, or one process from reading the database while
  17411. +** another is writing.
  17412. +**
  17413. +** @(#) $Id$
  17414. +*/
  17415. +#include "os.h" /* Must be first to enable large file support */
  17416. +#include "sqliteInt.h"
  17417. +#include "pager.h"
  17418. +#include <assert.h>
  17419. +#include <string.h>
  17420. +
  17421. +/*
  17422. +** Macros for troubleshooting. Normally turned off
  17423. +*/
  17424. +#if 0
  17425. +static Pager *mainPager = 0;
  17426. +#define SET_PAGER(X) if( mainPager==0 ) mainPager = (X)
  17427. +#define CLR_PAGER(X) if( mainPager==(X) ) mainPager = 0
  17428. +#define TRACE1(X) if( pPager==mainPager ) fprintf(stderr,X)
  17429. +#define TRACE2(X,Y) if( pPager==mainPager ) fprintf(stderr,X,Y)
  17430. +#define TRACE3(X,Y,Z) if( pPager==mainPager ) fprintf(stderr,X,Y,Z)
  17431. +#else
  17432. +#define SET_PAGER(X)
  17433. +#define CLR_PAGER(X)
  17434. +#define TRACE1(X)
  17435. +#define TRACE2(X,Y)
  17436. +#define TRACE3(X,Y,Z)
  17437. +#endif
  17438. +
  17439. +
  17440. +/*
  17441. +** The page cache as a whole is always in one of the following
  17442. +** states:
  17443. +**
  17444. +** SQLITE_UNLOCK The page cache is not currently reading or
  17445. +** writing the database file. There is no
  17446. +** data held in memory. This is the initial
  17447. +** state.
  17448. +**
  17449. +** SQLITE_READLOCK The page cache is reading the database.
  17450. +** Writing is not permitted. There can be
  17451. +** multiple readers accessing the same database
  17452. +** file at the same time.
  17453. +**
  17454. +** SQLITE_WRITELOCK The page cache is writing the database.
  17455. +** Access is exclusive. No other processes or
  17456. +** threads can be reading or writing while one
  17457. +** process is writing.
  17458. +**
  17459. +** The page cache comes up in SQLITE_UNLOCK. The first time a
  17460. +** sqlite_page_get() occurs, the state transitions to SQLITE_READLOCK.
  17461. +** After all pages have been released using sqlite_page_unref(),
  17462. +** the state transitions back to SQLITE_UNLOCK. The first time
  17463. +** that sqlite_page_write() is called, the state transitions to
  17464. +** SQLITE_WRITELOCK. (Note that sqlite_page_write() can only be
  17465. +** called on an outstanding page which means that the pager must
  17466. +** be in SQLITE_READLOCK before it transitions to SQLITE_WRITELOCK.)
  17467. +** The sqlite_page_rollback() and sqlite_page_commit() functions
  17468. +** transition the state from SQLITE_WRITELOCK back to SQLITE_READLOCK.
  17469. +*/
  17470. +#define SQLITE_UNLOCK 0
  17471. +#define SQLITE_READLOCK 1
  17472. +#define SQLITE_WRITELOCK 2
  17473. +
  17474. +
  17475. +/*
  17476. +** Each in-memory image of a page begins with the following header.
  17477. +** This header is only visible to this pager module. The client
  17478. +** code that calls pager sees only the data that follows the header.
  17479. +**
  17480. +** Client code should call sqlitepager_write() on a page prior to making
  17481. +** any modifications to that page. The first time sqlitepager_write()
  17482. +** is called, the original page contents are written into the rollback
  17483. +** journal and PgHdr.inJournal and PgHdr.needSync are set. Later, once
  17484. +** the journal page has made it onto the disk surface, PgHdr.needSync
  17485. +** is cleared. The modified page cannot be written back into the original
  17486. +** database file until the journal pages has been synced to disk and the
  17487. +** PgHdr.needSync has been cleared.
  17488. +**
  17489. +** The PgHdr.dirty flag is set when sqlitepager_write() is called and
  17490. +** is cleared again when the page content is written back to the original
  17491. +** database file.
  17492. +*/
  17493. +typedef struct PgHdr PgHdr;
  17494. +struct PgHdr {
  17495. + Pager *pPager; /* The pager to which this page belongs */
  17496. + Pgno pgno; /* The page number for this page */
  17497. + PgHdr *pNextHash, *pPrevHash; /* Hash collision chain for PgHdr.pgno */
  17498. + int nRef; /* Number of users of this page */
  17499. + PgHdr *pNextFree, *pPrevFree; /* Freelist of pages where nRef==0 */
  17500. + PgHdr *pNextAll, *pPrevAll; /* A list of all pages */
  17501. + PgHdr *pNextCkpt, *pPrevCkpt; /* List of pages in the checkpoint journal */
  17502. + u8 inJournal; /* TRUE if has been written to journal */
  17503. + u8 inCkpt; /* TRUE if written to the checkpoint journal */
  17504. + u8 dirty; /* TRUE if we need to write back changes */
  17505. + u8 needSync; /* Sync journal before writing this page */
  17506. + u8 alwaysRollback; /* Disable dont_rollback() for this page */
  17507. + PgHdr *pDirty; /* Dirty pages sorted by PgHdr.pgno */
  17508. + /* SQLITE_PAGE_SIZE bytes of page data follow this header */
  17509. + /* Pager.nExtra bytes of local data follow the page data */
  17510. +};
  17511. +
  17512. +
  17513. +/*
  17514. +** A macro used for invoking the codec if there is one
  17515. +*/
  17516. +#ifdef SQLITE_HAS_CODEC
  17517. +# define CODEC(P,D,N,X) if( P->xCodec ){ P->xCodec(P->pCodecArg,D,N,X); }
  17518. +#else
  17519. +# define CODEC(P,D,N,X)
  17520. +#endif
  17521. +
  17522. +/*
  17523. +** Convert a pointer to a PgHdr into a pointer to its data
  17524. +** and back again.
  17525. +*/
  17526. +#define PGHDR_TO_DATA(P) ((void*)(&(P)[1]))
  17527. +#define DATA_TO_PGHDR(D) (&((PgHdr*)(D))[-1])
  17528. +#define PGHDR_TO_EXTRA(P) ((void*)&((char*)(&(P)[1]))[SQLITE_PAGE_SIZE])
  17529. +
  17530. +/*
  17531. +** How big to make the hash table used for locating in-memory pages
  17532. +** by page number.
  17533. +*/
  17534. +#define N_PG_HASH 2048
  17535. +
  17536. +/*
  17537. +** Hash a page number
  17538. +*/
  17539. +#define pager_hash(PN) ((PN)&(N_PG_HASH-1))
  17540. +
  17541. +/*
  17542. +** A open page cache is an instance of the following structure.
  17543. +*/
  17544. +struct Pager {
  17545. + char *zFilename; /* Name of the database file */
  17546. + char *zJournal; /* Name of the journal file */
  17547. + char *zDirectory; /* Directory hold database and journal files */
  17548. + OsFile fd, jfd; /* File descriptors for database and journal */
  17549. + OsFile cpfd; /* File descriptor for the checkpoint journal */
  17550. + int dbSize; /* Number of pages in the file */
  17551. + int origDbSize; /* dbSize before the current change */
  17552. + int ckptSize; /* Size of database (in pages) at ckpt_begin() */
  17553. + off_t ckptJSize; /* Size of journal at ckpt_begin() */
  17554. + int nRec; /* Number of pages written to the journal */
  17555. + u32 cksumInit; /* Quasi-random value added to every checksum */
  17556. + int ckptNRec; /* Number of records in the checkpoint journal */
  17557. + int nExtra; /* Add this many bytes to each in-memory page */
  17558. + void (*xDestructor)(void*); /* Call this routine when freeing pages */
  17559. + int nPage; /* Total number of in-memory pages */
  17560. + int nRef; /* Number of in-memory pages with PgHdr.nRef>0 */
  17561. + int mxPage; /* Maximum number of pages to hold in cache */
  17562. + int nHit, nMiss, nOvfl; /* Cache hits, missing, and LRU overflows */
  17563. + void (*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  17564. + void *pCodecArg; /* First argument to xCodec() */
  17565. + u8 journalOpen; /* True if journal file descriptors is valid */
  17566. + u8 journalStarted; /* True if header of journal is synced */
  17567. + u8 useJournal; /* Use a rollback journal on this file */
  17568. + u8 ckptOpen; /* True if the checkpoint journal is open */
  17569. + u8 ckptInUse; /* True we are in a checkpoint */
  17570. + u8 ckptAutoopen; /* Open ckpt journal when main journal is opened*/
  17571. + u8 noSync; /* Do not sync the journal if true */
  17572. + u8 fullSync; /* Do extra syncs of the journal for robustness */
  17573. + u8 state; /* SQLITE_UNLOCK, _READLOCK or _WRITELOCK */
  17574. + u8 errMask; /* One of several kinds of errors */
  17575. + u8 tempFile; /* zFilename is a temporary file */
  17576. + u8 readOnly; /* True for a read-only database */
  17577. + u8 needSync; /* True if an fsync() is needed on the journal */
  17578. + u8 dirtyFile; /* True if database file has changed in any way */
  17579. + u8 alwaysRollback; /* Disable dont_rollback() for all pages */
  17580. + u8 *aInJournal; /* One bit for each page in the database file */
  17581. + u8 *aInCkpt; /* One bit for each page in the database */
  17582. + PgHdr *pFirst, *pLast; /* List of free pages */
  17583. + PgHdr *pFirstSynced; /* First free page with PgHdr.needSync==0 */
  17584. + PgHdr *pAll; /* List of all pages */
  17585. + PgHdr *pCkpt; /* List of pages in the checkpoint journal */
  17586. + PgHdr *aHash[N_PG_HASH]; /* Hash table to map page number of PgHdr */
  17587. +};
  17588. +
  17589. +/*
  17590. +** These are bits that can be set in Pager.errMask.
  17591. +*/
  17592. +#define PAGER_ERR_FULL 0x01 /* a write() failed */
  17593. +#define PAGER_ERR_MEM 0x02 /* malloc() failed */
  17594. +#define PAGER_ERR_LOCK 0x04 /* error in the locking protocol */
  17595. +#define PAGER_ERR_CORRUPT 0x08 /* database or journal corruption */
  17596. +#define PAGER_ERR_DISK 0x10 /* general disk I/O error - bad hard drive? */
  17597. +
  17598. +/*
  17599. +** The journal file contains page records in the following
  17600. +** format.
  17601. +**
  17602. +** Actually, this structure is the complete page record for pager
  17603. +** formats less than 3. Beginning with format 3, this record is surrounded
  17604. +** by two checksums.
  17605. +*/
  17606. +typedef struct PageRecord PageRecord;
  17607. +struct PageRecord {
  17608. + Pgno pgno; /* The page number */
  17609. + char aData[SQLITE_PAGE_SIZE]; /* Original data for page pgno */
  17610. +};
  17611. +
  17612. +/*
  17613. +** Journal files begin with the following magic string. The data
  17614. +** was obtained from /dev/random. It is used only as a sanity check.
  17615. +**
  17616. +** There are three journal formats (so far). The 1st journal format writes
  17617. +** 32-bit integers in the byte-order of the host machine. New
  17618. +** formats writes integers as big-endian. All new journals use the
  17619. +** new format, but we have to be able to read an older journal in order
  17620. +** to rollback journals created by older versions of the library.
  17621. +**
  17622. +** The 3rd journal format (added for 2.8.0) adds additional sanity
  17623. +** checking information to the journal. If the power fails while the
  17624. +** journal is being written, semi-random garbage data might appear in
  17625. +** the journal file after power is restored. If an attempt is then made
  17626. +** to roll the journal back, the database could be corrupted. The additional
  17627. +** sanity checking data is an attempt to discover the garbage in the
  17628. +** journal and ignore it.
  17629. +**
  17630. +** The sanity checking information for the 3rd journal format consists
  17631. +** of a 32-bit checksum on each page of data. The checksum covers both
  17632. +** the page number and the SQLITE_PAGE_SIZE bytes of data for the page.
  17633. +** This cksum is initialized to a 32-bit random value that appears in the
  17634. +** journal file right after the header. The random initializer is important,
  17635. +** because garbage data that appears at the end of a journal is likely
  17636. +** data that was once in other files that have now been deleted. If the
  17637. +** garbage data came from an obsolete journal file, the checksums might
  17638. +** be correct. But by initializing the checksum to random value which
  17639. +** is different for every journal, we minimize that risk.
  17640. +*/
  17641. +static const unsigned char aJournalMagic1[] = {
  17642. + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd4,
  17643. +};
  17644. +static const unsigned char aJournalMagic2[] = {
  17645. + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd5,
  17646. +};
  17647. +static const unsigned char aJournalMagic3[] = {
  17648. + 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd6,
  17649. +};
  17650. +#define JOURNAL_FORMAT_1 1
  17651. +#define JOURNAL_FORMAT_2 2
  17652. +#define JOURNAL_FORMAT_3 3
  17653. +
  17654. +/*
  17655. +** The following integer determines what format to use when creating
  17656. +** new primary journal files. By default we always use format 3.
  17657. +** When testing, we can set this value to older journal formats in order to
  17658. +** make sure that newer versions of the library are able to rollback older
  17659. +** journal files.
  17660. +**
  17661. +** Note that checkpoint journals always use format 2 and omit the header.
  17662. +*/
  17663. +#ifdef SQLITE_TEST
  17664. +int journal_format = 3;
  17665. +#else
  17666. +# define journal_format 3
  17667. +#endif
  17668. +
  17669. +/*
  17670. +** The size of the header and of each page in the journal varies according
  17671. +** to which journal format is being used. The following macros figure out
  17672. +** the sizes based on format numbers.
  17673. +*/
  17674. +#define JOURNAL_HDR_SZ(X) \
  17675. + (sizeof(aJournalMagic1) + sizeof(Pgno) + ((X)>=3)*2*sizeof(u32))
  17676. +#define JOURNAL_PG_SZ(X) \
  17677. + (SQLITE_PAGE_SIZE + sizeof(Pgno) + ((X)>=3)*sizeof(u32))
  17678. +
  17679. +/*
  17680. +** Enable reference count tracking here:
  17681. +*/
  17682. +#ifdef SQLITE_TEST
  17683. + int pager_refinfo_enable = 0;
  17684. + static void pager_refinfo(PgHdr *p){
  17685. + static int cnt = 0;
  17686. + if( !pager_refinfo_enable ) return;
  17687. + printf(
  17688. + "REFCNT: %4d addr=0x%08x nRef=%d\n",
  17689. + p->pgno, (int)PGHDR_TO_DATA(p), p->nRef
  17690. + );
  17691. + cnt++; /* Something to set a breakpoint on */
  17692. + }
  17693. +# define REFINFO(X) pager_refinfo(X)
  17694. +#else
  17695. +# define REFINFO(X)
  17696. +#endif
  17697. +
  17698. +/*
  17699. +** Read a 32-bit integer from the given file descriptor. Store the integer
  17700. +** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  17701. +** error code is something goes wrong.
  17702. +**
  17703. +** If the journal format is 2 or 3, read a big-endian integer. If the
  17704. +** journal format is 1, read an integer in the native byte-order of the
  17705. +** host machine.
  17706. +*/
  17707. +static int read32bits(int format, OsFile *fd, u32 *pRes){
  17708. + u32 res;
  17709. + int rc;
  17710. + rc = sqliteOsRead(fd, &res, sizeof(res));
  17711. + if( rc==SQLITE_OK && format>JOURNAL_FORMAT_1 ){
  17712. + unsigned char ac[4];
  17713. + memcpy(ac, &res, 4);
  17714. + res = (ac[0]<<24) | (ac[1]<<16) | (ac[2]<<8) | ac[3];
  17715. + }
  17716. + *pRes = res;
  17717. + return rc;
  17718. +}
  17719. +
  17720. +/*
  17721. +** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  17722. +** on success or an error code is something goes wrong.
  17723. +**
  17724. +** If the journal format is 2 or 3, write the integer as 4 big-endian
  17725. +** bytes. If the journal format is 1, write the integer in the native
  17726. +** byte order. In normal operation, only formats 2 and 3 are used.
  17727. +** Journal format 1 is only used for testing.
  17728. +*/
  17729. +static int write32bits(OsFile *fd, u32 val){
  17730. + unsigned char ac[4];
  17731. + if( journal_format<=1 ){
  17732. + return sqliteOsWrite(fd, &val, 4);
  17733. + }
  17734. + ac[0] = (val>>24) & 0xff;
  17735. + ac[1] = (val>>16) & 0xff;
  17736. + ac[2] = (val>>8) & 0xff;
  17737. + ac[3] = val & 0xff;
  17738. + return sqliteOsWrite(fd, ac, 4);
  17739. +}
  17740. +
  17741. +/*
  17742. +** Write a 32-bit integer into a page header right before the
  17743. +** page data. This will overwrite the PgHdr.pDirty pointer.
  17744. +**
  17745. +** The integer is big-endian for formats 2 and 3 and native byte order
  17746. +** for journal format 1.
  17747. +*/
  17748. +static void store32bits(u32 val, PgHdr *p, int offset){
  17749. + unsigned char *ac;
  17750. + ac = &((unsigned char*)PGHDR_TO_DATA(p))[offset];
  17751. + if( journal_format<=1 ){
  17752. + memcpy(ac, &val, 4);
  17753. + }else{
  17754. + ac[0] = (val>>24) & 0xff;
  17755. + ac[1] = (val>>16) & 0xff;
  17756. + ac[2] = (val>>8) & 0xff;
  17757. + ac[3] = val & 0xff;
  17758. + }
  17759. +}
  17760. +
  17761. +
  17762. +/*
  17763. +** Convert the bits in the pPager->errMask into an approprate
  17764. +** return code.
  17765. +*/
  17766. +static int pager_errcode(Pager *pPager){
  17767. + int rc = SQLITE_OK;
  17768. + if( pPager->errMask & PAGER_ERR_LOCK ) rc = SQLITE_PROTOCOL;
  17769. + if( pPager->errMask & PAGER_ERR_DISK ) rc = SQLITE_IOERR;
  17770. + if( pPager->errMask & PAGER_ERR_FULL ) rc = SQLITE_FULL;
  17771. + if( pPager->errMask & PAGER_ERR_MEM ) rc = SQLITE_NOMEM;
  17772. + if( pPager->errMask & PAGER_ERR_CORRUPT ) rc = SQLITE_CORRUPT;
  17773. + return rc;
  17774. +}
  17775. +
  17776. +/*
  17777. +** Add or remove a page from the list of all pages that are in the
  17778. +** checkpoint journal.
  17779. +**
  17780. +** The Pager keeps a separate list of pages that are currently in
  17781. +** the checkpoint journal. This helps the sqlitepager_ckpt_commit()
  17782. +** routine run MUCH faster for the common case where there are many
  17783. +** pages in memory but only a few are in the checkpoint journal.
  17784. +*/
  17785. +static void page_add_to_ckpt_list(PgHdr *pPg){
  17786. + Pager *pPager = pPg->pPager;
  17787. + if( pPg->inCkpt ) return;
  17788. + assert( pPg->pPrevCkpt==0 && pPg->pNextCkpt==0 );
  17789. + pPg->pPrevCkpt = 0;
  17790. + if( pPager->pCkpt ){
  17791. + pPager->pCkpt->pPrevCkpt = pPg;
  17792. + }
  17793. + pPg->pNextCkpt = pPager->pCkpt;
  17794. + pPager->pCkpt = pPg;
  17795. + pPg->inCkpt = 1;
  17796. +}
  17797. +static void page_remove_from_ckpt_list(PgHdr *pPg){
  17798. + if( !pPg->inCkpt ) return;
  17799. + if( pPg->pPrevCkpt ){
  17800. + assert( pPg->pPrevCkpt->pNextCkpt==pPg );
  17801. + pPg->pPrevCkpt->pNextCkpt = pPg->pNextCkpt;
  17802. + }else{
  17803. + assert( pPg->pPager->pCkpt==pPg );
  17804. + pPg->pPager->pCkpt = pPg->pNextCkpt;
  17805. + }
  17806. + if( pPg->pNextCkpt ){
  17807. + assert( pPg->pNextCkpt->pPrevCkpt==pPg );
  17808. + pPg->pNextCkpt->pPrevCkpt = pPg->pPrevCkpt;
  17809. + }
  17810. + pPg->pNextCkpt = 0;
  17811. + pPg->pPrevCkpt = 0;
  17812. + pPg->inCkpt = 0;
  17813. +}
  17814. +
  17815. +/*
  17816. +** Find a page in the hash table given its page number. Return
  17817. +** a pointer to the page or NULL if not found.
  17818. +*/
  17819. +static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
  17820. + PgHdr *p = pPager->aHash[pager_hash(pgno)];
  17821. + while( p && p->pgno!=pgno ){
  17822. + p = p->pNextHash;
  17823. + }
  17824. + return p;
  17825. +}
  17826. +
  17827. +/*
  17828. +** Unlock the database and clear the in-memory cache. This routine
  17829. +** sets the state of the pager back to what it was when it was first
  17830. +** opened. Any outstanding pages are invalidated and subsequent attempts
  17831. +** to access those pages will likely result in a coredump.
  17832. +*/
  17833. +static void pager_reset(Pager *pPager){
  17834. + PgHdr *pPg, *pNext;
  17835. + for(pPg=pPager->pAll; pPg; pPg=pNext){
  17836. + pNext = pPg->pNextAll;
  17837. + sqliteFree(pPg);
  17838. + }
  17839. + pPager->pFirst = 0;
  17840. + pPager->pFirstSynced = 0;
  17841. + pPager->pLast = 0;
  17842. + pPager->pAll = 0;
  17843. + memset(pPager->aHash, 0, sizeof(pPager->aHash));
  17844. + pPager->nPage = 0;
  17845. + if( pPager->state>=SQLITE_WRITELOCK ){
  17846. + sqlitepager_rollback(pPager);
  17847. + }
  17848. + sqliteOsUnlock(&pPager->fd);
  17849. + pPager->state = SQLITE_UNLOCK;
  17850. + pPager->dbSize = -1;
  17851. + pPager->nRef = 0;
  17852. + assert( pPager->journalOpen==0 );
  17853. +}
  17854. +
  17855. +/*
  17856. +** When this routine is called, the pager has the journal file open and
  17857. +** a write lock on the database. This routine releases the database
  17858. +** write lock and acquires a read lock in its place. The journal file
  17859. +** is deleted and closed.
  17860. +**
  17861. +** TODO: Consider keeping the journal file open for temporary databases.
  17862. +** This might give a performance improvement on windows where opening
  17863. +** a file is an expensive operation.
  17864. +*/
  17865. +static int pager_unwritelock(Pager *pPager){
  17866. + int rc;
  17867. + PgHdr *pPg;
  17868. + if( pPager->state<SQLITE_WRITELOCK ) return SQLITE_OK;
  17869. + sqlitepager_ckpt_commit(pPager);
  17870. + if( pPager->ckptOpen ){
  17871. + sqliteOsClose(&pPager->cpfd);
  17872. + pPager->ckptOpen = 0;
  17873. + }
  17874. + if( pPager->journalOpen ){
  17875. + sqliteOsClose(&pPager->jfd);
  17876. + pPager->journalOpen = 0;
  17877. + sqliteOsDelete(pPager->zJournal);
  17878. + sqliteFree( pPager->aInJournal );
  17879. + pPager->aInJournal = 0;
  17880. + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
  17881. + pPg->inJournal = 0;
  17882. + pPg->dirty = 0;
  17883. + pPg->needSync = 0;
  17884. + }
  17885. + }else{
  17886. + assert( pPager->dirtyFile==0 || pPager->useJournal==0 );
  17887. + }
  17888. + rc = sqliteOsReadLock(&pPager->fd);
  17889. + if( rc==SQLITE_OK ){
  17890. + pPager->state = SQLITE_READLOCK;
  17891. + }else{
  17892. + /* This can only happen if a process does a BEGIN, then forks and the
  17893. + ** child process does the COMMIT. Because of the semantics of unix
  17894. + ** file locking, the unlock will fail.
  17895. + */
  17896. + pPager->state = SQLITE_UNLOCK;
  17897. + }
  17898. + return rc;
  17899. +}
  17900. +
  17901. +/*
  17902. +** Compute and return a checksum for the page of data.
  17903. +**
  17904. +** This is not a real checksum. It is really just the sum of the
  17905. +** random initial value and the page number. We considered do a checksum
  17906. +** of the database, but that was found to be too slow.
  17907. +*/
  17908. +static u32 pager_cksum(Pager *pPager, Pgno pgno, const char *aData){
  17909. + u32 cksum = pPager->cksumInit + pgno;
  17910. + return cksum;
  17911. +}
  17912. +
  17913. +/*
  17914. +** Read a single page from the journal file opened on file descriptor
  17915. +** jfd. Playback this one page.
  17916. +**
  17917. +** There are three different journal formats. The format parameter determines
  17918. +** which format is used by the journal that is played back.
  17919. +*/
  17920. +static int pager_playback_one_page(Pager *pPager, OsFile *jfd, int format){
  17921. + int rc;
  17922. + PgHdr *pPg; /* An existing page in the cache */
  17923. + PageRecord pgRec;
  17924. + u32 cksum;
  17925. +
  17926. + rc = read32bits(format, jfd, &pgRec.pgno);
  17927. + if( rc!=SQLITE_OK ) return rc;
  17928. + rc = sqliteOsRead(jfd, &pgRec.aData, sizeof(pgRec.aData));
  17929. + if( rc!=SQLITE_OK ) return rc;
  17930. +
  17931. + /* Sanity checking on the page. This is more important that I originally
  17932. + ** thought. If a power failure occurs while the journal is being written,
  17933. + ** it could cause invalid data to be written into the journal. We need to
  17934. + ** detect this invalid data (with high probability) and ignore it.
  17935. + */
  17936. + if( pgRec.pgno==0 ){
  17937. + return SQLITE_DONE;
  17938. + }
  17939. + if( pgRec.pgno>(unsigned)pPager->dbSize ){
  17940. + return SQLITE_OK;
  17941. + }
  17942. + if( format>=JOURNAL_FORMAT_3 ){
  17943. + rc = read32bits(format, jfd, &cksum);
  17944. + if( rc ) return rc;
  17945. + if( pager_cksum(pPager, pgRec.pgno, pgRec.aData)!=cksum ){
  17946. + return SQLITE_DONE;
  17947. + }
  17948. + }
  17949. +
  17950. + /* Playback the page. Update the in-memory copy of the page
  17951. + ** at the same time, if there is one.
  17952. + */
  17953. + pPg = pager_lookup(pPager, pgRec.pgno);
  17954. + TRACE2("PLAYBACK %d\n", pgRec.pgno);
  17955. + sqliteOsSeek(&pPager->fd, (pgRec.pgno-1)*(off_t)SQLITE_PAGE_SIZE);
  17956. + rc = sqliteOsWrite(&pPager->fd, pgRec.aData, SQLITE_PAGE_SIZE);
  17957. + if( pPg ){
  17958. + /* No page should ever be rolled back that is in use, except for page
  17959. + ** 1 which is held in use in order to keep the lock on the database
  17960. + ** active.
  17961. + */
  17962. + assert( pPg->nRef==0 || pPg->pgno==1 );
  17963. + memcpy(PGHDR_TO_DATA(pPg), pgRec.aData, SQLITE_PAGE_SIZE);
  17964. + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
  17965. + pPg->dirty = 0;
  17966. + pPg->needSync = 0;
  17967. + CODEC(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
  17968. + }
  17969. + return rc;
  17970. +}
  17971. +
  17972. +/*
  17973. +** Playback the journal and thus restore the database file to
  17974. +** the state it was in before we started making changes.
  17975. +**
  17976. +** The journal file format is as follows:
  17977. +**
  17978. +** * 8 byte prefix. One of the aJournalMagic123 vectors defined
  17979. +** above. The format of the journal file is determined by which
  17980. +** of the three prefix vectors is seen.
  17981. +** * 4 byte big-endian integer which is the number of valid page records
  17982. +** in the journal. If this value is 0xffffffff, then compute the
  17983. +** number of page records from the journal size. This field appears
  17984. +** in format 3 only.
  17985. +** * 4 byte big-endian integer which is the initial value for the
  17986. +** sanity checksum. This field appears in format 3 only.
  17987. +** * 4 byte integer which is the number of pages to truncate the
  17988. +** database to during a rollback.
  17989. +** * Zero or more pages instances, each as follows:
  17990. +** + 4 byte page number.
  17991. +** + SQLITE_PAGE_SIZE bytes of data.
  17992. +** + 4 byte checksum (format 3 only)
  17993. +**
  17994. +** When we speak of the journal header, we mean the first 4 bullets above.
  17995. +** Each entry in the journal is an instance of the 5th bullet. Note that
  17996. +** bullets 2 and 3 only appear in format-3 journals.
  17997. +**
  17998. +** Call the value from the second bullet "nRec". nRec is the number of
  17999. +** valid page entries in the journal. In most cases, you can compute the
  18000. +** value of nRec from the size of the journal file. But if a power
  18001. +** failure occurred while the journal was being written, it could be the
  18002. +** case that the size of the journal file had already been increased but
  18003. +** the extra entries had not yet made it safely to disk. In such a case,
  18004. +** the value of nRec computed from the file size would be too large. For
  18005. +** that reason, we always use the nRec value in the header.
  18006. +**
  18007. +** If the nRec value is 0xffffffff it means that nRec should be computed
  18008. +** from the file size. This value is used when the user selects the
  18009. +** no-sync option for the journal. A power failure could lead to corruption
  18010. +** in this case. But for things like temporary table (which will be
  18011. +** deleted when the power is restored) we don't care.
  18012. +**
  18013. +** Journal formats 1 and 2 do not have an nRec value in the header so we
  18014. +** have to compute nRec from the file size. This has risks (as described
  18015. +** above) which is why all persistent tables have been changed to use
  18016. +** format 3.
  18017. +**
  18018. +** If the file opened as the journal file is not a well-formed
  18019. +** journal file then the database will likely already be
  18020. +** corrupted, so the PAGER_ERR_CORRUPT bit is set in pPager->errMask
  18021. +** and SQLITE_CORRUPT is returned. If it all works, then this routine
  18022. +** returns SQLITE_OK.
  18023. +*/
  18024. +static int pager_playback(Pager *pPager, int useJournalSize){
  18025. + off_t szJ; /* Size of the journal file in bytes */
  18026. + int nRec; /* Number of Records in the journal */
  18027. + int i; /* Loop counter */
  18028. + Pgno mxPg = 0; /* Size of the original file in pages */
  18029. + int format; /* Format of the journal file. */
  18030. + unsigned char aMagic[sizeof(aJournalMagic1)];
  18031. + int rc;
  18032. +
  18033. + /* Figure out how many records are in the journal. Abort early if
  18034. + ** the journal is empty.
  18035. + */
  18036. + assert( pPager->journalOpen );
  18037. + sqliteOsSeek(&pPager->jfd, 0);
  18038. + rc = sqliteOsFileSize(&pPager->jfd, &szJ);
  18039. + if( rc!=SQLITE_OK ){
  18040. + goto end_playback;
  18041. + }
  18042. +
  18043. + /* If the journal file is too small to contain a complete header,
  18044. + ** it must mean that the process that created the journal was just
  18045. + ** beginning to write the journal file when it died. In that case,
  18046. + ** the database file should have still been completely unchanged.
  18047. + ** Nothing needs to be rolled back. We can safely ignore this journal.
  18048. + */
  18049. + if( szJ < sizeof(aMagic)+sizeof(Pgno) ){
  18050. + goto end_playback;
  18051. + }
  18052. +
  18053. + /* Read the beginning of the journal and truncate the
  18054. + ** database file back to its original size.
  18055. + */
  18056. + rc = sqliteOsRead(&pPager->jfd, aMagic, sizeof(aMagic));
  18057. + if( rc!=SQLITE_OK ){
  18058. + rc = SQLITE_PROTOCOL;
  18059. + goto end_playback;
  18060. + }
  18061. + if( memcmp(aMagic, aJournalMagic3, sizeof(aMagic))==0 ){
  18062. + format = JOURNAL_FORMAT_3;
  18063. + }else if( memcmp(aMagic, aJournalMagic2, sizeof(aMagic))==0 ){
  18064. + format = JOURNAL_FORMAT_2;
  18065. + }else if( memcmp(aMagic, aJournalMagic1, sizeof(aMagic))==0 ){
  18066. + format = JOURNAL_FORMAT_1;
  18067. + }else{
  18068. + rc = SQLITE_PROTOCOL;
  18069. + goto end_playback;
  18070. + }
  18071. + if( format>=JOURNAL_FORMAT_3 ){
  18072. + if( szJ < sizeof(aMagic) + 3*sizeof(u32) ){
  18073. + /* Ignore the journal if it is too small to contain a complete
  18074. + ** header. We already did this test once above, but at the prior
  18075. + ** test, we did not know the journal format and so we had to assume
  18076. + ** the smallest possible header. Now we know the header is bigger
  18077. + ** than the minimum so we test again.
  18078. + */
  18079. + goto end_playback;
  18080. + }
  18081. + rc = read32bits(format, &pPager->jfd, (u32*)&nRec);
  18082. + if( rc ) goto end_playback;
  18083. + rc = read32bits(format, &pPager->jfd, &pPager->cksumInit);
  18084. + if( rc ) goto end_playback;
  18085. + if( nRec==0xffffffff || useJournalSize ){
  18086. + nRec = (szJ - JOURNAL_HDR_SZ(3))/JOURNAL_PG_SZ(3);
  18087. + }
  18088. + }else{
  18089. + nRec = (szJ - JOURNAL_HDR_SZ(2))/JOURNAL_PG_SZ(2);
  18090. + assert( nRec*JOURNAL_PG_SZ(2)+JOURNAL_HDR_SZ(2)==szJ );
  18091. + }
  18092. + rc = read32bits(format, &pPager->jfd, &mxPg);
  18093. + if( rc!=SQLITE_OK ){
  18094. + goto end_playback;
  18095. + }
  18096. + assert( pPager->origDbSize==0 || pPager->origDbSize==mxPg );
  18097. + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)mxPg);
  18098. + if( rc!=SQLITE_OK ){
  18099. + goto end_playback;
  18100. + }
  18101. + pPager->dbSize = mxPg;
  18102. +
  18103. + /* Copy original pages out of the journal and back into the database file.
  18104. + */
  18105. + for(i=0; i<nRec; i++){
  18106. + rc = pager_playback_one_page(pPager, &pPager->jfd, format);
  18107. + if( rc!=SQLITE_OK ){
  18108. + if( rc==SQLITE_DONE ){
  18109. + rc = SQLITE_OK;
  18110. + }
  18111. + break;
  18112. + }
  18113. + }
  18114. +
  18115. + /* Pages that have been written to the journal but never synced
  18116. + ** where not restored by the loop above. We have to restore those
  18117. + ** pages by reading them back from the original database.
  18118. + */
  18119. + if( rc==SQLITE_OK ){
  18120. + PgHdr *pPg;
  18121. + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
  18122. + char zBuf[SQLITE_PAGE_SIZE];
  18123. + if( !pPg->dirty ) continue;
  18124. + if( (int)pPg->pgno <= pPager->origDbSize ){
  18125. + sqliteOsSeek(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)(pPg->pgno-1));
  18126. + rc = sqliteOsRead(&pPager->fd, zBuf, SQLITE_PAGE_SIZE);
  18127. + TRACE2("REFETCH %d\n", pPg->pgno);
  18128. + CODEC(pPager, zBuf, pPg->pgno, 2);
  18129. + if( rc ) break;
  18130. + }else{
  18131. + memset(zBuf, 0, SQLITE_PAGE_SIZE);
  18132. + }
  18133. + if( pPg->nRef==0 || memcmp(zBuf, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE) ){
  18134. + memcpy(PGHDR_TO_DATA(pPg), zBuf, SQLITE_PAGE_SIZE);
  18135. + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
  18136. + }
  18137. + pPg->needSync = 0;
  18138. + pPg->dirty = 0;
  18139. + }
  18140. + }
  18141. +
  18142. +end_playback:
  18143. + if( rc!=SQLITE_OK ){
  18144. + pager_unwritelock(pPager);
  18145. + pPager->errMask |= PAGER_ERR_CORRUPT;
  18146. + rc = SQLITE_CORRUPT;
  18147. + }else{
  18148. + rc = pager_unwritelock(pPager);
  18149. + }
  18150. + return rc;
  18151. +}
  18152. +
  18153. +/*
  18154. +** Playback the checkpoint journal.
  18155. +**
  18156. +** This is similar to playing back the transaction journal but with
  18157. +** a few extra twists.
  18158. +**
  18159. +** (1) The number of pages in the database file at the start of
  18160. +** the checkpoint is stored in pPager->ckptSize, not in the
  18161. +** journal file itself.
  18162. +**
  18163. +** (2) In addition to playing back the checkpoint journal, also
  18164. +** playback all pages of the transaction journal beginning
  18165. +** at offset pPager->ckptJSize.
  18166. +*/
  18167. +static int pager_ckpt_playback(Pager *pPager){
  18168. + off_t szJ; /* Size of the full journal */
  18169. + int nRec; /* Number of Records */
  18170. + int i; /* Loop counter */
  18171. + int rc;
  18172. +
  18173. + /* Truncate the database back to its original size.
  18174. + */
  18175. + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)pPager->ckptSize);
  18176. + pPager->dbSize = pPager->ckptSize;
  18177. +
  18178. + /* Figure out how many records are in the checkpoint journal.
  18179. + */
  18180. + assert( pPager->ckptInUse && pPager->journalOpen );
  18181. + sqliteOsSeek(&pPager->cpfd, 0);
  18182. + nRec = pPager->ckptNRec;
  18183. +
  18184. + /* Copy original pages out of the checkpoint journal and back into the
  18185. + ** database file. Note that the checkpoint journal always uses format
  18186. + ** 2 instead of format 3 since it does not need to be concerned with
  18187. + ** power failures corrupting the journal and can thus omit the checksums.
  18188. + */
  18189. + for(i=nRec-1; i>=0; i--){
  18190. + rc = pager_playback_one_page(pPager, &pPager->cpfd, 2);
  18191. + assert( rc!=SQLITE_DONE );
  18192. + if( rc!=SQLITE_OK ) goto end_ckpt_playback;
  18193. + }
  18194. +
  18195. + /* Figure out how many pages need to be copied out of the transaction
  18196. + ** journal.
  18197. + */
  18198. + rc = sqliteOsSeek(&pPager->jfd, pPager->ckptJSize);
  18199. + if( rc!=SQLITE_OK ){
  18200. + goto end_ckpt_playback;
  18201. + }
  18202. + rc = sqliteOsFileSize(&pPager->jfd, &szJ);
  18203. + if( rc!=SQLITE_OK ){
  18204. + goto end_ckpt_playback;
  18205. + }
  18206. + nRec = (szJ - pPager->ckptJSize)/JOURNAL_PG_SZ(journal_format);
  18207. + for(i=nRec-1; i>=0; i--){
  18208. + rc = pager_playback_one_page(pPager, &pPager->jfd, journal_format);
  18209. + if( rc!=SQLITE_OK ){
  18210. + assert( rc!=SQLITE_DONE );
  18211. + goto end_ckpt_playback;
  18212. + }
  18213. + }
  18214. +
  18215. +end_ckpt_playback:
  18216. + if( rc!=SQLITE_OK ){
  18217. + pPager->errMask |= PAGER_ERR_CORRUPT;
  18218. + rc = SQLITE_CORRUPT;
  18219. + }
  18220. + return rc;
  18221. +}
  18222. +
  18223. +/*
  18224. +** Change the maximum number of in-memory pages that are allowed.
  18225. +**
  18226. +** The maximum number is the absolute value of the mxPage parameter.
  18227. +** If mxPage is negative, the noSync flag is also set. noSync bypasses
  18228. +** calls to sqliteOsSync(). The pager runs much faster with noSync on,
  18229. +** but if the operating system crashes or there is an abrupt power
  18230. +** failure, the database file might be left in an inconsistent and
  18231. +** unrepairable state.
  18232. +*/
  18233. +void sqlitepager_set_cachesize(Pager *pPager, int mxPage){
  18234. + if( mxPage>=0 ){
  18235. + pPager->noSync = pPager->tempFile;
  18236. + if( pPager->noSync==0 ) pPager->needSync = 0;
  18237. + }else{
  18238. + pPager->noSync = 1;
  18239. + mxPage = -mxPage;
  18240. + }
  18241. + if( mxPage>10 ){
  18242. + pPager->mxPage = mxPage;
  18243. + }
  18244. +}
  18245. +
  18246. +/*
  18247. +** Adjust the robustness of the database to damage due to OS crashes
  18248. +** or power failures by changing the number of syncs()s when writing
  18249. +** the rollback journal. There are three levels:
  18250. +**
  18251. +** OFF sqliteOsSync() is never called. This is the default
  18252. +** for temporary and transient files.
  18253. +**
  18254. +** NORMAL The journal is synced once before writes begin on the
  18255. +** database. This is normally adequate protection, but
  18256. +** it is theoretically possible, though very unlikely,
  18257. +** that an inopertune power failure could leave the journal
  18258. +** in a state which would cause damage to the database
  18259. +** when it is rolled back.
  18260. +**
  18261. +** FULL The journal is synced twice before writes begin on the
  18262. +** database (with some additional information - the nRec field
  18263. +** of the journal header - being written in between the two
  18264. +** syncs). If we assume that writing a
  18265. +** single disk sector is atomic, then this mode provides
  18266. +** assurance that the journal will not be corrupted to the
  18267. +** point of causing damage to the database during rollback.
  18268. +**
  18269. +** Numeric values associated with these states are OFF==1, NORMAL=2,
  18270. +** and FULL=3.
  18271. +*/
  18272. +void sqlitepager_set_safety_level(Pager *pPager, int level){
  18273. + pPager->noSync = level==1 || pPager->tempFile;
  18274. + pPager->fullSync = level==3 && !pPager->tempFile;
  18275. + if( pPager->noSync==0 ) pPager->needSync = 0;
  18276. +}
  18277. +
  18278. +/*
  18279. +** Open a temporary file. Write the name of the file into zName
  18280. +** (zName must be at least SQLITE_TEMPNAME_SIZE bytes long.) Write
  18281. +** the file descriptor into *fd. Return SQLITE_OK on success or some
  18282. +** other error code if we fail.
  18283. +**
  18284. +** The OS will automatically delete the temporary file when it is
  18285. +** closed.
  18286. +*/
  18287. +static int sqlitepager_opentemp(char *zFile, OsFile *fd){
  18288. + int cnt = 8;
  18289. + int rc;
  18290. + do{
  18291. + cnt--;
  18292. + sqliteOsTempFileName(zFile);
  18293. + rc = sqliteOsOpenExclusive(zFile, fd, 1);
  18294. + }while( cnt>0 && rc!=SQLITE_OK );
  18295. + return rc;
  18296. +}
  18297. +
  18298. +/*
  18299. +** Create a new page cache and put a pointer to the page cache in *ppPager.
  18300. +** The file to be cached need not exist. The file is not locked until
  18301. +** the first call to sqlitepager_get() and is only held open until the
  18302. +** last page is released using sqlitepager_unref().
  18303. +**
  18304. +** If zFilename is NULL then a randomly-named temporary file is created
  18305. +** and used as the file to be cached. The file will be deleted
  18306. +** automatically when it is closed.
  18307. +*/
  18308. +int sqlitepager_open(
  18309. + Pager **ppPager, /* Return the Pager structure here */
  18310. + const char *zFilename, /* Name of the database file to open */
  18311. + int mxPage, /* Max number of in-memory cache pages */
  18312. + int nExtra, /* Extra bytes append to each in-memory page */
  18313. + int useJournal /* TRUE to use a rollback journal on this file */
  18314. +){
  18315. + Pager *pPager;
  18316. + char *zFullPathname;
  18317. + int nameLen;
  18318. + OsFile fd;
  18319. + int rc, i;
  18320. + int tempFile;
  18321. + int readOnly = 0;
  18322. + char zTemp[SQLITE_TEMPNAME_SIZE];
  18323. +
  18324. + *ppPager = 0;
  18325. + if( sqlite_malloc_failed ){
  18326. + return SQLITE_NOMEM;
  18327. + }
  18328. + if( zFilename && zFilename[0] ){
  18329. + zFullPathname = sqliteOsFullPathname(zFilename);
  18330. + rc = sqliteOsOpenReadWrite(zFullPathname, &fd, &readOnly);
  18331. + tempFile = 0;
  18332. + }else{
  18333. + rc = sqlitepager_opentemp(zTemp, &fd);
  18334. + zFilename = zTemp;
  18335. + zFullPathname = sqliteOsFullPathname(zFilename);
  18336. + tempFile = 1;
  18337. + }
  18338. + if( sqlite_malloc_failed ){
  18339. + return SQLITE_NOMEM;
  18340. + }
  18341. + if( rc!=SQLITE_OK ){
  18342. + sqliteFree(zFullPathname);
  18343. + return SQLITE_CANTOPEN;
  18344. + }
  18345. + nameLen = strlen(zFullPathname);
  18346. + pPager = sqliteMalloc( sizeof(*pPager) + nameLen*3 + 30 );
  18347. + if( pPager==0 ){
  18348. + sqliteOsClose(&fd);
  18349. + sqliteFree(zFullPathname);
  18350. + return SQLITE_NOMEM;
  18351. + }
  18352. + SET_PAGER(pPager);
  18353. + pPager->zFilename = (char*)&pPager[1];
  18354. + pPager->zDirectory = &pPager->zFilename[nameLen+1];
  18355. + pPager->zJournal = &pPager->zDirectory[nameLen+1];
  18356. + strcpy(pPager->zFilename, zFullPathname);
  18357. + strcpy(pPager->zDirectory, zFullPathname);
  18358. + for(i=nameLen; i>0 && pPager->zDirectory[i-1]!='/'; i--){}
  18359. + if( i>0 ) pPager->zDirectory[i-1] = 0;
  18360. + strcpy(pPager->zJournal, zFullPathname);
  18361. + sqliteFree(zFullPathname);
  18362. + strcpy(&pPager->zJournal[nameLen], "-journal");
  18363. + pPager->fd = fd;
  18364. + pPager->journalOpen = 0;
  18365. + pPager->useJournal = useJournal;
  18366. + pPager->ckptOpen = 0;
  18367. + pPager->ckptInUse = 0;
  18368. + pPager->nRef = 0;
  18369. + pPager->dbSize = -1;
  18370. + pPager->ckptSize = 0;
  18371. + pPager->ckptJSize = 0;
  18372. + pPager->nPage = 0;
  18373. + pPager->mxPage = mxPage>5 ? mxPage : 10;
  18374. + pPager->state = SQLITE_UNLOCK;
  18375. + pPager->errMask = 0;
  18376. + pPager->tempFile = tempFile;
  18377. + pPager->readOnly = readOnly;
  18378. + pPager->needSync = 0;
  18379. + pPager->noSync = pPager->tempFile || !useJournal;
  18380. + pPager->pFirst = 0;
  18381. + pPager->pFirstSynced = 0;
  18382. + pPager->pLast = 0;
  18383. + pPager->nExtra = nExtra;
  18384. + memset(pPager->aHash, 0, sizeof(pPager->aHash));
  18385. + *ppPager = pPager;
  18386. + return SQLITE_OK;
  18387. +}
  18388. +
  18389. +/*
  18390. +** Set the destructor for this pager. If not NULL, the destructor is called
  18391. +** when the reference count on each page reaches zero. The destructor can
  18392. +** be used to clean up information in the extra segment appended to each page.
  18393. +**
  18394. +** The destructor is not called as a result sqlitepager_close().
  18395. +** Destructors are only called by sqlitepager_unref().
  18396. +*/
  18397. +void sqlitepager_set_destructor(Pager *pPager, void (*xDesc)(void*)){
  18398. + pPager->xDestructor = xDesc;
  18399. +}
  18400. +
  18401. +/*
  18402. +** Return the total number of pages in the disk file associated with
  18403. +** pPager.
  18404. +*/
  18405. +int sqlitepager_pagecount(Pager *pPager){
  18406. + off_t n;
  18407. + assert( pPager!=0 );
  18408. + if( pPager->dbSize>=0 ){
  18409. + return pPager->dbSize;
  18410. + }
  18411. + if( sqliteOsFileSize(&pPager->fd, &n)!=SQLITE_OK ){
  18412. + pPager->errMask |= PAGER_ERR_DISK;
  18413. + return 0;
  18414. + }
  18415. + n /= SQLITE_PAGE_SIZE;
  18416. + if( pPager->state!=SQLITE_UNLOCK ){
  18417. + pPager->dbSize = n;
  18418. + }
  18419. + return n;
  18420. +}
  18421. +
  18422. +/*
  18423. +** Forward declaration
  18424. +*/
  18425. +static int syncJournal(Pager*);
  18426. +
  18427. +/*
  18428. +** Truncate the file to the number of pages specified.
  18429. +*/
  18430. +int sqlitepager_truncate(Pager *pPager, Pgno nPage){
  18431. + int rc;
  18432. + if( pPager->dbSize<0 ){
  18433. + sqlitepager_pagecount(pPager);
  18434. + }
  18435. + if( pPager->errMask!=0 ){
  18436. + rc = pager_errcode(pPager);
  18437. + return rc;
  18438. + }
  18439. + if( nPage>=(unsigned)pPager->dbSize ){
  18440. + return SQLITE_OK;
  18441. + }
  18442. + syncJournal(pPager);
  18443. + rc = sqliteOsTruncate(&pPager->fd, SQLITE_PAGE_SIZE*(off_t)nPage);
  18444. + if( rc==SQLITE_OK ){
  18445. + pPager->dbSize = nPage;
  18446. + }
  18447. + return rc;
  18448. +}
  18449. +
  18450. +/*
  18451. +** Shutdown the page cache. Free all memory and close all files.
  18452. +**
  18453. +** If a transaction was in progress when this routine is called, that
  18454. +** transaction is rolled back. All outstanding pages are invalidated
  18455. +** and their memory is freed. Any attempt to use a page associated
  18456. +** with this page cache after this function returns will likely
  18457. +** result in a coredump.
  18458. +*/
  18459. +int sqlitepager_close(Pager *pPager){
  18460. + PgHdr *pPg, *pNext;
  18461. + switch( pPager->state ){
  18462. + case SQLITE_WRITELOCK: {
  18463. + sqlitepager_rollback(pPager);
  18464. + sqliteOsUnlock(&pPager->fd);
  18465. + assert( pPager->journalOpen==0 );
  18466. + break;
  18467. + }
  18468. + case SQLITE_READLOCK: {
  18469. + sqliteOsUnlock(&pPager->fd);
  18470. + break;
  18471. + }
  18472. + default: {
  18473. + /* Do nothing */
  18474. + break;
  18475. + }
  18476. + }
  18477. + for(pPg=pPager->pAll; pPg; pPg=pNext){
  18478. + pNext = pPg->pNextAll;
  18479. + sqliteFree(pPg);
  18480. + }
  18481. + sqliteOsClose(&pPager->fd);
  18482. + assert( pPager->journalOpen==0 );
  18483. + /* Temp files are automatically deleted by the OS
  18484. + ** if( pPager->tempFile ){
  18485. + ** sqliteOsDelete(pPager->zFilename);
  18486. + ** }
  18487. + */
  18488. + CLR_PAGER(pPager);
  18489. + if( pPager->zFilename!=(char*)&pPager[1] ){
  18490. + assert( 0 ); /* Cannot happen */
  18491. + sqliteFree(pPager->zFilename);
  18492. + sqliteFree(pPager->zJournal);
  18493. + sqliteFree(pPager->zDirectory);
  18494. + }
  18495. + sqliteFree(pPager);
  18496. + return SQLITE_OK;
  18497. +}
  18498. +
  18499. +/*
  18500. +** Return the page number for the given page data.
  18501. +*/
  18502. +Pgno sqlitepager_pagenumber(void *pData){
  18503. + PgHdr *p = DATA_TO_PGHDR(pData);
  18504. + return p->pgno;
  18505. +}
  18506. +
  18507. +/*
  18508. +** Increment the reference count for a page. If the page is
  18509. +** currently on the freelist (the reference count is zero) then
  18510. +** remove it from the freelist.
  18511. +*/
  18512. +#define page_ref(P) ((P)->nRef==0?_page_ref(P):(void)(P)->nRef++)
  18513. +static void _page_ref(PgHdr *pPg){
  18514. + if( pPg->nRef==0 ){
  18515. + /* The page is currently on the freelist. Remove it. */
  18516. + if( pPg==pPg->pPager->pFirstSynced ){
  18517. + PgHdr *p = pPg->pNextFree;
  18518. + while( p && p->needSync ){ p = p->pNextFree; }
  18519. + pPg->pPager->pFirstSynced = p;
  18520. + }
  18521. + if( pPg->pPrevFree ){
  18522. + pPg->pPrevFree->pNextFree = pPg->pNextFree;
  18523. + }else{
  18524. + pPg->pPager->pFirst = pPg->pNextFree;
  18525. + }
  18526. + if( pPg->pNextFree ){
  18527. + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
  18528. + }else{
  18529. + pPg->pPager->pLast = pPg->pPrevFree;
  18530. + }
  18531. + pPg->pPager->nRef++;
  18532. + }
  18533. + pPg->nRef++;
  18534. + REFINFO(pPg);
  18535. +}
  18536. +
  18537. +/*
  18538. +** Increment the reference count for a page. The input pointer is
  18539. +** a reference to the page data.
  18540. +*/
  18541. +int sqlitepager_ref(void *pData){
  18542. + PgHdr *pPg = DATA_TO_PGHDR(pData);
  18543. + page_ref(pPg);
  18544. + return SQLITE_OK;
  18545. +}
  18546. +
  18547. +/*
  18548. +** Sync the journal. In other words, make sure all the pages that have
  18549. +** been written to the journal have actually reached the surface of the
  18550. +** disk. It is not safe to modify the original database file until after
  18551. +** the journal has been synced. If the original database is modified before
  18552. +** the journal is synced and a power failure occurs, the unsynced journal
  18553. +** data would be lost and we would be unable to completely rollback the
  18554. +** database changes. Database corruption would occur.
  18555. +**
  18556. +** This routine also updates the nRec field in the header of the journal.
  18557. +** (See comments on the pager_playback() routine for additional information.)
  18558. +** If the sync mode is FULL, two syncs will occur. First the whole journal
  18559. +** is synced, then the nRec field is updated, then a second sync occurs.
  18560. +**
  18561. +** For temporary databases, we do not care if we are able to rollback
  18562. +** after a power failure, so sync occurs.
  18563. +**
  18564. +** This routine clears the needSync field of every page current held in
  18565. +** memory.
  18566. +*/
  18567. +static int syncJournal(Pager *pPager){
  18568. + PgHdr *pPg;
  18569. + int rc = SQLITE_OK;
  18570. +
  18571. + /* Sync the journal before modifying the main database
  18572. + ** (assuming there is a journal and it needs to be synced.)
  18573. + */
  18574. + if( pPager->needSync ){
  18575. + if( !pPager->tempFile ){
  18576. + assert( pPager->journalOpen );
  18577. + /* assert( !pPager->noSync ); // noSync might be set if synchronous
  18578. + ** was turned off after the transaction was started. Ticket #615 */
  18579. +#ifndef NDEBUG
  18580. + {
  18581. + /* Make sure the pPager->nRec counter we are keeping agrees
  18582. + ** with the nRec computed from the size of the journal file.
  18583. + */
  18584. + off_t hdrSz, pgSz, jSz;
  18585. + hdrSz = JOURNAL_HDR_SZ(journal_format);
  18586. + pgSz = JOURNAL_PG_SZ(journal_format);
  18587. + rc = sqliteOsFileSize(&pPager->jfd, &jSz);
  18588. + if( rc!=0 ) return rc;
  18589. + assert( pPager->nRec*pgSz+hdrSz==jSz );
  18590. + }
  18591. +#endif
  18592. + if( journal_format>=3 ){
  18593. + /* Write the nRec value into the journal file header */
  18594. + off_t szJ;
  18595. + if( pPager->fullSync ){
  18596. + TRACE1("SYNC\n");
  18597. + rc = sqliteOsSync(&pPager->jfd);
  18598. + if( rc!=0 ) return rc;
  18599. + }
  18600. + sqliteOsSeek(&pPager->jfd, sizeof(aJournalMagic1));
  18601. + rc = write32bits(&pPager->jfd, pPager->nRec);
  18602. + if( rc ) return rc;
  18603. + szJ = JOURNAL_HDR_SZ(journal_format) +
  18604. + pPager->nRec*JOURNAL_PG_SZ(journal_format);
  18605. + sqliteOsSeek(&pPager->jfd, szJ);
  18606. + }
  18607. + TRACE1("SYNC\n");
  18608. + rc = sqliteOsSync(&pPager->jfd);
  18609. + if( rc!=0 ) return rc;
  18610. + pPager->journalStarted = 1;
  18611. + }
  18612. + pPager->needSync = 0;
  18613. +
  18614. + /* Erase the needSync flag from every page.
  18615. + */
  18616. + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
  18617. + pPg->needSync = 0;
  18618. + }
  18619. + pPager->pFirstSynced = pPager->pFirst;
  18620. + }
  18621. +
  18622. +#ifndef NDEBUG
  18623. + /* If the Pager.needSync flag is clear then the PgHdr.needSync
  18624. + ** flag must also be clear for all pages. Verify that this
  18625. + ** invariant is true.
  18626. + */
  18627. + else{
  18628. + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
  18629. + assert( pPg->needSync==0 );
  18630. + }
  18631. + assert( pPager->pFirstSynced==pPager->pFirst );
  18632. + }
  18633. +#endif
  18634. +
  18635. + return rc;
  18636. +}
  18637. +
  18638. +/*
  18639. +** Given a list of pages (connected by the PgHdr.pDirty pointer) write
  18640. +** every one of those pages out to the database file and mark them all
  18641. +** as clean.
  18642. +*/
  18643. +static int pager_write_pagelist(PgHdr *pList){
  18644. + Pager *pPager;
  18645. + int rc;
  18646. +
  18647. + if( pList==0 ) return SQLITE_OK;
  18648. + pPager = pList->pPager;
  18649. + while( pList ){
  18650. + assert( pList->dirty );
  18651. + sqliteOsSeek(&pPager->fd, (pList->pgno-1)*(off_t)SQLITE_PAGE_SIZE);
  18652. + CODEC(pPager, PGHDR_TO_DATA(pList), pList->pgno, 6);
  18653. + TRACE2("STORE %d\n", pList->pgno);
  18654. + rc = sqliteOsWrite(&pPager->fd, PGHDR_TO_DATA(pList), SQLITE_PAGE_SIZE);
  18655. + CODEC(pPager, PGHDR_TO_DATA(pList), pList->pgno, 0);
  18656. + if( rc ) return rc;
  18657. + pList->dirty = 0;
  18658. + pList = pList->pDirty;
  18659. + }
  18660. + return SQLITE_OK;
  18661. +}
  18662. +
  18663. +/*
  18664. +** Collect every dirty page into a dirty list and
  18665. +** return a pointer to the head of that list. All pages are
  18666. +** collected even if they are still in use.
  18667. +*/
  18668. +static PgHdr *pager_get_all_dirty_pages(Pager *pPager){
  18669. + PgHdr *p, *pList;
  18670. + pList = 0;
  18671. + for(p=pPager->pAll; p; p=p->pNextAll){
  18672. + if( p->dirty ){
  18673. + p->pDirty = pList;
  18674. + pList = p;
  18675. + }
  18676. + }
  18677. + return pList;
  18678. +}
  18679. +
  18680. +/*
  18681. +** Acquire a page.
  18682. +**
  18683. +** A read lock on the disk file is obtained when the first page is acquired.
  18684. +** This read lock is dropped when the last page is released.
  18685. +**
  18686. +** A _get works for any page number greater than 0. If the database
  18687. +** file is smaller than the requested page, then no actual disk
  18688. +** read occurs and the memory image of the page is initialized to
  18689. +** all zeros. The extra data appended to a page is always initialized
  18690. +** to zeros the first time a page is loaded into memory.
  18691. +**
  18692. +** The acquisition might fail for several reasons. In all cases,
  18693. +** an appropriate error code is returned and *ppPage is set to NULL.
  18694. +**
  18695. +** See also sqlitepager_lookup(). Both this routine and _lookup() attempt
  18696. +** to find a page in the in-memory cache first. If the page is not already
  18697. +** in memory, this routine goes to disk to read it in whereas _lookup()
  18698. +** just returns 0. This routine acquires a read-lock the first time it
  18699. +** has to go to disk, and could also playback an old journal if necessary.
  18700. +** Since _lookup() never goes to disk, it never has to deal with locks
  18701. +** or journal files.
  18702. +*/
  18703. +int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage){
  18704. + PgHdr *pPg;
  18705. + int rc;
  18706. +
  18707. + /* Make sure we have not hit any critical errors.
  18708. + */
  18709. + assert( pPager!=0 );
  18710. + assert( pgno!=0 );
  18711. + *ppPage = 0;
  18712. + if( pPager->errMask & ~(PAGER_ERR_FULL) ){
  18713. + return pager_errcode(pPager);
  18714. + }
  18715. +
  18716. + /* If this is the first page accessed, then get a read lock
  18717. + ** on the database file.
  18718. + */
  18719. + if( pPager->nRef==0 ){
  18720. + rc = sqliteOsReadLock(&pPager->fd);
  18721. + if( rc!=SQLITE_OK ){
  18722. + return rc;
  18723. + }
  18724. + pPager->state = SQLITE_READLOCK;
  18725. +
  18726. + /* If a journal file exists, try to play it back.
  18727. + */
  18728. + if( pPager->useJournal && sqliteOsFileExists(pPager->zJournal) ){
  18729. + int rc;
  18730. +
  18731. + /* Get a write lock on the database
  18732. + */
  18733. + rc = sqliteOsWriteLock(&pPager->fd);
  18734. + if( rc!=SQLITE_OK ){
  18735. + if( sqliteOsUnlock(&pPager->fd)!=SQLITE_OK ){
  18736. + /* This should never happen! */
  18737. + rc = SQLITE_INTERNAL;
  18738. + }
  18739. + return rc;
  18740. + }
  18741. + pPager->state = SQLITE_WRITELOCK;
  18742. +
  18743. + /* Open the journal for reading only. Return SQLITE_BUSY if
  18744. + ** we are unable to open the journal file.
  18745. + **
  18746. + ** The journal file does not need to be locked itself. The
  18747. + ** journal file is never open unless the main database file holds
  18748. + ** a write lock, so there is never any chance of two or more
  18749. + ** processes opening the journal at the same time.
  18750. + */
  18751. + rc = sqliteOsOpenReadOnly(pPager->zJournal, &pPager->jfd);
  18752. + if( rc!=SQLITE_OK ){
  18753. + rc = sqliteOsUnlock(&pPager->fd);
  18754. + assert( rc==SQLITE_OK );
  18755. + return SQLITE_BUSY;
  18756. + }
  18757. + pPager->journalOpen = 1;
  18758. + pPager->journalStarted = 0;
  18759. +
  18760. + /* Playback and delete the journal. Drop the database write
  18761. + ** lock and reacquire the read lock.
  18762. + */
  18763. + rc = pager_playback(pPager, 0);
  18764. + if( rc!=SQLITE_OK ){
  18765. + return rc;
  18766. + }
  18767. + }
  18768. + pPg = 0;
  18769. + }else{
  18770. + /* Search for page in cache */
  18771. + pPg = pager_lookup(pPager, pgno);
  18772. + }
  18773. + if( pPg==0 ){
  18774. + /* The requested page is not in the page cache. */
  18775. + int h;
  18776. + pPager->nMiss++;
  18777. + if( pPager->nPage<pPager->mxPage || pPager->pFirst==0 ){
  18778. + /* Create a new page */
  18779. + pPg = sqliteMallocRaw( sizeof(*pPg) + SQLITE_PAGE_SIZE
  18780. + + sizeof(u32) + pPager->nExtra );
  18781. + if( pPg==0 ){
  18782. + pager_unwritelock(pPager);
  18783. + pPager->errMask |= PAGER_ERR_MEM;
  18784. + return SQLITE_NOMEM;
  18785. + }
  18786. + memset(pPg, 0, sizeof(*pPg));
  18787. + pPg->pPager = pPager;
  18788. + pPg->pNextAll = pPager->pAll;
  18789. + if( pPager->pAll ){
  18790. + pPager->pAll->pPrevAll = pPg;
  18791. + }
  18792. + pPg->pPrevAll = 0;
  18793. + pPager->pAll = pPg;
  18794. + pPager->nPage++;
  18795. + }else{
  18796. + /* Find a page to recycle. Try to locate a page that does not
  18797. + ** require us to do an fsync() on the journal.
  18798. + */
  18799. + pPg = pPager->pFirstSynced;
  18800. +
  18801. + /* If we could not find a page that does not require an fsync()
  18802. + ** on the journal file then fsync the journal file. This is a
  18803. + ** very slow operation, so we work hard to avoid it. But sometimes
  18804. + ** it can't be helped.
  18805. + */
  18806. + if( pPg==0 ){
  18807. + int rc = syncJournal(pPager);
  18808. + if( rc!=0 ){
  18809. + sqlitepager_rollback(pPager);
  18810. + return SQLITE_IOERR;
  18811. + }
  18812. + pPg = pPager->pFirst;
  18813. + }
  18814. + assert( pPg->nRef==0 );
  18815. +
  18816. + /* Write the page to the database file if it is dirty.
  18817. + */
  18818. + if( pPg->dirty ){
  18819. + assert( pPg->needSync==0 );
  18820. + pPg->pDirty = 0;
  18821. + rc = pager_write_pagelist( pPg );
  18822. + if( rc!=SQLITE_OK ){
  18823. + sqlitepager_rollback(pPager);
  18824. + return SQLITE_IOERR;
  18825. + }
  18826. + }
  18827. + assert( pPg->dirty==0 );
  18828. +
  18829. + /* If the page we are recycling is marked as alwaysRollback, then
  18830. + ** set the global alwaysRollback flag, thus disabling the
  18831. + ** sqlite_dont_rollback() optimization for the rest of this transaction.
  18832. + ** It is necessary to do this because the page marked alwaysRollback
  18833. + ** might be reloaded at a later time but at that point we won't remember
  18834. + ** that is was marked alwaysRollback. This means that all pages must
  18835. + ** be marked as alwaysRollback from here on out.
  18836. + */
  18837. + if( pPg->alwaysRollback ){
  18838. + pPager->alwaysRollback = 1;
  18839. + }
  18840. +
  18841. + /* Unlink the old page from the free list and the hash table
  18842. + */
  18843. + if( pPg==pPager->pFirstSynced ){
  18844. + PgHdr *p = pPg->pNextFree;
  18845. + while( p && p->needSync ){ p = p->pNextFree; }
  18846. + pPager->pFirstSynced = p;
  18847. + }
  18848. + if( pPg->pPrevFree ){
  18849. + pPg->pPrevFree->pNextFree = pPg->pNextFree;
  18850. + }else{
  18851. + assert( pPager->pFirst==pPg );
  18852. + pPager->pFirst = pPg->pNextFree;
  18853. + }
  18854. + if( pPg->pNextFree ){
  18855. + pPg->pNextFree->pPrevFree = pPg->pPrevFree;
  18856. + }else{
  18857. + assert( pPager->pLast==pPg );
  18858. + pPager->pLast = pPg->pPrevFree;
  18859. + }
  18860. + pPg->pNextFree = pPg->pPrevFree = 0;
  18861. + if( pPg->pNextHash ){
  18862. + pPg->pNextHash->pPrevHash = pPg->pPrevHash;
  18863. + }
  18864. + if( pPg->pPrevHash ){
  18865. + pPg->pPrevHash->pNextHash = pPg->pNextHash;
  18866. + }else{
  18867. + h = pager_hash(pPg->pgno);
  18868. + assert( pPager->aHash[h]==pPg );
  18869. + pPager->aHash[h] = pPg->pNextHash;
  18870. + }
  18871. + pPg->pNextHash = pPg->pPrevHash = 0;
  18872. + pPager->nOvfl++;
  18873. + }
  18874. + pPg->pgno = pgno;
  18875. + if( pPager->aInJournal && (int)pgno<=pPager->origDbSize ){
  18876. + sqliteCheckMemory(pPager->aInJournal, pgno/8);
  18877. + assert( pPager->journalOpen );
  18878. + pPg->inJournal = (pPager->aInJournal[pgno/8] & (1<<(pgno&7)))!=0;
  18879. + pPg->needSync = 0;
  18880. + }else{
  18881. + pPg->inJournal = 0;
  18882. + pPg->needSync = 0;
  18883. + }
  18884. + if( pPager->aInCkpt && (int)pgno<=pPager->ckptSize
  18885. + && (pPager->aInCkpt[pgno/8] & (1<<(pgno&7)))!=0 ){
  18886. + page_add_to_ckpt_list(pPg);
  18887. + }else{
  18888. + page_remove_from_ckpt_list(pPg);
  18889. + }
  18890. + pPg->dirty = 0;
  18891. + pPg->nRef = 1;
  18892. + REFINFO(pPg);
  18893. + pPager->nRef++;
  18894. + h = pager_hash(pgno);
  18895. + pPg->pNextHash = pPager->aHash[h];
  18896. + pPager->aHash[h] = pPg;
  18897. + if( pPg->pNextHash ){
  18898. + assert( pPg->pNextHash->pPrevHash==0 );
  18899. + pPg->pNextHash->pPrevHash = pPg;
  18900. + }
  18901. + if( pPager->nExtra>0 ){
  18902. + memset(PGHDR_TO_EXTRA(pPg), 0, pPager->nExtra);
  18903. + }
  18904. + if( pPager->dbSize<0 ) sqlitepager_pagecount(pPager);
  18905. + if( pPager->errMask!=0 ){
  18906. + sqlitepager_unref(PGHDR_TO_DATA(pPg));
  18907. + rc = pager_errcode(pPager);
  18908. + return rc;
  18909. + }
  18910. + if( pPager->dbSize<(int)pgno ){
  18911. + memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
  18912. + }else{
  18913. + int rc;
  18914. + sqliteOsSeek(&pPager->fd, (pgno-1)*(off_t)SQLITE_PAGE_SIZE);
  18915. + rc = sqliteOsRead(&pPager->fd, PGHDR_TO_DATA(pPg), SQLITE_PAGE_SIZE);
  18916. + TRACE2("FETCH %d\n", pPg->pgno);
  18917. + CODEC(pPager, PGHDR_TO_DATA(pPg), pPg->pgno, 3);
  18918. + if( rc!=SQLITE_OK ){
  18919. + off_t fileSize;
  18920. + if( sqliteOsFileSize(&pPager->fd,&fileSize)!=SQLITE_OK
  18921. + || fileSize>=pgno*SQLITE_PAGE_SIZE ){
  18922. + sqlitepager_unref(PGHDR_TO_DATA(pPg));
  18923. + return rc;
  18924. + }else{
  18925. + memset(PGHDR_TO_DATA(pPg), 0, SQLITE_PAGE_SIZE);
  18926. + }
  18927. + }
  18928. + }
  18929. + }else{
  18930. + /* The requested page is in the page cache. */
  18931. + pPager->nHit++;
  18932. + page_ref(pPg);
  18933. + }
  18934. + *ppPage = PGHDR_TO_DATA(pPg);
  18935. + return SQLITE_OK;
  18936. +}
  18937. +
  18938. +/*
  18939. +** Acquire a page if it is already in the in-memory cache. Do
  18940. +** not read the page from disk. Return a pointer to the page,
  18941. +** or 0 if the page is not in cache.
  18942. +**
  18943. +** See also sqlitepager_get(). The difference between this routine
  18944. +** and sqlitepager_get() is that _get() will go to the disk and read
  18945. +** in the page if the page is not already in cache. This routine
  18946. +** returns NULL if the page is not in cache or if a disk I/O error
  18947. +** has ever happened.
  18948. +*/
  18949. +void *sqlitepager_lookup(Pager *pPager, Pgno pgno){
  18950. + PgHdr *pPg;
  18951. +
  18952. + assert( pPager!=0 );
  18953. + assert( pgno!=0 );
  18954. + if( pPager->errMask & ~(PAGER_ERR_FULL) ){
  18955. + return 0;
  18956. + }
  18957. + /* if( pPager->nRef==0 ){
  18958. + ** return 0;
  18959. + ** }
  18960. + */
  18961. + pPg = pager_lookup(pPager, pgno);
  18962. + if( pPg==0 ) return 0;
  18963. + page_ref(pPg);
  18964. + return PGHDR_TO_DATA(pPg);
  18965. +}
  18966. +
  18967. +/*
  18968. +** Release a page.
  18969. +**
  18970. +** If the number of references to the page drop to zero, then the
  18971. +** page is added to the LRU list. When all references to all pages
  18972. +** are released, a rollback occurs and the lock on the database is
  18973. +** removed.
  18974. +*/
  18975. +int sqlitepager_unref(void *pData){
  18976. + PgHdr *pPg;
  18977. +
  18978. + /* Decrement the reference count for this page
  18979. + */
  18980. + pPg = DATA_TO_PGHDR(pData);
  18981. + assert( pPg->nRef>0 );
  18982. + pPg->nRef--;
  18983. + REFINFO(pPg);
  18984. +
  18985. + /* When the number of references to a page reach 0, call the
  18986. + ** destructor and add the page to the freelist.
  18987. + */
  18988. + if( pPg->nRef==0 ){
  18989. + Pager *pPager;
  18990. + pPager = pPg->pPager;
  18991. + pPg->pNextFree = 0;
  18992. + pPg->pPrevFree = pPager->pLast;
  18993. + pPager->pLast = pPg;
  18994. + if( pPg->pPrevFree ){
  18995. + pPg->pPrevFree->pNextFree = pPg;
  18996. + }else{
  18997. + pPager->pFirst = pPg;
  18998. + }
  18999. + if( pPg->needSync==0 && pPager->pFirstSynced==0 ){
  19000. + pPager->pFirstSynced = pPg;
  19001. + }
  19002. + if( pPager->xDestructor ){
  19003. + pPager->xDestructor(pData);
  19004. + }
  19005. +
  19006. + /* When all pages reach the freelist, drop the read lock from
  19007. + ** the database file.
  19008. + */
  19009. + pPager->nRef--;
  19010. + assert( pPager->nRef>=0 );
  19011. + if( pPager->nRef==0 ){
  19012. + pager_reset(pPager);
  19013. + }
  19014. + }
  19015. + return SQLITE_OK;
  19016. +}
  19017. +
  19018. +/*
  19019. +** Create a journal file for pPager. There should already be a write
  19020. +** lock on the database file when this routine is called.
  19021. +**
  19022. +** Return SQLITE_OK if everything. Return an error code and release the
  19023. +** write lock if anything goes wrong.
  19024. +*/
  19025. +static int pager_open_journal(Pager *pPager){
  19026. + int rc;
  19027. + assert( pPager->state==SQLITE_WRITELOCK );
  19028. + assert( pPager->journalOpen==0 );
  19029. + assert( pPager->useJournal );
  19030. + sqlitepager_pagecount(pPager);
  19031. + pPager->aInJournal = sqliteMalloc( pPager->dbSize/8 + 1 );
  19032. + if( pPager->aInJournal==0 ){
  19033. + sqliteOsReadLock(&pPager->fd);
  19034. + pPager->state = SQLITE_READLOCK;
  19035. + return SQLITE_NOMEM;
  19036. + }
  19037. + rc = sqliteOsOpenExclusive(pPager->zJournal, &pPager->jfd,pPager->tempFile);
  19038. + if( rc!=SQLITE_OK ){
  19039. + sqliteFree(pPager->aInJournal);
  19040. + pPager->aInJournal = 0;
  19041. + sqliteOsReadLock(&pPager->fd);
  19042. + pPager->state = SQLITE_READLOCK;
  19043. + return SQLITE_CANTOPEN;
  19044. + }
  19045. + sqliteOsOpenDirectory(pPager->zDirectory, &pPager->jfd);
  19046. + pPager->journalOpen = 1;
  19047. + pPager->journalStarted = 0;
  19048. + pPager->needSync = 0;
  19049. + pPager->alwaysRollback = 0;
  19050. + pPager->nRec = 0;
  19051. + if( pPager->errMask!=0 ){
  19052. + rc = pager_errcode(pPager);
  19053. + return rc;
  19054. + }
  19055. + pPager->origDbSize = pPager->dbSize;
  19056. + if( journal_format==JOURNAL_FORMAT_3 ){
  19057. + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic3, sizeof(aJournalMagic3));
  19058. + if( rc==SQLITE_OK ){
  19059. + rc = write32bits(&pPager->jfd, pPager->noSync ? 0xffffffff : 0);
  19060. + }
  19061. + if( rc==SQLITE_OK ){
  19062. + sqliteRandomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  19063. + rc = write32bits(&pPager->jfd, pPager->cksumInit);
  19064. + }
  19065. + }else if( journal_format==JOURNAL_FORMAT_2 ){
  19066. + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic2, sizeof(aJournalMagic2));
  19067. + }else{
  19068. + assert( journal_format==JOURNAL_FORMAT_1 );
  19069. + rc = sqliteOsWrite(&pPager->jfd, aJournalMagic1, sizeof(aJournalMagic1));
  19070. + }
  19071. + if( rc==SQLITE_OK ){
  19072. + rc = write32bits(&pPager->jfd, pPager->dbSize);
  19073. + }
  19074. + if( pPager->ckptAutoopen && rc==SQLITE_OK ){
  19075. + rc = sqlitepager_ckpt_begin(pPager);
  19076. + }
  19077. + if( rc!=SQLITE_OK ){
  19078. + rc = pager_unwritelock(pPager);
  19079. + if( rc==SQLITE_OK ){
  19080. + rc = SQLITE_FULL;
  19081. + }
  19082. + }
  19083. + return rc;
  19084. +}
  19085. +
  19086. +/*
  19087. +** Acquire a write-lock on the database. The lock is removed when
  19088. +** the any of the following happen:
  19089. +**
  19090. +** * sqlitepager_commit() is called.
  19091. +** * sqlitepager_rollback() is called.
  19092. +** * sqlitepager_close() is called.
  19093. +** * sqlitepager_unref() is called to on every outstanding page.
  19094. +**
  19095. +** The parameter to this routine is a pointer to any open page of the
  19096. +** database file. Nothing changes about the page - it is used merely
  19097. +** to acquire a pointer to the Pager structure and as proof that there
  19098. +** is already a read-lock on the database.
  19099. +**
  19100. +** A journal file is opened if this is not a temporary file. For
  19101. +** temporary files, the opening of the journal file is deferred until
  19102. +** there is an actual need to write to the journal.
  19103. +**
  19104. +** If the database is already write-locked, this routine is a no-op.
  19105. +*/
  19106. +int sqlitepager_begin(void *pData){
  19107. + PgHdr *pPg = DATA_TO_PGHDR(pData);
  19108. + Pager *pPager = pPg->pPager;
  19109. + int rc = SQLITE_OK;
  19110. + assert( pPg->nRef>0 );
  19111. + assert( pPager->state!=SQLITE_UNLOCK );
  19112. + if( pPager->state==SQLITE_READLOCK ){
  19113. + assert( pPager->aInJournal==0 );
  19114. + rc = sqliteOsWriteLock(&pPager->fd);
  19115. + if( rc!=SQLITE_OK ){
  19116. + return rc;
  19117. + }
  19118. + pPager->state = SQLITE_WRITELOCK;
  19119. + pPager->dirtyFile = 0;
  19120. + TRACE1("TRANSACTION\n");
  19121. + if( pPager->useJournal && !pPager->tempFile ){
  19122. + rc = pager_open_journal(pPager);
  19123. + }
  19124. + }
  19125. + return rc;
  19126. +}
  19127. +
  19128. +/*
  19129. +** Mark a data page as writeable. The page is written into the journal
  19130. +** if it is not there already. This routine must be called before making
  19131. +** changes to a page.
  19132. +**
  19133. +** The first time this routine is called, the pager creates a new
  19134. +** journal and acquires a write lock on the database. If the write
  19135. +** lock could not be acquired, this routine returns SQLITE_BUSY. The
  19136. +** calling routine must check for that return value and be careful not to
  19137. +** change any page data until this routine returns SQLITE_OK.
  19138. +**
  19139. +** If the journal file could not be written because the disk is full,
  19140. +** then this routine returns SQLITE_FULL and does an immediate rollback.
  19141. +** All subsequent write attempts also return SQLITE_FULL until there
  19142. +** is a call to sqlitepager_commit() or sqlitepager_rollback() to
  19143. +** reset.
  19144. +*/
  19145. +int sqlitepager_write(void *pData){
  19146. + PgHdr *pPg = DATA_TO_PGHDR(pData);
  19147. + Pager *pPager = pPg->pPager;
  19148. + int rc = SQLITE_OK;
  19149. +
  19150. + /* Check for errors
  19151. + */
  19152. + if( pPager->errMask ){
  19153. + return pager_errcode(pPager);
  19154. + }
  19155. + if( pPager->readOnly ){
  19156. + return SQLITE_PERM;
  19157. + }
  19158. +
  19159. + /* Mark the page as dirty. If the page has already been written
  19160. + ** to the journal then we can return right away.
  19161. + */
  19162. + pPg->dirty = 1;
  19163. + if( pPg->inJournal && (pPg->inCkpt || pPager->ckptInUse==0) ){
  19164. + pPager->dirtyFile = 1;
  19165. + return SQLITE_OK;
  19166. + }
  19167. +
  19168. + /* If we get this far, it means that the page needs to be
  19169. + ** written to the transaction journal or the ckeckpoint journal
  19170. + ** or both.
  19171. + **
  19172. + ** First check to see that the transaction journal exists and
  19173. + ** create it if it does not.
  19174. + */
  19175. + assert( pPager->state!=SQLITE_UNLOCK );
  19176. + rc = sqlitepager_begin(pData);
  19177. + if( rc!=SQLITE_OK ){
  19178. + return rc;
  19179. + }
  19180. + assert( pPager->state==SQLITE_WRITELOCK );
  19181. + if( !pPager->journalOpen && pPager->useJournal ){
  19182. + rc = pager_open_journal(pPager);
  19183. + if( rc!=SQLITE_OK ) return rc;
  19184. + }
  19185. + assert( pPager->journalOpen || !pPager->useJournal );
  19186. + pPager->dirtyFile = 1;
  19187. +
  19188. + /* The transaction journal now exists and we have a write lock on the
  19189. + ** main database file. Write the current page to the transaction
  19190. + ** journal if it is not there already.
  19191. + */
  19192. + if( !pPg->inJournal && pPager->useJournal ){
  19193. + if( (int)pPg->pgno <= pPager->origDbSize ){
  19194. + int szPg;
  19195. + u32 saved;
  19196. + if( journal_format>=JOURNAL_FORMAT_3 ){
  19197. + u32 cksum = pager_cksum(pPager, pPg->pgno, pData);
  19198. + saved = *(u32*)PGHDR_TO_EXTRA(pPg);
  19199. + store32bits(cksum, pPg, SQLITE_PAGE_SIZE);
  19200. + szPg = SQLITE_PAGE_SIZE+8;
  19201. + }else{
  19202. + szPg = SQLITE_PAGE_SIZE+4;
  19203. + }
  19204. + store32bits(pPg->pgno, pPg, -4);
  19205. + CODEC(pPager, pData, pPg->pgno, 7);
  19206. + rc = sqliteOsWrite(&pPager->jfd, &((char*)pData)[-4], szPg);
  19207. + TRACE3("JOURNAL %d %d\n", pPg->pgno, pPg->needSync);
  19208. + CODEC(pPager, pData, pPg->pgno, 0);
  19209. + if( journal_format>=JOURNAL_FORMAT_3 ){
  19210. + *(u32*)PGHDR_TO_EXTRA(pPg) = saved;
  19211. + }
  19212. + if( rc!=SQLITE_OK ){
  19213. + sqlitepager_rollback(pPager);
  19214. + pPager->errMask |= PAGER_ERR_FULL;
  19215. + return rc;
  19216. + }
  19217. + pPager->nRec++;
  19218. + assert( pPager->aInJournal!=0 );
  19219. + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19220. + pPg->needSync = !pPager->noSync;
  19221. + pPg->inJournal = 1;
  19222. + if( pPager->ckptInUse ){
  19223. + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19224. + page_add_to_ckpt_list(pPg);
  19225. + }
  19226. + }else{
  19227. + pPg->needSync = !pPager->journalStarted && !pPager->noSync;
  19228. + TRACE3("APPEND %d %d\n", pPg->pgno, pPg->needSync);
  19229. + }
  19230. + if( pPg->needSync ){
  19231. + pPager->needSync = 1;
  19232. + }
  19233. + }
  19234. +
  19235. + /* If the checkpoint journal is open and the page is not in it,
  19236. + ** then write the current page to the checkpoint journal. Note that
  19237. + ** the checkpoint journal always uses the simplier format 2 that lacks
  19238. + ** checksums. The header is also omitted from the checkpoint journal.
  19239. + */
  19240. + if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
  19241. + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
  19242. + store32bits(pPg->pgno, pPg, -4);
  19243. + CODEC(pPager, pData, pPg->pgno, 7);
  19244. + rc = sqliteOsWrite(&pPager->cpfd, &((char*)pData)[-4], SQLITE_PAGE_SIZE+4);
  19245. + TRACE2("CKPT-JOURNAL %d\n", pPg->pgno);
  19246. + CODEC(pPager, pData, pPg->pgno, 0);
  19247. + if( rc!=SQLITE_OK ){
  19248. + sqlitepager_rollback(pPager);
  19249. + pPager->errMask |= PAGER_ERR_FULL;
  19250. + return rc;
  19251. + }
  19252. + pPager->ckptNRec++;
  19253. + assert( pPager->aInCkpt!=0 );
  19254. + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19255. + page_add_to_ckpt_list(pPg);
  19256. + }
  19257. +
  19258. + /* Update the database size and return.
  19259. + */
  19260. + if( pPager->dbSize<(int)pPg->pgno ){
  19261. + pPager->dbSize = pPg->pgno;
  19262. + }
  19263. + return rc;
  19264. +}
  19265. +
  19266. +/*
  19267. +** Return TRUE if the page given in the argument was previously passed
  19268. +** to sqlitepager_write(). In other words, return TRUE if it is ok
  19269. +** to change the content of the page.
  19270. +*/
  19271. +int sqlitepager_iswriteable(void *pData){
  19272. + PgHdr *pPg = DATA_TO_PGHDR(pData);
  19273. + return pPg->dirty;
  19274. +}
  19275. +
  19276. +/*
  19277. +** Replace the content of a single page with the information in the third
  19278. +** argument.
  19279. +*/
  19280. +int sqlitepager_overwrite(Pager *pPager, Pgno pgno, void *pData){
  19281. + void *pPage;
  19282. + int rc;
  19283. +
  19284. + rc = sqlitepager_get(pPager, pgno, &pPage);
  19285. + if( rc==SQLITE_OK ){
  19286. + rc = sqlitepager_write(pPage);
  19287. + if( rc==SQLITE_OK ){
  19288. + memcpy(pPage, pData, SQLITE_PAGE_SIZE);
  19289. + }
  19290. + sqlitepager_unref(pPage);
  19291. + }
  19292. + return rc;
  19293. +}
  19294. +
  19295. +/*
  19296. +** A call to this routine tells the pager that it is not necessary to
  19297. +** write the information on page "pgno" back to the disk, even though
  19298. +** that page might be marked as dirty.
  19299. +**
  19300. +** The overlying software layer calls this routine when all of the data
  19301. +** on the given page is unused. The pager marks the page as clean so
  19302. +** that it does not get written to disk.
  19303. +**
  19304. +** Tests show that this optimization, together with the
  19305. +** sqlitepager_dont_rollback() below, more than double the speed
  19306. +** of large INSERT operations and quadruple the speed of large DELETEs.
  19307. +**
  19308. +** When this routine is called, set the alwaysRollback flag to true.
  19309. +** Subsequent calls to sqlitepager_dont_rollback() for the same page
  19310. +** will thereafter be ignored. This is necessary to avoid a problem
  19311. +** where a page with data is added to the freelist during one part of
  19312. +** a transaction then removed from the freelist during a later part
  19313. +** of the same transaction and reused for some other purpose. When it
  19314. +** is first added to the freelist, this routine is called. When reused,
  19315. +** the dont_rollback() routine is called. But because the page contains
  19316. +** critical data, we still need to be sure it gets rolled back in spite
  19317. +** of the dont_rollback() call.
  19318. +*/
  19319. +void sqlitepager_dont_write(Pager *pPager, Pgno pgno){
  19320. + PgHdr *pPg;
  19321. +
  19322. + pPg = pager_lookup(pPager, pgno);
  19323. + pPg->alwaysRollback = 1;
  19324. + if( pPg && pPg->dirty && !pPager->ckptInUse ){
  19325. + if( pPager->dbSize==(int)pPg->pgno && pPager->origDbSize<pPager->dbSize ){
  19326. + /* If this pages is the last page in the file and the file has grown
  19327. + ** during the current transaction, then do NOT mark the page as clean.
  19328. + ** When the database file grows, we must make sure that the last page
  19329. + ** gets written at least once so that the disk file will be the correct
  19330. + ** size. If you do not write this page and the size of the file
  19331. + ** on the disk ends up being too small, that can lead to database
  19332. + ** corruption during the next transaction.
  19333. + */
  19334. + }else{
  19335. + TRACE2("DONT_WRITE %d\n", pgno);
  19336. + pPg->dirty = 0;
  19337. + }
  19338. + }
  19339. +}
  19340. +
  19341. +/*
  19342. +** A call to this routine tells the pager that if a rollback occurs,
  19343. +** it is not necessary to restore the data on the given page. This
  19344. +** means that the pager does not have to record the given page in the
  19345. +** rollback journal.
  19346. +*/
  19347. +void sqlitepager_dont_rollback(void *pData){
  19348. + PgHdr *pPg = DATA_TO_PGHDR(pData);
  19349. + Pager *pPager = pPg->pPager;
  19350. +
  19351. + if( pPager->state!=SQLITE_WRITELOCK || pPager->journalOpen==0 ) return;
  19352. + if( pPg->alwaysRollback || pPager->alwaysRollback ) return;
  19353. + if( !pPg->inJournal && (int)pPg->pgno <= pPager->origDbSize ){
  19354. + assert( pPager->aInJournal!=0 );
  19355. + pPager->aInJournal[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19356. + pPg->inJournal = 1;
  19357. + if( pPager->ckptInUse ){
  19358. + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19359. + page_add_to_ckpt_list(pPg);
  19360. + }
  19361. + TRACE2("DONT_ROLLBACK %d\n", pPg->pgno);
  19362. + }
  19363. + if( pPager->ckptInUse && !pPg->inCkpt && (int)pPg->pgno<=pPager->ckptSize ){
  19364. + assert( pPg->inJournal || (int)pPg->pgno>pPager->origDbSize );
  19365. + assert( pPager->aInCkpt!=0 );
  19366. + pPager->aInCkpt[pPg->pgno/8] |= 1<<(pPg->pgno&7);
  19367. + page_add_to_ckpt_list(pPg);
  19368. + }
  19369. +}
  19370. +
  19371. +/*
  19372. +** Commit all changes to the database and release the write lock.
  19373. +**
  19374. +** If the commit fails for any reason, a rollback attempt is made
  19375. +** and an error code is returned. If the commit worked, SQLITE_OK
  19376. +** is returned.
  19377. +*/
  19378. +int sqlitepager_commit(Pager *pPager){
  19379. + int rc;
  19380. + PgHdr *pPg;
  19381. +
  19382. + if( pPager->errMask==PAGER_ERR_FULL ){
  19383. + rc = sqlitepager_rollback(pPager);
  19384. + if( rc==SQLITE_OK ){
  19385. + rc = SQLITE_FULL;
  19386. + }
  19387. + return rc;
  19388. + }
  19389. + if( pPager->errMask!=0 ){
  19390. + rc = pager_errcode(pPager);
  19391. + return rc;
  19392. + }
  19393. + if( pPager->state!=SQLITE_WRITELOCK ){
  19394. + return SQLITE_ERROR;
  19395. + }
  19396. + TRACE1("COMMIT\n");
  19397. + if( pPager->dirtyFile==0 ){
  19398. + /* Exit early (without doing the time-consuming sqliteOsSync() calls)
  19399. + ** if there have been no changes to the database file. */
  19400. + assert( pPager->needSync==0 );
  19401. + rc = pager_unwritelock(pPager);
  19402. + pPager->dbSize = -1;
  19403. + return rc;
  19404. + }
  19405. + assert( pPager->journalOpen );
  19406. + rc = syncJournal(pPager);
  19407. + if( rc!=SQLITE_OK ){
  19408. + goto commit_abort;
  19409. + }
  19410. + pPg = pager_get_all_dirty_pages(pPager);
  19411. + if( pPg ){
  19412. + rc = pager_write_pagelist(pPg);
  19413. + if( rc || (!pPager->noSync && sqliteOsSync(&pPager->fd)!=SQLITE_OK) ){
  19414. + goto commit_abort;
  19415. + }
  19416. + }
  19417. + rc = pager_unwritelock(pPager);
  19418. + pPager->dbSize = -1;
  19419. + return rc;
  19420. +
  19421. + /* Jump here if anything goes wrong during the commit process.
  19422. + */
  19423. +commit_abort:
  19424. + rc = sqlitepager_rollback(pPager);
  19425. + if( rc==SQLITE_OK ){
  19426. + rc = SQLITE_FULL;
  19427. + }
  19428. + return rc;
  19429. +}
  19430. +
  19431. +/*
  19432. +** Rollback all changes. The database falls back to read-only mode.
  19433. +** All in-memory cache pages revert to their original data contents.
  19434. +** The journal is deleted.
  19435. +**
  19436. +** This routine cannot fail unless some other process is not following
  19437. +** the correct locking protocol (SQLITE_PROTOCOL) or unless some other
  19438. +** process is writing trash into the journal file (SQLITE_CORRUPT) or
  19439. +** unless a prior malloc() failed (SQLITE_NOMEM). Appropriate error
  19440. +** codes are returned for all these occasions. Otherwise,
  19441. +** SQLITE_OK is returned.
  19442. +*/
  19443. +int sqlitepager_rollback(Pager *pPager){
  19444. + int rc;
  19445. + TRACE1("ROLLBACK\n");
  19446. + if( !pPager->dirtyFile || !pPager->journalOpen ){
  19447. + rc = pager_unwritelock(pPager);
  19448. + pPager->dbSize = -1;
  19449. + return rc;
  19450. + }
  19451. +
  19452. + if( pPager->errMask!=0 && pPager->errMask!=PAGER_ERR_FULL ){
  19453. + if( pPager->state>=SQLITE_WRITELOCK ){
  19454. + pager_playback(pPager, 1);
  19455. + }
  19456. + return pager_errcode(pPager);
  19457. + }
  19458. + if( pPager->state!=SQLITE_WRITELOCK ){
  19459. + return SQLITE_OK;
  19460. + }
  19461. + rc = pager_playback(pPager, 1);
  19462. + if( rc!=SQLITE_OK ){
  19463. + rc = SQLITE_CORRUPT;
  19464. + pPager->errMask |= PAGER_ERR_CORRUPT;
  19465. + }
  19466. + pPager->dbSize = -1;
  19467. + return rc;
  19468. +}
  19469. +
  19470. +/*
  19471. +** Return TRUE if the database file is opened read-only. Return FALSE
  19472. +** if the database is (in theory) writable.
  19473. +*/
  19474. +int sqlitepager_isreadonly(Pager *pPager){
  19475. + return pPager->readOnly;
  19476. +}
  19477. +
  19478. +/*
  19479. +** This routine is used for testing and analysis only.
  19480. +*/
  19481. +int *sqlitepager_stats(Pager *pPager){
  19482. + static int a[9];
  19483. + a[0] = pPager->nRef;
  19484. + a[1] = pPager->nPage;
  19485. + a[2] = pPager->mxPage;
  19486. + a[3] = pPager->dbSize;
  19487. + a[4] = pPager->state;
  19488. + a[5] = pPager->errMask;
  19489. + a[6] = pPager->nHit;
  19490. + a[7] = pPager->nMiss;
  19491. + a[8] = pPager->nOvfl;
  19492. + return a;
  19493. +}
  19494. +
  19495. +/*
  19496. +** Set the checkpoint.
  19497. +**
  19498. +** This routine should be called with the transaction journal already
  19499. +** open. A new checkpoint journal is created that can be used to rollback
  19500. +** changes of a single SQL command within a larger transaction.
  19501. +*/
  19502. +int sqlitepager_ckpt_begin(Pager *pPager){
  19503. + int rc;
  19504. + char zTemp[SQLITE_TEMPNAME_SIZE];
  19505. + if( !pPager->journalOpen ){
  19506. + pPager->ckptAutoopen = 1;
  19507. + return SQLITE_OK;
  19508. + }
  19509. + assert( pPager->journalOpen );
  19510. + assert( !pPager->ckptInUse );
  19511. + pPager->aInCkpt = sqliteMalloc( pPager->dbSize/8 + 1 );
  19512. + if( pPager->aInCkpt==0 ){
  19513. + sqliteOsReadLock(&pPager->fd);
  19514. + return SQLITE_NOMEM;
  19515. + }
  19516. +#ifndef NDEBUG
  19517. + rc = sqliteOsFileSize(&pPager->jfd, &pPager->ckptJSize);
  19518. + if( rc ) goto ckpt_begin_failed;
  19519. + assert( pPager->ckptJSize ==
  19520. + pPager->nRec*JOURNAL_PG_SZ(journal_format)+JOURNAL_HDR_SZ(journal_format) );
  19521. +#endif
  19522. + pPager->ckptJSize = pPager->nRec*JOURNAL_PG_SZ(journal_format)
  19523. + + JOURNAL_HDR_SZ(journal_format);
  19524. + pPager->ckptSize = pPager->dbSize;
  19525. + if( !pPager->ckptOpen ){
  19526. + rc = sqlitepager_opentemp(zTemp, &pPager->cpfd);
  19527. + if( rc ) goto ckpt_begin_failed;
  19528. + pPager->ckptOpen = 1;
  19529. + pPager->ckptNRec = 0;
  19530. + }
  19531. + pPager->ckptInUse = 1;
  19532. + return SQLITE_OK;
  19533. +
  19534. +ckpt_begin_failed:
  19535. + if( pPager->aInCkpt ){
  19536. + sqliteFree(pPager->aInCkpt);
  19537. + pPager->aInCkpt = 0;
  19538. + }
  19539. + return rc;
  19540. +}
  19541. +
  19542. +/*
  19543. +** Commit a checkpoint.
  19544. +*/
  19545. +int sqlitepager_ckpt_commit(Pager *pPager){
  19546. + if( pPager->ckptInUse ){
  19547. + PgHdr *pPg, *pNext;
  19548. + sqliteOsSeek(&pPager->cpfd, 0);
  19549. + /* sqliteOsTruncate(&pPager->cpfd, 0); */
  19550. + pPager->ckptNRec = 0;
  19551. + pPager->ckptInUse = 0;
  19552. + sqliteFree( pPager->aInCkpt );
  19553. + pPager->aInCkpt = 0;
  19554. + for(pPg=pPager->pCkpt; pPg; pPg=pNext){
  19555. + pNext = pPg->pNextCkpt;
  19556. + assert( pPg->inCkpt );
  19557. + pPg->inCkpt = 0;
  19558. + pPg->pPrevCkpt = pPg->pNextCkpt = 0;
  19559. + }
  19560. + pPager->pCkpt = 0;
  19561. + }
  19562. + pPager->ckptAutoopen = 0;
  19563. + return SQLITE_OK;
  19564. +}
  19565. +
  19566. +/*
  19567. +** Rollback a checkpoint.
  19568. +*/
  19569. +int sqlitepager_ckpt_rollback(Pager *pPager){
  19570. + int rc;
  19571. + if( pPager->ckptInUse ){
  19572. + rc = pager_ckpt_playback(pPager);
  19573. + sqlitepager_ckpt_commit(pPager);
  19574. + }else{
  19575. + rc = SQLITE_OK;
  19576. + }
  19577. + pPager->ckptAutoopen = 0;
  19578. + return rc;
  19579. +}
  19580. +
  19581. +/*
  19582. +** Return the full pathname of the database file.
  19583. +*/
  19584. +const char *sqlitepager_filename(Pager *pPager){
  19585. + return pPager->zFilename;
  19586. +}
  19587. +
  19588. +/*
  19589. +** Set the codec for this pager
  19590. +*/
  19591. +void sqlitepager_set_codec(
  19592. + Pager *pPager,
  19593. + void (*xCodec)(void*,void*,Pgno,int),
  19594. + void *pCodecArg
  19595. +){
  19596. + pPager->xCodec = xCodec;
  19597. + pPager->pCodecArg = pCodecArg;
  19598. +}
  19599. +
  19600. +#ifdef SQLITE_TEST
  19601. +/*
  19602. +** Print a listing of all referenced pages and their ref count.
  19603. +*/
  19604. +void sqlitepager_refdump(Pager *pPager){
  19605. + PgHdr *pPg;
  19606. + for(pPg=pPager->pAll; pPg; pPg=pPg->pNextAll){
  19607. + if( pPg->nRef<=0 ) continue;
  19608. + printf("PAGE %3d addr=0x%08x nRef=%d\n",
  19609. + pPg->pgno, (int)PGHDR_TO_DATA(pPg), pPg->nRef);
  19610. + }
  19611. +}
  19612. +#endif
  19613. --- /dev/null
  19614. +++ b/ext/sqlite/libsqlite/src/pager.h
  19615. @@ -0,0 +1,107 @@
  19616. +/*
  19617. +** 2001 September 15
  19618. +**
  19619. +** The author disclaims copyright to this source code. In place of
  19620. +** a legal notice, here is a blessing:
  19621. +**
  19622. +** May you do good and not evil.
  19623. +** May you find forgiveness for yourself and forgive others.
  19624. +** May you share freely, never taking more than you give.
  19625. +**
  19626. +*************************************************************************
  19627. +** This header file defines the interface that the sqlite page cache
  19628. +** subsystem. The page cache subsystem reads and writes a file a page
  19629. +** at a time and provides a journal for rollback.
  19630. +**
  19631. +** @(#) $Id$
  19632. +*/
  19633. +
  19634. +/*
  19635. +** The size of one page
  19636. +**
  19637. +** You can change this value to another (reasonable) value you want.
  19638. +** It need not be a power of two, though the interface to the disk
  19639. +** will likely be faster if it is.
  19640. +**
  19641. +** Experiments show that a page size of 1024 gives the best speed
  19642. +** for common usages. The speed differences for different sizes
  19643. +** such as 512, 2048, 4096, an so forth, is minimal. Note, however,
  19644. +** that changing the page size results in a completely imcompatible
  19645. +** file format.
  19646. +*/
  19647. +#ifndef SQLITE_PAGE_SIZE
  19648. +#define SQLITE_PAGE_SIZE 1024
  19649. +#endif
  19650. +
  19651. +/*
  19652. +** Number of extra bytes of data allocated at the end of each page and
  19653. +** stored on disk but not used by the higher level btree layer. Changing
  19654. +** this value results in a completely incompatible file format.
  19655. +*/
  19656. +#ifndef SQLITE_PAGE_RESERVE
  19657. +#define SQLITE_PAGE_RESERVE 0
  19658. +#endif
  19659. +
  19660. +/*
  19661. +** The total number of usable bytes stored on disk for each page.
  19662. +** The usable bytes come at the beginning of the page and the reserve
  19663. +** bytes come at the end.
  19664. +*/
  19665. +#define SQLITE_USABLE_SIZE (SQLITE_PAGE_SIZE-SQLITE_PAGE_RESERVE)
  19666. +
  19667. +/*
  19668. +** Maximum number of pages in one database. (This is a limitation of
  19669. +** imposed by 4GB files size limits.)
  19670. +*/
  19671. +#define SQLITE_MAX_PAGE 1073741823
  19672. +
  19673. +/*
  19674. +** The type used to represent a page number. The first page in a file
  19675. +** is called page 1. 0 is used to represent "not a page".
  19676. +*/
  19677. +typedef unsigned int Pgno;
  19678. +
  19679. +/*
  19680. +** Each open file is managed by a separate instance of the "Pager" structure.
  19681. +*/
  19682. +typedef struct Pager Pager;
  19683. +
  19684. +/*
  19685. +** See source code comments for a detailed description of the following
  19686. +** routines:
  19687. +*/
  19688. +int sqlitepager_open(Pager **ppPager, const char *zFilename,
  19689. + int nPage, int nExtra, int useJournal);
  19690. +void sqlitepager_set_destructor(Pager*, void(*)(void*));
  19691. +void sqlitepager_set_cachesize(Pager*, int);
  19692. +int sqlitepager_close(Pager *pPager);
  19693. +int sqlitepager_get(Pager *pPager, Pgno pgno, void **ppPage);
  19694. +void *sqlitepager_lookup(Pager *pPager, Pgno pgno);
  19695. +int sqlitepager_ref(void*);
  19696. +int sqlitepager_unref(void*);
  19697. +Pgno sqlitepager_pagenumber(void*);
  19698. +int sqlitepager_write(void*);
  19699. +int sqlitepager_iswriteable(void*);
  19700. +int sqlitepager_overwrite(Pager *pPager, Pgno pgno, void*);
  19701. +int sqlitepager_pagecount(Pager*);
  19702. +int sqlitepager_truncate(Pager*,Pgno);
  19703. +int sqlitepager_begin(void*);
  19704. +int sqlitepager_commit(Pager*);
  19705. +int sqlitepager_rollback(Pager*);
  19706. +int sqlitepager_isreadonly(Pager*);
  19707. +int sqlitepager_ckpt_begin(Pager*);
  19708. +int sqlitepager_ckpt_commit(Pager*);
  19709. +int sqlitepager_ckpt_rollback(Pager*);
  19710. +void sqlitepager_dont_rollback(void*);
  19711. +void sqlitepager_dont_write(Pager*, Pgno);
  19712. +int *sqlitepager_stats(Pager*);
  19713. +void sqlitepager_set_safety_level(Pager*,int);
  19714. +const char *sqlitepager_filename(Pager*);
  19715. +int sqlitepager_rename(Pager*, const char *zNewName);
  19716. +void sqlitepager_set_codec(Pager*,void(*)(void*,void*,Pgno,int),void*);
  19717. +
  19718. +#ifdef SQLITE_TEST
  19719. +void sqlitepager_refdump(Pager*);
  19720. +int pager_refinfo_enable;
  19721. +int journal_format;
  19722. +#endif
  19723. --- /dev/null
  19724. +++ b/ext/sqlite/libsqlite/src/parse.c
  19725. @@ -0,0 +1,3355 @@
  19726. +/* Driver template for the LEMON parser generator.
  19727. +** The author disclaims copyright to this source code.
  19728. +*/
  19729. +/* First off, code is included that follows the "include" declaration
  19730. +** in the input grammar file. */
  19731. +#include <stdio.h>
  19732. +#line 33 "ext/sqlite/libsqlite/src/parse.y"
  19733. +
  19734. +#include "sqliteInt.h"
  19735. +#include "parse.h"
  19736. +
  19737. +/*
  19738. +** An instance of this structure holds information about the
  19739. +** LIMIT clause of a SELECT statement.
  19740. +*/
  19741. +struct LimitVal {
  19742. + int limit; /* The LIMIT value. -1 if there is no limit */
  19743. + int offset; /* The OFFSET. 0 if there is none */
  19744. +};
  19745. +
  19746. +/*
  19747. +** An instance of the following structure describes the event of a
  19748. +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  19749. +** TK_DELETE, or TK_INSTEAD. If the event is of the form
  19750. +**
  19751. +** UPDATE ON (a,b,c)
  19752. +**
  19753. +** Then the "b" IdList records the list "a,b,c".
  19754. +*/
  19755. +struct TrigEvent { int a; IdList * b; };
  19756. +
  19757. +#line 33 "ext/sqlite/libsqlite/src/parse.c"
  19758. +/* Next is all token values, in a form suitable for use by makeheaders.
  19759. +** This section will be null unless lemon is run with the -m switch.
  19760. +*/
  19761. +/*
  19762. +** These constants (all generated automatically by the parser generator)
  19763. +** specify the various kinds of tokens (terminals) that the parser
  19764. +** understands.
  19765. +**
  19766. +** Each symbol here is a terminal symbol in the grammar.
  19767. +*/
  19768. +/* Make sure the INTERFACE macro is defined.
  19769. +*/
  19770. +#ifndef INTERFACE
  19771. +# define INTERFACE 1
  19772. +#endif
  19773. +/* The next thing included is series of defines which control
  19774. +** various aspects of the generated parser.
  19775. +** YYCODETYPE is the data type used for storing terminal
  19776. +** and nonterminal numbers. "unsigned char" is
  19777. +** used if there are fewer than 250 terminals
  19778. +** and nonterminals. "int" is used otherwise.
  19779. +** YYNOCODE is a number of type YYCODETYPE which corresponds
  19780. +** to no legal terminal or nonterminal number. This
  19781. +** number is used to fill in empty slots of the hash
  19782. +** table.
  19783. +** YYFALLBACK If defined, this indicates that one or more tokens
  19784. +** have fall-back values which should be used if the
  19785. +** original value of the token will not parse.
  19786. +** YYACTIONTYPE is the data type used for storing terminal
  19787. +** and nonterminal numbers. "unsigned char" is
  19788. +** used if there are fewer than 250 rules and
  19789. +** states combined. "int" is used otherwise.
  19790. +** sqliteParserTOKENTYPE is the data type used for minor tokens given
  19791. +** directly to the parser from the tokenizer.
  19792. +** YYMINORTYPE is the data type used for all minor tokens.
  19793. +** This is typically a union of many types, one of
  19794. +** which is sqliteParserTOKENTYPE. The entry in the union
  19795. +** for base tokens is called "yy0".
  19796. +** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  19797. +** zero the stack is dynamically sized using realloc()
  19798. +** sqliteParserARG_SDECL A static variable declaration for the %extra_argument
  19799. +** sqliteParserARG_PDECL A parameter declaration for the %extra_argument
  19800. +** sqliteParserARG_STORE Code to store %extra_argument into yypParser
  19801. +** sqliteParserARG_FETCH Code to extract %extra_argument from yypParser
  19802. +** YYNSTATE the combined number of states.
  19803. +** YYNRULE the number of rules in the grammar
  19804. +** YYERRORSYMBOL is the code number of the error symbol. If not
  19805. +** defined, then do no error processing.
  19806. +*/
  19807. +#define YYCODETYPE unsigned char
  19808. +#define YYNOCODE 221
  19809. +#define YYACTIONTYPE unsigned short int
  19810. +#define sqliteParserTOKENTYPE Token
  19811. +typedef union {
  19812. + int yyinit;
  19813. + sqliteParserTOKENTYPE yy0;
  19814. + TriggerStep * yy19;
  19815. + struct LimitVal yy124;
  19816. + Select* yy179;
  19817. + Expr * yy182;
  19818. + Expr* yy242;
  19819. + struct TrigEvent yy290;
  19820. + SrcList* yy307;
  19821. + IdList* yy320;
  19822. + ExprList* yy322;
  19823. + int yy372;
  19824. + struct {int value; int mask;} yy407;
  19825. +} YYMINORTYPE;
  19826. +#ifndef YYSTACKDEPTH
  19827. +#define YYSTACKDEPTH 100
  19828. +#endif
  19829. +#define sqliteParserARG_SDECL Parse *pParse;
  19830. +#define sqliteParserARG_PDECL ,Parse *pParse
  19831. +#define sqliteParserARG_FETCH Parse *pParse = yypParser->pParse
  19832. +#define sqliteParserARG_STORE yypParser->pParse = pParse
  19833. +#define YYNSTATE 563
  19834. +#define YYNRULE 293
  19835. +#define YYFALLBACK 1
  19836. +#define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  19837. +#define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  19838. +#define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  19839. +
  19840. +/* The yyzerominor constant is used to initialize instances of
  19841. +** YYMINORTYPE objects to zero. */
  19842. +static const YYMINORTYPE yyzerominor = { 0 };
  19843. +
  19844. +/* Define the yytestcase() macro to be a no-op if is not already defined
  19845. +** otherwise.
  19846. +**
  19847. +** Applications can choose to define yytestcase() in the %include section
  19848. +** to a macro that can assist in verifying code coverage. For production
  19849. +** code the yytestcase() macro should be turned off. But it is useful
  19850. +** for testing.
  19851. +*/
  19852. +#ifndef yytestcase
  19853. +# define yytestcase(X)
  19854. +#endif
  19855. +
  19856. +
  19857. +/* Next are the tables used to determine what action to take based on the
  19858. +** current state and lookahead token. These tables are used to implement
  19859. +** functions that take a state number and lookahead value and return an
  19860. +** action integer.
  19861. +**
  19862. +** Suppose the action integer is N. Then the action is determined as
  19863. +** follows
  19864. +**
  19865. +** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  19866. +** token onto the stack and goto state N.
  19867. +**
  19868. +** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  19869. +**
  19870. +** N == YYNSTATE+YYNRULE A syntax error has occurred.
  19871. +**
  19872. +** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  19873. +**
  19874. +** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  19875. +** slots in the yy_action[] table.
  19876. +**
  19877. +** The action table is constructed as a single large table named yy_action[].
  19878. +** Given state S and lookahead X, the action is computed as
  19879. +**
  19880. +** yy_action[ yy_shift_ofst[S] + X ]
  19881. +**
  19882. +** If the index value yy_shift_ofst[S]+X is out of range or if the value
  19883. +** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  19884. +** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  19885. +** and that yy_default[S] should be used instead.
  19886. +**
  19887. +** The formula above is for computing the action when the lookahead is
  19888. +** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  19889. +** a reduce action) then the yy_reduce_ofst[] array is used in place of
  19890. +** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  19891. +** YY_SHIFT_USE_DFLT.
  19892. +**
  19893. +** The following are the tables generated in this section:
  19894. +**
  19895. +** yy_action[] A single table containing all actions.
  19896. +** yy_lookahead[] A table containing the lookahead for each entry in
  19897. +** yy_action. Used to detect hash collisions.
  19898. +** yy_shift_ofst[] For each state, the offset into yy_action for
  19899. +** shifting terminals.
  19900. +** yy_reduce_ofst[] For each state, the offset into yy_action for
  19901. +** shifting non-terminals after a reduce.
  19902. +** yy_default[] Default action for each state.
  19903. +*/
  19904. +#define YY_ACTTAB_COUNT (1090)
  19905. +static const YYACTIONTYPE yy_action[] = {
  19906. + /* 0 */ 186, 561, 483, 69, 67, 70, 68, 64, 63, 62,
  19907. + /* 10 */ 61, 58, 57, 56, 55, 54, 53, 181, 180, 179,
  19908. + /* 20 */ 514, 421, 334, 420, 468, 515, 64, 63, 62, 61,
  19909. + /* 30 */ 58, 57, 56, 55, 54, 53, 9, 423, 422, 71,
  19910. + /* 40 */ 72, 129, 65, 66, 513, 510, 305, 52, 138, 69,
  19911. + /* 50 */ 67, 70, 68, 64, 63, 62, 61, 58, 57, 56,
  19912. + /* 60 */ 55, 54, 53, 448, 469, 175, 482, 514, 470, 344,
  19913. + /* 70 */ 342, 36, 515, 58, 57, 56, 55, 54, 53, 8,
  19914. + /* 80 */ 341, 281, 285, 307, 437, 178, 71, 72, 129, 65,
  19915. + /* 90 */ 66, 513, 510, 305, 52, 138, 69, 67, 70, 68,
  19916. + /* 100 */ 64, 63, 62, 61, 58, 57, 56, 55, 54, 53,
  19917. + /* 110 */ 130, 362, 360, 508, 507, 267, 551, 436, 298, 297,
  19918. + /* 120 */ 369, 368, 50, 128, 543, 29, 266, 449, 537, 447,
  19919. + /* 130 */ 591, 528, 442, 441, 187, 132, 514, 536, 47, 48,
  19920. + /* 140 */ 472, 515, 122, 427, 331, 409, 49, 371, 370, 518,
  19921. + /* 150 */ 328, 363, 517, 520, 45, 71, 72, 129, 65, 66,
  19922. + /* 160 */ 513, 510, 305, 52, 138, 69, 67, 70, 68, 64,
  19923. + /* 170 */ 63, 62, 61, 58, 57, 56, 55, 54, 53, 185,
  19924. + /* 180 */ 550, 549, 512, 175, 467, 516, 18, 344, 342, 36,
  19925. + /* 190 */ 544, 175, 320, 230, 231, 344, 342, 36, 341, 56,
  19926. + /* 200 */ 55, 54, 53, 212, 531, 514, 341, 551, 3, 213,
  19927. + /* 210 */ 515, 2, 551, 73, 7, 551, 184, 132, 551, 172,
  19928. + /* 220 */ 551, 309, 348, 42, 71, 72, 129, 65, 66, 513,
  19929. + /* 230 */ 510, 305, 52, 138, 69, 67, 70, 68, 64, 63,
  19930. + /* 240 */ 62, 61, 58, 57, 56, 55, 54, 53, 243, 197,
  19931. + /* 250 */ 282, 358, 268, 373, 264, 372, 183, 241, 436, 169,
  19932. + /* 260 */ 356, 171, 269, 240, 471, 426, 29, 446, 506, 514,
  19933. + /* 270 */ 445, 550, 549, 494, 515, 354, 550, 549, 359, 550,
  19934. + /* 280 */ 549, 144, 550, 549, 550, 549, 592, 309, 71, 72,
  19935. + /* 290 */ 129, 65, 66, 513, 510, 305, 52, 138, 69, 67,
  19936. + /* 300 */ 70, 68, 64, 63, 62, 61, 58, 57, 56, 55,
  19937. + /* 310 */ 54, 53, 514, 857, 82, 377, 1, 515, 268, 373,
  19938. + /* 320 */ 264, 372, 183, 241, 362, 12, 508, 507, 500, 240,
  19939. + /* 330 */ 17, 71, 72, 129, 65, 66, 513, 510, 305, 52,
  19940. + /* 340 */ 138, 69, 67, 70, 68, 64, 63, 62, 61, 58,
  19941. + /* 350 */ 57, 56, 55, 54, 53, 362, 182, 508, 507, 514,
  19942. + /* 360 */ 362, 527, 508, 507, 515, 563, 429, 463, 182, 444,
  19943. + /* 370 */ 375, 338, 443, 430, 379, 378, 593, 156, 71, 72,
  19944. + /* 380 */ 129, 65, 66, 513, 510, 305, 52, 138, 69, 67,
  19945. + /* 390 */ 70, 68, 64, 63, 62, 61, 58, 57, 56, 55,
  19946. + /* 400 */ 54, 53, 514, 526, 542, 450, 534, 515, 286, 493,
  19947. + /* 410 */ 453, 17, 478, 240, 80, 11, 533, 153, 194, 155,
  19948. + /* 420 */ 286, 71, 51, 129, 65, 66, 513, 510, 305, 52,
  19949. + /* 430 */ 138, 69, 67, 70, 68, 64, 63, 62, 61, 58,
  19950. + /* 440 */ 57, 56, 55, 54, 53, 514, 195, 466, 160, 17,
  19951. + /* 450 */ 515, 454, 490, 80, 459, 440, 460, 176, 239, 238,
  19952. + /* 460 */ 80, 80, 562, 1, 71, 40, 129, 65, 66, 513,
  19953. + /* 470 */ 510, 305, 52, 138, 69, 67, 70, 68, 64, 63,
  19954. + /* 480 */ 62, 61, 58, 57, 56, 55, 54, 53, 514, 365,
  19955. + /* 490 */ 154, 19, 339, 515, 80, 232, 405, 80, 165, 404,
  19956. + /* 500 */ 193, 32, 396, 13, 32, 86, 414, 108, 72, 129,
  19957. + /* 510 */ 65, 66, 513, 510, 305, 52, 138, 69, 67, 70,
  19958. + /* 520 */ 68, 64, 63, 62, 61, 58, 57, 56, 55, 54,
  19959. + /* 530 */ 53, 514, 551, 365, 483, 192, 515, 488, 323, 207,
  19960. + /* 540 */ 366, 249, 177, 186, 87, 483, 483, 46, 38, 44,
  19961. + /* 550 */ 458, 108, 129, 65, 66, 513, 510, 305, 52, 138,
  19962. + /* 560 */ 69, 67, 70, 68, 64, 63, 62, 61, 58, 57,
  19963. + /* 570 */ 56, 55, 54, 53, 274, 457, 272, 271, 270, 23,
  19964. + /* 580 */ 8, 551, 211, 412, 307, 257, 365, 385, 201, 31,
  19965. + /* 590 */ 217, 388, 141, 205, 387, 219, 550, 549, 482, 511,
  19966. + /* 600 */ 215, 376, 560, 134, 90, 477, 214, 514, 392, 482,
  19967. + /* 610 */ 482, 152, 515, 360, 203, 212, 409, 531, 800, 284,
  19968. + /* 620 */ 365, 145, 505, 50, 300, 365, 365, 173, 321, 212,
  19969. + /* 630 */ 487, 137, 135, 8, 41, 136, 531, 307, 93, 47,
  19970. + /* 640 */ 48, 346, 316, 106, 106, 550, 549, 49, 371, 370,
  19971. + /* 650 */ 518, 509, 531, 517, 520, 504, 531, 531, 162, 495,
  19972. + /* 660 */ 170, 317, 503, 319, 223, 231, 360, 551, 502, 283,
  19973. + /* 670 */ 162, 207, 557, 486, 212, 191, 50, 10, 289, 304,
  19974. + /* 680 */ 303, 556, 207, 531, 8, 531, 516, 18, 307, 498,
  19975. + /* 690 */ 498, 189, 47, 48, 393, 531, 555, 28, 302, 554,
  19976. + /* 700 */ 49, 371, 370, 518, 484, 480, 517, 520, 322, 299,
  19977. + /* 710 */ 553, 418, 365, 323, 17, 365, 365, 360, 416, 207,
  19978. + /* 720 */ 322, 417, 207, 418, 327, 212, 480, 50, 207, 326,
  19979. + /* 730 */ 106, 550, 549, 106, 105, 247, 407, 475, 332, 516,
  19980. + /* 740 */ 18, 326, 365, 47, 48, 207, 295, 365, 475, 294,
  19981. + /* 750 */ 158, 49, 371, 370, 518, 293, 473, 517, 520, 485,
  19982. + /* 760 */ 106, 391, 390, 202, 148, 93, 351, 480, 204, 301,
  19983. + /* 770 */ 333, 190, 291, 541, 60, 531, 498, 252, 453, 498,
  19984. + /* 780 */ 365, 365, 290, 365, 501, 475, 365, 79, 475, 531,
  19985. + /* 790 */ 516, 18, 379, 378, 475, 365, 465, 245, 89, 112,
  19986. + /* 800 */ 365, 109, 365, 131, 121, 288, 499, 365, 365, 439,
  19987. + /* 810 */ 365, 475, 365, 120, 365, 365, 343, 365, 119, 365,
  19988. + /* 820 */ 118, 365, 365, 365, 365, 117, 116, 365, 126, 365,
  19989. + /* 830 */ 125, 365, 124, 123, 365, 115, 365, 114, 431, 140,
  19990. + /* 840 */ 139, 255, 254, 365, 365, 253, 365, 280, 365, 107,
  19991. + /* 850 */ 365, 365, 113, 365, 111, 26, 365, 365, 365, 365,
  19992. + /* 860 */ 365, 279, 278, 365, 277, 365, 92, 365, 104, 103,
  19993. + /* 870 */ 365, 91, 365, 365, 102, 101, 110, 100, 99, 347,
  19994. + /* 880 */ 25, 98, 340, 30, 24, 97, 266, 174, 96, 85,
  19995. + /* 890 */ 95, 94, 166, 292, 78, 165, 415, 14, 163, 60,
  19996. + /* 900 */ 164, 22, 6, 408, 5, 77, 34, 33, 159, 16,
  19997. + /* 910 */ 157, 151, 75, 149, 15, 146, 313, 312, 395, 384,
  19998. + /* 920 */ 143, 20, 60, 206, 21, 273, 198, 559, 375, 548,
  19999. + /* 930 */ 547, 546, 374, 4, 540, 539, 538, 308, 535, 532,
  20000. + /* 940 */ 530, 212, 261, 38, 260, 352, 259, 39, 258, 367,
  20001. + /* 950 */ 529, 196, 210, 256, 521, 522, 53, 53, 209, 43,
  20002. + /* 960 */ 496, 188, 492, 208, 256, 81, 246, 37, 479, 349,
  20003. + /* 970 */ 244, 37, 474, 464, 276, 27, 452, 451, 433, 432,
  20004. + /* 980 */ 275, 235, 234, 335, 424, 35, 329, 413, 410, 127,
  20005. + /* 990 */ 161, 84, 76, 403, 38, 400, 188, 399, 224, 398,
  20006. + /* 1000 */ 38, 150, 318, 220, 83, 147, 315, 200, 381, 383,
  20007. + /* 1010 */ 199, 142, 545, 265, 88, 262, 523, 361, 491, 476,
  20008. + /* 1020 */ 463, 406, 397, 287, 389, 386, 310, 382, 552, 74,
  20009. + /* 1030 */ 306, 525, 524, 364, 519, 357, 355, 353, 497, 489,
  20010. + /* 1040 */ 481, 263, 242, 462, 461, 456, 455, 438, 296, 345,
  20011. + /* 1050 */ 434, 237, 425, 337, 168, 167, 336, 236, 419, 330,
  20012. + /* 1060 */ 233, 325, 324, 229, 228, 402, 401, 227, 226, 225,
  20013. + /* 1070 */ 222, 221, 218, 314, 394, 311, 216, 380, 251, 250,
  20014. + /* 1080 */ 133, 350, 248, 364, 558, 59, 435, 411, 428, 212,
  20015. +};
  20016. +static const YYCODETYPE yy_lookahead[] = {
  20017. + /* 0 */ 21, 9, 23, 70, 71, 72, 73, 74, 75, 76,
  20018. + /* 10 */ 77, 78, 79, 80, 81, 82, 83, 100, 101, 102,
  20019. + /* 20 */ 41, 100, 101, 102, 20, 46, 74, 75, 76, 77,
  20020. + /* 30 */ 78, 79, 80, 81, 82, 83, 19, 55, 56, 60,
  20021. + /* 40 */ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70,
  20022. + /* 50 */ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  20023. + /* 60 */ 81, 82, 83, 23, 108, 90, 87, 41, 112, 94,
  20024. + /* 70 */ 95, 96, 46, 78, 79, 80, 81, 82, 83, 19,
  20025. + /* 80 */ 105, 149, 143, 23, 152, 153, 60, 61, 62, 63,
  20026. + /* 90 */ 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
  20027. + /* 100 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  20028. + /* 110 */ 31, 107, 52, 109, 110, 93, 23, 140, 78, 79,
  20029. + /* 120 */ 78, 79, 62, 22, 147, 148, 104, 87, 34, 89,
  20030. + /* 130 */ 113, 89, 92, 93, 183, 184, 41, 43, 78, 79,
  20031. + /* 140 */ 80, 46, 165, 166, 205, 53, 86, 87, 88, 89,
  20032. + /* 150 */ 211, 62, 92, 93, 128, 60, 61, 62, 63, 64,
  20033. + /* 160 */ 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  20034. + /* 170 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 146,
  20035. + /* 180 */ 87, 88, 93, 90, 20, 125, 126, 94, 95, 96,
  20036. + /* 190 */ 20, 90, 100, 101, 102, 94, 95, 96, 105, 80,
  20037. + /* 200 */ 81, 82, 83, 111, 171, 41, 105, 23, 19, 48,
  20038. + /* 210 */ 46, 19, 23, 19, 19, 23, 183, 184, 23, 17,
  20039. + /* 220 */ 23, 62, 189, 128, 60, 61, 62, 63, 64, 65,
  20040. + /* 230 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
  20041. + /* 240 */ 76, 77, 78, 79, 80, 81, 82, 83, 20, 90,
  20042. + /* 250 */ 91, 15, 93, 94, 95, 96, 97, 98, 140, 57,
  20043. + /* 260 */ 24, 59, 144, 104, 80, 147, 148, 89, 20, 41,
  20044. + /* 270 */ 92, 87, 88, 20, 46, 39, 87, 88, 42, 87,
  20045. + /* 280 */ 88, 19, 87, 88, 87, 88, 113, 62, 60, 61,
  20046. + /* 290 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  20047. + /* 300 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  20048. + /* 310 */ 82, 83, 41, 132, 133, 134, 135, 46, 93, 94,
  20049. + /* 320 */ 95, 96, 97, 98, 107, 63, 109, 110, 20, 104,
  20050. + /* 330 */ 22, 60, 61, 62, 63, 64, 65, 66, 67, 68,
  20051. + /* 340 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  20052. + /* 350 */ 79, 80, 81, 82, 83, 107, 47, 109, 110, 41,
  20053. + /* 360 */ 107, 89, 109, 110, 46, 0, 161, 162, 47, 89,
  20054. + /* 370 */ 99, 62, 92, 168, 9, 10, 113, 17, 60, 61,
  20055. + /* 380 */ 62, 63, 64, 65, 66, 67, 68, 69, 70, 71,
  20056. + /* 390 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  20057. + /* 400 */ 82, 83, 41, 89, 155, 156, 26, 46, 99, 20,
  20058. + /* 410 */ 161, 22, 20, 104, 22, 118, 36, 57, 22, 59,
  20059. + /* 420 */ 99, 60, 61, 62, 63, 64, 65, 66, 67, 68,
  20060. + /* 430 */ 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
  20061. + /* 440 */ 79, 80, 81, 82, 83, 41, 50, 20, 22, 22,
  20062. + /* 450 */ 46, 20, 22, 22, 91, 20, 93, 22, 20, 20,
  20063. + /* 460 */ 22, 22, 134, 135, 60, 61, 62, 63, 64, 65,
  20064. + /* 470 */ 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
  20065. + /* 480 */ 76, 77, 78, 79, 80, 81, 82, 83, 41, 140,
  20066. + /* 490 */ 130, 22, 20, 46, 22, 20, 20, 22, 22, 20,
  20067. + /* 500 */ 113, 22, 20, 19, 22, 21, 18, 158, 61, 62,
  20068. + /* 510 */ 63, 64, 65, 66, 67, 68, 69, 70, 71, 72,
  20069. + /* 520 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  20070. + /* 530 */ 83, 41, 23, 140, 23, 113, 46, 22, 140, 140,
  20071. + /* 540 */ 191, 192, 19, 21, 114, 23, 23, 127, 122, 129,
  20072. + /* 550 */ 29, 158, 62, 63, 64, 65, 66, 67, 68, 69,
  20073. + /* 560 */ 70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  20074. + /* 570 */ 80, 81, 82, 83, 11, 54, 13, 14, 15, 16,
  20075. + /* 580 */ 19, 23, 174, 95, 23, 192, 140, 78, 79, 181,
  20076. + /* 590 */ 27, 89, 146, 195, 92, 32, 87, 88, 87, 93,
  20077. + /* 600 */ 37, 136, 137, 88, 158, 206, 141, 41, 99, 87,
  20078. + /* 610 */ 87, 146, 46, 52, 51, 111, 53, 171, 130, 19,
  20079. + /* 620 */ 140, 58, 14, 62, 103, 140, 140, 146, 124, 111,
  20080. + /* 630 */ 115, 146, 146, 19, 68, 69, 171, 23, 158, 78,
  20081. + /* 640 */ 79, 80, 124, 158, 158, 87, 88, 86, 87, 88,
  20082. + /* 650 */ 89, 108, 171, 92, 93, 20, 171, 171, 146, 93,
  20083. + /* 660 */ 146, 196, 20, 100, 101, 102, 52, 23, 20, 106,
  20084. + /* 670 */ 146, 140, 15, 115, 111, 22, 62, 118, 198, 194,
  20085. + /* 680 */ 194, 24, 140, 171, 19, 171, 125, 126, 23, 204,
  20086. + /* 690 */ 204, 22, 78, 79, 140, 171, 39, 19, 167, 42,
  20087. + /* 700 */ 86, 87, 88, 89, 115, 152, 92, 93, 196, 167,
  20088. + /* 710 */ 53, 140, 140, 140, 22, 140, 140, 52, 25, 140,
  20089. + /* 720 */ 196, 28, 140, 140, 212, 111, 152, 62, 140, 217,
  20090. + /* 730 */ 158, 87, 88, 158, 158, 182, 212, 206, 45, 125,
  20091. + /* 740 */ 126, 217, 140, 78, 79, 140, 167, 140, 206, 167,
  20092. + /* 750 */ 146, 86, 87, 88, 89, 167, 182, 92, 93, 115,
  20093. + /* 760 */ 158, 207, 208, 209, 146, 158, 194, 152, 195, 194,
  20094. + /* 770 */ 199, 22, 167, 156, 200, 171, 204, 201, 161, 204,
  20095. + /* 780 */ 140, 140, 199, 140, 20, 206, 140, 20, 206, 171,
  20096. + /* 790 */ 125, 126, 9, 10, 206, 140, 20, 182, 158, 158,
  20097. + /* 800 */ 140, 158, 140, 113, 158, 198, 204, 140, 140, 20,
  20098. + /* 810 */ 140, 206, 140, 158, 140, 140, 48, 140, 158, 140,
  20099. + /* 820 */ 158, 140, 140, 140, 140, 158, 158, 140, 158, 140,
  20100. + /* 830 */ 158, 140, 158, 158, 140, 158, 140, 158, 139, 158,
  20101. + /* 840 */ 158, 158, 158, 140, 140, 158, 140, 158, 140, 158,
  20102. + /* 850 */ 140, 140, 158, 140, 158, 19, 140, 140, 140, 140,
  20103. + /* 860 */ 140, 158, 158, 140, 158, 140, 158, 140, 158, 158,
  20104. + /* 870 */ 140, 158, 140, 140, 158, 158, 158, 158, 158, 140,
  20105. + /* 880 */ 19, 158, 48, 158, 19, 158, 104, 97, 158, 21,
  20106. + /* 890 */ 158, 158, 99, 38, 49, 22, 49, 158, 99, 200,
  20107. + /* 900 */ 130, 19, 11, 14, 9, 103, 63, 63, 123, 19,
  20108. + /* 910 */ 114, 114, 103, 123, 19, 114, 116, 35, 87, 20,
  20109. + /* 920 */ 21, 150, 200, 160, 160, 138, 12, 139, 99, 138,
  20110. + /* 930 */ 138, 138, 145, 22, 139, 139, 164, 44, 139, 139,
  20111. + /* 940 */ 171, 111, 176, 122, 177, 119, 178, 120, 179, 117,
  20112. + /* 950 */ 180, 121, 193, 98, 151, 23, 83, 83, 202, 127,
  20113. + /* 960 */ 186, 113, 186, 193, 98, 186, 187, 99, 188, 116,
  20114. + /* 970 */ 187, 99, 188, 139, 159, 19, 151, 164, 139, 139,
  20115. + /* 980 */ 159, 186, 215, 40, 216, 127, 186, 139, 169, 60,
  20116. + /* 990 */ 169, 197, 19, 176, 122, 186, 113, 186, 186, 176,
  20117. + /* 1000 */ 122, 169, 186, 186, 197, 169, 186, 218, 33, 219,
  20118. + /* 1010 */ 116, 218, 142, 157, 173, 175, 157, 203, 157, 157,
  20119. + /* 1020 */ 162, 176, 176, 152, 210, 210, 152, 152, 140, 140,
  20120. + /* 1030 */ 154, 154, 154, 140, 140, 140, 140, 140, 140, 185,
  20121. + /* 1040 */ 140, 172, 140, 140, 163, 163, 163, 152, 154, 154,
  20122. + /* 1050 */ 140, 140, 140, 140, 140, 213, 214, 140, 140, 140,
  20123. + /* 1060 */ 140, 140, 140, 140, 140, 140, 140, 140, 140, 140,
  20124. + /* 1070 */ 140, 140, 140, 140, 140, 140, 140, 140, 140, 140,
  20125. + /* 1080 */ 140, 140, 140, 140, 170, 200, 166, 170, 166, 111,
  20126. +};
  20127. +#define YY_SHIFT_USE_DFLT (-84)
  20128. +#define YY_SHIFT_COUNT (376)
  20129. +#define YY_SHIFT_MIN (-83)
  20130. +#define YY_SHIFT_MAX (978)
  20131. +static const short yy_shift_ofst[] = {
  20132. + /* 0 */ 783, 563, 614, 614, 93, 92, 92, 978, 614, 561,
  20133. + /* 10 */ 665, 665, 509, 197, -21, 665, 665, 665, 665, 665,
  20134. + /* 20 */ 159, 309, 197, 488, 197, 197, 197, 197, 197, 511,
  20135. + /* 30 */ 271, 60, 665, 665, 665, 665, 665, 665, 665, 665,
  20136. + /* 40 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
  20137. + /* 50 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
  20138. + /* 60 */ 665, 665, 665, 665, 665, 665, 665, 665, 665, 665,
  20139. + /* 70 */ 665, 665, 665, 665, 225, 197, 197, 197, 197, 522,
  20140. + /* 80 */ 197, 522, 365, 518, 504, 978, 978, -84, -84, 228,
  20141. + /* 90 */ 164, 95, 26, 318, 318, 318, 318, 318, 318, 318,
  20142. + /* 100 */ 318, 404, 318, 318, 318, 318, 318, 361, 318, 447,
  20143. + /* 110 */ 490, 490, 490, -67, -67, -67, -67, -67, -48, -48,
  20144. + /* 120 */ -48, -48, 101, -5, -5, -5, -5, 657, -25, 566,
  20145. + /* 130 */ 657, 184, 195, 644, 558, 253, 192, 248, 189, 119,
  20146. + /* 140 */ 119, 4, 197, 197, 197, 197, 197, 197, 217, 197,
  20147. + /* 150 */ 197, 197, 217, 197, 197, 197, 197, 197, 217, 197,
  20148. + /* 160 */ 197, 197, 217, 197, 197, 197, 197, -79, 693, 197,
  20149. + /* 170 */ 217, 197, 197, 217, 197, 197, 42, 42, 523, 521,
  20150. + /* 180 */ 521, 521, 197, 197, 515, 217, 197, 515, 197, 197,
  20151. + /* 190 */ 197, 197, 197, 197, 42, 42, 42, 197, 197, 511,
  20152. + /* 200 */ 511, 502, 502, 511, 426, 426, 321, 380, 380, 420,
  20153. + /* 210 */ 380, 430, -44, 380, 484, 975, 894, 975, 883, 929,
  20154. + /* 220 */ 973, 883, 883, 929, 878, 883, 883, 883, 872, 973,
  20155. + /* 230 */ 929, 929, 829, 848, 858, 943, 848, 956, 829, 829,
  20156. + /* 240 */ 893, 932, 956, 829, 853, 872, 853, 868, 848, 866,
  20157. + /* 250 */ 848, 848, 832, 874, 874, 873, 932, 855, 830, 832,
  20158. + /* 260 */ 827, 826, 821, 830, 829, 829, 893, 829, 829, 911,
  20159. + /* 270 */ 914, 914, 914, 829, 914, -84, -84, -84, -84, -84,
  20160. + /* 280 */ -84, -84, 40, 360, 236, 202, -83, 262, 482, 479,
  20161. + /* 290 */ 476, 475, -18, 472, 439, 438, 435, 280, 178, 431,
  20162. + /* 300 */ 363, 427, 392, 389, 308, 89, 396, 17, 94, 22,
  20163. + /* 310 */ 899, 899, 831, 882, 800, 801, 895, 790, 809, 797,
  20164. + /* 320 */ 796, 890, 785, 844, 843, 802, 895, 889, 891, 882,
  20165. + /* 330 */ 799, 770, 847, 873, 845, 855, 793, 868, 782, 790,
  20166. + /* 340 */ 865, 834, 861, 836, 768, 789, 776, 690, 767, 678,
  20167. + /* 350 */ 589, 692, 559, 764, 669, 648, 749, 642, 653, 635,
  20168. + /* 360 */ 600, 608, 543, 506, 422, 387, 469, 297, 314, 272,
  20169. + /* 370 */ 263, 173, 194, 161, 170, 79, -8,
  20170. +};
  20171. +#define YY_REDUCE_USE_DFLT (-69)
  20172. +#define YY_REDUCE_COUNT (281)
  20173. +#define YY_REDUCE_MIN (-68)
  20174. +#define YY_REDUCE_MAX (943)
  20175. +static const short yy_reduce_ofst[] = {
  20176. + /* 0 */ 181, 465, 486, 485, -23, 524, 512, 33, 446, 575,
  20177. + /* 10 */ 572, 349, 554, 118, 574, 607, 480, 602, 576, 393,
  20178. + /* 20 */ 249, 205, 605, -61, 588, 582, 579, 542, 531, -68,
  20179. + /* 30 */ 699, 739, 733, 732, 730, 727, 725, 723, 720, 719,
  20180. + /* 40 */ 718, 717, 716, 713, 711, 710, 708, 706, 704, 703,
  20181. + /* 50 */ 696, 694, 691, 689, 687, 684, 683, 682, 681, 679,
  20182. + /* 60 */ 677, 675, 674, 672, 670, 668, 667, 662, 660, 655,
  20183. + /* 70 */ 646, 643, 641, 640, 617, 573, 583, 398, 571, 615,
  20184. + /* 80 */ 399, 553, 328, 618, 604, 514, 481, -49, 408, 722,
  20185. + /* 90 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
  20186. + /* 100 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
  20187. + /* 110 */ 722, 722, 722, 722, 722, 722, 722, 722, 722, 722,
  20188. + /* 120 */ 722, 722, 922, 722, 722, 722, 722, 917, 920, 885,
  20189. + /* 130 */ 914, 943, 942, 941, 940, 869, 939, 869, 938, 722,
  20190. + /* 140 */ 722, 869, 937, 936, 935, 934, 933, 932, 869, 931,
  20191. + /* 150 */ 930, 929, 869, 928, 927, 926, 925, 924, 869, 923,
  20192. + /* 160 */ 922, 921, 869, 920, 919, 918, 917, 842, 842, 914,
  20193. + /* 170 */ 869, 913, 912, 869, 911, 910, 895, 894, 895, 883,
  20194. + /* 180 */ 882, 881, 903, 902, 854, 869, 900, 854, 898, 897,
  20195. + /* 190 */ 896, 895, 894, 893, 878, 877, 876, 889, 888, 875,
  20196. + /* 200 */ 874, 815, 814, 871, 846, 845, 858, 862, 861, 814,
  20197. + /* 210 */ 859, 840, 841, 856, 870, 793, 790, 789, 820, 836,
  20198. + /* 220 */ 807, 817, 816, 832, 823, 812, 811, 809, 817, 794,
  20199. + /* 230 */ 821, 819, 848, 800, 768, 767, 795, 821, 840, 839,
  20200. + /* 240 */ 813, 825, 815, 834, 784, 783, 780, 779, 779, 770,
  20201. + /* 250 */ 776, 774, 756, 722, 722, 722, 803, 759, 770, 769,
  20202. + /* 260 */ 768, 767, 766, 769, 800, 799, 772, 796, 795, 787,
  20203. + /* 270 */ 793, 792, 791, 788, 787, 764, 763, 722, 722, 722,
  20204. + /* 280 */ 722, 771,
  20205. +};
  20206. +static const YYACTIONTYPE yy_default[] = {
  20207. + /* 0 */ 570, 856, 797, 797, 856, 839, 839, 685, 856, 797,
  20208. + /* 10 */ 797, 856, 822, 856, 681, 856, 856, 797, 793, 856,
  20209. + /* 20 */ 586, 649, 856, 581, 856, 856, 856, 856, 856, 594,
  20210. + /* 30 */ 651, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20211. + /* 40 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20212. + /* 50 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20213. + /* 60 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20214. + /* 70 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 681,
  20215. + /* 80 */ 856, 681, 570, 856, 856, 856, 856, 685, 675, 856,
  20216. + /* 90 */ 856, 856, 856, 730, 729, 724, 723, 837, 697, 721,
  20217. + /* 100 */ 714, 856, 789, 790, 788, 792, 796, 856, 705, 748,
  20218. + /* 110 */ 780, 774, 747, 779, 760, 759, 754, 753, 752, 751,
  20219. + /* 120 */ 750, 749, 640, 758, 757, 756, 755, 856, 856, 856,
  20220. + /* 130 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 764,
  20221. + /* 140 */ 763, 856, 856, 856, 856, 809, 856, 856, 726, 856,
  20222. + /* 150 */ 856, 856, 663, 856, 856, 856, 856, 856, 842, 856,
  20223. + /* 160 */ 856, 856, 844, 856, 856, 856, 856, 856, 828, 856,
  20224. + /* 170 */ 661, 856, 856, 583, 856, 856, 856, 856, 595, 856,
  20225. + /* 180 */ 856, 856, 856, 856, 689, 688, 856, 683, 856, 856,
  20226. + /* 190 */ 856, 856, 856, 856, 856, 856, 856, 856, 573, 856,
  20227. + /* 200 */ 856, 856, 856, 856, 720, 720, 621, 708, 708, 791,
  20228. + /* 210 */ 708, 682, 673, 708, 856, 854, 852, 854, 690, 653,
  20229. + /* 220 */ 731, 690, 690, 653, 720, 690, 690, 690, 720, 731,
  20230. + /* 230 */ 653, 653, 651, 690, 836, 833, 690, 801, 651, 651,
  20231. + /* 240 */ 636, 856, 801, 651, 700, 698, 700, 698, 690, 709,
  20232. + /* 250 */ 690, 690, 856, 767, 766, 765, 856, 709, 715, 701,
  20233. + /* 260 */ 713, 711, 720, 856, 651, 651, 636, 651, 651, 639,
  20234. + /* 270 */ 572, 572, 572, 651, 572, 624, 624, 777, 776, 775,
  20235. + /* 280 */ 768, 604, 856, 856, 856, 856, 856, 816, 856, 856,
  20236. + /* 290 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20237. + /* 300 */ 856, 856, 856, 856, 856, 856, 716, 737, 856, 856,
  20238. + /* 310 */ 856, 856, 856, 856, 808, 856, 856, 856, 856, 856,
  20239. + /* 320 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20240. + /* 330 */ 856, 856, 856, 832, 831, 856, 856, 856, 856, 856,
  20241. + /* 340 */ 856, 856, 856, 856, 856, 856, 856, 856, 856, 856,
  20242. + /* 350 */ 856, 712, 856, 856, 856, 856, 856, 856, 856, 856,
  20243. + /* 360 */ 856, 856, 666, 856, 739, 856, 702, 856, 856, 856,
  20244. + /* 370 */ 738, 743, 856, 856, 856, 856, 856, 565, 569, 567,
  20245. + /* 380 */ 855, 853, 851, 850, 815, 821, 818, 820, 819, 817,
  20246. + /* 390 */ 814, 813, 812, 811, 810, 807, 725, 722, 719, 849,
  20247. + /* 400 */ 806, 662, 660, 843, 841, 732, 840, 838, 823, 728,
  20248. + /* 410 */ 727, 654, 799, 798, 580, 827, 826, 825, 734, 733,
  20249. + /* 420 */ 830, 829, 835, 834, 824, 579, 585, 643, 642, 650,
  20250. + /* 430 */ 648, 647, 646, 645, 644, 641, 587, 598, 599, 597,
  20251. + /* 440 */ 596, 615, 612, 614, 611, 613, 610, 609, 608, 607,
  20252. + /* 450 */ 606, 635, 623, 622, 802, 629, 628, 633, 632, 631,
  20253. + /* 460 */ 630, 627, 626, 625, 620, 746, 745, 735, 778, 672,
  20254. + /* 470 */ 671, 678, 677, 676, 687, 804, 805, 803, 699, 686,
  20255. + /* 480 */ 680, 679, 590, 589, 696, 695, 694, 693, 692, 684,
  20256. + /* 490 */ 674, 704, 786, 783, 784, 772, 785, 691, 795, 794,
  20257. + /* 500 */ 781, 848, 847, 846, 845, 787, 782, 669, 668, 667,
  20258. + /* 510 */ 771, 773, 770, 769, 762, 761, 744, 742, 741, 740,
  20259. + /* 520 */ 736, 710, 588, 703, 718, 717, 602, 601, 600, 670,
  20260. + /* 530 */ 665, 664, 619, 707, 706, 618, 638, 637, 634, 617,
  20261. + /* 540 */ 616, 605, 603, 584, 582, 578, 577, 576, 575, 593,
  20262. + /* 550 */ 592, 591, 574, 659, 658, 657, 656, 655, 652, 571,
  20263. + /* 560 */ 568, 566, 564,
  20264. +};
  20265. +
  20266. +/* The next table maps tokens into fallback tokens. If a construct
  20267. +** like the following:
  20268. +**
  20269. +** %fallback ID X Y Z.
  20270. +**
  20271. +** appears in the grammar, then ID becomes a fallback token for X, Y,
  20272. +** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  20273. +** but it does not parse, the type of the token is changed to ID and
  20274. +** the parse is retried before an error is thrown.
  20275. +*/
  20276. +#ifdef YYFALLBACK
  20277. +static const YYCODETYPE yyFallback[] = {
  20278. + 0, /* $ => nothing */
  20279. + 0, /* END_OF_FILE => nothing */
  20280. + 0, /* ILLEGAL => nothing */
  20281. + 0, /* SPACE => nothing */
  20282. + 0, /* UNCLOSED_STRING => nothing */
  20283. + 0, /* COMMENT => nothing */
  20284. + 0, /* FUNCTION => nothing */
  20285. + 0, /* COLUMN => nothing */
  20286. + 0, /* AGG_FUNCTION => nothing */
  20287. + 0, /* SEMI => nothing */
  20288. + 23, /* EXPLAIN => ID */
  20289. + 23, /* BEGIN => ID */
  20290. + 0, /* TRANSACTION => nothing */
  20291. + 0, /* COMMIT => nothing */
  20292. + 23, /* END => ID */
  20293. + 0, /* ROLLBACK => nothing */
  20294. + 0, /* CREATE => nothing */
  20295. + 0, /* TABLE => nothing */
  20296. + 23, /* TEMP => ID */
  20297. + 0, /* LP => nothing */
  20298. + 0, /* RP => nothing */
  20299. + 0, /* AS => nothing */
  20300. + 0, /* COMMA => nothing */
  20301. + 0, /* ID => nothing */
  20302. + 23, /* ABORT => ID */
  20303. + 23, /* AFTER => ID */
  20304. + 23, /* ASC => ID */
  20305. + 23, /* ATTACH => ID */
  20306. + 23, /* BEFORE => ID */
  20307. + 23, /* CASCADE => ID */
  20308. + 23, /* CLUSTER => ID */
  20309. + 23, /* CONFLICT => ID */
  20310. + 23, /* COPY => ID */
  20311. + 23, /* DATABASE => ID */
  20312. + 23, /* DEFERRED => ID */
  20313. + 23, /* DELIMITERS => ID */
  20314. + 23, /* DESC => ID */
  20315. + 23, /* DETACH => ID */
  20316. + 23, /* EACH => ID */
  20317. + 23, /* FAIL => ID */
  20318. + 23, /* FOR => ID */
  20319. + 23, /* GLOB => ID */
  20320. + 23, /* IGNORE => ID */
  20321. + 23, /* IMMEDIATE => ID */
  20322. + 23, /* INITIALLY => ID */
  20323. + 23, /* INSTEAD => ID */
  20324. + 23, /* LIKE => ID */
  20325. + 23, /* MATCH => ID */
  20326. + 23, /* KEY => ID */
  20327. + 23, /* OF => ID */
  20328. + 23, /* OFFSET => ID */
  20329. + 23, /* PRAGMA => ID */
  20330. + 23, /* RAISE => ID */
  20331. + 23, /* REPLACE => ID */
  20332. + 23, /* RESTRICT => ID */
  20333. + 23, /* ROW => ID */
  20334. + 23, /* STATEMENT => ID */
  20335. + 23, /* TRIGGER => ID */
  20336. + 23, /* VACUUM => ID */
  20337. + 23, /* VIEW => ID */
  20338. +};
  20339. +#endif /* YYFALLBACK */
  20340. +
  20341. +/* The following structure represents a single element of the
  20342. +** parser's stack. Information stored includes:
  20343. +**
  20344. +** + The state number for the parser at this level of the stack.
  20345. +**
  20346. +** + The value of the token stored at this level of the stack.
  20347. +** (In other words, the "major" token.)
  20348. +**
  20349. +** + The semantic value stored at this level of the stack. This is
  20350. +** the information used by the action routines in the grammar.
  20351. +** It is sometimes called the "minor" token.
  20352. +*/
  20353. +struct yyStackEntry {
  20354. + YYACTIONTYPE stateno; /* The state-number */
  20355. + YYCODETYPE major; /* The major token value. This is the code
  20356. + ** number for the token at this stack level */
  20357. + YYMINORTYPE minor; /* The user-supplied minor token value. This
  20358. + ** is the value of the token */
  20359. +};
  20360. +typedef struct yyStackEntry yyStackEntry;
  20361. +
  20362. +/* The state of the parser is completely contained in an instance of
  20363. +** the following structure */
  20364. +struct yyParser {
  20365. + int yyidx; /* Index of top element in stack */
  20366. +#ifdef YYTRACKMAXSTACKDEPTH
  20367. + int yyidxMax; /* Maximum value of yyidx */
  20368. +#endif
  20369. + int yyerrcnt; /* Shifts left before out of the error */
  20370. + sqliteParserARG_SDECL /* A place to hold %extra_argument */
  20371. +#if YYSTACKDEPTH<=0
  20372. + int yystksz; /* Current side of the stack */
  20373. + yyStackEntry *yystack; /* The parser's stack */
  20374. +#else
  20375. + yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  20376. +#endif
  20377. +};
  20378. +typedef struct yyParser yyParser;
  20379. +
  20380. +#ifndef NDEBUG
  20381. +#include <stdio.h>
  20382. +static FILE *yyTraceFILE = 0;
  20383. +static char *yyTracePrompt = 0;
  20384. +#endif /* NDEBUG */
  20385. +
  20386. +#ifndef NDEBUG
  20387. +/*
  20388. +** Turn parser tracing on by giving a stream to which to write the trace
  20389. +** and a prompt to preface each trace message. Tracing is turned off
  20390. +** by making either argument NULL
  20391. +**
  20392. +** Inputs:
  20393. +** <ul>
  20394. +** <li> A FILE* to which trace output should be written.
  20395. +** If NULL, then tracing is turned off.
  20396. +** <li> A prefix string written at the beginning of every
  20397. +** line of trace output. If NULL, then tracing is
  20398. +** turned off.
  20399. +** </ul>
  20400. +**
  20401. +** Outputs:
  20402. +** None.
  20403. +*/
  20404. +void sqliteParserTrace(FILE *TraceFILE, char *zTracePrompt){
  20405. + yyTraceFILE = TraceFILE;
  20406. + yyTracePrompt = zTracePrompt;
  20407. + if( yyTraceFILE==0 ) yyTracePrompt = 0;
  20408. + else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  20409. +}
  20410. +#endif /* NDEBUG */
  20411. +
  20412. +#ifndef NDEBUG
  20413. +/* For tracing shifts, the names of all terminals and nonterminals
  20414. +** are required. The following table supplies these names */
  20415. +static const char *const yyTokenName[] = {
  20416. + "$", "END_OF_FILE", "ILLEGAL", "SPACE",
  20417. + "UNCLOSED_STRING", "COMMENT", "FUNCTION", "COLUMN",
  20418. + "AGG_FUNCTION", "SEMI", "EXPLAIN", "BEGIN",
  20419. + "TRANSACTION", "COMMIT", "END", "ROLLBACK",
  20420. + "CREATE", "TABLE", "TEMP", "LP",
  20421. + "RP", "AS", "COMMA", "ID",
  20422. + "ABORT", "AFTER", "ASC", "ATTACH",
  20423. + "BEFORE", "CASCADE", "CLUSTER", "CONFLICT",
  20424. + "COPY", "DATABASE", "DEFERRED", "DELIMITERS",
  20425. + "DESC", "DETACH", "EACH", "FAIL",
  20426. + "FOR", "GLOB", "IGNORE", "IMMEDIATE",
  20427. + "INITIALLY", "INSTEAD", "LIKE", "MATCH",
  20428. + "KEY", "OF", "OFFSET", "PRAGMA",
  20429. + "RAISE", "REPLACE", "RESTRICT", "ROW",
  20430. + "STATEMENT", "TRIGGER", "VACUUM", "VIEW",
  20431. + "OR", "AND", "NOT", "EQ",
  20432. + "NE", "ISNULL", "NOTNULL", "IS",
  20433. + "BETWEEN", "IN", "GT", "GE",
  20434. + "LT", "LE", "BITAND", "BITOR",
  20435. + "LSHIFT", "RSHIFT", "PLUS", "MINUS",
  20436. + "STAR", "SLASH", "REM", "CONCAT",
  20437. + "UMINUS", "UPLUS", "BITNOT", "STRING",
  20438. + "JOIN_KW", "INTEGER", "CONSTRAINT", "DEFAULT",
  20439. + "FLOAT", "NULL", "PRIMARY", "UNIQUE",
  20440. + "CHECK", "REFERENCES", "COLLATE", "ON",
  20441. + "DELETE", "UPDATE", "INSERT", "SET",
  20442. + "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  20443. + "ALL", "INTERSECT", "EXCEPT", "SELECT",
  20444. + "DISTINCT", "DOT", "FROM", "JOIN",
  20445. + "USING", "ORDER", "BY", "GROUP",
  20446. + "HAVING", "LIMIT", "WHERE", "INTO",
  20447. + "VALUES", "VARIABLE", "CASE", "WHEN",
  20448. + "THEN", "ELSE", "INDEX", "error",
  20449. + "input", "cmdlist", "ecmd", "explain",
  20450. + "cmdx", "cmd", "trans_opt", "onconf",
  20451. + "nm", "create_table", "create_table_args", "temp",
  20452. + "columnlist", "conslist_opt", "select", "column",
  20453. + "columnid", "type", "carglist", "id",
  20454. + "ids", "typename", "signed", "carg",
  20455. + "ccons", "sortorder", "expr", "idxlist_opt",
  20456. + "refargs", "defer_subclause", "refarg", "refact",
  20457. + "init_deferred_pred_opt", "conslist", "tcons", "idxlist",
  20458. + "defer_subclause_opt", "orconf", "resolvetype", "oneselect",
  20459. + "multiselect_op", "distinct", "selcollist", "from",
  20460. + "where_opt", "groupby_opt", "having_opt", "orderby_opt",
  20461. + "limit_opt", "sclp", "as", "seltablist",
  20462. + "stl_prefix", "joinop", "dbnm", "on_opt",
  20463. + "using_opt", "seltablist_paren", "joinop2", "sortlist",
  20464. + "sortitem", "collate", "exprlist", "setlist",
  20465. + "insert_cmd", "inscollist_opt", "itemlist", "inscollist",
  20466. + "likeop", "case_operand", "case_exprlist", "case_else",
  20467. + "expritem", "uniqueflag", "idxitem", "plus_num",
  20468. + "minus_num", "plus_opt", "number", "trigger_decl",
  20469. + "trigger_cmd_list", "trigger_time", "trigger_event", "foreach_clause",
  20470. + "when_clause", "trigger_cmd", "database_kw_opt", "key_opt",
  20471. +};
  20472. +#endif /* NDEBUG */
  20473. +
  20474. +#ifndef NDEBUG
  20475. +/* For tracing reduce actions, the names of all rules are required.
  20476. +*/
  20477. +static const char *const yyRuleName[] = {
  20478. + /* 0 */ "input ::= cmdlist",
  20479. + /* 1 */ "cmdlist ::= cmdlist ecmd",
  20480. + /* 2 */ "cmdlist ::= ecmd",
  20481. + /* 3 */ "ecmd ::= explain cmdx SEMI",
  20482. + /* 4 */ "ecmd ::= SEMI",
  20483. + /* 5 */ "cmdx ::= cmd",
  20484. + /* 6 */ "explain ::= EXPLAIN",
  20485. + /* 7 */ "explain ::=",
  20486. + /* 8 */ "cmd ::= BEGIN trans_opt onconf",
  20487. + /* 9 */ "trans_opt ::=",
  20488. + /* 10 */ "trans_opt ::= TRANSACTION",
  20489. + /* 11 */ "trans_opt ::= TRANSACTION nm",
  20490. + /* 12 */ "cmd ::= COMMIT trans_opt",
  20491. + /* 13 */ "cmd ::= END trans_opt",
  20492. + /* 14 */ "cmd ::= ROLLBACK trans_opt",
  20493. + /* 15 */ "cmd ::= create_table create_table_args",
  20494. + /* 16 */ "create_table ::= CREATE temp TABLE nm",
  20495. + /* 17 */ "temp ::= TEMP",
  20496. + /* 18 */ "temp ::=",
  20497. + /* 19 */ "create_table_args ::= LP columnlist conslist_opt RP",
  20498. + /* 20 */ "create_table_args ::= AS select",
  20499. + /* 21 */ "columnlist ::= columnlist COMMA column",
  20500. + /* 22 */ "columnlist ::= column",
  20501. + /* 23 */ "column ::= columnid type carglist",
  20502. + /* 24 */ "columnid ::= nm",
  20503. + /* 25 */ "id ::= ID",
  20504. + /* 26 */ "ids ::= ID",
  20505. + /* 27 */ "ids ::= STRING",
  20506. + /* 28 */ "nm ::= ID",
  20507. + /* 29 */ "nm ::= STRING",
  20508. + /* 30 */ "nm ::= JOIN_KW",
  20509. + /* 31 */ "type ::=",
  20510. + /* 32 */ "type ::= typename",
  20511. + /* 33 */ "type ::= typename LP signed RP",
  20512. + /* 34 */ "type ::= typename LP signed COMMA signed RP",
  20513. + /* 35 */ "typename ::= ids",
  20514. + /* 36 */ "typename ::= typename ids",
  20515. + /* 37 */ "signed ::= INTEGER",
  20516. + /* 38 */ "signed ::= PLUS INTEGER",
  20517. + /* 39 */ "signed ::= MINUS INTEGER",
  20518. + /* 40 */ "carglist ::= carglist carg",
  20519. + /* 41 */ "carglist ::=",
  20520. + /* 42 */ "carg ::= CONSTRAINT nm ccons",
  20521. + /* 43 */ "carg ::= ccons",
  20522. + /* 44 */ "carg ::= DEFAULT STRING",
  20523. + /* 45 */ "carg ::= DEFAULT ID",
  20524. + /* 46 */ "carg ::= DEFAULT INTEGER",
  20525. + /* 47 */ "carg ::= DEFAULT PLUS INTEGER",
  20526. + /* 48 */ "carg ::= DEFAULT MINUS INTEGER",
  20527. + /* 49 */ "carg ::= DEFAULT FLOAT",
  20528. + /* 50 */ "carg ::= DEFAULT PLUS FLOAT",
  20529. + /* 51 */ "carg ::= DEFAULT MINUS FLOAT",
  20530. + /* 52 */ "carg ::= DEFAULT NULL",
  20531. + /* 53 */ "ccons ::= NULL onconf",
  20532. + /* 54 */ "ccons ::= NOT NULL onconf",
  20533. + /* 55 */ "ccons ::= PRIMARY KEY sortorder onconf",
  20534. + /* 56 */ "ccons ::= UNIQUE onconf",
  20535. + /* 57 */ "ccons ::= CHECK LP expr RP onconf",
  20536. + /* 58 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  20537. + /* 59 */ "ccons ::= defer_subclause",
  20538. + /* 60 */ "ccons ::= COLLATE id",
  20539. + /* 61 */ "refargs ::=",
  20540. + /* 62 */ "refargs ::= refargs refarg",
  20541. + /* 63 */ "refarg ::= MATCH nm",
  20542. + /* 64 */ "refarg ::= ON DELETE refact",
  20543. + /* 65 */ "refarg ::= ON UPDATE refact",
  20544. + /* 66 */ "refarg ::= ON INSERT refact",
  20545. + /* 67 */ "refact ::= SET NULL",
  20546. + /* 68 */ "refact ::= SET DEFAULT",
  20547. + /* 69 */ "refact ::= CASCADE",
  20548. + /* 70 */ "refact ::= RESTRICT",
  20549. + /* 71 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  20550. + /* 72 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  20551. + /* 73 */ "init_deferred_pred_opt ::=",
  20552. + /* 74 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  20553. + /* 75 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  20554. + /* 76 */ "conslist_opt ::=",
  20555. + /* 77 */ "conslist_opt ::= COMMA conslist",
  20556. + /* 78 */ "conslist ::= conslist COMMA tcons",
  20557. + /* 79 */ "conslist ::= conslist tcons",
  20558. + /* 80 */ "conslist ::= tcons",
  20559. + /* 81 */ "tcons ::= CONSTRAINT nm",
  20560. + /* 82 */ "tcons ::= PRIMARY KEY LP idxlist RP onconf",
  20561. + /* 83 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  20562. + /* 84 */ "tcons ::= CHECK expr onconf",
  20563. + /* 85 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  20564. + /* 86 */ "defer_subclause_opt ::=",
  20565. + /* 87 */ "defer_subclause_opt ::= defer_subclause",
  20566. + /* 88 */ "onconf ::=",
  20567. + /* 89 */ "onconf ::= ON CONFLICT resolvetype",
  20568. + /* 90 */ "orconf ::=",
  20569. + /* 91 */ "orconf ::= OR resolvetype",
  20570. + /* 92 */ "resolvetype ::= ROLLBACK",
  20571. + /* 93 */ "resolvetype ::= ABORT",
  20572. + /* 94 */ "resolvetype ::= FAIL",
  20573. + /* 95 */ "resolvetype ::= IGNORE",
  20574. + /* 96 */ "resolvetype ::= REPLACE",
  20575. + /* 97 */ "cmd ::= DROP TABLE nm",
  20576. + /* 98 */ "cmd ::= CREATE temp VIEW nm AS select",
  20577. + /* 99 */ "cmd ::= DROP VIEW nm",
  20578. + /* 100 */ "cmd ::= select",
  20579. + /* 101 */ "select ::= oneselect",
  20580. + /* 102 */ "select ::= select multiselect_op oneselect",
  20581. + /* 103 */ "multiselect_op ::= UNION",
  20582. + /* 104 */ "multiselect_op ::= UNION ALL",
  20583. + /* 105 */ "multiselect_op ::= INTERSECT",
  20584. + /* 106 */ "multiselect_op ::= EXCEPT",
  20585. + /* 107 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  20586. + /* 108 */ "distinct ::= DISTINCT",
  20587. + /* 109 */ "distinct ::= ALL",
  20588. + /* 110 */ "distinct ::=",
  20589. + /* 111 */ "sclp ::= selcollist COMMA",
  20590. + /* 112 */ "sclp ::=",
  20591. + /* 113 */ "selcollist ::= sclp expr as",
  20592. + /* 114 */ "selcollist ::= sclp STAR",
  20593. + /* 115 */ "selcollist ::= sclp nm DOT STAR",
  20594. + /* 116 */ "as ::= AS nm",
  20595. + /* 117 */ "as ::= ids",
  20596. + /* 118 */ "as ::=",
  20597. + /* 119 */ "from ::=",
  20598. + /* 120 */ "from ::= FROM seltablist",
  20599. + /* 121 */ "stl_prefix ::= seltablist joinop",
  20600. + /* 122 */ "stl_prefix ::=",
  20601. + /* 123 */ "seltablist ::= stl_prefix nm dbnm as on_opt using_opt",
  20602. + /* 124 */ "seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt",
  20603. + /* 125 */ "seltablist_paren ::= select",
  20604. + /* 126 */ "seltablist_paren ::= seltablist",
  20605. + /* 127 */ "dbnm ::=",
  20606. + /* 128 */ "dbnm ::= DOT nm",
  20607. + /* 129 */ "joinop ::= COMMA",
  20608. + /* 130 */ "joinop ::= JOIN",
  20609. + /* 131 */ "joinop ::= JOIN_KW JOIN",
  20610. + /* 132 */ "joinop ::= JOIN_KW nm JOIN",
  20611. + /* 133 */ "joinop ::= JOIN_KW nm nm JOIN",
  20612. + /* 134 */ "on_opt ::= ON expr",
  20613. + /* 135 */ "on_opt ::=",
  20614. + /* 136 */ "using_opt ::= USING LP idxlist RP",
  20615. + /* 137 */ "using_opt ::=",
  20616. + /* 138 */ "orderby_opt ::=",
  20617. + /* 139 */ "orderby_opt ::= ORDER BY sortlist",
  20618. + /* 140 */ "sortlist ::= sortlist COMMA sortitem collate sortorder",
  20619. + /* 141 */ "sortlist ::= sortitem collate sortorder",
  20620. + /* 142 */ "sortitem ::= expr",
  20621. + /* 143 */ "sortorder ::= ASC",
  20622. + /* 144 */ "sortorder ::= DESC",
  20623. + /* 145 */ "sortorder ::=",
  20624. + /* 146 */ "collate ::=",
  20625. + /* 147 */ "collate ::= COLLATE id",
  20626. + /* 148 */ "groupby_opt ::=",
  20627. + /* 149 */ "groupby_opt ::= GROUP BY exprlist",
  20628. + /* 150 */ "having_opt ::=",
  20629. + /* 151 */ "having_opt ::= HAVING expr",
  20630. + /* 152 */ "limit_opt ::=",
  20631. + /* 153 */ "limit_opt ::= LIMIT signed",
  20632. + /* 154 */ "limit_opt ::= LIMIT signed OFFSET signed",
  20633. + /* 155 */ "limit_opt ::= LIMIT signed COMMA signed",
  20634. + /* 156 */ "cmd ::= DELETE FROM nm dbnm where_opt",
  20635. + /* 157 */ "where_opt ::=",
  20636. + /* 158 */ "where_opt ::= WHERE expr",
  20637. + /* 159 */ "cmd ::= UPDATE orconf nm dbnm SET setlist where_opt",
  20638. + /* 160 */ "setlist ::= setlist COMMA nm EQ expr",
  20639. + /* 161 */ "setlist ::= nm EQ expr",
  20640. + /* 162 */ "cmd ::= insert_cmd INTO nm dbnm inscollist_opt VALUES LP itemlist RP",
  20641. + /* 163 */ "cmd ::= insert_cmd INTO nm dbnm inscollist_opt select",
  20642. + /* 164 */ "insert_cmd ::= INSERT orconf",
  20643. + /* 165 */ "insert_cmd ::= REPLACE",
  20644. + /* 166 */ "itemlist ::= itemlist COMMA expr",
  20645. + /* 167 */ "itemlist ::= expr",
  20646. + /* 168 */ "inscollist_opt ::=",
  20647. + /* 169 */ "inscollist_opt ::= LP inscollist RP",
  20648. + /* 170 */ "inscollist ::= inscollist COMMA nm",
  20649. + /* 171 */ "inscollist ::= nm",
  20650. + /* 172 */ "expr ::= LP expr RP",
  20651. + /* 173 */ "expr ::= NULL",
  20652. + /* 174 */ "expr ::= ID",
  20653. + /* 175 */ "expr ::= JOIN_KW",
  20654. + /* 176 */ "expr ::= nm DOT nm",
  20655. + /* 177 */ "expr ::= nm DOT nm DOT nm",
  20656. + /* 178 */ "expr ::= INTEGER",
  20657. + /* 179 */ "expr ::= FLOAT",
  20658. + /* 180 */ "expr ::= STRING",
  20659. + /* 181 */ "expr ::= VARIABLE",
  20660. + /* 182 */ "expr ::= ID LP exprlist RP",
  20661. + /* 183 */ "expr ::= ID LP STAR RP",
  20662. + /* 184 */ "expr ::= expr AND expr",
  20663. + /* 185 */ "expr ::= expr OR expr",
  20664. + /* 186 */ "expr ::= expr LT expr",
  20665. + /* 187 */ "expr ::= expr GT expr",
  20666. + /* 188 */ "expr ::= expr LE expr",
  20667. + /* 189 */ "expr ::= expr GE expr",
  20668. + /* 190 */ "expr ::= expr NE expr",
  20669. + /* 191 */ "expr ::= expr EQ expr",
  20670. + /* 192 */ "expr ::= expr BITAND expr",
  20671. + /* 193 */ "expr ::= expr BITOR expr",
  20672. + /* 194 */ "expr ::= expr LSHIFT expr",
  20673. + /* 195 */ "expr ::= expr RSHIFT expr",
  20674. + /* 196 */ "expr ::= expr likeop expr",
  20675. + /* 197 */ "expr ::= expr NOT likeop expr",
  20676. + /* 198 */ "likeop ::= LIKE",
  20677. + /* 199 */ "likeop ::= GLOB",
  20678. + /* 200 */ "expr ::= expr PLUS expr",
  20679. + /* 201 */ "expr ::= expr MINUS expr",
  20680. + /* 202 */ "expr ::= expr STAR expr",
  20681. + /* 203 */ "expr ::= expr SLASH expr",
  20682. + /* 204 */ "expr ::= expr REM expr",
  20683. + /* 205 */ "expr ::= expr CONCAT expr",
  20684. + /* 206 */ "expr ::= expr ISNULL",
  20685. + /* 207 */ "expr ::= expr IS NULL",
  20686. + /* 208 */ "expr ::= expr NOTNULL",
  20687. + /* 209 */ "expr ::= expr NOT NULL",
  20688. + /* 210 */ "expr ::= expr IS NOT NULL",
  20689. + /* 211 */ "expr ::= NOT expr",
  20690. + /* 212 */ "expr ::= BITNOT expr",
  20691. + /* 213 */ "expr ::= MINUS expr",
  20692. + /* 214 */ "expr ::= PLUS expr",
  20693. + /* 215 */ "expr ::= LP select RP",
  20694. + /* 216 */ "expr ::= expr BETWEEN expr AND expr",
  20695. + /* 217 */ "expr ::= expr NOT BETWEEN expr AND expr",
  20696. + /* 218 */ "expr ::= expr IN LP exprlist RP",
  20697. + /* 219 */ "expr ::= expr IN LP select RP",
  20698. + /* 220 */ "expr ::= expr NOT IN LP exprlist RP",
  20699. + /* 221 */ "expr ::= expr NOT IN LP select RP",
  20700. + /* 222 */ "expr ::= expr IN nm dbnm",
  20701. + /* 223 */ "expr ::= expr NOT IN nm dbnm",
  20702. + /* 224 */ "expr ::= CASE case_operand case_exprlist case_else END",
  20703. + /* 225 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  20704. + /* 226 */ "case_exprlist ::= WHEN expr THEN expr",
  20705. + /* 227 */ "case_else ::= ELSE expr",
  20706. + /* 228 */ "case_else ::=",
  20707. + /* 229 */ "case_operand ::= expr",
  20708. + /* 230 */ "case_operand ::=",
  20709. + /* 231 */ "exprlist ::= exprlist COMMA expritem",
  20710. + /* 232 */ "exprlist ::= expritem",
  20711. + /* 233 */ "expritem ::= expr",
  20712. + /* 234 */ "expritem ::=",
  20713. + /* 235 */ "cmd ::= CREATE uniqueflag INDEX nm ON nm dbnm LP idxlist RP onconf",
  20714. + /* 236 */ "uniqueflag ::= UNIQUE",
  20715. + /* 237 */ "uniqueflag ::=",
  20716. + /* 238 */ "idxlist_opt ::=",
  20717. + /* 239 */ "idxlist_opt ::= LP idxlist RP",
  20718. + /* 240 */ "idxlist ::= idxlist COMMA idxitem",
  20719. + /* 241 */ "idxlist ::= idxitem",
  20720. + /* 242 */ "idxitem ::= nm sortorder",
  20721. + /* 243 */ "cmd ::= DROP INDEX nm dbnm",
  20722. + /* 244 */ "cmd ::= COPY orconf nm dbnm FROM nm USING DELIMITERS STRING",
  20723. + /* 245 */ "cmd ::= COPY orconf nm dbnm FROM nm",
  20724. + /* 246 */ "cmd ::= VACUUM",
  20725. + /* 247 */ "cmd ::= VACUUM nm",
  20726. + /* 248 */ "cmd ::= PRAGMA ids EQ nm",
  20727. + /* 249 */ "cmd ::= PRAGMA ids EQ ON",
  20728. + /* 250 */ "cmd ::= PRAGMA ids EQ plus_num",
  20729. + /* 251 */ "cmd ::= PRAGMA ids EQ minus_num",
  20730. + /* 252 */ "cmd ::= PRAGMA ids LP nm RP",
  20731. + /* 253 */ "cmd ::= PRAGMA ids",
  20732. + /* 254 */ "plus_num ::= plus_opt number",
  20733. + /* 255 */ "minus_num ::= MINUS number",
  20734. + /* 256 */ "number ::= INTEGER",
  20735. + /* 257 */ "number ::= FLOAT",
  20736. + /* 258 */ "plus_opt ::= PLUS",
  20737. + /* 259 */ "plus_opt ::=",
  20738. + /* 260 */ "cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END",
  20739. + /* 261 */ "trigger_decl ::= temp TRIGGER nm trigger_time trigger_event ON nm dbnm foreach_clause when_clause",
  20740. + /* 262 */ "trigger_time ::= BEFORE",
  20741. + /* 263 */ "trigger_time ::= AFTER",
  20742. + /* 264 */ "trigger_time ::= INSTEAD OF",
  20743. + /* 265 */ "trigger_time ::=",
  20744. + /* 266 */ "trigger_event ::= DELETE",
  20745. + /* 267 */ "trigger_event ::= INSERT",
  20746. + /* 268 */ "trigger_event ::= UPDATE",
  20747. + /* 269 */ "trigger_event ::= UPDATE OF inscollist",
  20748. + /* 270 */ "foreach_clause ::=",
  20749. + /* 271 */ "foreach_clause ::= FOR EACH ROW",
  20750. + /* 272 */ "foreach_clause ::= FOR EACH STATEMENT",
  20751. + /* 273 */ "when_clause ::=",
  20752. + /* 274 */ "when_clause ::= WHEN expr",
  20753. + /* 275 */ "trigger_cmd_list ::= trigger_cmd SEMI trigger_cmd_list",
  20754. + /* 276 */ "trigger_cmd_list ::=",
  20755. + /* 277 */ "trigger_cmd ::= UPDATE orconf nm SET setlist where_opt",
  20756. + /* 278 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP",
  20757. + /* 279 */ "trigger_cmd ::= insert_cmd INTO nm inscollist_opt select",
  20758. + /* 280 */ "trigger_cmd ::= DELETE FROM nm where_opt",
  20759. + /* 281 */ "trigger_cmd ::= select",
  20760. + /* 282 */ "expr ::= RAISE LP IGNORE RP",
  20761. + /* 283 */ "expr ::= RAISE LP ROLLBACK COMMA nm RP",
  20762. + /* 284 */ "expr ::= RAISE LP ABORT COMMA nm RP",
  20763. + /* 285 */ "expr ::= RAISE LP FAIL COMMA nm RP",
  20764. + /* 286 */ "cmd ::= DROP TRIGGER nm dbnm",
  20765. + /* 287 */ "cmd ::= ATTACH database_kw_opt ids AS nm key_opt",
  20766. + /* 288 */ "key_opt ::= USING ids",
  20767. + /* 289 */ "key_opt ::=",
  20768. + /* 290 */ "database_kw_opt ::= DATABASE",
  20769. + /* 291 */ "database_kw_opt ::=",
  20770. + /* 292 */ "cmd ::= DETACH database_kw_opt nm",
  20771. +};
  20772. +#endif /* NDEBUG */
  20773. +
  20774. +
  20775. +#if YYSTACKDEPTH<=0
  20776. +/*
  20777. +** Try to increase the size of the parser stack.
  20778. +*/
  20779. +static void yyGrowStack(yyParser *p){
  20780. + int newSize;
  20781. + yyStackEntry *pNew;
  20782. +
  20783. + newSize = p->yystksz*2 + 100;
  20784. + pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  20785. + if( pNew ){
  20786. + p->yystack = pNew;
  20787. + p->yystksz = newSize;
  20788. +#ifndef NDEBUG
  20789. + if( yyTraceFILE ){
  20790. + fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  20791. + yyTracePrompt, p->yystksz);
  20792. + }
  20793. +#endif
  20794. + }
  20795. +}
  20796. +#endif
  20797. +
  20798. +/*
  20799. +** This function allocates a new parser.
  20800. +** The only argument is a pointer to a function which works like
  20801. +** malloc.
  20802. +**
  20803. +** Inputs:
  20804. +** A pointer to the function used to allocate memory.
  20805. +**
  20806. +** Outputs:
  20807. +** A pointer to a parser. This pointer is used in subsequent calls
  20808. +** to sqliteParser and sqliteParserFree.
  20809. +*/
  20810. +void *sqliteParserAlloc(void *(*mallocProc)(size_t)){
  20811. + yyParser *pParser;
  20812. + pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
  20813. + if( pParser ){
  20814. + pParser->yyidx = -1;
  20815. +#ifdef YYTRACKMAXSTACKDEPTH
  20816. + pParser->yyidxMax = 0;
  20817. +#endif
  20818. +#if YYSTACKDEPTH<=0
  20819. + pParser->yystack = NULL;
  20820. + pParser->yystksz = 0;
  20821. + yyGrowStack(pParser);
  20822. +#endif
  20823. + }
  20824. + return pParser;
  20825. +}
  20826. +
  20827. +/* The following function deletes the value associated with a
  20828. +** symbol. The symbol can be either a terminal or nonterminal.
  20829. +** "yymajor" is the symbol code, and "yypminor" is a pointer to
  20830. +** the value.
  20831. +*/
  20832. +static void yy_destructor(
  20833. + yyParser *yypParser, /* The parser */
  20834. + YYCODETYPE yymajor, /* Type code for object to destroy */
  20835. + YYMINORTYPE *yypminor /* The object to be destroyed */
  20836. +){
  20837. + sqliteParserARG_FETCH;
  20838. + switch( yymajor ){
  20839. + /* Here is inserted the actions which take place when a
  20840. + ** terminal or non-terminal is destroyed. This can happen
  20841. + ** when the symbol is popped from the stack during a
  20842. + ** reduce or during error processing or when a parser is
  20843. + ** being destroyed before it is finished parsing.
  20844. + **
  20845. + ** Note: during a reduce, the only symbols destroyed are those
  20846. + ** which appear on the RHS of the rule, but which are not used
  20847. + ** inside the C code.
  20848. + */
  20849. + case 146: /* select */
  20850. + case 171: /* oneselect */
  20851. + case 189: /* seltablist_paren */
  20852. +{
  20853. +#line 286 "ext/sqlite/libsqlite/src/parse.y"
  20854. +sqliteSelectDelete((yypminor->yy179));
  20855. +#line 1131 "ext/sqlite/libsqlite/src/parse.c"
  20856. +}
  20857. + break;
  20858. + case 158: /* expr */
  20859. + case 176: /* where_opt */
  20860. + case 178: /* having_opt */
  20861. + case 187: /* on_opt */
  20862. + case 192: /* sortitem */
  20863. + case 204: /* expritem */
  20864. +{
  20865. +#line 533 "ext/sqlite/libsqlite/src/parse.y"
  20866. +sqliteExprDelete((yypminor->yy242));
  20867. +#line 1143 "ext/sqlite/libsqlite/src/parse.c"
  20868. +}
  20869. + break;
  20870. + case 159: /* idxlist_opt */
  20871. + case 167: /* idxlist */
  20872. + case 188: /* using_opt */
  20873. + case 197: /* inscollist_opt */
  20874. + case 199: /* inscollist */
  20875. +{
  20876. +#line 746 "ext/sqlite/libsqlite/src/parse.y"
  20877. +sqliteIdListDelete((yypminor->yy320));
  20878. +#line 1154 "ext/sqlite/libsqlite/src/parse.c"
  20879. +}
  20880. + break;
  20881. + case 174: /* selcollist */
  20882. + case 177: /* groupby_opt */
  20883. + case 179: /* orderby_opt */
  20884. + case 181: /* sclp */
  20885. + case 191: /* sortlist */
  20886. + case 194: /* exprlist */
  20887. + case 195: /* setlist */
  20888. + case 198: /* itemlist */
  20889. + case 202: /* case_exprlist */
  20890. +{
  20891. +#line 322 "ext/sqlite/libsqlite/src/parse.y"
  20892. +sqliteExprListDelete((yypminor->yy322));
  20893. +#line 1169 "ext/sqlite/libsqlite/src/parse.c"
  20894. +}
  20895. + break;
  20896. + case 175: /* from */
  20897. + case 183: /* seltablist */
  20898. + case 184: /* stl_prefix */
  20899. +{
  20900. +#line 353 "ext/sqlite/libsqlite/src/parse.y"
  20901. +sqliteSrcListDelete((yypminor->yy307));
  20902. +#line 1178 "ext/sqlite/libsqlite/src/parse.c"
  20903. +}
  20904. + break;
  20905. + case 212: /* trigger_cmd_list */
  20906. + case 217: /* trigger_cmd */
  20907. +{
  20908. +#line 828 "ext/sqlite/libsqlite/src/parse.y"
  20909. +sqliteDeleteTriggerStep((yypminor->yy19));
  20910. +#line 1186 "ext/sqlite/libsqlite/src/parse.c"
  20911. +}
  20912. + break;
  20913. + case 214: /* trigger_event */
  20914. +{
  20915. +#line 812 "ext/sqlite/libsqlite/src/parse.y"
  20916. +sqliteIdListDelete((yypminor->yy290).b);
  20917. +#line 1193 "ext/sqlite/libsqlite/src/parse.c"
  20918. +}
  20919. + break;
  20920. + default: break; /* If no destructor action specified: do nothing */
  20921. + }
  20922. +}
  20923. +
  20924. +/*
  20925. +** Pop the parser's stack once.
  20926. +**
  20927. +** If there is a destructor routine associated with the token which
  20928. +** is popped from the stack, then call it.
  20929. +**
  20930. +** Return the major token number for the symbol popped.
  20931. +*/
  20932. +static int yy_pop_parser_stack(yyParser *pParser){
  20933. + YYCODETYPE yymajor;
  20934. + yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  20935. +
  20936. + if( pParser->yyidx<0 ) return 0;
  20937. +#ifndef NDEBUG
  20938. + if( yyTraceFILE && pParser->yyidx>=0 ){
  20939. + fprintf(yyTraceFILE,"%sPopping %s\n",
  20940. + yyTracePrompt,
  20941. + yyTokenName[yytos->major]);
  20942. + }
  20943. +#endif
  20944. + yymajor = yytos->major;
  20945. + yy_destructor(pParser, yymajor, &yytos->minor);
  20946. + pParser->yyidx--;
  20947. + return yymajor;
  20948. +}
  20949. +
  20950. +/*
  20951. +** Deallocate and destroy a parser. Destructors are all called for
  20952. +** all stack elements before shutting the parser down.
  20953. +**
  20954. +** Inputs:
  20955. +** <ul>
  20956. +** <li> A pointer to the parser. This should be a pointer
  20957. +** obtained from sqliteParserAlloc.
  20958. +** <li> A pointer to a function used to reclaim memory obtained
  20959. +** from malloc.
  20960. +** </ul>
  20961. +*/
  20962. +void sqliteParserFree(
  20963. + void *p, /* The parser to be deleted */
  20964. + void (*freeProc)(void*) /* Function used to reclaim memory */
  20965. +){
  20966. + yyParser *pParser = (yyParser*)p;
  20967. + if( pParser==0 ) return;
  20968. + while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  20969. +#if YYSTACKDEPTH<=0
  20970. + free(pParser->yystack);
  20971. +#endif
  20972. + (*freeProc)((void*)pParser);
  20973. +}
  20974. +
  20975. +/*
  20976. +** Return the peak depth of the stack for a parser.
  20977. +*/
  20978. +#ifdef YYTRACKMAXSTACKDEPTH
  20979. +int sqliteParserStackPeak(void *p){
  20980. + yyParser *pParser = (yyParser*)p;
  20981. + return pParser->yyidxMax;
  20982. +}
  20983. +#endif
  20984. +
  20985. +/*
  20986. +** Find the appropriate action for a parser given the terminal
  20987. +** look-ahead token iLookAhead.
  20988. +**
  20989. +** If the look-ahead token is YYNOCODE, then check to see if the action is
  20990. +** independent of the look-ahead. If it is, return the action, otherwise
  20991. +** return YY_NO_ACTION.
  20992. +*/
  20993. +static int yy_find_shift_action(
  20994. + yyParser *pParser, /* The parser */
  20995. + YYCODETYPE iLookAhead /* The look-ahead token */
  20996. +){
  20997. + int i;
  20998. + int stateno = pParser->yystack[pParser->yyidx].stateno;
  20999. +
  21000. + if( stateno>YY_SHIFT_COUNT
  21001. + || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  21002. + return yy_default[stateno];
  21003. + }
  21004. + assert( iLookAhead!=YYNOCODE );
  21005. + i += iLookAhead;
  21006. + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  21007. + if( iLookAhead>0 ){
  21008. +#ifdef YYFALLBACK
  21009. + YYCODETYPE iFallback; /* Fallback token */
  21010. + if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  21011. + && (iFallback = yyFallback[iLookAhead])!=0 ){
  21012. +#ifndef NDEBUG
  21013. + if( yyTraceFILE ){
  21014. + fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  21015. + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  21016. + }
  21017. +#endif
  21018. + return yy_find_shift_action(pParser, iFallback);
  21019. + }
  21020. +#endif
  21021. +#ifdef YYWILDCARD
  21022. + {
  21023. + int j = i - iLookAhead + YYWILDCARD;
  21024. + if(
  21025. +#if YY_SHIFT_MIN+YYWILDCARD<0
  21026. + j>=0 &&
  21027. +#endif
  21028. +#if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  21029. + j<YY_ACTTAB_COUNT &&
  21030. +#endif
  21031. + yy_lookahead[j]==YYWILDCARD
  21032. + ){
  21033. +#ifndef NDEBUG
  21034. + if( yyTraceFILE ){
  21035. + fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  21036. + yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  21037. + }
  21038. +#endif /* NDEBUG */
  21039. + return yy_action[j];
  21040. + }
  21041. + }
  21042. +#endif /* YYWILDCARD */
  21043. + }
  21044. + return yy_default[stateno];
  21045. + }else{
  21046. + return yy_action[i];
  21047. + }
  21048. +}
  21049. +
  21050. +/*
  21051. +** Find the appropriate action for a parser given the non-terminal
  21052. +** look-ahead token iLookAhead.
  21053. +**
  21054. +** If the look-ahead token is YYNOCODE, then check to see if the action is
  21055. +** independent of the look-ahead. If it is, return the action, otherwise
  21056. +** return YY_NO_ACTION.
  21057. +*/
  21058. +static int yy_find_reduce_action(
  21059. + int stateno, /* Current state number */
  21060. + YYCODETYPE iLookAhead /* The look-ahead token */
  21061. +){
  21062. + int i;
  21063. +#ifdef YYERRORSYMBOL
  21064. + if( stateno>YY_REDUCE_COUNT ){
  21065. + return yy_default[stateno];
  21066. + }
  21067. +#else
  21068. + assert( stateno<=YY_REDUCE_COUNT );
  21069. +#endif
  21070. + i = yy_reduce_ofst[stateno];
  21071. + assert( i!=YY_REDUCE_USE_DFLT );
  21072. + assert( iLookAhead!=YYNOCODE );
  21073. + i += iLookAhead;
  21074. +#ifdef YYERRORSYMBOL
  21075. + if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  21076. + return yy_default[stateno];
  21077. + }
  21078. +#else
  21079. + assert( i>=0 && i<YY_ACTTAB_COUNT );
  21080. + assert( yy_lookahead[i]==iLookAhead );
  21081. +#endif
  21082. + return yy_action[i];
  21083. +}
  21084. +
  21085. +/*
  21086. +** The following routine is called if the stack overflows.
  21087. +*/
  21088. +static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  21089. + sqliteParserARG_FETCH;
  21090. + yypParser->yyidx--;
  21091. +#ifndef NDEBUG
  21092. + if( yyTraceFILE ){
  21093. + fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  21094. + }
  21095. +#endif
  21096. + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  21097. + /* Here code is inserted which will execute if the parser
  21098. + ** stack every overflows */
  21099. + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  21100. +}
  21101. +
  21102. +/*
  21103. +** Perform a shift action.
  21104. +*/
  21105. +static void yy_shift(
  21106. + yyParser *yypParser, /* The parser to be shifted */
  21107. + int yyNewState, /* The new state to shift in */
  21108. + int yyMajor, /* The major token to shift in */
  21109. + YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  21110. +){
  21111. + yyStackEntry *yytos;
  21112. + yypParser->yyidx++;
  21113. +#ifdef YYTRACKMAXSTACKDEPTH
  21114. + if( yypParser->yyidx>yypParser->yyidxMax ){
  21115. + yypParser->yyidxMax = yypParser->yyidx;
  21116. + }
  21117. +#endif
  21118. +#if YYSTACKDEPTH>0
  21119. + if( yypParser->yyidx>=YYSTACKDEPTH ){
  21120. + yyStackOverflow(yypParser, yypMinor);
  21121. + return;
  21122. + }
  21123. +#else
  21124. + if( yypParser->yyidx>=yypParser->yystksz ){
  21125. + yyGrowStack(yypParser);
  21126. + if( yypParser->yyidx>=yypParser->yystksz ){
  21127. + yyStackOverflow(yypParser, yypMinor);
  21128. + return;
  21129. + }
  21130. + }
  21131. +#endif
  21132. + yytos = &yypParser->yystack[yypParser->yyidx];
  21133. + yytos->stateno = (YYACTIONTYPE)yyNewState;
  21134. + yytos->major = (YYCODETYPE)yyMajor;
  21135. + yytos->minor = *yypMinor;
  21136. +#ifndef NDEBUG
  21137. + if( yyTraceFILE && yypParser->yyidx>0 ){
  21138. + int i;
  21139. + fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  21140. + fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  21141. + for(i=1; i<=yypParser->yyidx; i++)
  21142. + fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  21143. + fprintf(yyTraceFILE,"\n");
  21144. + }
  21145. +#endif
  21146. +}
  21147. +
  21148. +/* The following table contains information about every rule that
  21149. +** is used during the reduce.
  21150. +*/
  21151. +static const struct {
  21152. + YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  21153. + unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  21154. +} yyRuleInfo[] = {
  21155. + { 132, 1 },
  21156. + { 133, 2 },
  21157. + { 133, 1 },
  21158. + { 134, 3 },
  21159. + { 134, 1 },
  21160. + { 136, 1 },
  21161. + { 135, 1 },
  21162. + { 135, 0 },
  21163. + { 137, 3 },
  21164. + { 138, 0 },
  21165. + { 138, 1 },
  21166. + { 138, 2 },
  21167. + { 137, 2 },
  21168. + { 137, 2 },
  21169. + { 137, 2 },
  21170. + { 137, 2 },
  21171. + { 141, 4 },
  21172. + { 143, 1 },
  21173. + { 143, 0 },
  21174. + { 142, 4 },
  21175. + { 142, 2 },
  21176. + { 144, 3 },
  21177. + { 144, 1 },
  21178. + { 147, 3 },
  21179. + { 148, 1 },
  21180. + { 151, 1 },
  21181. + { 152, 1 },
  21182. + { 152, 1 },
  21183. + { 140, 1 },
  21184. + { 140, 1 },
  21185. + { 140, 1 },
  21186. + { 149, 0 },
  21187. + { 149, 1 },
  21188. + { 149, 4 },
  21189. + { 149, 6 },
  21190. + { 153, 1 },
  21191. + { 153, 2 },
  21192. + { 154, 1 },
  21193. + { 154, 2 },
  21194. + { 154, 2 },
  21195. + { 150, 2 },
  21196. + { 150, 0 },
  21197. + { 155, 3 },
  21198. + { 155, 1 },
  21199. + { 155, 2 },
  21200. + { 155, 2 },
  21201. + { 155, 2 },
  21202. + { 155, 3 },
  21203. + { 155, 3 },
  21204. + { 155, 2 },
  21205. + { 155, 3 },
  21206. + { 155, 3 },
  21207. + { 155, 2 },
  21208. + { 156, 2 },
  21209. + { 156, 3 },
  21210. + { 156, 4 },
  21211. + { 156, 2 },
  21212. + { 156, 5 },
  21213. + { 156, 4 },
  21214. + { 156, 1 },
  21215. + { 156, 2 },
  21216. + { 160, 0 },
  21217. + { 160, 2 },
  21218. + { 162, 2 },
  21219. + { 162, 3 },
  21220. + { 162, 3 },
  21221. + { 162, 3 },
  21222. + { 163, 2 },
  21223. + { 163, 2 },
  21224. + { 163, 1 },
  21225. + { 163, 1 },
  21226. + { 161, 3 },
  21227. + { 161, 2 },
  21228. + { 164, 0 },
  21229. + { 164, 2 },
  21230. + { 164, 2 },
  21231. + { 145, 0 },
  21232. + { 145, 2 },
  21233. + { 165, 3 },
  21234. + { 165, 2 },
  21235. + { 165, 1 },
  21236. + { 166, 2 },
  21237. + { 166, 6 },
  21238. + { 166, 5 },
  21239. + { 166, 3 },
  21240. + { 166, 10 },
  21241. + { 168, 0 },
  21242. + { 168, 1 },
  21243. + { 139, 0 },
  21244. + { 139, 3 },
  21245. + { 169, 0 },
  21246. + { 169, 2 },
  21247. + { 170, 1 },
  21248. + { 170, 1 },
  21249. + { 170, 1 },
  21250. + { 170, 1 },
  21251. + { 170, 1 },
  21252. + { 137, 3 },
  21253. + { 137, 6 },
  21254. + { 137, 3 },
  21255. + { 137, 1 },
  21256. + { 146, 1 },
  21257. + { 146, 3 },
  21258. + { 172, 1 },
  21259. + { 172, 2 },
  21260. + { 172, 1 },
  21261. + { 172, 1 },
  21262. + { 171, 9 },
  21263. + { 173, 1 },
  21264. + { 173, 1 },
  21265. + { 173, 0 },
  21266. + { 181, 2 },
  21267. + { 181, 0 },
  21268. + { 174, 3 },
  21269. + { 174, 2 },
  21270. + { 174, 4 },
  21271. + { 182, 2 },
  21272. + { 182, 1 },
  21273. + { 182, 0 },
  21274. + { 175, 0 },
  21275. + { 175, 2 },
  21276. + { 184, 2 },
  21277. + { 184, 0 },
  21278. + { 183, 6 },
  21279. + { 183, 7 },
  21280. + { 189, 1 },
  21281. + { 189, 1 },
  21282. + { 186, 0 },
  21283. + { 186, 2 },
  21284. + { 185, 1 },
  21285. + { 185, 1 },
  21286. + { 185, 2 },
  21287. + { 185, 3 },
  21288. + { 185, 4 },
  21289. + { 187, 2 },
  21290. + { 187, 0 },
  21291. + { 188, 4 },
  21292. + { 188, 0 },
  21293. + { 179, 0 },
  21294. + { 179, 3 },
  21295. + { 191, 5 },
  21296. + { 191, 3 },
  21297. + { 192, 1 },
  21298. + { 157, 1 },
  21299. + { 157, 1 },
  21300. + { 157, 0 },
  21301. + { 193, 0 },
  21302. + { 193, 2 },
  21303. + { 177, 0 },
  21304. + { 177, 3 },
  21305. + { 178, 0 },
  21306. + { 178, 2 },
  21307. + { 180, 0 },
  21308. + { 180, 2 },
  21309. + { 180, 4 },
  21310. + { 180, 4 },
  21311. + { 137, 5 },
  21312. + { 176, 0 },
  21313. + { 176, 2 },
  21314. + { 137, 7 },
  21315. + { 195, 5 },
  21316. + { 195, 3 },
  21317. + { 137, 9 },
  21318. + { 137, 6 },
  21319. + { 196, 2 },
  21320. + { 196, 1 },
  21321. + { 198, 3 },
  21322. + { 198, 1 },
  21323. + { 197, 0 },
  21324. + { 197, 3 },
  21325. + { 199, 3 },
  21326. + { 199, 1 },
  21327. + { 158, 3 },
  21328. + { 158, 1 },
  21329. + { 158, 1 },
  21330. + { 158, 1 },
  21331. + { 158, 3 },
  21332. + { 158, 5 },
  21333. + { 158, 1 },
  21334. + { 158, 1 },
  21335. + { 158, 1 },
  21336. + { 158, 1 },
  21337. + { 158, 4 },
  21338. + { 158, 4 },
  21339. + { 158, 3 },
  21340. + { 158, 3 },
  21341. + { 158, 3 },
  21342. + { 158, 3 },
  21343. + { 158, 3 },
  21344. + { 158, 3 },
  21345. + { 158, 3 },
  21346. + { 158, 3 },
  21347. + { 158, 3 },
  21348. + { 158, 3 },
  21349. + { 158, 3 },
  21350. + { 158, 3 },
  21351. + { 158, 3 },
  21352. + { 158, 4 },
  21353. + { 200, 1 },
  21354. + { 200, 1 },
  21355. + { 158, 3 },
  21356. + { 158, 3 },
  21357. + { 158, 3 },
  21358. + { 158, 3 },
  21359. + { 158, 3 },
  21360. + { 158, 3 },
  21361. + { 158, 2 },
  21362. + { 158, 3 },
  21363. + { 158, 2 },
  21364. + { 158, 3 },
  21365. + { 158, 4 },
  21366. + { 158, 2 },
  21367. + { 158, 2 },
  21368. + { 158, 2 },
  21369. + { 158, 2 },
  21370. + { 158, 3 },
  21371. + { 158, 5 },
  21372. + { 158, 6 },
  21373. + { 158, 5 },
  21374. + { 158, 5 },
  21375. + { 158, 6 },
  21376. + { 158, 6 },
  21377. + { 158, 4 },
  21378. + { 158, 5 },
  21379. + { 158, 5 },
  21380. + { 202, 5 },
  21381. + { 202, 4 },
  21382. + { 203, 2 },
  21383. + { 203, 0 },
  21384. + { 201, 1 },
  21385. + { 201, 0 },
  21386. + { 194, 3 },
  21387. + { 194, 1 },
  21388. + { 204, 1 },
  21389. + { 204, 0 },
  21390. + { 137, 11 },
  21391. + { 205, 1 },
  21392. + { 205, 0 },
  21393. + { 159, 0 },
  21394. + { 159, 3 },
  21395. + { 167, 3 },
  21396. + { 167, 1 },
  21397. + { 206, 2 },
  21398. + { 137, 4 },
  21399. + { 137, 9 },
  21400. + { 137, 6 },
  21401. + { 137, 1 },
  21402. + { 137, 2 },
  21403. + { 137, 4 },
  21404. + { 137, 4 },
  21405. + { 137, 4 },
  21406. + { 137, 4 },
  21407. + { 137, 5 },
  21408. + { 137, 2 },
  21409. + { 207, 2 },
  21410. + { 208, 2 },
  21411. + { 210, 1 },
  21412. + { 210, 1 },
  21413. + { 209, 1 },
  21414. + { 209, 0 },
  21415. + { 137, 5 },
  21416. + { 211, 10 },
  21417. + { 213, 1 },
  21418. + { 213, 1 },
  21419. + { 213, 2 },
  21420. + { 213, 0 },
  21421. + { 214, 1 },
  21422. + { 214, 1 },
  21423. + { 214, 1 },
  21424. + { 214, 3 },
  21425. + { 215, 0 },
  21426. + { 215, 3 },
  21427. + { 215, 3 },
  21428. + { 216, 0 },
  21429. + { 216, 2 },
  21430. + { 212, 3 },
  21431. + { 212, 0 },
  21432. + { 217, 6 },
  21433. + { 217, 8 },
  21434. + { 217, 5 },
  21435. + { 217, 4 },
  21436. + { 217, 1 },
  21437. + { 158, 4 },
  21438. + { 158, 6 },
  21439. + { 158, 6 },
  21440. + { 158, 6 },
  21441. + { 137, 4 },
  21442. + { 137, 6 },
  21443. + { 219, 2 },
  21444. + { 219, 0 },
  21445. + { 218, 1 },
  21446. + { 218, 0 },
  21447. + { 137, 3 },
  21448. +};
  21449. +
  21450. +static void yy_accept(yyParser*); /* Forward Declaration */
  21451. +
  21452. +/*
  21453. +** Perform a reduce action and the shift that must immediately
  21454. +** follow the reduce.
  21455. +*/
  21456. +static void yy_reduce(
  21457. + yyParser *yypParser, /* The parser */
  21458. + int yyruleno /* Number of the rule by which to reduce */
  21459. +){
  21460. + int yygoto; /* The next state */
  21461. + int yyact; /* The next action */
  21462. + YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  21463. + yyStackEntry *yymsp; /* The top of the parser's stack */
  21464. + int yysize; /* Amount to pop the stack */
  21465. + sqliteParserARG_FETCH;
  21466. + yymsp = &yypParser->yystack[yypParser->yyidx];
  21467. +#ifndef NDEBUG
  21468. + if( yyTraceFILE && yyruleno>=0
  21469. + && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  21470. + fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  21471. + yyRuleName[yyruleno]);
  21472. + }
  21473. +#endif /* NDEBUG */
  21474. +
  21475. + /* Silence complaints from purify about yygotominor being uninitialized
  21476. + ** in some cases when it is copied into the stack after the following
  21477. + ** switch. yygotominor is uninitialized when a rule reduces that does
  21478. + ** not set the value of its left-hand side nonterminal. Leaving the
  21479. + ** value of the nonterminal uninitialized is utterly harmless as long
  21480. + ** as the value is never used. So really the only thing this code
  21481. + ** accomplishes is to quieten purify.
  21482. + **
  21483. + ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  21484. + ** without this code, their parser segfaults. I'm not sure what there
  21485. + ** parser is doing to make this happen. This is the second bug report
  21486. + ** from wireshark this week. Clearly they are stressing Lemon in ways
  21487. + ** that it has not been previously stressed... (SQLite ticket #2172)
  21488. + */
  21489. + /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  21490. + yygotominor = yyzerominor;
  21491. +
  21492. +
  21493. + switch( yyruleno ){
  21494. + /* Beginning here are the reduction cases. A typical example
  21495. + ** follows:
  21496. + ** case 0:
  21497. + ** #line <lineno> <grammarfile>
  21498. + ** { ... } // User supplied code
  21499. + ** #line <lineno> <thisfile>
  21500. + ** break;
  21501. + */
  21502. + case 5: /* cmdx ::= cmd */
  21503. +#line 72 "ext/sqlite/libsqlite/src/parse.y"
  21504. +{ sqliteExec(pParse); }
  21505. +#line 1781 "ext/sqlite/libsqlite/src/parse.c"
  21506. + break;
  21507. + case 6: /* explain ::= EXPLAIN */
  21508. +#line 73 "ext/sqlite/libsqlite/src/parse.y"
  21509. +{ sqliteBeginParse(pParse, 1); }
  21510. +#line 1786 "ext/sqlite/libsqlite/src/parse.c"
  21511. + break;
  21512. + case 7: /* explain ::= */
  21513. +#line 74 "ext/sqlite/libsqlite/src/parse.y"
  21514. +{ sqliteBeginParse(pParse, 0); }
  21515. +#line 1791 "ext/sqlite/libsqlite/src/parse.c"
  21516. + break;
  21517. + case 8: /* cmd ::= BEGIN trans_opt onconf */
  21518. +#line 79 "ext/sqlite/libsqlite/src/parse.y"
  21519. +{sqliteBeginTransaction(pParse,yymsp[0].minor.yy372);}
  21520. +#line 1796 "ext/sqlite/libsqlite/src/parse.c"
  21521. + break;
  21522. + case 12: /* cmd ::= COMMIT trans_opt */
  21523. + case 13: /* cmd ::= END trans_opt */ yytestcase(yyruleno==13);
  21524. +#line 83 "ext/sqlite/libsqlite/src/parse.y"
  21525. +{sqliteCommitTransaction(pParse);}
  21526. +#line 1802 "ext/sqlite/libsqlite/src/parse.c"
  21527. + break;
  21528. + case 14: /* cmd ::= ROLLBACK trans_opt */
  21529. +#line 85 "ext/sqlite/libsqlite/src/parse.y"
  21530. +{sqliteRollbackTransaction(pParse);}
  21531. +#line 1807 "ext/sqlite/libsqlite/src/parse.c"
  21532. + break;
  21533. + case 16: /* create_table ::= CREATE temp TABLE nm */
  21534. +#line 90 "ext/sqlite/libsqlite/src/parse.y"
  21535. +{
  21536. + sqliteStartTable(pParse,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0,yymsp[-2].minor.yy372,0);
  21537. +}
  21538. +#line 1814 "ext/sqlite/libsqlite/src/parse.c"
  21539. + break;
  21540. + case 17: /* temp ::= TEMP */
  21541. + case 74: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==74);
  21542. + case 108: /* distinct ::= DISTINCT */ yytestcase(yyruleno==108);
  21543. +#line 94 "ext/sqlite/libsqlite/src/parse.y"
  21544. +{yygotominor.yy372 = 1;}
  21545. +#line 1821 "ext/sqlite/libsqlite/src/parse.c"
  21546. + break;
  21547. + case 18: /* temp ::= */
  21548. + case 73: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==73);
  21549. + case 75: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==75);
  21550. + case 86: /* defer_subclause_opt ::= */ yytestcase(yyruleno==86);
  21551. + case 109: /* distinct ::= ALL */ yytestcase(yyruleno==109);
  21552. + case 110: /* distinct ::= */ yytestcase(yyruleno==110);
  21553. +#line 95 "ext/sqlite/libsqlite/src/parse.y"
  21554. +{yygotominor.yy372 = 0;}
  21555. +#line 1831 "ext/sqlite/libsqlite/src/parse.c"
  21556. + break;
  21557. + case 19: /* create_table_args ::= LP columnlist conslist_opt RP */
  21558. +#line 96 "ext/sqlite/libsqlite/src/parse.y"
  21559. +{
  21560. + sqliteEndTable(pParse,&yymsp[0].minor.yy0,0);
  21561. +}
  21562. +#line 1838 "ext/sqlite/libsqlite/src/parse.c"
  21563. + break;
  21564. + case 20: /* create_table_args ::= AS select */
  21565. +#line 99 "ext/sqlite/libsqlite/src/parse.y"
  21566. +{
  21567. + sqliteEndTable(pParse,0,yymsp[0].minor.yy179);
  21568. + sqliteSelectDelete(yymsp[0].minor.yy179);
  21569. +}
  21570. +#line 1846 "ext/sqlite/libsqlite/src/parse.c"
  21571. + break;
  21572. + case 24: /* columnid ::= nm */
  21573. +#line 111 "ext/sqlite/libsqlite/src/parse.y"
  21574. +{sqliteAddColumn(pParse,&yymsp[0].minor.yy0);}
  21575. +#line 1851 "ext/sqlite/libsqlite/src/parse.c"
  21576. + break;
  21577. + case 25: /* id ::= ID */
  21578. + case 26: /* ids ::= ID */ yytestcase(yyruleno==26);
  21579. + case 27: /* ids ::= STRING */ yytestcase(yyruleno==27);
  21580. + case 28: /* nm ::= ID */ yytestcase(yyruleno==28);
  21581. + case 29: /* nm ::= STRING */ yytestcase(yyruleno==29);
  21582. + case 30: /* nm ::= JOIN_KW */ yytestcase(yyruleno==30);
  21583. + case 35: /* typename ::= ids */ yytestcase(yyruleno==35);
  21584. + case 128: /* dbnm ::= DOT nm */ yytestcase(yyruleno==128);
  21585. + case 254: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==254);
  21586. + case 255: /* minus_num ::= MINUS number */ yytestcase(yyruleno==255);
  21587. + case 256: /* number ::= INTEGER */ yytestcase(yyruleno==256);
  21588. + case 257: /* number ::= FLOAT */ yytestcase(yyruleno==257);
  21589. +#line 117 "ext/sqlite/libsqlite/src/parse.y"
  21590. +{yygotominor.yy0 = yymsp[0].minor.yy0;}
  21591. +#line 1867 "ext/sqlite/libsqlite/src/parse.c"
  21592. + break;
  21593. + case 32: /* type ::= typename */
  21594. +#line 160 "ext/sqlite/libsqlite/src/parse.y"
  21595. +{sqliteAddColumnType(pParse,&yymsp[0].minor.yy0,&yymsp[0].minor.yy0);}
  21596. +#line 1872 "ext/sqlite/libsqlite/src/parse.c"
  21597. + break;
  21598. + case 33: /* type ::= typename LP signed RP */
  21599. +#line 161 "ext/sqlite/libsqlite/src/parse.y"
  21600. +{sqliteAddColumnType(pParse,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);}
  21601. +#line 1877 "ext/sqlite/libsqlite/src/parse.c"
  21602. + break;
  21603. + case 34: /* type ::= typename LP signed COMMA signed RP */
  21604. +#line 163 "ext/sqlite/libsqlite/src/parse.y"
  21605. +{sqliteAddColumnType(pParse,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);}
  21606. +#line 1882 "ext/sqlite/libsqlite/src/parse.c"
  21607. + break;
  21608. + case 36: /* typename ::= typename ids */
  21609. + case 242: /* idxitem ::= nm sortorder */ yytestcase(yyruleno==242);
  21610. +#line 166 "ext/sqlite/libsqlite/src/parse.y"
  21611. +{yygotominor.yy0 = yymsp[-1].minor.yy0;}
  21612. +#line 1888 "ext/sqlite/libsqlite/src/parse.c"
  21613. + break;
  21614. + case 37: /* signed ::= INTEGER */
  21615. + case 38: /* signed ::= PLUS INTEGER */ yytestcase(yyruleno==38);
  21616. +#line 168 "ext/sqlite/libsqlite/src/parse.y"
  21617. +{ yygotominor.yy372 = atoi(yymsp[0].minor.yy0.z); }
  21618. +#line 1894 "ext/sqlite/libsqlite/src/parse.c"
  21619. + break;
  21620. + case 39: /* signed ::= MINUS INTEGER */
  21621. +#line 170 "ext/sqlite/libsqlite/src/parse.y"
  21622. +{ yygotominor.yy372 = -atoi(yymsp[0].minor.yy0.z); }
  21623. +#line 1899 "ext/sqlite/libsqlite/src/parse.c"
  21624. + break;
  21625. + case 44: /* carg ::= DEFAULT STRING */
  21626. + case 45: /* carg ::= DEFAULT ID */ yytestcase(yyruleno==45);
  21627. + case 46: /* carg ::= DEFAULT INTEGER */ yytestcase(yyruleno==46);
  21628. + case 47: /* carg ::= DEFAULT PLUS INTEGER */ yytestcase(yyruleno==47);
  21629. + case 49: /* carg ::= DEFAULT FLOAT */ yytestcase(yyruleno==49);
  21630. + case 50: /* carg ::= DEFAULT PLUS FLOAT */ yytestcase(yyruleno==50);
  21631. +#line 175 "ext/sqlite/libsqlite/src/parse.y"
  21632. +{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,0);}
  21633. +#line 1909 "ext/sqlite/libsqlite/src/parse.c"
  21634. + break;
  21635. + case 48: /* carg ::= DEFAULT MINUS INTEGER */
  21636. + case 51: /* carg ::= DEFAULT MINUS FLOAT */ yytestcase(yyruleno==51);
  21637. +#line 179 "ext/sqlite/libsqlite/src/parse.y"
  21638. +{sqliteAddDefaultValue(pParse,&yymsp[0].minor.yy0,1);}
  21639. +#line 1915 "ext/sqlite/libsqlite/src/parse.c"
  21640. + break;
  21641. + case 54: /* ccons ::= NOT NULL onconf */
  21642. +#line 189 "ext/sqlite/libsqlite/src/parse.y"
  21643. +{sqliteAddNotNull(pParse, yymsp[0].minor.yy372);}
  21644. +#line 1920 "ext/sqlite/libsqlite/src/parse.c"
  21645. + break;
  21646. + case 55: /* ccons ::= PRIMARY KEY sortorder onconf */
  21647. +#line 190 "ext/sqlite/libsqlite/src/parse.y"
  21648. +{sqliteAddPrimaryKey(pParse,0,yymsp[0].minor.yy372);}
  21649. +#line 1925 "ext/sqlite/libsqlite/src/parse.c"
  21650. + break;
  21651. + case 56: /* ccons ::= UNIQUE onconf */
  21652. +#line 191 "ext/sqlite/libsqlite/src/parse.y"
  21653. +{sqliteCreateIndex(pParse,0,0,0,yymsp[0].minor.yy372,0,0);}
  21654. +#line 1930 "ext/sqlite/libsqlite/src/parse.c"
  21655. + break;
  21656. + case 57: /* ccons ::= CHECK LP expr RP onconf */
  21657. +#line 192 "ext/sqlite/libsqlite/src/parse.y"
  21658. +{
  21659. + yy_destructor(yypParser,158,&yymsp[-2].minor);
  21660. +}
  21661. +#line 1937 "ext/sqlite/libsqlite/src/parse.c"
  21662. + break;
  21663. + case 58: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  21664. +#line 194 "ext/sqlite/libsqlite/src/parse.y"
  21665. +{sqliteCreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy320,yymsp[0].minor.yy372);}
  21666. +#line 1942 "ext/sqlite/libsqlite/src/parse.c"
  21667. + break;
  21668. + case 59: /* ccons ::= defer_subclause */
  21669. +#line 195 "ext/sqlite/libsqlite/src/parse.y"
  21670. +{sqliteDeferForeignKey(pParse,yymsp[0].minor.yy372);}
  21671. +#line 1947 "ext/sqlite/libsqlite/src/parse.c"
  21672. + break;
  21673. + case 60: /* ccons ::= COLLATE id */
  21674. +#line 196 "ext/sqlite/libsqlite/src/parse.y"
  21675. +{
  21676. + sqliteAddCollateType(pParse, sqliteCollateType(yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n));
  21677. +}
  21678. +#line 1954 "ext/sqlite/libsqlite/src/parse.c"
  21679. + break;
  21680. + case 61: /* refargs ::= */
  21681. +#line 206 "ext/sqlite/libsqlite/src/parse.y"
  21682. +{ yygotominor.yy372 = OE_Restrict * 0x010101; }
  21683. +#line 1959 "ext/sqlite/libsqlite/src/parse.c"
  21684. + break;
  21685. + case 62: /* refargs ::= refargs refarg */
  21686. +#line 207 "ext/sqlite/libsqlite/src/parse.y"
  21687. +{ yygotominor.yy372 = (yymsp[-1].minor.yy372 & yymsp[0].minor.yy407.mask) | yymsp[0].minor.yy407.value; }
  21688. +#line 1964 "ext/sqlite/libsqlite/src/parse.c"
  21689. + break;
  21690. + case 63: /* refarg ::= MATCH nm */
  21691. +#line 209 "ext/sqlite/libsqlite/src/parse.y"
  21692. +{ yygotominor.yy407.value = 0; yygotominor.yy407.mask = 0x000000; }
  21693. +#line 1969 "ext/sqlite/libsqlite/src/parse.c"
  21694. + break;
  21695. + case 64: /* refarg ::= ON DELETE refact */
  21696. +#line 210 "ext/sqlite/libsqlite/src/parse.y"
  21697. +{ yygotominor.yy407.value = yymsp[0].minor.yy372; yygotominor.yy407.mask = 0x0000ff; }
  21698. +#line 1974 "ext/sqlite/libsqlite/src/parse.c"
  21699. + break;
  21700. + case 65: /* refarg ::= ON UPDATE refact */
  21701. +#line 211 "ext/sqlite/libsqlite/src/parse.y"
  21702. +{ yygotominor.yy407.value = yymsp[0].minor.yy372<<8; yygotominor.yy407.mask = 0x00ff00; }
  21703. +#line 1979 "ext/sqlite/libsqlite/src/parse.c"
  21704. + break;
  21705. + case 66: /* refarg ::= ON INSERT refact */
  21706. +#line 212 "ext/sqlite/libsqlite/src/parse.y"
  21707. +{ yygotominor.yy407.value = yymsp[0].minor.yy372<<16; yygotominor.yy407.mask = 0xff0000; }
  21708. +#line 1984 "ext/sqlite/libsqlite/src/parse.c"
  21709. + break;
  21710. + case 67: /* refact ::= SET NULL */
  21711. +#line 214 "ext/sqlite/libsqlite/src/parse.y"
  21712. +{ yygotominor.yy372 = OE_SetNull; }
  21713. +#line 1989 "ext/sqlite/libsqlite/src/parse.c"
  21714. + break;
  21715. + case 68: /* refact ::= SET DEFAULT */
  21716. +#line 215 "ext/sqlite/libsqlite/src/parse.y"
  21717. +{ yygotominor.yy372 = OE_SetDflt; }
  21718. +#line 1994 "ext/sqlite/libsqlite/src/parse.c"
  21719. + break;
  21720. + case 69: /* refact ::= CASCADE */
  21721. +#line 216 "ext/sqlite/libsqlite/src/parse.y"
  21722. +{ yygotominor.yy372 = OE_Cascade; }
  21723. +#line 1999 "ext/sqlite/libsqlite/src/parse.c"
  21724. + break;
  21725. + case 70: /* refact ::= RESTRICT */
  21726. +#line 217 "ext/sqlite/libsqlite/src/parse.y"
  21727. +{ yygotominor.yy372 = OE_Restrict; }
  21728. +#line 2004 "ext/sqlite/libsqlite/src/parse.c"
  21729. + break;
  21730. + case 71: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
  21731. + case 72: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==72);
  21732. + case 87: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==87);
  21733. + case 164: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==164);
  21734. +#line 219 "ext/sqlite/libsqlite/src/parse.y"
  21735. +{yygotominor.yy372 = yymsp[0].minor.yy372;}
  21736. +#line 2012 "ext/sqlite/libsqlite/src/parse.c"
  21737. + break;
  21738. + case 82: /* tcons ::= PRIMARY KEY LP idxlist RP onconf */
  21739. +#line 236 "ext/sqlite/libsqlite/src/parse.y"
  21740. +{sqliteAddPrimaryKey(pParse,yymsp[-2].minor.yy320,yymsp[0].minor.yy372);}
  21741. +#line 2017 "ext/sqlite/libsqlite/src/parse.c"
  21742. + break;
  21743. + case 83: /* tcons ::= UNIQUE LP idxlist RP onconf */
  21744. +#line 238 "ext/sqlite/libsqlite/src/parse.y"
  21745. +{sqliteCreateIndex(pParse,0,0,yymsp[-2].minor.yy320,yymsp[0].minor.yy372,0,0);}
  21746. +#line 2022 "ext/sqlite/libsqlite/src/parse.c"
  21747. + break;
  21748. + case 84: /* tcons ::= CHECK expr onconf */
  21749. +#line 239 "ext/sqlite/libsqlite/src/parse.y"
  21750. +{
  21751. + yy_destructor(yypParser,158,&yymsp[-1].minor);
  21752. +}
  21753. +#line 2029 "ext/sqlite/libsqlite/src/parse.c"
  21754. + break;
  21755. + case 85: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  21756. +#line 241 "ext/sqlite/libsqlite/src/parse.y"
  21757. +{
  21758. + sqliteCreateForeignKey(pParse, yymsp[-6].minor.yy320, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy320, yymsp[-1].minor.yy372);
  21759. + sqliteDeferForeignKey(pParse, yymsp[0].minor.yy372);
  21760. +}
  21761. +#line 2037 "ext/sqlite/libsqlite/src/parse.c"
  21762. + break;
  21763. + case 88: /* onconf ::= */
  21764. + case 90: /* orconf ::= */ yytestcase(yyruleno==90);
  21765. +#line 255 "ext/sqlite/libsqlite/src/parse.y"
  21766. +{ yygotominor.yy372 = OE_Default; }
  21767. +#line 2043 "ext/sqlite/libsqlite/src/parse.c"
  21768. + break;
  21769. + case 89: /* onconf ::= ON CONFLICT resolvetype */
  21770. + case 91: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==91);
  21771. +#line 256 "ext/sqlite/libsqlite/src/parse.y"
  21772. +{ yygotominor.yy372 = yymsp[0].minor.yy372; }
  21773. +#line 2049 "ext/sqlite/libsqlite/src/parse.c"
  21774. + break;
  21775. + case 92: /* resolvetype ::= ROLLBACK */
  21776. +#line 259 "ext/sqlite/libsqlite/src/parse.y"
  21777. +{ yygotominor.yy372 = OE_Rollback; }
  21778. +#line 2054 "ext/sqlite/libsqlite/src/parse.c"
  21779. + break;
  21780. + case 93: /* resolvetype ::= ABORT */
  21781. + case 236: /* uniqueflag ::= UNIQUE */ yytestcase(yyruleno==236);
  21782. +#line 260 "ext/sqlite/libsqlite/src/parse.y"
  21783. +{ yygotominor.yy372 = OE_Abort; }
  21784. +#line 2060 "ext/sqlite/libsqlite/src/parse.c"
  21785. + break;
  21786. + case 94: /* resolvetype ::= FAIL */
  21787. +#line 261 "ext/sqlite/libsqlite/src/parse.y"
  21788. +{ yygotominor.yy372 = OE_Fail; }
  21789. +#line 2065 "ext/sqlite/libsqlite/src/parse.c"
  21790. + break;
  21791. + case 95: /* resolvetype ::= IGNORE */
  21792. +#line 262 "ext/sqlite/libsqlite/src/parse.y"
  21793. +{ yygotominor.yy372 = OE_Ignore; }
  21794. +#line 2070 "ext/sqlite/libsqlite/src/parse.c"
  21795. + break;
  21796. + case 96: /* resolvetype ::= REPLACE */
  21797. +#line 263 "ext/sqlite/libsqlite/src/parse.y"
  21798. +{ yygotominor.yy372 = OE_Replace; }
  21799. +#line 2075 "ext/sqlite/libsqlite/src/parse.c"
  21800. + break;
  21801. + case 97: /* cmd ::= DROP TABLE nm */
  21802. +#line 267 "ext/sqlite/libsqlite/src/parse.y"
  21803. +{sqliteDropTable(pParse,&yymsp[0].minor.yy0,0);}
  21804. +#line 2080 "ext/sqlite/libsqlite/src/parse.c"
  21805. + break;
  21806. + case 98: /* cmd ::= CREATE temp VIEW nm AS select */
  21807. +#line 271 "ext/sqlite/libsqlite/src/parse.y"
  21808. +{
  21809. + sqliteCreateView(pParse, &yymsp[-5].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy179, yymsp[-4].minor.yy372);
  21810. +}
  21811. +#line 2087 "ext/sqlite/libsqlite/src/parse.c"
  21812. + break;
  21813. + case 99: /* cmd ::= DROP VIEW nm */
  21814. +#line 274 "ext/sqlite/libsqlite/src/parse.y"
  21815. +{
  21816. + sqliteDropTable(pParse, &yymsp[0].minor.yy0, 1);
  21817. +}
  21818. +#line 2094 "ext/sqlite/libsqlite/src/parse.c"
  21819. + break;
  21820. + case 100: /* cmd ::= select */
  21821. +#line 280 "ext/sqlite/libsqlite/src/parse.y"
  21822. +{
  21823. + sqliteSelect(pParse, yymsp[0].minor.yy179, SRT_Callback, 0, 0, 0, 0);
  21824. + sqliteSelectDelete(yymsp[0].minor.yy179);
  21825. +}
  21826. +#line 2102 "ext/sqlite/libsqlite/src/parse.c"
  21827. + break;
  21828. + case 101: /* select ::= oneselect */
  21829. + case 125: /* seltablist_paren ::= select */ yytestcase(yyruleno==125);
  21830. +#line 290 "ext/sqlite/libsqlite/src/parse.y"
  21831. +{yygotominor.yy179 = yymsp[0].minor.yy179;}
  21832. +#line 2108 "ext/sqlite/libsqlite/src/parse.c"
  21833. + break;
  21834. + case 102: /* select ::= select multiselect_op oneselect */
  21835. +#line 291 "ext/sqlite/libsqlite/src/parse.y"
  21836. +{
  21837. + if( yymsp[0].minor.yy179 ){
  21838. + yymsp[0].minor.yy179->op = yymsp[-1].minor.yy372;
  21839. + yymsp[0].minor.yy179->pPrior = yymsp[-2].minor.yy179;
  21840. + }
  21841. + yygotominor.yy179 = yymsp[0].minor.yy179;
  21842. +}
  21843. +#line 2119 "ext/sqlite/libsqlite/src/parse.c"
  21844. + break;
  21845. + case 103: /* multiselect_op ::= UNION */
  21846. +#line 299 "ext/sqlite/libsqlite/src/parse.y"
  21847. +{yygotominor.yy372 = TK_UNION;}
  21848. +#line 2124 "ext/sqlite/libsqlite/src/parse.c"
  21849. + break;
  21850. + case 104: /* multiselect_op ::= UNION ALL */
  21851. +#line 300 "ext/sqlite/libsqlite/src/parse.y"
  21852. +{yygotominor.yy372 = TK_ALL;}
  21853. +#line 2129 "ext/sqlite/libsqlite/src/parse.c"
  21854. + break;
  21855. + case 105: /* multiselect_op ::= INTERSECT */
  21856. +#line 301 "ext/sqlite/libsqlite/src/parse.y"
  21857. +{yygotominor.yy372 = TK_INTERSECT;}
  21858. +#line 2134 "ext/sqlite/libsqlite/src/parse.c"
  21859. + break;
  21860. + case 106: /* multiselect_op ::= EXCEPT */
  21861. +#line 302 "ext/sqlite/libsqlite/src/parse.y"
  21862. +{yygotominor.yy372 = TK_EXCEPT;}
  21863. +#line 2139 "ext/sqlite/libsqlite/src/parse.c"
  21864. + break;
  21865. + case 107: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  21866. +#line 304 "ext/sqlite/libsqlite/src/parse.y"
  21867. +{
  21868. + yygotominor.yy179 = sqliteSelectNew(yymsp[-6].minor.yy322,yymsp[-5].minor.yy307,yymsp[-4].minor.yy242,yymsp[-3].minor.yy322,yymsp[-2].minor.yy242,yymsp[-1].minor.yy322,yymsp[-7].minor.yy372,yymsp[0].minor.yy124.limit,yymsp[0].minor.yy124.offset);
  21869. +}
  21870. +#line 2146 "ext/sqlite/libsqlite/src/parse.c"
  21871. + break;
  21872. + case 111: /* sclp ::= selcollist COMMA */
  21873. +#line 325 "ext/sqlite/libsqlite/src/parse.y"
  21874. +{yygotominor.yy322 = yymsp[-1].minor.yy322;}
  21875. +#line 2151 "ext/sqlite/libsqlite/src/parse.c"
  21876. + break;
  21877. + case 112: /* sclp ::= */
  21878. + case 138: /* orderby_opt ::= */ yytestcase(yyruleno==138);
  21879. + case 148: /* groupby_opt ::= */ yytestcase(yyruleno==148);
  21880. +#line 326 "ext/sqlite/libsqlite/src/parse.y"
  21881. +{yygotominor.yy322 = 0;}
  21882. +#line 2158 "ext/sqlite/libsqlite/src/parse.c"
  21883. + break;
  21884. + case 113: /* selcollist ::= sclp expr as */
  21885. +#line 327 "ext/sqlite/libsqlite/src/parse.y"
  21886. +{
  21887. + yygotominor.yy322 = sqliteExprListAppend(yymsp[-2].minor.yy322,yymsp[-1].minor.yy242,yymsp[0].minor.yy0.n?&yymsp[0].minor.yy0:0);
  21888. +}
  21889. +#line 2165 "ext/sqlite/libsqlite/src/parse.c"
  21890. + break;
  21891. + case 114: /* selcollist ::= sclp STAR */
  21892. +#line 330 "ext/sqlite/libsqlite/src/parse.y"
  21893. +{
  21894. + yygotominor.yy322 = sqliteExprListAppend(yymsp[-1].minor.yy322, sqliteExpr(TK_ALL, 0, 0, 0), 0);
  21895. +}
  21896. +#line 2172 "ext/sqlite/libsqlite/src/parse.c"
  21897. + break;
  21898. + case 115: /* selcollist ::= sclp nm DOT STAR */
  21899. +#line 333 "ext/sqlite/libsqlite/src/parse.y"
  21900. +{
  21901. + Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
  21902. + Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  21903. + yygotominor.yy322 = sqliteExprListAppend(yymsp[-3].minor.yy322, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
  21904. +}
  21905. +#line 2181 "ext/sqlite/libsqlite/src/parse.c"
  21906. + break;
  21907. + case 116: /* as ::= AS nm */
  21908. + case 117: /* as ::= ids */ yytestcase(yyruleno==117);
  21909. + case 288: /* key_opt ::= USING ids */ yytestcase(yyruleno==288);
  21910. +#line 343 "ext/sqlite/libsqlite/src/parse.y"
  21911. +{ yygotominor.yy0 = yymsp[0].minor.yy0; }
  21912. +#line 2188 "ext/sqlite/libsqlite/src/parse.c"
  21913. + break;
  21914. + case 118: /* as ::= */
  21915. +#line 345 "ext/sqlite/libsqlite/src/parse.y"
  21916. +{ yygotominor.yy0.n = 0; }
  21917. +#line 2193 "ext/sqlite/libsqlite/src/parse.c"
  21918. + break;
  21919. + case 119: /* from ::= */
  21920. +#line 357 "ext/sqlite/libsqlite/src/parse.y"
  21921. +{yygotominor.yy307 = sqliteMalloc(sizeof(*yygotominor.yy307));}
  21922. +#line 2198 "ext/sqlite/libsqlite/src/parse.c"
  21923. + break;
  21924. + case 120: /* from ::= FROM seltablist */
  21925. +#line 358 "ext/sqlite/libsqlite/src/parse.y"
  21926. +{yygotominor.yy307 = yymsp[0].minor.yy307;}
  21927. +#line 2203 "ext/sqlite/libsqlite/src/parse.c"
  21928. + break;
  21929. + case 121: /* stl_prefix ::= seltablist joinop */
  21930. +#line 363 "ext/sqlite/libsqlite/src/parse.y"
  21931. +{
  21932. + yygotominor.yy307 = yymsp[-1].minor.yy307;
  21933. + if( yygotominor.yy307 && yygotominor.yy307->nSrc>0 ) yygotominor.yy307->a[yygotominor.yy307->nSrc-1].jointype = yymsp[0].minor.yy372;
  21934. +}
  21935. +#line 2211 "ext/sqlite/libsqlite/src/parse.c"
  21936. + break;
  21937. + case 122: /* stl_prefix ::= */
  21938. +#line 367 "ext/sqlite/libsqlite/src/parse.y"
  21939. +{yygotominor.yy307 = 0;}
  21940. +#line 2216 "ext/sqlite/libsqlite/src/parse.c"
  21941. + break;
  21942. + case 123: /* seltablist ::= stl_prefix nm dbnm as on_opt using_opt */
  21943. +#line 368 "ext/sqlite/libsqlite/src/parse.y"
  21944. +{
  21945. + yygotominor.yy307 = sqliteSrcListAppend(yymsp[-5].minor.yy307,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0);
  21946. + if( yymsp[-2].minor.yy0.n ) sqliteSrcListAddAlias(yygotominor.yy307,&yymsp[-2].minor.yy0);
  21947. + if( yymsp[-1].minor.yy242 ){
  21948. + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pOn = yymsp[-1].minor.yy242; }
  21949. + else { sqliteExprDelete(yymsp[-1].minor.yy242); }
  21950. + }
  21951. + if( yymsp[0].minor.yy320 ){
  21952. + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pUsing = yymsp[0].minor.yy320; }
  21953. + else { sqliteIdListDelete(yymsp[0].minor.yy320); }
  21954. + }
  21955. +}
  21956. +#line 2232 "ext/sqlite/libsqlite/src/parse.c"
  21957. + break;
  21958. + case 124: /* seltablist ::= stl_prefix LP seltablist_paren RP as on_opt using_opt */
  21959. +#line 381 "ext/sqlite/libsqlite/src/parse.y"
  21960. +{
  21961. + yygotominor.yy307 = sqliteSrcListAppend(yymsp[-6].minor.yy307,0,0);
  21962. + yygotominor.yy307->a[yygotominor.yy307->nSrc-1].pSelect = yymsp[-4].minor.yy179;
  21963. + if( yymsp[-2].minor.yy0.n ) sqliteSrcListAddAlias(yygotominor.yy307,&yymsp[-2].minor.yy0);
  21964. + if( yymsp[-1].minor.yy242 ){
  21965. + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pOn = yymsp[-1].minor.yy242; }
  21966. + else { sqliteExprDelete(yymsp[-1].minor.yy242); }
  21967. + }
  21968. + if( yymsp[0].minor.yy320 ){
  21969. + if( yygotominor.yy307 && yygotominor.yy307->nSrc>1 ){ yygotominor.yy307->a[yygotominor.yy307->nSrc-2].pUsing = yymsp[0].minor.yy320; }
  21970. + else { sqliteIdListDelete(yymsp[0].minor.yy320); }
  21971. + }
  21972. +}
  21973. +#line 2249 "ext/sqlite/libsqlite/src/parse.c"
  21974. + break;
  21975. + case 126: /* seltablist_paren ::= seltablist */
  21976. +#line 402 "ext/sqlite/libsqlite/src/parse.y"
  21977. +{
  21978. + yygotominor.yy179 = sqliteSelectNew(0,yymsp[0].minor.yy307,0,0,0,0,0,-1,0);
  21979. +}
  21980. +#line 2256 "ext/sqlite/libsqlite/src/parse.c"
  21981. + break;
  21982. + case 127: /* dbnm ::= */
  21983. +#line 407 "ext/sqlite/libsqlite/src/parse.y"
  21984. +{yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  21985. +#line 2261 "ext/sqlite/libsqlite/src/parse.c"
  21986. + break;
  21987. + case 129: /* joinop ::= COMMA */
  21988. + case 130: /* joinop ::= JOIN */ yytestcase(yyruleno==130);
  21989. +#line 412 "ext/sqlite/libsqlite/src/parse.y"
  21990. +{ yygotominor.yy372 = JT_INNER; }
  21991. +#line 2267 "ext/sqlite/libsqlite/src/parse.c"
  21992. + break;
  21993. + case 131: /* joinop ::= JOIN_KW JOIN */
  21994. +#line 414 "ext/sqlite/libsqlite/src/parse.y"
  21995. +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  21996. +#line 2272 "ext/sqlite/libsqlite/src/parse.c"
  21997. + break;
  21998. + case 132: /* joinop ::= JOIN_KW nm JOIN */
  21999. +#line 415 "ext/sqlite/libsqlite/src/parse.y"
  22000. +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  22001. +#line 2277 "ext/sqlite/libsqlite/src/parse.c"
  22002. + break;
  22003. + case 133: /* joinop ::= JOIN_KW nm nm JOIN */
  22004. +#line 417 "ext/sqlite/libsqlite/src/parse.y"
  22005. +{ yygotominor.yy372 = sqliteJoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  22006. +#line 2282 "ext/sqlite/libsqlite/src/parse.c"
  22007. + break;
  22008. + case 134: /* on_opt ::= ON expr */
  22009. + case 142: /* sortitem ::= expr */ yytestcase(yyruleno==142);
  22010. + case 151: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==151);
  22011. + case 158: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==158);
  22012. + case 227: /* case_else ::= ELSE expr */ yytestcase(yyruleno==227);
  22013. + case 229: /* case_operand ::= expr */ yytestcase(yyruleno==229);
  22014. + case 233: /* expritem ::= expr */ yytestcase(yyruleno==233);
  22015. +#line 421 "ext/sqlite/libsqlite/src/parse.y"
  22016. +{yygotominor.yy242 = yymsp[0].minor.yy242;}
  22017. +#line 2293 "ext/sqlite/libsqlite/src/parse.c"
  22018. + break;
  22019. + case 135: /* on_opt ::= */
  22020. + case 150: /* having_opt ::= */ yytestcase(yyruleno==150);
  22021. + case 157: /* where_opt ::= */ yytestcase(yyruleno==157);
  22022. + case 228: /* case_else ::= */ yytestcase(yyruleno==228);
  22023. + case 230: /* case_operand ::= */ yytestcase(yyruleno==230);
  22024. + case 234: /* expritem ::= */ yytestcase(yyruleno==234);
  22025. +#line 422 "ext/sqlite/libsqlite/src/parse.y"
  22026. +{yygotominor.yy242 = 0;}
  22027. +#line 2303 "ext/sqlite/libsqlite/src/parse.c"
  22028. + break;
  22029. + case 136: /* using_opt ::= USING LP idxlist RP */
  22030. + case 169: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==169);
  22031. + case 239: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==239);
  22032. +#line 426 "ext/sqlite/libsqlite/src/parse.y"
  22033. +{yygotominor.yy320 = yymsp[-1].minor.yy320;}
  22034. +#line 2310 "ext/sqlite/libsqlite/src/parse.c"
  22035. + break;
  22036. + case 137: /* using_opt ::= */
  22037. + case 168: /* inscollist_opt ::= */ yytestcase(yyruleno==168);
  22038. + case 238: /* idxlist_opt ::= */ yytestcase(yyruleno==238);
  22039. +#line 427 "ext/sqlite/libsqlite/src/parse.y"
  22040. +{yygotominor.yy320 = 0;}
  22041. +#line 2317 "ext/sqlite/libsqlite/src/parse.c"
  22042. + break;
  22043. + case 139: /* orderby_opt ::= ORDER BY sortlist */
  22044. + case 149: /* groupby_opt ::= GROUP BY exprlist */ yytestcase(yyruleno==149);
  22045. +#line 438 "ext/sqlite/libsqlite/src/parse.y"
  22046. +{yygotominor.yy322 = yymsp[0].minor.yy322;}
  22047. +#line 2323 "ext/sqlite/libsqlite/src/parse.c"
  22048. + break;
  22049. + case 140: /* sortlist ::= sortlist COMMA sortitem collate sortorder */
  22050. +#line 439 "ext/sqlite/libsqlite/src/parse.y"
  22051. +{
  22052. + yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322,yymsp[-2].minor.yy242,0);
  22053. + if( yygotominor.yy322 ) yygotominor.yy322->a[yygotominor.yy322->nExpr-1].sortOrder = yymsp[-1].minor.yy372+yymsp[0].minor.yy372;
  22054. +}
  22055. +#line 2331 "ext/sqlite/libsqlite/src/parse.c"
  22056. + break;
  22057. + case 141: /* sortlist ::= sortitem collate sortorder */
  22058. +#line 443 "ext/sqlite/libsqlite/src/parse.y"
  22059. +{
  22060. + yygotominor.yy322 = sqliteExprListAppend(0,yymsp[-2].minor.yy242,0);
  22061. + if( yygotominor.yy322 ) yygotominor.yy322->a[0].sortOrder = yymsp[-1].minor.yy372+yymsp[0].minor.yy372;
  22062. +}
  22063. +#line 2339 "ext/sqlite/libsqlite/src/parse.c"
  22064. + break;
  22065. + case 143: /* sortorder ::= ASC */
  22066. + case 145: /* sortorder ::= */ yytestcase(yyruleno==145);
  22067. +#line 452 "ext/sqlite/libsqlite/src/parse.y"
  22068. +{yygotominor.yy372 = SQLITE_SO_ASC;}
  22069. +#line 2345 "ext/sqlite/libsqlite/src/parse.c"
  22070. + break;
  22071. + case 144: /* sortorder ::= DESC */
  22072. +#line 453 "ext/sqlite/libsqlite/src/parse.y"
  22073. +{yygotominor.yy372 = SQLITE_SO_DESC;}
  22074. +#line 2350 "ext/sqlite/libsqlite/src/parse.c"
  22075. + break;
  22076. + case 146: /* collate ::= */
  22077. +#line 455 "ext/sqlite/libsqlite/src/parse.y"
  22078. +{yygotominor.yy372 = SQLITE_SO_UNK;}
  22079. +#line 2355 "ext/sqlite/libsqlite/src/parse.c"
  22080. + break;
  22081. + case 147: /* collate ::= COLLATE id */
  22082. +#line 456 "ext/sqlite/libsqlite/src/parse.y"
  22083. +{yygotominor.yy372 = sqliteCollateType(yymsp[0].minor.yy0.z, yymsp[0].minor.yy0.n);}
  22084. +#line 2360 "ext/sqlite/libsqlite/src/parse.c"
  22085. + break;
  22086. + case 152: /* limit_opt ::= */
  22087. +#line 469 "ext/sqlite/libsqlite/src/parse.y"
  22088. +{yygotominor.yy124.limit = -1; yygotominor.yy124.offset = 0;}
  22089. +#line 2365 "ext/sqlite/libsqlite/src/parse.c"
  22090. + break;
  22091. + case 153: /* limit_opt ::= LIMIT signed */
  22092. +#line 470 "ext/sqlite/libsqlite/src/parse.y"
  22093. +{yygotominor.yy124.limit = yymsp[0].minor.yy372; yygotominor.yy124.offset = 0;}
  22094. +#line 2370 "ext/sqlite/libsqlite/src/parse.c"
  22095. + break;
  22096. + case 154: /* limit_opt ::= LIMIT signed OFFSET signed */
  22097. +#line 472 "ext/sqlite/libsqlite/src/parse.y"
  22098. +{yygotominor.yy124.limit = yymsp[-2].minor.yy372; yygotominor.yy124.offset = yymsp[0].minor.yy372;}
  22099. +#line 2375 "ext/sqlite/libsqlite/src/parse.c"
  22100. + break;
  22101. + case 155: /* limit_opt ::= LIMIT signed COMMA signed */
  22102. +#line 474 "ext/sqlite/libsqlite/src/parse.y"
  22103. +{yygotominor.yy124.limit = yymsp[0].minor.yy372; yygotominor.yy124.offset = yymsp[-2].minor.yy372;}
  22104. +#line 2380 "ext/sqlite/libsqlite/src/parse.c"
  22105. + break;
  22106. + case 156: /* cmd ::= DELETE FROM nm dbnm where_opt */
  22107. +#line 478 "ext/sqlite/libsqlite/src/parse.y"
  22108. +{
  22109. + sqliteDeleteFrom(pParse, sqliteSrcListAppend(0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0), yymsp[0].minor.yy242);
  22110. +}
  22111. +#line 2387 "ext/sqlite/libsqlite/src/parse.c"
  22112. + break;
  22113. + case 159: /* cmd ::= UPDATE orconf nm dbnm SET setlist where_opt */
  22114. +#line 494 "ext/sqlite/libsqlite/src/parse.y"
  22115. +{sqliteUpdate(pParse,sqliteSrcListAppend(0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0),yymsp[-1].minor.yy322,yymsp[0].minor.yy242,yymsp[-5].minor.yy372);}
  22116. +#line 2392 "ext/sqlite/libsqlite/src/parse.c"
  22117. + break;
  22118. + case 160: /* setlist ::= setlist COMMA nm EQ expr */
  22119. +#line 497 "ext/sqlite/libsqlite/src/parse.y"
  22120. +{yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322,yymsp[0].minor.yy242,&yymsp[-2].minor.yy0);}
  22121. +#line 2397 "ext/sqlite/libsqlite/src/parse.c"
  22122. + break;
  22123. + case 161: /* setlist ::= nm EQ expr */
  22124. +#line 498 "ext/sqlite/libsqlite/src/parse.y"
  22125. +{yygotominor.yy322 = sqliteExprListAppend(0,yymsp[0].minor.yy242,&yymsp[-2].minor.yy0);}
  22126. +#line 2402 "ext/sqlite/libsqlite/src/parse.c"
  22127. + break;
  22128. + case 162: /* cmd ::= insert_cmd INTO nm dbnm inscollist_opt VALUES LP itemlist RP */
  22129. +#line 504 "ext/sqlite/libsqlite/src/parse.y"
  22130. +{sqliteInsert(pParse, sqliteSrcListAppend(0,&yymsp[-6].minor.yy0,&yymsp[-5].minor.yy0), yymsp[-1].minor.yy322, 0, yymsp[-4].minor.yy320, yymsp[-8].minor.yy372);}
  22131. +#line 2407 "ext/sqlite/libsqlite/src/parse.c"
  22132. + break;
  22133. + case 163: /* cmd ::= insert_cmd INTO nm dbnm inscollist_opt select */
  22134. +#line 506 "ext/sqlite/libsqlite/src/parse.y"
  22135. +{sqliteInsert(pParse, sqliteSrcListAppend(0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0), 0, yymsp[0].minor.yy179, yymsp[-1].minor.yy320, yymsp[-5].minor.yy372);}
  22136. +#line 2412 "ext/sqlite/libsqlite/src/parse.c"
  22137. + break;
  22138. + case 165: /* insert_cmd ::= REPLACE */
  22139. +#line 510 "ext/sqlite/libsqlite/src/parse.y"
  22140. +{yygotominor.yy372 = OE_Replace;}
  22141. +#line 2417 "ext/sqlite/libsqlite/src/parse.c"
  22142. + break;
  22143. + case 166: /* itemlist ::= itemlist COMMA expr */
  22144. + case 231: /* exprlist ::= exprlist COMMA expritem */ yytestcase(yyruleno==231);
  22145. +#line 516 "ext/sqlite/libsqlite/src/parse.y"
  22146. +{yygotominor.yy322 = sqliteExprListAppend(yymsp[-2].minor.yy322,yymsp[0].minor.yy242,0);}
  22147. +#line 2423 "ext/sqlite/libsqlite/src/parse.c"
  22148. + break;
  22149. + case 167: /* itemlist ::= expr */
  22150. + case 232: /* exprlist ::= expritem */ yytestcase(yyruleno==232);
  22151. +#line 517 "ext/sqlite/libsqlite/src/parse.y"
  22152. +{yygotominor.yy322 = sqliteExprListAppend(0,yymsp[0].minor.yy242,0);}
  22153. +#line 2429 "ext/sqlite/libsqlite/src/parse.c"
  22154. + break;
  22155. + case 170: /* inscollist ::= inscollist COMMA nm */
  22156. + case 240: /* idxlist ::= idxlist COMMA idxitem */ yytestcase(yyruleno==240);
  22157. +#line 526 "ext/sqlite/libsqlite/src/parse.y"
  22158. +{yygotominor.yy320 = sqliteIdListAppend(yymsp[-2].minor.yy320,&yymsp[0].minor.yy0);}
  22159. +#line 2435 "ext/sqlite/libsqlite/src/parse.c"
  22160. + break;
  22161. + case 171: /* inscollist ::= nm */
  22162. + case 241: /* idxlist ::= idxitem */ yytestcase(yyruleno==241);
  22163. +#line 527 "ext/sqlite/libsqlite/src/parse.y"
  22164. +{yygotominor.yy320 = sqliteIdListAppend(0,&yymsp[0].minor.yy0);}
  22165. +#line 2441 "ext/sqlite/libsqlite/src/parse.c"
  22166. + break;
  22167. + case 172: /* expr ::= LP expr RP */
  22168. +#line 535 "ext/sqlite/libsqlite/src/parse.y"
  22169. +{yygotominor.yy242 = yymsp[-1].minor.yy242; sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); }
  22170. +#line 2446 "ext/sqlite/libsqlite/src/parse.c"
  22171. + break;
  22172. + case 173: /* expr ::= NULL */
  22173. +#line 536 "ext/sqlite/libsqlite/src/parse.y"
  22174. +{yygotominor.yy242 = sqliteExpr(TK_NULL, 0, 0, &yymsp[0].minor.yy0);}
  22175. +#line 2451 "ext/sqlite/libsqlite/src/parse.c"
  22176. + break;
  22177. + case 174: /* expr ::= ID */
  22178. + case 175: /* expr ::= JOIN_KW */ yytestcase(yyruleno==175);
  22179. +#line 537 "ext/sqlite/libsqlite/src/parse.y"
  22180. +{yygotominor.yy242 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);}
  22181. +#line 2457 "ext/sqlite/libsqlite/src/parse.c"
  22182. + break;
  22183. + case 176: /* expr ::= nm DOT nm */
  22184. +#line 539 "ext/sqlite/libsqlite/src/parse.y"
  22185. +{
  22186. + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  22187. + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);
  22188. + yygotominor.yy242 = sqliteExpr(TK_DOT, temp1, temp2, 0);
  22189. +}
  22190. +#line 2466 "ext/sqlite/libsqlite/src/parse.c"
  22191. + break;
  22192. + case 177: /* expr ::= nm DOT nm DOT nm */
  22193. +#line 544 "ext/sqlite/libsqlite/src/parse.y"
  22194. +{
  22195. + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  22196. + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  22197. + Expr *temp3 = sqliteExpr(TK_ID, 0, 0, &yymsp[0].minor.yy0);
  22198. + Expr *temp4 = sqliteExpr(TK_DOT, temp2, temp3, 0);
  22199. + yygotominor.yy242 = sqliteExpr(TK_DOT, temp1, temp4, 0);
  22200. +}
  22201. +#line 2477 "ext/sqlite/libsqlite/src/parse.c"
  22202. + break;
  22203. + case 178: /* expr ::= INTEGER */
  22204. +#line 551 "ext/sqlite/libsqlite/src/parse.y"
  22205. +{yygotominor.yy242 = sqliteExpr(TK_INTEGER, 0, 0, &yymsp[0].minor.yy0);}
  22206. +#line 2482 "ext/sqlite/libsqlite/src/parse.c"
  22207. + break;
  22208. + case 179: /* expr ::= FLOAT */
  22209. +#line 552 "ext/sqlite/libsqlite/src/parse.y"
  22210. +{yygotominor.yy242 = sqliteExpr(TK_FLOAT, 0, 0, &yymsp[0].minor.yy0);}
  22211. +#line 2487 "ext/sqlite/libsqlite/src/parse.c"
  22212. + break;
  22213. + case 180: /* expr ::= STRING */
  22214. +#line 553 "ext/sqlite/libsqlite/src/parse.y"
  22215. +{yygotominor.yy242 = sqliteExpr(TK_STRING, 0, 0, &yymsp[0].minor.yy0);}
  22216. +#line 2492 "ext/sqlite/libsqlite/src/parse.c"
  22217. + break;
  22218. + case 181: /* expr ::= VARIABLE */
  22219. +#line 554 "ext/sqlite/libsqlite/src/parse.y"
  22220. +{
  22221. + yygotominor.yy242 = sqliteExpr(TK_VARIABLE, 0, 0, &yymsp[0].minor.yy0);
  22222. + if( yygotominor.yy242 ) yygotominor.yy242->iTable = ++pParse->nVar;
  22223. +}
  22224. +#line 2500 "ext/sqlite/libsqlite/src/parse.c"
  22225. + break;
  22226. + case 182: /* expr ::= ID LP exprlist RP */
  22227. +#line 558 "ext/sqlite/libsqlite/src/parse.y"
  22228. +{
  22229. + yygotominor.yy242 = sqliteExprFunction(yymsp[-1].minor.yy322, &yymsp[-3].minor.yy0);
  22230. + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  22231. +}
  22232. +#line 2508 "ext/sqlite/libsqlite/src/parse.c"
  22233. + break;
  22234. + case 183: /* expr ::= ID LP STAR RP */
  22235. +#line 562 "ext/sqlite/libsqlite/src/parse.y"
  22236. +{
  22237. + yygotominor.yy242 = sqliteExprFunction(0, &yymsp[-3].minor.yy0);
  22238. + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  22239. +}
  22240. +#line 2516 "ext/sqlite/libsqlite/src/parse.c"
  22241. + break;
  22242. + case 184: /* expr ::= expr AND expr */
  22243. +#line 566 "ext/sqlite/libsqlite/src/parse.y"
  22244. +{yygotominor.yy242 = sqliteExpr(TK_AND, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22245. +#line 2521 "ext/sqlite/libsqlite/src/parse.c"
  22246. + break;
  22247. + case 185: /* expr ::= expr OR expr */
  22248. +#line 567 "ext/sqlite/libsqlite/src/parse.y"
  22249. +{yygotominor.yy242 = sqliteExpr(TK_OR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22250. +#line 2526 "ext/sqlite/libsqlite/src/parse.c"
  22251. + break;
  22252. + case 186: /* expr ::= expr LT expr */
  22253. +#line 568 "ext/sqlite/libsqlite/src/parse.y"
  22254. +{yygotominor.yy242 = sqliteExpr(TK_LT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22255. +#line 2531 "ext/sqlite/libsqlite/src/parse.c"
  22256. + break;
  22257. + case 187: /* expr ::= expr GT expr */
  22258. +#line 569 "ext/sqlite/libsqlite/src/parse.y"
  22259. +{yygotominor.yy242 = sqliteExpr(TK_GT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22260. +#line 2536 "ext/sqlite/libsqlite/src/parse.c"
  22261. + break;
  22262. + case 188: /* expr ::= expr LE expr */
  22263. +#line 570 "ext/sqlite/libsqlite/src/parse.y"
  22264. +{yygotominor.yy242 = sqliteExpr(TK_LE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22265. +#line 2541 "ext/sqlite/libsqlite/src/parse.c"
  22266. + break;
  22267. + case 189: /* expr ::= expr GE expr */
  22268. +#line 571 "ext/sqlite/libsqlite/src/parse.y"
  22269. +{yygotominor.yy242 = sqliteExpr(TK_GE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22270. +#line 2546 "ext/sqlite/libsqlite/src/parse.c"
  22271. + break;
  22272. + case 190: /* expr ::= expr NE expr */
  22273. +#line 572 "ext/sqlite/libsqlite/src/parse.y"
  22274. +{yygotominor.yy242 = sqliteExpr(TK_NE, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22275. +#line 2551 "ext/sqlite/libsqlite/src/parse.c"
  22276. + break;
  22277. + case 191: /* expr ::= expr EQ expr */
  22278. +#line 573 "ext/sqlite/libsqlite/src/parse.y"
  22279. +{yygotominor.yy242 = sqliteExpr(TK_EQ, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22280. +#line 2556 "ext/sqlite/libsqlite/src/parse.c"
  22281. + break;
  22282. + case 192: /* expr ::= expr BITAND expr */
  22283. +#line 574 "ext/sqlite/libsqlite/src/parse.y"
  22284. +{yygotominor.yy242 = sqliteExpr(TK_BITAND, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22285. +#line 2561 "ext/sqlite/libsqlite/src/parse.c"
  22286. + break;
  22287. + case 193: /* expr ::= expr BITOR expr */
  22288. +#line 575 "ext/sqlite/libsqlite/src/parse.y"
  22289. +{yygotominor.yy242 = sqliteExpr(TK_BITOR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22290. +#line 2566 "ext/sqlite/libsqlite/src/parse.c"
  22291. + break;
  22292. + case 194: /* expr ::= expr LSHIFT expr */
  22293. +#line 576 "ext/sqlite/libsqlite/src/parse.y"
  22294. +{yygotominor.yy242 = sqliteExpr(TK_LSHIFT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22295. +#line 2571 "ext/sqlite/libsqlite/src/parse.c"
  22296. + break;
  22297. + case 195: /* expr ::= expr RSHIFT expr */
  22298. +#line 577 "ext/sqlite/libsqlite/src/parse.y"
  22299. +{yygotominor.yy242 = sqliteExpr(TK_RSHIFT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22300. +#line 2576 "ext/sqlite/libsqlite/src/parse.c"
  22301. + break;
  22302. + case 196: /* expr ::= expr likeop expr */
  22303. +#line 578 "ext/sqlite/libsqlite/src/parse.y"
  22304. +{
  22305. + ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy242, 0);
  22306. + pList = sqliteExprListAppend(pList, yymsp[-2].minor.yy242, 0);
  22307. + yygotominor.yy242 = sqliteExprFunction(pList, 0);
  22308. + if( yygotominor.yy242 ) yygotominor.yy242->op = yymsp[-1].minor.yy372;
  22309. + sqliteExprSpan(yygotominor.yy242, &yymsp[-2].minor.yy242->span, &yymsp[0].minor.yy242->span);
  22310. +}
  22311. +#line 2587 "ext/sqlite/libsqlite/src/parse.c"
  22312. + break;
  22313. + case 197: /* expr ::= expr NOT likeop expr */
  22314. +#line 585 "ext/sqlite/libsqlite/src/parse.y"
  22315. +{
  22316. + ExprList *pList = sqliteExprListAppend(0, yymsp[0].minor.yy242, 0);
  22317. + pList = sqliteExprListAppend(pList, yymsp[-3].minor.yy242, 0);
  22318. + yygotominor.yy242 = sqliteExprFunction(pList, 0);
  22319. + if( yygotominor.yy242 ) yygotominor.yy242->op = yymsp[-1].minor.yy372;
  22320. + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
  22321. + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,&yymsp[0].minor.yy242->span);
  22322. +}
  22323. +#line 2599 "ext/sqlite/libsqlite/src/parse.c"
  22324. + break;
  22325. + case 198: /* likeop ::= LIKE */
  22326. +#line 594 "ext/sqlite/libsqlite/src/parse.y"
  22327. +{yygotominor.yy372 = TK_LIKE;}
  22328. +#line 2604 "ext/sqlite/libsqlite/src/parse.c"
  22329. + break;
  22330. + case 199: /* likeop ::= GLOB */
  22331. +#line 595 "ext/sqlite/libsqlite/src/parse.y"
  22332. +{yygotominor.yy372 = TK_GLOB;}
  22333. +#line 2609 "ext/sqlite/libsqlite/src/parse.c"
  22334. + break;
  22335. + case 200: /* expr ::= expr PLUS expr */
  22336. +#line 596 "ext/sqlite/libsqlite/src/parse.y"
  22337. +{yygotominor.yy242 = sqliteExpr(TK_PLUS, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22338. +#line 2614 "ext/sqlite/libsqlite/src/parse.c"
  22339. + break;
  22340. + case 201: /* expr ::= expr MINUS expr */
  22341. +#line 597 "ext/sqlite/libsqlite/src/parse.y"
  22342. +{yygotominor.yy242 = sqliteExpr(TK_MINUS, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22343. +#line 2619 "ext/sqlite/libsqlite/src/parse.c"
  22344. + break;
  22345. + case 202: /* expr ::= expr STAR expr */
  22346. +#line 598 "ext/sqlite/libsqlite/src/parse.y"
  22347. +{yygotominor.yy242 = sqliteExpr(TK_STAR, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22348. +#line 2624 "ext/sqlite/libsqlite/src/parse.c"
  22349. + break;
  22350. + case 203: /* expr ::= expr SLASH expr */
  22351. +#line 599 "ext/sqlite/libsqlite/src/parse.y"
  22352. +{yygotominor.yy242 = sqliteExpr(TK_SLASH, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22353. +#line 2629 "ext/sqlite/libsqlite/src/parse.c"
  22354. + break;
  22355. + case 204: /* expr ::= expr REM expr */
  22356. +#line 600 "ext/sqlite/libsqlite/src/parse.y"
  22357. +{yygotominor.yy242 = sqliteExpr(TK_REM, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22358. +#line 2634 "ext/sqlite/libsqlite/src/parse.c"
  22359. + break;
  22360. + case 205: /* expr ::= expr CONCAT expr */
  22361. +#line 601 "ext/sqlite/libsqlite/src/parse.y"
  22362. +{yygotominor.yy242 = sqliteExpr(TK_CONCAT, yymsp[-2].minor.yy242, yymsp[0].minor.yy242, 0);}
  22363. +#line 2639 "ext/sqlite/libsqlite/src/parse.c"
  22364. + break;
  22365. + case 206: /* expr ::= expr ISNULL */
  22366. +#line 602 "ext/sqlite/libsqlite/src/parse.y"
  22367. +{
  22368. + yygotominor.yy242 = sqliteExpr(TK_ISNULL, yymsp[-1].minor.yy242, 0, 0);
  22369. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy242->span,&yymsp[0].minor.yy0);
  22370. +}
  22371. +#line 2647 "ext/sqlite/libsqlite/src/parse.c"
  22372. + break;
  22373. + case 207: /* expr ::= expr IS NULL */
  22374. +#line 606 "ext/sqlite/libsqlite/src/parse.y"
  22375. +{
  22376. + yygotominor.yy242 = sqliteExpr(TK_ISNULL, yymsp[-2].minor.yy242, 0, 0);
  22377. + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy242->span,&yymsp[0].minor.yy0);
  22378. +}
  22379. +#line 2655 "ext/sqlite/libsqlite/src/parse.c"
  22380. + break;
  22381. + case 208: /* expr ::= expr NOTNULL */
  22382. +#line 610 "ext/sqlite/libsqlite/src/parse.y"
  22383. +{
  22384. + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-1].minor.yy242, 0, 0);
  22385. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy242->span,&yymsp[0].minor.yy0);
  22386. +}
  22387. +#line 2663 "ext/sqlite/libsqlite/src/parse.c"
  22388. + break;
  22389. + case 209: /* expr ::= expr NOT NULL */
  22390. +#line 614 "ext/sqlite/libsqlite/src/parse.y"
  22391. +{
  22392. + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-2].minor.yy242, 0, 0);
  22393. + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy242->span,&yymsp[0].minor.yy0);
  22394. +}
  22395. +#line 2671 "ext/sqlite/libsqlite/src/parse.c"
  22396. + break;
  22397. + case 210: /* expr ::= expr IS NOT NULL */
  22398. +#line 618 "ext/sqlite/libsqlite/src/parse.y"
  22399. +{
  22400. + yygotominor.yy242 = sqliteExpr(TK_NOTNULL, yymsp[-3].minor.yy242, 0, 0);
  22401. + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,&yymsp[0].minor.yy0);
  22402. +}
  22403. +#line 2679 "ext/sqlite/libsqlite/src/parse.c"
  22404. + break;
  22405. + case 211: /* expr ::= NOT expr */
  22406. +#line 622 "ext/sqlite/libsqlite/src/parse.y"
  22407. +{
  22408. + yygotominor.yy242 = sqliteExpr(TK_NOT, yymsp[0].minor.yy242, 0, 0);
  22409. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
  22410. +}
  22411. +#line 2687 "ext/sqlite/libsqlite/src/parse.c"
  22412. + break;
  22413. + case 212: /* expr ::= BITNOT expr */
  22414. +#line 626 "ext/sqlite/libsqlite/src/parse.y"
  22415. +{
  22416. + yygotominor.yy242 = sqliteExpr(TK_BITNOT, yymsp[0].minor.yy242, 0, 0);
  22417. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
  22418. +}
  22419. +#line 2695 "ext/sqlite/libsqlite/src/parse.c"
  22420. + break;
  22421. + case 213: /* expr ::= MINUS expr */
  22422. +#line 630 "ext/sqlite/libsqlite/src/parse.y"
  22423. +{
  22424. + yygotominor.yy242 = sqliteExpr(TK_UMINUS, yymsp[0].minor.yy242, 0, 0);
  22425. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
  22426. +}
  22427. +#line 2703 "ext/sqlite/libsqlite/src/parse.c"
  22428. + break;
  22429. + case 214: /* expr ::= PLUS expr */
  22430. +#line 634 "ext/sqlite/libsqlite/src/parse.y"
  22431. +{
  22432. + yygotominor.yy242 = sqliteExpr(TK_UPLUS, yymsp[0].minor.yy242, 0, 0);
  22433. + sqliteExprSpan(yygotominor.yy242,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy242->span);
  22434. +}
  22435. +#line 2711 "ext/sqlite/libsqlite/src/parse.c"
  22436. + break;
  22437. + case 215: /* expr ::= LP select RP */
  22438. +#line 638 "ext/sqlite/libsqlite/src/parse.y"
  22439. +{
  22440. + yygotominor.yy242 = sqliteExpr(TK_SELECT, 0, 0, 0);
  22441. + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
  22442. + sqliteExprSpan(yygotominor.yy242,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  22443. +}
  22444. +#line 2720 "ext/sqlite/libsqlite/src/parse.c"
  22445. + break;
  22446. + case 216: /* expr ::= expr BETWEEN expr AND expr */
  22447. +#line 643 "ext/sqlite/libsqlite/src/parse.y"
  22448. +{
  22449. + ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
  22450. + pList = sqliteExprListAppend(pList, yymsp[0].minor.yy242, 0);
  22451. + yygotominor.yy242 = sqliteExpr(TK_BETWEEN, yymsp[-4].minor.yy242, 0, 0);
  22452. + if( yygotominor.yy242 ) yygotominor.yy242->pList = pList;
  22453. + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy242->span);
  22454. +}
  22455. +#line 2731 "ext/sqlite/libsqlite/src/parse.c"
  22456. + break;
  22457. + case 217: /* expr ::= expr NOT BETWEEN expr AND expr */
  22458. +#line 650 "ext/sqlite/libsqlite/src/parse.y"
  22459. +{
  22460. + ExprList *pList = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
  22461. + pList = sqliteExprListAppend(pList, yymsp[0].minor.yy242, 0);
  22462. + yygotominor.yy242 = sqliteExpr(TK_BETWEEN, yymsp[-5].minor.yy242, 0, 0);
  22463. + if( yygotominor.yy242 ) yygotominor.yy242->pList = pList;
  22464. + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
  22465. + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy242->span);
  22466. +}
  22467. +#line 2743 "ext/sqlite/libsqlite/src/parse.c"
  22468. + break;
  22469. + case 218: /* expr ::= expr IN LP exprlist RP */
  22470. +#line 658 "ext/sqlite/libsqlite/src/parse.y"
  22471. +{
  22472. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
  22473. + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-1].minor.yy322;
  22474. + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy0);
  22475. +}
  22476. +#line 2752 "ext/sqlite/libsqlite/src/parse.c"
  22477. + break;
  22478. + case 219: /* expr ::= expr IN LP select RP */
  22479. +#line 663 "ext/sqlite/libsqlite/src/parse.y"
  22480. +{
  22481. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
  22482. + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
  22483. + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,&yymsp[0].minor.yy0);
  22484. +}
  22485. +#line 2761 "ext/sqlite/libsqlite/src/parse.c"
  22486. + break;
  22487. + case 220: /* expr ::= expr NOT IN LP exprlist RP */
  22488. +#line 668 "ext/sqlite/libsqlite/src/parse.y"
  22489. +{
  22490. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-5].minor.yy242, 0, 0);
  22491. + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-1].minor.yy322;
  22492. + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
  22493. + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy0);
  22494. +}
  22495. +#line 2771 "ext/sqlite/libsqlite/src/parse.c"
  22496. + break;
  22497. + case 221: /* expr ::= expr NOT IN LP select RP */
  22498. +#line 674 "ext/sqlite/libsqlite/src/parse.y"
  22499. +{
  22500. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-5].minor.yy242, 0, 0);
  22501. + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = yymsp[-1].minor.yy179;
  22502. + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
  22503. + sqliteExprSpan(yygotominor.yy242,&yymsp[-5].minor.yy242->span,&yymsp[0].minor.yy0);
  22504. +}
  22505. +#line 2781 "ext/sqlite/libsqlite/src/parse.c"
  22506. + break;
  22507. + case 222: /* expr ::= expr IN nm dbnm */
  22508. +#line 680 "ext/sqlite/libsqlite/src/parse.y"
  22509. +{
  22510. + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
  22511. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-3].minor.yy242, 0, 0);
  22512. + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
  22513. + sqliteExprSpan(yygotominor.yy242,&yymsp[-3].minor.yy242->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  22514. +}
  22515. +#line 2791 "ext/sqlite/libsqlite/src/parse.c"
  22516. + break;
  22517. + case 223: /* expr ::= expr NOT IN nm dbnm */
  22518. +#line 686 "ext/sqlite/libsqlite/src/parse.y"
  22519. +{
  22520. + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
  22521. + yygotominor.yy242 = sqliteExpr(TK_IN, yymsp[-4].minor.yy242, 0, 0);
  22522. + if( yygotominor.yy242 ) yygotominor.yy242->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
  22523. + yygotominor.yy242 = sqliteExpr(TK_NOT, yygotominor.yy242, 0, 0);
  22524. + sqliteExprSpan(yygotominor.yy242,&yymsp[-4].minor.yy242->span,yymsp[0].minor.yy0.z?&yymsp[0].minor.yy0:&yymsp[-1].minor.yy0);
  22525. +}
  22526. +#line 2802 "ext/sqlite/libsqlite/src/parse.c"
  22527. + break;
  22528. + case 224: /* expr ::= CASE case_operand case_exprlist case_else END */
  22529. +#line 696 "ext/sqlite/libsqlite/src/parse.y"
  22530. +{
  22531. + yygotominor.yy242 = sqliteExpr(TK_CASE, yymsp[-3].minor.yy242, yymsp[-1].minor.yy242, 0);
  22532. + if( yygotominor.yy242 ) yygotominor.yy242->pList = yymsp[-2].minor.yy322;
  22533. + sqliteExprSpan(yygotominor.yy242, &yymsp[-4].minor.yy0, &yymsp[0].minor.yy0);
  22534. +}
  22535. +#line 2811 "ext/sqlite/libsqlite/src/parse.c"
  22536. + break;
  22537. + case 225: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  22538. +#line 703 "ext/sqlite/libsqlite/src/parse.y"
  22539. +{
  22540. + yygotominor.yy322 = sqliteExprListAppend(yymsp[-4].minor.yy322, yymsp[-2].minor.yy242, 0);
  22541. + yygotominor.yy322 = sqliteExprListAppend(yygotominor.yy322, yymsp[0].minor.yy242, 0);
  22542. +}
  22543. +#line 2819 "ext/sqlite/libsqlite/src/parse.c"
  22544. + break;
  22545. + case 226: /* case_exprlist ::= WHEN expr THEN expr */
  22546. +#line 707 "ext/sqlite/libsqlite/src/parse.y"
  22547. +{
  22548. + yygotominor.yy322 = sqliteExprListAppend(0, yymsp[-2].minor.yy242, 0);
  22549. + yygotominor.yy322 = sqliteExprListAppend(yygotominor.yy322, yymsp[0].minor.yy242, 0);
  22550. +}
  22551. +#line 2827 "ext/sqlite/libsqlite/src/parse.c"
  22552. + break;
  22553. + case 235: /* cmd ::= CREATE uniqueflag INDEX nm ON nm dbnm LP idxlist RP onconf */
  22554. +#line 732 "ext/sqlite/libsqlite/src/parse.y"
  22555. +{
  22556. + SrcList *pSrc = sqliteSrcListAppend(0, &yymsp[-5].minor.yy0, &yymsp[-4].minor.yy0);
  22557. + if( yymsp[-9].minor.yy372!=OE_None ) yymsp[-9].minor.yy372 = yymsp[0].minor.yy372;
  22558. + if( yymsp[-9].minor.yy372==OE_Default) yymsp[-9].minor.yy372 = OE_Abort;
  22559. + sqliteCreateIndex(pParse, &yymsp[-7].minor.yy0, pSrc, yymsp[-2].minor.yy320, yymsp[-9].minor.yy372, &yymsp[-10].minor.yy0, &yymsp[-1].minor.yy0);
  22560. +}
  22561. +#line 2837 "ext/sqlite/libsqlite/src/parse.c"
  22562. + break;
  22563. + case 237: /* uniqueflag ::= */
  22564. +#line 741 "ext/sqlite/libsqlite/src/parse.y"
  22565. +{ yygotominor.yy372 = OE_None; }
  22566. +#line 2842 "ext/sqlite/libsqlite/src/parse.c"
  22567. + break;
  22568. + case 243: /* cmd ::= DROP INDEX nm dbnm */
  22569. +#line 758 "ext/sqlite/libsqlite/src/parse.y"
  22570. +{
  22571. + sqliteDropIndex(pParse, sqliteSrcListAppend(0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0));
  22572. +}
  22573. +#line 2849 "ext/sqlite/libsqlite/src/parse.c"
  22574. + break;
  22575. + case 244: /* cmd ::= COPY orconf nm dbnm FROM nm USING DELIMITERS STRING */
  22576. +#line 766 "ext/sqlite/libsqlite/src/parse.y"
  22577. +{sqliteCopy(pParse,sqliteSrcListAppend(0,&yymsp[-6].minor.yy0,&yymsp[-5].minor.yy0),&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0,yymsp[-7].minor.yy372);}
  22578. +#line 2854 "ext/sqlite/libsqlite/src/parse.c"
  22579. + break;
  22580. + case 245: /* cmd ::= COPY orconf nm dbnm FROM nm */
  22581. +#line 768 "ext/sqlite/libsqlite/src/parse.y"
  22582. +{sqliteCopy(pParse,sqliteSrcListAppend(0,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0),&yymsp[0].minor.yy0,0,yymsp[-4].minor.yy372);}
  22583. +#line 2859 "ext/sqlite/libsqlite/src/parse.c"
  22584. + break;
  22585. + case 246: /* cmd ::= VACUUM */
  22586. +#line 772 "ext/sqlite/libsqlite/src/parse.y"
  22587. +{sqliteVacuum(pParse,0);}
  22588. +#line 2864 "ext/sqlite/libsqlite/src/parse.c"
  22589. + break;
  22590. + case 247: /* cmd ::= VACUUM nm */
  22591. +#line 773 "ext/sqlite/libsqlite/src/parse.y"
  22592. +{sqliteVacuum(pParse,&yymsp[0].minor.yy0);}
  22593. +#line 2869 "ext/sqlite/libsqlite/src/parse.c"
  22594. + break;
  22595. + case 248: /* cmd ::= PRAGMA ids EQ nm */
  22596. + case 249: /* cmd ::= PRAGMA ids EQ ON */ yytestcase(yyruleno==249);
  22597. + case 250: /* cmd ::= PRAGMA ids EQ plus_num */ yytestcase(yyruleno==250);
  22598. +#line 777 "ext/sqlite/libsqlite/src/parse.y"
  22599. +{sqlitePragma(pParse,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  22600. +#line 2876 "ext/sqlite/libsqlite/src/parse.c"
  22601. + break;
  22602. + case 251: /* cmd ::= PRAGMA ids EQ minus_num */
  22603. +#line 780 "ext/sqlite/libsqlite/src/parse.y"
  22604. +{sqlitePragma(pParse,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  22605. +#line 2881 "ext/sqlite/libsqlite/src/parse.c"
  22606. + break;
  22607. + case 252: /* cmd ::= PRAGMA ids LP nm RP */
  22608. +#line 781 "ext/sqlite/libsqlite/src/parse.y"
  22609. +{sqlitePragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  22610. +#line 2886 "ext/sqlite/libsqlite/src/parse.c"
  22611. + break;
  22612. + case 253: /* cmd ::= PRAGMA ids */
  22613. +#line 782 "ext/sqlite/libsqlite/src/parse.y"
  22614. +{sqlitePragma(pParse,&yymsp[0].minor.yy0,&yymsp[0].minor.yy0,0);}
  22615. +#line 2891 "ext/sqlite/libsqlite/src/parse.c"
  22616. + break;
  22617. + case 260: /* cmd ::= CREATE trigger_decl BEGIN trigger_cmd_list END */
  22618. +#line 792 "ext/sqlite/libsqlite/src/parse.y"
  22619. +{
  22620. + Token all;
  22621. + all.z = yymsp[-4].minor.yy0.z;
  22622. + all.n = (yymsp[0].minor.yy0.z - yymsp[-4].minor.yy0.z) + yymsp[0].minor.yy0.n;
  22623. + sqliteFinishTrigger(pParse, yymsp[-1].minor.yy19, &all);
  22624. +}
  22625. +#line 2901 "ext/sqlite/libsqlite/src/parse.c"
  22626. + break;
  22627. + case 261: /* trigger_decl ::= temp TRIGGER nm trigger_time trigger_event ON nm dbnm foreach_clause when_clause */
  22628. +#line 800 "ext/sqlite/libsqlite/src/parse.y"
  22629. +{
  22630. + SrcList *pTab = sqliteSrcListAppend(0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0);
  22631. + sqliteBeginTrigger(pParse, &yymsp[-7].minor.yy0, yymsp[-6].minor.yy372, yymsp[-5].minor.yy290.a, yymsp[-5].minor.yy290.b, pTab, yymsp[-1].minor.yy372, yymsp[0].minor.yy182, yymsp[-9].minor.yy372);
  22632. +}
  22633. +#line 2909 "ext/sqlite/libsqlite/src/parse.c"
  22634. + break;
  22635. + case 262: /* trigger_time ::= BEFORE */
  22636. + case 265: /* trigger_time ::= */ yytestcase(yyruleno==265);
  22637. +#line 806 "ext/sqlite/libsqlite/src/parse.y"
  22638. +{ yygotominor.yy372 = TK_BEFORE; }
  22639. +#line 2915 "ext/sqlite/libsqlite/src/parse.c"
  22640. + break;
  22641. + case 263: /* trigger_time ::= AFTER */
  22642. +#line 807 "ext/sqlite/libsqlite/src/parse.y"
  22643. +{ yygotominor.yy372 = TK_AFTER; }
  22644. +#line 2920 "ext/sqlite/libsqlite/src/parse.c"
  22645. + break;
  22646. + case 264: /* trigger_time ::= INSTEAD OF */
  22647. +#line 808 "ext/sqlite/libsqlite/src/parse.y"
  22648. +{ yygotominor.yy372 = TK_INSTEAD;}
  22649. +#line 2925 "ext/sqlite/libsqlite/src/parse.c"
  22650. + break;
  22651. + case 266: /* trigger_event ::= DELETE */
  22652. +#line 813 "ext/sqlite/libsqlite/src/parse.y"
  22653. +{ yygotominor.yy290.a = TK_DELETE; yygotominor.yy290.b = 0; }
  22654. +#line 2930 "ext/sqlite/libsqlite/src/parse.c"
  22655. + break;
  22656. + case 267: /* trigger_event ::= INSERT */
  22657. +#line 814 "ext/sqlite/libsqlite/src/parse.y"
  22658. +{ yygotominor.yy290.a = TK_INSERT; yygotominor.yy290.b = 0; }
  22659. +#line 2935 "ext/sqlite/libsqlite/src/parse.c"
  22660. + break;
  22661. + case 268: /* trigger_event ::= UPDATE */
  22662. +#line 815 "ext/sqlite/libsqlite/src/parse.y"
  22663. +{ yygotominor.yy290.a = TK_UPDATE; yygotominor.yy290.b = 0;}
  22664. +#line 2940 "ext/sqlite/libsqlite/src/parse.c"
  22665. + break;
  22666. + case 269: /* trigger_event ::= UPDATE OF inscollist */
  22667. +#line 816 "ext/sqlite/libsqlite/src/parse.y"
  22668. +{yygotominor.yy290.a = TK_UPDATE; yygotominor.yy290.b = yymsp[0].minor.yy320; }
  22669. +#line 2945 "ext/sqlite/libsqlite/src/parse.c"
  22670. + break;
  22671. + case 270: /* foreach_clause ::= */
  22672. + case 271: /* foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==271);
  22673. +#line 819 "ext/sqlite/libsqlite/src/parse.y"
  22674. +{ yygotominor.yy372 = TK_ROW; }
  22675. +#line 2951 "ext/sqlite/libsqlite/src/parse.c"
  22676. + break;
  22677. + case 272: /* foreach_clause ::= FOR EACH STATEMENT */
  22678. +#line 821 "ext/sqlite/libsqlite/src/parse.y"
  22679. +{ yygotominor.yy372 = TK_STATEMENT; }
  22680. +#line 2956 "ext/sqlite/libsqlite/src/parse.c"
  22681. + break;
  22682. + case 273: /* when_clause ::= */
  22683. +#line 824 "ext/sqlite/libsqlite/src/parse.y"
  22684. +{ yygotominor.yy182 = 0; }
  22685. +#line 2961 "ext/sqlite/libsqlite/src/parse.c"
  22686. + break;
  22687. + case 274: /* when_clause ::= WHEN expr */
  22688. +#line 825 "ext/sqlite/libsqlite/src/parse.y"
  22689. +{ yygotominor.yy182 = yymsp[0].minor.yy242; }
  22690. +#line 2966 "ext/sqlite/libsqlite/src/parse.c"
  22691. + break;
  22692. + case 275: /* trigger_cmd_list ::= trigger_cmd SEMI trigger_cmd_list */
  22693. +#line 829 "ext/sqlite/libsqlite/src/parse.y"
  22694. +{
  22695. + yymsp[-2].minor.yy19->pNext = yymsp[0].minor.yy19;
  22696. + yygotominor.yy19 = yymsp[-2].minor.yy19;
  22697. +}
  22698. +#line 2974 "ext/sqlite/libsqlite/src/parse.c"
  22699. + break;
  22700. + case 276: /* trigger_cmd_list ::= */
  22701. +#line 833 "ext/sqlite/libsqlite/src/parse.y"
  22702. +{ yygotominor.yy19 = 0; }
  22703. +#line 2979 "ext/sqlite/libsqlite/src/parse.c"
  22704. + break;
  22705. + case 277: /* trigger_cmd ::= UPDATE orconf nm SET setlist where_opt */
  22706. +#line 839 "ext/sqlite/libsqlite/src/parse.y"
  22707. +{ yygotominor.yy19 = sqliteTriggerUpdateStep(&yymsp[-3].minor.yy0, yymsp[-1].minor.yy322, yymsp[0].minor.yy242, yymsp[-4].minor.yy372); }
  22708. +#line 2984 "ext/sqlite/libsqlite/src/parse.c"
  22709. + break;
  22710. + case 278: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt VALUES LP itemlist RP */
  22711. +#line 844 "ext/sqlite/libsqlite/src/parse.y"
  22712. +{yygotominor.yy19 = sqliteTriggerInsertStep(&yymsp[-5].minor.yy0, yymsp[-4].minor.yy320, yymsp[-1].minor.yy322, 0, yymsp[-7].minor.yy372);}
  22713. +#line 2989 "ext/sqlite/libsqlite/src/parse.c"
  22714. + break;
  22715. + case 279: /* trigger_cmd ::= insert_cmd INTO nm inscollist_opt select */
  22716. +#line 847 "ext/sqlite/libsqlite/src/parse.y"
  22717. +{yygotominor.yy19 = sqliteTriggerInsertStep(&yymsp[-2].minor.yy0, yymsp[-1].minor.yy320, 0, yymsp[0].minor.yy179, yymsp[-4].minor.yy372);}
  22718. +#line 2994 "ext/sqlite/libsqlite/src/parse.c"
  22719. + break;
  22720. + case 280: /* trigger_cmd ::= DELETE FROM nm where_opt */
  22721. +#line 851 "ext/sqlite/libsqlite/src/parse.y"
  22722. +{yygotominor.yy19 = sqliteTriggerDeleteStep(&yymsp[-1].minor.yy0, yymsp[0].minor.yy242);}
  22723. +#line 2999 "ext/sqlite/libsqlite/src/parse.c"
  22724. + break;
  22725. + case 281: /* trigger_cmd ::= select */
  22726. +#line 854 "ext/sqlite/libsqlite/src/parse.y"
  22727. +{yygotominor.yy19 = sqliteTriggerSelectStep(yymsp[0].minor.yy179); }
  22728. +#line 3004 "ext/sqlite/libsqlite/src/parse.c"
  22729. + break;
  22730. + case 282: /* expr ::= RAISE LP IGNORE RP */
  22731. +#line 857 "ext/sqlite/libsqlite/src/parse.y"
  22732. +{
  22733. + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, 0);
  22734. + yygotominor.yy242->iColumn = OE_Ignore;
  22735. + sqliteExprSpan(yygotominor.yy242, &yymsp[-3].minor.yy0, &yymsp[0].minor.yy0);
  22736. +}
  22737. +#line 3013 "ext/sqlite/libsqlite/src/parse.c"
  22738. + break;
  22739. + case 283: /* expr ::= RAISE LP ROLLBACK COMMA nm RP */
  22740. +#line 862 "ext/sqlite/libsqlite/src/parse.y"
  22741. +{
  22742. + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  22743. + yygotominor.yy242->iColumn = OE_Rollback;
  22744. + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  22745. +}
  22746. +#line 3022 "ext/sqlite/libsqlite/src/parse.c"
  22747. + break;
  22748. + case 284: /* expr ::= RAISE LP ABORT COMMA nm RP */
  22749. +#line 867 "ext/sqlite/libsqlite/src/parse.y"
  22750. +{
  22751. + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  22752. + yygotominor.yy242->iColumn = OE_Abort;
  22753. + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  22754. +}
  22755. +#line 3031 "ext/sqlite/libsqlite/src/parse.c"
  22756. + break;
  22757. + case 285: /* expr ::= RAISE LP FAIL COMMA nm RP */
  22758. +#line 872 "ext/sqlite/libsqlite/src/parse.y"
  22759. +{
  22760. + yygotominor.yy242 = sqliteExpr(TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  22761. + yygotominor.yy242->iColumn = OE_Fail;
  22762. + sqliteExprSpan(yygotominor.yy242, &yymsp[-5].minor.yy0, &yymsp[0].minor.yy0);
  22763. +}
  22764. +#line 3040 "ext/sqlite/libsqlite/src/parse.c"
  22765. + break;
  22766. + case 286: /* cmd ::= DROP TRIGGER nm dbnm */
  22767. +#line 879 "ext/sqlite/libsqlite/src/parse.y"
  22768. +{
  22769. + sqliteDropTrigger(pParse,sqliteSrcListAppend(0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0));
  22770. +}
  22771. +#line 3047 "ext/sqlite/libsqlite/src/parse.c"
  22772. + break;
  22773. + case 287: /* cmd ::= ATTACH database_kw_opt ids AS nm key_opt */
  22774. +#line 884 "ext/sqlite/libsqlite/src/parse.y"
  22775. +{
  22776. + sqliteAttach(pParse, &yymsp[-3].minor.yy0, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);
  22777. +}
  22778. +#line 3054 "ext/sqlite/libsqlite/src/parse.c"
  22779. + break;
  22780. + case 289: /* key_opt ::= */
  22781. +#line 889 "ext/sqlite/libsqlite/src/parse.y"
  22782. +{ yygotominor.yy0.z = 0; yygotominor.yy0.n = 0; }
  22783. +#line 3059 "ext/sqlite/libsqlite/src/parse.c"
  22784. + break;
  22785. + case 292: /* cmd ::= DETACH database_kw_opt nm */
  22786. +#line 895 "ext/sqlite/libsqlite/src/parse.y"
  22787. +{
  22788. + sqliteDetach(pParse, &yymsp[0].minor.yy0);
  22789. +}
  22790. +#line 3066 "ext/sqlite/libsqlite/src/parse.c"
  22791. + break;
  22792. + default:
  22793. + /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  22794. + /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  22795. + /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  22796. + /* (3) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==3);
  22797. + /* (4) ecmd ::= SEMI */ yytestcase(yyruleno==4);
  22798. + /* (9) trans_opt ::= */ yytestcase(yyruleno==9);
  22799. + /* (10) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==10);
  22800. + /* (11) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==11);
  22801. + /* (15) cmd ::= create_table create_table_args */ yytestcase(yyruleno==15);
  22802. + /* (21) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==21);
  22803. + /* (22) columnlist ::= column */ yytestcase(yyruleno==22);
  22804. + /* (23) column ::= columnid type carglist */ yytestcase(yyruleno==23);
  22805. + /* (31) type ::= */ yytestcase(yyruleno==31);
  22806. + /* (40) carglist ::= carglist carg */ yytestcase(yyruleno==40);
  22807. + /* (41) carglist ::= */ yytestcase(yyruleno==41);
  22808. + /* (42) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==42);
  22809. + /* (43) carg ::= ccons */ yytestcase(yyruleno==43);
  22810. + /* (52) carg ::= DEFAULT NULL */ yytestcase(yyruleno==52);
  22811. + /* (53) ccons ::= NULL onconf */ yytestcase(yyruleno==53);
  22812. + /* (76) conslist_opt ::= */ yytestcase(yyruleno==76);
  22813. + /* (77) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==77);
  22814. + /* (78) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==78);
  22815. + /* (79) conslist ::= conslist tcons */ yytestcase(yyruleno==79);
  22816. + /* (80) conslist ::= tcons */ yytestcase(yyruleno==80);
  22817. + /* (81) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==81);
  22818. + /* (258) plus_opt ::= PLUS */ yytestcase(yyruleno==258);
  22819. + /* (259) plus_opt ::= */ yytestcase(yyruleno==259);
  22820. + /* (290) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==290);
  22821. + /* (291) database_kw_opt ::= */ yytestcase(yyruleno==291);
  22822. + break;
  22823. + };
  22824. + yygoto = yyRuleInfo[yyruleno].lhs;
  22825. + yysize = yyRuleInfo[yyruleno].nrhs;
  22826. + yypParser->yyidx -= yysize;
  22827. + yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  22828. + if( yyact < YYNSTATE ){
  22829. +#ifdef NDEBUG
  22830. + /* If we are not debugging and the reduce action popped at least
  22831. + ** one element off the stack, then we can push the new element back
  22832. + ** onto the stack here, and skip the stack overflow test in yy_shift().
  22833. + ** That gives a significant speed improvement. */
  22834. + if( yysize ){
  22835. + yypParser->yyidx++;
  22836. + yymsp -= yysize-1;
  22837. + yymsp->stateno = (YYACTIONTYPE)yyact;
  22838. + yymsp->major = (YYCODETYPE)yygoto;
  22839. + yymsp->minor = yygotominor;
  22840. + }else
  22841. +#endif
  22842. + {
  22843. + yy_shift(yypParser,yyact,yygoto,&yygotominor);
  22844. + }
  22845. + }else{
  22846. + assert( yyact == YYNSTATE + YYNRULE + 1 );
  22847. + yy_accept(yypParser);
  22848. + }
  22849. +}
  22850. +
  22851. +/*
  22852. +** The following code executes when the parse fails
  22853. +*/
  22854. +#ifndef YYNOERRORRECOVERY
  22855. +static void yy_parse_failed(
  22856. + yyParser *yypParser /* The parser */
  22857. +){
  22858. + sqliteParserARG_FETCH;
  22859. +#ifndef NDEBUG
  22860. + if( yyTraceFILE ){
  22861. + fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  22862. + }
  22863. +#endif
  22864. + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  22865. + /* Here code is inserted which will be executed whenever the
  22866. + ** parser fails */
  22867. + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  22868. +}
  22869. +#endif /* YYNOERRORRECOVERY */
  22870. +
  22871. +/*
  22872. +** The following code executes when a syntax error first occurs.
  22873. +*/
  22874. +static void yy_syntax_error(
  22875. + yyParser *yypParser, /* The parser */
  22876. + int yymajor, /* The major type of the error token */
  22877. + YYMINORTYPE yyminor /* The minor type of the error token */
  22878. +){
  22879. + sqliteParserARG_FETCH;
  22880. +#define TOKEN (yyminor.yy0)
  22881. +#line 23 "ext/sqlite/libsqlite/src/parse.y"
  22882. +
  22883. + if( pParse->zErrMsg==0 ){
  22884. + if( TOKEN.z[0] ){
  22885. + sqliteErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  22886. + }else{
  22887. + sqliteErrorMsg(pParse, "incomplete SQL statement");
  22888. + }
  22889. + }
  22890. +#line 3166 "ext/sqlite/libsqlite/src/parse.c"
  22891. + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  22892. +}
  22893. +
  22894. +/*
  22895. +** The following is executed when the parser accepts
  22896. +*/
  22897. +static void yy_accept(
  22898. + yyParser *yypParser /* The parser */
  22899. +){
  22900. + sqliteParserARG_FETCH;
  22901. +#ifndef NDEBUG
  22902. + if( yyTraceFILE ){
  22903. + fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  22904. + }
  22905. +#endif
  22906. + while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  22907. + /* Here code is inserted which will be executed whenever the
  22908. + ** parser accepts */
  22909. + sqliteParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  22910. +}
  22911. +
  22912. +/* The main parser program.
  22913. +** The first argument is a pointer to a structure obtained from
  22914. +** "sqliteParserAlloc" which describes the current state of the parser.
  22915. +** The second argument is the major token number. The third is
  22916. +** the minor token. The fourth optional argument is whatever the
  22917. +** user wants (and specified in the grammar) and is available for
  22918. +** use by the action routines.
  22919. +**
  22920. +** Inputs:
  22921. +** <ul>
  22922. +** <li> A pointer to the parser (an opaque structure.)
  22923. +** <li> The major token number.
  22924. +** <li> The minor token number.
  22925. +** <li> An option argument of a grammar-specified type.
  22926. +** </ul>
  22927. +**
  22928. +** Outputs:
  22929. +** None.
  22930. +*/
  22931. +void sqliteParser(
  22932. + void *yyp, /* The parser */
  22933. + int yymajor, /* The major token code number */
  22934. + sqliteParserTOKENTYPE yyminor /* The value for the token */
  22935. + sqliteParserARG_PDECL /* Optional %extra_argument parameter */
  22936. +){
  22937. + YYMINORTYPE yyminorunion;
  22938. + int yyact; /* The parser action. */
  22939. + int yyendofinput; /* True if we are at the end of input */
  22940. +#ifdef YYERRORSYMBOL
  22941. + int yyerrorhit = 0; /* True if yymajor has invoked an error */
  22942. +#endif
  22943. + yyParser *yypParser; /* The parser */
  22944. +
  22945. + /* (re)initialize the parser, if necessary */
  22946. + yypParser = (yyParser*)yyp;
  22947. + if( yypParser->yyidx<0 ){
  22948. +#if YYSTACKDEPTH<=0
  22949. + if( yypParser->yystksz <=0 ){
  22950. + /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  22951. + yyminorunion = yyzerominor;
  22952. + yyStackOverflow(yypParser, &yyminorunion);
  22953. + return;
  22954. + }
  22955. +#endif
  22956. + yypParser->yyidx = 0;
  22957. + yypParser->yyerrcnt = -1;
  22958. + yypParser->yystack[0].stateno = 0;
  22959. + yypParser->yystack[0].major = 0;
  22960. + }
  22961. + yyminorunion.yy0 = yyminor;
  22962. + yyendofinput = (yymajor==0);
  22963. + sqliteParserARG_STORE;
  22964. +
  22965. +#ifndef NDEBUG
  22966. + if( yyTraceFILE ){
  22967. + fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  22968. + }
  22969. +#endif
  22970. +
  22971. + do{
  22972. + yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  22973. + if( yyact<YYNSTATE ){
  22974. + assert( !yyendofinput ); /* Impossible to shift the $ token */
  22975. + yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  22976. + yypParser->yyerrcnt--;
  22977. + yymajor = YYNOCODE;
  22978. + }else if( yyact < YYNSTATE + YYNRULE ){
  22979. + yy_reduce(yypParser,yyact-YYNSTATE);
  22980. + }else{
  22981. + assert( yyact == YY_ERROR_ACTION );
  22982. +#ifdef YYERRORSYMBOL
  22983. + int yymx;
  22984. +#endif
  22985. +#ifndef NDEBUG
  22986. + if( yyTraceFILE ){
  22987. + fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  22988. + }
  22989. +#endif
  22990. +#ifdef YYERRORSYMBOL
  22991. + /* A syntax error has occurred.
  22992. + ** The response to an error depends upon whether or not the
  22993. + ** grammar defines an error token "ERROR".
  22994. + **
  22995. + ** This is what we do if the grammar does define ERROR:
  22996. + **
  22997. + ** * Call the %syntax_error function.
  22998. + **
  22999. + ** * Begin popping the stack until we enter a state where
  23000. + ** it is legal to shift the error symbol, then shift
  23001. + ** the error symbol.
  23002. + **
  23003. + ** * Set the error count to three.
  23004. + **
  23005. + ** * Begin accepting and shifting new tokens. No new error
  23006. + ** processing will occur until three tokens have been
  23007. + ** shifted successfully.
  23008. + **
  23009. + */
  23010. + if( yypParser->yyerrcnt<0 ){
  23011. + yy_syntax_error(yypParser,yymajor,yyminorunion);
  23012. + }
  23013. + yymx = yypParser->yystack[yypParser->yyidx].major;
  23014. + if( yymx==YYERRORSYMBOL || yyerrorhit ){
  23015. +#ifndef NDEBUG
  23016. + if( yyTraceFILE ){
  23017. + fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  23018. + yyTracePrompt,yyTokenName[yymajor]);
  23019. + }
  23020. +#endif
  23021. + yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  23022. + yymajor = YYNOCODE;
  23023. + }else{
  23024. + while(
  23025. + yypParser->yyidx >= 0 &&
  23026. + yymx != YYERRORSYMBOL &&
  23027. + (yyact = yy_find_reduce_action(
  23028. + yypParser->yystack[yypParser->yyidx].stateno,
  23029. + YYERRORSYMBOL)) >= YYNSTATE
  23030. + ){
  23031. + yy_pop_parser_stack(yypParser);
  23032. + }
  23033. + if( yypParser->yyidx < 0 || yymajor==0 ){
  23034. + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  23035. + yy_parse_failed(yypParser);
  23036. + yymajor = YYNOCODE;
  23037. + }else if( yymx!=YYERRORSYMBOL ){
  23038. + YYMINORTYPE u2;
  23039. + u2.YYERRSYMDT = 0;
  23040. + yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  23041. + }
  23042. + }
  23043. + yypParser->yyerrcnt = 3;
  23044. + yyerrorhit = 1;
  23045. +#elif defined(YYNOERRORRECOVERY)
  23046. + /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  23047. + ** do any kind of error recovery. Instead, simply invoke the syntax
  23048. + ** error routine and continue going as if nothing had happened.
  23049. + **
  23050. + ** Applications can set this macro (for example inside %include) if
  23051. + ** they intend to abandon the parse upon the first syntax error seen.
  23052. + */
  23053. + yy_syntax_error(yypParser,yymajor,yyminorunion);
  23054. + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  23055. + yymajor = YYNOCODE;
  23056. +
  23057. +#else /* YYERRORSYMBOL is not defined */
  23058. + /* This is what we do if the grammar does not define ERROR:
  23059. + **
  23060. + ** * Report an error message, and throw away the input token.
  23061. + **
  23062. + ** * If the input token is $, then fail the parse.
  23063. + **
  23064. + ** As before, subsequent error messages are suppressed until
  23065. + ** three input tokens have been successfully shifted.
  23066. + */
  23067. + if( yypParser->yyerrcnt<=0 ){
  23068. + yy_syntax_error(yypParser,yymajor,yyminorunion);
  23069. + }
  23070. + yypParser->yyerrcnt = 3;
  23071. + yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  23072. + if( yyendofinput ){
  23073. + yy_parse_failed(yypParser);
  23074. + }
  23075. + yymajor = YYNOCODE;
  23076. +#endif
  23077. + }
  23078. + }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  23079. + return;
  23080. +}
  23081. --- /dev/null
  23082. +++ b/ext/sqlite/libsqlite/src/parse.h
  23083. @@ -0,0 +1,130 @@
  23084. +#define TK_END_OF_FILE 1
  23085. +#define TK_ILLEGAL 2
  23086. +#define TK_SPACE 3
  23087. +#define TK_UNCLOSED_STRING 4
  23088. +#define TK_COMMENT 5
  23089. +#define TK_FUNCTION 6
  23090. +#define TK_COLUMN 7
  23091. +#define TK_AGG_FUNCTION 8
  23092. +#define TK_SEMI 9
  23093. +#define TK_EXPLAIN 10
  23094. +#define TK_BEGIN 11
  23095. +#define TK_TRANSACTION 12
  23096. +#define TK_COMMIT 13
  23097. +#define TK_END 14
  23098. +#define TK_ROLLBACK 15
  23099. +#define TK_CREATE 16
  23100. +#define TK_TABLE 17
  23101. +#define TK_TEMP 18
  23102. +#define TK_LP 19
  23103. +#define TK_RP 20
  23104. +#define TK_AS 21
  23105. +#define TK_COMMA 22
  23106. +#define TK_ID 23
  23107. +#define TK_ABORT 24
  23108. +#define TK_AFTER 25
  23109. +#define TK_ASC 26
  23110. +#define TK_ATTACH 27
  23111. +#define TK_BEFORE 28
  23112. +#define TK_CASCADE 29
  23113. +#define TK_CLUSTER 30
  23114. +#define TK_CONFLICT 31
  23115. +#define TK_COPY 32
  23116. +#define TK_DATABASE 33
  23117. +#define TK_DEFERRED 34
  23118. +#define TK_DELIMITERS 35
  23119. +#define TK_DESC 36
  23120. +#define TK_DETACH 37
  23121. +#define TK_EACH 38
  23122. +#define TK_FAIL 39
  23123. +#define TK_FOR 40
  23124. +#define TK_GLOB 41
  23125. +#define TK_IGNORE 42
  23126. +#define TK_IMMEDIATE 43
  23127. +#define TK_INITIALLY 44
  23128. +#define TK_INSTEAD 45
  23129. +#define TK_LIKE 46
  23130. +#define TK_MATCH 47
  23131. +#define TK_KEY 48
  23132. +#define TK_OF 49
  23133. +#define TK_OFFSET 50
  23134. +#define TK_PRAGMA 51
  23135. +#define TK_RAISE 52
  23136. +#define TK_REPLACE 53
  23137. +#define TK_RESTRICT 54
  23138. +#define TK_ROW 55
  23139. +#define TK_STATEMENT 56
  23140. +#define TK_TRIGGER 57
  23141. +#define TK_VACUUM 58
  23142. +#define TK_VIEW 59
  23143. +#define TK_OR 60
  23144. +#define TK_AND 61
  23145. +#define TK_NOT 62
  23146. +#define TK_EQ 63
  23147. +#define TK_NE 64
  23148. +#define TK_ISNULL 65
  23149. +#define TK_NOTNULL 66
  23150. +#define TK_IS 67
  23151. +#define TK_BETWEEN 68
  23152. +#define TK_IN 69
  23153. +#define TK_GT 70
  23154. +#define TK_GE 71
  23155. +#define TK_LT 72
  23156. +#define TK_LE 73
  23157. +#define TK_BITAND 74
  23158. +#define TK_BITOR 75
  23159. +#define TK_LSHIFT 76
  23160. +#define TK_RSHIFT 77
  23161. +#define TK_PLUS 78
  23162. +#define TK_MINUS 79
  23163. +#define TK_STAR 80
  23164. +#define TK_SLASH 81
  23165. +#define TK_REM 82
  23166. +#define TK_CONCAT 83
  23167. +#define TK_UMINUS 84
  23168. +#define TK_UPLUS 85
  23169. +#define TK_BITNOT 86
  23170. +#define TK_STRING 87
  23171. +#define TK_JOIN_KW 88
  23172. +#define TK_INTEGER 89
  23173. +#define TK_CONSTRAINT 90
  23174. +#define TK_DEFAULT 91
  23175. +#define TK_FLOAT 92
  23176. +#define TK_NULL 93
  23177. +#define TK_PRIMARY 94
  23178. +#define TK_UNIQUE 95
  23179. +#define TK_CHECK 96
  23180. +#define TK_REFERENCES 97
  23181. +#define TK_COLLATE 98
  23182. +#define TK_ON 99
  23183. +#define TK_DELETE 100
  23184. +#define TK_UPDATE 101
  23185. +#define TK_INSERT 102
  23186. +#define TK_SET 103
  23187. +#define TK_DEFERRABLE 104
  23188. +#define TK_FOREIGN 105
  23189. +#define TK_DROP 106
  23190. +#define TK_UNION 107
  23191. +#define TK_ALL 108
  23192. +#define TK_INTERSECT 109
  23193. +#define TK_EXCEPT 110
  23194. +#define TK_SELECT 111
  23195. +#define TK_DISTINCT 112
  23196. +#define TK_DOT 113
  23197. +#define TK_FROM 114
  23198. +#define TK_JOIN 115
  23199. +#define TK_USING 116
  23200. +#define TK_ORDER 117
  23201. +#define TK_BY 118
  23202. +#define TK_GROUP 119
  23203. +#define TK_HAVING 120
  23204. +#define TK_LIMIT 121
  23205. +#define TK_WHERE 122
  23206. +#define TK_INTO 123
  23207. +#define TK_VALUES 124
  23208. +#define TK_VARIABLE 125
  23209. +#define TK_CASE 126
  23210. +#define TK_WHEN 127
  23211. +#define TK_THEN 128
  23212. +#define TK_ELSE 129
  23213. +#define TK_INDEX 130
  23214. --- /dev/null
  23215. +++ b/ext/sqlite/libsqlite/src/parse.y
  23216. @@ -0,0 +1,897 @@
  23217. +/*
  23218. +** 2001 September 15
  23219. +**
  23220. +** The author disclaims copyright to this source code. In place of
  23221. +** a legal notice, here is a blessing:
  23222. +**
  23223. +** May you do good and not evil.
  23224. +** May you find forgiveness for yourself and forgive others.
  23225. +** May you share freely, never taking more than you give.
  23226. +**
  23227. +*************************************************************************
  23228. +** This file contains SQLite's grammar for SQL. Process this file
  23229. +** using the lemon parser generator to generate C code that runs
  23230. +** the parser. Lemon will also generate a header file containing
  23231. +** numeric codes for all of the tokens.
  23232. +**
  23233. +** @(#) $Id$
  23234. +*/
  23235. +%token_prefix TK_
  23236. +%token_type {Token}
  23237. +%default_type {Token}
  23238. +%extra_argument {Parse *pParse}
  23239. +%syntax_error {
  23240. + if( pParse->zErrMsg==0 ){
  23241. + if( TOKEN.z[0] ){
  23242. + sqliteErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  23243. + }else{
  23244. + sqliteErrorMsg(pParse, "incomplete SQL statement");
  23245. + }
  23246. + }
  23247. +}
  23248. +%name sqliteParser
  23249. +%include {
  23250. +#include "sqliteInt.h"
  23251. +#include "parse.h"
  23252. +
  23253. +/*
  23254. +** An instance of this structure holds information about the
  23255. +** LIMIT clause of a SELECT statement.
  23256. +*/
  23257. +struct LimitVal {
  23258. + int limit; /* The LIMIT value. -1 if there is no limit */
  23259. + int offset; /* The OFFSET. 0 if there is none */
  23260. +};
  23261. +
  23262. +/*
  23263. +** An instance of the following structure describes the event of a
  23264. +** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  23265. +** TK_DELETE, or TK_INSTEAD. If the event is of the form
  23266. +**
  23267. +** UPDATE ON (a,b,c)
  23268. +**
  23269. +** Then the "b" IdList records the list "a,b,c".
  23270. +*/
  23271. +struct TrigEvent { int a; IdList * b; };
  23272. +
  23273. +} // end %include
  23274. +
  23275. +// These are extra tokens used by the lexer but never seen by the
  23276. +// parser. We put them in a rule so that the parser generator will
  23277. +// add them to the parse.h output file.
  23278. +//
  23279. +%nonassoc END_OF_FILE ILLEGAL SPACE UNCLOSED_STRING COMMENT FUNCTION
  23280. + COLUMN AGG_FUNCTION.
  23281. +
  23282. +// Input is a single SQL command
  23283. +input ::= cmdlist.
  23284. +cmdlist ::= cmdlist ecmd.
  23285. +cmdlist ::= ecmd.
  23286. +ecmd ::= explain cmdx SEMI.
  23287. +ecmd ::= SEMI.
  23288. +cmdx ::= cmd. { sqliteExec(pParse); }
  23289. +explain ::= EXPLAIN. { sqliteBeginParse(pParse, 1); }
  23290. +explain ::= . { sqliteBeginParse(pParse, 0); }
  23291. +
  23292. +///////////////////// Begin and end transactions. ////////////////////////////
  23293. +//
  23294. +
  23295. +cmd ::= BEGIN trans_opt onconf(R). {sqliteBeginTransaction(pParse,R);}
  23296. +trans_opt ::= .
  23297. +trans_opt ::= TRANSACTION.
  23298. +trans_opt ::= TRANSACTION nm.
  23299. +cmd ::= COMMIT trans_opt. {sqliteCommitTransaction(pParse);}
  23300. +cmd ::= END trans_opt. {sqliteCommitTransaction(pParse);}
  23301. +cmd ::= ROLLBACK trans_opt. {sqliteRollbackTransaction(pParse);}
  23302. +
  23303. +///////////////////// The CREATE TABLE statement ////////////////////////////
  23304. +//
  23305. +cmd ::= create_table create_table_args.
  23306. +create_table ::= CREATE(X) temp(T) TABLE nm(Y). {
  23307. + sqliteStartTable(pParse,&X,&Y,T,0);
  23308. +}
  23309. +%type temp {int}
  23310. +temp(A) ::= TEMP. {A = 1;}
  23311. +temp(A) ::= . {A = 0;}
  23312. +create_table_args ::= LP columnlist conslist_opt RP(X). {
  23313. + sqliteEndTable(pParse,&X,0);
  23314. +}
  23315. +create_table_args ::= AS select(S). {
  23316. + sqliteEndTable(pParse,0,S);
  23317. + sqliteSelectDelete(S);
  23318. +}
  23319. +columnlist ::= columnlist COMMA column.
  23320. +columnlist ::= column.
  23321. +
  23322. +// About the only information used for a column is the name of the
  23323. +// column. The type is always just "text". But the code will accept
  23324. +// an elaborate typename. Perhaps someday we'll do something with it.
  23325. +//
  23326. +column ::= columnid type carglist.
  23327. +columnid ::= nm(X). {sqliteAddColumn(pParse,&X);}
  23328. +
  23329. +// An IDENTIFIER can be a generic identifier, or one of several
  23330. +// keywords. Any non-standard keyword can also be an identifier.
  23331. +//
  23332. +%type id {Token}
  23333. +id(A) ::= ID(X). {A = X;}
  23334. +
  23335. +// The following directive causes tokens ABORT, AFTER, ASC, etc. to
  23336. +// fallback to ID if they will not parse as their original value.
  23337. +// This obviates the need for the "id" nonterminal.
  23338. +//
  23339. +%fallback ID
  23340. + ABORT AFTER ASC ATTACH BEFORE BEGIN CASCADE CLUSTER CONFLICT
  23341. + COPY DATABASE DEFERRED DELIMITERS DESC DETACH EACH END EXPLAIN FAIL FOR
  23342. + GLOB IGNORE IMMEDIATE INITIALLY INSTEAD LIKE MATCH KEY
  23343. + OF OFFSET PRAGMA RAISE REPLACE RESTRICT ROW STATEMENT
  23344. + TEMP TRIGGER VACUUM VIEW.
  23345. +
  23346. +// Define operator precedence early so that this is the first occurance
  23347. +// of the operator tokens in the grammer. Keeping the operators together
  23348. +// causes them to be assigned integer values that are close together,
  23349. +// which keeps parser tables smaller.
  23350. +//
  23351. +%left OR.
  23352. +%left AND.
  23353. +%right NOT.
  23354. +%left EQ NE ISNULL NOTNULL IS LIKE GLOB BETWEEN IN.
  23355. +%left GT GE LT LE.
  23356. +%left BITAND BITOR LSHIFT RSHIFT.
  23357. +%left PLUS MINUS.
  23358. +%left STAR SLASH REM.
  23359. +%left CONCAT.
  23360. +%right UMINUS UPLUS BITNOT.
  23361. +
  23362. +// And "ids" is an identifer-or-string.
  23363. +//
  23364. +%type ids {Token}
  23365. +ids(A) ::= ID(X). {A = X;}
  23366. +ids(A) ::= STRING(X). {A = X;}
  23367. +
  23368. +// The name of a column or table can be any of the following:
  23369. +//
  23370. +%type nm {Token}
  23371. +nm(A) ::= ID(X). {A = X;}
  23372. +nm(A) ::= STRING(X). {A = X;}
  23373. +nm(A) ::= JOIN_KW(X). {A = X;}
  23374. +
  23375. +type ::= .
  23376. +type ::= typename(X). {sqliteAddColumnType(pParse,&X,&X);}
  23377. +type ::= typename(X) LP signed RP(Y). {sqliteAddColumnType(pParse,&X,&Y);}
  23378. +type ::= typename(X) LP signed COMMA signed RP(Y).
  23379. + {sqliteAddColumnType(pParse,&X,&Y);}
  23380. +%type typename {Token}
  23381. +typename(A) ::= ids(X). {A = X;}
  23382. +typename(A) ::= typename(X) ids. {A = X;}
  23383. +%type signed {int}
  23384. +signed(A) ::= INTEGER(X). { A = atoi(X.z); }
  23385. +signed(A) ::= PLUS INTEGER(X). { A = atoi(X.z); }
  23386. +signed(A) ::= MINUS INTEGER(X). { A = -atoi(X.z); }
  23387. +carglist ::= carglist carg.
  23388. +carglist ::= .
  23389. +carg ::= CONSTRAINT nm ccons.
  23390. +carg ::= ccons.
  23391. +carg ::= DEFAULT STRING(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23392. +carg ::= DEFAULT ID(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23393. +carg ::= DEFAULT INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23394. +carg ::= DEFAULT PLUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23395. +carg ::= DEFAULT MINUS INTEGER(X). {sqliteAddDefaultValue(pParse,&X,1);}
  23396. +carg ::= DEFAULT FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23397. +carg ::= DEFAULT PLUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,0);}
  23398. +carg ::= DEFAULT MINUS FLOAT(X). {sqliteAddDefaultValue(pParse,&X,1);}
  23399. +carg ::= DEFAULT NULL.
  23400. +
  23401. +// In addition to the type name, we also care about the primary key and
  23402. +// UNIQUE constraints.
  23403. +//
  23404. +ccons ::= NULL onconf.
  23405. +ccons ::= NOT NULL onconf(R). {sqliteAddNotNull(pParse, R);}
  23406. +ccons ::= PRIMARY KEY sortorder onconf(R). {sqliteAddPrimaryKey(pParse,0,R);}
  23407. +ccons ::= UNIQUE onconf(R). {sqliteCreateIndex(pParse,0,0,0,R,0,0);}
  23408. +ccons ::= CHECK LP expr RP onconf.
  23409. +ccons ::= REFERENCES nm(T) idxlist_opt(TA) refargs(R).
  23410. + {sqliteCreateForeignKey(pParse,0,&T,TA,R);}
  23411. +ccons ::= defer_subclause(D). {sqliteDeferForeignKey(pParse,D);}
  23412. +ccons ::= COLLATE id(C). {
  23413. + sqliteAddCollateType(pParse, sqliteCollateType(C.z, C.n));
  23414. +}
  23415. +
  23416. +// The next group of rules parses the arguments to a REFERENCES clause
  23417. +// that determine if the referential integrity checking is deferred or
  23418. +// or immediate and which determine what action to take if a ref-integ
  23419. +// check fails.
  23420. +//
  23421. +%type refargs {int}
  23422. +refargs(A) ::= . { A = OE_Restrict * 0x010101; }
  23423. +refargs(A) ::= refargs(X) refarg(Y). { A = (X & Y.mask) | Y.value; }
  23424. +%type refarg {struct {int value; int mask;}}
  23425. +refarg(A) ::= MATCH nm. { A.value = 0; A.mask = 0x000000; }
  23426. +refarg(A) ::= ON DELETE refact(X). { A.value = X; A.mask = 0x0000ff; }
  23427. +refarg(A) ::= ON UPDATE refact(X). { A.value = X<<8; A.mask = 0x00ff00; }
  23428. +refarg(A) ::= ON INSERT refact(X). { A.value = X<<16; A.mask = 0xff0000; }
  23429. +%type refact {int}
  23430. +refact(A) ::= SET NULL. { A = OE_SetNull; }
  23431. +refact(A) ::= SET DEFAULT. { A = OE_SetDflt; }
  23432. +refact(A) ::= CASCADE. { A = OE_Cascade; }
  23433. +refact(A) ::= RESTRICT. { A = OE_Restrict; }
  23434. +%type defer_subclause {int}
  23435. +defer_subclause(A) ::= NOT DEFERRABLE init_deferred_pred_opt(X). {A = X;}
  23436. +defer_subclause(A) ::= DEFERRABLE init_deferred_pred_opt(X). {A = X;}
  23437. +%type init_deferred_pred_opt {int}
  23438. +init_deferred_pred_opt(A) ::= . {A = 0;}
  23439. +init_deferred_pred_opt(A) ::= INITIALLY DEFERRED. {A = 1;}
  23440. +init_deferred_pred_opt(A) ::= INITIALLY IMMEDIATE. {A = 0;}
  23441. +
  23442. +// For the time being, the only constraint we care about is the primary
  23443. +// key and UNIQUE. Both create indices.
  23444. +//
  23445. +conslist_opt ::= .
  23446. +conslist_opt ::= COMMA conslist.
  23447. +conslist ::= conslist COMMA tcons.
  23448. +conslist ::= conslist tcons.
  23449. +conslist ::= tcons.
  23450. +tcons ::= CONSTRAINT nm.
  23451. +tcons ::= PRIMARY KEY LP idxlist(X) RP onconf(R).
  23452. + {sqliteAddPrimaryKey(pParse,X,R);}
  23453. +tcons ::= UNIQUE LP idxlist(X) RP onconf(R).
  23454. + {sqliteCreateIndex(pParse,0,0,X,R,0,0);}
  23455. +tcons ::= CHECK expr onconf.
  23456. +tcons ::= FOREIGN KEY LP idxlist(FA) RP
  23457. + REFERENCES nm(T) idxlist_opt(TA) refargs(R) defer_subclause_opt(D). {
  23458. + sqliteCreateForeignKey(pParse, FA, &T, TA, R);
  23459. + sqliteDeferForeignKey(pParse, D);
  23460. +}
  23461. +%type defer_subclause_opt {int}
  23462. +defer_subclause_opt(A) ::= . {A = 0;}
  23463. +defer_subclause_opt(A) ::= defer_subclause(X). {A = X;}
  23464. +
  23465. +// The following is a non-standard extension that allows us to declare the
  23466. +// default behavior when there is a constraint conflict.
  23467. +//
  23468. +%type onconf {int}
  23469. +%type orconf {int}
  23470. +%type resolvetype {int}
  23471. +onconf(A) ::= . { A = OE_Default; }
  23472. +onconf(A) ::= ON CONFLICT resolvetype(X). { A = X; }
  23473. +orconf(A) ::= . { A = OE_Default; }
  23474. +orconf(A) ::= OR resolvetype(X). { A = X; }
  23475. +resolvetype(A) ::= ROLLBACK. { A = OE_Rollback; }
  23476. +resolvetype(A) ::= ABORT. { A = OE_Abort; }
  23477. +resolvetype(A) ::= FAIL. { A = OE_Fail; }
  23478. +resolvetype(A) ::= IGNORE. { A = OE_Ignore; }
  23479. +resolvetype(A) ::= REPLACE. { A = OE_Replace; }
  23480. +
  23481. +////////////////////////// The DROP TABLE /////////////////////////////////////
  23482. +//
  23483. +cmd ::= DROP TABLE nm(X). {sqliteDropTable(pParse,&X,0);}
  23484. +
  23485. +///////////////////// The CREATE VIEW statement /////////////////////////////
  23486. +//
  23487. +cmd ::= CREATE(X) temp(T) VIEW nm(Y) AS select(S). {
  23488. + sqliteCreateView(pParse, &X, &Y, S, T);
  23489. +}
  23490. +cmd ::= DROP VIEW nm(X). {
  23491. + sqliteDropTable(pParse, &X, 1);
  23492. +}
  23493. +
  23494. +//////////////////////// The SELECT statement /////////////////////////////////
  23495. +//
  23496. +cmd ::= select(X). {
  23497. + sqliteSelect(pParse, X, SRT_Callback, 0, 0, 0, 0);
  23498. + sqliteSelectDelete(X);
  23499. +}
  23500. +
  23501. +%type select {Select*}
  23502. +%destructor select {sqliteSelectDelete($$);}
  23503. +%type oneselect {Select*}
  23504. +%destructor oneselect {sqliteSelectDelete($$);}
  23505. +
  23506. +select(A) ::= oneselect(X). {A = X;}
  23507. +select(A) ::= select(X) multiselect_op(Y) oneselect(Z). {
  23508. + if( Z ){
  23509. + Z->op = Y;
  23510. + Z->pPrior = X;
  23511. + }
  23512. + A = Z;
  23513. +}
  23514. +%type multiselect_op {int}
  23515. +multiselect_op(A) ::= UNION. {A = TK_UNION;}
  23516. +multiselect_op(A) ::= UNION ALL. {A = TK_ALL;}
  23517. +multiselect_op(A) ::= INTERSECT. {A = TK_INTERSECT;}
  23518. +multiselect_op(A) ::= EXCEPT. {A = TK_EXCEPT;}
  23519. +oneselect(A) ::= SELECT distinct(D) selcollist(W) from(X) where_opt(Y)
  23520. + groupby_opt(P) having_opt(Q) orderby_opt(Z) limit_opt(L). {
  23521. + A = sqliteSelectNew(W,X,Y,P,Q,Z,D,L.limit,L.offset);
  23522. +}
  23523. +
  23524. +// The "distinct" nonterminal is true (1) if the DISTINCT keyword is
  23525. +// present and false (0) if it is not.
  23526. +//
  23527. +%type distinct {int}
  23528. +distinct(A) ::= DISTINCT. {A = 1;}
  23529. +distinct(A) ::= ALL. {A = 0;}
  23530. +distinct(A) ::= . {A = 0;}
  23531. +
  23532. +// selcollist is a list of expressions that are to become the return
  23533. +// values of the SELECT statement. The "*" in statements like
  23534. +// "SELECT * FROM ..." is encoded as a special expression with an
  23535. +// opcode of TK_ALL.
  23536. +//
  23537. +%type selcollist {ExprList*}
  23538. +%destructor selcollist {sqliteExprListDelete($$);}
  23539. +%type sclp {ExprList*}
  23540. +%destructor sclp {sqliteExprListDelete($$);}
  23541. +sclp(A) ::= selcollist(X) COMMA. {A = X;}
  23542. +sclp(A) ::= . {A = 0;}
  23543. +selcollist(A) ::= sclp(P) expr(X) as(Y). {
  23544. + A = sqliteExprListAppend(P,X,Y.n?&Y:0);
  23545. +}
  23546. +selcollist(A) ::= sclp(P) STAR. {
  23547. + A = sqliteExprListAppend(P, sqliteExpr(TK_ALL, 0, 0, 0), 0);
  23548. +}
  23549. +selcollist(A) ::= sclp(P) nm(X) DOT STAR. {
  23550. + Expr *pRight = sqliteExpr(TK_ALL, 0, 0, 0);
  23551. + Expr *pLeft = sqliteExpr(TK_ID, 0, 0, &X);
  23552. + A = sqliteExprListAppend(P, sqliteExpr(TK_DOT, pLeft, pRight, 0), 0);
  23553. +}
  23554. +
  23555. +// An option "AS <id>" phrase that can follow one of the expressions that
  23556. +// define the result set, or one of the tables in the FROM clause.
  23557. +//
  23558. +%type as {Token}
  23559. +as(X) ::= AS nm(Y). { X = Y; }
  23560. +as(X) ::= ids(Y). { X = Y; }
  23561. +as(X) ::= . { X.n = 0; }
  23562. +
  23563. +
  23564. +%type seltablist {SrcList*}
  23565. +%destructor seltablist {sqliteSrcListDelete($$);}
  23566. +%type stl_prefix {SrcList*}
  23567. +%destructor stl_prefix {sqliteSrcListDelete($$);}
  23568. +%type from {SrcList*}
  23569. +%destructor from {sqliteSrcListDelete($$);}
  23570. +
  23571. +// A complete FROM clause.
  23572. +//
  23573. +from(A) ::= . {A = sqliteMalloc(sizeof(*A));}
  23574. +from(A) ::= FROM seltablist(X). {A = X;}
  23575. +
  23576. +// "seltablist" is a "Select Table List" - the content of the FROM clause
  23577. +// in a SELECT statement. "stl_prefix" is a prefix of this list.
  23578. +//
  23579. +stl_prefix(A) ::= seltablist(X) joinop(Y). {
  23580. + A = X;
  23581. + if( A && A->nSrc>0 ) A->a[A->nSrc-1].jointype = Y;
  23582. +}
  23583. +stl_prefix(A) ::= . {A = 0;}
  23584. +seltablist(A) ::= stl_prefix(X) nm(Y) dbnm(D) as(Z) on_opt(N) using_opt(U). {
  23585. + A = sqliteSrcListAppend(X,&Y,&D);
  23586. + if( Z.n ) sqliteSrcListAddAlias(A,&Z);
  23587. + if( N ){
  23588. + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
  23589. + else { sqliteExprDelete(N); }
  23590. + }
  23591. + if( U ){
  23592. + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
  23593. + else { sqliteIdListDelete(U); }
  23594. + }
  23595. +}
  23596. +seltablist(A) ::= stl_prefix(X) LP seltablist_paren(S) RP
  23597. + as(Z) on_opt(N) using_opt(U). {
  23598. + A = sqliteSrcListAppend(X,0,0);
  23599. + A->a[A->nSrc-1].pSelect = S;
  23600. + if( Z.n ) sqliteSrcListAddAlias(A,&Z);
  23601. + if( N ){
  23602. + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pOn = N; }
  23603. + else { sqliteExprDelete(N); }
  23604. + }
  23605. + if( U ){
  23606. + if( A && A->nSrc>1 ){ A->a[A->nSrc-2].pUsing = U; }
  23607. + else { sqliteIdListDelete(U); }
  23608. + }
  23609. +}
  23610. +
  23611. +// A seltablist_paren nonterminal represents anything in a FROM that
  23612. +// is contained inside parentheses. This can be either a subquery or
  23613. +// a grouping of table and subqueries.
  23614. +//
  23615. +%type seltablist_paren {Select*}
  23616. +%destructor seltablist_paren {sqliteSelectDelete($$);}
  23617. +seltablist_paren(A) ::= select(S). {A = S;}
  23618. +seltablist_paren(A) ::= seltablist(F). {
  23619. + A = sqliteSelectNew(0,F,0,0,0,0,0,-1,0);
  23620. +}
  23621. +
  23622. +%type dbnm {Token}
  23623. +dbnm(A) ::= . {A.z=0; A.n=0;}
  23624. +dbnm(A) ::= DOT nm(X). {A = X;}
  23625. +
  23626. +%type joinop {int}
  23627. +%type joinop2 {int}
  23628. +joinop(X) ::= COMMA. { X = JT_INNER; }
  23629. +joinop(X) ::= JOIN. { X = JT_INNER; }
  23630. +joinop(X) ::= JOIN_KW(A) JOIN. { X = sqliteJoinType(pParse,&A,0,0); }
  23631. +joinop(X) ::= JOIN_KW(A) nm(B) JOIN. { X = sqliteJoinType(pParse,&A,&B,0); }
  23632. +joinop(X) ::= JOIN_KW(A) nm(B) nm(C) JOIN.
  23633. + { X = sqliteJoinType(pParse,&A,&B,&C); }
  23634. +
  23635. +%type on_opt {Expr*}
  23636. +%destructor on_opt {sqliteExprDelete($$);}
  23637. +on_opt(N) ::= ON expr(E). {N = E;}
  23638. +on_opt(N) ::= . {N = 0;}
  23639. +
  23640. +%type using_opt {IdList*}
  23641. +%destructor using_opt {sqliteIdListDelete($$);}
  23642. +using_opt(U) ::= USING LP idxlist(L) RP. {U = L;}
  23643. +using_opt(U) ::= . {U = 0;}
  23644. +
  23645. +
  23646. +%type orderby_opt {ExprList*}
  23647. +%destructor orderby_opt {sqliteExprListDelete($$);}
  23648. +%type sortlist {ExprList*}
  23649. +%destructor sortlist {sqliteExprListDelete($$);}
  23650. +%type sortitem {Expr*}
  23651. +%destructor sortitem {sqliteExprDelete($$);}
  23652. +
  23653. +orderby_opt(A) ::= . {A = 0;}
  23654. +orderby_opt(A) ::= ORDER BY sortlist(X). {A = X;}
  23655. +sortlist(A) ::= sortlist(X) COMMA sortitem(Y) collate(C) sortorder(Z). {
  23656. + A = sqliteExprListAppend(X,Y,0);
  23657. + if( A ) A->a[A->nExpr-1].sortOrder = C+Z;
  23658. +}
  23659. +sortlist(A) ::= sortitem(Y) collate(C) sortorder(Z). {
  23660. + A = sqliteExprListAppend(0,Y,0);
  23661. + if( A ) A->a[0].sortOrder = C+Z;
  23662. +}
  23663. +sortitem(A) ::= expr(X). {A = X;}
  23664. +
  23665. +%type sortorder {int}
  23666. +%type collate {int}
  23667. +
  23668. +sortorder(A) ::= ASC. {A = SQLITE_SO_ASC;}
  23669. +sortorder(A) ::= DESC. {A = SQLITE_SO_DESC;}
  23670. +sortorder(A) ::= . {A = SQLITE_SO_ASC;}
  23671. +collate(C) ::= . {C = SQLITE_SO_UNK;}
  23672. +collate(C) ::= COLLATE id(X). {C = sqliteCollateType(X.z, X.n);}
  23673. +
  23674. +%type groupby_opt {ExprList*}
  23675. +%destructor groupby_opt {sqliteExprListDelete($$);}
  23676. +groupby_opt(A) ::= . {A = 0;}
  23677. +groupby_opt(A) ::= GROUP BY exprlist(X). {A = X;}
  23678. +
  23679. +%type having_opt {Expr*}
  23680. +%destructor having_opt {sqliteExprDelete($$);}
  23681. +having_opt(A) ::= . {A = 0;}
  23682. +having_opt(A) ::= HAVING expr(X). {A = X;}
  23683. +
  23684. +%type limit_opt {struct LimitVal}
  23685. +limit_opt(A) ::= . {A.limit = -1; A.offset = 0;}
  23686. +limit_opt(A) ::= LIMIT signed(X). {A.limit = X; A.offset = 0;}
  23687. +limit_opt(A) ::= LIMIT signed(X) OFFSET signed(Y).
  23688. + {A.limit = X; A.offset = Y;}
  23689. +limit_opt(A) ::= LIMIT signed(X) COMMA signed(Y).
  23690. + {A.limit = Y; A.offset = X;}
  23691. +
  23692. +/////////////////////////// The DELETE statement /////////////////////////////
  23693. +//
  23694. +cmd ::= DELETE FROM nm(X) dbnm(D) where_opt(Y). {
  23695. + sqliteDeleteFrom(pParse, sqliteSrcListAppend(0,&X,&D), Y);
  23696. +}
  23697. +
  23698. +%type where_opt {Expr*}
  23699. +%destructor where_opt {sqliteExprDelete($$);}
  23700. +
  23701. +where_opt(A) ::= . {A = 0;}
  23702. +where_opt(A) ::= WHERE expr(X). {A = X;}
  23703. +
  23704. +%type setlist {ExprList*}
  23705. +%destructor setlist {sqliteExprListDelete($$);}
  23706. +
  23707. +////////////////////////// The UPDATE command ////////////////////////////////
  23708. +//
  23709. +cmd ::= UPDATE orconf(R) nm(X) dbnm(D) SET setlist(Y) where_opt(Z).
  23710. + {sqliteUpdate(pParse,sqliteSrcListAppend(0,&X,&D),Y,Z,R);}
  23711. +
  23712. +setlist(A) ::= setlist(Z) COMMA nm(X) EQ expr(Y).
  23713. + {A = sqliteExprListAppend(Z,Y,&X);}
  23714. +setlist(A) ::= nm(X) EQ expr(Y). {A = sqliteExprListAppend(0,Y,&X);}
  23715. +
  23716. +////////////////////////// The INSERT command /////////////////////////////////
  23717. +//
  23718. +cmd ::= insert_cmd(R) INTO nm(X) dbnm(D) inscollist_opt(F)
  23719. + VALUES LP itemlist(Y) RP.
  23720. + {sqliteInsert(pParse, sqliteSrcListAppend(0,&X,&D), Y, 0, F, R);}
  23721. +cmd ::= insert_cmd(R) INTO nm(X) dbnm(D) inscollist_opt(F) select(S).
  23722. + {sqliteInsert(pParse, sqliteSrcListAppend(0,&X,&D), 0, S, F, R);}
  23723. +
  23724. +%type insert_cmd {int}
  23725. +insert_cmd(A) ::= INSERT orconf(R). {A = R;}
  23726. +insert_cmd(A) ::= REPLACE. {A = OE_Replace;}
  23727. +
  23728. +
  23729. +%type itemlist {ExprList*}
  23730. +%destructor itemlist {sqliteExprListDelete($$);}
  23731. +
  23732. +itemlist(A) ::= itemlist(X) COMMA expr(Y). {A = sqliteExprListAppend(X,Y,0);}
  23733. +itemlist(A) ::= expr(X). {A = sqliteExprListAppend(0,X,0);}
  23734. +
  23735. +%type inscollist_opt {IdList*}
  23736. +%destructor inscollist_opt {sqliteIdListDelete($$);}
  23737. +%type inscollist {IdList*}
  23738. +%destructor inscollist {sqliteIdListDelete($$);}
  23739. +
  23740. +inscollist_opt(A) ::= . {A = 0;}
  23741. +inscollist_opt(A) ::= LP inscollist(X) RP. {A = X;}
  23742. +inscollist(A) ::= inscollist(X) COMMA nm(Y). {A = sqliteIdListAppend(X,&Y);}
  23743. +inscollist(A) ::= nm(Y). {A = sqliteIdListAppend(0,&Y);}
  23744. +
  23745. +/////////////////////////// Expression Processing /////////////////////////////
  23746. +//
  23747. +
  23748. +%type expr {Expr*}
  23749. +%destructor expr {sqliteExprDelete($$);}
  23750. +
  23751. +expr(A) ::= LP(B) expr(X) RP(E). {A = X; sqliteExprSpan(A,&B,&E); }
  23752. +expr(A) ::= NULL(X). {A = sqliteExpr(TK_NULL, 0, 0, &X);}
  23753. +expr(A) ::= ID(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
  23754. +expr(A) ::= JOIN_KW(X). {A = sqliteExpr(TK_ID, 0, 0, &X);}
  23755. +expr(A) ::= nm(X) DOT nm(Y). {
  23756. + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
  23757. + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
  23758. + A = sqliteExpr(TK_DOT, temp1, temp2, 0);
  23759. +}
  23760. +expr(A) ::= nm(X) DOT nm(Y) DOT nm(Z). {
  23761. + Expr *temp1 = sqliteExpr(TK_ID, 0, 0, &X);
  23762. + Expr *temp2 = sqliteExpr(TK_ID, 0, 0, &Y);
  23763. + Expr *temp3 = sqliteExpr(TK_ID, 0, 0, &Z);
  23764. + Expr *temp4 = sqliteExpr(TK_DOT, temp2, temp3, 0);
  23765. + A = sqliteExpr(TK_DOT, temp1, temp4, 0);
  23766. +}
  23767. +expr(A) ::= INTEGER(X). {A = sqliteExpr(TK_INTEGER, 0, 0, &X);}
  23768. +expr(A) ::= FLOAT(X). {A = sqliteExpr(TK_FLOAT, 0, 0, &X);}
  23769. +expr(A) ::= STRING(X). {A = sqliteExpr(TK_STRING, 0, 0, &X);}
  23770. +expr(A) ::= VARIABLE(X). {
  23771. + A = sqliteExpr(TK_VARIABLE, 0, 0, &X);
  23772. + if( A ) A->iTable = ++pParse->nVar;
  23773. +}
  23774. +expr(A) ::= ID(X) LP exprlist(Y) RP(E). {
  23775. + A = sqliteExprFunction(Y, &X);
  23776. + sqliteExprSpan(A,&X,&E);
  23777. +}
  23778. +expr(A) ::= ID(X) LP STAR RP(E). {
  23779. + A = sqliteExprFunction(0, &X);
  23780. + sqliteExprSpan(A,&X,&E);
  23781. +}
  23782. +expr(A) ::= expr(X) AND expr(Y). {A = sqliteExpr(TK_AND, X, Y, 0);}
  23783. +expr(A) ::= expr(X) OR expr(Y). {A = sqliteExpr(TK_OR, X, Y, 0);}
  23784. +expr(A) ::= expr(X) LT expr(Y). {A = sqliteExpr(TK_LT, X, Y, 0);}
  23785. +expr(A) ::= expr(X) GT expr(Y). {A = sqliteExpr(TK_GT, X, Y, 0);}
  23786. +expr(A) ::= expr(X) LE expr(Y). {A = sqliteExpr(TK_LE, X, Y, 0);}
  23787. +expr(A) ::= expr(X) GE expr(Y). {A = sqliteExpr(TK_GE, X, Y, 0);}
  23788. +expr(A) ::= expr(X) NE expr(Y). {A = sqliteExpr(TK_NE, X, Y, 0);}
  23789. +expr(A) ::= expr(X) EQ expr(Y). {A = sqliteExpr(TK_EQ, X, Y, 0);}
  23790. +expr(A) ::= expr(X) BITAND expr(Y). {A = sqliteExpr(TK_BITAND, X, Y, 0);}
  23791. +expr(A) ::= expr(X) BITOR expr(Y). {A = sqliteExpr(TK_BITOR, X, Y, 0);}
  23792. +expr(A) ::= expr(X) LSHIFT expr(Y). {A = sqliteExpr(TK_LSHIFT, X, Y, 0);}
  23793. +expr(A) ::= expr(X) RSHIFT expr(Y). {A = sqliteExpr(TK_RSHIFT, X, Y, 0);}
  23794. +expr(A) ::= expr(X) likeop(OP) expr(Y). [LIKE] {
  23795. + ExprList *pList = sqliteExprListAppend(0, Y, 0);
  23796. + pList = sqliteExprListAppend(pList, X, 0);
  23797. + A = sqliteExprFunction(pList, 0);
  23798. + if( A ) A->op = OP;
  23799. + sqliteExprSpan(A, &X->span, &Y->span);
  23800. +}
  23801. +expr(A) ::= expr(X) NOT likeop(OP) expr(Y). [LIKE] {
  23802. + ExprList *pList = sqliteExprListAppend(0, Y, 0);
  23803. + pList = sqliteExprListAppend(pList, X, 0);
  23804. + A = sqliteExprFunction(pList, 0);
  23805. + if( A ) A->op = OP;
  23806. + A = sqliteExpr(TK_NOT, A, 0, 0);
  23807. + sqliteExprSpan(A,&X->span,&Y->span);
  23808. +}
  23809. +%type likeop {int}
  23810. +likeop(A) ::= LIKE. {A = TK_LIKE;}
  23811. +likeop(A) ::= GLOB. {A = TK_GLOB;}
  23812. +expr(A) ::= expr(X) PLUS expr(Y). {A = sqliteExpr(TK_PLUS, X, Y, 0);}
  23813. +expr(A) ::= expr(X) MINUS expr(Y). {A = sqliteExpr(TK_MINUS, X, Y, 0);}
  23814. +expr(A) ::= expr(X) STAR expr(Y). {A = sqliteExpr(TK_STAR, X, Y, 0);}
  23815. +expr(A) ::= expr(X) SLASH expr(Y). {A = sqliteExpr(TK_SLASH, X, Y, 0);}
  23816. +expr(A) ::= expr(X) REM expr(Y). {A = sqliteExpr(TK_REM, X, Y, 0);}
  23817. +expr(A) ::= expr(X) CONCAT expr(Y). {A = sqliteExpr(TK_CONCAT, X, Y, 0);}
  23818. +expr(A) ::= expr(X) ISNULL(E). {
  23819. + A = sqliteExpr(TK_ISNULL, X, 0, 0);
  23820. + sqliteExprSpan(A,&X->span,&E);
  23821. +}
  23822. +expr(A) ::= expr(X) IS NULL(E). {
  23823. + A = sqliteExpr(TK_ISNULL, X, 0, 0);
  23824. + sqliteExprSpan(A,&X->span,&E);
  23825. +}
  23826. +expr(A) ::= expr(X) NOTNULL(E). {
  23827. + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
  23828. + sqliteExprSpan(A,&X->span,&E);
  23829. +}
  23830. +expr(A) ::= expr(X) NOT NULL(E). {
  23831. + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
  23832. + sqliteExprSpan(A,&X->span,&E);
  23833. +}
  23834. +expr(A) ::= expr(X) IS NOT NULL(E). {
  23835. + A = sqliteExpr(TK_NOTNULL, X, 0, 0);
  23836. + sqliteExprSpan(A,&X->span,&E);
  23837. +}
  23838. +expr(A) ::= NOT(B) expr(X). {
  23839. + A = sqliteExpr(TK_NOT, X, 0, 0);
  23840. + sqliteExprSpan(A,&B,&X->span);
  23841. +}
  23842. +expr(A) ::= BITNOT(B) expr(X). {
  23843. + A = sqliteExpr(TK_BITNOT, X, 0, 0);
  23844. + sqliteExprSpan(A,&B,&X->span);
  23845. +}
  23846. +expr(A) ::= MINUS(B) expr(X). [UMINUS] {
  23847. + A = sqliteExpr(TK_UMINUS, X, 0, 0);
  23848. + sqliteExprSpan(A,&B,&X->span);
  23849. +}
  23850. +expr(A) ::= PLUS(B) expr(X). [UPLUS] {
  23851. + A = sqliteExpr(TK_UPLUS, X, 0, 0);
  23852. + sqliteExprSpan(A,&B,&X->span);
  23853. +}
  23854. +expr(A) ::= LP(B) select(X) RP(E). {
  23855. + A = sqliteExpr(TK_SELECT, 0, 0, 0);
  23856. + if( A ) A->pSelect = X;
  23857. + sqliteExprSpan(A,&B,&E);
  23858. +}
  23859. +expr(A) ::= expr(W) BETWEEN expr(X) AND expr(Y). {
  23860. + ExprList *pList = sqliteExprListAppend(0, X, 0);
  23861. + pList = sqliteExprListAppend(pList, Y, 0);
  23862. + A = sqliteExpr(TK_BETWEEN, W, 0, 0);
  23863. + if( A ) A->pList = pList;
  23864. + sqliteExprSpan(A,&W->span,&Y->span);
  23865. +}
  23866. +expr(A) ::= expr(W) NOT BETWEEN expr(X) AND expr(Y). {
  23867. + ExprList *pList = sqliteExprListAppend(0, X, 0);
  23868. + pList = sqliteExprListAppend(pList, Y, 0);
  23869. + A = sqliteExpr(TK_BETWEEN, W, 0, 0);
  23870. + if( A ) A->pList = pList;
  23871. + A = sqliteExpr(TK_NOT, A, 0, 0);
  23872. + sqliteExprSpan(A,&W->span,&Y->span);
  23873. +}
  23874. +expr(A) ::= expr(X) IN LP exprlist(Y) RP(E). {
  23875. + A = sqliteExpr(TK_IN, X, 0, 0);
  23876. + if( A ) A->pList = Y;
  23877. + sqliteExprSpan(A,&X->span,&E);
  23878. +}
  23879. +expr(A) ::= expr(X) IN LP select(Y) RP(E). {
  23880. + A = sqliteExpr(TK_IN, X, 0, 0);
  23881. + if( A ) A->pSelect = Y;
  23882. + sqliteExprSpan(A,&X->span,&E);
  23883. +}
  23884. +expr(A) ::= expr(X) NOT IN LP exprlist(Y) RP(E). {
  23885. + A = sqliteExpr(TK_IN, X, 0, 0);
  23886. + if( A ) A->pList = Y;
  23887. + A = sqliteExpr(TK_NOT, A, 0, 0);
  23888. + sqliteExprSpan(A,&X->span,&E);
  23889. +}
  23890. +expr(A) ::= expr(X) NOT IN LP select(Y) RP(E). {
  23891. + A = sqliteExpr(TK_IN, X, 0, 0);
  23892. + if( A ) A->pSelect = Y;
  23893. + A = sqliteExpr(TK_NOT, A, 0, 0);
  23894. + sqliteExprSpan(A,&X->span,&E);
  23895. +}
  23896. +expr(A) ::= expr(X) IN nm(Y) dbnm(D). {
  23897. + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
  23898. + A = sqliteExpr(TK_IN, X, 0, 0);
  23899. + if( A ) A->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
  23900. + sqliteExprSpan(A,&X->span,D.z?&D:&Y);
  23901. +}
  23902. +expr(A) ::= expr(X) NOT IN nm(Y) dbnm(D). {
  23903. + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
  23904. + A = sqliteExpr(TK_IN, X, 0, 0);
  23905. + if( A ) A->pSelect = sqliteSelectNew(0,pSrc,0,0,0,0,0,-1,0);
  23906. + A = sqliteExpr(TK_NOT, A, 0, 0);
  23907. + sqliteExprSpan(A,&X->span,D.z?&D:&Y);
  23908. +}
  23909. +
  23910. +
  23911. +/* CASE expressions */
  23912. +expr(A) ::= CASE(C) case_operand(X) case_exprlist(Y) case_else(Z) END(E). {
  23913. + A = sqliteExpr(TK_CASE, X, Z, 0);
  23914. + if( A ) A->pList = Y;
  23915. + sqliteExprSpan(A, &C, &E);
  23916. +}
  23917. +%type case_exprlist {ExprList*}
  23918. +%destructor case_exprlist {sqliteExprListDelete($$);}
  23919. +case_exprlist(A) ::= case_exprlist(X) WHEN expr(Y) THEN expr(Z). {
  23920. + A = sqliteExprListAppend(X, Y, 0);
  23921. + A = sqliteExprListAppend(A, Z, 0);
  23922. +}
  23923. +case_exprlist(A) ::= WHEN expr(Y) THEN expr(Z). {
  23924. + A = sqliteExprListAppend(0, Y, 0);
  23925. + A = sqliteExprListAppend(A, Z, 0);
  23926. +}
  23927. +%type case_else {Expr*}
  23928. +case_else(A) ::= ELSE expr(X). {A = X;}
  23929. +case_else(A) ::= . {A = 0;}
  23930. +%type case_operand {Expr*}
  23931. +case_operand(A) ::= expr(X). {A = X;}
  23932. +case_operand(A) ::= . {A = 0;}
  23933. +
  23934. +%type exprlist {ExprList*}
  23935. +%destructor exprlist {sqliteExprListDelete($$);}
  23936. +%type expritem {Expr*}
  23937. +%destructor expritem {sqliteExprDelete($$);}
  23938. +
  23939. +exprlist(A) ::= exprlist(X) COMMA expritem(Y).
  23940. + {A = sqliteExprListAppend(X,Y,0);}
  23941. +exprlist(A) ::= expritem(X). {A = sqliteExprListAppend(0,X,0);}
  23942. +expritem(A) ::= expr(X). {A = X;}
  23943. +expritem(A) ::= . {A = 0;}
  23944. +
  23945. +///////////////////////////// The CREATE INDEX command ///////////////////////
  23946. +//
  23947. +cmd ::= CREATE(S) uniqueflag(U) INDEX nm(X)
  23948. + ON nm(Y) dbnm(D) LP idxlist(Z) RP(E) onconf(R). {
  23949. + SrcList *pSrc = sqliteSrcListAppend(0, &Y, &D);
  23950. + if( U!=OE_None ) U = R;
  23951. + if( U==OE_Default) U = OE_Abort;
  23952. + sqliteCreateIndex(pParse, &X, pSrc, Z, U, &S, &E);
  23953. +}
  23954. +
  23955. +%type uniqueflag {int}
  23956. +uniqueflag(A) ::= UNIQUE. { A = OE_Abort; }
  23957. +uniqueflag(A) ::= . { A = OE_None; }
  23958. +
  23959. +%type idxlist {IdList*}
  23960. +%destructor idxlist {sqliteIdListDelete($$);}
  23961. +%type idxlist_opt {IdList*}
  23962. +%destructor idxlist_opt {sqliteIdListDelete($$);}
  23963. +%type idxitem {Token}
  23964. +
  23965. +idxlist_opt(A) ::= . {A = 0;}
  23966. +idxlist_opt(A) ::= LP idxlist(X) RP. {A = X;}
  23967. +idxlist(A) ::= idxlist(X) COMMA idxitem(Y). {A = sqliteIdListAppend(X,&Y);}
  23968. +idxlist(A) ::= idxitem(Y). {A = sqliteIdListAppend(0,&Y);}
  23969. +idxitem(A) ::= nm(X) sortorder. {A = X;}
  23970. +
  23971. +///////////////////////////// The DROP INDEX command /////////////////////////
  23972. +//
  23973. +
  23974. +cmd ::= DROP INDEX nm(X) dbnm(Y). {
  23975. + sqliteDropIndex(pParse, sqliteSrcListAppend(0,&X,&Y));
  23976. +}
  23977. +
  23978. +
  23979. +///////////////////////////// The COPY command ///////////////////////////////
  23980. +//
  23981. +cmd ::= COPY orconf(R) nm(X) dbnm(D) FROM nm(Y) USING DELIMITERS STRING(Z).
  23982. + {sqliteCopy(pParse,sqliteSrcListAppend(0,&X,&D),&Y,&Z,R);}
  23983. +cmd ::= COPY orconf(R) nm(X) dbnm(D) FROM nm(Y).
  23984. + {sqliteCopy(pParse,sqliteSrcListAppend(0,&X,&D),&Y,0,R);}
  23985. +
  23986. +///////////////////////////// The VACUUM command /////////////////////////////
  23987. +//
  23988. +cmd ::= VACUUM. {sqliteVacuum(pParse,0);}
  23989. +cmd ::= VACUUM nm(X). {sqliteVacuum(pParse,&X);}
  23990. +
  23991. +///////////////////////////// The PRAGMA command /////////////////////////////
  23992. +//
  23993. +cmd ::= PRAGMA ids(X) EQ nm(Y). {sqlitePragma(pParse,&X,&Y,0);}
  23994. +cmd ::= PRAGMA ids(X) EQ ON(Y). {sqlitePragma(pParse,&X,&Y,0);}
  23995. +cmd ::= PRAGMA ids(X) EQ plus_num(Y). {sqlitePragma(pParse,&X,&Y,0);}
  23996. +cmd ::= PRAGMA ids(X) EQ minus_num(Y). {sqlitePragma(pParse,&X,&Y,1);}
  23997. +cmd ::= PRAGMA ids(X) LP nm(Y) RP. {sqlitePragma(pParse,&X,&Y,0);}
  23998. +cmd ::= PRAGMA ids(X). {sqlitePragma(pParse,&X,&X,0);}
  23999. +plus_num(A) ::= plus_opt number(X). {A = X;}
  24000. +minus_num(A) ::= MINUS number(X). {A = X;}
  24001. +number(A) ::= INTEGER(X). {A = X;}
  24002. +number(A) ::= FLOAT(X). {A = X;}
  24003. +plus_opt ::= PLUS.
  24004. +plus_opt ::= .
  24005. +
  24006. +//////////////////////////// The CREATE TRIGGER command /////////////////////
  24007. +
  24008. +cmd ::= CREATE(A) trigger_decl BEGIN trigger_cmd_list(S) END(Z). {
  24009. + Token all;
  24010. + all.z = A.z;
  24011. + all.n = (Z.z - A.z) + Z.n;
  24012. + sqliteFinishTrigger(pParse, S, &all);
  24013. +}
  24014. +
  24015. +trigger_decl ::= temp(T) TRIGGER nm(B) trigger_time(C) trigger_event(D)
  24016. + ON nm(E) dbnm(DB) foreach_clause(F) when_clause(G). {
  24017. + SrcList *pTab = sqliteSrcListAppend(0, &E, &DB);
  24018. + sqliteBeginTrigger(pParse, &B, C, D.a, D.b, pTab, F, G, T);
  24019. +}
  24020. +
  24021. +%type trigger_time {int}
  24022. +trigger_time(A) ::= BEFORE. { A = TK_BEFORE; }
  24023. +trigger_time(A) ::= AFTER. { A = TK_AFTER; }
  24024. +trigger_time(A) ::= INSTEAD OF. { A = TK_INSTEAD;}
  24025. +trigger_time(A) ::= . { A = TK_BEFORE; }
  24026. +
  24027. +%type trigger_event {struct TrigEvent}
  24028. +%destructor trigger_event {sqliteIdListDelete($$.b);}
  24029. +trigger_event(A) ::= DELETE. { A.a = TK_DELETE; A.b = 0; }
  24030. +trigger_event(A) ::= INSERT. { A.a = TK_INSERT; A.b = 0; }
  24031. +trigger_event(A) ::= UPDATE. { A.a = TK_UPDATE; A.b = 0;}
  24032. +trigger_event(A) ::= UPDATE OF inscollist(X). {A.a = TK_UPDATE; A.b = X; }
  24033. +
  24034. +%type foreach_clause {int}
  24035. +foreach_clause(A) ::= . { A = TK_ROW; }
  24036. +foreach_clause(A) ::= FOR EACH ROW. { A = TK_ROW; }
  24037. +foreach_clause(A) ::= FOR EACH STATEMENT. { A = TK_STATEMENT; }
  24038. +
  24039. +%type when_clause {Expr *}
  24040. +when_clause(A) ::= . { A = 0; }
  24041. +when_clause(A) ::= WHEN expr(X). { A = X; }
  24042. +
  24043. +%type trigger_cmd_list {TriggerStep *}
  24044. +%destructor trigger_cmd_list {sqliteDeleteTriggerStep($$);}
  24045. +trigger_cmd_list(A) ::= trigger_cmd(X) SEMI trigger_cmd_list(Y). {
  24046. + X->pNext = Y;
  24047. + A = X;
  24048. +}
  24049. +trigger_cmd_list(A) ::= . { A = 0; }
  24050. +
  24051. +%type trigger_cmd {TriggerStep *}
  24052. +%destructor trigger_cmd {sqliteDeleteTriggerStep($$);}
  24053. +// UPDATE
  24054. +trigger_cmd(A) ::= UPDATE orconf(R) nm(X) SET setlist(Y) where_opt(Z).
  24055. + { A = sqliteTriggerUpdateStep(&X, Y, Z, R); }
  24056. +
  24057. +// INSERT
  24058. +trigger_cmd(A) ::= insert_cmd(R) INTO nm(X) inscollist_opt(F)
  24059. + VALUES LP itemlist(Y) RP.
  24060. +{A = sqliteTriggerInsertStep(&X, F, Y, 0, R);}
  24061. +
  24062. +trigger_cmd(A) ::= insert_cmd(R) INTO nm(X) inscollist_opt(F) select(S).
  24063. + {A = sqliteTriggerInsertStep(&X, F, 0, S, R);}
  24064. +
  24065. +// DELETE
  24066. +trigger_cmd(A) ::= DELETE FROM nm(X) where_opt(Y).
  24067. + {A = sqliteTriggerDeleteStep(&X, Y);}
  24068. +
  24069. +// SELECT
  24070. +trigger_cmd(A) ::= select(X). {A = sqliteTriggerSelectStep(X); }
  24071. +
  24072. +// The special RAISE expression that may occur in trigger programs
  24073. +expr(A) ::= RAISE(X) LP IGNORE RP(Y). {
  24074. + A = sqliteExpr(TK_RAISE, 0, 0, 0);
  24075. + A->iColumn = OE_Ignore;
  24076. + sqliteExprSpan(A, &X, &Y);
  24077. +}
  24078. +expr(A) ::= RAISE(X) LP ROLLBACK COMMA nm(Z) RP(Y). {
  24079. + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
  24080. + A->iColumn = OE_Rollback;
  24081. + sqliteExprSpan(A, &X, &Y);
  24082. +}
  24083. +expr(A) ::= RAISE(X) LP ABORT COMMA nm(Z) RP(Y). {
  24084. + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
  24085. + A->iColumn = OE_Abort;
  24086. + sqliteExprSpan(A, &X, &Y);
  24087. +}
  24088. +expr(A) ::= RAISE(X) LP FAIL COMMA nm(Z) RP(Y). {
  24089. + A = sqliteExpr(TK_RAISE, 0, 0, &Z);
  24090. + A->iColumn = OE_Fail;
  24091. + sqliteExprSpan(A, &X, &Y);
  24092. +}
  24093. +
  24094. +//////////////////////// DROP TRIGGER statement //////////////////////////////
  24095. +cmd ::= DROP TRIGGER nm(X) dbnm(D). {
  24096. + sqliteDropTrigger(pParse,sqliteSrcListAppend(0,&X,&D));
  24097. +}
  24098. +
  24099. +//////////////////////// ATTACH DATABASE file AS name /////////////////////////
  24100. +cmd ::= ATTACH database_kw_opt ids(F) AS nm(D) key_opt(K). {
  24101. + sqliteAttach(pParse, &F, &D, &K);
  24102. +}
  24103. +%type key_opt {Token}
  24104. +key_opt(A) ::= USING ids(X). { A = X; }
  24105. +key_opt(A) ::= . { A.z = 0; A.n = 0; }
  24106. +
  24107. +database_kw_opt ::= DATABASE.
  24108. +database_kw_opt ::= .
  24109. +
  24110. +//////////////////////// DETACH DATABASE name /////////////////////////////////
  24111. +cmd ::= DETACH database_kw_opt nm(D). {
  24112. + sqliteDetach(pParse, &D);
  24113. +}
  24114. --- /dev/null
  24115. +++ b/ext/sqlite/libsqlite/src/pragma.c
  24116. @@ -0,0 +1,712 @@
  24117. +/*
  24118. +** 2003 April 6
  24119. +**
  24120. +** The author disclaims copyright to this source code. In place of
  24121. +** a legal notice, here is a blessing:
  24122. +**
  24123. +** May you do good and not evil.
  24124. +** May you find forgiveness for yourself and forgive others.
  24125. +** May you share freely, never taking more than you give.
  24126. +**
  24127. +*************************************************************************
  24128. +** This file contains code used to implement the PRAGMA command.
  24129. +**
  24130. +** $Id$
  24131. +*/
  24132. +#include "sqliteInt.h"
  24133. +#include <ctype.h>
  24134. +
  24135. +/*
  24136. +** Interpret the given string as a boolean value.
  24137. +*/
  24138. +static int getBoolean(const char *z){
  24139. + static char *azTrue[] = { "yes", "on", "true" };
  24140. + int i;
  24141. + if( z[0]==0 ) return 0;
  24142. + if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
  24143. + return atoi(z);
  24144. + }
  24145. + for(i=0; i<sizeof(azTrue)/sizeof(azTrue[0]); i++){
  24146. + if( sqliteStrICmp(z,azTrue[i])==0 ) return 1;
  24147. + }
  24148. + return 0;
  24149. +}
  24150. +
  24151. +/*
  24152. +** Interpret the given string as a safety level. Return 0 for OFF,
  24153. +** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  24154. +** unrecognized string argument.
  24155. +**
  24156. +** Note that the values returned are one less that the values that
  24157. +** should be passed into sqliteBtreeSetSafetyLevel(). The is done
  24158. +** to support legacy SQL code. The safety level used to be boolean
  24159. +** and older scripts may have used numbers 0 for OFF and 1 for ON.
  24160. +*/
  24161. +static int getSafetyLevel(char *z){
  24162. + static const struct {
  24163. + const char *zWord;
  24164. + int val;
  24165. + } aKey[] = {
  24166. + { "no", 0 },
  24167. + { "off", 0 },
  24168. + { "false", 0 },
  24169. + { "yes", 1 },
  24170. + { "on", 1 },
  24171. + { "true", 1 },
  24172. + { "full", 2 },
  24173. + };
  24174. + int i;
  24175. + if( z[0]==0 ) return 1;
  24176. + if( isdigit(z[0]) || (z[0]=='-' && isdigit(z[1])) ){
  24177. + return atoi(z);
  24178. + }
  24179. + for(i=0; i<sizeof(aKey)/sizeof(aKey[0]); i++){
  24180. + if( sqliteStrICmp(z,aKey[i].zWord)==0 ) return aKey[i].val;
  24181. + }
  24182. + return 1;
  24183. +}
  24184. +
  24185. +/*
  24186. +** Interpret the given string as a temp db location. Return 1 for file
  24187. +** backed temporary databases, 2 for the Red-Black tree in memory database
  24188. +** and 0 to use the compile-time default.
  24189. +*/
  24190. +static int getTempStore(const char *z){
  24191. + if( z[0]>='0' && z[0]<='2' ){
  24192. + return z[0] - '0';
  24193. + }else if( sqliteStrICmp(z, "file")==0 ){
  24194. + return 1;
  24195. + }else if( sqliteStrICmp(z, "memory")==0 ){
  24196. + return 2;
  24197. + }else{
  24198. + return 0;
  24199. + }
  24200. +}
  24201. +
  24202. +/*
  24203. +** If the TEMP database is open, close it and mark the database schema
  24204. +** as needing reloading. This must be done when using the TEMP_STORE
  24205. +** or DEFAULT_TEMP_STORE pragmas.
  24206. +*/
  24207. +static int changeTempStorage(Parse *pParse, const char *zStorageType){
  24208. + int ts = getTempStore(zStorageType);
  24209. + sqlite *db = pParse->db;
  24210. + if( db->temp_store==ts ) return SQLITE_OK;
  24211. + if( db->aDb[1].pBt!=0 ){
  24212. + if( db->flags & SQLITE_InTrans ){
  24213. + sqliteErrorMsg(pParse, "temporary storage cannot be changed "
  24214. + "from within a transaction");
  24215. + return SQLITE_ERROR;
  24216. + }
  24217. + sqliteBtreeClose(db->aDb[1].pBt);
  24218. + db->aDb[1].pBt = 0;
  24219. + sqliteResetInternalSchema(db, 0);
  24220. + }
  24221. + db->temp_store = ts;
  24222. + return SQLITE_OK;
  24223. +}
  24224. +
  24225. +/*
  24226. +** Check to see if zRight and zLeft refer to a pragma that queries
  24227. +** or changes one of the flags in db->flags. Return 1 if so and 0 if not.
  24228. +** Also, implement the pragma.
  24229. +*/
  24230. +static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
  24231. + static const struct {
  24232. + const char *zName; /* Name of the pragma */
  24233. + int mask; /* Mask for the db->flags value */
  24234. + } aPragma[] = {
  24235. + { "vdbe_trace", SQLITE_VdbeTrace },
  24236. + { "full_column_names", SQLITE_FullColNames },
  24237. + { "short_column_names", SQLITE_ShortColNames },
  24238. + { "show_datatypes", SQLITE_ReportTypes },
  24239. + { "count_changes", SQLITE_CountRows },
  24240. + { "empty_result_callbacks", SQLITE_NullCallback },
  24241. + };
  24242. + int i;
  24243. + for(i=0; i<sizeof(aPragma)/sizeof(aPragma[0]); i++){
  24244. + if( sqliteStrICmp(zLeft, aPragma[i].zName)==0 ){
  24245. + sqlite *db = pParse->db;
  24246. + Vdbe *v;
  24247. + if( strcmp(zLeft,zRight)==0 && (v = sqliteGetVdbe(pParse))!=0 ){
  24248. + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, aPragma[i].zName, P3_STATIC);
  24249. + sqliteVdbeOp3(v, OP_ColumnName, 1, 0, "boolean", P3_STATIC);
  24250. + sqliteVdbeCode(v, OP_Integer, (db->flags & aPragma[i].mask)!=0, 0,
  24251. + OP_Callback, 1, 0,
  24252. + 0);
  24253. + }else if( getBoolean(zRight) ){
  24254. + db->flags |= aPragma[i].mask;
  24255. + }else{
  24256. + db->flags &= ~aPragma[i].mask;
  24257. + }
  24258. + return 1;
  24259. + }
  24260. + }
  24261. + return 0;
  24262. +}
  24263. +
  24264. +/*
  24265. +** Process a pragma statement.
  24266. +**
  24267. +** Pragmas are of this form:
  24268. +**
  24269. +** PRAGMA id = value
  24270. +**
  24271. +** The identifier might also be a string. The value is a string, and
  24272. +** identifier, or a number. If minusFlag is true, then the value is
  24273. +** a number that was preceded by a minus sign.
  24274. +*/
  24275. +void sqlitePragma(Parse *pParse, Token *pLeft, Token *pRight, int minusFlag){
  24276. + char *zLeft = 0;
  24277. + char *zRight = 0;
  24278. + sqlite *db = pParse->db;
  24279. + Vdbe *v = sqliteGetVdbe(pParse);
  24280. + if( v==0 ) return;
  24281. +
  24282. + zLeft = sqliteStrNDup(pLeft->z, pLeft->n);
  24283. + sqliteDequote(zLeft);
  24284. + if( minusFlag ){
  24285. + zRight = 0;
  24286. + sqliteSetNString(&zRight, "-", 1, pRight->z, pRight->n, 0);
  24287. + }else{
  24288. + zRight = sqliteStrNDup(pRight->z, pRight->n);
  24289. + sqliteDequote(zRight);
  24290. + }
  24291. + if( sqliteAuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, 0) ){
  24292. + sqliteFree(zLeft);
  24293. + sqliteFree(zRight);
  24294. + return;
  24295. + }
  24296. +
  24297. + /*
  24298. + ** PRAGMA default_cache_size
  24299. + ** PRAGMA default_cache_size=N
  24300. + **
  24301. + ** The first form reports the current persistent setting for the
  24302. + ** page cache size. The value returned is the maximum number of
  24303. + ** pages in the page cache. The second form sets both the current
  24304. + ** page cache size value and the persistent page cache size value
  24305. + ** stored in the database file.
  24306. + **
  24307. + ** The default cache size is stored in meta-value 2 of page 1 of the
  24308. + ** database file. The cache size is actually the absolute value of
  24309. + ** this memory location. The sign of meta-value 2 determines the
  24310. + ** synchronous setting. A negative value means synchronous is off
  24311. + ** and a positive value means synchronous is on.
  24312. + */
  24313. + if( sqliteStrICmp(zLeft,"default_cache_size")==0 ){
  24314. + static VdbeOpList getCacheSize[] = {
  24315. + { OP_ReadCookie, 0, 2, 0},
  24316. + { OP_AbsValue, 0, 0, 0},
  24317. + { OP_Dup, 0, 0, 0},
  24318. + { OP_Integer, 0, 0, 0},
  24319. + { OP_Ne, 0, 6, 0},
  24320. + { OP_Integer, 0, 0, 0}, /* 5 */
  24321. + { OP_ColumnName, 0, 1, "cache_size"},
  24322. + { OP_Callback, 1, 0, 0},
  24323. + };
  24324. + int addr;
  24325. + if( pRight->z==pLeft->z ){
  24326. + addr = sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  24327. + sqliteVdbeChangeP1(v, addr+5, MAX_PAGES);
  24328. + }else{
  24329. + int size = atoi(zRight);
  24330. + if( size<0 ) size = -size;
  24331. + sqliteBeginWriteOperation(pParse, 0, 0);
  24332. + sqliteVdbeAddOp(v, OP_Integer, size, 0);
  24333. + sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
  24334. + addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  24335. + sqliteVdbeAddOp(v, OP_Ge, 0, addr+3);
  24336. + sqliteVdbeAddOp(v, OP_Negative, 0, 0);
  24337. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
  24338. + sqliteEndWriteOperation(pParse);
  24339. + db->cache_size = db->cache_size<0 ? -size : size;
  24340. + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
  24341. + }
  24342. + }else
  24343. +
  24344. + /*
  24345. + ** PRAGMA cache_size
  24346. + ** PRAGMA cache_size=N
  24347. + **
  24348. + ** The first form reports the current local setting for the
  24349. + ** page cache size. The local setting can be different from
  24350. + ** the persistent cache size value that is stored in the database
  24351. + ** file itself. The value returned is the maximum number of
  24352. + ** pages in the page cache. The second form sets the local
  24353. + ** page cache size value. It does not change the persistent
  24354. + ** cache size stored on the disk so the cache size will revert
  24355. + ** to its default value when the database is closed and reopened.
  24356. + ** N should be a positive integer.
  24357. + */
  24358. + if( sqliteStrICmp(zLeft,"cache_size")==0 ){
  24359. + static VdbeOpList getCacheSize[] = {
  24360. + { OP_ColumnName, 0, 1, "cache_size"},
  24361. + { OP_Callback, 1, 0, 0},
  24362. + };
  24363. + if( pRight->z==pLeft->z ){
  24364. + int size = db->cache_size;;
  24365. + if( size<0 ) size = -size;
  24366. + sqliteVdbeAddOp(v, OP_Integer, size, 0);
  24367. + sqliteVdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
  24368. + }else{
  24369. + int size = atoi(zRight);
  24370. + if( size<0 ) size = -size;
  24371. + if( db->cache_size<0 ) size = -size;
  24372. + db->cache_size = size;
  24373. + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
  24374. + }
  24375. + }else
  24376. +
  24377. + /*
  24378. + ** PRAGMA default_synchronous
  24379. + ** PRAGMA default_synchronous=ON|OFF|NORMAL|FULL
  24380. + **
  24381. + ** The first form returns the persistent value of the "synchronous" setting
  24382. + ** that is stored in the database. This is the synchronous setting that
  24383. + ** is used whenever the database is opened unless overridden by a separate
  24384. + ** "synchronous" pragma. The second form changes the persistent and the
  24385. + ** local synchronous setting to the value given.
  24386. + **
  24387. + ** If synchronous is OFF, SQLite does not attempt any fsync() systems calls
  24388. + ** to make sure data is committed to disk. Write operations are very fast,
  24389. + ** but a power failure can leave the database in an inconsistent state.
  24390. + ** If synchronous is ON or NORMAL, SQLite will do an fsync() system call to
  24391. + ** make sure data is being written to disk. The risk of corruption due to
  24392. + ** a power loss in this mode is negligible but non-zero. If synchronous
  24393. + ** is FULL, extra fsync()s occur to reduce the risk of corruption to near
  24394. + ** zero, but with a write performance penalty. The default mode is NORMAL.
  24395. + */
  24396. + if( sqliteStrICmp(zLeft,"default_synchronous")==0 ){
  24397. + static VdbeOpList getSync[] = {
  24398. + { OP_ColumnName, 0, 1, "synchronous"},
  24399. + { OP_ReadCookie, 0, 3, 0},
  24400. + { OP_Dup, 0, 0, 0},
  24401. + { OP_If, 0, 0, 0}, /* 3 */
  24402. + { OP_ReadCookie, 0, 2, 0},
  24403. + { OP_Integer, 0, 0, 0},
  24404. + { OP_Lt, 0, 5, 0},
  24405. + { OP_AddImm, 1, 0, 0},
  24406. + { OP_Callback, 1, 0, 0},
  24407. + { OP_Halt, 0, 0, 0},
  24408. + { OP_AddImm, -1, 0, 0}, /* 10 */
  24409. + { OP_Callback, 1, 0, 0}
  24410. + };
  24411. + if( pRight->z==pLeft->z ){
  24412. + int addr = sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
  24413. + sqliteVdbeChangeP2(v, addr+3, addr+10);
  24414. + }else{
  24415. + int addr;
  24416. + int size = db->cache_size;
  24417. + if( size<0 ) size = -size;
  24418. + sqliteBeginWriteOperation(pParse, 0, 0);
  24419. + sqliteVdbeAddOp(v, OP_ReadCookie, 0, 2);
  24420. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  24421. + addr = sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  24422. + sqliteVdbeAddOp(v, OP_Ne, 0, addr+3);
  24423. + sqliteVdbeAddOp(v, OP_AddImm, MAX_PAGES, 0);
  24424. + sqliteVdbeAddOp(v, OP_AbsValue, 0, 0);
  24425. + db->safety_level = getSafetyLevel(zRight)+1;
  24426. + if( db->safety_level==1 ){
  24427. + sqliteVdbeAddOp(v, OP_Negative, 0, 0);
  24428. + size = -size;
  24429. + }
  24430. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 2);
  24431. + sqliteVdbeAddOp(v, OP_Integer, db->safety_level, 0);
  24432. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 3);
  24433. + sqliteEndWriteOperation(pParse);
  24434. + db->cache_size = size;
  24435. + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
  24436. + sqliteBtreeSetSafetyLevel(db->aDb[0].pBt, db->safety_level);
  24437. + }
  24438. + }else
  24439. +
  24440. + /*
  24441. + ** PRAGMA synchronous
  24442. + ** PRAGMA synchronous=OFF|ON|NORMAL|FULL
  24443. + **
  24444. + ** Return or set the local value of the synchronous flag. Changing
  24445. + ** the local value does not make changes to the disk file and the
  24446. + ** default value will be restored the next time the database is
  24447. + ** opened.
  24448. + */
  24449. + if( sqliteStrICmp(zLeft,"synchronous")==0 ){
  24450. + static VdbeOpList getSync[] = {
  24451. + { OP_ColumnName, 0, 1, "synchronous"},
  24452. + { OP_Callback, 1, 0, 0},
  24453. + };
  24454. + if( pRight->z==pLeft->z ){
  24455. + sqliteVdbeAddOp(v, OP_Integer, db->safety_level-1, 0);
  24456. + sqliteVdbeAddOpList(v, ArraySize(getSync), getSync);
  24457. + }else{
  24458. + int size = db->cache_size;
  24459. + if( size<0 ) size = -size;
  24460. + db->safety_level = getSafetyLevel(zRight)+1;
  24461. + if( db->safety_level==1 ) size = -size;
  24462. + db->cache_size = size;
  24463. + sqliteBtreeSetCacheSize(db->aDb[0].pBt, db->cache_size);
  24464. + sqliteBtreeSetSafetyLevel(db->aDb[0].pBt, db->safety_level);
  24465. + }
  24466. + }else
  24467. +
  24468. +#ifndef NDEBUG
  24469. + if( sqliteStrICmp(zLeft, "trigger_overhead_test")==0 ){
  24470. + if( getBoolean(zRight) ){
  24471. + always_code_trigger_setup = 1;
  24472. + }else{
  24473. + always_code_trigger_setup = 0;
  24474. + }
  24475. + }else
  24476. +#endif
  24477. +
  24478. + if( flagPragma(pParse, zLeft, zRight) ){
  24479. + /* The flagPragma() call also generates any necessary code */
  24480. + }else
  24481. +
  24482. + if( sqliteStrICmp(zLeft, "table_info")==0 ){
  24483. + Table *pTab;
  24484. + pTab = sqliteFindTable(db, zRight, 0);
  24485. + if( pTab ){
  24486. + static VdbeOpList tableInfoPreface[] = {
  24487. + { OP_ColumnName, 0, 0, "cid"},
  24488. + { OP_ColumnName, 1, 0, "name"},
  24489. + { OP_ColumnName, 2, 0, "type"},
  24490. + { OP_ColumnName, 3, 0, "notnull"},
  24491. + { OP_ColumnName, 4, 0, "dflt_value"},
  24492. + { OP_ColumnName, 5, 1, "pk"},
  24493. + };
  24494. + int i;
  24495. + sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
  24496. + sqliteViewGetColumnNames(pParse, pTab);
  24497. + for(i=0; i<pTab->nCol; i++){
  24498. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24499. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[i].zName, 0);
  24500. + sqliteVdbeOp3(v, OP_String, 0, 0,
  24501. + pTab->aCol[i].zType ? pTab->aCol[i].zType : "numeric", 0);
  24502. + sqliteVdbeAddOp(v, OP_Integer, pTab->aCol[i].notNull, 0);
  24503. + sqliteVdbeOp3(v, OP_String, 0, 0,
  24504. + pTab->aCol[i].zDflt, P3_STATIC);
  24505. + sqliteVdbeAddOp(v, OP_Integer, pTab->aCol[i].isPrimKey, 0);
  24506. + sqliteVdbeAddOp(v, OP_Callback, 6, 0);
  24507. + }
  24508. + }
  24509. + }else
  24510. +
  24511. + if( sqliteStrICmp(zLeft, "index_info")==0 ){
  24512. + Index *pIdx;
  24513. + Table *pTab;
  24514. + pIdx = sqliteFindIndex(db, zRight, 0);
  24515. + if( pIdx ){
  24516. + static VdbeOpList tableInfoPreface[] = {
  24517. + { OP_ColumnName, 0, 0, "seqno"},
  24518. + { OP_ColumnName, 1, 0, "cid"},
  24519. + { OP_ColumnName, 2, 1, "name"},
  24520. + };
  24521. + int i;
  24522. + pTab = pIdx->pTable;
  24523. + sqliteVdbeAddOpList(v, ArraySize(tableInfoPreface), tableInfoPreface);
  24524. + for(i=0; i<pIdx->nColumn; i++){
  24525. + int cnum = pIdx->aiColumn[i];
  24526. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24527. + sqliteVdbeAddOp(v, OP_Integer, cnum, 0);
  24528. + assert( pTab->nCol>cnum );
  24529. + sqliteVdbeOp3(v, OP_String, 0, 0, pTab->aCol[cnum].zName, 0);
  24530. + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
  24531. + }
  24532. + }
  24533. + }else
  24534. +
  24535. + if( sqliteStrICmp(zLeft, "index_list")==0 ){
  24536. + Index *pIdx;
  24537. + Table *pTab;
  24538. + pTab = sqliteFindTable(db, zRight, 0);
  24539. + if( pTab ){
  24540. + v = sqliteGetVdbe(pParse);
  24541. + pIdx = pTab->pIndex;
  24542. + }
  24543. + if( pTab && pIdx ){
  24544. + int i = 0;
  24545. + static VdbeOpList indexListPreface[] = {
  24546. + { OP_ColumnName, 0, 0, "seq"},
  24547. + { OP_ColumnName, 1, 0, "name"},
  24548. + { OP_ColumnName, 2, 1, "unique"},
  24549. + };
  24550. +
  24551. + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
  24552. + while(pIdx){
  24553. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24554. + sqliteVdbeOp3(v, OP_String, 0, 0, pIdx->zName, 0);
  24555. + sqliteVdbeAddOp(v, OP_Integer, pIdx->onError!=OE_None, 0);
  24556. + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
  24557. + ++i;
  24558. + pIdx = pIdx->pNext;
  24559. + }
  24560. + }
  24561. + }else
  24562. +
  24563. + if( sqliteStrICmp(zLeft, "foreign_key_list")==0 ){
  24564. + FKey *pFK;
  24565. + Table *pTab;
  24566. + pTab = sqliteFindTable(db, zRight, 0);
  24567. + if( pTab ){
  24568. + v = sqliteGetVdbe(pParse);
  24569. + pFK = pTab->pFKey;
  24570. + }
  24571. + if( pTab && pFK ){
  24572. + int i = 0;
  24573. + static VdbeOpList indexListPreface[] = {
  24574. + { OP_ColumnName, 0, 0, "id"},
  24575. + { OP_ColumnName, 1, 0, "seq"},
  24576. + { OP_ColumnName, 2, 0, "table"},
  24577. + { OP_ColumnName, 3, 0, "from"},
  24578. + { OP_ColumnName, 4, 1, "to"},
  24579. + };
  24580. +
  24581. + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
  24582. + while(pFK){
  24583. + int j;
  24584. + for(j=0; j<pFK->nCol; j++){
  24585. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24586. + sqliteVdbeAddOp(v, OP_Integer, j, 0);
  24587. + sqliteVdbeOp3(v, OP_String, 0, 0, pFK->zTo, 0);
  24588. + sqliteVdbeOp3(v, OP_String, 0, 0,
  24589. + pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  24590. + sqliteVdbeOp3(v, OP_String, 0, 0, pFK->aCol[j].zCol, 0);
  24591. + sqliteVdbeAddOp(v, OP_Callback, 5, 0);
  24592. + }
  24593. + ++i;
  24594. + pFK = pFK->pNextFrom;
  24595. + }
  24596. + }
  24597. + }else
  24598. +
  24599. + if( sqliteStrICmp(zLeft, "database_list")==0 ){
  24600. + int i;
  24601. + static VdbeOpList indexListPreface[] = {
  24602. + { OP_ColumnName, 0, 0, "seq"},
  24603. + { OP_ColumnName, 1, 0, "name"},
  24604. + { OP_ColumnName, 2, 1, "file"},
  24605. + };
  24606. +
  24607. + sqliteVdbeAddOpList(v, ArraySize(indexListPreface), indexListPreface);
  24608. + for(i=0; i<db->nDb; i++){
  24609. + if( db->aDb[i].pBt==0 ) continue;
  24610. + assert( db->aDb[i].zName!=0 );
  24611. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24612. + sqliteVdbeOp3(v, OP_String, 0, 0, db->aDb[i].zName, 0);
  24613. + sqliteVdbeOp3(v, OP_String, 0, 0,
  24614. + sqliteBtreeGetFilename(db->aDb[i].pBt), 0);
  24615. + sqliteVdbeAddOp(v, OP_Callback, 3, 0);
  24616. + }
  24617. + }else
  24618. +
  24619. +
  24620. + /*
  24621. + ** PRAGMA temp_store
  24622. + ** PRAGMA temp_store = "default"|"memory"|"file"
  24623. + **
  24624. + ** Return or set the local value of the temp_store flag. Changing
  24625. + ** the local value does not make changes to the disk file and the default
  24626. + ** value will be restored the next time the database is opened.
  24627. + **
  24628. + ** Note that it is possible for the library compile-time options to
  24629. + ** override this setting
  24630. + */
  24631. + if( sqliteStrICmp(zLeft, "temp_store")==0 ){
  24632. + static VdbeOpList getTmpDbLoc[] = {
  24633. + { OP_ColumnName, 0, 1, "temp_store"},
  24634. + { OP_Callback, 1, 0, 0},
  24635. + };
  24636. + if( pRight->z==pLeft->z ){
  24637. + sqliteVdbeAddOp(v, OP_Integer, db->temp_store, 0);
  24638. + sqliteVdbeAddOpList(v, ArraySize(getTmpDbLoc), getTmpDbLoc);
  24639. + }else{
  24640. + changeTempStorage(pParse, zRight);
  24641. + }
  24642. + }else
  24643. +
  24644. + /*
  24645. + ** PRAGMA default_temp_store
  24646. + ** PRAGMA default_temp_store = "default"|"memory"|"file"
  24647. + **
  24648. + ** Return or set the value of the persistent temp_store flag. Any
  24649. + ** change does not take effect until the next time the database is
  24650. + ** opened.
  24651. + **
  24652. + ** Note that it is possible for the library compile-time options to
  24653. + ** override this setting
  24654. + */
  24655. + if( sqliteStrICmp(zLeft, "default_temp_store")==0 ){
  24656. + static VdbeOpList getTmpDbLoc[] = {
  24657. + { OP_ColumnName, 0, 1, "temp_store"},
  24658. + { OP_ReadCookie, 0, 5, 0},
  24659. + { OP_Callback, 1, 0, 0}};
  24660. + if( pRight->z==pLeft->z ){
  24661. + sqliteVdbeAddOpList(v, ArraySize(getTmpDbLoc), getTmpDbLoc);
  24662. + }else{
  24663. + sqliteBeginWriteOperation(pParse, 0, 0);
  24664. + sqliteVdbeAddOp(v, OP_Integer, getTempStore(zRight), 0);
  24665. + sqliteVdbeAddOp(v, OP_SetCookie, 0, 5);
  24666. + sqliteEndWriteOperation(pParse);
  24667. + }
  24668. + }else
  24669. +
  24670. +#ifndef NDEBUG
  24671. + if( sqliteStrICmp(zLeft, "parser_trace")==0 ){
  24672. + extern void sqliteParserTrace(FILE*, char *);
  24673. + if( getBoolean(zRight) ){
  24674. + sqliteParserTrace(stdout, "parser: ");
  24675. + }else{
  24676. + sqliteParserTrace(0, 0);
  24677. + }
  24678. + }else
  24679. +#endif
  24680. +
  24681. + if( sqliteStrICmp(zLeft, "integrity_check")==0 ){
  24682. + int i, j, addr;
  24683. +
  24684. + /* Code that initializes the integrity check program. Set the
  24685. + ** error count 0
  24686. + */
  24687. + static VdbeOpList initCode[] = {
  24688. + { OP_Integer, 0, 0, 0},
  24689. + { OP_MemStore, 0, 1, 0},
  24690. + { OP_ColumnName, 0, 1, "integrity_check"},
  24691. + };
  24692. +
  24693. + /* Code to do an BTree integrity check on a single database file.
  24694. + */
  24695. + static VdbeOpList checkDb[] = {
  24696. + { OP_SetInsert, 0, 0, "2"},
  24697. + { OP_Integer, 0, 0, 0}, /* 1 */
  24698. + { OP_OpenRead, 0, 2, 0},
  24699. + { OP_Rewind, 0, 7, 0}, /* 3 */
  24700. + { OP_Column, 0, 3, 0}, /* 4 */
  24701. + { OP_SetInsert, 0, 0, 0},
  24702. + { OP_Next, 0, 4, 0}, /* 6 */
  24703. + { OP_IntegrityCk, 0, 0, 0}, /* 7 */
  24704. + { OP_Dup, 0, 1, 0},
  24705. + { OP_String, 0, 0, "ok"},
  24706. + { OP_StrEq, 0, 12, 0}, /* 10 */
  24707. + { OP_MemIncr, 0, 0, 0},
  24708. + { OP_String, 0, 0, "*** in database "},
  24709. + { OP_String, 0, 0, 0}, /* 13 */
  24710. + { OP_String, 0, 0, " ***\n"},
  24711. + { OP_Pull, 3, 0, 0},
  24712. + { OP_Concat, 4, 1, 0},
  24713. + { OP_Callback, 1, 0, 0},
  24714. + };
  24715. +
  24716. + /* Code that appears at the end of the integrity check. If no error
  24717. + ** messages have been generated, output OK. Otherwise output the
  24718. + ** error message
  24719. + */
  24720. + static VdbeOpList endCode[] = {
  24721. + { OP_MemLoad, 0, 0, 0},
  24722. + { OP_Integer, 0, 0, 0},
  24723. + { OP_Ne, 0, 0, 0}, /* 2 */
  24724. + { OP_String, 0, 0, "ok"},
  24725. + { OP_Callback, 1, 0, 0},
  24726. + };
  24727. +
  24728. + /* Initialize the VDBE program */
  24729. + sqliteVdbeAddOpList(v, ArraySize(initCode), initCode);
  24730. +
  24731. + /* Do an integrity check on each database file */
  24732. + for(i=0; i<db->nDb; i++){
  24733. + HashElem *x;
  24734. +
  24735. + /* Do an integrity check of the B-Tree
  24736. + */
  24737. + addr = sqliteVdbeAddOpList(v, ArraySize(checkDb), checkDb);
  24738. + sqliteVdbeChangeP1(v, addr+1, i);
  24739. + sqliteVdbeChangeP2(v, addr+3, addr+7);
  24740. + sqliteVdbeChangeP2(v, addr+6, addr+4);
  24741. + sqliteVdbeChangeP2(v, addr+7, i);
  24742. + sqliteVdbeChangeP2(v, addr+10, addr+ArraySize(checkDb));
  24743. + sqliteVdbeChangeP3(v, addr+13, db->aDb[i].zName, P3_STATIC);
  24744. +
  24745. + /* Make sure all the indices are constructed correctly.
  24746. + */
  24747. + sqliteCodeVerifySchema(pParse, i);
  24748. + for(x=sqliteHashFirst(&db->aDb[i].tblHash); x; x=sqliteHashNext(x)){
  24749. + Table *pTab = sqliteHashData(x);
  24750. + Index *pIdx;
  24751. + int loopTop;
  24752. +
  24753. + if( pTab->pIndex==0 ) continue;
  24754. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  24755. + sqliteVdbeOp3(v, OP_OpenRead, 1, pTab->tnum, pTab->zName, 0);
  24756. + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  24757. + if( pIdx->tnum==0 ) continue;
  24758. + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
  24759. + sqliteVdbeOp3(v, OP_OpenRead, j+2, pIdx->tnum, pIdx->zName, 0);
  24760. + }
  24761. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  24762. + sqliteVdbeAddOp(v, OP_MemStore, 1, 1);
  24763. + loopTop = sqliteVdbeAddOp(v, OP_Rewind, 1, 0);
  24764. + sqliteVdbeAddOp(v, OP_MemIncr, 1, 0);
  24765. + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  24766. + int k, jmp2;
  24767. + static VdbeOpList idxErr[] = {
  24768. + { OP_MemIncr, 0, 0, 0},
  24769. + { OP_String, 0, 0, "rowid "},
  24770. + { OP_Recno, 1, 0, 0},
  24771. + { OP_String, 0, 0, " missing from index "},
  24772. + { OP_String, 0, 0, 0}, /* 4 */
  24773. + { OP_Concat, 4, 0, 0},
  24774. + { OP_Callback, 1, 0, 0},
  24775. + };
  24776. + sqliteVdbeAddOp(v, OP_Recno, 1, 0);
  24777. + for(k=0; k<pIdx->nColumn; k++){
  24778. + int idx = pIdx->aiColumn[k];
  24779. + if( idx==pTab->iPKey ){
  24780. + sqliteVdbeAddOp(v, OP_Recno, 1, 0);
  24781. + }else{
  24782. + sqliteVdbeAddOp(v, OP_Column, 1, idx);
  24783. + }
  24784. + }
  24785. + sqliteVdbeAddOp(v, OP_MakeIdxKey, pIdx->nColumn, 0);
  24786. + if( db->file_format>=4 ) sqliteAddIdxKeyType(v, pIdx);
  24787. + jmp2 = sqliteVdbeAddOp(v, OP_Found, j+2, 0);
  24788. + addr = sqliteVdbeAddOpList(v, ArraySize(idxErr), idxErr);
  24789. + sqliteVdbeChangeP3(v, addr+4, pIdx->zName, P3_STATIC);
  24790. + sqliteVdbeChangeP2(v, jmp2, sqliteVdbeCurrentAddr(v));
  24791. + }
  24792. + sqliteVdbeAddOp(v, OP_Next, 1, loopTop+1);
  24793. + sqliteVdbeChangeP2(v, loopTop, sqliteVdbeCurrentAddr(v));
  24794. + for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  24795. + static VdbeOpList cntIdx[] = {
  24796. + { OP_Integer, 0, 0, 0},
  24797. + { OP_MemStore, 2, 1, 0},
  24798. + { OP_Rewind, 0, 0, 0}, /* 2 */
  24799. + { OP_MemIncr, 2, 0, 0},
  24800. + { OP_Next, 0, 0, 0}, /* 4 */
  24801. + { OP_MemLoad, 1, 0, 0},
  24802. + { OP_MemLoad, 2, 0, 0},
  24803. + { OP_Eq, 0, 0, 0}, /* 7 */
  24804. + { OP_MemIncr, 0, 0, 0},
  24805. + { OP_String, 0, 0, "wrong # of entries in index "},
  24806. + { OP_String, 0, 0, 0}, /* 10 */
  24807. + { OP_Concat, 2, 0, 0},
  24808. + { OP_Callback, 1, 0, 0},
  24809. + };
  24810. + if( pIdx->tnum==0 ) continue;
  24811. + addr = sqliteVdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
  24812. + sqliteVdbeChangeP1(v, addr+2, j+2);
  24813. + sqliteVdbeChangeP2(v, addr+2, addr+5);
  24814. + sqliteVdbeChangeP1(v, addr+4, j+2);
  24815. + sqliteVdbeChangeP2(v, addr+4, addr+3);
  24816. + sqliteVdbeChangeP2(v, addr+7, addr+ArraySize(cntIdx));
  24817. + sqliteVdbeChangeP3(v, addr+10, pIdx->zName, P3_STATIC);
  24818. + }
  24819. + }
  24820. + }
  24821. + addr = sqliteVdbeAddOpList(v, ArraySize(endCode), endCode);
  24822. + sqliteVdbeChangeP2(v, addr+2, addr+ArraySize(endCode));
  24823. + }else
  24824. +
  24825. + {}
  24826. + sqliteFree(zLeft);
  24827. + sqliteFree(zRight);
  24828. +}
  24829. --- /dev/null
  24830. +++ b/ext/sqlite/libsqlite/src/printf.c
  24831. @@ -0,0 +1,858 @@
  24832. +/*
  24833. +** The "printf" code that follows dates from the 1980's. It is in
  24834. +** the public domain. The original comments are included here for
  24835. +** completeness. They are very out-of-date but might be useful as
  24836. +** an historical reference. Most of the "enhancements" have been backed
  24837. +** out so that the functionality is now the same as standard printf().
  24838. +**
  24839. +**************************************************************************
  24840. +**
  24841. +** The following modules is an enhanced replacement for the "printf" subroutines
  24842. +** found in the standard C library. The following enhancements are
  24843. +** supported:
  24844. +**
  24845. +** + Additional functions. The standard set of "printf" functions
  24846. +** includes printf, fprintf, sprintf, vprintf, vfprintf, and
  24847. +** vsprintf. This module adds the following:
  24848. +**
  24849. +** * snprintf -- Works like sprintf, but has an extra argument
  24850. +** which is the size of the buffer written to.
  24851. +**
  24852. +** * mprintf -- Similar to sprintf. Writes output to memory
  24853. +** obtained from malloc.
  24854. +**
  24855. +** * xprintf -- Calls a function to dispose of output.
  24856. +**
  24857. +** * nprintf -- No output, but returns the number of characters
  24858. +** that would have been output by printf.
  24859. +**
  24860. +** * A v- version (ex: vsnprintf) of every function is also
  24861. +** supplied.
  24862. +**
  24863. +** + A few extensions to the formatting notation are supported:
  24864. +**
  24865. +** * The "=" flag (similar to "-") causes the output to be
  24866. +** be centered in the appropriately sized field.
  24867. +**
  24868. +** * The %b field outputs an integer in binary notation.
  24869. +**
  24870. +** * The %c field now accepts a precision. The character output
  24871. +** is repeated by the number of times the precision specifies.
  24872. +**
  24873. +** * The %' field works like %c, but takes as its character the
  24874. +** next character of the format string, instead of the next
  24875. +** argument. For example, printf("%.78'-") prints 78 minus
  24876. +** signs, the same as printf("%.78c",'-').
  24877. +**
  24878. +** + When compiled using GCC on a SPARC, this version of printf is
  24879. +** faster than the library printf for SUN OS 4.1.
  24880. +**
  24881. +** + All functions are fully reentrant.
  24882. +**
  24883. +*/
  24884. +#include "sqliteInt.h"
  24885. +
  24886. +/*
  24887. +** Conversion types fall into various categories as defined by the
  24888. +** following enumeration.
  24889. +*/
  24890. +#define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  24891. +#define etFLOAT 2 /* Floating point. %f */
  24892. +#define etEXP 3 /* Exponentional notation. %e and %E */
  24893. +#define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  24894. +#define etSIZE 5 /* Return number of characters processed so far. %n */
  24895. +#define etSTRING 6 /* Strings. %s */
  24896. +#define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  24897. +#define etPERCENT 8 /* Percent symbol. %% */
  24898. +#define etCHARX 9 /* Characters. %c */
  24899. +#define etERROR 10 /* Used to indicate no such conversion type */
  24900. +/* The rest are extensions, not normally found in printf() */
  24901. +#define etCHARLIT 11 /* Literal characters. %' */
  24902. +#define etSQLESCAPE 12 /* Strings with '\'' doubled. %q */
  24903. +#define etSQLESCAPE2 13 /* Strings with '\'' doubled and enclosed in '',
  24904. + NULL pointers replaced by SQL NULL. %Q */
  24905. +#define etTOKEN 14 /* a pointer to a Token structure */
  24906. +#define etSRCLIST 15 /* a pointer to a SrcList */
  24907. +
  24908. +
  24909. +/*
  24910. +** An "etByte" is an 8-bit unsigned value.
  24911. +*/
  24912. +typedef unsigned char etByte;
  24913. +
  24914. +/*
  24915. +** Each builtin conversion character (ex: the 'd' in "%d") is described
  24916. +** by an instance of the following structure
  24917. +*/
  24918. +typedef struct et_info { /* Information about each format field */
  24919. + char fmttype; /* The format field code letter */
  24920. + etByte base; /* The base for radix conversion */
  24921. + etByte flags; /* One or more of FLAG_ constants below */
  24922. + etByte type; /* Conversion paradigm */
  24923. + char *charset; /* The character set for conversion */
  24924. + char *prefix; /* Prefix on non-zero values in alt format */
  24925. +} et_info;
  24926. +
  24927. +/*
  24928. +** Allowed values for et_info.flags
  24929. +*/
  24930. +#define FLAG_SIGNED 1 /* True if the value to convert is signed */
  24931. +#define FLAG_INTERN 2 /* True if for internal use only */
  24932. +
  24933. +
  24934. +/*
  24935. +** The following table is searched linearly, so it is good to put the
  24936. +** most frequently used conversion types first.
  24937. +*/
  24938. +static et_info fmtinfo[] = {
  24939. + { 'd', 10, 1, etRADIX, "0123456789", 0 },
  24940. + { 's', 0, 0, etSTRING, 0, 0 },
  24941. + { 'z', 0, 2, etDYNSTRING, 0, 0 },
  24942. + { 'q', 0, 0, etSQLESCAPE, 0, 0 },
  24943. + { 'Q', 0, 0, etSQLESCAPE2, 0, 0 },
  24944. + { 'c', 0, 0, etCHARX, 0, 0 },
  24945. + { 'o', 8, 0, etRADIX, "01234567", "0" },
  24946. + { 'u', 10, 0, etRADIX, "0123456789", 0 },
  24947. + { 'x', 16, 0, etRADIX, "0123456789abcdef", "x0" },
  24948. + { 'X', 16, 0, etRADIX, "0123456789ABCDEF", "X0" },
  24949. + { 'f', 0, 1, etFLOAT, 0, 0 },
  24950. + { 'e', 0, 1, etEXP, "e", 0 },
  24951. + { 'E', 0, 1, etEXP, "E", 0 },
  24952. + { 'g', 0, 1, etGENERIC, "e", 0 },
  24953. + { 'G', 0, 1, etGENERIC, "E", 0 },
  24954. + { 'i', 10, 1, etRADIX, "0123456789", 0 },
  24955. + { 'n', 0, 0, etSIZE, 0, 0 },
  24956. + { '%', 0, 0, etPERCENT, 0, 0 },
  24957. + { 'p', 10, 0, etRADIX, "0123456789", 0 },
  24958. + { 'T', 0, 2, etTOKEN, 0, 0 },
  24959. + { 'S', 0, 2, etSRCLIST, 0, 0 },
  24960. +};
  24961. +#define etNINFO (sizeof(fmtinfo)/sizeof(fmtinfo[0]))
  24962. +
  24963. +/*
  24964. +** If NOFLOATINGPOINT is defined, then none of the floating point
  24965. +** conversions will work.
  24966. +*/
  24967. +#ifndef etNOFLOATINGPOINT
  24968. +/*
  24969. +** "*val" is a double such that 0.1 <= *val < 10.0
  24970. +** Return the ascii code for the leading digit of *val, then
  24971. +** multiply "*val" by 10.0 to renormalize.
  24972. +**
  24973. +** Example:
  24974. +** input: *val = 3.14159
  24975. +** output: *val = 1.4159 function return = '3'
  24976. +**
  24977. +** The counter *cnt is incremented each time. After counter exceeds
  24978. +** 16 (the number of significant digits in a 64-bit float) '0' is
  24979. +** always returned.
  24980. +*/
  24981. +static int et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  24982. + int digit;
  24983. + LONGDOUBLE_TYPE d;
  24984. + if( (*cnt)++ >= 16 ) return '0';
  24985. + digit = (int)*val;
  24986. + d = digit;
  24987. + digit += '0';
  24988. + *val = (*val - d)*10.0;
  24989. + return digit;
  24990. +}
  24991. +#endif
  24992. +
  24993. +#define etBUFSIZE 1000 /* Size of the output buffer */
  24994. +
  24995. +/*
  24996. +** The root program. All variations call this core.
  24997. +**
  24998. +** INPUTS:
  24999. +** func This is a pointer to a function taking three arguments
  25000. +** 1. A pointer to anything. Same as the "arg" parameter.
  25001. +** 2. A pointer to the list of characters to be output
  25002. +** (Note, this list is NOT null terminated.)
  25003. +** 3. An integer number of characters to be output.
  25004. +** (Note: This number might be zero.)
  25005. +**
  25006. +** arg This is the pointer to anything which will be passed as the
  25007. +** first argument to "func". Use it for whatever you like.
  25008. +**
  25009. +** fmt This is the format string, as in the usual print.
  25010. +**
  25011. +** ap This is a pointer to a list of arguments. Same as in
  25012. +** vfprint.
  25013. +**
  25014. +** OUTPUTS:
  25015. +** The return value is the total number of characters sent to
  25016. +** the function "func". Returns -1 on a error.
  25017. +**
  25018. +** Note that the order in which automatic variables are declared below
  25019. +** seems to make a big difference in determining how fast this beast
  25020. +** will run.
  25021. +*/
  25022. +static int vxprintf(
  25023. + void (*func)(void*,const char*,int), /* Consumer of text */
  25024. + void *arg, /* First argument to the consumer */
  25025. + int useExtended, /* Allow extended %-conversions */
  25026. + const char *fmt, /* Format string */
  25027. + va_list ap /* arguments */
  25028. +){
  25029. + int c; /* Next character in the format string */
  25030. + char *bufpt; /* Pointer to the conversion buffer */
  25031. + int precision; /* Precision of the current field */
  25032. + int length; /* Length of the field */
  25033. + int idx; /* A general purpose loop counter */
  25034. + int count; /* Total number of characters output */
  25035. + int width; /* Width of the current field */
  25036. + etByte flag_leftjustify; /* True if "-" flag is present */
  25037. + etByte flag_plussign; /* True if "+" flag is present */
  25038. + etByte flag_blanksign; /* True if " " flag is present */
  25039. + etByte flag_alternateform; /* True if "#" flag is present */
  25040. + etByte flag_zeropad; /* True if field width constant starts with zero */
  25041. + etByte flag_long; /* True if "l" flag is present */
  25042. + unsigned long longvalue; /* Value for integer types */
  25043. + LONGDOUBLE_TYPE realvalue; /* Value for real types */
  25044. + et_info *infop; /* Pointer to the appropriate info structure */
  25045. + char buf[etBUFSIZE]; /* Conversion buffer */
  25046. + char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  25047. + etByte errorflag = 0; /* True if an error is encountered */
  25048. + etByte xtype; /* Conversion paradigm */
  25049. + char *zExtra; /* Extra memory used for etTCLESCAPE conversions */
  25050. + static char spaces[] = " ";
  25051. +#define etSPACESIZE (sizeof(spaces)-1)
  25052. +#ifndef etNOFLOATINGPOINT
  25053. + int exp; /* exponent of real numbers */
  25054. + double rounder; /* Used for rounding floating point values */
  25055. + etByte flag_dp; /* True if decimal point should be shown */
  25056. + etByte flag_rtz; /* True if trailing zeros should be removed */
  25057. + etByte flag_exp; /* True to force display of the exponent */
  25058. + int nsd; /* Number of significant digits returned */
  25059. +#endif
  25060. +
  25061. + func(arg,"",0);
  25062. + count = length = 0;
  25063. + bufpt = 0;
  25064. + for(; (c=(*fmt))!=0; ++fmt){
  25065. + if( c!='%' ){
  25066. + int amt;
  25067. + bufpt = (char *)fmt;
  25068. + amt = 1;
  25069. + while( (c=(*++fmt))!='%' && c!=0 ) amt++;
  25070. + (*func)(arg,bufpt,amt);
  25071. + count += amt;
  25072. + if( c==0 ) break;
  25073. + }
  25074. + if( (c=(*++fmt))==0 ){
  25075. + errorflag = 1;
  25076. + (*func)(arg,"%",1);
  25077. + count++;
  25078. + break;
  25079. + }
  25080. + /* Find out what flags are present */
  25081. + flag_leftjustify = flag_plussign = flag_blanksign =
  25082. + flag_alternateform = flag_zeropad = 0;
  25083. + do{
  25084. + switch( c ){
  25085. + case '-': flag_leftjustify = 1; c = 0; break;
  25086. + case '+': flag_plussign = 1; c = 0; break;
  25087. + case ' ': flag_blanksign = 1; c = 0; break;
  25088. + case '#': flag_alternateform = 1; c = 0; break;
  25089. + case '0': flag_zeropad = 1; c = 0; break;
  25090. + default: break;
  25091. + }
  25092. + }while( c==0 && (c=(*++fmt))!=0 );
  25093. + /* Get the field width */
  25094. + width = 0;
  25095. + if( c=='*' ){
  25096. + width = va_arg(ap,int);
  25097. + if( width<0 ){
  25098. + flag_leftjustify = 1;
  25099. + width = -width;
  25100. + }
  25101. + c = *++fmt;
  25102. + }else{
  25103. + while( c>='0' && c<='9' ){
  25104. + width = width*10 + c - '0';
  25105. + c = *++fmt;
  25106. + }
  25107. + }
  25108. + if( width > etBUFSIZE-10 ){
  25109. + width = etBUFSIZE-10;
  25110. + }
  25111. + /* Get the precision */
  25112. + if( c=='.' ){
  25113. + precision = 0;
  25114. + c = *++fmt;
  25115. + if( c=='*' ){
  25116. + precision = va_arg(ap,int);
  25117. + if( precision<0 ) precision = -precision;
  25118. + c = *++fmt;
  25119. + }else{
  25120. + while( c>='0' && c<='9' ){
  25121. + precision = precision*10 + c - '0';
  25122. + c = *++fmt;
  25123. + }
  25124. + }
  25125. + /* Limit the precision to prevent overflowing buf[] during conversion */
  25126. + if( precision>etBUFSIZE-40 ) precision = etBUFSIZE-40;
  25127. + }else{
  25128. + precision = -1;
  25129. + }
  25130. + /* Get the conversion type modifier */
  25131. + if( c=='l' ){
  25132. + flag_long = 1;
  25133. + c = *++fmt;
  25134. + }else{
  25135. + flag_long = 0;
  25136. + }
  25137. + /* Fetch the info entry for the field */
  25138. + infop = 0;
  25139. + xtype = etERROR;
  25140. + for(idx=0; idx<etNINFO; idx++){
  25141. + if( c==fmtinfo[idx].fmttype ){
  25142. + infop = &fmtinfo[idx];
  25143. + if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
  25144. + xtype = infop->type;
  25145. + }
  25146. + break;
  25147. + }
  25148. + }
  25149. + zExtra = 0;
  25150. +
  25151. + /*
  25152. + ** At this point, variables are initialized as follows:
  25153. + **
  25154. + ** flag_alternateform TRUE if a '#' is present.
  25155. + ** flag_plussign TRUE if a '+' is present.
  25156. + ** flag_leftjustify TRUE if a '-' is present or if the
  25157. + ** field width was negative.
  25158. + ** flag_zeropad TRUE if the width began with 0.
  25159. + ** flag_long TRUE if the letter 'l' (ell) prefixed
  25160. + ** the conversion character.
  25161. + ** flag_blanksign TRUE if a ' ' is present.
  25162. + ** width The specified field width. This is
  25163. + ** always non-negative. Zero is the default.
  25164. + ** precision The specified precision. The default
  25165. + ** is -1.
  25166. + ** xtype The class of the conversion.
  25167. + ** infop Pointer to the appropriate info struct.
  25168. + */
  25169. + switch( xtype ){
  25170. + case etRADIX:
  25171. + if( flag_long ) longvalue = va_arg(ap,long);
  25172. + else longvalue = va_arg(ap,int);
  25173. +#if 1
  25174. + /* For the format %#x, the value zero is printed "0" not "0x0".
  25175. + ** I think this is stupid. */
  25176. + if( longvalue==0 ) flag_alternateform = 0;
  25177. +#else
  25178. + /* More sensible: turn off the prefix for octal (to prevent "00"),
  25179. + ** but leave the prefix for hex. */
  25180. + if( longvalue==0 && infop->base==8 ) flag_alternateform = 0;
  25181. +#endif
  25182. + if( infop->flags & FLAG_SIGNED ){
  25183. + if( *(long*)&longvalue<0 ){
  25184. + longvalue = -*(long*)&longvalue;
  25185. + prefix = '-';
  25186. + }else if( flag_plussign ) prefix = '+';
  25187. + else if( flag_blanksign ) prefix = ' ';
  25188. + else prefix = 0;
  25189. + }else prefix = 0;
  25190. + if( flag_zeropad && precision<width-(prefix!=0) ){
  25191. + precision = width-(prefix!=0);
  25192. + }
  25193. + bufpt = &buf[etBUFSIZE-1];
  25194. + {
  25195. + register char *cset; /* Use registers for speed */
  25196. + register int base;
  25197. + cset = infop->charset;
  25198. + base = infop->base;
  25199. + do{ /* Convert to ascii */
  25200. + *(--bufpt) = cset[longvalue%base];
  25201. + longvalue = longvalue/base;
  25202. + }while( longvalue>0 );
  25203. + }
  25204. + length = &buf[etBUFSIZE-1]-bufpt;
  25205. + for(idx=precision-length; idx>0; idx--){
  25206. + *(--bufpt) = '0'; /* Zero pad */
  25207. + }
  25208. + if( prefix ) *(--bufpt) = prefix; /* Add sign */
  25209. + if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  25210. + char *pre, x;
  25211. + pre = infop->prefix;
  25212. + if( *bufpt!=pre[0] ){
  25213. + for(pre=infop->prefix; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  25214. + }
  25215. + }
  25216. + length = &buf[etBUFSIZE-1]-bufpt;
  25217. + break;
  25218. + case etFLOAT:
  25219. + case etEXP:
  25220. + case etGENERIC:
  25221. + realvalue = va_arg(ap,double);
  25222. +#ifndef etNOFLOATINGPOINT
  25223. + if( precision<0 ) precision = 6; /* Set default precision */
  25224. + if( precision>etBUFSIZE-10 ) precision = etBUFSIZE-10;
  25225. + if( realvalue<0.0 ){
  25226. + realvalue = -realvalue;
  25227. + prefix = '-';
  25228. + }else{
  25229. + if( flag_plussign ) prefix = '+';
  25230. + else if( flag_blanksign ) prefix = ' ';
  25231. + else prefix = 0;
  25232. + }
  25233. + if( infop->type==etGENERIC && precision>0 ) precision--;
  25234. + rounder = 0.0;
  25235. +#if 0
  25236. + /* Rounding works like BSD when the constant 0.4999 is used. Wierd! */
  25237. + for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
  25238. +#else
  25239. + /* It makes more sense to use 0.5 */
  25240. + for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1);
  25241. +#endif
  25242. + if( infop->type==etFLOAT ) realvalue += rounder;
  25243. + /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  25244. + exp = 0;
  25245. + if( realvalue>0.0 ){
  25246. + while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
  25247. + while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
  25248. + while( realvalue<1e-8 && exp>=-350 ){ realvalue *= 1e8; exp-=8; }
  25249. + while( realvalue<1.0 && exp>=-350 ){ realvalue *= 10.0; exp--; }
  25250. + if( exp>350 || exp<-350 ){
  25251. + bufpt = "NaN";
  25252. + length = 3;
  25253. + break;
  25254. + }
  25255. + }
  25256. + bufpt = buf;
  25257. + /*
  25258. + ** If the field type is etGENERIC, then convert to either etEXP
  25259. + ** or etFLOAT, as appropriate.
  25260. + */
  25261. + flag_exp = xtype==etEXP;
  25262. + if( xtype!=etFLOAT ){
  25263. + realvalue += rounder;
  25264. + if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  25265. + }
  25266. + if( xtype==etGENERIC ){
  25267. + flag_rtz = !flag_alternateform;
  25268. + if( exp<-4 || exp>precision ){
  25269. + xtype = etEXP;
  25270. + }else{
  25271. + precision = precision - exp;
  25272. + xtype = etFLOAT;
  25273. + }
  25274. + }else{
  25275. + flag_rtz = 0;
  25276. + }
  25277. + /*
  25278. + ** The "exp+precision" test causes output to be of type etEXP if
  25279. + ** the precision is too large to fit in buf[].
  25280. + */
  25281. + nsd = 0;
  25282. + if( xtype==etFLOAT && exp+precision<etBUFSIZE-30 ){
  25283. + flag_dp = (precision>0 || flag_alternateform);
  25284. + if( prefix ) *(bufpt++) = prefix; /* Sign */
  25285. + if( exp<0 ) *(bufpt++) = '0'; /* Digits before "." */
  25286. + else for(; exp>=0; exp--) *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25287. + if( flag_dp ) *(bufpt++) = '.'; /* The decimal point */
  25288. + for(exp++; exp<0 && precision>0; precision--, exp++){
  25289. + *(bufpt++) = '0';
  25290. + }
  25291. + while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25292. + *(bufpt--) = 0; /* Null terminate */
  25293. + if( flag_rtz && flag_dp ){ /* Remove trailing zeros and "." */
  25294. + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
  25295. + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
  25296. + }
  25297. + bufpt++; /* point to next free slot */
  25298. + }else{ /* etEXP or etGENERIC */
  25299. + flag_dp = (precision>0 || flag_alternateform);
  25300. + if( prefix ) *(bufpt++) = prefix; /* Sign */
  25301. + *(bufpt++) = et_getdigit(&realvalue,&nsd); /* First digit */
  25302. + if( flag_dp ) *(bufpt++) = '.'; /* Decimal point */
  25303. + while( (precision--)>0 ) *(bufpt++) = et_getdigit(&realvalue,&nsd);
  25304. + bufpt--; /* point to last digit */
  25305. + if( flag_rtz && flag_dp ){ /* Remove tail zeros */
  25306. + while( bufpt>=buf && *bufpt=='0' ) *(bufpt--) = 0;
  25307. + if( bufpt>=buf && *bufpt=='.' ) *(bufpt--) = 0;
  25308. + }
  25309. + bufpt++; /* point to next free slot */
  25310. + if( exp || flag_exp ){
  25311. + *(bufpt++) = infop->charset[0];
  25312. + if( exp<0 ){ *(bufpt++) = '-'; exp = -exp; } /* sign of exp */
  25313. + else { *(bufpt++) = '+'; }
  25314. + if( exp>=100 ){
  25315. + *(bufpt++) = (exp/100)+'0'; /* 100's digit */
  25316. + exp %= 100;
  25317. + }
  25318. + *(bufpt++) = exp/10+'0'; /* 10's digit */
  25319. + *(bufpt++) = exp%10+'0'; /* 1's digit */
  25320. + }
  25321. + }
  25322. + /* The converted number is in buf[] and zero terminated. Output it.
  25323. + ** Note that the number is in the usual order, not reversed as with
  25324. + ** integer conversions. */
  25325. + length = bufpt-buf;
  25326. + bufpt = buf;
  25327. +
  25328. + /* Special case: Add leading zeros if the flag_zeropad flag is
  25329. + ** set and we are not left justified */
  25330. + if( flag_zeropad && !flag_leftjustify && length < width){
  25331. + int i;
  25332. + int nPad = width - length;
  25333. + for(i=width; i>=nPad; i--){
  25334. + bufpt[i] = bufpt[i-nPad];
  25335. + }
  25336. + i = prefix!=0;
  25337. + while( nPad-- ) bufpt[i++] = '0';
  25338. + length = width;
  25339. + }
  25340. +#endif
  25341. + break;
  25342. + case etSIZE:
  25343. + *(va_arg(ap,int*)) = count;
  25344. + length = width = 0;
  25345. + break;
  25346. + case etPERCENT:
  25347. + buf[0] = '%';
  25348. + bufpt = buf;
  25349. + length = 1;
  25350. + break;
  25351. + case etCHARLIT:
  25352. + case etCHARX:
  25353. + c = buf[0] = (xtype==etCHARX ? va_arg(ap,int) : *++fmt);
  25354. + if( precision>=0 ){
  25355. + for(idx=1; idx<precision; idx++) buf[idx] = c;
  25356. + length = precision;
  25357. + }else{
  25358. + length =1;
  25359. + }
  25360. + bufpt = buf;
  25361. + break;
  25362. + case etSTRING:
  25363. + case etDYNSTRING:
  25364. + bufpt = va_arg(ap,char*);
  25365. + if( bufpt==0 ){
  25366. + bufpt = "";
  25367. + }else if( xtype==etDYNSTRING ){
  25368. + zExtra = bufpt;
  25369. + }
  25370. + length = strlen(bufpt);
  25371. + if( precision>=0 && precision<length ) length = precision;
  25372. + break;
  25373. + case etSQLESCAPE:
  25374. + case etSQLESCAPE2:
  25375. + {
  25376. + int i, j, n, c, isnull;
  25377. + char *arg = va_arg(ap,char*);
  25378. + isnull = arg==0;
  25379. + if( isnull ) arg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  25380. + for(i=n=0; (c=arg[i])!=0; i++){
  25381. + if( c=='\'' ) n++;
  25382. + }
  25383. + n += i + 1 + ((!isnull && xtype==etSQLESCAPE2) ? 2 : 0);
  25384. + if( n>etBUFSIZE ){
  25385. + bufpt = zExtra = sqliteMalloc( n );
  25386. + if( bufpt==0 ) return -1;
  25387. + }else{
  25388. + bufpt = buf;
  25389. + }
  25390. + j = 0;
  25391. + if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
  25392. + for(i=0; (c=arg[i])!=0; i++){
  25393. + bufpt[j++] = c;
  25394. + if( c=='\'' ) bufpt[j++] = c;
  25395. + }
  25396. + if( !isnull && xtype==etSQLESCAPE2 ) bufpt[j++] = '\'';
  25397. + bufpt[j] = 0;
  25398. + length = j;
  25399. + if( precision>=0 && precision<length ) length = precision;
  25400. + }
  25401. + break;
  25402. + case etTOKEN: {
  25403. + Token *pToken = va_arg(ap, Token*);
  25404. + (*func)(arg, pToken->z, pToken->n);
  25405. + length = width = 0;
  25406. + break;
  25407. + }
  25408. + case etSRCLIST: {
  25409. + SrcList *pSrc = va_arg(ap, SrcList*);
  25410. + int k = va_arg(ap, int);
  25411. + struct SrcList_item *pItem = &pSrc->a[k];
  25412. + assert( k>=0 && k<pSrc->nSrc );
  25413. + if( pItem->zDatabase && pItem->zDatabase[0] ){
  25414. + (*func)(arg, pItem->zDatabase, strlen(pItem->zDatabase));
  25415. + (*func)(arg, ".", 1);
  25416. + }
  25417. + (*func)(arg, pItem->zName, strlen(pItem->zName));
  25418. + length = width = 0;
  25419. + break;
  25420. + }
  25421. + case etERROR:
  25422. + buf[0] = '%';
  25423. + buf[1] = c;
  25424. + errorflag = 0;
  25425. + idx = 1+(c!=0);
  25426. + (*func)(arg,"%",idx);
  25427. + count += idx;
  25428. + if( c==0 ) fmt--;
  25429. + break;
  25430. + }/* End switch over the format type */
  25431. + /*
  25432. + ** The text of the conversion is pointed to by "bufpt" and is
  25433. + ** "length" characters long. The field width is "width". Do
  25434. + ** the output.
  25435. + */
  25436. + if( !flag_leftjustify ){
  25437. + register int nspace;
  25438. + nspace = width-length;
  25439. + if( nspace>0 ){
  25440. + count += nspace;
  25441. + while( nspace>=etSPACESIZE ){
  25442. + (*func)(arg,spaces,etSPACESIZE);
  25443. + nspace -= etSPACESIZE;
  25444. + }
  25445. + if( nspace>0 ) (*func)(arg,spaces,nspace);
  25446. + }
  25447. + }
  25448. + if( length>0 ){
  25449. + (*func)(arg,bufpt,length);
  25450. + count += length;
  25451. + }
  25452. + if( flag_leftjustify ){
  25453. + register int nspace;
  25454. + nspace = width-length;
  25455. + if( nspace>0 ){
  25456. + count += nspace;
  25457. + while( nspace>=etSPACESIZE ){
  25458. + (*func)(arg,spaces,etSPACESIZE);
  25459. + nspace -= etSPACESIZE;
  25460. + }
  25461. + if( nspace>0 ) (*func)(arg,spaces,nspace);
  25462. + }
  25463. + }
  25464. + if( zExtra ){
  25465. + sqliteFree(zExtra);
  25466. + }
  25467. + }/* End for loop over the format string */
  25468. + return errorflag ? -1 : count;
  25469. +} /* End of function */
  25470. +
  25471. +
  25472. +/* This structure is used to store state information about the
  25473. +** write to memory that is currently in progress.
  25474. +*/
  25475. +struct sgMprintf {
  25476. + char *zBase; /* A base allocation */
  25477. + char *zText; /* The string collected so far */
  25478. + int nChar; /* Length of the string so far */
  25479. + int nTotal; /* Output size if unconstrained */
  25480. + int nAlloc; /* Amount of space allocated in zText */
  25481. + void *(*xRealloc)(void*,int); /* Function used to realloc memory */
  25482. +};
  25483. +
  25484. +/*
  25485. +** This function implements the callback from vxprintf.
  25486. +**
  25487. +** This routine add nNewChar characters of text in zNewText to
  25488. +** the sgMprintf structure pointed to by "arg".
  25489. +*/
  25490. +static void mout(void *arg, const char *zNewText, int nNewChar){
  25491. + struct sgMprintf *pM = (struct sgMprintf*)arg;
  25492. + pM->nTotal += nNewChar;
  25493. + if( pM->nChar + nNewChar + 1 > pM->nAlloc ){
  25494. + if( pM->xRealloc==0 ){
  25495. + nNewChar = pM->nAlloc - pM->nChar - 1;
  25496. + }else{
  25497. + pM->nAlloc = pM->nChar + nNewChar*2 + 1;
  25498. + if( pM->zText==pM->zBase ){
  25499. + pM->zText = pM->xRealloc(0, pM->nAlloc);
  25500. + if( pM->zText && pM->nChar ){
  25501. + memcpy(pM->zText, pM->zBase, pM->nChar);
  25502. + }
  25503. + }else{
  25504. + pM->zText = pM->xRealloc(pM->zText, pM->nAlloc);
  25505. + }
  25506. + }
  25507. + }
  25508. + if( pM->zText ){
  25509. + if( nNewChar>0 ){
  25510. + memcpy(&pM->zText[pM->nChar], zNewText, nNewChar);
  25511. + pM->nChar += nNewChar;
  25512. + }
  25513. + pM->zText[pM->nChar] = 0;
  25514. + }
  25515. +}
  25516. +
  25517. +/*
  25518. +** This routine is a wrapper around xprintf() that invokes mout() as
  25519. +** the consumer.
  25520. +*/
  25521. +static char *base_vprintf(
  25522. + void *(*xRealloc)(void*,int), /* Routine to realloc memory. May be NULL */
  25523. + int useInternal, /* Use internal %-conversions if true */
  25524. + char *zInitBuf, /* Initially write here, before mallocing */
  25525. + int nInitBuf, /* Size of zInitBuf[] */
  25526. + const char *zFormat, /* format string */
  25527. + va_list ap /* arguments */
  25528. +){
  25529. + struct sgMprintf sM;
  25530. + sM.zBase = sM.zText = zInitBuf;
  25531. + sM.nChar = sM.nTotal = 0;
  25532. + sM.nAlloc = nInitBuf;
  25533. + sM.xRealloc = xRealloc;
  25534. + vxprintf(mout, &sM, useInternal, zFormat, ap);
  25535. + if( xRealloc ){
  25536. + if( sM.zText==sM.zBase ){
  25537. + sM.zText = xRealloc(0, sM.nChar+1);
  25538. + memcpy(sM.zText, sM.zBase, sM.nChar+1);
  25539. + }else if( sM.nAlloc>sM.nChar+10 ){
  25540. + sM.zText = xRealloc(sM.zText, sM.nChar+1);
  25541. + }
  25542. + }
  25543. + return sM.zText;
  25544. +}
  25545. +
  25546. +/*
  25547. +** Realloc that is a real function, not a macro.
  25548. +*/
  25549. +static void *printf_realloc(void *old, int size){
  25550. + return sqliteRealloc(old,size);
  25551. +}
  25552. +
  25553. +/*
  25554. +** Print into memory obtained from sqliteMalloc(). Use the internal
  25555. +** %-conversion extensions.
  25556. +*/
  25557. +char *sqliteVMPrintf(const char *zFormat, va_list ap){
  25558. + char zBase[1000];
  25559. + return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
  25560. +}
  25561. +
  25562. +/*
  25563. +** Print into memory obtained from sqliteMalloc(). Use the internal
  25564. +** %-conversion extensions.
  25565. +*/
  25566. +char *sqliteMPrintf(const char *zFormat, ...){
  25567. + va_list ap;
  25568. + char *z;
  25569. + char zBase[1000];
  25570. + va_start(ap, zFormat);
  25571. + z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap);
  25572. + va_end(ap);
  25573. + return z;
  25574. +}
  25575. +
  25576. +/*
  25577. +** Print into memory obtained from malloc(). Do not use the internal
  25578. +** %-conversion extensions. This routine is for use by external users.
  25579. +*/
  25580. +char *sqlite_mprintf(const char *zFormat, ...){
  25581. + va_list ap;
  25582. + char *z;
  25583. + char zBuf[200];
  25584. +
  25585. + va_start(ap,zFormat);
  25586. + z = base_vprintf((void*(*)(void*,int))realloc, 0,
  25587. + zBuf, sizeof(zBuf), zFormat, ap);
  25588. + va_end(ap);
  25589. + return z;
  25590. +}
  25591. +
  25592. +/* This is the varargs version of sqlite_mprintf.
  25593. +*/
  25594. +char *sqlite_vmprintf(const char *zFormat, va_list ap){
  25595. + char zBuf[200];
  25596. + return base_vprintf((void*(*)(void*,int))realloc, 0,
  25597. + zBuf, sizeof(zBuf), zFormat, ap);
  25598. +}
  25599. +
  25600. +/*
  25601. +** sqlite_snprintf() works like snprintf() except that it ignores the
  25602. +** current locale settings. This is important for SQLite because we
  25603. +** are not able to use a "," as the decimal point in place of "." as
  25604. +** specified by some locales.
  25605. +*/
  25606. +char *sqlite_snprintf(int n, char *zBuf, const char *zFormat, ...){
  25607. + char *z;
  25608. + va_list ap;
  25609. +
  25610. + va_start(ap,zFormat);
  25611. + z = base_vprintf(0, 0, zBuf, n, zFormat, ap);
  25612. + va_end(ap);
  25613. + return z;
  25614. +}
  25615. +
  25616. +/*
  25617. +** The following four routines implement the varargs versions of the
  25618. +** sqlite_exec() and sqlite_get_table() interfaces. See the sqlite.h
  25619. +** header files for a more detailed description of how these interfaces
  25620. +** work.
  25621. +**
  25622. +** These routines are all just simple wrappers.
  25623. +*/
  25624. +int sqlite_exec_printf(
  25625. + sqlite *db, /* An open database */
  25626. + const char *sqlFormat, /* printf-style format string for the SQL */
  25627. + sqlite_callback xCallback, /* Callback function */
  25628. + void *pArg, /* 1st argument to callback function */
  25629. + char **errmsg, /* Error msg written here */
  25630. + ... /* Arguments to the format string. */
  25631. +){
  25632. + va_list ap;
  25633. + int rc;
  25634. +
  25635. + va_start(ap, errmsg);
  25636. + rc = sqlite_exec_vprintf(db, sqlFormat, xCallback, pArg, errmsg, ap);
  25637. + va_end(ap);
  25638. + return rc;
  25639. +}
  25640. +int sqlite_exec_vprintf(
  25641. + sqlite *db, /* An open database */
  25642. + const char *sqlFormat, /* printf-style format string for the SQL */
  25643. + sqlite_callback xCallback, /* Callback function */
  25644. + void *pArg, /* 1st argument to callback function */
  25645. + char **errmsg, /* Error msg written here */
  25646. + va_list ap /* Arguments to the format string. */
  25647. +){
  25648. + char *zSql;
  25649. + int rc;
  25650. +
  25651. + zSql = sqlite_vmprintf(sqlFormat, ap);
  25652. + rc = sqlite_exec(db, zSql, xCallback, pArg, errmsg);
  25653. + free(zSql);
  25654. + return rc;
  25655. +}
  25656. +int sqlite_get_table_printf(
  25657. + sqlite *db, /* An open database */
  25658. + const char *sqlFormat, /* printf-style format string for the SQL */
  25659. + char ***resultp, /* Result written to a char *[] that this points to */
  25660. + int *nrow, /* Number of result rows written here */
  25661. + int *ncol, /* Number of result columns written here */
  25662. + char **errmsg, /* Error msg written here */
  25663. + ... /* Arguments to the format string */
  25664. +){
  25665. + va_list ap;
  25666. + int rc;
  25667. +
  25668. + va_start(ap, errmsg);
  25669. + rc = sqlite_get_table_vprintf(db, sqlFormat, resultp, nrow, ncol, errmsg, ap);
  25670. + va_end(ap);
  25671. + return rc;
  25672. +}
  25673. +int sqlite_get_table_vprintf(
  25674. + sqlite *db, /* An open database */
  25675. + const char *sqlFormat, /* printf-style format string for the SQL */
  25676. + char ***resultp, /* Result written to a char *[] that this points to */
  25677. + int *nrow, /* Number of result rows written here */
  25678. + int *ncolumn, /* Number of result columns written here */
  25679. + char **errmsg, /* Error msg written here */
  25680. + va_list ap /* Arguments to the format string */
  25681. +){
  25682. + char *zSql;
  25683. + int rc;
  25684. +
  25685. + zSql = sqlite_vmprintf(sqlFormat, ap);
  25686. + rc = sqlite_get_table(db, zSql, resultp, nrow, ncolumn, errmsg);
  25687. + free(zSql);
  25688. + return rc;
  25689. +}
  25690. --- /dev/null
  25691. +++ b/ext/sqlite/libsqlite/src/random.c
  25692. @@ -0,0 +1,97 @@
  25693. +/*
  25694. +** 2001 September 15
  25695. +**
  25696. +** The author disclaims copyright to this source code. In place of
  25697. +** a legal notice, here is a blessing:
  25698. +**
  25699. +** May you do good and not evil.
  25700. +** May you find forgiveness for yourself and forgive others.
  25701. +** May you share freely, never taking more than you give.
  25702. +**
  25703. +*************************************************************************
  25704. +** This file contains code to implement a pseudo-random number
  25705. +** generator (PRNG) for SQLite.
  25706. +**
  25707. +** Random numbers are used by some of the database backends in order
  25708. +** to generate random integer keys for tables or random filenames.
  25709. +**
  25710. +** $Id$
  25711. +*/
  25712. +#include "sqliteInt.h"
  25713. +#include "os.h"
  25714. +
  25715. +
  25716. +/*
  25717. +** Get a single 8-bit random value from the RC4 PRNG. The Mutex
  25718. +** must be held while executing this routine.
  25719. +**
  25720. +** Why not just use a library random generator like lrand48() for this?
  25721. +** Because the OP_NewRecno opcode in the VDBE depends on having a very
  25722. +** good source of random numbers. The lrand48() library function may
  25723. +** well be good enough. But maybe not. Or maybe lrand48() has some
  25724. +** subtle problems on some systems that could cause problems. It is hard
  25725. +** to know. To minimize the risk of problems due to bad lrand48()
  25726. +** implementations, SQLite uses this random number generator based
  25727. +** on RC4, which we know works very well.
  25728. +*/
  25729. +static int randomByte(){
  25730. + unsigned char t;
  25731. +
  25732. + /* All threads share a single random number generator.
  25733. + ** This structure is the current state of the generator.
  25734. + */
  25735. + static struct {
  25736. + unsigned char isInit; /* True if initialized */
  25737. + unsigned char i, j; /* State variables */
  25738. + unsigned char s[256]; /* State variables */
  25739. + } prng;
  25740. +
  25741. + /* Initialize the state of the random number generator once,
  25742. + ** the first time this routine is called. The seed value does
  25743. + ** not need to contain a lot of randomness since we are not
  25744. + ** trying to do secure encryption or anything like that...
  25745. + **
  25746. + ** Nothing in this file or anywhere else in SQLite does any kind of
  25747. + ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  25748. + ** number generator) not as an encryption device.
  25749. + */
  25750. + if( !prng.isInit ){
  25751. + int i;
  25752. + char k[256];
  25753. + prng.j = 0;
  25754. + prng.i = 0;
  25755. + sqliteOsRandomSeed(k);
  25756. + for(i=0; i<256; i++){
  25757. + prng.s[i] = i;
  25758. + }
  25759. + for(i=0; i<256; i++){
  25760. + prng.j += prng.s[i] + k[i];
  25761. + t = prng.s[prng.j];
  25762. + prng.s[prng.j] = prng.s[i];
  25763. + prng.s[i] = t;
  25764. + }
  25765. + prng.isInit = 1;
  25766. + }
  25767. +
  25768. + /* Generate and return single random byte
  25769. + */
  25770. + prng.i++;
  25771. + t = prng.s[prng.i];
  25772. + prng.j += t;
  25773. + prng.s[prng.i] = prng.s[prng.j];
  25774. + prng.s[prng.j] = t;
  25775. + t += prng.s[prng.i];
  25776. + return prng.s[t];
  25777. +}
  25778. +
  25779. +/*
  25780. +** Return N random bytes.
  25781. +*/
  25782. +void sqliteRandomness(int N, void *pBuf){
  25783. + unsigned char *zBuf = pBuf;
  25784. + sqliteOsEnterMutex();
  25785. + while( N-- ){
  25786. + *(zBuf++) = randomByte();
  25787. + }
  25788. + sqliteOsLeaveMutex();
  25789. +}
  25790. --- /dev/null
  25791. +++ b/ext/sqlite/libsqlite/src/select.c
  25792. @@ -0,0 +1,2434 @@
  25793. +/*
  25794. +** 2001 September 15
  25795. +**
  25796. +** The author disclaims copyright to this source code. In place of
  25797. +** a legal notice, here is a blessing:
  25798. +**
  25799. +** May you do good and not evil.
  25800. +** May you find forgiveness for yourself and forgive others.
  25801. +** May you share freely, never taking more than you give.
  25802. +**
  25803. +*************************************************************************
  25804. +** This file contains C code routines that are called by the parser
  25805. +** to handle SELECT statements in SQLite.
  25806. +**
  25807. +** $Id$
  25808. +*/
  25809. +#include "sqliteInt.h"
  25810. +
  25811. +
  25812. +/*
  25813. +** Allocate a new Select structure and return a pointer to that
  25814. +** structure.
  25815. +*/
  25816. +Select *sqliteSelectNew(
  25817. + ExprList *pEList, /* which columns to include in the result */
  25818. + SrcList *pSrc, /* the FROM clause -- which tables to scan */
  25819. + Expr *pWhere, /* the WHERE clause */
  25820. + ExprList *pGroupBy, /* the GROUP BY clause */
  25821. + Expr *pHaving, /* the HAVING clause */
  25822. + ExprList *pOrderBy, /* the ORDER BY clause */
  25823. + int isDistinct, /* true if the DISTINCT keyword is present */
  25824. + int nLimit, /* LIMIT value. -1 means not used */
  25825. + int nOffset /* OFFSET value. 0 means no offset */
  25826. +){
  25827. + Select *pNew;
  25828. + pNew = sqliteMalloc( sizeof(*pNew) );
  25829. + if( pNew==0 ){
  25830. + sqliteExprListDelete(pEList);
  25831. + sqliteSrcListDelete(pSrc);
  25832. + sqliteExprDelete(pWhere);
  25833. + sqliteExprListDelete(pGroupBy);
  25834. + sqliteExprDelete(pHaving);
  25835. + sqliteExprListDelete(pOrderBy);
  25836. + }else{
  25837. + if( pEList==0 ){
  25838. + pEList = sqliteExprListAppend(0, sqliteExpr(TK_ALL,0,0,0), 0);
  25839. + }
  25840. + pNew->pEList = pEList;
  25841. + pNew->pSrc = pSrc;
  25842. + pNew->pWhere = pWhere;
  25843. + pNew->pGroupBy = pGroupBy;
  25844. + pNew->pHaving = pHaving;
  25845. + pNew->pOrderBy = pOrderBy;
  25846. + pNew->isDistinct = isDistinct;
  25847. + pNew->op = TK_SELECT;
  25848. + pNew->nLimit = nLimit;
  25849. + pNew->nOffset = nOffset;
  25850. + pNew->iLimit = -1;
  25851. + pNew->iOffset = -1;
  25852. + }
  25853. + return pNew;
  25854. +}
  25855. +
  25856. +/*
  25857. +** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
  25858. +** type of join. Return an integer constant that expresses that type
  25859. +** in terms of the following bit values:
  25860. +**
  25861. +** JT_INNER
  25862. +** JT_OUTER
  25863. +** JT_NATURAL
  25864. +** JT_LEFT
  25865. +** JT_RIGHT
  25866. +**
  25867. +** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  25868. +**
  25869. +** If an illegal or unsupported join type is seen, then still return
  25870. +** a join type, but put an error in the pParse structure.
  25871. +*/
  25872. +int sqliteJoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  25873. + int jointype = 0;
  25874. + Token *apAll[3];
  25875. + Token *p;
  25876. + static struct {
  25877. + const char *zKeyword;
  25878. + int nChar;
  25879. + int code;
  25880. + } keywords[] = {
  25881. + { "natural", 7, JT_NATURAL },
  25882. + { "left", 4, JT_LEFT|JT_OUTER },
  25883. + { "right", 5, JT_RIGHT|JT_OUTER },
  25884. + { "full", 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  25885. + { "outer", 5, JT_OUTER },
  25886. + { "inner", 5, JT_INNER },
  25887. + { "cross", 5, JT_INNER },
  25888. + };
  25889. + int i, j;
  25890. + apAll[0] = pA;
  25891. + apAll[1] = pB;
  25892. + apAll[2] = pC;
  25893. + for(i=0; i<3 && apAll[i]; i++){
  25894. + p = apAll[i];
  25895. + for(j=0; j<sizeof(keywords)/sizeof(keywords[0]); j++){
  25896. + if( p->n==keywords[j].nChar
  25897. + && sqliteStrNICmp(p->z, keywords[j].zKeyword, p->n)==0 ){
  25898. + jointype |= keywords[j].code;
  25899. + break;
  25900. + }
  25901. + }
  25902. + if( j>=sizeof(keywords)/sizeof(keywords[0]) ){
  25903. + jointype |= JT_ERROR;
  25904. + break;
  25905. + }
  25906. + }
  25907. + if(
  25908. + (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  25909. + (jointype & JT_ERROR)!=0
  25910. + ){
  25911. + static Token dummy = { 0, 0 };
  25912. + char *zSp1 = " ", *zSp2 = " ";
  25913. + if( pB==0 ){ pB = &dummy; zSp1 = 0; }
  25914. + if( pC==0 ){ pC = &dummy; zSp2 = 0; }
  25915. + sqliteSetNString(&pParse->zErrMsg, "unknown or unsupported join type: ", 0,
  25916. + pA->z, pA->n, zSp1, 1, pB->z, pB->n, zSp2, 1, pC->z, pC->n, 0);
  25917. + pParse->nErr++;
  25918. + jointype = JT_INNER;
  25919. + }else if( jointype & JT_RIGHT ){
  25920. + sqliteErrorMsg(pParse,
  25921. + "RIGHT and FULL OUTER JOINs are not currently supported");
  25922. + jointype = JT_INNER;
  25923. + }
  25924. + return jointype;
  25925. +}
  25926. +
  25927. +/*
  25928. +** Return the index of a column in a table. Return -1 if the column
  25929. +** is not contained in the table.
  25930. +*/
  25931. +static int columnIndex(Table *pTab, const char *zCol){
  25932. + int i;
  25933. + for(i=0; i<pTab->nCol; i++){
  25934. + if( sqliteStrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  25935. + }
  25936. + return -1;
  25937. +}
  25938. +
  25939. +/*
  25940. +** Add a term to the WHERE expression in *ppExpr that requires the
  25941. +** zCol column to be equal in the two tables pTab1 and pTab2.
  25942. +*/
  25943. +static void addWhereTerm(
  25944. + const char *zCol, /* Name of the column */
  25945. + const Table *pTab1, /* First table */
  25946. + const Table *pTab2, /* Second table */
  25947. + Expr **ppExpr /* Add the equality term to this expression */
  25948. +){
  25949. + Token dummy;
  25950. + Expr *pE1a, *pE1b, *pE1c;
  25951. + Expr *pE2a, *pE2b, *pE2c;
  25952. + Expr *pE;
  25953. +
  25954. + dummy.z = zCol;
  25955. + dummy.n = strlen(zCol);
  25956. + dummy.dyn = 0;
  25957. + pE1a = sqliteExpr(TK_ID, 0, 0, &dummy);
  25958. + pE2a = sqliteExpr(TK_ID, 0, 0, &dummy);
  25959. + dummy.z = pTab1->zName;
  25960. + dummy.n = strlen(dummy.z);
  25961. + pE1b = sqliteExpr(TK_ID, 0, 0, &dummy);
  25962. + dummy.z = pTab2->zName;
  25963. + dummy.n = strlen(dummy.z);
  25964. + pE2b = sqliteExpr(TK_ID, 0, 0, &dummy);
  25965. + pE1c = sqliteExpr(TK_DOT, pE1b, pE1a, 0);
  25966. + pE2c = sqliteExpr(TK_DOT, pE2b, pE2a, 0);
  25967. + pE = sqliteExpr(TK_EQ, pE1c, pE2c, 0);
  25968. + ExprSetProperty(pE, EP_FromJoin);
  25969. + if( *ppExpr ){
  25970. + *ppExpr = sqliteExpr(TK_AND, *ppExpr, pE, 0);
  25971. + }else{
  25972. + *ppExpr = pE;
  25973. + }
  25974. +}
  25975. +
  25976. +/*
  25977. +** Set the EP_FromJoin property on all terms of the given expression.
  25978. +**
  25979. +** The EP_FromJoin property is used on terms of an expression to tell
  25980. +** the LEFT OUTER JOIN processing logic that this term is part of the
  25981. +** join restriction specified in the ON or USING clause and not a part
  25982. +** of the more general WHERE clause. These terms are moved over to the
  25983. +** WHERE clause during join processing but we need to remember that they
  25984. +** originated in the ON or USING clause.
  25985. +*/
  25986. +static void setJoinExpr(Expr *p){
  25987. + while( p ){
  25988. + ExprSetProperty(p, EP_FromJoin);
  25989. + setJoinExpr(p->pLeft);
  25990. + p = p->pRight;
  25991. + }
  25992. +}
  25993. +
  25994. +/*
  25995. +** This routine processes the join information for a SELECT statement.
  25996. +** ON and USING clauses are converted into extra terms of the WHERE clause.
  25997. +** NATURAL joins also create extra WHERE clause terms.
  25998. +**
  25999. +** This routine returns the number of errors encountered.
  26000. +*/
  26001. +static int sqliteProcessJoin(Parse *pParse, Select *p){
  26002. + SrcList *pSrc;
  26003. + int i, j;
  26004. + pSrc = p->pSrc;
  26005. + for(i=0; i<pSrc->nSrc-1; i++){
  26006. + struct SrcList_item *pTerm = &pSrc->a[i];
  26007. + struct SrcList_item *pOther = &pSrc->a[i+1];
  26008. +
  26009. + if( pTerm->pTab==0 || pOther->pTab==0 ) continue;
  26010. +
  26011. + /* When the NATURAL keyword is present, add WHERE clause terms for
  26012. + ** every column that the two tables have in common.
  26013. + */
  26014. + if( pTerm->jointype & JT_NATURAL ){
  26015. + Table *pTab;
  26016. + if( pTerm->pOn || pTerm->pUsing ){
  26017. + sqliteErrorMsg(pParse, "a NATURAL join may not have "
  26018. + "an ON or USING clause", 0);
  26019. + return 1;
  26020. + }
  26021. + pTab = pTerm->pTab;
  26022. + for(j=0; j<pTab->nCol; j++){
  26023. + if( columnIndex(pOther->pTab, pTab->aCol[j].zName)>=0 ){
  26024. + addWhereTerm(pTab->aCol[j].zName, pTab, pOther->pTab, &p->pWhere);
  26025. + }
  26026. + }
  26027. + }
  26028. +
  26029. + /* Disallow both ON and USING clauses in the same join
  26030. + */
  26031. + if( pTerm->pOn && pTerm->pUsing ){
  26032. + sqliteErrorMsg(pParse, "cannot have both ON and USING "
  26033. + "clauses in the same join");
  26034. + return 1;
  26035. + }
  26036. +
  26037. + /* Add the ON clause to the end of the WHERE clause, connected by
  26038. + ** and AND operator.
  26039. + */
  26040. + if( pTerm->pOn ){
  26041. + setJoinExpr(pTerm->pOn);
  26042. + if( p->pWhere==0 ){
  26043. + p->pWhere = pTerm->pOn;
  26044. + }else{
  26045. + p->pWhere = sqliteExpr(TK_AND, p->pWhere, pTerm->pOn, 0);
  26046. + }
  26047. + pTerm->pOn = 0;
  26048. + }
  26049. +
  26050. + /* Create extra terms on the WHERE clause for each column named
  26051. + ** in the USING clause. Example: If the two tables to be joined are
  26052. + ** A and B and the USING clause names X, Y, and Z, then add this
  26053. + ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  26054. + ** Report an error if any column mentioned in the USING clause is
  26055. + ** not contained in both tables to be joined.
  26056. + */
  26057. + if( pTerm->pUsing ){
  26058. + IdList *pList;
  26059. + int j;
  26060. + assert( i<pSrc->nSrc-1 );
  26061. + pList = pTerm->pUsing;
  26062. + for(j=0; j<pList->nId; j++){
  26063. + if( columnIndex(pTerm->pTab, pList->a[j].zName)<0 ||
  26064. + columnIndex(pOther->pTab, pList->a[j].zName)<0 ){
  26065. + sqliteErrorMsg(pParse, "cannot join using column %s - column "
  26066. + "not present in both tables", pList->a[j].zName);
  26067. + return 1;
  26068. + }
  26069. + addWhereTerm(pList->a[j].zName, pTerm->pTab, pOther->pTab, &p->pWhere);
  26070. + }
  26071. + }
  26072. + }
  26073. + return 0;
  26074. +}
  26075. +
  26076. +/*
  26077. +** Delete the given Select structure and all of its substructures.
  26078. +*/
  26079. +void sqliteSelectDelete(Select *p){
  26080. + if( p==0 ) return;
  26081. + sqliteExprListDelete(p->pEList);
  26082. + sqliteSrcListDelete(p->pSrc);
  26083. + sqliteExprDelete(p->pWhere);
  26084. + sqliteExprListDelete(p->pGroupBy);
  26085. + sqliteExprDelete(p->pHaving);
  26086. + sqliteExprListDelete(p->pOrderBy);
  26087. + sqliteSelectDelete(p->pPrior);
  26088. + sqliteFree(p->zSelect);
  26089. + sqliteFree(p);
  26090. +}
  26091. +
  26092. +/*
  26093. +** Delete the aggregate information from the parse structure.
  26094. +*/
  26095. +static void sqliteAggregateInfoReset(Parse *pParse){
  26096. + sqliteFree(pParse->aAgg);
  26097. + pParse->aAgg = 0;
  26098. + pParse->nAgg = 0;
  26099. + pParse->useAgg = 0;
  26100. +}
  26101. +
  26102. +/*
  26103. +** Insert code into "v" that will push the record on the top of the
  26104. +** stack into the sorter.
  26105. +*/
  26106. +static void pushOntoSorter(Parse *pParse, Vdbe *v, ExprList *pOrderBy){
  26107. + char *zSortOrder;
  26108. + int i;
  26109. + zSortOrder = sqliteMalloc( pOrderBy->nExpr + 1 );
  26110. + if( zSortOrder==0 ) return;
  26111. + for(i=0; i<pOrderBy->nExpr; i++){
  26112. + int order = pOrderBy->a[i].sortOrder;
  26113. + int type;
  26114. + int c;
  26115. + if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_TEXT ){
  26116. + type = SQLITE_SO_TEXT;
  26117. + }else if( (order & SQLITE_SO_TYPEMASK)==SQLITE_SO_NUM ){
  26118. + type = SQLITE_SO_NUM;
  26119. + }else if( pParse->db->file_format>=4 ){
  26120. + type = sqliteExprType(pOrderBy->a[i].pExpr);
  26121. + }else{
  26122. + type = SQLITE_SO_NUM;
  26123. + }
  26124. + if( (order & SQLITE_SO_DIRMASK)==SQLITE_SO_ASC ){
  26125. + c = type==SQLITE_SO_TEXT ? 'A' : '+';
  26126. + }else{
  26127. + c = type==SQLITE_SO_TEXT ? 'D' : '-';
  26128. + }
  26129. + zSortOrder[i] = c;
  26130. + sqliteExprCode(pParse, pOrderBy->a[i].pExpr);
  26131. + }
  26132. + zSortOrder[pOrderBy->nExpr] = 0;
  26133. + sqliteVdbeOp3(v, OP_SortMakeKey, pOrderBy->nExpr, 0, zSortOrder, P3_DYNAMIC);
  26134. + sqliteVdbeAddOp(v, OP_SortPut, 0, 0);
  26135. +}
  26136. +
  26137. +/*
  26138. +** This routine adds a P3 argument to the last VDBE opcode that was
  26139. +** inserted. The P3 argument added is a string suitable for the
  26140. +** OP_MakeKey or OP_MakeIdxKey opcodes. The string consists of
  26141. +** characters 't' or 'n' depending on whether or not the various
  26142. +** fields of the key to be generated should be treated as numeric
  26143. +** or as text. See the OP_MakeKey and OP_MakeIdxKey opcode
  26144. +** documentation for additional information about the P3 string.
  26145. +** See also the sqliteAddIdxKeyType() routine.
  26146. +*/
  26147. +void sqliteAddKeyType(Vdbe *v, ExprList *pEList){
  26148. + int nColumn = pEList->nExpr;
  26149. + char *zType = sqliteMalloc( nColumn+1 );
  26150. + int i;
  26151. + if( zType==0 ) return;
  26152. + for(i=0; i<nColumn; i++){
  26153. + zType[i] = sqliteExprType(pEList->a[i].pExpr)==SQLITE_SO_NUM ? 'n' : 't';
  26154. + }
  26155. + zType[i] = 0;
  26156. + sqliteVdbeChangeP3(v, -1, zType, P3_DYNAMIC);
  26157. +}
  26158. +
  26159. +/*
  26160. +** Add code to implement the OFFSET and LIMIT
  26161. +*/
  26162. +static void codeLimiter(
  26163. + Vdbe *v, /* Generate code into this VM */
  26164. + Select *p, /* The SELECT statement being coded */
  26165. + int iContinue, /* Jump here to skip the current record */
  26166. + int iBreak, /* Jump here to end the loop */
  26167. + int nPop /* Number of times to pop stack when jumping */
  26168. +){
  26169. + if( p->iOffset>=0 ){
  26170. + int addr = sqliteVdbeCurrentAddr(v) + 2;
  26171. + if( nPop>0 ) addr++;
  26172. + sqliteVdbeAddOp(v, OP_MemIncr, p->iOffset, addr);
  26173. + if( nPop>0 ){
  26174. + sqliteVdbeAddOp(v, OP_Pop, nPop, 0);
  26175. + }
  26176. + sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
  26177. + }
  26178. + if( p->iLimit>=0 ){
  26179. + sqliteVdbeAddOp(v, OP_MemIncr, p->iLimit, iBreak);
  26180. + }
  26181. +}
  26182. +
  26183. +/*
  26184. +** This routine generates the code for the inside of the inner loop
  26185. +** of a SELECT.
  26186. +**
  26187. +** If srcTab and nColumn are both zero, then the pEList expressions
  26188. +** are evaluated in order to get the data for this row. If nColumn>0
  26189. +** then data is pulled from srcTab and pEList is used only to get the
  26190. +** datatypes for each column.
  26191. +*/
  26192. +static int selectInnerLoop(
  26193. + Parse *pParse, /* The parser context */
  26194. + Select *p, /* The complete select statement being coded */
  26195. + ExprList *pEList, /* List of values being extracted */
  26196. + int srcTab, /* Pull data from this table */
  26197. + int nColumn, /* Number of columns in the source table */
  26198. + ExprList *pOrderBy, /* If not NULL, sort results using this key */
  26199. + int distinct, /* If >=0, make sure results are distinct */
  26200. + int eDest, /* How to dispose of the results */
  26201. + int iParm, /* An argument to the disposal method */
  26202. + int iContinue, /* Jump here to continue with next row */
  26203. + int iBreak /* Jump here to break out of the inner loop */
  26204. +){
  26205. + Vdbe *v = pParse->pVdbe;
  26206. + int i;
  26207. + int hasDistinct; /* True if the DISTINCT keyword is present */
  26208. +
  26209. + if( v==0 ) return 0;
  26210. + assert( pEList!=0 );
  26211. +
  26212. + /* If there was a LIMIT clause on the SELECT statement, then do the check
  26213. + ** to see if this row should be output.
  26214. + */
  26215. + hasDistinct = distinct>=0 && pEList && pEList->nExpr>0;
  26216. + if( pOrderBy==0 && !hasDistinct ){
  26217. + codeLimiter(v, p, iContinue, iBreak, 0);
  26218. + }
  26219. +
  26220. + /* Pull the requested columns.
  26221. + */
  26222. + if( nColumn>0 ){
  26223. + for(i=0; i<nColumn; i++){
  26224. + sqliteVdbeAddOp(v, OP_Column, srcTab, i);
  26225. + }
  26226. + }else{
  26227. + nColumn = pEList->nExpr;
  26228. + for(i=0; i<pEList->nExpr; i++){
  26229. + sqliteExprCode(pParse, pEList->a[i].pExpr);
  26230. + }
  26231. + }
  26232. +
  26233. + /* If the DISTINCT keyword was present on the SELECT statement
  26234. + ** and this row has been seen before, then do not make this row
  26235. + ** part of the result.
  26236. + */
  26237. + if( hasDistinct ){
  26238. +#if NULL_ALWAYS_DISTINCT
  26239. + sqliteVdbeAddOp(v, OP_IsNull, -pEList->nExpr, sqliteVdbeCurrentAddr(v)+7);
  26240. +#endif
  26241. + sqliteVdbeAddOp(v, OP_MakeKey, pEList->nExpr, 1);
  26242. + if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pEList);
  26243. + sqliteVdbeAddOp(v, OP_Distinct, distinct, sqliteVdbeCurrentAddr(v)+3);
  26244. + sqliteVdbeAddOp(v, OP_Pop, pEList->nExpr+1, 0);
  26245. + sqliteVdbeAddOp(v, OP_Goto, 0, iContinue);
  26246. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  26247. + sqliteVdbeAddOp(v, OP_PutStrKey, distinct, 0);
  26248. + if( pOrderBy==0 ){
  26249. + codeLimiter(v, p, iContinue, iBreak, nColumn);
  26250. + }
  26251. + }
  26252. +
  26253. + switch( eDest ){
  26254. + /* In this mode, write each query result to the key of the temporary
  26255. + ** table iParm.
  26256. + */
  26257. + case SRT_Union: {
  26258. + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
  26259. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  26260. + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
  26261. + break;
  26262. + }
  26263. +
  26264. + /* Store the result as data using a unique key.
  26265. + */
  26266. + case SRT_Table:
  26267. + case SRT_TempTable: {
  26268. + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  26269. + if( pOrderBy ){
  26270. + pushOntoSorter(pParse, v, pOrderBy);
  26271. + }else{
  26272. + sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
  26273. + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
  26274. + sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
  26275. + }
  26276. + break;
  26277. + }
  26278. +
  26279. + /* Construct a record from the query result, but instead of
  26280. + ** saving that record, use it as a key to delete elements from
  26281. + ** the temporary table iParm.
  26282. + */
  26283. + case SRT_Except: {
  26284. + int addr;
  26285. + addr = sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, NULL_ALWAYS_DISTINCT);
  26286. + sqliteVdbeAddOp(v, OP_NotFound, iParm, addr+3);
  26287. + sqliteVdbeAddOp(v, OP_Delete, iParm, 0);
  26288. + break;
  26289. + }
  26290. +
  26291. + /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  26292. + ** then there should be a single item on the stack. Write this
  26293. + ** item into the set table with bogus data.
  26294. + */
  26295. + case SRT_Set: {
  26296. + int addr1 = sqliteVdbeCurrentAddr(v);
  26297. + int addr2;
  26298. + assert( nColumn==1 );
  26299. + sqliteVdbeAddOp(v, OP_NotNull, -1, addr1+3);
  26300. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  26301. + addr2 = sqliteVdbeAddOp(v, OP_Goto, 0, 0);
  26302. + if( pOrderBy ){
  26303. + pushOntoSorter(pParse, v, pOrderBy);
  26304. + }else{
  26305. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  26306. + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
  26307. + }
  26308. + sqliteVdbeChangeP2(v, addr2, sqliteVdbeCurrentAddr(v));
  26309. + break;
  26310. + }
  26311. +
  26312. + /* If this is a scalar select that is part of an expression, then
  26313. + ** store the results in the appropriate memory cell and break out
  26314. + ** of the scan loop.
  26315. + */
  26316. + case SRT_Mem: {
  26317. + assert( nColumn==1 );
  26318. + if( pOrderBy ){
  26319. + pushOntoSorter(pParse, v, pOrderBy);
  26320. + }else{
  26321. + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
  26322. + sqliteVdbeAddOp(v, OP_Goto, 0, iBreak);
  26323. + }
  26324. + break;
  26325. + }
  26326. +
  26327. + /* Send the data to the callback function.
  26328. + */
  26329. + case SRT_Callback:
  26330. + case SRT_Sorter: {
  26331. + if( pOrderBy ){
  26332. + sqliteVdbeAddOp(v, OP_SortMakeRec, nColumn, 0);
  26333. + pushOntoSorter(pParse, v, pOrderBy);
  26334. + }else{
  26335. + assert( eDest==SRT_Callback );
  26336. + sqliteVdbeAddOp(v, OP_Callback, nColumn, 0);
  26337. + }
  26338. + break;
  26339. + }
  26340. +
  26341. + /* Invoke a subroutine to handle the results. The subroutine itself
  26342. + ** is responsible for popping the results off of the stack.
  26343. + */
  26344. + case SRT_Subroutine: {
  26345. + if( pOrderBy ){
  26346. + sqliteVdbeAddOp(v, OP_MakeRecord, nColumn, 0);
  26347. + pushOntoSorter(pParse, v, pOrderBy);
  26348. + }else{
  26349. + sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
  26350. + }
  26351. + break;
  26352. + }
  26353. +
  26354. + /* Discard the results. This is used for SELECT statements inside
  26355. + ** the body of a TRIGGER. The purpose of such selects is to call
  26356. + ** user-defined functions that have side effects. We do not care
  26357. + ** about the actual results of the select.
  26358. + */
  26359. + default: {
  26360. + assert( eDest==SRT_Discard );
  26361. + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
  26362. + break;
  26363. + }
  26364. + }
  26365. + return 0;
  26366. +}
  26367. +
  26368. +/*
  26369. +** If the inner loop was generated using a non-null pOrderBy argument,
  26370. +** then the results were placed in a sorter. After the loop is terminated
  26371. +** we need to run the sorter and output the results. The following
  26372. +** routine generates the code needed to do that.
  26373. +*/
  26374. +static void generateSortTail(
  26375. + Select *p, /* The SELECT statement */
  26376. + Vdbe *v, /* Generate code into this VDBE */
  26377. + int nColumn, /* Number of columns of data */
  26378. + int eDest, /* Write the sorted results here */
  26379. + int iParm /* Optional parameter associated with eDest */
  26380. +){
  26381. + int end1 = sqliteVdbeMakeLabel(v);
  26382. + int end2 = sqliteVdbeMakeLabel(v);
  26383. + int addr;
  26384. + if( eDest==SRT_Sorter ) return;
  26385. + sqliteVdbeAddOp(v, OP_Sort, 0, 0);
  26386. + addr = sqliteVdbeAddOp(v, OP_SortNext, 0, end1);
  26387. + codeLimiter(v, p, addr, end2, 1);
  26388. + switch( eDest ){
  26389. + case SRT_Callback: {
  26390. + sqliteVdbeAddOp(v, OP_SortCallback, nColumn, 0);
  26391. + break;
  26392. + }
  26393. + case SRT_Table:
  26394. + case SRT_TempTable: {
  26395. + sqliteVdbeAddOp(v, OP_NewRecno, iParm, 0);
  26396. + sqliteVdbeAddOp(v, OP_Pull, 1, 0);
  26397. + sqliteVdbeAddOp(v, OP_PutIntKey, iParm, 0);
  26398. + break;
  26399. + }
  26400. + case SRT_Set: {
  26401. + assert( nColumn==1 );
  26402. + sqliteVdbeAddOp(v, OP_NotNull, -1, sqliteVdbeCurrentAddr(v)+3);
  26403. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  26404. + sqliteVdbeAddOp(v, OP_Goto, 0, sqliteVdbeCurrentAddr(v)+3);
  26405. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  26406. + sqliteVdbeAddOp(v, OP_PutStrKey, iParm, 0);
  26407. + break;
  26408. + }
  26409. + case SRT_Mem: {
  26410. + assert( nColumn==1 );
  26411. + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
  26412. + sqliteVdbeAddOp(v, OP_Goto, 0, end1);
  26413. + break;
  26414. + }
  26415. + case SRT_Subroutine: {
  26416. + int i;
  26417. + for(i=0; i<nColumn; i++){
  26418. + sqliteVdbeAddOp(v, OP_Column, -1-i, i);
  26419. + }
  26420. + sqliteVdbeAddOp(v, OP_Gosub, 0, iParm);
  26421. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  26422. + break;
  26423. + }
  26424. + default: {
  26425. + /* Do nothing */
  26426. + break;
  26427. + }
  26428. + }
  26429. + sqliteVdbeAddOp(v, OP_Goto, 0, addr);
  26430. + sqliteVdbeResolveLabel(v, end2);
  26431. + sqliteVdbeAddOp(v, OP_Pop, 1, 0);
  26432. + sqliteVdbeResolveLabel(v, end1);
  26433. + sqliteVdbeAddOp(v, OP_SortReset, 0, 0);
  26434. +}
  26435. +
  26436. +/*
  26437. +** Generate code that will tell the VDBE the datatypes of
  26438. +** columns in the result set.
  26439. +**
  26440. +** This routine only generates code if the "PRAGMA show_datatypes=on"
  26441. +** has been executed. The datatypes are reported out in the azCol
  26442. +** parameter to the callback function. The first N azCol[] entries
  26443. +** are the names of the columns, and the second N entries are the
  26444. +** datatypes for the columns.
  26445. +**
  26446. +** The "datatype" for a result that is a column of a type is the
  26447. +** datatype definition extracted from the CREATE TABLE statement.
  26448. +** The datatype for an expression is either TEXT or NUMERIC. The
  26449. +** datatype for a ROWID field is INTEGER.
  26450. +*/
  26451. +static void generateColumnTypes(
  26452. + Parse *pParse, /* Parser context */
  26453. + SrcList *pTabList, /* List of tables */
  26454. + ExprList *pEList /* Expressions defining the result set */
  26455. +){
  26456. + Vdbe *v = pParse->pVdbe;
  26457. + int i, j;
  26458. + for(i=0; i<pEList->nExpr; i++){
  26459. + Expr *p = pEList->a[i].pExpr;
  26460. + char *zType = 0;
  26461. + if( p==0 ) continue;
  26462. + if( p->op==TK_COLUMN && pTabList ){
  26463. + Table *pTab;
  26464. + int iCol = p->iColumn;
  26465. + for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
  26466. + assert( j<pTabList->nSrc );
  26467. + pTab = pTabList->a[j].pTab;
  26468. + if( iCol<0 ) iCol = pTab->iPKey;
  26469. + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  26470. + if( iCol<0 ){
  26471. + zType = "INTEGER";
  26472. + }else{
  26473. + zType = pTab->aCol[iCol].zType;
  26474. + }
  26475. + }else{
  26476. + if( sqliteExprType(p)==SQLITE_SO_TEXT ){
  26477. + zType = "TEXT";
  26478. + }else{
  26479. + zType = "NUMERIC";
  26480. + }
  26481. + }
  26482. + sqliteVdbeOp3(v, OP_ColumnName, i + pEList->nExpr, 0, zType, 0);
  26483. + }
  26484. +}
  26485. +
  26486. +/*
  26487. +** Generate code that will tell the VDBE the names of columns
  26488. +** in the result set. This information is used to provide the
  26489. +** azCol[] values in the callback.
  26490. +*/
  26491. +static void generateColumnNames(
  26492. + Parse *pParse, /* Parser context */
  26493. + SrcList *pTabList, /* List of tables */
  26494. + ExprList *pEList /* Expressions defining the result set */
  26495. +){
  26496. + Vdbe *v = pParse->pVdbe;
  26497. + int i, j;
  26498. + sqlite *db = pParse->db;
  26499. + int fullNames, shortNames;
  26500. +
  26501. + assert( v!=0 );
  26502. + if( pParse->colNamesSet || v==0 || sqlite_malloc_failed ) return;
  26503. + pParse->colNamesSet = 1;
  26504. + fullNames = (db->flags & SQLITE_FullColNames)!=0;
  26505. + shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  26506. + for(i=0; i<pEList->nExpr; i++){
  26507. + Expr *p;
  26508. + int p2 = i==pEList->nExpr-1;
  26509. + p = pEList->a[i].pExpr;
  26510. + if( p==0 ) continue;
  26511. + if( pEList->a[i].zName ){
  26512. + char *zName = pEList->a[i].zName;
  26513. + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
  26514. + continue;
  26515. + }
  26516. + if( p->op==TK_COLUMN && pTabList ){
  26517. + Table *pTab;
  26518. + char *zCol;
  26519. + int iCol = p->iColumn;
  26520. + for(j=0; j<pTabList->nSrc && pTabList->a[j].iCursor!=p->iTable; j++){}
  26521. + assert( j<pTabList->nSrc );
  26522. + pTab = pTabList->a[j].pTab;
  26523. + if( iCol<0 ) iCol = pTab->iPKey;
  26524. + assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  26525. + if( iCol<0 ){
  26526. + zCol = "_ROWID_";
  26527. + }else{
  26528. + zCol = pTab->aCol[iCol].zName;
  26529. + }
  26530. + if( !shortNames && !fullNames && p->span.z && p->span.z[0] ){
  26531. + int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
  26532. + sqliteVdbeCompressSpace(v, addr);
  26533. + }else if( fullNames || (!shortNames && pTabList->nSrc>1) ){
  26534. + char *zName = 0;
  26535. + char *zTab;
  26536. +
  26537. + zTab = pTabList->a[j].zAlias;
  26538. + if( fullNames || zTab==0 ) zTab = pTab->zName;
  26539. + sqliteSetString(&zName, zTab, ".", zCol, 0);
  26540. + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, P3_DYNAMIC);
  26541. + }else{
  26542. + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zCol, 0);
  26543. + }
  26544. + }else if( p->span.z && p->span.z[0] ){
  26545. + int addr = sqliteVdbeOp3(v,OP_ColumnName, i, p2, p->span.z, p->span.n);
  26546. + sqliteVdbeCompressSpace(v, addr);
  26547. + }else{
  26548. + char zName[30];
  26549. + assert( p->op!=TK_COLUMN || pTabList==0 );
  26550. + sprintf(zName, "column%d", i+1);
  26551. + sqliteVdbeOp3(v, OP_ColumnName, i, p2, zName, 0);
  26552. + }
  26553. + }
  26554. +}
  26555. +
  26556. +/*
  26557. +** Name of the connection operator, used for error messages.
  26558. +*/
  26559. +static const char *selectOpName(int id){
  26560. + char *z;
  26561. + switch( id ){
  26562. + case TK_ALL: z = "UNION ALL"; break;
  26563. + case TK_INTERSECT: z = "INTERSECT"; break;
  26564. + case TK_EXCEPT: z = "EXCEPT"; break;
  26565. + default: z = "UNION"; break;
  26566. + }
  26567. + return z;
  26568. +}
  26569. +
  26570. +/*
  26571. +** Forward declaration
  26572. +*/
  26573. +static int fillInColumnList(Parse*, Select*);
  26574. +
  26575. +/*
  26576. +** Given a SELECT statement, generate a Table structure that describes
  26577. +** the result set of that SELECT.
  26578. +*/
  26579. +Table *sqliteResultSetOfSelect(Parse *pParse, char *zTabName, Select *pSelect){
  26580. + Table *pTab;
  26581. + int i, j;
  26582. + ExprList *pEList;
  26583. + Column *aCol;
  26584. +
  26585. + if( fillInColumnList(pParse, pSelect) ){
  26586. + return 0;
  26587. + }
  26588. + pTab = sqliteMalloc( sizeof(Table) );
  26589. + if( pTab==0 ){
  26590. + return 0;
  26591. + }
  26592. + pTab->zName = zTabName ? sqliteStrDup(zTabName) : 0;
  26593. + pEList = pSelect->pEList;
  26594. + pTab->nCol = pEList->nExpr;
  26595. + assert( pTab->nCol>0 );
  26596. + pTab->aCol = aCol = sqliteMalloc( sizeof(pTab->aCol[0])*pTab->nCol );
  26597. + for(i=0; i<pTab->nCol; i++){
  26598. + Expr *p, *pR;
  26599. + if( pEList->a[i].zName ){
  26600. + aCol[i].zName = sqliteStrDup(pEList->a[i].zName);
  26601. + }else if( (p=pEList->a[i].pExpr)->op==TK_DOT
  26602. + && (pR=p->pRight)!=0 && pR->token.z && pR->token.z[0] ){
  26603. + int cnt;
  26604. + sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, 0);
  26605. + for(j=cnt=0; j<i; j++){
  26606. + if( sqliteStrICmp(aCol[j].zName, aCol[i].zName)==0 ){
  26607. + int n;
  26608. + char zBuf[30];
  26609. + sprintf(zBuf,"_%d",++cnt);
  26610. + n = strlen(zBuf);
  26611. + sqliteSetNString(&aCol[i].zName, pR->token.z, pR->token.n, zBuf, n,0);
  26612. + j = -1;
  26613. + }
  26614. + }
  26615. + }else if( p->span.z && p->span.z[0] ){
  26616. + sqliteSetNString(&pTab->aCol[i].zName, p->span.z, p->span.n, 0);
  26617. + }else{
  26618. + char zBuf[30];
  26619. + sprintf(zBuf, "column%d", i+1);
  26620. + aCol[i].zName = sqliteStrDup(zBuf);
  26621. + }
  26622. + sqliteDequote(aCol[i].zName);
  26623. + }
  26624. + pTab->iPKey = -1;
  26625. + return pTab;
  26626. +}
  26627. +
  26628. +/*
  26629. +** For the given SELECT statement, do three things.
  26630. +**
  26631. +** (1) Fill in the pTabList->a[].pTab fields in the SrcList that
  26632. +** defines the set of tables that should be scanned. For views,
  26633. +** fill pTabList->a[].pSelect with a copy of the SELECT statement
  26634. +** that implements the view. A copy is made of the view's SELECT
  26635. +** statement so that we can freely modify or delete that statement
  26636. +** without worrying about messing up the presistent representation
  26637. +** of the view.
  26638. +**
  26639. +** (2) Add terms to the WHERE clause to accomodate the NATURAL keyword
  26640. +** on joins and the ON and USING clause of joins.
  26641. +**
  26642. +** (3) Scan the list of columns in the result set (pEList) looking
  26643. +** for instances of the "*" operator or the TABLE.* operator.
  26644. +** If found, expand each "*" to be every column in every table
  26645. +** and TABLE.* to be every column in TABLE.
  26646. +**
  26647. +** Return 0 on success. If there are problems, leave an error message
  26648. +** in pParse and return non-zero.
  26649. +*/
  26650. +static int fillInColumnList(Parse *pParse, Select *p){
  26651. + int i, j, k, rc;
  26652. + SrcList *pTabList;
  26653. + ExprList *pEList;
  26654. + Table *pTab;
  26655. +
  26656. + if( p==0 || p->pSrc==0 ) return 1;
  26657. + pTabList = p->pSrc;
  26658. + pEList = p->pEList;
  26659. +
  26660. + /* Look up every table in the table list.
  26661. + */
  26662. + for(i=0; i<pTabList->nSrc; i++){
  26663. + if( pTabList->a[i].pTab ){
  26664. + /* This routine has run before! No need to continue */
  26665. + return 0;
  26666. + }
  26667. + if( pTabList->a[i].zName==0 ){
  26668. + /* A sub-query in the FROM clause of a SELECT */
  26669. + assert( pTabList->a[i].pSelect!=0 );
  26670. + if( pTabList->a[i].zAlias==0 ){
  26671. + char zFakeName[60];
  26672. + sprintf(zFakeName, "sqlite_subquery_%p_",
  26673. + (void*)pTabList->a[i].pSelect);
  26674. + sqliteSetString(&pTabList->a[i].zAlias, zFakeName, 0);
  26675. + }
  26676. + pTabList->a[i].pTab = pTab =
  26677. + sqliteResultSetOfSelect(pParse, pTabList->a[i].zAlias,
  26678. + pTabList->a[i].pSelect);
  26679. + if( pTab==0 ){
  26680. + return 1;
  26681. + }
  26682. + /* The isTransient flag indicates that the Table structure has been
  26683. + ** dynamically allocated and may be freed at any time. In other words,
  26684. + ** pTab is not pointing to a persistent table structure that defines
  26685. + ** part of the schema. */
  26686. + pTab->isTransient = 1;
  26687. + }else{
  26688. + /* An ordinary table or view name in the FROM clause */
  26689. + pTabList->a[i].pTab = pTab =
  26690. + sqliteLocateTable(pParse,pTabList->a[i].zName,pTabList->a[i].zDatabase);
  26691. + if( pTab==0 ){
  26692. + return 1;
  26693. + }
  26694. + if( pTab->pSelect ){
  26695. + /* We reach here if the named table is a really a view */
  26696. + if( sqliteViewGetColumnNames(pParse, pTab) ){
  26697. + return 1;
  26698. + }
  26699. + /* If pTabList->a[i].pSelect!=0 it means we are dealing with a
  26700. + ** view within a view. The SELECT structure has already been
  26701. + ** copied by the outer view so we can skip the copy step here
  26702. + ** in the inner view.
  26703. + */
  26704. + if( pTabList->a[i].pSelect==0 ){
  26705. + pTabList->a[i].pSelect = sqliteSelectDup(pTab->pSelect);
  26706. + }
  26707. + }
  26708. + }
  26709. + }
  26710. +
  26711. + /* Process NATURAL keywords, and ON and USING clauses of joins.
  26712. + */
  26713. + if( sqliteProcessJoin(pParse, p) ) return 1;
  26714. +
  26715. + /* For every "*" that occurs in the column list, insert the names of
  26716. + ** all columns in all tables. And for every TABLE.* insert the names
  26717. + ** of all columns in TABLE. The parser inserted a special expression
  26718. + ** with the TK_ALL operator for each "*" that it found in the column list.
  26719. + ** The following code just has to locate the TK_ALL expressions and expand
  26720. + ** each one to the list of all columns in all tables.
  26721. + **
  26722. + ** The first loop just checks to see if there are any "*" operators
  26723. + ** that need expanding.
  26724. + */
  26725. + for(k=0; k<pEList->nExpr; k++){
  26726. + Expr *pE = pEList->a[k].pExpr;
  26727. + if( pE->op==TK_ALL ) break;
  26728. + if( pE->op==TK_DOT && pE->pRight && pE->pRight->op==TK_ALL
  26729. + && pE->pLeft && pE->pLeft->op==TK_ID ) break;
  26730. + }
  26731. + rc = 0;
  26732. + if( k<pEList->nExpr ){
  26733. + /*
  26734. + ** If we get here it means the result set contains one or more "*"
  26735. + ** operators that need to be expanded. Loop through each expression
  26736. + ** in the result set and expand them one by one.
  26737. + */
  26738. + struct ExprList_item *a = pEList->a;
  26739. + ExprList *pNew = 0;
  26740. + for(k=0; k<pEList->nExpr; k++){
  26741. + Expr *pE = a[k].pExpr;
  26742. + if( pE->op!=TK_ALL &&
  26743. + (pE->op!=TK_DOT || pE->pRight==0 || pE->pRight->op!=TK_ALL) ){
  26744. + /* This particular expression does not need to be expanded.
  26745. + */
  26746. + pNew = sqliteExprListAppend(pNew, a[k].pExpr, 0);
  26747. + pNew->a[pNew->nExpr-1].zName = a[k].zName;
  26748. + a[k].pExpr = 0;
  26749. + a[k].zName = 0;
  26750. + }else{
  26751. + /* This expression is a "*" or a "TABLE.*" and needs to be
  26752. + ** expanded. */
  26753. + int tableSeen = 0; /* Set to 1 when TABLE matches */
  26754. + char *zTName; /* text of name of TABLE */
  26755. + if( pE->op==TK_DOT && pE->pLeft ){
  26756. + zTName = sqliteTableNameFromToken(&pE->pLeft->token);
  26757. + }else{
  26758. + zTName = 0;
  26759. + }
  26760. + for(i=0; i<pTabList->nSrc; i++){
  26761. + Table *pTab = pTabList->a[i].pTab;
  26762. + char *zTabName = pTabList->a[i].zAlias;
  26763. + if( zTabName==0 || zTabName[0]==0 ){
  26764. + zTabName = pTab->zName;
  26765. + }
  26766. + if( zTName && (zTabName==0 || zTabName[0]==0 ||
  26767. + sqliteStrICmp(zTName, zTabName)!=0) ){
  26768. + continue;
  26769. + }
  26770. + tableSeen = 1;
  26771. + for(j=0; j<pTab->nCol; j++){
  26772. + Expr *pExpr, *pLeft, *pRight;
  26773. + char *zName = pTab->aCol[j].zName;
  26774. +
  26775. + if( i>0 && (pTabList->a[i-1].jointype & JT_NATURAL)!=0 &&
  26776. + columnIndex(pTabList->a[i-1].pTab, zName)>=0 ){
  26777. + /* In a NATURAL join, omit the join columns from the
  26778. + ** table on the right */
  26779. + continue;
  26780. + }
  26781. + if( i>0 && sqliteIdListIndex(pTabList->a[i-1].pUsing, zName)>=0 ){
  26782. + /* In a join with a USING clause, omit columns in the
  26783. + ** using clause from the table on the right. */
  26784. + continue;
  26785. + }
  26786. + pRight = sqliteExpr(TK_ID, 0, 0, 0);
  26787. + if( pRight==0 ) break;
  26788. + pRight->token.z = zName;
  26789. + pRight->token.n = strlen(zName);
  26790. + pRight->token.dyn = 0;
  26791. + if( zTabName && pTabList->nSrc>1 ){
  26792. + pLeft = sqliteExpr(TK_ID, 0, 0, 0);
  26793. + pExpr = sqliteExpr(TK_DOT, pLeft, pRight, 0);
  26794. + if( pExpr==0 ) break;
  26795. + pLeft->token.z = zTabName;
  26796. + pLeft->token.n = strlen(zTabName);
  26797. + pLeft->token.dyn = 0;
  26798. + sqliteSetString((char**)&pExpr->span.z, zTabName, ".", zName, 0);
  26799. + pExpr->span.n = strlen(pExpr->span.z);
  26800. + pExpr->span.dyn = 1;
  26801. + pExpr->token.z = 0;
  26802. + pExpr->token.n = 0;
  26803. + pExpr->token.dyn = 0;
  26804. + }else{
  26805. + pExpr = pRight;
  26806. + pExpr->span = pExpr->token;
  26807. + }
  26808. + pNew = sqliteExprListAppend(pNew, pExpr, 0);
  26809. + }
  26810. + }
  26811. + if( !tableSeen ){
  26812. + if( zTName ){
  26813. + sqliteErrorMsg(pParse, "no such table: %s", zTName);
  26814. + }else{
  26815. + sqliteErrorMsg(pParse, "no tables specified");
  26816. + }
  26817. + rc = 1;
  26818. + }
  26819. + sqliteFree(zTName);
  26820. + }
  26821. + }
  26822. + sqliteExprListDelete(pEList);
  26823. + p->pEList = pNew;
  26824. + }
  26825. + return rc;
  26826. +}
  26827. +
  26828. +/*
  26829. +** This routine recursively unlinks the Select.pSrc.a[].pTab pointers
  26830. +** in a select structure. It just sets the pointers to NULL. This
  26831. +** routine is recursive in the sense that if the Select.pSrc.a[].pSelect
  26832. +** pointer is not NULL, this routine is called recursively on that pointer.
  26833. +**
  26834. +** This routine is called on the Select structure that defines a
  26835. +** VIEW in order to undo any bindings to tables. This is necessary
  26836. +** because those tables might be DROPed by a subsequent SQL command.
  26837. +** If the bindings are not removed, then the Select.pSrc->a[].pTab field
  26838. +** will be left pointing to a deallocated Table structure after the
  26839. +** DROP and a coredump will occur the next time the VIEW is used.
  26840. +*/
  26841. +void sqliteSelectUnbind(Select *p){
  26842. + int i;
  26843. + SrcList *pSrc = p->pSrc;
  26844. + Table *pTab;
  26845. + if( p==0 ) return;
  26846. + for(i=0; i<pSrc->nSrc; i++){
  26847. + if( (pTab = pSrc->a[i].pTab)!=0 ){
  26848. + if( pTab->isTransient ){
  26849. + sqliteDeleteTable(0, pTab);
  26850. + }
  26851. + pSrc->a[i].pTab = 0;
  26852. + if( pSrc->a[i].pSelect ){
  26853. + sqliteSelectUnbind(pSrc->a[i].pSelect);
  26854. + }
  26855. + }
  26856. + }
  26857. +}
  26858. +
  26859. +/*
  26860. +** This routine associates entries in an ORDER BY expression list with
  26861. +** columns in a result. For each ORDER BY expression, the opcode of
  26862. +** the top-level node is changed to TK_COLUMN and the iColumn value of
  26863. +** the top-level node is filled in with column number and the iTable
  26864. +** value of the top-level node is filled with iTable parameter.
  26865. +**
  26866. +** If there are prior SELECT clauses, they are processed first. A match
  26867. +** in an earlier SELECT takes precedence over a later SELECT.
  26868. +**
  26869. +** Any entry that does not match is flagged as an error. The number
  26870. +** of errors is returned.
  26871. +**
  26872. +** This routine does NOT correctly initialize the Expr.dataType field
  26873. +** of the ORDER BY expressions. The multiSelectSortOrder() routine
  26874. +** must be called to do that after the individual select statements
  26875. +** have all been analyzed. This routine is unable to compute Expr.dataType
  26876. +** because it must be called before the individual select statements
  26877. +** have been analyzed.
  26878. +*/
  26879. +static int matchOrderbyToColumn(
  26880. + Parse *pParse, /* A place to leave error messages */
  26881. + Select *pSelect, /* Match to result columns of this SELECT */
  26882. + ExprList *pOrderBy, /* The ORDER BY values to match against columns */
  26883. + int iTable, /* Insert this value in iTable */
  26884. + int mustComplete /* If TRUE all ORDER BYs must match */
  26885. +){
  26886. + int nErr = 0;
  26887. + int i, j;
  26888. + ExprList *pEList;
  26889. +
  26890. + if( pSelect==0 || pOrderBy==0 ) return 1;
  26891. + if( mustComplete ){
  26892. + for(i=0; i<pOrderBy->nExpr; i++){ pOrderBy->a[i].done = 0; }
  26893. + }
  26894. + if( fillInColumnList(pParse, pSelect) ){
  26895. + return 1;
  26896. + }
  26897. + if( pSelect->pPrior ){
  26898. + if( matchOrderbyToColumn(pParse, pSelect->pPrior, pOrderBy, iTable, 0) ){
  26899. + return 1;
  26900. + }
  26901. + }
  26902. + pEList = pSelect->pEList;
  26903. + for(i=0; i<pOrderBy->nExpr; i++){
  26904. + Expr *pE = pOrderBy->a[i].pExpr;
  26905. + int iCol = -1;
  26906. + if( pOrderBy->a[i].done ) continue;
  26907. + if( sqliteExprIsInteger(pE, &iCol) ){
  26908. + if( iCol<=0 || iCol>pEList->nExpr ){
  26909. + sqliteErrorMsg(pParse,
  26910. + "ORDER BY position %d should be between 1 and %d",
  26911. + iCol, pEList->nExpr);
  26912. + nErr++;
  26913. + break;
  26914. + }
  26915. + if( !mustComplete ) continue;
  26916. + iCol--;
  26917. + }
  26918. + for(j=0; iCol<0 && j<pEList->nExpr; j++){
  26919. + if( pEList->a[j].zName && (pE->op==TK_ID || pE->op==TK_STRING) ){
  26920. + char *zName, *zLabel;
  26921. + zName = pEList->a[j].zName;
  26922. + assert( pE->token.z );
  26923. + zLabel = sqliteStrNDup(pE->token.z, pE->token.n);
  26924. + sqliteDequote(zLabel);
  26925. + if( sqliteStrICmp(zName, zLabel)==0 ){
  26926. + iCol = j;
  26927. + }
  26928. + sqliteFree(zLabel);
  26929. + }
  26930. + if( iCol<0 && sqliteExprCompare(pE, pEList->a[j].pExpr) ){
  26931. + iCol = j;
  26932. + }
  26933. + }
  26934. + if( iCol>=0 ){
  26935. + pE->op = TK_COLUMN;
  26936. + pE->iColumn = iCol;
  26937. + pE->iTable = iTable;
  26938. + pOrderBy->a[i].done = 1;
  26939. + }
  26940. + if( iCol<0 && mustComplete ){
  26941. + sqliteErrorMsg(pParse,
  26942. + "ORDER BY term number %d does not match any result column", i+1);
  26943. + nErr++;
  26944. + break;
  26945. + }
  26946. + }
  26947. + return nErr;
  26948. +}
  26949. +
  26950. +/*
  26951. +** Get a VDBE for the given parser context. Create a new one if necessary.
  26952. +** If an error occurs, return NULL and leave a message in pParse.
  26953. +*/
  26954. +Vdbe *sqliteGetVdbe(Parse *pParse){
  26955. + Vdbe *v = pParse->pVdbe;
  26956. + if( v==0 ){
  26957. + v = pParse->pVdbe = sqliteVdbeCreate(pParse->db);
  26958. + }
  26959. + return v;
  26960. +}
  26961. +
  26962. +/*
  26963. +** This routine sets the Expr.dataType field on all elements of
  26964. +** the pOrderBy expression list. The pOrderBy list will have been
  26965. +** set up by matchOrderbyToColumn(). Hence each expression has
  26966. +** a TK_COLUMN as its root node. The Expr.iColumn refers to a
  26967. +** column in the result set. The datatype is set to SQLITE_SO_TEXT
  26968. +** if the corresponding column in p and every SELECT to the left of
  26969. +** p has a datatype of SQLITE_SO_TEXT. If the cooressponding column
  26970. +** in p or any of the left SELECTs is SQLITE_SO_NUM, then the datatype
  26971. +** of the order-by expression is set to SQLITE_SO_NUM.
  26972. +**
  26973. +** Examples:
  26974. +**
  26975. +** CREATE TABLE one(a INTEGER, b TEXT);
  26976. +** CREATE TABLE two(c VARCHAR(5), d FLOAT);
  26977. +**
  26978. +** SELECT b, b FROM one UNION SELECT d, c FROM two ORDER BY 1, 2;
  26979. +**
  26980. +** The primary sort key will use SQLITE_SO_NUM because the "d" in
  26981. +** the second SELECT is numeric. The 1st column of the first SELECT
  26982. +** is text but that does not matter because a numeric always overrides
  26983. +** a text.
  26984. +**
  26985. +** The secondary key will use the SQLITE_SO_TEXT sort order because
  26986. +** both the (second) "b" in the first SELECT and the "c" in the second
  26987. +** SELECT have a datatype of text.
  26988. +*/
  26989. +static void multiSelectSortOrder(Select *p, ExprList *pOrderBy){
  26990. + int i;
  26991. + ExprList *pEList;
  26992. + if( pOrderBy==0 ) return;
  26993. + if( p==0 ){
  26994. + for(i=0; i<pOrderBy->nExpr; i++){
  26995. + pOrderBy->a[i].pExpr->dataType = SQLITE_SO_TEXT;
  26996. + }
  26997. + return;
  26998. + }
  26999. + multiSelectSortOrder(p->pPrior, pOrderBy);
  27000. + pEList = p->pEList;
  27001. + for(i=0; i<pOrderBy->nExpr; i++){
  27002. + Expr *pE = pOrderBy->a[i].pExpr;
  27003. + if( pE->dataType==SQLITE_SO_NUM ) continue;
  27004. + assert( pE->iColumn>=0 );
  27005. + if( pEList->nExpr>pE->iColumn ){
  27006. + pE->dataType = sqliteExprType(pEList->a[pE->iColumn].pExpr);
  27007. + }
  27008. + }
  27009. +}
  27010. +
  27011. +/*
  27012. +** Compute the iLimit and iOffset fields of the SELECT based on the
  27013. +** nLimit and nOffset fields. nLimit and nOffset hold the integers
  27014. +** that appear in the original SQL statement after the LIMIT and OFFSET
  27015. +** keywords. Or that hold -1 and 0 if those keywords are omitted.
  27016. +** iLimit and iOffset are the integer memory register numbers for
  27017. +** counters used to compute the limit and offset. If there is no
  27018. +** limit and/or offset, then iLimit and iOffset are negative.
  27019. +**
  27020. +** This routine changes the values if iLimit and iOffset only if
  27021. +** a limit or offset is defined by nLimit and nOffset. iLimit and
  27022. +** iOffset should have been preset to appropriate default values
  27023. +** (usually but not always -1) prior to calling this routine.
  27024. +** Only if nLimit>=0 or nOffset>0 do the limit registers get
  27025. +** redefined. The UNION ALL operator uses this property to force
  27026. +** the reuse of the same limit and offset registers across multiple
  27027. +** SELECT statements.
  27028. +*/
  27029. +static void computeLimitRegisters(Parse *pParse, Select *p){
  27030. + /*
  27031. + ** If the comparison is p->nLimit>0 then "LIMIT 0" shows
  27032. + ** all rows. It is the same as no limit. If the comparision is
  27033. + ** p->nLimit>=0 then "LIMIT 0" show no rows at all.
  27034. + ** "LIMIT -1" always shows all rows. There is some
  27035. + ** contraversy about what the correct behavior should be.
  27036. + ** The current implementation interprets "LIMIT 0" to mean
  27037. + ** no rows.
  27038. + */
  27039. + if( p->nLimit>=0 ){
  27040. + int iMem = pParse->nMem++;
  27041. + Vdbe *v = sqliteGetVdbe(pParse);
  27042. + if( v==0 ) return;
  27043. + sqliteVdbeAddOp(v, OP_Integer, -p->nLimit, 0);
  27044. + sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
  27045. + p->iLimit = iMem;
  27046. + }
  27047. + if( p->nOffset>0 ){
  27048. + int iMem = pParse->nMem++;
  27049. + Vdbe *v = sqliteGetVdbe(pParse);
  27050. + if( v==0 ) return;
  27051. + sqliteVdbeAddOp(v, OP_Integer, -p->nOffset, 0);
  27052. + sqliteVdbeAddOp(v, OP_MemStore, iMem, 1);
  27053. + p->iOffset = iMem;
  27054. + }
  27055. +}
  27056. +
  27057. +/*
  27058. +** This routine is called to process a query that is really the union
  27059. +** or intersection of two or more separate queries.
  27060. +**
  27061. +** "p" points to the right-most of the two queries. the query on the
  27062. +** left is p->pPrior. The left query could also be a compound query
  27063. +** in which case this routine will be called recursively.
  27064. +**
  27065. +** The results of the total query are to be written into a destination
  27066. +** of type eDest with parameter iParm.
  27067. +**
  27068. +** Example 1: Consider a three-way compound SQL statement.
  27069. +**
  27070. +** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  27071. +**
  27072. +** This statement is parsed up as follows:
  27073. +**
  27074. +** SELECT c FROM t3
  27075. +** |
  27076. +** `-----> SELECT b FROM t2
  27077. +** |
  27078. +** `------> SELECT a FROM t1
  27079. +**
  27080. +** The arrows in the diagram above represent the Select.pPrior pointer.
  27081. +** So if this routine is called with p equal to the t3 query, then
  27082. +** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  27083. +**
  27084. +** Notice that because of the way SQLite parses compound SELECTs, the
  27085. +** individual selects always group from left to right.
  27086. +*/
  27087. +static int multiSelect(Parse *pParse, Select *p, int eDest, int iParm){
  27088. + int rc; /* Success code from a subroutine */
  27089. + Select *pPrior; /* Another SELECT immediately to our left */
  27090. + Vdbe *v; /* Generate code to this VDBE */
  27091. +
  27092. + /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  27093. + ** the last SELECT in the series may have an ORDER BY or LIMIT.
  27094. + */
  27095. + if( p==0 || p->pPrior==0 ) return 1;
  27096. + pPrior = p->pPrior;
  27097. + if( pPrior->pOrderBy ){
  27098. + sqliteErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  27099. + selectOpName(p->op));
  27100. + return 1;
  27101. + }
  27102. + if( pPrior->nLimit>=0 || pPrior->nOffset>0 ){
  27103. + sqliteErrorMsg(pParse,"LIMIT clause should come after %s not before",
  27104. + selectOpName(p->op));
  27105. + return 1;
  27106. + }
  27107. +
  27108. + /* Make sure we have a valid query engine. If not, create a new one.
  27109. + */
  27110. + v = sqliteGetVdbe(pParse);
  27111. + if( v==0 ) return 1;
  27112. +
  27113. + /* Create the destination temporary table if necessary
  27114. + */
  27115. + if( eDest==SRT_TempTable ){
  27116. + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
  27117. + eDest = SRT_Table;
  27118. + }
  27119. +
  27120. + /* Generate code for the left and right SELECT statements.
  27121. + */
  27122. + switch( p->op ){
  27123. + case TK_ALL: {
  27124. + if( p->pOrderBy==0 ){
  27125. + pPrior->nLimit = p->nLimit;
  27126. + pPrior->nOffset = p->nOffset;
  27127. + rc = sqliteSelect(pParse, pPrior, eDest, iParm, 0, 0, 0);
  27128. + if( rc ) return rc;
  27129. + p->pPrior = 0;
  27130. + p->iLimit = pPrior->iLimit;
  27131. + p->iOffset = pPrior->iOffset;
  27132. + p->nLimit = -1;
  27133. + p->nOffset = 0;
  27134. + rc = sqliteSelect(pParse, p, eDest, iParm, 0, 0, 0);
  27135. + p->pPrior = pPrior;
  27136. + if( rc ) return rc;
  27137. + break;
  27138. + }
  27139. + /* For UNION ALL ... ORDER BY fall through to the next case */
  27140. + }
  27141. + case TK_EXCEPT:
  27142. + case TK_UNION: {
  27143. + int unionTab; /* Cursor number of the temporary table holding result */
  27144. + int op; /* One of the SRT_ operations to apply to self */
  27145. + int priorOp; /* The SRT_ operation to apply to prior selects */
  27146. + int nLimit, nOffset; /* Saved values of p->nLimit and p->nOffset */
  27147. + ExprList *pOrderBy; /* The ORDER BY clause for the right SELECT */
  27148. +
  27149. + priorOp = p->op==TK_ALL ? SRT_Table : SRT_Union;
  27150. + if( eDest==priorOp && p->pOrderBy==0 && p->nLimit<0 && p->nOffset==0 ){
  27151. + /* We can reuse a temporary table generated by a SELECT to our
  27152. + ** right.
  27153. + */
  27154. + unionTab = iParm;
  27155. + }else{
  27156. + /* We will need to create our own temporary table to hold the
  27157. + ** intermediate results.
  27158. + */
  27159. + unionTab = pParse->nTab++;
  27160. + if( p->pOrderBy
  27161. + && matchOrderbyToColumn(pParse, p, p->pOrderBy, unionTab, 1) ){
  27162. + return 1;
  27163. + }
  27164. + if( p->op!=TK_ALL ){
  27165. + sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 1);
  27166. + sqliteVdbeAddOp(v, OP_KeyAsData, unionTab, 1);
  27167. + }else{
  27168. + sqliteVdbeAddOp(v, OP_OpenTemp, unionTab, 0);
  27169. + }
  27170. + }
  27171. +
  27172. + /* Code the SELECT statements to our left
  27173. + */
  27174. + rc = sqliteSelect(pParse, pPrior, priorOp, unionTab, 0, 0, 0);
  27175. + if( rc ) return rc;
  27176. +
  27177. + /* Code the current SELECT statement
  27178. + */
  27179. + switch( p->op ){
  27180. + case TK_EXCEPT: op = SRT_Except; break;
  27181. + case TK_UNION: op = SRT_Union; break;
  27182. + case TK_ALL: op = SRT_Table; break;
  27183. + }
  27184. + p->pPrior = 0;
  27185. + pOrderBy = p->pOrderBy;
  27186. + p->pOrderBy = 0;
  27187. + nLimit = p->nLimit;
  27188. + p->nLimit = -1;
  27189. + nOffset = p->nOffset;
  27190. + p->nOffset = 0;
  27191. + rc = sqliteSelect(pParse, p, op, unionTab, 0, 0, 0);
  27192. + p->pPrior = pPrior;
  27193. + p->pOrderBy = pOrderBy;
  27194. + p->nLimit = nLimit;
  27195. + p->nOffset = nOffset;
  27196. + if( rc ) return rc;
  27197. +
  27198. + /* Convert the data in the temporary table into whatever form
  27199. + ** it is that we currently need.
  27200. + */
  27201. + if( eDest!=priorOp || unionTab!=iParm ){
  27202. + int iCont, iBreak, iStart;
  27203. + assert( p->pEList );
  27204. + if( eDest==SRT_Callback ){
  27205. + generateColumnNames(pParse, 0, p->pEList);
  27206. + generateColumnTypes(pParse, p->pSrc, p->pEList);
  27207. + }
  27208. + iBreak = sqliteVdbeMakeLabel(v);
  27209. + iCont = sqliteVdbeMakeLabel(v);
  27210. + sqliteVdbeAddOp(v, OP_Rewind, unionTab, iBreak);
  27211. + computeLimitRegisters(pParse, p);
  27212. + iStart = sqliteVdbeCurrentAddr(v);
  27213. + multiSelectSortOrder(p, p->pOrderBy);
  27214. + rc = selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
  27215. + p->pOrderBy, -1, eDest, iParm,
  27216. + iCont, iBreak);
  27217. + if( rc ) return 1;
  27218. + sqliteVdbeResolveLabel(v, iCont);
  27219. + sqliteVdbeAddOp(v, OP_Next, unionTab, iStart);
  27220. + sqliteVdbeResolveLabel(v, iBreak);
  27221. + sqliteVdbeAddOp(v, OP_Close, unionTab, 0);
  27222. + if( p->pOrderBy ){
  27223. + generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
  27224. + }
  27225. + }
  27226. + break;
  27227. + }
  27228. + case TK_INTERSECT: {
  27229. + int tab1, tab2;
  27230. + int iCont, iBreak, iStart;
  27231. + int nLimit, nOffset;
  27232. +
  27233. + /* INTERSECT is different from the others since it requires
  27234. + ** two temporary tables. Hence it has its own case. Begin
  27235. + ** by allocating the tables we will need.
  27236. + */
  27237. + tab1 = pParse->nTab++;
  27238. + tab2 = pParse->nTab++;
  27239. + if( p->pOrderBy && matchOrderbyToColumn(pParse,p,p->pOrderBy,tab1,1) ){
  27240. + return 1;
  27241. + }
  27242. + sqliteVdbeAddOp(v, OP_OpenTemp, tab1, 1);
  27243. + sqliteVdbeAddOp(v, OP_KeyAsData, tab1, 1);
  27244. +
  27245. + /* Code the SELECTs to our left into temporary table "tab1".
  27246. + */
  27247. + rc = sqliteSelect(pParse, pPrior, SRT_Union, tab1, 0, 0, 0);
  27248. + if( rc ) return rc;
  27249. +
  27250. + /* Code the current SELECT into temporary table "tab2"
  27251. + */
  27252. + sqliteVdbeAddOp(v, OP_OpenTemp, tab2, 1);
  27253. + sqliteVdbeAddOp(v, OP_KeyAsData, tab2, 1);
  27254. + p->pPrior = 0;
  27255. + nLimit = p->nLimit;
  27256. + p->nLimit = -1;
  27257. + nOffset = p->nOffset;
  27258. + p->nOffset = 0;
  27259. + rc = sqliteSelect(pParse, p, SRT_Union, tab2, 0, 0, 0);
  27260. + p->pPrior = pPrior;
  27261. + p->nLimit = nLimit;
  27262. + p->nOffset = nOffset;
  27263. + if( rc ) return rc;
  27264. +
  27265. + /* Generate code to take the intersection of the two temporary
  27266. + ** tables.
  27267. + */
  27268. + assert( p->pEList );
  27269. + if( eDest==SRT_Callback ){
  27270. + generateColumnNames(pParse, 0, p->pEList);
  27271. + generateColumnTypes(pParse, p->pSrc, p->pEList);
  27272. + }
  27273. + iBreak = sqliteVdbeMakeLabel(v);
  27274. + iCont = sqliteVdbeMakeLabel(v);
  27275. + sqliteVdbeAddOp(v, OP_Rewind, tab1, iBreak);
  27276. + computeLimitRegisters(pParse, p);
  27277. + iStart = sqliteVdbeAddOp(v, OP_FullKey, tab1, 0);
  27278. + sqliteVdbeAddOp(v, OP_NotFound, tab2, iCont);
  27279. + multiSelectSortOrder(p, p->pOrderBy);
  27280. + rc = selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
  27281. + p->pOrderBy, -1, eDest, iParm,
  27282. + iCont, iBreak);
  27283. + if( rc ) return 1;
  27284. + sqliteVdbeResolveLabel(v, iCont);
  27285. + sqliteVdbeAddOp(v, OP_Next, tab1, iStart);
  27286. + sqliteVdbeResolveLabel(v, iBreak);
  27287. + sqliteVdbeAddOp(v, OP_Close, tab2, 0);
  27288. + sqliteVdbeAddOp(v, OP_Close, tab1, 0);
  27289. + if( p->pOrderBy ){
  27290. + generateSortTail(p, v, p->pEList->nExpr, eDest, iParm);
  27291. + }
  27292. + break;
  27293. + }
  27294. + }
  27295. + assert( p->pEList && pPrior->pEList );
  27296. + if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  27297. + sqliteErrorMsg(pParse, "SELECTs to the left and right of %s"
  27298. + " do not have the same number of result columns", selectOpName(p->op));
  27299. + return 1;
  27300. + }
  27301. + return 0;
  27302. +}
  27303. +
  27304. +/*
  27305. +** Scan through the expression pExpr. Replace every reference to
  27306. +** a column in table number iTable with a copy of the iColumn-th
  27307. +** entry in pEList. (But leave references to the ROWID column
  27308. +** unchanged.)
  27309. +**
  27310. +** This routine is part of the flattening procedure. A subquery
  27311. +** whose result set is defined by pEList appears as entry in the
  27312. +** FROM clause of a SELECT such that the VDBE cursor assigned to that
  27313. +** FORM clause entry is iTable. This routine make the necessary
  27314. +** changes to pExpr so that it refers directly to the source table
  27315. +** of the subquery rather the result set of the subquery.
  27316. +*/
  27317. +static void substExprList(ExprList*,int,ExprList*); /* Forward Decl */
  27318. +static void substExpr(Expr *pExpr, int iTable, ExprList *pEList){
  27319. + if( pExpr==0 ) return;
  27320. + if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  27321. + if( pExpr->iColumn<0 ){
  27322. + pExpr->op = TK_NULL;
  27323. + }else{
  27324. + Expr *pNew;
  27325. + assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  27326. + assert( pExpr->pLeft==0 && pExpr->pRight==0 && pExpr->pList==0 );
  27327. + pNew = pEList->a[pExpr->iColumn].pExpr;
  27328. + assert( pNew!=0 );
  27329. + pExpr->op = pNew->op;
  27330. + pExpr->dataType = pNew->dataType;
  27331. + assert( pExpr->pLeft==0 );
  27332. + pExpr->pLeft = sqliteExprDup(pNew->pLeft);
  27333. + assert( pExpr->pRight==0 );
  27334. + pExpr->pRight = sqliteExprDup(pNew->pRight);
  27335. + assert( pExpr->pList==0 );
  27336. + pExpr->pList = sqliteExprListDup(pNew->pList);
  27337. + pExpr->iTable = pNew->iTable;
  27338. + pExpr->iColumn = pNew->iColumn;
  27339. + pExpr->iAgg = pNew->iAgg;
  27340. + sqliteTokenCopy(&pExpr->token, &pNew->token);
  27341. + sqliteTokenCopy(&pExpr->span, &pNew->span);
  27342. + }
  27343. + }else{
  27344. + substExpr(pExpr->pLeft, iTable, pEList);
  27345. + substExpr(pExpr->pRight, iTable, pEList);
  27346. + substExprList(pExpr->pList, iTable, pEList);
  27347. + }
  27348. +}
  27349. +static void
  27350. +substExprList(ExprList *pList, int iTable, ExprList *pEList){
  27351. + int i;
  27352. + if( pList==0 ) return;
  27353. + for(i=0; i<pList->nExpr; i++){
  27354. + substExpr(pList->a[i].pExpr, iTable, pEList);
  27355. + }
  27356. +}
  27357. +
  27358. +/*
  27359. +** This routine attempts to flatten subqueries in order to speed
  27360. +** execution. It returns 1 if it makes changes and 0 if no flattening
  27361. +** occurs.
  27362. +**
  27363. +** To understand the concept of flattening, consider the following
  27364. +** query:
  27365. +**
  27366. +** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  27367. +**
  27368. +** The default way of implementing this query is to execute the
  27369. +** subquery first and store the results in a temporary table, then
  27370. +** run the outer query on that temporary table. This requires two
  27371. +** passes over the data. Furthermore, because the temporary table
  27372. +** has no indices, the WHERE clause on the outer query cannot be
  27373. +** optimized.
  27374. +**
  27375. +** This routine attempts to rewrite queries such as the above into
  27376. +** a single flat select, like this:
  27377. +**
  27378. +** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  27379. +**
  27380. +** The code generated for this simpification gives the same result
  27381. +** but only has to scan the data once. And because indices might
  27382. +** exist on the table t1, a complete scan of the data might be
  27383. +** avoided.
  27384. +**
  27385. +** Flattening is only attempted if all of the following are true:
  27386. +**
  27387. +** (1) The subquery and the outer query do not both use aggregates.
  27388. +**
  27389. +** (2) The subquery is not an aggregate or the outer query is not a join.
  27390. +**
  27391. +** (3) The subquery is not the right operand of a left outer join, or
  27392. +** the subquery is not itself a join. (Ticket #306)
  27393. +**
  27394. +** (4) The subquery is not DISTINCT or the outer query is not a join.
  27395. +**
  27396. +** (5) The subquery is not DISTINCT or the outer query does not use
  27397. +** aggregates.
  27398. +**
  27399. +** (6) The subquery does not use aggregates or the outer query is not
  27400. +** DISTINCT.
  27401. +**
  27402. +** (7) The subquery has a FROM clause.
  27403. +**
  27404. +** (8) The subquery does not use LIMIT or the outer query is not a join.
  27405. +**
  27406. +** (9) The subquery does not use LIMIT or the outer query does not use
  27407. +** aggregates.
  27408. +**
  27409. +** (10) The subquery does not use aggregates or the outer query does not
  27410. +** use LIMIT.
  27411. +**
  27412. +** (11) The subquery and the outer query do not both have ORDER BY clauses.
  27413. +**
  27414. +** (12) The subquery is not the right term of a LEFT OUTER JOIN or the
  27415. +** subquery has no WHERE clause. (added by ticket #350)
  27416. +**
  27417. +** In this routine, the "p" parameter is a pointer to the outer query.
  27418. +** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  27419. +** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  27420. +**
  27421. +** If flattening is not attempted, this routine is a no-op and returns 0.
  27422. +** If flattening is attempted this routine returns 1.
  27423. +**
  27424. +** All of the expression analysis must occur on both the outer query and
  27425. +** the subquery before this routine runs.
  27426. +*/
  27427. +static int flattenSubquery(
  27428. + Parse *pParse, /* The parsing context */
  27429. + Select *p, /* The parent or outer SELECT statement */
  27430. + int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  27431. + int isAgg, /* True if outer SELECT uses aggregate functions */
  27432. + int subqueryIsAgg /* True if the subquery uses aggregate functions */
  27433. +){
  27434. + Select *pSub; /* The inner query or "subquery" */
  27435. + SrcList *pSrc; /* The FROM clause of the outer query */
  27436. + SrcList *pSubSrc; /* The FROM clause of the subquery */
  27437. + ExprList *pList; /* The result set of the outer query */
  27438. + int iParent; /* VDBE cursor number of the pSub result set temp table */
  27439. + int i;
  27440. + Expr *pWhere;
  27441. +
  27442. + /* Check to see if flattening is permitted. Return 0 if not.
  27443. + */
  27444. + if( p==0 ) return 0;
  27445. + pSrc = p->pSrc;
  27446. + assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  27447. + pSub = pSrc->a[iFrom].pSelect;
  27448. + assert( pSub!=0 );
  27449. + if( isAgg && subqueryIsAgg ) return 0;
  27450. + if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;
  27451. + pSubSrc = pSub->pSrc;
  27452. + assert( pSubSrc );
  27453. + if( pSubSrc->nSrc==0 ) return 0;
  27454. + if( (pSub->isDistinct || pSub->nLimit>=0) && (pSrc->nSrc>1 || isAgg) ){
  27455. + return 0;
  27456. + }
  27457. + if( (p->isDistinct || p->nLimit>=0) && subqueryIsAgg ) return 0;
  27458. + if( p->pOrderBy && pSub->pOrderBy ) return 0;
  27459. +
  27460. + /* Restriction 3: If the subquery is a join, make sure the subquery is
  27461. + ** not used as the right operand of an outer join. Examples of why this
  27462. + ** is not allowed:
  27463. + **
  27464. + ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  27465. + **
  27466. + ** If we flatten the above, we would get
  27467. + **
  27468. + ** (t1 LEFT OUTER JOIN t2) JOIN t3
  27469. + **
  27470. + ** which is not at all the same thing.
  27471. + */
  27472. + if( pSubSrc->nSrc>1 && iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0 ){
  27473. + return 0;
  27474. + }
  27475. +
  27476. + /* Restriction 12: If the subquery is the right operand of a left outer
  27477. + ** join, make sure the subquery has no WHERE clause.
  27478. + ** An examples of why this is not allowed:
  27479. + **
  27480. + ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  27481. + **
  27482. + ** If we flatten the above, we would get
  27483. + **
  27484. + ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  27485. + **
  27486. + ** But the t2.x>0 test will always fail on a NULL row of t2, which
  27487. + ** effectively converts the OUTER JOIN into an INNER JOIN.
  27488. + */
  27489. + if( iFrom>0 && (pSrc->a[iFrom-1].jointype & JT_OUTER)!=0
  27490. + && pSub->pWhere!=0 ){
  27491. + return 0;
  27492. + }
  27493. +
  27494. + /* If we reach this point, it means flattening is permitted for the
  27495. + ** iFrom-th entry of the FROM clause in the outer query.
  27496. + */
  27497. +
  27498. + /* Move all of the FROM elements of the subquery into the
  27499. + ** the FROM clause of the outer query. Before doing this, remember
  27500. + ** the cursor number for the original outer query FROM element in
  27501. + ** iParent. The iParent cursor will never be used. Subsequent code
  27502. + ** will scan expressions looking for iParent references and replace
  27503. + ** those references with expressions that resolve to the subquery FROM
  27504. + ** elements we are now copying in.
  27505. + */
  27506. + iParent = pSrc->a[iFrom].iCursor;
  27507. + {
  27508. + int nSubSrc = pSubSrc->nSrc;
  27509. + int jointype = pSrc->a[iFrom].jointype;
  27510. +
  27511. + if( pSrc->a[iFrom].pTab && pSrc->a[iFrom].pTab->isTransient ){
  27512. + sqliteDeleteTable(0, pSrc->a[iFrom].pTab);
  27513. + }
  27514. + sqliteFree(pSrc->a[iFrom].zDatabase);
  27515. + sqliteFree(pSrc->a[iFrom].zName);
  27516. + sqliteFree(pSrc->a[iFrom].zAlias);
  27517. + if( nSubSrc>1 ){
  27518. + int extra = nSubSrc - 1;
  27519. + for(i=1; i<nSubSrc; i++){
  27520. + pSrc = sqliteSrcListAppend(pSrc, 0, 0);
  27521. + }
  27522. + p->pSrc = pSrc;
  27523. + for(i=pSrc->nSrc-1; i-extra>=iFrom; i--){
  27524. + pSrc->a[i] = pSrc->a[i-extra];
  27525. + }
  27526. + }
  27527. + for(i=0; i<nSubSrc; i++){
  27528. + pSrc->a[i+iFrom] = pSubSrc->a[i];
  27529. + memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  27530. + }
  27531. + pSrc->a[iFrom+nSubSrc-1].jointype = jointype;
  27532. + }
  27533. +
  27534. + /* Now begin substituting subquery result set expressions for
  27535. + ** references to the iParent in the outer query.
  27536. + **
  27537. + ** Example:
  27538. + **
  27539. + ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  27540. + ** \ \_____________ subquery __________/ /
  27541. + ** \_____________________ outer query ______________________________/
  27542. + **
  27543. + ** We look at every expression in the outer query and every place we see
  27544. + ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  27545. + */
  27546. + substExprList(p->pEList, iParent, pSub->pEList);
  27547. + pList = p->pEList;
  27548. + for(i=0; i<pList->nExpr; i++){
  27549. + Expr *pExpr;
  27550. + if( pList->a[i].zName==0 && (pExpr = pList->a[i].pExpr)->span.z!=0 ){
  27551. + pList->a[i].zName = sqliteStrNDup(pExpr->span.z, pExpr->span.n);
  27552. + }
  27553. + }
  27554. + if( isAgg ){
  27555. + substExprList(p->pGroupBy, iParent, pSub->pEList);
  27556. + substExpr(p->pHaving, iParent, pSub->pEList);
  27557. + }
  27558. + if( pSub->pOrderBy ){
  27559. + assert( p->pOrderBy==0 );
  27560. + p->pOrderBy = pSub->pOrderBy;
  27561. + pSub->pOrderBy = 0;
  27562. + }else if( p->pOrderBy ){
  27563. + substExprList(p->pOrderBy, iParent, pSub->pEList);
  27564. + }
  27565. + if( pSub->pWhere ){
  27566. + pWhere = sqliteExprDup(pSub->pWhere);
  27567. + }else{
  27568. + pWhere = 0;
  27569. + }
  27570. + if( subqueryIsAgg ){
  27571. + assert( p->pHaving==0 );
  27572. + p->pHaving = p->pWhere;
  27573. + p->pWhere = pWhere;
  27574. + substExpr(p->pHaving, iParent, pSub->pEList);
  27575. + if( pSub->pHaving ){
  27576. + Expr *pHaving = sqliteExprDup(pSub->pHaving);
  27577. + if( p->pHaving ){
  27578. + p->pHaving = sqliteExpr(TK_AND, p->pHaving, pHaving, 0);
  27579. + }else{
  27580. + p->pHaving = pHaving;
  27581. + }
  27582. + }
  27583. + assert( p->pGroupBy==0 );
  27584. + p->pGroupBy = sqliteExprListDup(pSub->pGroupBy);
  27585. + }else if( p->pWhere==0 ){
  27586. + p->pWhere = pWhere;
  27587. + }else{
  27588. + substExpr(p->pWhere, iParent, pSub->pEList);
  27589. + if( pWhere ){
  27590. + p->pWhere = sqliteExpr(TK_AND, p->pWhere, pWhere, 0);
  27591. + }
  27592. + }
  27593. +
  27594. + /* The flattened query is distinct if either the inner or the
  27595. + ** outer query is distinct.
  27596. + */
  27597. + p->isDistinct = p->isDistinct || pSub->isDistinct;
  27598. +
  27599. + /* Transfer the limit expression from the subquery to the outer
  27600. + ** query.
  27601. + */
  27602. + if( pSub->nLimit>=0 ){
  27603. + if( p->nLimit<0 ){
  27604. + p->nLimit = pSub->nLimit;
  27605. + }else if( p->nLimit+p->nOffset > pSub->nLimit+pSub->nOffset ){
  27606. + p->nLimit = pSub->nLimit + pSub->nOffset - p->nOffset;
  27607. + }
  27608. + }
  27609. + p->nOffset += pSub->nOffset;
  27610. +
  27611. + /* Finially, delete what is left of the subquery and return
  27612. + ** success.
  27613. + */
  27614. + sqliteSelectDelete(pSub);
  27615. + return 1;
  27616. +}
  27617. +
  27618. +/*
  27619. +** Analyze the SELECT statement passed in as an argument to see if it
  27620. +** is a simple min() or max() query. If it is and this query can be
  27621. +** satisfied using a single seek to the beginning or end of an index,
  27622. +** then generate the code for this SELECT and return 1. If this is not a
  27623. +** simple min() or max() query, then return 0;
  27624. +**
  27625. +** A simply min() or max() query looks like this:
  27626. +**
  27627. +** SELECT min(a) FROM table;
  27628. +** SELECT max(a) FROM table;
  27629. +**
  27630. +** The query may have only a single table in its FROM argument. There
  27631. +** can be no GROUP BY or HAVING or WHERE clauses. The result set must
  27632. +** be the min() or max() of a single column of the table. The column
  27633. +** in the min() or max() function must be indexed.
  27634. +**
  27635. +** The parameters to this routine are the same as for sqliteSelect().
  27636. +** See the header comment on that routine for additional information.
  27637. +*/
  27638. +static int simpleMinMaxQuery(Parse *pParse, Select *p, int eDest, int iParm){
  27639. + Expr *pExpr;
  27640. + int iCol;
  27641. + Table *pTab;
  27642. + Index *pIdx;
  27643. + int base;
  27644. + Vdbe *v;
  27645. + int seekOp;
  27646. + int cont;
  27647. + ExprList *pEList, *pList, eList;
  27648. + struct ExprList_item eListItem;
  27649. + SrcList *pSrc;
  27650. +
  27651. +
  27652. + /* Check to see if this query is a simple min() or max() query. Return
  27653. + ** zero if it is not.
  27654. + */
  27655. + if( p->pGroupBy || p->pHaving || p->pWhere ) return 0;
  27656. + pSrc = p->pSrc;
  27657. + if( pSrc->nSrc!=1 ) return 0;
  27658. + pEList = p->pEList;
  27659. + if( pEList->nExpr!=1 ) return 0;
  27660. + pExpr = pEList->a[0].pExpr;
  27661. + if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  27662. + pList = pExpr->pList;
  27663. + if( pList==0 || pList->nExpr!=1 ) return 0;
  27664. + if( pExpr->token.n!=3 ) return 0;
  27665. + if( sqliteStrNICmp(pExpr->token.z,"min",3)==0 ){
  27666. + seekOp = OP_Rewind;
  27667. + }else if( sqliteStrNICmp(pExpr->token.z,"max",3)==0 ){
  27668. + seekOp = OP_Last;
  27669. + }else{
  27670. + return 0;
  27671. + }
  27672. + pExpr = pList->a[0].pExpr;
  27673. + if( pExpr->op!=TK_COLUMN ) return 0;
  27674. + iCol = pExpr->iColumn;
  27675. + pTab = pSrc->a[0].pTab;
  27676. +
  27677. + /* If we get to here, it means the query is of the correct form.
  27678. + ** Check to make sure we have an index and make pIdx point to the
  27679. + ** appropriate index. If the min() or max() is on an INTEGER PRIMARY
  27680. + ** key column, no index is necessary so set pIdx to NULL. If no
  27681. + ** usable index is found, return 0.
  27682. + */
  27683. + if( iCol<0 ){
  27684. + pIdx = 0;
  27685. + }else{
  27686. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  27687. + assert( pIdx->nColumn>=1 );
  27688. + if( pIdx->aiColumn[0]==iCol ) break;
  27689. + }
  27690. + if( pIdx==0 ) return 0;
  27691. + }
  27692. +
  27693. + /* Identify column types if we will be using the callback. This
  27694. + ** step is skipped if the output is going to a table or a memory cell.
  27695. + ** The column names have already been generated in the calling function.
  27696. + */
  27697. + v = sqliteGetVdbe(pParse);
  27698. + if( v==0 ) return 0;
  27699. + if( eDest==SRT_Callback ){
  27700. + generateColumnTypes(pParse, p->pSrc, p->pEList);
  27701. + }
  27702. +
  27703. + /* If the output is destined for a temporary table, open that table.
  27704. + */
  27705. + if( eDest==SRT_TempTable ){
  27706. + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
  27707. + }
  27708. +
  27709. + /* Generating code to find the min or the max. Basically all we have
  27710. + ** to do is find the first or the last entry in the chosen index. If
  27711. + ** the min() or max() is on the INTEGER PRIMARY KEY, then find the first
  27712. + ** or last entry in the main table.
  27713. + */
  27714. + sqliteCodeVerifySchema(pParse, pTab->iDb);
  27715. + base = pSrc->a[0].iCursor;
  27716. + computeLimitRegisters(pParse, p);
  27717. + if( pSrc->a[0].pSelect==0 ){
  27718. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  27719. + sqliteVdbeOp3(v, OP_OpenRead, base, pTab->tnum, pTab->zName, 0);
  27720. + }
  27721. + cont = sqliteVdbeMakeLabel(v);
  27722. + if( pIdx==0 ){
  27723. + sqliteVdbeAddOp(v, seekOp, base, 0);
  27724. + }else{
  27725. + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
  27726. + sqliteVdbeOp3(v, OP_OpenRead, base+1, pIdx->tnum, pIdx->zName, P3_STATIC);
  27727. + if( seekOp==OP_Rewind ){
  27728. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  27729. + sqliteVdbeAddOp(v, OP_MakeKey, 1, 0);
  27730. + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
  27731. + seekOp = OP_MoveTo;
  27732. + }
  27733. + sqliteVdbeAddOp(v, seekOp, base+1, 0);
  27734. + sqliteVdbeAddOp(v, OP_IdxRecno, base+1, 0);
  27735. + sqliteVdbeAddOp(v, OP_Close, base+1, 0);
  27736. + sqliteVdbeAddOp(v, OP_MoveTo, base, 0);
  27737. + }
  27738. + eList.nExpr = 1;
  27739. + memset(&eListItem, 0, sizeof(eListItem));
  27740. + eList.a = &eListItem;
  27741. + eList.a[0].pExpr = pExpr;
  27742. + selectInnerLoop(pParse, p, &eList, 0, 0, 0, -1, eDest, iParm, cont, cont);
  27743. + sqliteVdbeResolveLabel(v, cont);
  27744. + sqliteVdbeAddOp(v, OP_Close, base, 0);
  27745. +
  27746. + return 1;
  27747. +}
  27748. +
  27749. +/*
  27750. +** Generate code for the given SELECT statement.
  27751. +**
  27752. +** The results are distributed in various ways depending on the
  27753. +** value of eDest and iParm.
  27754. +**
  27755. +** eDest Value Result
  27756. +** ------------ -------------------------------------------
  27757. +** SRT_Callback Invoke the callback for each row of the result.
  27758. +**
  27759. +** SRT_Mem Store first result in memory cell iParm
  27760. +**
  27761. +** SRT_Set Store results as keys of a table with cursor iParm
  27762. +**
  27763. +** SRT_Union Store results as a key in a temporary table iParm
  27764. +**
  27765. +** SRT_Except Remove results from the temporary table iParm.
  27766. +**
  27767. +** SRT_Table Store results in temporary table iParm
  27768. +**
  27769. +** The table above is incomplete. Additional eDist value have be added
  27770. +** since this comment was written. See the selectInnerLoop() function for
  27771. +** a complete listing of the allowed values of eDest and their meanings.
  27772. +**
  27773. +** This routine returns the number of errors. If any errors are
  27774. +** encountered, then an appropriate error message is left in
  27775. +** pParse->zErrMsg.
  27776. +**
  27777. +** This routine does NOT free the Select structure passed in. The
  27778. +** calling function needs to do that.
  27779. +**
  27780. +** The pParent, parentTab, and *pParentAgg fields are filled in if this
  27781. +** SELECT is a subquery. This routine may try to combine this SELECT
  27782. +** with its parent to form a single flat query. In so doing, it might
  27783. +** change the parent query from a non-aggregate to an aggregate query.
  27784. +** For that reason, the pParentAgg flag is passed as a pointer, so it
  27785. +** can be changed.
  27786. +**
  27787. +** Example 1: The meaning of the pParent parameter.
  27788. +**
  27789. +** SELECT * FROM t1 JOIN (SELECT x, count(*) FROM t2) JOIN t3;
  27790. +** \ \_______ subquery _______/ /
  27791. +** \ /
  27792. +** \____________________ outer query ___________________/
  27793. +**
  27794. +** This routine is called for the outer query first. For that call,
  27795. +** pParent will be NULL. During the processing of the outer query, this
  27796. +** routine is called recursively to handle the subquery. For the recursive
  27797. +** call, pParent will point to the outer query. Because the subquery is
  27798. +** the second element in a three-way join, the parentTab parameter will
  27799. +** be 1 (the 2nd value of a 0-indexed array.)
  27800. +*/
  27801. +int sqliteSelect(
  27802. + Parse *pParse, /* The parser context */
  27803. + Select *p, /* The SELECT statement being coded. */
  27804. + int eDest, /* How to dispose of the results */
  27805. + int iParm, /* A parameter used by the eDest disposal method */
  27806. + Select *pParent, /* Another SELECT for which this is a sub-query */
  27807. + int parentTab, /* Index in pParent->pSrc of this query */
  27808. + int *pParentAgg /* True if pParent uses aggregate functions */
  27809. +){
  27810. + int i;
  27811. + WhereInfo *pWInfo;
  27812. + Vdbe *v;
  27813. + int isAgg = 0; /* True for select lists like "count(*)" */
  27814. + ExprList *pEList; /* List of columns to extract. */
  27815. + SrcList *pTabList; /* List of tables to select from */
  27816. + Expr *pWhere; /* The WHERE clause. May be NULL */
  27817. + ExprList *pOrderBy; /* The ORDER BY clause. May be NULL */
  27818. + ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  27819. + Expr *pHaving; /* The HAVING clause. May be NULL */
  27820. + int isDistinct; /* True if the DISTINCT keyword is present */
  27821. + int distinct; /* Table to use for the distinct set */
  27822. + int rc = 1; /* Value to return from this function */
  27823. +
  27824. + if( sqlite_malloc_failed || pParse->nErr || p==0 ) return 1;
  27825. + if( sqliteAuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  27826. +
  27827. + /* If there is are a sequence of queries, do the earlier ones first.
  27828. + */
  27829. + if( p->pPrior ){
  27830. + return multiSelect(pParse, p, eDest, iParm);
  27831. + }
  27832. +
  27833. + /* Make local copies of the parameters for this query.
  27834. + */
  27835. + pTabList = p->pSrc;
  27836. + pWhere = p->pWhere;
  27837. + pOrderBy = p->pOrderBy;
  27838. + pGroupBy = p->pGroupBy;
  27839. + pHaving = p->pHaving;
  27840. + isDistinct = p->isDistinct;
  27841. +
  27842. + /* Allocate VDBE cursors for each table in the FROM clause
  27843. + */
  27844. + sqliteSrcListAssignCursors(pParse, pTabList);
  27845. +
  27846. + /*
  27847. + ** Do not even attempt to generate any code if we have already seen
  27848. + ** errors before this routine starts.
  27849. + */
  27850. + if( pParse->nErr>0 ) goto select_end;
  27851. +
  27852. + /* Expand any "*" terms in the result set. (For example the "*" in
  27853. + ** "SELECT * FROM t1") The fillInColumnlist() routine also does some
  27854. + ** other housekeeping - see the header comment for details.
  27855. + */
  27856. + if( fillInColumnList(pParse, p) ){
  27857. + goto select_end;
  27858. + }
  27859. + pWhere = p->pWhere;
  27860. + pEList = p->pEList;
  27861. + if( pEList==0 ) goto select_end;
  27862. +
  27863. + /* If writing to memory or generating a set
  27864. + ** only a single column may be output.
  27865. + */
  27866. + if( (eDest==SRT_Mem || eDest==SRT_Set) && pEList->nExpr>1 ){
  27867. + sqliteErrorMsg(pParse, "only a single result allowed for "
  27868. + "a SELECT that is part of an expression");
  27869. + goto select_end;
  27870. + }
  27871. +
  27872. + /* ORDER BY is ignored for some destinations.
  27873. + */
  27874. + switch( eDest ){
  27875. + case SRT_Union:
  27876. + case SRT_Except:
  27877. + case SRT_Discard:
  27878. + pOrderBy = 0;
  27879. + break;
  27880. + default:
  27881. + break;
  27882. + }
  27883. +
  27884. + /* At this point, we should have allocated all the cursors that we
  27885. + ** need to handle subquerys and temporary tables.
  27886. + **
  27887. + ** Resolve the column names and do a semantics check on all the expressions.
  27888. + */
  27889. + for(i=0; i<pEList->nExpr; i++){
  27890. + if( sqliteExprResolveIds(pParse, pTabList, 0, pEList->a[i].pExpr) ){
  27891. + goto select_end;
  27892. + }
  27893. + if( sqliteExprCheck(pParse, pEList->a[i].pExpr, 1, &isAgg) ){
  27894. + goto select_end;
  27895. + }
  27896. + }
  27897. + if( pWhere ){
  27898. + if( sqliteExprResolveIds(pParse, pTabList, pEList, pWhere) ){
  27899. + goto select_end;
  27900. + }
  27901. + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
  27902. + goto select_end;
  27903. + }
  27904. + }
  27905. + if( pHaving ){
  27906. + if( pGroupBy==0 ){
  27907. + sqliteErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  27908. + goto select_end;
  27909. + }
  27910. + if( sqliteExprResolveIds(pParse, pTabList, pEList, pHaving) ){
  27911. + goto select_end;
  27912. + }
  27913. + if( sqliteExprCheck(pParse, pHaving, 1, &isAgg) ){
  27914. + goto select_end;
  27915. + }
  27916. + }
  27917. + if( pOrderBy ){
  27918. + for(i=0; i<pOrderBy->nExpr; i++){
  27919. + int iCol;
  27920. + Expr *pE = pOrderBy->a[i].pExpr;
  27921. + if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
  27922. + sqliteExprDelete(pE);
  27923. + pE = pOrderBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
  27924. + }
  27925. + if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
  27926. + goto select_end;
  27927. + }
  27928. + if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
  27929. + goto select_end;
  27930. + }
  27931. + if( sqliteExprIsConstant(pE) ){
  27932. + if( sqliteExprIsInteger(pE, &iCol)==0 ){
  27933. + sqliteErrorMsg(pParse,
  27934. + "ORDER BY terms must not be non-integer constants");
  27935. + goto select_end;
  27936. + }else if( iCol<=0 || iCol>pEList->nExpr ){
  27937. + sqliteErrorMsg(pParse,
  27938. + "ORDER BY column number %d out of range - should be "
  27939. + "between 1 and %d", iCol, pEList->nExpr);
  27940. + goto select_end;
  27941. + }
  27942. + }
  27943. + }
  27944. + }
  27945. + if( pGroupBy ){
  27946. + for(i=0; i<pGroupBy->nExpr; i++){
  27947. + int iCol;
  27948. + Expr *pE = pGroupBy->a[i].pExpr;
  27949. + if( sqliteExprIsInteger(pE, &iCol) && iCol>0 && iCol<=pEList->nExpr ){
  27950. + sqliteExprDelete(pE);
  27951. + pE = pGroupBy->a[i].pExpr = sqliteExprDup(pEList->a[iCol-1].pExpr);
  27952. + }
  27953. + if( sqliteExprResolveIds(pParse, pTabList, pEList, pE) ){
  27954. + goto select_end;
  27955. + }
  27956. + if( sqliteExprCheck(pParse, pE, isAgg, 0) ){
  27957. + goto select_end;
  27958. + }
  27959. + if( sqliteExprIsConstant(pE) ){
  27960. + if( sqliteExprIsInteger(pE, &iCol)==0 ){
  27961. + sqliteErrorMsg(pParse,
  27962. + "GROUP BY terms must not be non-integer constants");
  27963. + goto select_end;
  27964. + }else if( iCol<=0 || iCol>pEList->nExpr ){
  27965. + sqliteErrorMsg(pParse,
  27966. + "GROUP BY column number %d out of range - should be "
  27967. + "between 1 and %d", iCol, pEList->nExpr);
  27968. + goto select_end;
  27969. + }
  27970. + }
  27971. + }
  27972. + }
  27973. +
  27974. + /* Begin generating code.
  27975. + */
  27976. + v = sqliteGetVdbe(pParse);
  27977. + if( v==0 ) goto select_end;
  27978. +
  27979. + /* Identify column names if we will be using them in a callback. This
  27980. + ** step is skipped if the output is going to some other destination.
  27981. + */
  27982. + if( eDest==SRT_Callback ){
  27983. + generateColumnNames(pParse, pTabList, pEList);
  27984. + }
  27985. +
  27986. + /* Generate code for all sub-queries in the FROM clause
  27987. + */
  27988. + for(i=0; i<pTabList->nSrc; i++){
  27989. + const char *zSavedAuthContext;
  27990. + int needRestoreContext;
  27991. +
  27992. + if( pTabList->a[i].pSelect==0 ) continue;
  27993. + if( pTabList->a[i].zName!=0 ){
  27994. + zSavedAuthContext = pParse->zAuthContext;
  27995. + pParse->zAuthContext = pTabList->a[i].zName;
  27996. + needRestoreContext = 1;
  27997. + }else{
  27998. + needRestoreContext = 0;
  27999. + }
  28000. + sqliteSelect(pParse, pTabList->a[i].pSelect, SRT_TempTable,
  28001. + pTabList->a[i].iCursor, p, i, &isAgg);
  28002. + if( needRestoreContext ){
  28003. + pParse->zAuthContext = zSavedAuthContext;
  28004. + }
  28005. + pTabList = p->pSrc;
  28006. + pWhere = p->pWhere;
  28007. + if( eDest!=SRT_Union && eDest!=SRT_Except && eDest!=SRT_Discard ){
  28008. + pOrderBy = p->pOrderBy;
  28009. + }
  28010. + pGroupBy = p->pGroupBy;
  28011. + pHaving = p->pHaving;
  28012. + isDistinct = p->isDistinct;
  28013. + }
  28014. +
  28015. + /* Check for the special case of a min() or max() function by itself
  28016. + ** in the result set.
  28017. + */
  28018. + if( simpleMinMaxQuery(pParse, p, eDest, iParm) ){
  28019. + rc = 0;
  28020. + goto select_end;
  28021. + }
  28022. +
  28023. + /* Check to see if this is a subquery that can be "flattened" into its parent.
  28024. + ** If flattening is a possiblity, do so and return immediately.
  28025. + */
  28026. + if( pParent && pParentAgg &&
  28027. + flattenSubquery(pParse, pParent, parentTab, *pParentAgg, isAgg) ){
  28028. + if( isAgg ) *pParentAgg = 1;
  28029. + return rc;
  28030. + }
  28031. +
  28032. + /* Set the limiter.
  28033. + */
  28034. + computeLimitRegisters(pParse, p);
  28035. +
  28036. + /* Identify column types if we will be using a callback. This
  28037. + ** step is skipped if the output is going to a destination other
  28038. + ** than a callback.
  28039. + **
  28040. + ** We have to do this separately from the creation of column names
  28041. + ** above because if the pTabList contains views then they will not
  28042. + ** have been resolved and we will not know the column types until
  28043. + ** now.
  28044. + */
  28045. + if( eDest==SRT_Callback ){
  28046. + generateColumnTypes(pParse, pTabList, pEList);
  28047. + }
  28048. +
  28049. + /* If the output is destined for a temporary table, open that table.
  28050. + */
  28051. + if( eDest==SRT_TempTable ){
  28052. + sqliteVdbeAddOp(v, OP_OpenTemp, iParm, 0);
  28053. + }
  28054. +
  28055. + /* Do an analysis of aggregate expressions.
  28056. + */
  28057. + sqliteAggregateInfoReset(pParse);
  28058. + if( isAgg || pGroupBy ){
  28059. + assert( pParse->nAgg==0 );
  28060. + isAgg = 1;
  28061. + for(i=0; i<pEList->nExpr; i++){
  28062. + if( sqliteExprAnalyzeAggregates(pParse, pEList->a[i].pExpr) ){
  28063. + goto select_end;
  28064. + }
  28065. + }
  28066. + if( pGroupBy ){
  28067. + for(i=0; i<pGroupBy->nExpr; i++){
  28068. + if( sqliteExprAnalyzeAggregates(pParse, pGroupBy->a[i].pExpr) ){
  28069. + goto select_end;
  28070. + }
  28071. + }
  28072. + }
  28073. + if( pHaving && sqliteExprAnalyzeAggregates(pParse, pHaving) ){
  28074. + goto select_end;
  28075. + }
  28076. + if( pOrderBy ){
  28077. + for(i=0; i<pOrderBy->nExpr; i++){
  28078. + if( sqliteExprAnalyzeAggregates(pParse, pOrderBy->a[i].pExpr) ){
  28079. + goto select_end;
  28080. + }
  28081. + }
  28082. + }
  28083. + }
  28084. +
  28085. + /* Reset the aggregator
  28086. + */
  28087. + if( isAgg ){
  28088. + sqliteVdbeAddOp(v, OP_AggReset, 0, pParse->nAgg);
  28089. + for(i=0; i<pParse->nAgg; i++){
  28090. + FuncDef *pFunc;
  28091. + if( (pFunc = pParse->aAgg[i].pFunc)!=0 && pFunc->xFinalize!=0 ){
  28092. + sqliteVdbeOp3(v, OP_AggInit, 0, i, (char*)pFunc, P3_POINTER);
  28093. + }
  28094. + }
  28095. + if( pGroupBy==0 ){
  28096. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  28097. + sqliteVdbeAddOp(v, OP_AggFocus, 0, 0);
  28098. + }
  28099. + }
  28100. +
  28101. + /* Initialize the memory cell to NULL
  28102. + */
  28103. + if( eDest==SRT_Mem ){
  28104. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  28105. + sqliteVdbeAddOp(v, OP_MemStore, iParm, 1);
  28106. + }
  28107. +
  28108. + /* Open a temporary table to use for the distinct set.
  28109. + */
  28110. + if( isDistinct ){
  28111. + distinct = pParse->nTab++;
  28112. + sqliteVdbeAddOp(v, OP_OpenTemp, distinct, 1);
  28113. + }else{
  28114. + distinct = -1;
  28115. + }
  28116. +
  28117. + /* Begin the database scan
  28118. + */
  28119. + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 0,
  28120. + pGroupBy ? 0 : &pOrderBy);
  28121. + if( pWInfo==0 ) goto select_end;
  28122. +
  28123. + /* Use the standard inner loop if we are not dealing with
  28124. + ** aggregates
  28125. + */
  28126. + if( !isAgg ){
  28127. + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
  28128. + iParm, pWInfo->iContinue, pWInfo->iBreak) ){
  28129. + goto select_end;
  28130. + }
  28131. + }
  28132. +
  28133. + /* If we are dealing with aggregates, then do the special aggregate
  28134. + ** processing.
  28135. + */
  28136. + else{
  28137. + AggExpr *pAgg;
  28138. + if( pGroupBy ){
  28139. + int lbl1;
  28140. + for(i=0; i<pGroupBy->nExpr; i++){
  28141. + sqliteExprCode(pParse, pGroupBy->a[i].pExpr);
  28142. + }
  28143. + sqliteVdbeAddOp(v, OP_MakeKey, pGroupBy->nExpr, 0);
  28144. + if( pParse->db->file_format>=4 ) sqliteAddKeyType(v, pGroupBy);
  28145. + lbl1 = sqliteVdbeMakeLabel(v);
  28146. + sqliteVdbeAddOp(v, OP_AggFocus, 0, lbl1);
  28147. + for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
  28148. + if( pAgg->isAgg ) continue;
  28149. + sqliteExprCode(pParse, pAgg->pExpr);
  28150. + sqliteVdbeAddOp(v, OP_AggSet, 0, i);
  28151. + }
  28152. + sqliteVdbeResolveLabel(v, lbl1);
  28153. + }
  28154. + for(i=0, pAgg=pParse->aAgg; i<pParse->nAgg; i++, pAgg++){
  28155. + Expr *pE;
  28156. + int nExpr;
  28157. + FuncDef *pDef;
  28158. + if( !pAgg->isAgg ) continue;
  28159. + assert( pAgg->pFunc!=0 );
  28160. + assert( pAgg->pFunc->xStep!=0 );
  28161. + pDef = pAgg->pFunc;
  28162. + pE = pAgg->pExpr;
  28163. + assert( pE!=0 );
  28164. + assert( pE->op==TK_AGG_FUNCTION );
  28165. + nExpr = sqliteExprCodeExprList(pParse, pE->pList, pDef->includeTypes);
  28166. + sqliteVdbeAddOp(v, OP_Integer, i, 0);
  28167. + sqliteVdbeOp3(v, OP_AggFunc, 0, nExpr, (char*)pDef, P3_POINTER);
  28168. + }
  28169. + }
  28170. +
  28171. + /* End the database scan loop.
  28172. + */
  28173. + sqliteWhereEnd(pWInfo);
  28174. +
  28175. + /* If we are processing aggregates, we need to set up a second loop
  28176. + ** over all of the aggregate values and process them.
  28177. + */
  28178. + if( isAgg ){
  28179. + int endagg = sqliteVdbeMakeLabel(v);
  28180. + int startagg;
  28181. + startagg = sqliteVdbeAddOp(v, OP_AggNext, 0, endagg);
  28182. + pParse->useAgg = 1;
  28183. + if( pHaving ){
  28184. + sqliteExprIfFalse(pParse, pHaving, startagg, 1);
  28185. + }
  28186. + if( selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, distinct, eDest,
  28187. + iParm, startagg, endagg) ){
  28188. + goto select_end;
  28189. + }
  28190. + sqliteVdbeAddOp(v, OP_Goto, 0, startagg);
  28191. + sqliteVdbeResolveLabel(v, endagg);
  28192. + sqliteVdbeAddOp(v, OP_Noop, 0, 0);
  28193. + pParse->useAgg = 0;
  28194. + }
  28195. +
  28196. + /* If there is an ORDER BY clause, then we need to sort the results
  28197. + ** and send them to the callback one by one.
  28198. + */
  28199. + if( pOrderBy ){
  28200. + generateSortTail(p, v, pEList->nExpr, eDest, iParm);
  28201. + }
  28202. +
  28203. + /* If this was a subquery, we have now converted the subquery into a
  28204. + ** temporary table. So delete the subquery structure from the parent
  28205. + ** to prevent this subquery from being evaluated again and to force the
  28206. + ** the use of the temporary table.
  28207. + */
  28208. + if( pParent ){
  28209. + assert( pParent->pSrc->nSrc>parentTab );
  28210. + assert( pParent->pSrc->a[parentTab].pSelect==p );
  28211. + sqliteSelectDelete(p);
  28212. + pParent->pSrc->a[parentTab].pSelect = 0;
  28213. + }
  28214. +
  28215. + /* The SELECT was successfully coded. Set the return code to 0
  28216. + ** to indicate no errors.
  28217. + */
  28218. + rc = 0;
  28219. +
  28220. + /* Control jumps to here if an error is encountered above, or upon
  28221. + ** successful coding of the SELECT.
  28222. + */
  28223. +select_end:
  28224. + sqliteAggregateInfoReset(pParse);
  28225. + return rc;
  28226. +}
  28227. --- /dev/null
  28228. +++ b/ext/sqlite/libsqlite/src/sqlite_config.w32.h
  28229. @@ -0,0 +1,8 @@
  28230. +#include "config.w32.h"
  28231. +#if ZTS
  28232. +# define THREADSAFE 1
  28233. +#endif
  28234. +#if !ZEND_DEBUG && !defined(NDEBUG)
  28235. +# define NDEBUG
  28236. +#endif
  28237. +#define SQLITE_PTR_SZ 4
  28238. \ No newline at end of file
  28239. --- /dev/null
  28240. +++ b/ext/sqlite/libsqlite/src/sqlite.h.in
  28241. @@ -0,0 +1,886 @@
  28242. +/*
  28243. +** 2001 September 15
  28244. +**
  28245. +** The author disclaims copyright to this source code. In place of
  28246. +** a legal notice, here is a blessing:
  28247. +**
  28248. +** May you do good and not evil.
  28249. +** May you find forgiveness for yourself and forgive others.
  28250. +** May you share freely, never taking more than you give.
  28251. +**
  28252. +*************************************************************************
  28253. +** This header file defines the interface that the SQLite library
  28254. +** presents to client programs.
  28255. +**
  28256. +** @(#) $Id$
  28257. +*/
  28258. +#ifndef _SQLITE_H_
  28259. +#define _SQLITE_H_
  28260. +#include <stdarg.h> /* Needed for the definition of va_list */
  28261. +
  28262. +/*
  28263. +** Make sure we can call this stuff from C++.
  28264. +*/
  28265. +#ifdef __cplusplus
  28266. +extern "C" {
  28267. +#endif
  28268. +
  28269. +/*
  28270. +** The version of the SQLite library.
  28271. +*/
  28272. +#ifdef SQLITE_VERSION
  28273. +# undef SQLITE_VERSION
  28274. +#else
  28275. +# define SQLITE_VERSION "--VERS--"
  28276. +#endif
  28277. +
  28278. +/*
  28279. +** The version string is also compiled into the library so that a program
  28280. +** can check to make sure that the lib*.a file and the *.h file are from
  28281. +** the same version.
  28282. +*/
  28283. +extern const char sqlite_version[];
  28284. +
  28285. +/*
  28286. +** The SQLITE_UTF8 macro is defined if the library expects to see
  28287. +** UTF-8 encoded data. The SQLITE_ISO8859 macro is defined if the
  28288. +** iso8859 encoded should be used.
  28289. +*/
  28290. +#define SQLITE_--ENCODING-- 1
  28291. +
  28292. +/*
  28293. +** The following constant holds one of two strings, "UTF-8" or "iso8859",
  28294. +** depending on which character encoding the SQLite library expects to
  28295. +** see. The character encoding makes a difference for the LIKE and GLOB
  28296. +** operators and for the LENGTH() and SUBSTR() functions.
  28297. +*/
  28298. +extern const char sqlite_encoding[];
  28299. +
  28300. +/*
  28301. +** Each open sqlite database is represented by an instance of the
  28302. +** following opaque structure.
  28303. +*/
  28304. +typedef struct sqlite sqlite;
  28305. +
  28306. +/*
  28307. +** A function to open a new sqlite database.
  28308. +**
  28309. +** If the database does not exist and mode indicates write
  28310. +** permission, then a new database is created. If the database
  28311. +** does not exist and mode does not indicate write permission,
  28312. +** then the open fails, an error message generated (if errmsg!=0)
  28313. +** and the function returns 0.
  28314. +**
  28315. +** If mode does not indicates user write permission, then the
  28316. +** database is opened read-only.
  28317. +**
  28318. +** The Truth: As currently implemented, all databases are opened
  28319. +** for writing all the time. Maybe someday we will provide the
  28320. +** ability to open a database readonly. The mode parameters is
  28321. +** provided in anticipation of that enhancement.
  28322. +*/
  28323. +sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
  28324. +
  28325. +/*
  28326. +** A function to close the database.
  28327. +**
  28328. +** Call this function with a pointer to a structure that was previously
  28329. +** returned from sqlite_open() and the corresponding database will by closed.
  28330. +*/
  28331. +void sqlite_close(sqlite *);
  28332. +
  28333. +/*
  28334. +** The type for a callback function.
  28335. +*/
  28336. +typedef int (*sqlite_callback)(void*,int,char**, char**);
  28337. +
  28338. +/*
  28339. +** A function to executes one or more statements of SQL.
  28340. +**
  28341. +** If one or more of the SQL statements are queries, then
  28342. +** the callback function specified by the 3rd parameter is
  28343. +** invoked once for each row of the query result. This callback
  28344. +** should normally return 0. If the callback returns a non-zero
  28345. +** value then the query is aborted, all subsequent SQL statements
  28346. +** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
  28347. +**
  28348. +** The 4th parameter is an arbitrary pointer that is passed
  28349. +** to the callback function as its first parameter.
  28350. +**
  28351. +** The 2nd parameter to the callback function is the number of
  28352. +** columns in the query result. The 3rd parameter to the callback
  28353. +** is an array of strings holding the values for each column.
  28354. +** The 4th parameter to the callback is an array of strings holding
  28355. +** the names of each column.
  28356. +**
  28357. +** The callback function may be NULL, even for queries. A NULL
  28358. +** callback is not an error. It just means that no callback
  28359. +** will be invoked.
  28360. +**
  28361. +** If an error occurs while parsing or evaluating the SQL (but
  28362. +** not while executing the callback) then an appropriate error
  28363. +** message is written into memory obtained from malloc() and
  28364. +** *errmsg is made to point to that message. The calling function
  28365. +** is responsible for freeing the memory that holds the error
  28366. +** message. Use sqlite_freemem() for this. If errmsg==NULL,
  28367. +** then no error message is ever written.
  28368. +**
  28369. +** The return value is is SQLITE_OK if there are no errors and
  28370. +** some other return code if there is an error. The particular
  28371. +** return value depends on the type of error.
  28372. +**
  28373. +** If the query could not be executed because a database file is
  28374. +** locked or busy, then this function returns SQLITE_BUSY. (This
  28375. +** behavior can be modified somewhat using the sqlite_busy_handler()
  28376. +** and sqlite_busy_timeout() functions below.)
  28377. +*/
  28378. +int sqlite_exec(
  28379. + sqlite*, /* An open database */
  28380. + const char *sql, /* SQL to be executed */
  28381. + sqlite_callback, /* Callback function */
  28382. + void *, /* 1st argument to callback function */
  28383. + char **errmsg /* Error msg written here */
  28384. +);
  28385. +
  28386. +/*
  28387. +** Return values for sqlite_exec() and sqlite_step()
  28388. +*/
  28389. +#define SQLITE_OK 0 /* Successful result */
  28390. +#define SQLITE_ERROR 1 /* SQL error or missing database */
  28391. +#define SQLITE_INTERNAL 2 /* An internal logic error in SQLite */
  28392. +#define SQLITE_PERM 3 /* Access permission denied */
  28393. +#define SQLITE_ABORT 4 /* Callback routine requested an abort */
  28394. +#define SQLITE_BUSY 5 /* The database file is locked */
  28395. +#define SQLITE_LOCKED 6 /* A table in the database is locked */
  28396. +#define SQLITE_NOMEM 7 /* A malloc() failed */
  28397. +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  28398. +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite_interrupt() */
  28399. +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  28400. +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  28401. +#define SQLITE_NOTFOUND 12 /* (Internal Only) Table or record not found */
  28402. +#define SQLITE_FULL 13 /* Insertion failed because database is full */
  28403. +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  28404. +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  28405. +#define SQLITE_EMPTY 16 /* (Internal Only) Database table is empty */
  28406. +#define SQLITE_SCHEMA 17 /* The database schema changed */
  28407. +#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
  28408. +#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
  28409. +#define SQLITE_MISMATCH 20 /* Data type mismatch */
  28410. +#define SQLITE_MISUSE 21 /* Library used incorrectly */
  28411. +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  28412. +#define SQLITE_AUTH 23 /* Authorization denied */
  28413. +#define SQLITE_FORMAT 24 /* Auxiliary database format error */
  28414. +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite_bind out of range */
  28415. +#define SQLITE_NOTADB 26 /* File opened that is not a database file */
  28416. +#define SQLITE_ROW 100 /* sqlite_step() has another row ready */
  28417. +#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
  28418. +
  28419. +/*
  28420. +** Each entry in an SQLite table has a unique integer key. (The key is
  28421. +** the value of the INTEGER PRIMARY KEY column if there is such a column,
  28422. +** otherwise the key is generated at random. The unique key is always
  28423. +** available as the ROWID, OID, or _ROWID_ column.) The following routine
  28424. +** returns the integer key of the most recent insert in the database.
  28425. +**
  28426. +** This function is similar to the mysql_insert_id() function from MySQL.
  28427. +*/
  28428. +int sqlite_last_insert_rowid(sqlite*);
  28429. +
  28430. +/*
  28431. +** This function returns the number of database rows that were changed
  28432. +** (or inserted or deleted) by the most recent called sqlite_exec().
  28433. +**
  28434. +** All changes are counted, even if they were later undone by a
  28435. +** ROLLBACK or ABORT. Except, changes associated with creating and
  28436. +** dropping tables are not counted.
  28437. +**
  28438. +** If a callback invokes sqlite_exec() recursively, then the changes
  28439. +** in the inner, recursive call are counted together with the changes
  28440. +** in the outer call.
  28441. +**
  28442. +** SQLite implements the command "DELETE FROM table" without a WHERE clause
  28443. +** by dropping and recreating the table. (This is much faster than going
  28444. +** through and deleting individual elements form the table.) Because of
  28445. +** this optimization, the change count for "DELETE FROM table" will be
  28446. +** zero regardless of the number of elements that were originally in the
  28447. +** table. To get an accurate count of the number of rows deleted, use
  28448. +** "DELETE FROM table WHERE 1" instead.
  28449. +*/
  28450. +int sqlite_changes(sqlite*);
  28451. +
  28452. +/*
  28453. +** This function returns the number of database rows that were changed
  28454. +** by the last INSERT, UPDATE, or DELETE statment executed by sqlite_exec(),
  28455. +** or by the last VM to run to completion. The change count is not updated
  28456. +** by SQL statements other than INSERT, UPDATE or DELETE.
  28457. +**
  28458. +** Changes are counted, even if they are later undone by a ROLLBACK or
  28459. +** ABORT. Changes associated with trigger programs that execute as a
  28460. +** result of the INSERT, UPDATE, or DELETE statement are not counted.
  28461. +**
  28462. +** If a callback invokes sqlite_exec() recursively, then the changes
  28463. +** in the inner, recursive call are counted together with the changes
  28464. +** in the outer call.
  28465. +**
  28466. +** SQLite implements the command "DELETE FROM table" without a WHERE clause
  28467. +** by dropping and recreating the table. (This is much faster than going
  28468. +** through and deleting individual elements form the table.) Because of
  28469. +** this optimization, the change count for "DELETE FROM table" will be
  28470. +** zero regardless of the number of elements that were originally in the
  28471. +** table. To get an accurate count of the number of rows deleted, use
  28472. +** "DELETE FROM table WHERE 1" instead.
  28473. +**
  28474. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  28475. +*/
  28476. +int sqlite_last_statement_changes(sqlite*);
  28477. +
  28478. +/* If the parameter to this routine is one of the return value constants
  28479. +** defined above, then this routine returns a constant text string which
  28480. +** descripts (in English) the meaning of the return value.
  28481. +*/
  28482. +const char *sqlite_error_string(int);
  28483. +#define sqliteErrStr sqlite_error_string /* Legacy. Do not use in new code. */
  28484. +
  28485. +/* This function causes any pending database operation to abort and
  28486. +** return at its earliest opportunity. This routine is typically
  28487. +** called in response to a user action such as pressing "Cancel"
  28488. +** or Ctrl-C where the user wants a long query operation to halt
  28489. +** immediately.
  28490. +*/
  28491. +void sqlite_interrupt(sqlite*);
  28492. +
  28493. +
  28494. +/* This function returns true if the given input string comprises
  28495. +** one or more complete SQL statements.
  28496. +**
  28497. +** The algorithm is simple. If the last token other than spaces
  28498. +** and comments is a semicolon, then return true. otherwise return
  28499. +** false.
  28500. +*/
  28501. +int sqlite_complete(const char *sql);
  28502. +
  28503. +/*
  28504. +** This routine identifies a callback function that is invoked
  28505. +** whenever an attempt is made to open a database table that is
  28506. +** currently locked by another process or thread. If the busy callback
  28507. +** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
  28508. +** it finds a locked table. If the busy callback is not NULL, then
  28509. +** sqlite_exec() invokes the callback with three arguments. The
  28510. +** second argument is the name of the locked table and the third
  28511. +** argument is the number of times the table has been busy. If the
  28512. +** busy callback returns 0, then sqlite_exec() immediately returns
  28513. +** SQLITE_BUSY. If the callback returns non-zero, then sqlite_exec()
  28514. +** tries to open the table again and the cycle repeats.
  28515. +**
  28516. +** The default busy callback is NULL.
  28517. +**
  28518. +** Sqlite is re-entrant, so the busy handler may start a new query.
  28519. +** (It is not clear why anyone would every want to do this, but it
  28520. +** is allowed, in theory.) But the busy handler may not close the
  28521. +** database. Closing the database from a busy handler will delete
  28522. +** data structures out from under the executing query and will
  28523. +** probably result in a coredump.
  28524. +*/
  28525. +void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
  28526. +
  28527. +/*
  28528. +** This routine sets a busy handler that sleeps for a while when a
  28529. +** table is locked. The handler will sleep multiple times until
  28530. +** at least "ms" milleseconds of sleeping have been done. After
  28531. +** "ms" milleseconds of sleeping, the handler returns 0 which
  28532. +** causes sqlite_exec() to return SQLITE_BUSY.
  28533. +**
  28534. +** Calling this routine with an argument less than or equal to zero
  28535. +** turns off all busy handlers.
  28536. +*/
  28537. +void sqlite_busy_timeout(sqlite*, int ms);
  28538. +
  28539. +/*
  28540. +** This next routine is really just a wrapper around sqlite_exec().
  28541. +** Instead of invoking a user-supplied callback for each row of the
  28542. +** result, this routine remembers each row of the result in memory
  28543. +** obtained from malloc(), then returns all of the result after the
  28544. +** query has finished.
  28545. +**
  28546. +** As an example, suppose the query result where this table:
  28547. +**
  28548. +** Name | Age
  28549. +** -----------------------
  28550. +** Alice | 43
  28551. +** Bob | 28
  28552. +** Cindy | 21
  28553. +**
  28554. +** If the 3rd argument were &azResult then after the function returns
  28555. +** azResult will contain the following data:
  28556. +**
  28557. +** azResult[0] = "Name";
  28558. +** azResult[1] = "Age";
  28559. +** azResult[2] = "Alice";
  28560. +** azResult[3] = "43";
  28561. +** azResult[4] = "Bob";
  28562. +** azResult[5] = "28";
  28563. +** azResult[6] = "Cindy";
  28564. +** azResult[7] = "21";
  28565. +**
  28566. +** Notice that there is an extra row of data containing the column
  28567. +** headers. But the *nrow return value is still 3. *ncolumn is
  28568. +** set to 2. In general, the number of values inserted into azResult
  28569. +** will be ((*nrow) + 1)*(*ncolumn).
  28570. +**
  28571. +** After the calling function has finished using the result, it should
  28572. +** pass the result data pointer to sqlite_free_table() in order to
  28573. +** release the memory that was malloc-ed. Because of the way the
  28574. +** malloc() happens, the calling function must not try to call
  28575. +** malloc() directly. Only sqlite_free_table() is able to release
  28576. +** the memory properly and safely.
  28577. +**
  28578. +** The return value of this routine is the same as from sqlite_exec().
  28579. +*/
  28580. +int sqlite_get_table(
  28581. + sqlite*, /* An open database */
  28582. + const char *sql, /* SQL to be executed */
  28583. + char ***resultp, /* Result written to a char *[] that this points to */
  28584. + int *nrow, /* Number of result rows written here */
  28585. + int *ncolumn, /* Number of result columns written here */
  28586. + char **errmsg /* Error msg written here */
  28587. +);
  28588. +
  28589. +/*
  28590. +** Call this routine to free the memory that sqlite_get_table() allocated.
  28591. +*/
  28592. +void sqlite_free_table(char **result);
  28593. +
  28594. +/*
  28595. +** The following routines are wrappers around sqlite_exec() and
  28596. +** sqlite_get_table(). The only difference between the routines that
  28597. +** follow and the originals is that the second argument to the
  28598. +** routines that follow is really a printf()-style format
  28599. +** string describing the SQL to be executed. Arguments to the format
  28600. +** string appear at the end of the argument list.
  28601. +**
  28602. +** All of the usual printf formatting options apply. In addition, there
  28603. +** is a "%q" option. %q works like %s in that it substitutes a null-terminated
  28604. +** string from the argument list. But %q also doubles every '\'' character.
  28605. +** %q is designed for use inside a string literal. By doubling each '\''
  28606. +** character it escapes that character and allows it to be inserted into
  28607. +** the string.
  28608. +**
  28609. +** For example, so some string variable contains text as follows:
  28610. +**
  28611. +** char *zText = "It's a happy day!";
  28612. +**
  28613. +** We can use this text in an SQL statement as follows:
  28614. +**
  28615. +** sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
  28616. +** callback1, 0, 0, zText);
  28617. +**
  28618. +** Because the %q format string is used, the '\'' character in zText
  28619. +** is escaped and the SQL generated is as follows:
  28620. +**
  28621. +** INSERT INTO table1 VALUES('It''s a happy day!')
  28622. +**
  28623. +** This is correct. Had we used %s instead of %q, the generated SQL
  28624. +** would have looked like this:
  28625. +**
  28626. +** INSERT INTO table1 VALUES('It's a happy day!');
  28627. +**
  28628. +** This second example is an SQL syntax error. As a general rule you
  28629. +** should always use %q instead of %s when inserting text into a string
  28630. +** literal.
  28631. +*/
  28632. +int sqlite_exec_printf(
  28633. + sqlite*, /* An open database */
  28634. + const char *sqlFormat, /* printf-style format string for the SQL */
  28635. + sqlite_callback, /* Callback function */
  28636. + void *, /* 1st argument to callback function */
  28637. + char **errmsg, /* Error msg written here */
  28638. + ... /* Arguments to the format string. */
  28639. +);
  28640. +int sqlite_exec_vprintf(
  28641. + sqlite*, /* An open database */
  28642. + const char *sqlFormat, /* printf-style format string for the SQL */
  28643. + sqlite_callback, /* Callback function */
  28644. + void *, /* 1st argument to callback function */
  28645. + char **errmsg, /* Error msg written here */
  28646. + va_list ap /* Arguments to the format string. */
  28647. +);
  28648. +int sqlite_get_table_printf(
  28649. + sqlite*, /* An open database */
  28650. + const char *sqlFormat, /* printf-style format string for the SQL */
  28651. + char ***resultp, /* Result written to a char *[] that this points to */
  28652. + int *nrow, /* Number of result rows written here */
  28653. + int *ncolumn, /* Number of result columns written here */
  28654. + char **errmsg, /* Error msg written here */
  28655. + ... /* Arguments to the format string */
  28656. +);
  28657. +int sqlite_get_table_vprintf(
  28658. + sqlite*, /* An open database */
  28659. + const char *sqlFormat, /* printf-style format string for the SQL */
  28660. + char ***resultp, /* Result written to a char *[] that this points to */
  28661. + int *nrow, /* Number of result rows written here */
  28662. + int *ncolumn, /* Number of result columns written here */
  28663. + char **errmsg, /* Error msg written here */
  28664. + va_list ap /* Arguments to the format string */
  28665. +);
  28666. +char *sqlite_mprintf(const char*,...);
  28667. +char *sqlite_vmprintf(const char*, va_list);
  28668. +
  28669. +/*
  28670. +** Windows systems should call this routine to free memory that
  28671. +** is returned in the in the errmsg parameter of sqlite_open() when
  28672. +** SQLite is a DLL. For some reason, it does not work to call free()
  28673. +** directly.
  28674. +*/
  28675. +void sqlite_freemem(void *p);
  28676. +
  28677. +/*
  28678. +** Windows systems need functions to call to return the sqlite_version
  28679. +** and sqlite_encoding strings.
  28680. +*/
  28681. +const char *sqlite_libversion(void);
  28682. +const char *sqlite_libencoding(void);
  28683. +
  28684. +/*
  28685. +** A pointer to the following structure is used to communicate with
  28686. +** the implementations of user-defined functions.
  28687. +*/
  28688. +typedef struct sqlite_func sqlite_func;
  28689. +
  28690. +/*
  28691. +** Use the following routines to create new user-defined functions. See
  28692. +** the documentation for details.
  28693. +*/
  28694. +int sqlite_create_function(
  28695. + sqlite*, /* Database where the new function is registered */
  28696. + const char *zName, /* Name of the new function */
  28697. + int nArg, /* Number of arguments. -1 means any number */
  28698. + void (*xFunc)(sqlite_func*,int,const char**), /* C code to implement */
  28699. + void *pUserData /* Available via the sqlite_user_data() call */
  28700. +);
  28701. +int sqlite_create_aggregate(
  28702. + sqlite*, /* Database where the new function is registered */
  28703. + const char *zName, /* Name of the function */
  28704. + int nArg, /* Number of arguments */
  28705. + void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
  28706. + void (*xFinalize)(sqlite_func*), /* Called once to get final result */
  28707. + void *pUserData /* Available via the sqlite_user_data() call */
  28708. +);
  28709. +
  28710. +/*
  28711. +** Use the following routine to define the datatype returned by a
  28712. +** user-defined function. The second argument can be one of the
  28713. +** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
  28714. +** can be an integer greater than or equal to zero. When the datatype
  28715. +** parameter is non-negative, the type of the result will be the
  28716. +** same as the datatype-th argument. If datatype==SQLITE_NUMERIC
  28717. +** then the result is always numeric. If datatype==SQLITE_TEXT then
  28718. +** the result is always text. If datatype==SQLITE_ARGS then the result
  28719. +** is numeric if any argument is numeric and is text otherwise.
  28720. +*/
  28721. +int sqlite_function_type(
  28722. + sqlite *db, /* The database there the function is registered */
  28723. + const char *zName, /* Name of the function */
  28724. + int datatype /* The datatype for this function */
  28725. +);
  28726. +#define SQLITE_NUMERIC (-1)
  28727. +/* #define SQLITE_TEXT (-2) // See below */
  28728. +#define SQLITE_ARGS (-3)
  28729. +
  28730. +/*
  28731. +** SQLite version 3 defines SQLITE_TEXT differently. To allow both
  28732. +** version 2 and version 3 to be included, undefine them both if a
  28733. +** conflict is seen. Define SQLITE2_TEXT to be the version 2 value.
  28734. +*/
  28735. +#ifdef SQLITE_TEXT
  28736. +# undef SQLITE_TEXT
  28737. +#else
  28738. +# define SQLITE_TEXT (-2)
  28739. +#endif
  28740. +#define SQLITE2_TEXT (-2)
  28741. +
  28742. +
  28743. +
  28744. +/*
  28745. +** The user function implementations call one of the following four routines
  28746. +** in order to return their results. The first parameter to each of these
  28747. +** routines is a copy of the first argument to xFunc() or xFinialize().
  28748. +** The second parameter to these routines is the result to be returned.
  28749. +** A NULL can be passed as the second parameter to sqlite_set_result_string()
  28750. +** in order to return a NULL result.
  28751. +**
  28752. +** The 3rd argument to _string and _error is the number of characters to
  28753. +** take from the string. If this argument is negative, then all characters
  28754. +** up to and including the first '\000' are used.
  28755. +**
  28756. +** The sqlite_set_result_string() function allocates a buffer to hold the
  28757. +** result and returns a pointer to this buffer. The calling routine
  28758. +** (that is, the implmentation of a user function) can alter the content
  28759. +** of this buffer if desired.
  28760. +*/
  28761. +char *sqlite_set_result_string(sqlite_func*,const char*,int);
  28762. +void sqlite_set_result_int(sqlite_func*,int);
  28763. +void sqlite_set_result_double(sqlite_func*,double);
  28764. +void sqlite_set_result_error(sqlite_func*,const char*,int);
  28765. +
  28766. +/*
  28767. +** The pUserData parameter to the sqlite_create_function() and
  28768. +** sqlite_create_aggregate() routines used to register user functions
  28769. +** is available to the implementation of the function using this
  28770. +** call.
  28771. +*/
  28772. +void *sqlite_user_data(sqlite_func*);
  28773. +
  28774. +/*
  28775. +** Aggregate functions use the following routine to allocate
  28776. +** a structure for storing their state. The first time this routine
  28777. +** is called for a particular aggregate, a new structure of size nBytes
  28778. +** is allocated, zeroed, and returned. On subsequent calls (for the
  28779. +** same aggregate instance) the same buffer is returned. The implementation
  28780. +** of the aggregate can use the returned buffer to accumulate data.
  28781. +**
  28782. +** The buffer allocated is freed automatically be SQLite.
  28783. +*/
  28784. +void *sqlite_aggregate_context(sqlite_func*, int nBytes);
  28785. +
  28786. +/*
  28787. +** The next routine returns the number of calls to xStep for a particular
  28788. +** aggregate function instance. The current call to xStep counts so this
  28789. +** routine always returns at least 1.
  28790. +*/
  28791. +int sqlite_aggregate_count(sqlite_func*);
  28792. +
  28793. +/*
  28794. +** This routine registers a callback with the SQLite library. The
  28795. +** callback is invoked (at compile-time, not at run-time) for each
  28796. +** attempt to access a column of a table in the database. The callback
  28797. +** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
  28798. +** SQL statement should be aborted with an error and SQLITE_IGNORE
  28799. +** if the column should be treated as a NULL value.
  28800. +*/
  28801. +int sqlite_set_authorizer(
  28802. + sqlite*,
  28803. + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  28804. + void *pUserData
  28805. +);
  28806. +
  28807. +/*
  28808. +** The second parameter to the access authorization function above will
  28809. +** be one of the values below. These values signify what kind of operation
  28810. +** is to be authorized. The 3rd and 4th parameters to the authorization
  28811. +** function will be parameters or NULL depending on which of the following
  28812. +** codes is used as the second parameter. The 5th parameter is the name
  28813. +** of the database ("main", "temp", etc.) if applicable. The 6th parameter
  28814. +** is the name of the inner-most trigger or view that is responsible for
  28815. +** the access attempt or NULL if this access attempt is directly from
  28816. +** input SQL code.
  28817. +**
  28818. +** Arg-3 Arg-4
  28819. +*/
  28820. +#define SQLITE_COPY 0 /* Table Name File Name */
  28821. +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  28822. +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  28823. +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  28824. +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  28825. +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  28826. +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  28827. +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  28828. +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  28829. +#define SQLITE_DELETE 9 /* Table Name NULL */
  28830. +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  28831. +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  28832. +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  28833. +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  28834. +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  28835. +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  28836. +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  28837. +#define SQLITE_DROP_VIEW 17 /* View Name NULL */
  28838. +#define SQLITE_INSERT 18 /* Table Name NULL */
  28839. +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  28840. +#define SQLITE_READ 20 /* Table Name Column Name */
  28841. +#define SQLITE_SELECT 21 /* NULL NULL */
  28842. +#define SQLITE_TRANSACTION 22 /* NULL NULL */
  28843. +#define SQLITE_UPDATE 23 /* Table Name Column Name */
  28844. +#define SQLITE_ATTACH 24 /* Filename NULL */
  28845. +#define SQLITE_DETACH 25 /* Database Name NULL */
  28846. +
  28847. +
  28848. +/*
  28849. +** The return value of the authorization function should be one of the
  28850. +** following constants:
  28851. +*/
  28852. +/* #define SQLITE_OK 0 // Allow access (This is actually defined above) */
  28853. +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  28854. +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  28855. +
  28856. +/*
  28857. +** Register a function that is called at every invocation of sqlite_exec()
  28858. +** or sqlite_compile(). This function can be used (for example) to generate
  28859. +** a log file of all SQL executed against a database.
  28860. +*/
  28861. +void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
  28862. +
  28863. +/*** The Callback-Free API
  28864. +**
  28865. +** The following routines implement a new way to access SQLite that does not
  28866. +** involve the use of callbacks.
  28867. +**
  28868. +** An sqlite_vm is an opaque object that represents a single SQL statement
  28869. +** that is ready to be executed.
  28870. +*/
  28871. +typedef struct sqlite_vm sqlite_vm;
  28872. +
  28873. +/*
  28874. +** To execute an SQLite query without the use of callbacks, you first have
  28875. +** to compile the SQL using this routine. The 1st parameter "db" is a pointer
  28876. +** to an sqlite object obtained from sqlite_open(). The 2nd parameter
  28877. +** "zSql" is the text of the SQL to be compiled. The remaining parameters
  28878. +** are all outputs.
  28879. +**
  28880. +** *pzTail is made to point to the first character past the end of the first
  28881. +** SQL statement in zSql. This routine only compiles the first statement
  28882. +** in zSql, so *pzTail is left pointing to what remains uncompiled.
  28883. +**
  28884. +** *ppVm is left pointing to a "virtual machine" that can be used to execute
  28885. +** the compiled statement. Or if there is an error, *ppVm may be set to NULL.
  28886. +** If the input text contained no SQL (if the input is and empty string or
  28887. +** a comment) then *ppVm is set to NULL.
  28888. +**
  28889. +** If any errors are detected during compilation, an error message is written
  28890. +** into space obtained from malloc() and *pzErrMsg is made to point to that
  28891. +** error message. The calling routine is responsible for freeing the text
  28892. +** of this message when it has finished with it. Use sqlite_freemem() to
  28893. +** free the message. pzErrMsg may be NULL in which case no error message
  28894. +** will be generated.
  28895. +**
  28896. +** On success, SQLITE_OK is returned. Otherwise and error code is returned.
  28897. +*/
  28898. +int sqlite_compile(
  28899. + sqlite *db, /* The open database */
  28900. + const char *zSql, /* SQL statement to be compiled */
  28901. + const char **pzTail, /* OUT: uncompiled tail of zSql */
  28902. + sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */
  28903. + char **pzErrmsg /* OUT: Error message. */
  28904. +);
  28905. +
  28906. +/*
  28907. +** After an SQL statement has been compiled, it is handed to this routine
  28908. +** to be executed. This routine executes the statement as far as it can
  28909. +** go then returns. The return value will be one of SQLITE_DONE,
  28910. +** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
  28911. +**
  28912. +** SQLITE_DONE means that the execute of the SQL statement is complete
  28913. +** an no errors have occurred. sqlite_step() should not be called again
  28914. +** for the same virtual machine. *pN is set to the number of columns in
  28915. +** the result set and *pazColName is set to an array of strings that
  28916. +** describe the column names and datatypes. The name of the i-th column
  28917. +** is (*pazColName)[i] and the datatype of the i-th column is
  28918. +** (*pazColName)[i+*pN]. *pazValue is set to NULL.
  28919. +**
  28920. +** SQLITE_ERROR means that the virtual machine encountered a run-time
  28921. +** error. sqlite_step() should not be called again for the same
  28922. +** virtual machine. *pN is set to 0 and *pazColName and *pazValue are set
  28923. +** to NULL. Use sqlite_finalize() to obtain the specific error code
  28924. +** and the error message text for the error.
  28925. +**
  28926. +** SQLITE_BUSY means that an attempt to open the database failed because
  28927. +** another thread or process is holding a lock. The calling routine
  28928. +** can try again to open the database by calling sqlite_step() again.
  28929. +** The return code will only be SQLITE_BUSY if no busy handler is registered
  28930. +** using the sqlite_busy_handler() or sqlite_busy_timeout() routines. If
  28931. +** a busy handler callback has been registered but returns 0, then this
  28932. +** routine will return SQLITE_ERROR and sqltie_finalize() will return
  28933. +** SQLITE_BUSY when it is called.
  28934. +**
  28935. +** SQLITE_ROW means that a single row of the result is now available.
  28936. +** The data is contained in *pazValue. The value of the i-th column is
  28937. +** (*azValue)[i]. *pN and *pazColName are set as described in SQLITE_DONE.
  28938. +** Invoke sqlite_step() again to advance to the next row.
  28939. +**
  28940. +** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
  28941. +** For example, if you call sqlite_step() after the virtual machine
  28942. +** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
  28943. +** or if you call sqlite_step() with an incorrectly initialized virtual
  28944. +** machine or a virtual machine that has been deleted or that is associated
  28945. +** with an sqlite structure that has been closed.
  28946. +*/
  28947. +int sqlite_step(
  28948. + sqlite_vm *pVm, /* The virtual machine to execute */
  28949. + int *pN, /* OUT: Number of columns in result */
  28950. + const char ***pazValue, /* OUT: Column data */
  28951. + const char ***pazColName /* OUT: Column names and datatypes */
  28952. +);
  28953. +
  28954. +/*
  28955. +** This routine is called to delete a virtual machine after it has finished
  28956. +** executing. The return value is the result code. SQLITE_OK is returned
  28957. +** if the statement executed successfully and some other value is returned if
  28958. +** there was any kind of error. If an error occurred and pzErrMsg is not
  28959. +** NULL, then an error message is written into memory obtained from malloc()
  28960. +** and *pzErrMsg is made to point to that error message. The calling routine
  28961. +** should use sqlite_freemem() to delete this message when it has finished
  28962. +** with it.
  28963. +**
  28964. +** This routine can be called at any point during the execution of the
  28965. +** virtual machine. If the virtual machine has not completed execution
  28966. +** when this routine is called, that is like encountering an error or
  28967. +** an interrupt. (See sqlite_interrupt().) Incomplete updates may be
  28968. +** rolled back and transactions cancelled, depending on the circumstances,
  28969. +** and the result code returned will be SQLITE_ABORT.
  28970. +*/
  28971. +int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
  28972. +
  28973. +/*
  28974. +** This routine deletes the virtual machine, writes any error message to
  28975. +** *pzErrMsg and returns an SQLite return code in the same way as the
  28976. +** sqlite_finalize() function.
  28977. +**
  28978. +** Additionally, if ppVm is not NULL, *ppVm is left pointing to a new virtual
  28979. +** machine loaded with the compiled version of the original query ready for
  28980. +** execution.
  28981. +**
  28982. +** If sqlite_reset() returns SQLITE_SCHEMA, then *ppVm is set to NULL.
  28983. +**
  28984. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  28985. +*/
  28986. +int sqlite_reset(sqlite_vm*, char **pzErrMsg);
  28987. +
  28988. +/*
  28989. +** If the SQL that was handed to sqlite_compile contains variables that
  28990. +** are represeted in the SQL text by a question mark ('?'). This routine
  28991. +** is used to assign values to those variables.
  28992. +**
  28993. +** The first parameter is a virtual machine obtained from sqlite_compile().
  28994. +** The 2nd "idx" parameter determines which variable in the SQL statement
  28995. +** to bind the value to. The left most '?' is 1. The 3rd parameter is
  28996. +** the value to assign to that variable. The 4th parameter is the number
  28997. +** of bytes in the value, including the terminating \000 for strings.
  28998. +** Finally, the 5th "copy" parameter is TRUE if SQLite should make its
  28999. +** own private copy of this value, or false if the space that the 3rd
  29000. +** parameter points to will be unchanging and can be used directly by
  29001. +** SQLite.
  29002. +**
  29003. +** Unbound variables are treated as having a value of NULL. To explicitly
  29004. +** set a variable to NULL, call this routine with the 3rd parameter as a
  29005. +** NULL pointer.
  29006. +**
  29007. +** If the 4th "len" parameter is -1, then strlen() is used to find the
  29008. +** length.
  29009. +**
  29010. +** This routine can only be called immediately after sqlite_compile()
  29011. +** or sqlite_reset() and before any calls to sqlite_step().
  29012. +**
  29013. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  29014. +*/
  29015. +int sqlite_bind(sqlite_vm*, int idx, const char *value, int len, int copy);
  29016. +
  29017. +/*
  29018. +** This routine configures a callback function - the progress callback - that
  29019. +** is invoked periodically during long running calls to sqlite_exec(),
  29020. +** sqlite_step() and sqlite_get_table(). An example use for this API is to keep
  29021. +** a GUI updated during a large query.
  29022. +**
  29023. +** The progress callback is invoked once for every N virtual machine opcodes,
  29024. +** where N is the second argument to this function. The progress callback
  29025. +** itself is identified by the third argument to this function. The fourth
  29026. +** argument to this function is a void pointer passed to the progress callback
  29027. +** function each time it is invoked.
  29028. +**
  29029. +** If a call to sqlite_exec(), sqlite_step() or sqlite_get_table() results
  29030. +** in less than N opcodes being executed, then the progress callback is not
  29031. +** invoked.
  29032. +**
  29033. +** Calling this routine overwrites any previously installed progress callback.
  29034. +** To remove the progress callback altogether, pass NULL as the third
  29035. +** argument to this function.
  29036. +**
  29037. +** If the progress callback returns a result other than 0, then the current
  29038. +** query is immediately terminated and any database changes rolled back. If the
  29039. +** query was part of a larger transaction, then the transaction is not rolled
  29040. +** back and remains active. The sqlite_exec() call returns SQLITE_ABORT.
  29041. +**
  29042. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  29043. +*/
  29044. +void sqlite_progress_handler(sqlite*, int, int(*)(void*), void*);
  29045. +
  29046. +/*
  29047. +** Register a callback function to be invoked whenever a new transaction
  29048. +** is committed. The pArg argument is passed through to the callback.
  29049. +** callback. If the callback function returns non-zero, then the commit
  29050. +** is converted into a rollback.
  29051. +**
  29052. +** If another function was previously registered, its pArg value is returned.
  29053. +** Otherwise NULL is returned.
  29054. +**
  29055. +** Registering a NULL function disables the callback.
  29056. +**
  29057. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  29058. +*/
  29059. +void *sqlite_commit_hook(sqlite*, int(*)(void*), void*);
  29060. +
  29061. +/*
  29062. +** Open an encrypted SQLite database. If pKey==0 or nKey==0, this routine
  29063. +** is the same as sqlite_open().
  29064. +**
  29065. +** The code to implement this API is not available in the public release
  29066. +** of SQLite.
  29067. +*/
  29068. +sqlite *sqlite_open_encrypted(
  29069. + const char *zFilename, /* Name of the encrypted database */
  29070. + const void *pKey, /* Pointer to the key */
  29071. + int nKey, /* Number of bytes in the key */
  29072. + int *pErrcode, /* Write error code here */
  29073. + char **pzErrmsg /* Write error message here */
  29074. +);
  29075. +
  29076. +/*
  29077. +** Change the key on an open database. If the current database is not
  29078. +** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  29079. +** database is decrypted.
  29080. +**
  29081. +** The code to implement this API is not available in the public release
  29082. +** of SQLite.
  29083. +*/
  29084. +int sqlite_rekey(
  29085. + sqlite *db, /* Database to be rekeyed */
  29086. + const void *pKey, int nKey /* The new key */
  29087. +);
  29088. +
  29089. +/*
  29090. +** Encode a binary buffer "in" of size n bytes so that it contains
  29091. +** no instances of characters '\'' or '\000'. The output is
  29092. +** null-terminated and can be used as a string value in an INSERT
  29093. +** or UPDATE statement. Use sqlite_decode_binary() to convert the
  29094. +** string back into its original binary.
  29095. +**
  29096. +** The result is written into a preallocated output buffer "out".
  29097. +** "out" must be able to hold at least 2 +(257*n)/254 bytes.
  29098. +** In other words, the output will be expanded by as much as 3
  29099. +** bytes for every 254 bytes of input plus 2 bytes of fixed overhead.
  29100. +** (This is approximately 2 + 1.0118*n or about a 1.2% size increase.)
  29101. +**
  29102. +** The return value is the number of characters in the encoded
  29103. +** string, excluding the "\000" terminator.
  29104. +**
  29105. +** If out==NULL then no output is generated but the routine still returns
  29106. +** the number of characters that would have been generated if out had
  29107. +** not been NULL.
  29108. +*/
  29109. +int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
  29110. +
  29111. +/*
  29112. +** Decode the string "in" into binary data and write it into "out".
  29113. +** This routine reverses the encoding created by sqlite_encode_binary().
  29114. +** The output will always be a few bytes less than the input. The number
  29115. +** of bytes of output is returned. If the input is not a well-formed
  29116. +** encoding, -1 is returned.
  29117. +**
  29118. +** The "in" and "out" parameters may point to the same buffer in order
  29119. +** to decode a string in place.
  29120. +*/
  29121. +int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
  29122. +
  29123. +#ifdef __cplusplus
  29124. +} /* End of the 'extern "C"' block */
  29125. +#endif
  29126. +
  29127. +#endif /* _SQLITE_H_ */
  29128. --- /dev/null
  29129. +++ b/ext/sqlite/libsqlite/src/sqliteInt.h
  29130. @@ -0,0 +1,1270 @@
  29131. +/*
  29132. +** 2001 September 15
  29133. +**
  29134. +** The author disclaims copyright to this source code. In place of
  29135. +** a legal notice, here is a blessing:
  29136. +**
  29137. +** May you do good and not evil.
  29138. +** May you find forgiveness for yourself and forgive others.
  29139. +** May you share freely, never taking more than you give.
  29140. +**
  29141. +*************************************************************************
  29142. +** Internal interface definitions for SQLite.
  29143. +**
  29144. +** @(#) $Id$
  29145. +*/
  29146. +#include "config.h"
  29147. +#include "sqlite.h"
  29148. +#include "hash.h"
  29149. +#include "parse.h"
  29150. +#include "btree.h"
  29151. +#include <stdio.h>
  29152. +#include <stdlib.h>
  29153. +#include <string.h>
  29154. +#include <assert.h>
  29155. +
  29156. +/*
  29157. +** The maximum number of in-memory pages to use for the main database
  29158. +** table and for temporary tables.
  29159. +*/
  29160. +#define MAX_PAGES 2000
  29161. +#define TEMP_PAGES 500
  29162. +
  29163. +/*
  29164. +** If the following macro is set to 1, then NULL values are considered
  29165. +** distinct for the SELECT DISTINCT statement and for UNION or EXCEPT
  29166. +** compound queries. No other SQL database engine (among those tested)
  29167. +** works this way except for OCELOT. But the SQL92 spec implies that
  29168. +** this is how things should work.
  29169. +**
  29170. +** If the following macro is set to 0, then NULLs are indistinct for
  29171. +** SELECT DISTINCT and for UNION.
  29172. +*/
  29173. +#define NULL_ALWAYS_DISTINCT 0
  29174. +
  29175. +/*
  29176. +** If the following macro is set to 1, then NULL values are considered
  29177. +** distinct when determining whether or not two entries are the same
  29178. +** in a UNIQUE index. This is the way PostgreSQL, Oracle, DB2, MySQL,
  29179. +** OCELOT, and Firebird all work. The SQL92 spec explicitly says this
  29180. +** is the way things are suppose to work.
  29181. +**
  29182. +** If the following macro is set to 0, the NULLs are indistinct for
  29183. +** a UNIQUE index. In this mode, you can only have a single NULL entry
  29184. +** for a column declared UNIQUE. This is the way Informix and SQL Server
  29185. +** work.
  29186. +*/
  29187. +#define NULL_DISTINCT_FOR_UNIQUE 1
  29188. +
  29189. +/*
  29190. +** The maximum number of attached databases. This must be at least 2
  29191. +** in order to support the main database file (0) and the file used to
  29192. +** hold temporary tables (1). And it must be less than 256 because
  29193. +** an unsigned character is used to stored the database index.
  29194. +*/
  29195. +#define MAX_ATTACHED 10
  29196. +
  29197. +/*
  29198. +** The next macro is used to determine where TEMP tables and indices
  29199. +** are stored. Possible values:
  29200. +**
  29201. +** 0 Always use a temporary files
  29202. +** 1 Use a file unless overridden by "PRAGMA temp_store"
  29203. +** 2 Use memory unless overridden by "PRAGMA temp_store"
  29204. +** 3 Always use memory
  29205. +*/
  29206. +#ifndef TEMP_STORE
  29207. +# define TEMP_STORE 1
  29208. +#endif
  29209. +
  29210. +/*
  29211. +** When building SQLite for embedded systems where memory is scarce,
  29212. +** you can define one or more of the following macros to omit extra
  29213. +** features of the library and thus keep the size of the library to
  29214. +** a minimum.
  29215. +*/
  29216. +/* #define SQLITE_OMIT_AUTHORIZATION 1 */
  29217. +/* #define SQLITE_OMIT_INMEMORYDB 1 */
  29218. +/* #define SQLITE_OMIT_VACUUM 1 */
  29219. +/* #define SQLITE_OMIT_DATETIME_FUNCS 1 */
  29220. +/* #define SQLITE_OMIT_PROGRESS_CALLBACK 1 */
  29221. +
  29222. +/*
  29223. +** Integers of known sizes. These typedefs might change for architectures
  29224. +** where the sizes very. Preprocessor macros are available so that the
  29225. +** types can be conveniently redefined at compile-type. Like this:
  29226. +**
  29227. +** cc '-DUINTPTR_TYPE=long long int' ...
  29228. +*/
  29229. +#ifndef UINT32_TYPE
  29230. +# define UINT32_TYPE unsigned int
  29231. +#endif
  29232. +#ifndef UINT16_TYPE
  29233. +# define UINT16_TYPE unsigned short int
  29234. +#endif
  29235. +#ifndef INT16_TYPE
  29236. +# define INT16_TYPE short int
  29237. +#endif
  29238. +#ifndef UINT8_TYPE
  29239. +# define UINT8_TYPE unsigned char
  29240. +#endif
  29241. +#ifndef INT8_TYPE
  29242. +# define INT8_TYPE signed char
  29243. +#endif
  29244. +#ifndef INTPTR_TYPE
  29245. +# if SQLITE_PTR_SZ==4
  29246. +# define INTPTR_TYPE int
  29247. +# else
  29248. +# define INTPTR_TYPE long long
  29249. +# endif
  29250. +#endif
  29251. +typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  29252. +typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  29253. +typedef INT16_TYPE i16; /* 2-byte signed integer */
  29254. +typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  29255. +typedef UINT8_TYPE i8; /* 1-byte signed integer */
  29256. +typedef INTPTR_TYPE ptr; /* Big enough to hold a pointer */
  29257. +typedef unsigned INTPTR_TYPE uptr; /* Big enough to hold a pointer */
  29258. +
  29259. +/*
  29260. +** Defer sourcing vdbe.h until after the "u8" typedef is defined.
  29261. +*/
  29262. +#include "vdbe.h"
  29263. +
  29264. +/*
  29265. +** Most C compilers these days recognize "long double", don't they?
  29266. +** Just in case we encounter one that does not, we will create a macro
  29267. +** for long double so that it can be easily changed to just "double".
  29268. +*/
  29269. +#ifndef LONGDOUBLE_TYPE
  29270. +# define LONGDOUBLE_TYPE long double
  29271. +#endif
  29272. +
  29273. +/*
  29274. +** This macro casts a pointer to an integer. Useful for doing
  29275. +** pointer arithmetic.
  29276. +*/
  29277. +#define Addr(X) ((uptr)X)
  29278. +
  29279. +/*
  29280. +** The maximum number of bytes of data that can be put into a single
  29281. +** row of a single table. The upper bound on this limit is 16777215
  29282. +** bytes (or 16MB-1). We have arbitrarily set the limit to just 1MB
  29283. +** here because the overflow page chain is inefficient for really big
  29284. +** records and we want to discourage people from thinking that
  29285. +** multi-megabyte records are OK. If your needs are different, you can
  29286. +** change this define and recompile to increase or decrease the record
  29287. +** size.
  29288. +**
  29289. +** The 16777198 is computed as follows: 238 bytes of payload on the
  29290. +** original pages plus 16448 overflow pages each holding 1020 bytes of
  29291. +** data.
  29292. +*/
  29293. +#define MAX_BYTES_PER_ROW 1048576
  29294. +/* #define MAX_BYTES_PER_ROW 16777198 */
  29295. +
  29296. +/*
  29297. +** If memory allocation problems are found, recompile with
  29298. +**
  29299. +** -DMEMORY_DEBUG=1
  29300. +**
  29301. +** to enable some sanity checking on malloc() and free(). To
  29302. +** check for memory leaks, recompile with
  29303. +**
  29304. +** -DMEMORY_DEBUG=2
  29305. +**
  29306. +** and a line of text will be written to standard error for
  29307. +** each malloc() and free(). This output can be analyzed
  29308. +** by an AWK script to determine if there are any leaks.
  29309. +*/
  29310. +#ifdef MEMORY_DEBUG
  29311. +# define sqliteMalloc(X) sqliteMalloc_(X,1,__FILE__,__LINE__)
  29312. +# define sqliteMallocRaw(X) sqliteMalloc_(X,0,__FILE__,__LINE__)
  29313. +# define sqliteFree(X) sqliteFree_(X,__FILE__,__LINE__)
  29314. +# define sqliteRealloc(X,Y) sqliteRealloc_(X,Y,__FILE__,__LINE__)
  29315. +# define sqliteStrDup(X) sqliteStrDup_(X,__FILE__,__LINE__)
  29316. +# define sqliteStrNDup(X,Y) sqliteStrNDup_(X,Y,__FILE__,__LINE__)
  29317. + void sqliteStrRealloc(char**);
  29318. +#else
  29319. +# define sqliteRealloc_(X,Y) sqliteRealloc(X,Y)
  29320. +# define sqliteStrRealloc(X)
  29321. +#endif
  29322. +
  29323. +/*
  29324. +** This variable gets set if malloc() ever fails. After it gets set,
  29325. +** the SQLite library shuts down permanently.
  29326. +*/
  29327. +extern int sqlite_malloc_failed;
  29328. +
  29329. +/*
  29330. +** The following global variables are used for testing and debugging
  29331. +** only. They only work if MEMORY_DEBUG is defined.
  29332. +*/
  29333. +#ifdef MEMORY_DEBUG
  29334. +extern int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
  29335. +extern int sqlite_nFree; /* Number of sqliteFree() calls */
  29336. +extern int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
  29337. +#endif
  29338. +
  29339. +/*
  29340. +** Name of the master database table. The master database table
  29341. +** is a special table that holds the names and attributes of all
  29342. +** user tables and indices.
  29343. +*/
  29344. +#define MASTER_NAME "sqlite_master"
  29345. +#define TEMP_MASTER_NAME "sqlite_temp_master"
  29346. +
  29347. +/*
  29348. +** The name of the schema table.
  29349. +*/
  29350. +#define SCHEMA_TABLE(x) (x?TEMP_MASTER_NAME:MASTER_NAME)
  29351. +
  29352. +/*
  29353. +** A convenience macro that returns the number of elements in
  29354. +** an array.
  29355. +*/
  29356. +#define ArraySize(X) (sizeof(X)/sizeof(X[0]))
  29357. +
  29358. +/*
  29359. +** Forward references to structures
  29360. +*/
  29361. +typedef struct Column Column;
  29362. +typedef struct Table Table;
  29363. +typedef struct Index Index;
  29364. +typedef struct Instruction Instruction;
  29365. +typedef struct Expr Expr;
  29366. +typedef struct ExprList ExprList;
  29367. +typedef struct Parse Parse;
  29368. +typedef struct Token Token;
  29369. +typedef struct IdList IdList;
  29370. +typedef struct SrcList SrcList;
  29371. +typedef struct WhereInfo WhereInfo;
  29372. +typedef struct WhereLevel WhereLevel;
  29373. +typedef struct Select Select;
  29374. +typedef struct AggExpr AggExpr;
  29375. +typedef struct FuncDef FuncDef;
  29376. +typedef struct Trigger Trigger;
  29377. +typedef struct TriggerStep TriggerStep;
  29378. +typedef struct TriggerStack TriggerStack;
  29379. +typedef struct FKey FKey;
  29380. +typedef struct Db Db;
  29381. +typedef struct AuthContext AuthContext;
  29382. +
  29383. +/*
  29384. +** Each database file to be accessed by the system is an instance
  29385. +** of the following structure. There are normally two of these structures
  29386. +** in the sqlite.aDb[] array. aDb[0] is the main database file and
  29387. +** aDb[1] is the database file used to hold temporary tables. Additional
  29388. +** databases may be attached.
  29389. +*/
  29390. +struct Db {
  29391. + char *zName; /* Name of this database */
  29392. + Btree *pBt; /* The B*Tree structure for this database file */
  29393. + int schema_cookie; /* Database schema version number for this file */
  29394. + Hash tblHash; /* All tables indexed by name */
  29395. + Hash idxHash; /* All (named) indices indexed by name */
  29396. + Hash trigHash; /* All triggers indexed by name */
  29397. + Hash aFKey; /* Foreign keys indexed by to-table */
  29398. + u8 inTrans; /* 0: not writable. 1: Transaction. 2: Checkpoint */
  29399. + u16 flags; /* Flags associated with this database */
  29400. + void *pAux; /* Auxiliary data. Usually NULL */
  29401. + void (*xFreeAux)(void*); /* Routine to free pAux */
  29402. +};
  29403. +
  29404. +/*
  29405. +** These macros can be used to test, set, or clear bits in the
  29406. +** Db.flags field.
  29407. +*/
  29408. +#define DbHasProperty(D,I,P) (((D)->aDb[I].flags&(P))==(P))
  29409. +#define DbHasAnyProperty(D,I,P) (((D)->aDb[I].flags&(P))!=0)
  29410. +#define DbSetProperty(D,I,P) (D)->aDb[I].flags|=(P)
  29411. +#define DbClearProperty(D,I,P) (D)->aDb[I].flags&=~(P)
  29412. +
  29413. +/*
  29414. +** Allowed values for the DB.flags field.
  29415. +**
  29416. +** The DB_Locked flag is set when the first OP_Transaction or OP_Checkpoint
  29417. +** opcode is emitted for a database. This prevents multiple occurances
  29418. +** of those opcodes for the same database in the same program. Similarly,
  29419. +** the DB_Cookie flag is set when the OP_VerifyCookie opcode is emitted,
  29420. +** and prevents duplicate OP_VerifyCookies from taking up space and slowing
  29421. +** down execution.
  29422. +**
  29423. +** The DB_SchemaLoaded flag is set after the database schema has been
  29424. +** read into internal hash tables.
  29425. +**
  29426. +** DB_UnresetViews means that one or more views have column names that
  29427. +** have been filled out. If the schema changes, these column names might
  29428. +** changes and so the view will need to be reset.
  29429. +*/
  29430. +#define DB_Locked 0x0001 /* OP_Transaction opcode has been emitted */
  29431. +#define DB_Cookie 0x0002 /* OP_VerifyCookie opcode has been emiited */
  29432. +#define DB_SchemaLoaded 0x0004 /* The schema has been loaded */
  29433. +#define DB_UnresetViews 0x0008 /* Some views have defined column names */
  29434. +
  29435. +
  29436. +/*
  29437. +** Each database is an instance of the following structure.
  29438. +**
  29439. +** The sqlite.file_format is initialized by the database file
  29440. +** and helps determines how the data in the database file is
  29441. +** represented. This field allows newer versions of the library
  29442. +** to read and write older databases. The various file formats
  29443. +** are as follows:
  29444. +**
  29445. +** file_format==1 Version 2.1.0.
  29446. +** file_format==2 Version 2.2.0. Add support for INTEGER PRIMARY KEY.
  29447. +** file_format==3 Version 2.6.0. Fix empty-string index bug.
  29448. +** file_format==4 Version 2.7.0. Add support for separate numeric and
  29449. +** text datatypes.
  29450. +**
  29451. +** The sqlite.temp_store determines where temporary database files
  29452. +** are stored. If 1, then a file is created to hold those tables. If
  29453. +** 2, then they are held in memory. 0 means use the default value in
  29454. +** the TEMP_STORE macro.
  29455. +**
  29456. +** The sqlite.lastRowid records the last insert rowid generated by an
  29457. +** insert statement. Inserts on views do not affect its value. Each
  29458. +** trigger has its own context, so that lastRowid can be updated inside
  29459. +** triggers as usual. The previous value will be restored once the trigger
  29460. +** exits. Upon entering a before or instead of trigger, lastRowid is no
  29461. +** longer (since after version 2.8.12) reset to -1.
  29462. +**
  29463. +** The sqlite.nChange does not count changes within triggers and keeps no
  29464. +** context. It is reset at start of sqlite_exec.
  29465. +** The sqlite.lsChange represents the number of changes made by the last
  29466. +** insert, update, or delete statement. It remains constant throughout the
  29467. +** length of a statement and is then updated by OP_SetCounts. It keeps a
  29468. +** context stack just like lastRowid so that the count of changes
  29469. +** within a trigger is not seen outside the trigger. Changes to views do not
  29470. +** affect the value of lsChange.
  29471. +** The sqlite.csChange keeps track of the number of current changes (since
  29472. +** the last statement) and is used to update sqlite_lsChange.
  29473. +*/
  29474. +struct sqlite {
  29475. + int nDb; /* Number of backends currently in use */
  29476. + Db *aDb; /* All backends */
  29477. + Db aDbStatic[2]; /* Static space for the 2 default backends */
  29478. + int flags; /* Miscellanous flags. See below */
  29479. + u8 file_format; /* What file format version is this database? */
  29480. + u8 safety_level; /* How aggressive at synching data to disk */
  29481. + u8 want_to_close; /* Close after all VDBEs are deallocated */
  29482. + u8 temp_store; /* 1=file, 2=memory, 0=compile-time default */
  29483. + u8 onError; /* Default conflict algorithm */
  29484. + int next_cookie; /* Next value of aDb[0].schema_cookie */
  29485. + int cache_size; /* Number of pages to use in the cache */
  29486. + int nTable; /* Number of tables in the database */
  29487. + void *pBusyArg; /* 1st Argument to the busy callback */
  29488. + int (*xBusyCallback)(void *,const char*,int); /* The busy callback */
  29489. + void *pCommitArg; /* Argument to xCommitCallback() */
  29490. + int (*xCommitCallback)(void*);/* Invoked at every commit. */
  29491. + Hash aFunc; /* All functions that can be in SQL exprs */
  29492. + int lastRowid; /* ROWID of most recent insert (see above) */
  29493. + int priorNewRowid; /* Last randomly generated ROWID */
  29494. + int magic; /* Magic number for detect library misuse */
  29495. + int nChange; /* Number of rows changed (see above) */
  29496. + int lsChange; /* Last statement change count (see above) */
  29497. + int csChange; /* Current statement change count (see above) */
  29498. + struct sqliteInitInfo { /* Information used during initialization */
  29499. + int iDb; /* When back is being initialized */
  29500. + int newTnum; /* Rootpage of table being initialized */
  29501. + u8 busy; /* TRUE if currently initializing */
  29502. + } init;
  29503. + struct Vdbe *pVdbe; /* List of active virtual machines */
  29504. + void (*xTrace)(void*,const char*); /* Trace function */
  29505. + void *pTraceArg; /* Argument to the trace function */
  29506. +#ifndef SQLITE_OMIT_AUTHORIZATION
  29507. + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
  29508. + /* Access authorization function */
  29509. + void *pAuthArg; /* 1st argument to the access auth function */
  29510. +#endif
  29511. +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  29512. + int (*xProgress)(void *); /* The progress callback */
  29513. + void *pProgressArg; /* Argument to the progress callback */
  29514. + int nProgressOps; /* Number of opcodes for progress callback */
  29515. +#endif
  29516. +};
  29517. +
  29518. +/*
  29519. +** Possible values for the sqlite.flags and or Db.flags fields.
  29520. +**
  29521. +** On sqlite.flags, the SQLITE_InTrans value means that we have
  29522. +** executed a BEGIN. On Db.flags, SQLITE_InTrans means a statement
  29523. +** transaction is active on that particular database file.
  29524. +*/
  29525. +#define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  29526. +#define SQLITE_Initialized 0x00000002 /* True after initialization */
  29527. +#define SQLITE_Interrupt 0x00000004 /* Cancel current operation */
  29528. +#define SQLITE_InTrans 0x00000008 /* True if in a transaction */
  29529. +#define SQLITE_InternChanges 0x00000010 /* Uncommitted Hash table changes */
  29530. +#define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  29531. +#define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  29532. +#define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  29533. + /* DELETE, or UPDATE and return */
  29534. + /* the count using a callback. */
  29535. +#define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  29536. + /* result set is empty */
  29537. +#define SQLITE_ReportTypes 0x00000200 /* Include information on datatypes */
  29538. + /* in 4th argument of callback */
  29539. +
  29540. +/*
  29541. +** Possible values for the sqlite.magic field.
  29542. +** The numbers are obtained at random and have no special meaning, other
  29543. +** than being distinct from one another.
  29544. +*/
  29545. +#define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  29546. +#define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  29547. +#define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  29548. +#define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  29549. +
  29550. +/*
  29551. +** Each SQL function is defined by an instance of the following
  29552. +** structure. A pointer to this structure is stored in the sqlite.aFunc
  29553. +** hash table. When multiple functions have the same name, the hash table
  29554. +** points to a linked list of these structures.
  29555. +*/
  29556. +struct FuncDef {
  29557. + void (*xFunc)(sqlite_func*,int,const char**); /* Regular function */
  29558. + void (*xStep)(sqlite_func*,int,const char**); /* Aggregate function step */
  29559. + void (*xFinalize)(sqlite_func*); /* Aggregate function finializer */
  29560. + signed char nArg; /* Number of arguments. -1 means unlimited */
  29561. + signed char dataType; /* Arg that determines datatype. -1=NUMERIC, */
  29562. + /* -2=TEXT. -3=SQLITE_ARGS */
  29563. + u8 includeTypes; /* Add datatypes to args of xFunc and xStep */
  29564. + void *pUserData; /* User data parameter */
  29565. + FuncDef *pNext; /* Next function with same name */
  29566. +};
  29567. +
  29568. +/*
  29569. +** information about each column of an SQL table is held in an instance
  29570. +** of this structure.
  29571. +*/
  29572. +struct Column {
  29573. + char *zName; /* Name of this column */
  29574. + char *zDflt; /* Default value of this column */
  29575. + char *zType; /* Data type for this column */
  29576. + u8 notNull; /* True if there is a NOT NULL constraint */
  29577. + u8 isPrimKey; /* True if this column is part of the PRIMARY KEY */
  29578. + u8 sortOrder; /* Some combination of SQLITE_SO_... values */
  29579. + u8 dottedName; /* True if zName contains a "." character */
  29580. +};
  29581. +
  29582. +/*
  29583. +** The allowed sort orders.
  29584. +**
  29585. +** The TEXT and NUM values use bits that do not overlap with DESC and ASC.
  29586. +** That way the two can be combined into a single number.
  29587. +*/
  29588. +#define SQLITE_SO_UNK 0 /* Use the default collating type. (SCT_NUM) */
  29589. +#define SQLITE_SO_TEXT 2 /* Sort using memcmp() */
  29590. +#define SQLITE_SO_NUM 4 /* Sort using sqliteCompare() */
  29591. +#define SQLITE_SO_TYPEMASK 6 /* Mask to extract the collating sequence */
  29592. +#define SQLITE_SO_ASC 0 /* Sort in ascending order */
  29593. +#define SQLITE_SO_DESC 1 /* Sort in descending order */
  29594. +#define SQLITE_SO_DIRMASK 1 /* Mask to extract the sort direction */
  29595. +
  29596. +/*
  29597. +** Each SQL table is represented in memory by an instance of the
  29598. +** following structure.
  29599. +**
  29600. +** Table.zName is the name of the table. The case of the original
  29601. +** CREATE TABLE statement is stored, but case is not significant for
  29602. +** comparisons.
  29603. +**
  29604. +** Table.nCol is the number of columns in this table. Table.aCol is a
  29605. +** pointer to an array of Column structures, one for each column.
  29606. +**
  29607. +** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  29608. +** the column that is that key. Otherwise Table.iPKey is negative. Note
  29609. +** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  29610. +** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  29611. +** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  29612. +** is generated for each row of the table. Table.hasPrimKey is true if
  29613. +** the table has any PRIMARY KEY, INTEGER or otherwise.
  29614. +**
  29615. +** Table.tnum is the page number for the root BTree page of the table in the
  29616. +** database file. If Table.iDb is the index of the database table backend
  29617. +** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  29618. +** holds temporary tables and indices. If Table.isTransient
  29619. +** is true, then the table is stored in a file that is automatically deleted
  29620. +** when the VDBE cursor to the table is closed. In this case Table.tnum
  29621. +** refers VDBE cursor number that holds the table open, not to the root
  29622. +** page number. Transient tables are used to hold the results of a
  29623. +** sub-query that appears instead of a real table name in the FROM clause
  29624. +** of a SELECT statement.
  29625. +*/
  29626. +struct Table {
  29627. + char *zName; /* Name of the table */
  29628. + int nCol; /* Number of columns in this table */
  29629. + Column *aCol; /* Information about each column */
  29630. + int iPKey; /* If not less then 0, use aCol[iPKey] as the primary key */
  29631. + Index *pIndex; /* List of SQL indexes on this table. */
  29632. + int tnum; /* Root BTree node for this table (see note above) */
  29633. + Select *pSelect; /* NULL for tables. Points to definition if a view. */
  29634. + u8 readOnly; /* True if this table should not be written by the user */
  29635. + u8 iDb; /* Index into sqlite.aDb[] of the backend for this table */
  29636. + u8 isTransient; /* True if automatically deleted when VDBE finishes */
  29637. + u8 hasPrimKey; /* True if there exists a primary key */
  29638. + u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  29639. + Trigger *pTrigger; /* List of SQL triggers on this table */
  29640. + FKey *pFKey; /* Linked list of all foreign keys in this table */
  29641. +};
  29642. +
  29643. +/*
  29644. +** Each foreign key constraint is an instance of the following structure.
  29645. +**
  29646. +** A foreign key is associated with two tables. The "from" table is
  29647. +** the table that contains the REFERENCES clause that creates the foreign
  29648. +** key. The "to" table is the table that is named in the REFERENCES clause.
  29649. +** Consider this example:
  29650. +**
  29651. +** CREATE TABLE ex1(
  29652. +** a INTEGER PRIMARY KEY,
  29653. +** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  29654. +** );
  29655. +**
  29656. +** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  29657. +**
  29658. +** Each REFERENCES clause generates an instance of the following structure
  29659. +** which is attached to the from-table. The to-table need not exist when
  29660. +** the from-table is created. The existance of the to-table is not checked
  29661. +** until an attempt is made to insert data into the from-table.
  29662. +**
  29663. +** The sqlite.aFKey hash table stores pointers to this structure
  29664. +** given the name of a to-table. For each to-table, all foreign keys
  29665. +** associated with that table are on a linked list using the FKey.pNextTo
  29666. +** field.
  29667. +*/
  29668. +struct FKey {
  29669. + Table *pFrom; /* The table that constains the REFERENCES clause */
  29670. + FKey *pNextFrom; /* Next foreign key in pFrom */
  29671. + char *zTo; /* Name of table that the key points to */
  29672. + FKey *pNextTo; /* Next foreign key that points to zTo */
  29673. + int nCol; /* Number of columns in this key */
  29674. + struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  29675. + int iFrom; /* Index of column in pFrom */
  29676. + char *zCol; /* Name of column in zTo. If 0 use PRIMARY KEY */
  29677. + } *aCol; /* One entry for each of nCol column s */
  29678. + u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  29679. + u8 updateConf; /* How to resolve conflicts that occur on UPDATE */
  29680. + u8 deleteConf; /* How to resolve conflicts that occur on DELETE */
  29681. + u8 insertConf; /* How to resolve conflicts that occur on INSERT */
  29682. +};
  29683. +
  29684. +/*
  29685. +** SQLite supports many different ways to resolve a contraint
  29686. +** error. ROLLBACK processing means that a constraint violation
  29687. +** causes the operation in process to fail and for the current transaction
  29688. +** to be rolled back. ABORT processing means the operation in process
  29689. +** fails and any prior changes from that one operation are backed out,
  29690. +** but the transaction is not rolled back. FAIL processing means that
  29691. +** the operation in progress stops and returns an error code. But prior
  29692. +** changes due to the same operation are not backed out and no rollback
  29693. +** occurs. IGNORE means that the particular row that caused the constraint
  29694. +** error is not inserted or updated. Processing continues and no error
  29695. +** is returned. REPLACE means that preexisting database rows that caused
  29696. +** a UNIQUE constraint violation are removed so that the new insert or
  29697. +** update can proceed. Processing continues and no error is reported.
  29698. +**
  29699. +** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  29700. +** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  29701. +** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  29702. +** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  29703. +** referenced table row is propagated into the row that holds the
  29704. +** foreign key.
  29705. +**
  29706. +** The following symbolic values are used to record which type
  29707. +** of action to take.
  29708. +*/
  29709. +#define OE_None 0 /* There is no constraint to check */
  29710. +#define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  29711. +#define OE_Abort 2 /* Back out changes but do no rollback transaction */
  29712. +#define OE_Fail 3 /* Stop the operation but leave all prior changes */
  29713. +#define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  29714. +#define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  29715. +
  29716. +#define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  29717. +#define OE_SetNull 7 /* Set the foreign key value to NULL */
  29718. +#define OE_SetDflt 8 /* Set the foreign key value to its default */
  29719. +#define OE_Cascade 9 /* Cascade the changes */
  29720. +
  29721. +#define OE_Default 99 /* Do whatever the default action is */
  29722. +
  29723. +/*
  29724. +** Each SQL index is represented in memory by an
  29725. +** instance of the following structure.
  29726. +**
  29727. +** The columns of the table that are to be indexed are described
  29728. +** by the aiColumn[] field of this structure. For example, suppose
  29729. +** we have the following table and index:
  29730. +**
  29731. +** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  29732. +** CREATE INDEX Ex2 ON Ex1(c3,c1);
  29733. +**
  29734. +** In the Table structure describing Ex1, nCol==3 because there are
  29735. +** three columns in the table. In the Index structure describing
  29736. +** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  29737. +** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  29738. +** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  29739. +** The second column to be indexed (c1) has an index of 0 in
  29740. +** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  29741. +**
  29742. +** The Index.onError field determines whether or not the indexed columns
  29743. +** must be unique and what to do if they are not. When Index.onError=OE_None,
  29744. +** it means this is not a unique index. Otherwise it is a unique index
  29745. +** and the value of Index.onError indicate the which conflict resolution
  29746. +** algorithm to employ whenever an attempt is made to insert a non-unique
  29747. +** element.
  29748. +*/
  29749. +struct Index {
  29750. + char *zName; /* Name of this index */
  29751. + int nColumn; /* Number of columns in the table used by this index */
  29752. + int *aiColumn; /* Which columns are used by this index. 1st is 0 */
  29753. + Table *pTable; /* The SQL table being indexed */
  29754. + int tnum; /* Page containing root of this index in database file */
  29755. + u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  29756. + u8 autoIndex; /* True if is automatically created (ex: by UNIQUE) */
  29757. + u8 iDb; /* Index in sqlite.aDb[] of where this index is stored */
  29758. + Index *pNext; /* The next index associated with the same table */
  29759. +};
  29760. +
  29761. +/*
  29762. +** Each token coming out of the lexer is an instance of
  29763. +** this structure. Tokens are also used as part of an expression.
  29764. +**
  29765. +** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  29766. +** may contain random values. Do not make any assuptions about Token.dyn
  29767. +** and Token.n when Token.z==0.
  29768. +*/
  29769. +struct Token {
  29770. + const char *z; /* Text of the token. Not NULL-terminated! */
  29771. + unsigned dyn : 1; /* True for malloced memory, false for static */
  29772. + unsigned n : 31; /* Number of characters in this token */
  29773. +};
  29774. +
  29775. +/*
  29776. +** Each node of an expression in the parse tree is an instance
  29777. +** of this structure.
  29778. +**
  29779. +** Expr.op is the opcode. The integer parser token codes are reused
  29780. +** as opcodes here. For example, the parser defines TK_GE to be an integer
  29781. +** code representing the ">=" operator. This same integer code is reused
  29782. +** to represent the greater-than-or-equal-to operator in the expression
  29783. +** tree.
  29784. +**
  29785. +** Expr.pRight and Expr.pLeft are subexpressions. Expr.pList is a list
  29786. +** of argument if the expression is a function.
  29787. +**
  29788. +** Expr.token is the operator token for this node. For some expressions
  29789. +** that have subexpressions, Expr.token can be the complete text that gave
  29790. +** rise to the Expr. In the latter case, the token is marked as being
  29791. +** a compound token.
  29792. +**
  29793. +** An expression of the form ID or ID.ID refers to a column in a table.
  29794. +** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  29795. +** the integer cursor number of a VDBE cursor pointing to that table and
  29796. +** Expr.iColumn is the column number for the specific column. If the
  29797. +** expression is used as a result in an aggregate SELECT, then the
  29798. +** value is also stored in the Expr.iAgg column in the aggregate so that
  29799. +** it can be accessed after all aggregates are computed.
  29800. +**
  29801. +** If the expression is a function, the Expr.iTable is an integer code
  29802. +** representing which function. If the expression is an unbound variable
  29803. +** marker (a question mark character '?' in the original SQL) then the
  29804. +** Expr.iTable holds the index number for that variable.
  29805. +**
  29806. +** The Expr.pSelect field points to a SELECT statement. The SELECT might
  29807. +** be the right operand of an IN operator. Or, if a scalar SELECT appears
  29808. +** in an expression the opcode is TK_SELECT and Expr.pSelect is the only
  29809. +** operand.
  29810. +*/
  29811. +struct Expr {
  29812. + u8 op; /* Operation performed by this node */
  29813. + u8 dataType; /* Either SQLITE_SO_TEXT or SQLITE_SO_NUM */
  29814. + u8 iDb; /* Database referenced by this expression */
  29815. + u8 flags; /* Various flags. See below */
  29816. + Expr *pLeft, *pRight; /* Left and right subnodes */
  29817. + ExprList *pList; /* A list of expressions used as function arguments
  29818. + ** or in "<expr> IN (<expr-list)" */
  29819. + Token token; /* An operand token */
  29820. + Token span; /* Complete text of the expression */
  29821. + int iTable, iColumn; /* When op==TK_COLUMN, then this expr node means the
  29822. + ** iColumn-th field of the iTable-th table. */
  29823. + int iAgg; /* When op==TK_COLUMN and pParse->useAgg==TRUE, pull
  29824. + ** result from the iAgg-th element of the aggregator */
  29825. + Select *pSelect; /* When the expression is a sub-select. Also the
  29826. + ** right side of "<expr> IN (<select>)" */
  29827. +};
  29828. +
  29829. +/*
  29830. +** The following are the meanings of bits in the Expr.flags field.
  29831. +*/
  29832. +#define EP_FromJoin 0x0001 /* Originated in ON or USING clause of a join */
  29833. +
  29834. +/*
  29835. +** These macros can be used to test, set, or clear bits in the
  29836. +** Expr.flags field.
  29837. +*/
  29838. +#define ExprHasProperty(E,P) (((E)->flags&(P))==(P))
  29839. +#define ExprHasAnyProperty(E,P) (((E)->flags&(P))!=0)
  29840. +#define ExprSetProperty(E,P) (E)->flags|=(P)
  29841. +#define ExprClearProperty(E,P) (E)->flags&=~(P)
  29842. +
  29843. +/*
  29844. +** A list of expressions. Each expression may optionally have a
  29845. +** name. An expr/name combination can be used in several ways, such
  29846. +** as the list of "expr AS ID" fields following a "SELECT" or in the
  29847. +** list of "ID = expr" items in an UPDATE. A list of expressions can
  29848. +** also be used as the argument to a function, in which case the a.zName
  29849. +** field is not used.
  29850. +*/
  29851. +struct ExprList {
  29852. + int nExpr; /* Number of expressions on the list */
  29853. + int nAlloc; /* Number of entries allocated below */
  29854. + struct ExprList_item {
  29855. + Expr *pExpr; /* The list of expressions */
  29856. + char *zName; /* Token associated with this expression */
  29857. + u8 sortOrder; /* 1 for DESC or 0 for ASC */
  29858. + u8 isAgg; /* True if this is an aggregate like count(*) */
  29859. + u8 done; /* A flag to indicate when processing is finished */
  29860. + } *a; /* One entry for each expression */
  29861. +};
  29862. +
  29863. +/*
  29864. +** An instance of this structure can hold a simple list of identifiers,
  29865. +** such as the list "a,b,c" in the following statements:
  29866. +**
  29867. +** INSERT INTO t(a,b,c) VALUES ...;
  29868. +** CREATE INDEX idx ON t(a,b,c);
  29869. +** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  29870. +**
  29871. +** The IdList.a.idx field is used when the IdList represents the list of
  29872. +** column names after a table name in an INSERT statement. In the statement
  29873. +**
  29874. +** INSERT INTO t(a,b,c) ...
  29875. +**
  29876. +** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  29877. +*/
  29878. +struct IdList {
  29879. + int nId; /* Number of identifiers on the list */
  29880. + int nAlloc; /* Number of entries allocated for a[] below */
  29881. + struct IdList_item {
  29882. + char *zName; /* Name of the identifier */
  29883. + int idx; /* Index in some Table.aCol[] of a column named zName */
  29884. + } *a;
  29885. +};
  29886. +
  29887. +/*
  29888. +** The following structure describes the FROM clause of a SELECT statement.
  29889. +** Each table or subquery in the FROM clause is a separate element of
  29890. +** the SrcList.a[] array.
  29891. +**
  29892. +** With the addition of multiple database support, the following structure
  29893. +** can also be used to describe a particular table such as the table that
  29894. +** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  29895. +** such a table must be a simple name: ID. But in SQLite, the table can
  29896. +** now be identified by a database name, a dot, then the table name: ID.ID.
  29897. +*/
  29898. +struct SrcList {
  29899. + i16 nSrc; /* Number of tables or subqueries in the FROM clause */
  29900. + i16 nAlloc; /* Number of entries allocated in a[] below */
  29901. + struct SrcList_item {
  29902. + char *zDatabase; /* Name of database holding this table */
  29903. + char *zName; /* Name of the table */
  29904. + char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  29905. + Table *pTab; /* An SQL table corresponding to zName */
  29906. + Select *pSelect; /* A SELECT statement used in place of a table name */
  29907. + int jointype; /* Type of join between this table and the next */
  29908. + int iCursor; /* The VDBE cursor number used to access this table */
  29909. + Expr *pOn; /* The ON clause of a join */
  29910. + IdList *pUsing; /* The USING clause of a join */
  29911. + } a[1]; /* One entry for each identifier on the list */
  29912. +};
  29913. +
  29914. +/*
  29915. +** Permitted values of the SrcList.a.jointype field
  29916. +*/
  29917. +#define JT_INNER 0x0001 /* Any kind of inner or cross join */
  29918. +#define JT_NATURAL 0x0002 /* True for a "natural" join */
  29919. +#define JT_LEFT 0x0004 /* Left outer join */
  29920. +#define JT_RIGHT 0x0008 /* Right outer join */
  29921. +#define JT_OUTER 0x0010 /* The "OUTER" keyword is present */
  29922. +#define JT_ERROR 0x0020 /* unknown or unsupported join type */
  29923. +
  29924. +/*
  29925. +** For each nested loop in a WHERE clause implementation, the WhereInfo
  29926. +** structure contains a single instance of this structure. This structure
  29927. +** is intended to be private the the where.c module and should not be
  29928. +** access or modified by other modules.
  29929. +*/
  29930. +struct WhereLevel {
  29931. + int iMem; /* Memory cell used by this level */
  29932. + Index *pIdx; /* Index used */
  29933. + int iCur; /* Cursor number used for this index */
  29934. + int score; /* How well this indexed scored */
  29935. + int brk; /* Jump here to break out of the loop */
  29936. + int cont; /* Jump here to continue with the next loop cycle */
  29937. + int op, p1, p2; /* Opcode used to terminate the loop */
  29938. + int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  29939. + int top; /* First instruction of interior of the loop */
  29940. + int inOp, inP1, inP2;/* Opcode used to implement an IN operator */
  29941. + int bRev; /* Do the scan in the reverse direction */
  29942. +};
  29943. +
  29944. +/*
  29945. +** The WHERE clause processing routine has two halves. The
  29946. +** first part does the start of the WHERE loop and the second
  29947. +** half does the tail of the WHERE loop. An instance of
  29948. +** this structure is returned by the first half and passed
  29949. +** into the second half to give some continuity.
  29950. +*/
  29951. +struct WhereInfo {
  29952. + Parse *pParse;
  29953. + SrcList *pTabList; /* List of tables in the join */
  29954. + int iContinue; /* Jump here to continue with next record */
  29955. + int iBreak; /* Jump here to break out of the loop */
  29956. + int nLevel; /* Number of nested loop */
  29957. + int savedNTab; /* Value of pParse->nTab before WhereBegin() */
  29958. + int peakNTab; /* Value of pParse->nTab after WhereBegin() */
  29959. + WhereLevel a[1]; /* Information about each nest loop in the WHERE */
  29960. +};
  29961. +
  29962. +/*
  29963. +** An instance of the following structure contains all information
  29964. +** needed to generate code for a single SELECT statement.
  29965. +**
  29966. +** The zSelect field is used when the Select structure must be persistent.
  29967. +** Normally, the expression tree points to tokens in the original input
  29968. +** string that encodes the select. But if the Select structure must live
  29969. +** longer than its input string (for example when it is used to describe
  29970. +** a VIEW) we have to make a copy of the input string so that the nodes
  29971. +** of the expression tree will have something to point to. zSelect is used
  29972. +** to hold that copy.
  29973. +**
  29974. +** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  29975. +** If there is a LIMIT clause, the parser sets nLimit to the value of the
  29976. +** limit and nOffset to the value of the offset (or 0 if there is not
  29977. +** offset). But later on, nLimit and nOffset become the memory locations
  29978. +** in the VDBE that record the limit and offset counters.
  29979. +*/
  29980. +struct Select {
  29981. + ExprList *pEList; /* The fields of the result */
  29982. + u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  29983. + u8 isDistinct; /* True if the DISTINCT keyword is present */
  29984. + SrcList *pSrc; /* The FROM clause */
  29985. + Expr *pWhere; /* The WHERE clause */
  29986. + ExprList *pGroupBy; /* The GROUP BY clause */
  29987. + Expr *pHaving; /* The HAVING clause */
  29988. + ExprList *pOrderBy; /* The ORDER BY clause */
  29989. + Select *pPrior; /* Prior select in a compound select statement */
  29990. + int nLimit, nOffset; /* LIMIT and OFFSET values. -1 means not used */
  29991. + int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  29992. + char *zSelect; /* Complete text of the SELECT command */
  29993. +};
  29994. +
  29995. +/*
  29996. +** The results of a select can be distributed in several ways.
  29997. +*/
  29998. +#define SRT_Callback 1 /* Invoke a callback with each row of result */
  29999. +#define SRT_Mem 2 /* Store result in a memory cell */
  30000. +#define SRT_Set 3 /* Store result as unique keys in a table */
  30001. +#define SRT_Union 5 /* Store result as keys in a table */
  30002. +#define SRT_Except 6 /* Remove result from a UNION table */
  30003. +#define SRT_Table 7 /* Store result as data with a unique key */
  30004. +#define SRT_TempTable 8 /* Store result in a trasient table */
  30005. +#define SRT_Discard 9 /* Do not save the results anywhere */
  30006. +#define SRT_Sorter 10 /* Store results in the sorter */
  30007. +#define SRT_Subroutine 11 /* Call a subroutine to handle results */
  30008. +
  30009. +/*
  30010. +** When a SELECT uses aggregate functions (like "count(*)" or "avg(f1)")
  30011. +** we have to do some additional analysis of expressions. An instance
  30012. +** of the following structure holds information about a single subexpression
  30013. +** somewhere in the SELECT statement. An array of these structures holds
  30014. +** all the information we need to generate code for aggregate
  30015. +** expressions.
  30016. +**
  30017. +** Note that when analyzing a SELECT containing aggregates, both
  30018. +** non-aggregate field variables and aggregate functions are stored
  30019. +** in the AggExpr array of the Parser structure.
  30020. +**
  30021. +** The pExpr field points to an expression that is part of either the
  30022. +** field list, the GROUP BY clause, the HAVING clause or the ORDER BY
  30023. +** clause. The expression will be freed when those clauses are cleaned
  30024. +** up. Do not try to delete the expression attached to AggExpr.pExpr.
  30025. +**
  30026. +** If AggExpr.pExpr==0, that means the expression is "count(*)".
  30027. +*/
  30028. +struct AggExpr {
  30029. + int isAgg; /* if TRUE contains an aggregate function */
  30030. + Expr *pExpr; /* The expression */
  30031. + FuncDef *pFunc; /* Information about the aggregate function */
  30032. +};
  30033. +
  30034. +/*
  30035. +** An SQL parser context. A copy of this structure is passed through
  30036. +** the parser and down into all the parser action routine in order to
  30037. +** carry around information that is global to the entire parse.
  30038. +*/
  30039. +struct Parse {
  30040. + sqlite *db; /* The main database structure */
  30041. + int rc; /* Return code from execution */
  30042. + char *zErrMsg; /* An error message */
  30043. + Token sErrToken; /* The token at which the error occurred */
  30044. + Token sFirstToken; /* The first token parsed */
  30045. + Token sLastToken; /* The last token parsed */
  30046. + const char *zTail; /* All SQL text past the last semicolon parsed */
  30047. + Table *pNewTable; /* A table being constructed by CREATE TABLE */
  30048. + Vdbe *pVdbe; /* An engine for executing database bytecode */
  30049. + u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  30050. + u8 explain; /* True if the EXPLAIN flag is found on the query */
  30051. + u8 nameClash; /* A permanent table name clashes with temp table name */
  30052. + u8 useAgg; /* If true, extract field values from the aggregator
  30053. + ** while generating expressions. Normally false */
  30054. + int nErr; /* Number of errors seen */
  30055. + int nTab; /* Number of previously allocated VDBE cursors */
  30056. + int nMem; /* Number of memory cells used so far */
  30057. + int nSet; /* Number of sets used so far */
  30058. + int nAgg; /* Number of aggregate expressions */
  30059. + int nVar; /* Number of '?' variables seen in the SQL so far */
  30060. + AggExpr *aAgg; /* An array of aggregate expressions */
  30061. + const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  30062. + Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  30063. + TriggerStack *trigStack; /* Trigger actions being coded */
  30064. +};
  30065. +
  30066. +/*
  30067. +** An instance of the following structure can be declared on a stack and used
  30068. +** to save the Parse.zAuthContext value so that it can be restored later.
  30069. +*/
  30070. +struct AuthContext {
  30071. + const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  30072. + Parse *pParse; /* The Parse structure */
  30073. +};
  30074. +
  30075. +/*
  30076. +** Bitfield flags for P2 value in OP_PutIntKey and OP_Delete
  30077. +*/
  30078. +#define OPFLAG_NCHANGE 1 /* Set to update db->nChange */
  30079. +#define OPFLAG_LASTROWID 2 /* Set to update db->lastRowid */
  30080. +#define OPFLAG_CSCHANGE 4 /* Set to update db->csChange */
  30081. +
  30082. +/*
  30083. + * Each trigger present in the database schema is stored as an instance of
  30084. + * struct Trigger.
  30085. + *
  30086. + * Pointers to instances of struct Trigger are stored in two ways.
  30087. + * 1. In the "trigHash" hash table (part of the sqlite* that represents the
  30088. + * database). This allows Trigger structures to be retrieved by name.
  30089. + * 2. All triggers associated with a single table form a linked list, using the
  30090. + * pNext member of struct Trigger. A pointer to the first element of the
  30091. + * linked list is stored as the "pTrigger" member of the associated
  30092. + * struct Table.
  30093. + *
  30094. + * The "step_list" member points to the first element of a linked list
  30095. + * containing the SQL statements specified as the trigger program.
  30096. + */
  30097. +struct Trigger {
  30098. + char *name; /* The name of the trigger */
  30099. + char *table; /* The table or view to which the trigger applies */
  30100. + u8 iDb; /* Database containing this trigger */
  30101. + u8 iTabDb; /* Database containing Trigger.table */
  30102. + u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  30103. + u8 tr_tm; /* One of TK_BEFORE, TK_AFTER */
  30104. + Expr *pWhen; /* The WHEN clause of the expresion (may be NULL) */
  30105. + IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  30106. + the <column-list> is stored here */
  30107. + int foreach; /* One of TK_ROW or TK_STATEMENT */
  30108. + Token nameToken; /* Token containing zName. Use during parsing only */
  30109. +
  30110. + TriggerStep *step_list; /* Link list of trigger program steps */
  30111. + Trigger *pNext; /* Next trigger associated with the table */
  30112. +};
  30113. +
  30114. +/*
  30115. + * An instance of struct TriggerStep is used to store a single SQL statement
  30116. + * that is a part of a trigger-program.
  30117. + *
  30118. + * Instances of struct TriggerStep are stored in a singly linked list (linked
  30119. + * using the "pNext" member) referenced by the "step_list" member of the
  30120. + * associated struct Trigger instance. The first element of the linked list is
  30121. + * the first step of the trigger-program.
  30122. + *
  30123. + * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  30124. + * "SELECT" statement. The meanings of the other members is determined by the
  30125. + * value of "op" as follows:
  30126. + *
  30127. + * (op == TK_INSERT)
  30128. + * orconf -> stores the ON CONFLICT algorithm
  30129. + * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  30130. + * this stores a pointer to the SELECT statement. Otherwise NULL.
  30131. + * target -> A token holding the name of the table to insert into.
  30132. + * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  30133. + * this stores values to be inserted. Otherwise NULL.
  30134. + * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  30135. + * statement, then this stores the column-names to be
  30136. + * inserted into.
  30137. + *
  30138. + * (op == TK_DELETE)
  30139. + * target -> A token holding the name of the table to delete from.
  30140. + * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  30141. + * Otherwise NULL.
  30142. + *
  30143. + * (op == TK_UPDATE)
  30144. + * target -> A token holding the name of the table to update rows of.
  30145. + * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  30146. + * Otherwise NULL.
  30147. + * pExprList -> A list of the columns to update and the expressions to update
  30148. + * them to. See sqliteUpdate() documentation of "pChanges"
  30149. + * argument.
  30150. + *
  30151. + */
  30152. +struct TriggerStep {
  30153. + int op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  30154. + int orconf; /* OE_Rollback etc. */
  30155. + Trigger *pTrig; /* The trigger that this step is a part of */
  30156. +
  30157. + Select *pSelect; /* Valid for SELECT and sometimes
  30158. + INSERT steps (when pExprList == 0) */
  30159. + Token target; /* Valid for DELETE, UPDATE, INSERT steps */
  30160. + Expr *pWhere; /* Valid for DELETE, UPDATE steps */
  30161. + ExprList *pExprList; /* Valid for UPDATE statements and sometimes
  30162. + INSERT steps (when pSelect == 0) */
  30163. + IdList *pIdList; /* Valid for INSERT statements only */
  30164. +
  30165. + TriggerStep * pNext; /* Next in the link-list */
  30166. +};
  30167. +
  30168. +/*
  30169. + * An instance of struct TriggerStack stores information required during code
  30170. + * generation of a single trigger program. While the trigger program is being
  30171. + * coded, its associated TriggerStack instance is pointed to by the
  30172. + * "pTriggerStack" member of the Parse structure.
  30173. + *
  30174. + * The pTab member points to the table that triggers are being coded on. The
  30175. + * newIdx member contains the index of the vdbe cursor that points at the temp
  30176. + * table that stores the new.* references. If new.* references are not valid
  30177. + * for the trigger being coded (for example an ON DELETE trigger), then newIdx
  30178. + * is set to -1. The oldIdx member is analogous to newIdx, for old.* references.
  30179. + *
  30180. + * The ON CONFLICT policy to be used for the trigger program steps is stored
  30181. + * as the orconf member. If this is OE_Default, then the ON CONFLICT clause
  30182. + * specified for individual triggers steps is used.
  30183. + *
  30184. + * struct TriggerStack has a "pNext" member, to allow linked lists to be
  30185. + * constructed. When coding nested triggers (triggers fired by other triggers)
  30186. + * each nested trigger stores its parent trigger's TriggerStack as the "pNext"
  30187. + * pointer. Once the nested trigger has been coded, the pNext value is restored
  30188. + * to the pTriggerStack member of the Parse stucture and coding of the parent
  30189. + * trigger continues.
  30190. + *
  30191. + * Before a nested trigger is coded, the linked list pointed to by the
  30192. + * pTriggerStack is scanned to ensure that the trigger is not about to be coded
  30193. + * recursively. If this condition is detected, the nested trigger is not coded.
  30194. + */
  30195. +struct TriggerStack {
  30196. + Table *pTab; /* Table that triggers are currently being coded on */
  30197. + int newIdx; /* Index of vdbe cursor to "new" temp table */
  30198. + int oldIdx; /* Index of vdbe cursor to "old" temp table */
  30199. + int orconf; /* Current orconf policy */
  30200. + int ignoreJump; /* where to jump to for a RAISE(IGNORE) */
  30201. + Trigger *pTrigger; /* The trigger currently being coded */
  30202. + TriggerStack *pNext; /* Next trigger down on the trigger stack */
  30203. +};
  30204. +
  30205. +/*
  30206. +** The following structure contains information used by the sqliteFix...
  30207. +** routines as they walk the parse tree to make database references
  30208. +** explicit.
  30209. +*/
  30210. +typedef struct DbFixer DbFixer;
  30211. +struct DbFixer {
  30212. + Parse *pParse; /* The parsing context. Error messages written here */
  30213. + const char *zDb; /* Make sure all objects are contained in this database */
  30214. + const char *zType; /* Type of the container - used for error messages */
  30215. + const Token *pName; /* Name of the container - used for error messages */
  30216. +};
  30217. +
  30218. +/*
  30219. + * This global flag is set for performance testing of triggers. When it is set
  30220. + * SQLite will perform the overhead of building new and old trigger references
  30221. + * even when no triggers exist
  30222. + */
  30223. +extern int always_code_trigger_setup;
  30224. +
  30225. +/*
  30226. +** Internal function prototypes
  30227. +*/
  30228. +int sqliteStrICmp(const char *, const char *);
  30229. +int sqliteStrNICmp(const char *, const char *, int);
  30230. +int sqliteHashNoCase(const char *, int);
  30231. +int sqliteIsNumber(const char*);
  30232. +int sqliteCompare(const char *, const char *);
  30233. +int sqliteSortCompare(const char *, const char *);
  30234. +void sqliteRealToSortable(double r, char *);
  30235. +#ifdef MEMORY_DEBUG
  30236. + void *sqliteMalloc_(int,int,char*,int);
  30237. + void sqliteFree_(void*,char*,int);
  30238. + void *sqliteRealloc_(void*,int,char*,int);
  30239. + char *sqliteStrDup_(const char*,char*,int);
  30240. + char *sqliteStrNDup_(const char*, int,char*,int);
  30241. + void sqliteCheckMemory(void*,int);
  30242. +#else
  30243. + void *sqliteMalloc(int);
  30244. + void *sqliteMallocRaw(int);
  30245. + void sqliteFree(void*);
  30246. + void *sqliteRealloc(void*,int);
  30247. + char *sqliteStrDup(const char*);
  30248. + char *sqliteStrNDup(const char*, int);
  30249. +# define sqliteCheckMemory(a,b)
  30250. +#endif
  30251. +char *sqliteMPrintf(const char*, ...);
  30252. +char *sqliteVMPrintf(const char*, va_list);
  30253. +void sqliteSetString(char **, ...);
  30254. +void sqliteSetNString(char **, ...);
  30255. +void sqliteErrorMsg(Parse*, const char*, ...);
  30256. +void sqliteDequote(char*);
  30257. +int sqliteKeywordCode(const char*, int);
  30258. +int sqliteRunParser(Parse*, const char*, char **);
  30259. +void sqliteExec(Parse*);
  30260. +Expr *sqliteExpr(int, Expr*, Expr*, Token*);
  30261. +void sqliteExprSpan(Expr*,Token*,Token*);
  30262. +Expr *sqliteExprFunction(ExprList*, Token*);
  30263. +void sqliteExprDelete(Expr*);
  30264. +ExprList *sqliteExprListAppend(ExprList*,Expr*,Token*);
  30265. +void sqliteExprListDelete(ExprList*);
  30266. +int sqliteInit(sqlite*, char**);
  30267. +void sqlitePragma(Parse*,Token*,Token*,int);
  30268. +void sqliteResetInternalSchema(sqlite*, int);
  30269. +void sqliteBeginParse(Parse*,int);
  30270. +void sqliteRollbackInternalChanges(sqlite*);
  30271. +void sqliteCommitInternalChanges(sqlite*);
  30272. +Table *sqliteResultSetOfSelect(Parse*,char*,Select*);
  30273. +void sqliteOpenMasterTable(Vdbe *v, int);
  30274. +void sqliteStartTable(Parse*,Token*,Token*,int,int);
  30275. +void sqliteAddColumn(Parse*,Token*);
  30276. +void sqliteAddNotNull(Parse*, int);
  30277. +void sqliteAddPrimaryKey(Parse*, IdList*, int);
  30278. +void sqliteAddColumnType(Parse*,Token*,Token*);
  30279. +void sqliteAddDefaultValue(Parse*,Token*,int);
  30280. +int sqliteCollateType(const char*, int);
  30281. +void sqliteAddCollateType(Parse*, int);
  30282. +void sqliteEndTable(Parse*,Token*,Select*);
  30283. +void sqliteCreateView(Parse*,Token*,Token*,Select*,int);
  30284. +int sqliteViewGetColumnNames(Parse*,Table*);
  30285. +void sqliteDropTable(Parse*, Token*, int);
  30286. +void sqliteDeleteTable(sqlite*, Table*);
  30287. +void sqliteInsert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
  30288. +IdList *sqliteIdListAppend(IdList*, Token*);
  30289. +int sqliteIdListIndex(IdList*,const char*);
  30290. +SrcList *sqliteSrcListAppend(SrcList*, Token*, Token*);
  30291. +void sqliteSrcListAddAlias(SrcList*, Token*);
  30292. +void sqliteSrcListAssignCursors(Parse*, SrcList*);
  30293. +void sqliteIdListDelete(IdList*);
  30294. +void sqliteSrcListDelete(SrcList*);
  30295. +void sqliteCreateIndex(Parse*,Token*,SrcList*,IdList*,int,Token*,Token*);
  30296. +void sqliteDropIndex(Parse*, SrcList*);
  30297. +void sqliteAddKeyType(Vdbe*, ExprList*);
  30298. +void sqliteAddIdxKeyType(Vdbe*, Index*);
  30299. +int sqliteSelect(Parse*, Select*, int, int, Select*, int, int*);
  30300. +Select *sqliteSelectNew(ExprList*,SrcList*,Expr*,ExprList*,Expr*,ExprList*,
  30301. + int,int,int);
  30302. +void sqliteSelectDelete(Select*);
  30303. +void sqliteSelectUnbind(Select*);
  30304. +Table *sqliteSrcListLookup(Parse*, SrcList*);
  30305. +int sqliteIsReadOnly(Parse*, Table*, int);
  30306. +void sqliteDeleteFrom(Parse*, SrcList*, Expr*);
  30307. +void sqliteUpdate(Parse*, SrcList*, ExprList*, Expr*, int);
  30308. +WhereInfo *sqliteWhereBegin(Parse*, SrcList*, Expr*, int, ExprList**);
  30309. +void sqliteWhereEnd(WhereInfo*);
  30310. +void sqliteExprCode(Parse*, Expr*);
  30311. +int sqliteExprCodeExprList(Parse*, ExprList*, int);
  30312. +void sqliteExprIfTrue(Parse*, Expr*, int, int);
  30313. +void sqliteExprIfFalse(Parse*, Expr*, int, int);
  30314. +Table *sqliteFindTable(sqlite*,const char*, const char*);
  30315. +Table *sqliteLocateTable(Parse*,const char*, const char*);
  30316. +Index *sqliteFindIndex(sqlite*,const char*, const char*);
  30317. +void sqliteUnlinkAndDeleteIndex(sqlite*,Index*);
  30318. +void sqliteCopy(Parse*, SrcList*, Token*, Token*, int);
  30319. +void sqliteVacuum(Parse*, Token*);
  30320. +int sqliteRunVacuum(char**, sqlite*);
  30321. +int sqliteGlobCompare(const unsigned char*,const unsigned char*);
  30322. +int sqliteLikeCompare(const unsigned char*,const unsigned char*);
  30323. +char *sqliteTableNameFromToken(Token*);
  30324. +int sqliteExprCheck(Parse*, Expr*, int, int*);
  30325. +int sqliteExprType(Expr*);
  30326. +int sqliteExprCompare(Expr*, Expr*);
  30327. +int sqliteFuncId(Token*);
  30328. +int sqliteExprResolveIds(Parse*, SrcList*, ExprList*, Expr*);
  30329. +int sqliteExprAnalyzeAggregates(Parse*, Expr*);
  30330. +Vdbe *sqliteGetVdbe(Parse*);
  30331. +void sqliteRandomness(int, void*);
  30332. +void sqliteRollbackAll(sqlite*);
  30333. +void sqliteCodeVerifySchema(Parse*, int);
  30334. +void sqliteBeginTransaction(Parse*, int);
  30335. +void sqliteCommitTransaction(Parse*);
  30336. +void sqliteRollbackTransaction(Parse*);
  30337. +int sqliteExprIsConstant(Expr*);
  30338. +int sqliteExprIsInteger(Expr*, int*);
  30339. +int sqliteIsRowid(const char*);
  30340. +void sqliteGenerateRowDelete(sqlite*, Vdbe*, Table*, int, int);
  30341. +void sqliteGenerateRowIndexDelete(sqlite*, Vdbe*, Table*, int, char*);
  30342. +void sqliteGenerateConstraintChecks(Parse*,Table*,int,char*,int,int,int,int);
  30343. +void sqliteCompleteInsertion(Parse*, Table*, int, char*, int, int, int);
  30344. +int sqliteOpenTableAndIndices(Parse*, Table*, int);
  30345. +void sqliteBeginWriteOperation(Parse*, int, int);
  30346. +void sqliteEndWriteOperation(Parse*);
  30347. +Expr *sqliteExprDup(Expr*);
  30348. +void sqliteTokenCopy(Token*, Token*);
  30349. +ExprList *sqliteExprListDup(ExprList*);
  30350. +SrcList *sqliteSrcListDup(SrcList*);
  30351. +IdList *sqliteIdListDup(IdList*);
  30352. +Select *sqliteSelectDup(Select*);
  30353. +FuncDef *sqliteFindFunction(sqlite*,const char*,int,int,int);
  30354. +void sqliteRegisterBuiltinFunctions(sqlite*);
  30355. +void sqliteRegisterDateTimeFunctions(sqlite*);
  30356. +int sqliteSafetyOn(sqlite*);
  30357. +int sqliteSafetyOff(sqlite*);
  30358. +int sqliteSafetyCheck(sqlite*);
  30359. +void sqliteChangeCookie(sqlite*, Vdbe*);
  30360. +void sqliteBeginTrigger(Parse*, Token*,int,int,IdList*,SrcList*,int,Expr*,int);
  30361. +void sqliteFinishTrigger(Parse*, TriggerStep*, Token*);
  30362. +void sqliteDropTrigger(Parse*, SrcList*);
  30363. +void sqliteDropTriggerPtr(Parse*, Trigger*, int);
  30364. +int sqliteTriggersExist(Parse* , Trigger* , int , int , int, ExprList*);
  30365. +int sqliteCodeRowTrigger(Parse*, int, ExprList*, int, Table *, int, int,
  30366. + int, int);
  30367. +void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  30368. +void sqliteDeleteTriggerStep(TriggerStep*);
  30369. +TriggerStep *sqliteTriggerSelectStep(Select*);
  30370. +TriggerStep *sqliteTriggerInsertStep(Token*, IdList*, ExprList*, Select*, int);
  30371. +TriggerStep *sqliteTriggerUpdateStep(Token*, ExprList*, Expr*, int);
  30372. +TriggerStep *sqliteTriggerDeleteStep(Token*, Expr*);
  30373. +void sqliteDeleteTrigger(Trigger*);
  30374. +int sqliteJoinType(Parse*, Token*, Token*, Token*);
  30375. +void sqliteCreateForeignKey(Parse*, IdList*, Token*, IdList*, int);
  30376. +void sqliteDeferForeignKey(Parse*, int);
  30377. +#ifndef SQLITE_OMIT_AUTHORIZATION
  30378. + void sqliteAuthRead(Parse*,Expr*,SrcList*);
  30379. + int sqliteAuthCheck(Parse*,int, const char*, const char*, const char*);
  30380. + void sqliteAuthContextPush(Parse*, AuthContext*, const char*);
  30381. + void sqliteAuthContextPop(AuthContext*);
  30382. +#else
  30383. +# define sqliteAuthRead(a,b,c)
  30384. +# define sqliteAuthCheck(a,b,c,d,e) SQLITE_OK
  30385. +# define sqliteAuthContextPush(a,b,c)
  30386. +# define sqliteAuthContextPop(a) ((void)(a))
  30387. +#endif
  30388. +void sqliteAttach(Parse*, Token*, Token*, Token*);
  30389. +void sqliteDetach(Parse*, Token*);
  30390. +int sqliteBtreeFactory(const sqlite *db, const char *zFilename,
  30391. + int mode, int nPg, Btree **ppBtree);
  30392. +int sqliteFixInit(DbFixer*, Parse*, int, const char*, const Token*);
  30393. +int sqliteFixSrcList(DbFixer*, SrcList*);
  30394. +int sqliteFixSelect(DbFixer*, Select*);
  30395. +int sqliteFixExpr(DbFixer*, Expr*);
  30396. +int sqliteFixExprList(DbFixer*, ExprList*);
  30397. +int sqliteFixTriggerStep(DbFixer*, TriggerStep*);
  30398. +double sqliteAtoF(const char *z, const char **);
  30399. +char *sqlite_snprintf(int,char*,const char*,...);
  30400. +int sqliteFitsIn32Bits(const char *);
  30401. --- /dev/null
  30402. +++ b/ext/sqlite/libsqlite/src/sqlite.w32.h
  30403. @@ -0,0 +1,764 @@
  30404. +/*
  30405. +** 2001 September 15
  30406. +**
  30407. +** The author disclaims copyright to this source code. In place of
  30408. +** a legal notice, here is a blessing:
  30409. +**
  30410. +** May you do good and not evil.
  30411. +** May you find forgiveness for yourself and forgive others.
  30412. +** May you share freely, never taking more than you give.
  30413. +**
  30414. +*************************************************************************
  30415. +** This header file defines the interface that the SQLite library
  30416. +** presents to client programs.
  30417. +**
  30418. +** @(#) $Id$
  30419. +*/
  30420. +#ifndef _SQLITE_H_
  30421. +#define _SQLITE_H_
  30422. +#include <stdarg.h> /* Needed for the definition of va_list */
  30423. +
  30424. +/*
  30425. +** Make sure we can call this stuff from C++.
  30426. +*/
  30427. +#ifdef __cplusplus
  30428. +extern "C" {
  30429. +#endif
  30430. +
  30431. +/*
  30432. +** The version of the SQLite library.
  30433. +*/
  30434. +#define SQLITE_VERSION "2.8.17"
  30435. +
  30436. +/*
  30437. +** The version string is also compiled into the library so that a program
  30438. +** can check to make sure that the lib*.a file and the *.h file are from
  30439. +** the same version.
  30440. +*/
  30441. +extern const char sqlite_version[];
  30442. +
  30443. +/*
  30444. +** The SQLITE_UTF8 macro is defined if the library expects to see
  30445. +** UTF-8 encoded data. The SQLITE_ISO8859 macro is defined if the
  30446. +** iso8859 encoded should be used.
  30447. +*/
  30448. +#define SQLITE_ISO8859 1
  30449. +
  30450. +/*
  30451. +** The following constant holds one of two strings, "UTF-8" or "iso8859",
  30452. +** depending on which character encoding the SQLite library expects to
  30453. +** see. The character encoding makes a difference for the LIKE and GLOB
  30454. +** operators and for the LENGTH() and SUBSTR() functions.
  30455. +*/
  30456. +extern const char sqlite_encoding[];
  30457. +
  30458. +/*
  30459. +** Each open sqlite database is represented by an instance of the
  30460. +** following opaque structure.
  30461. +*/
  30462. +typedef struct sqlite sqlite;
  30463. +
  30464. +/*
  30465. +** A function to open a new sqlite database.
  30466. +**
  30467. +** If the database does not exist and mode indicates write
  30468. +** permission, then a new database is created. If the database
  30469. +** does not exist and mode does not indicate write permission,
  30470. +** then the open fails, an error message generated (if errmsg!=0)
  30471. +** and the function returns 0.
  30472. +**
  30473. +** If mode does not indicates user write permission, then the
  30474. +** database is opened read-only.
  30475. +**
  30476. +** The Truth: As currently implemented, all databases are opened
  30477. +** for writing all the time. Maybe someday we will provide the
  30478. +** ability to open a database readonly. The mode parameters is
  30479. +** provided in anticipation of that enhancement.
  30480. +*/
  30481. +sqlite *sqlite_open(const char *filename, int mode, char **errmsg);
  30482. +
  30483. +/*
  30484. +** A function to close the database.
  30485. +**
  30486. +** Call this function with a pointer to a structure that was previously
  30487. +** returned from sqlite_open() and the corresponding database will by closed.
  30488. +*/
  30489. +void sqlite_close(sqlite *);
  30490. +
  30491. +/*
  30492. +** The type for a callback function.
  30493. +*/
  30494. +typedef int (*sqlite_callback)(void*,int,char**, char**);
  30495. +
  30496. +/*
  30497. +** A function to executes one or more statements of SQL.
  30498. +**
  30499. +** If one or more of the SQL statements are queries, then
  30500. +** the callback function specified by the 3rd parameter is
  30501. +** invoked once for each row of the query result. This callback
  30502. +** should normally return 0. If the callback returns a non-zero
  30503. +** value then the query is aborted, all subsequent SQL statements
  30504. +** are skipped and the sqlite_exec() function returns the SQLITE_ABORT.
  30505. +**
  30506. +** The 4th parameter is an arbitrary pointer that is passed
  30507. +** to the callback function as its first parameter.
  30508. +**
  30509. +** The 2nd parameter to the callback function is the number of
  30510. +** columns in the query result. The 3rd parameter to the callback
  30511. +** is an array of strings holding the values for each column.
  30512. +** The 4th parameter to the callback is an array of strings holding
  30513. +** the names of each column.
  30514. +**
  30515. +** The callback function may be NULL, even for queries. A NULL
  30516. +** callback is not an error. It just means that no callback
  30517. +** will be invoked.
  30518. +**
  30519. +** If an error occurs while parsing or evaluating the SQL (but
  30520. +** not while executing the callback) then an appropriate error
  30521. +** message is written into memory obtained from malloc() and
  30522. +** *errmsg is made to point to that message. The calling function
  30523. +** is responsible for freeing the memory that holds the error
  30524. +** message. Use sqlite_freemem() for this. If errmsg==NULL,
  30525. +** then no error message is ever written.
  30526. +**
  30527. +** The return value is is SQLITE_OK if there are no errors and
  30528. +** some other return code if there is an error. The particular
  30529. +** return value depends on the type of error.
  30530. +**
  30531. +** If the query could not be executed because a database file is
  30532. +** locked or busy, then this function returns SQLITE_BUSY. (This
  30533. +** behavior can be modified somewhat using the sqlite_busy_handler()
  30534. +** and sqlite_busy_timeout() functions below.)
  30535. +*/
  30536. +int sqlite_exec(
  30537. + sqlite*, /* An open database */
  30538. + const char *sql, /* SQL to be executed */
  30539. + sqlite_callback, /* Callback function */
  30540. + void *, /* 1st argument to callback function */
  30541. + char **errmsg /* Error msg written here */
  30542. +);
  30543. +
  30544. +/*
  30545. +** Return values for sqlite_exec() and sqlite_step()
  30546. +*/
  30547. +#define SQLITE_OK 0 /* Successful result */
  30548. +#define SQLITE_ERROR 1 /* SQL error or missing database */
  30549. +#define SQLITE_INTERNAL 2 /* An internal logic error in SQLite */
  30550. +#define SQLITE_PERM 3 /* Access permission denied */
  30551. +#define SQLITE_ABORT 4 /* Callback routine requested an abort */
  30552. +#define SQLITE_BUSY 5 /* The database file is locked */
  30553. +#define SQLITE_LOCKED 6 /* A table in the database is locked */
  30554. +#define SQLITE_NOMEM 7 /* A malloc() failed */
  30555. +#define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  30556. +#define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite_interrupt() */
  30557. +#define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  30558. +#define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  30559. +#define SQLITE_NOTFOUND 12 /* (Internal Only) Table or record not found */
  30560. +#define SQLITE_FULL 13 /* Insertion failed because database is full */
  30561. +#define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  30562. +#define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  30563. +#define SQLITE_EMPTY 16 /* (Internal Only) Database table is empty */
  30564. +#define SQLITE_SCHEMA 17 /* The database schema changed */
  30565. +#define SQLITE_TOOBIG 18 /* Too much data for one row of a table */
  30566. +#define SQLITE_CONSTRAINT 19 /* Abort due to contraint violation */
  30567. +#define SQLITE_MISMATCH 20 /* Data type mismatch */
  30568. +#define SQLITE_MISUSE 21 /* Library used incorrectly */
  30569. +#define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  30570. +#define SQLITE_AUTH 23 /* Authorization denied */
  30571. +#define SQLITE_FORMAT 24 /* Auxiliary database format error */
  30572. +#define SQLITE_RANGE 25 /* 2nd parameter to sqlite_bind out of range */
  30573. +#define SQLITE_NOTADB 26 /* File opened that is not a database file */
  30574. +#define SQLITE_ROW 100 /* sqlite_step() has another row ready */
  30575. +#define SQLITE_DONE 101 /* sqlite_step() has finished executing */
  30576. +
  30577. +/*
  30578. +** Each entry in an SQLite table has a unique integer key. (The key is
  30579. +** the value of the INTEGER PRIMARY KEY column if there is such a column,
  30580. +** otherwise the key is generated at random. The unique key is always
  30581. +** available as the ROWID, OID, or _ROWID_ column.) The following routine
  30582. +** returns the integer key of the most recent insert in the database.
  30583. +**
  30584. +** This function is similar to the mysql_insert_id() function from MySQL.
  30585. +*/
  30586. +int sqlite_last_insert_rowid(sqlite*);
  30587. +
  30588. +/*
  30589. +** This function returns the number of database rows that were changed
  30590. +** (or inserted or deleted) by the most recent called sqlite_exec().
  30591. +**
  30592. +** All changes are counted, even if they were later undone by a
  30593. +** ROLLBACK or ABORT. Except, changes associated with creating and
  30594. +** dropping tables are not counted.
  30595. +**
  30596. +** If a callback invokes sqlite_exec() recursively, then the changes
  30597. +** in the inner, recursive call are counted together with the changes
  30598. +** in the outer call.
  30599. +**
  30600. +** SQLite implements the command "DELETE FROM table" without a WHERE clause
  30601. +** by dropping and recreating the table. (This is much faster than going
  30602. +** through and deleting individual elements form the table.) Because of
  30603. +** this optimization, the change count for "DELETE FROM table" will be
  30604. +** zero regardless of the number of elements that were originally in the
  30605. +** table. To get an accurate count of the number of rows deleted, use
  30606. +** "DELETE FROM table WHERE 1" instead.
  30607. +*/
  30608. +int sqlite_changes(sqlite*);
  30609. +
  30610. +/* If the parameter to this routine is one of the return value constants
  30611. +** defined above, then this routine returns a constant text string which
  30612. +** descripts (in English) the meaning of the return value.
  30613. +*/
  30614. +const char *sqlite_error_string(int);
  30615. +#define sqliteErrStr sqlite_error_string /* Legacy. Do not use in new code. */
  30616. +
  30617. +/* This function causes any pending database operation to abort and
  30618. +** return at its earliest opportunity. This routine is typically
  30619. +** called in response to a user action such as pressing "Cancel"
  30620. +** or Ctrl-C where the user wants a long query operation to halt
  30621. +** immediately.
  30622. +*/
  30623. +void sqlite_interrupt(sqlite*);
  30624. +
  30625. +
  30626. +/* This function returns true if the given input string comprises
  30627. +** one or more complete SQL statements.
  30628. +**
  30629. +** The algorithm is simple. If the last token other than spaces
  30630. +** and comments is a semicolon, then return true. otherwise return
  30631. +** false.
  30632. +*/
  30633. +int sqlite_complete(const char *sql);
  30634. +
  30635. +/*
  30636. +** This routine identifies a callback function that is invoked
  30637. +** whenever an attempt is made to open a database table that is
  30638. +** currently locked by another process or thread. If the busy callback
  30639. +** is NULL, then sqlite_exec() returns SQLITE_BUSY immediately if
  30640. +** it finds a locked table. If the busy callback is not NULL, then
  30641. +** sqlite_exec() invokes the callback with three arguments. The
  30642. +** second argument is the name of the locked table and the third
  30643. +** argument is the number of times the table has been busy. If the
  30644. +** busy callback returns 0, then sqlite_exec() immediately returns
  30645. +** SQLITE_BUSY. If the callback returns non-zero, then sqlite_exec()
  30646. +** tries to open the table again and the cycle repeats.
  30647. +**
  30648. +** The default busy callback is NULL.
  30649. +**
  30650. +** Sqlite is re-entrant, so the busy handler may start a new query.
  30651. +** (It is not clear why anyone would every want to do this, but it
  30652. +** is allowed, in theory.) But the busy handler may not close the
  30653. +** database. Closing the database from a busy handler will delete
  30654. +** data structures out from under the executing query and will
  30655. +** probably result in a coredump.
  30656. +*/
  30657. +void sqlite_busy_handler(sqlite*, int(*)(void*,const char*,int), void*);
  30658. +
  30659. +/*
  30660. +** This routine sets a busy handler that sleeps for a while when a
  30661. +** table is locked. The handler will sleep multiple times until
  30662. +** at least "ms" milleseconds of sleeping have been done. After
  30663. +** "ms" milleseconds of sleeping, the handler returns 0 which
  30664. +** causes sqlite_exec() to return SQLITE_BUSY.
  30665. +**
  30666. +** Calling this routine with an argument less than or equal to zero
  30667. +** turns off all busy handlers.
  30668. +*/
  30669. +void sqlite_busy_timeout(sqlite*, int ms);
  30670. +
  30671. +/*
  30672. +** This next routine is really just a wrapper around sqlite_exec().
  30673. +** Instead of invoking a user-supplied callback for each row of the
  30674. +** result, this routine remembers each row of the result in memory
  30675. +** obtained from malloc(), then returns all of the result after the
  30676. +** query has finished.
  30677. +**
  30678. +** As an example, suppose the query result where this table:
  30679. +**
  30680. +** Name | Age
  30681. +** -----------------------
  30682. +** Alice | 43
  30683. +** Bob | 28
  30684. +** Cindy | 21
  30685. +**
  30686. +** If the 3rd argument were &azResult then after the function returns
  30687. +** azResult will contain the following data:
  30688. +**
  30689. +** azResult[0] = "Name";
  30690. +** azResult[1] = "Age";
  30691. +** azResult[2] = "Alice";
  30692. +** azResult[3] = "43";
  30693. +** azResult[4] = "Bob";
  30694. +** azResult[5] = "28";
  30695. +** azResult[6] = "Cindy";
  30696. +** azResult[7] = "21";
  30697. +**
  30698. +** Notice that there is an extra row of data containing the column
  30699. +** headers. But the *nrow return value is still 3. *ncolumn is
  30700. +** set to 2. In general, the number of values inserted into azResult
  30701. +** will be ((*nrow) + 1)*(*ncolumn).
  30702. +**
  30703. +** After the calling function has finished using the result, it should
  30704. +** pass the result data pointer to sqlite_free_table() in order to
  30705. +** release the memory that was malloc-ed. Because of the way the
  30706. +** malloc() happens, the calling function must not try to call
  30707. +** malloc() directly. Only sqlite_free_table() is able to release
  30708. +** the memory properly and safely.
  30709. +**
  30710. +** The return value of this routine is the same as from sqlite_exec().
  30711. +*/
  30712. +int sqlite_get_table(
  30713. + sqlite*, /* An open database */
  30714. + const char *sql, /* SQL to be executed */
  30715. + char ***resultp, /* Result written to a char *[] that this points to */
  30716. + int *nrow, /* Number of result rows written here */
  30717. + int *ncolumn, /* Number of result columns written here */
  30718. + char **errmsg /* Error msg written here */
  30719. +);
  30720. +
  30721. +/*
  30722. +** Call this routine to free the memory that sqlite_get_table() allocated.
  30723. +*/
  30724. +void sqlite_free_table(char **result);
  30725. +
  30726. +/*
  30727. +** The following routines are wrappers around sqlite_exec() and
  30728. +** sqlite_get_table(). The only difference between the routines that
  30729. +** follow and the originals is that the second argument to the
  30730. +** routines that follow is really a printf()-style format
  30731. +** string describing the SQL to be executed. Arguments to the format
  30732. +** string appear at the end of the argument list.
  30733. +**
  30734. +** All of the usual printf formatting options apply. In addition, there
  30735. +** is a "%q" option. %q works like %s in that it substitutes a null-terminated
  30736. +** string from the argument list. But %q also doubles every '\'' character.
  30737. +** %q is designed for use inside a string literal. By doubling each '\''
  30738. +** character it escapes that character and allows it to be inserted into
  30739. +** the string.
  30740. +**
  30741. +** For example, so some string variable contains text as follows:
  30742. +**
  30743. +** char *zText = "It's a happy day!";
  30744. +**
  30745. +** We can use this text in an SQL statement as follows:
  30746. +**
  30747. +** sqlite_exec_printf(db, "INSERT INTO table VALUES('%q')",
  30748. +** callback1, 0, 0, zText);
  30749. +**
  30750. +** Because the %q format string is used, the '\'' character in zText
  30751. +** is escaped and the SQL generated is as follows:
  30752. +**
  30753. +** INSERT INTO table1 VALUES('It''s a happy day!')
  30754. +**
  30755. +** This is correct. Had we used %s instead of %q, the generated SQL
  30756. +** would have looked like this:
  30757. +**
  30758. +** INSERT INTO table1 VALUES('It's a happy day!');
  30759. +**
  30760. +** This second example is an SQL syntax error. As a general rule you
  30761. +** should always use %q instead of %s when inserting text into a string
  30762. +** literal.
  30763. +*/
  30764. +int sqlite_exec_printf(
  30765. + sqlite*, /* An open database */
  30766. + const char *sqlFormat, /* printf-style format string for the SQL */
  30767. + sqlite_callback, /* Callback function */
  30768. + void *, /* 1st argument to callback function */
  30769. + char **errmsg, /* Error msg written here */
  30770. + ... /* Arguments to the format string. */
  30771. +);
  30772. +int sqlite_exec_vprintf(
  30773. + sqlite*, /* An open database */
  30774. + const char *sqlFormat, /* printf-style format string for the SQL */
  30775. + sqlite_callback, /* Callback function */
  30776. + void *, /* 1st argument to callback function */
  30777. + char **errmsg, /* Error msg written here */
  30778. + va_list ap /* Arguments to the format string. */
  30779. +);
  30780. +int sqlite_get_table_printf(
  30781. + sqlite*, /* An open database */
  30782. + const char *sqlFormat, /* printf-style format string for the SQL */
  30783. + char ***resultp, /* Result written to a char *[] that this points to */
  30784. + int *nrow, /* Number of result rows written here */
  30785. + int *ncolumn, /* Number of result columns written here */
  30786. + char **errmsg, /* Error msg written here */
  30787. + ... /* Arguments to the format string */
  30788. +);
  30789. +int sqlite_get_table_vprintf(
  30790. + sqlite*, /* An open database */
  30791. + const char *sqlFormat, /* printf-style format string for the SQL */
  30792. + char ***resultp, /* Result written to a char *[] that this points to */
  30793. + int *nrow, /* Number of result rows written here */
  30794. + int *ncolumn, /* Number of result columns written here */
  30795. + char **errmsg, /* Error msg written here */
  30796. + va_list ap /* Arguments to the format string */
  30797. +);
  30798. +char *sqlite_mprintf(const char*,...);
  30799. +char *sqlite_vmprintf(const char*, va_list);
  30800. +
  30801. +/*
  30802. +** Windows systems should call this routine to free memory that
  30803. +** is returned in the in the errmsg parameter of sqlite_open() when
  30804. +** SQLite is a DLL. For some reason, it does not work to call free()
  30805. +** directly.
  30806. +*/
  30807. +void sqlite_freemem(void *p);
  30808. +
  30809. +/*
  30810. +** Windows systems need functions to call to return the sqlite_version
  30811. +** and sqlite_encoding strings.
  30812. +*/
  30813. +const char *sqlite_libversion(void);
  30814. +const char *sqlite_libencoding(void);
  30815. +
  30816. +/*
  30817. +** A pointer to the following structure is used to communicate with
  30818. +** the implementations of user-defined functions.
  30819. +*/
  30820. +typedef struct sqlite_func sqlite_func;
  30821. +
  30822. +/*
  30823. +** Use the following routines to create new user-defined functions. See
  30824. +** the documentation for details.
  30825. +*/
  30826. +int sqlite_create_function(
  30827. + sqlite*, /* Database where the new function is registered */
  30828. + const char *zName, /* Name of the new function */
  30829. + int nArg, /* Number of arguments. -1 means any number */
  30830. + void (*xFunc)(sqlite_func*,int,const char**), /* C code to implement */
  30831. + void *pUserData /* Available via the sqlite_user_data() call */
  30832. +);
  30833. +int sqlite_create_aggregate(
  30834. + sqlite*, /* Database where the new function is registered */
  30835. + const char *zName, /* Name of the function */
  30836. + int nArg, /* Number of arguments */
  30837. + void (*xStep)(sqlite_func*,int,const char**), /* Called for each row */
  30838. + void (*xFinalize)(sqlite_func*), /* Called once to get final result */
  30839. + void *pUserData /* Available via the sqlite_user_data() call */
  30840. +);
  30841. +
  30842. +/*
  30843. +** Use the following routine to define the datatype returned by a
  30844. +** user-defined function. The second argument can be one of the
  30845. +** constants SQLITE_NUMERIC, SQLITE_TEXT, or SQLITE_ARGS or it
  30846. +** can be an integer greater than or equal to zero. The datatype
  30847. +** will be numeric or text (the only two types supported) if the
  30848. +** argument is SQLITE_NUMERIC or SQLITE_TEXT. If the argument is
  30849. +** SQLITE_ARGS, then the datatype is numeric if any argument to the
  30850. +** function is numeric and is text otherwise. If the second argument
  30851. +** is an integer, then the datatype of the result is the same as the
  30852. +** parameter to the function that corresponds to that integer.
  30853. +*/
  30854. +int sqlite_function_type(
  30855. + sqlite *db, /* The database there the function is registered */
  30856. + const char *zName, /* Name of the function */
  30857. + int datatype /* The datatype for this function */
  30858. +);
  30859. +#define SQLITE_NUMERIC (-1)
  30860. +#define SQLITE_TEXT (-2)
  30861. +#define SQLITE_ARGS (-3)
  30862. +
  30863. +/*
  30864. +** The user function implementations call one of the following four routines
  30865. +** in order to return their results. The first parameter to each of these
  30866. +** routines is a copy of the first argument to xFunc() or xFinialize().
  30867. +** The second parameter to these routines is the result to be returned.
  30868. +** A NULL can be passed as the second parameter to sqlite_set_result_string()
  30869. +** in order to return a NULL result.
  30870. +**
  30871. +** The 3rd argument to _string and _error is the number of characters to
  30872. +** take from the string. If this argument is negative, then all characters
  30873. +** up to and including the first '\000' are used.
  30874. +**
  30875. +** The sqlite_set_result_string() function allocates a buffer to hold the
  30876. +** result and returns a pointer to this buffer. The calling routine
  30877. +** (that is, the implmentation of a user function) can alter the content
  30878. +** of this buffer if desired.
  30879. +*/
  30880. +char *sqlite_set_result_string(sqlite_func*,const char*,int);
  30881. +void sqlite_set_result_int(sqlite_func*,int);
  30882. +void sqlite_set_result_double(sqlite_func*,double);
  30883. +void sqlite_set_result_error(sqlite_func*,const char*,int);
  30884. +
  30885. +/*
  30886. +** The pUserData parameter to the sqlite_create_function() and
  30887. +** sqlite_create_aggregate() routines used to register user functions
  30888. +** is available to the implementation of the function using this
  30889. +** call.
  30890. +*/
  30891. +void *sqlite_user_data(sqlite_func*);
  30892. +
  30893. +/*
  30894. +** Aggregate functions use the following routine to allocate
  30895. +** a structure for storing their state. The first time this routine
  30896. +** is called for a particular aggregate, a new structure of size nBytes
  30897. +** is allocated, zeroed, and returned. On subsequent calls (for the
  30898. +** same aggregate instance) the same buffer is returned. The implementation
  30899. +** of the aggregate can use the returned buffer to accumulate data.
  30900. +**
  30901. +** The buffer allocated is freed automatically be SQLite.
  30902. +*/
  30903. +void *sqlite_aggregate_context(sqlite_func*, int nBytes);
  30904. +
  30905. +/*
  30906. +** The next routine returns the number of calls to xStep for a particular
  30907. +** aggregate function instance. The current call to xStep counts so this
  30908. +** routine always returns at least 1.
  30909. +*/
  30910. +int sqlite_aggregate_count(sqlite_func*);
  30911. +
  30912. +/*
  30913. +** This routine registers a callback with the SQLite library. The
  30914. +** callback is invoked (at compile-time, not at run-time) for each
  30915. +** attempt to access a column of a table in the database. The callback
  30916. +** returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire
  30917. +** SQL statement should be aborted with an error and SQLITE_IGNORE
  30918. +** if the column should be treated as a NULL value.
  30919. +*/
  30920. +int sqlite_set_authorizer(
  30921. + sqlite*,
  30922. + int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  30923. + void *pUserData
  30924. +);
  30925. +
  30926. +/*
  30927. +** The second parameter to the access authorization function above will
  30928. +** be one of the values below. These values signify what kind of operation
  30929. +** is to be authorized. The 3rd and 4th parameters to the authorization
  30930. +** function will be parameters or NULL depending on which of the following
  30931. +** codes is used as the second parameter. The 5th parameter is the name
  30932. +** of the database ("main", "temp", etc.) if applicable. The 6th parameter
  30933. +** is the name of the inner-most trigger or view that is responsible for
  30934. +** the access attempt or NULL if this access attempt is directly from
  30935. +** input SQL code.
  30936. +**
  30937. +** Arg-3 Arg-4
  30938. +*/
  30939. +#define SQLITE_COPY 0 /* Table Name File Name */
  30940. +#define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  30941. +#define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  30942. +#define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  30943. +#define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  30944. +#define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  30945. +#define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  30946. +#define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  30947. +#define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  30948. +#define SQLITE_DELETE 9 /* Table Name NULL */
  30949. +#define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  30950. +#define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  30951. +#define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  30952. +#define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  30953. +#define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  30954. +#define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  30955. +#define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  30956. +#define SQLITE_DROP_VIEW 17 /* View Name NULL */
  30957. +#define SQLITE_INSERT 18 /* Table Name NULL */
  30958. +#define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  30959. +#define SQLITE_READ 20 /* Table Name Column Name */
  30960. +#define SQLITE_SELECT 21 /* NULL NULL */
  30961. +#define SQLITE_TRANSACTION 22 /* NULL NULL */
  30962. +#define SQLITE_UPDATE 23 /* Table Name Column Name */
  30963. +#define SQLITE_ATTACH 24 /* Filename NULL */
  30964. +#define SQLITE_DETACH 25 /* Database Name NULL */
  30965. +
  30966. +
  30967. +/*
  30968. +** The return value of the authorization function should be one of the
  30969. +** following constants:
  30970. +*/
  30971. +/* #define SQLITE_OK 0 // Allow access (This is actually defined above) */
  30972. +#define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  30973. +#define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  30974. +
  30975. +/*
  30976. +** Register a function that is called at every invocation of sqlite_exec()
  30977. +** or sqlite_compile(). This function can be used (for example) to generate
  30978. +** a log file of all SQL executed against a database.
  30979. +*/
  30980. +void *sqlite_trace(sqlite*, void(*xTrace)(void*,const char*), void*);
  30981. +
  30982. +/*** The Callback-Free API
  30983. +**
  30984. +** The following routines implement a new way to access SQLite that does not
  30985. +** involve the use of callbacks.
  30986. +**
  30987. +** An sqlite_vm is an opaque object that represents a single SQL statement
  30988. +** that is ready to be executed.
  30989. +*/
  30990. +typedef struct sqlite_vm sqlite_vm;
  30991. +
  30992. +/*
  30993. +** To execute an SQLite query without the use of callbacks, you first have
  30994. +** to compile the SQL using this routine. The 1st parameter "db" is a pointer
  30995. +** to an sqlite object obtained from sqlite_open(). The 2nd parameter
  30996. +** "zSql" is the text of the SQL to be compiled. The remaining parameters
  30997. +** are all outputs.
  30998. +**
  30999. +** *pzTail is made to point to the first character past the end of the first
  31000. +** SQL statement in zSql. This routine only compiles the first statement
  31001. +** in zSql, so *pzTail is left pointing to what remains uncompiled.
  31002. +**
  31003. +** *ppVm is left pointing to a "virtual machine" that can be used to execute
  31004. +** the compiled statement. Or if there is an error, *ppVm may be set to NULL.
  31005. +** If the input text contained no SQL (if the input is and empty string or
  31006. +** a comment) then *ppVm is set to NULL.
  31007. +**
  31008. +** If any errors are detected during compilation, an error message is written
  31009. +** into space obtained from malloc() and *pzErrMsg is made to point to that
  31010. +** error message. The calling routine is responsible for freeing the text
  31011. +** of this message when it has finished with it. Use sqlite_freemem() to
  31012. +** free the message. pzErrMsg may be NULL in which case no error message
  31013. +** will be generated.
  31014. +**
  31015. +** On success, SQLITE_OK is returned. Otherwise and error code is returned.
  31016. +*/
  31017. +int sqlite_compile(
  31018. + sqlite *db, /* The open database */
  31019. + const char *zSql, /* SQL statement to be compiled */
  31020. + const char **pzTail, /* OUT: uncompiled tail of zSql */
  31021. + sqlite_vm **ppVm, /* OUT: the virtual machine to execute zSql */
  31022. + char **pzErrmsg /* OUT: Error message. */
  31023. +);
  31024. +
  31025. +/*
  31026. +** After an SQL statement has been compiled, it is handed to this routine
  31027. +** to be executed. This routine executes the statement as far as it can
  31028. +** go then returns. The return value will be one of SQLITE_DONE,
  31029. +** SQLITE_ERROR, SQLITE_BUSY, SQLITE_ROW, or SQLITE_MISUSE.
  31030. +**
  31031. +** SQLITE_DONE means that the execute of the SQL statement is complete
  31032. +** an no errors have occurred. sqlite_step() should not be called again
  31033. +** for the same virtual machine. *pN is set to the number of columns in
  31034. +** the result set and *pazColName is set to an array of strings that
  31035. +** describe the column names and datatypes. The name of the i-th column
  31036. +** is (*pazColName)[i] and the datatype of the i-th column is
  31037. +** (*pazColName)[i+*pN]. *pazValue is set to NULL.
  31038. +**
  31039. +** SQLITE_ERROR means that the virtual machine encountered a run-time
  31040. +** error. sqlite_step() should not be called again for the same
  31041. +** virtual machine. *pN is set to 0 and *pazColName and *pazValue are set
  31042. +** to NULL. Use sqlite_finalize() to obtain the specific error code
  31043. +** and the error message text for the error.
  31044. +**
  31045. +** SQLITE_BUSY means that an attempt to open the database failed because
  31046. +** another thread or process is holding a lock. The calling routine
  31047. +** can try again to open the database by calling sqlite_step() again.
  31048. +** The return code will only be SQLITE_BUSY if no busy handler is registered
  31049. +** using the sqlite_busy_handler() or sqlite_busy_timeout() routines. If
  31050. +** a busy handler callback has been registered but returns 0, then this
  31051. +** routine will return SQLITE_ERROR and sqltie_finalize() will return
  31052. +** SQLITE_BUSY when it is called.
  31053. +**
  31054. +** SQLITE_ROW means that a single row of the result is now available.
  31055. +** The data is contained in *pazValue. The value of the i-th column is
  31056. +** (*azValue)[i]. *pN and *pazColName are set as described in SQLITE_DONE.
  31057. +** Invoke sqlite_step() again to advance to the next row.
  31058. +**
  31059. +** SQLITE_MISUSE is returned if sqlite_step() is called incorrectly.
  31060. +** For example, if you call sqlite_step() after the virtual machine
  31061. +** has halted (after a prior call to sqlite_step() has returned SQLITE_DONE)
  31062. +** or if you call sqlite_step() with an incorrectly initialized virtual
  31063. +** machine or a virtual machine that has been deleted or that is associated
  31064. +** with an sqlite structure that has been closed.
  31065. +*/
  31066. +int sqlite_step(
  31067. + sqlite_vm *pVm, /* The virtual machine to execute */
  31068. + int *pN, /* OUT: Number of columns in result */
  31069. + const char ***pazValue, /* OUT: Column data */
  31070. + const char ***pazColName /* OUT: Column names and datatypes */
  31071. +);
  31072. +
  31073. +/*
  31074. +** This routine is called to delete a virtual machine after it has finished
  31075. +** executing. The return value is the result code. SQLITE_OK is returned
  31076. +** if the statement executed successfully and some other value is returned if
  31077. +** there was any kind of error. If an error occurred and pzErrMsg is not
  31078. +** NULL, then an error message is written into memory obtained from malloc()
  31079. +** and *pzErrMsg is made to point to that error message. The calling routine
  31080. +** should use sqlite_freemem() to delete this message when it has finished
  31081. +** with it.
  31082. +**
  31083. +** This routine can be called at any point during the execution of the
  31084. +** virtual machine. If the virtual machine has not completed execution
  31085. +** when this routine is called, that is like encountering an error or
  31086. +** an interrupt. (See sqlite_interrupt().) Incomplete updates may be
  31087. +** rolled back and transactions cancelled, depending on the circumstances,
  31088. +** and the result code returned will be SQLITE_ABORT.
  31089. +*/
  31090. +int sqlite_finalize(sqlite_vm*, char **pzErrMsg);
  31091. +
  31092. +/*
  31093. +** This routine deletes the virtual machine, writes any error message to
  31094. +** *pzErrMsg and returns an SQLite return code in the same way as the
  31095. +** sqlite_finalize() function.
  31096. +**
  31097. +** Additionally, if ppVm is not NULL, *ppVm is left pointing to a new virtual
  31098. +** machine loaded with the compiled version of the original query ready for
  31099. +** execution.
  31100. +**
  31101. +** If sqlite_reset() returns SQLITE_SCHEMA, then *ppVm is set to NULL.
  31102. +**
  31103. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  31104. +*/
  31105. +int sqlite_reset(sqlite_vm*, char **pzErrMsg);
  31106. +
  31107. +/*
  31108. +** If the SQL that was handed to sqlite_compile contains variables that
  31109. +** are represeted in the SQL text by a question mark ('?'). This routine
  31110. +** is used to assign values to those variables.
  31111. +**
  31112. +** The first parameter is a virtual machine obtained from sqlite_compile().
  31113. +** The 2nd "idx" parameter determines which variable in the SQL statement
  31114. +** to bind the value to. The left most '?' is 1. The 3rd parameter is
  31115. +** the value to assign to that variable. The 4th parameter is the number
  31116. +** of bytes in the value, including the terminating \000 for strings.
  31117. +** Finally, the 5th "copy" parameter is TRUE if SQLite should make its
  31118. +** own private copy of this value, or false if the space that the 3rd
  31119. +** parameter points to will be unchanging and can be used directly by
  31120. +** SQLite.
  31121. +**
  31122. +** Unbound variables are treated as having a value of NULL. To explicitly
  31123. +** set a variable to NULL, call this routine with the 3rd parameter as a
  31124. +** NULL pointer.
  31125. +**
  31126. +** If the 4th "len" parameter is -1, then strlen() is used to find the
  31127. +** length.
  31128. +**
  31129. +** This routine can only be called immediately after sqlite_compile()
  31130. +** or sqlite_reset() and before any calls to sqlite_step().
  31131. +**
  31132. +******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
  31133. +*/
  31134. +int sqlite_bind(sqlite_vm*, int idx, const char *value, int len, int copy);
  31135. +
  31136. +/*
  31137. +** This routine configures a callback function - the progress callback - that
  31138. +** is invoked periodically during long running calls to sqlite_exec(),
  31139. +** sqlite_step() and sqlite_get_table(). An example use for this API is to keep
  31140. +** a GUI updated during a large query.
  31141. +**
  31142. +** The progress callback is invoked once for every N virtual machine opcodes,
  31143. +** where N is the second argument to this function. The progress callback
  31144. +** itself is identified by the third argument to this function. The fourth
  31145. +** argument to this function is a void pointer passed to the progress callback
  31146. +** function each time it is invoked.
  31147. +**
  31148. +** If a call to sqlite_exec(), sqlite_step() or sqlite_get_table() results
  31149. +** in less than N opcodes being executed, then the progress callback is not
  31150. +** invoked.
  31151. +**
  31152. +** Calling this routine overwrites any previously installed progress callback.
  31153. +** To remove the progress callback altogether, pass NULL as the third
  31154. +** argument to this function.
  31155. +**
  31156. +** If the progress callback returns a result other than 0, then the current
  31157. +** query is immediately terminated and any database changes rolled back. If the
  31158. +** query was part of a larger transaction, then the transaction is not rolled
  31159. +** back and remains active. The sqlite_exec() call returns SQLITE_ABORT.
  31160. +*/
  31161. +void sqlite_progress_handler(sqlite*, int, int(*)(void*), void*);
  31162. +
  31163. +#ifdef __cplusplus
  31164. +} /* End of the 'extern "C"' block */
  31165. +#endif
  31166. +
  31167. +#endif /* _SQLITE_H_ */
  31168. --- /dev/null
  31169. +++ b/ext/sqlite/libsqlite/src/table.c
  31170. @@ -0,0 +1,203 @@
  31171. +/*
  31172. +** 2001 September 15
  31173. +**
  31174. +** The author disclaims copyright to this source code. In place of
  31175. +** a legal notice, here is a blessing:
  31176. +**
  31177. +** May you do good and not evil.
  31178. +** May you find forgiveness for yourself and forgive others.
  31179. +** May you share freely, never taking more than you give.
  31180. +**
  31181. +*************************************************************************
  31182. +** This file contains the sqlite_get_table() and sqlite_free_table()
  31183. +** interface routines. These are just wrappers around the main
  31184. +** interface routine of sqlite_exec().
  31185. +**
  31186. +** These routines are in a separate files so that they will not be linked
  31187. +** if they are not used.
  31188. +*/
  31189. +#include <stdlib.h>
  31190. +#include <string.h>
  31191. +#include "sqliteInt.h"
  31192. +
  31193. +/*
  31194. +** This structure is used to pass data from sqlite_get_table() through
  31195. +** to the callback function is uses to build the result.
  31196. +*/
  31197. +typedef struct TabResult {
  31198. + char **azResult;
  31199. + char *zErrMsg;
  31200. + int nResult;
  31201. + int nAlloc;
  31202. + int nRow;
  31203. + int nColumn;
  31204. + long nData;
  31205. + int rc;
  31206. +} TabResult;
  31207. +
  31208. +/*
  31209. +** This routine is called once for each row in the result table. Its job
  31210. +** is to fill in the TabResult structure appropriately, allocating new
  31211. +** memory as necessary.
  31212. +*/
  31213. +static int sqlite_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  31214. + TabResult *p = (TabResult*)pArg;
  31215. + int need;
  31216. + int i;
  31217. + char *z;
  31218. +
  31219. + /* Make sure there is enough space in p->azResult to hold everything
  31220. + ** we need to remember from this invocation of the callback.
  31221. + */
  31222. + if( p->nRow==0 && argv!=0 ){
  31223. + need = nCol*2;
  31224. + }else{
  31225. + need = nCol;
  31226. + }
  31227. + if( p->nData + need >= p->nAlloc ){
  31228. + char **azNew;
  31229. + p->nAlloc = p->nAlloc*2 + need + 1;
  31230. + azNew = realloc( p->azResult, sizeof(char*)*p->nAlloc );
  31231. + if( azNew==0 ){
  31232. + p->rc = SQLITE_NOMEM;
  31233. + return 1;
  31234. + }
  31235. + p->azResult = azNew;
  31236. + }
  31237. +
  31238. + /* If this is the first row, then generate an extra row containing
  31239. + ** the names of all columns.
  31240. + */
  31241. + if( p->nRow==0 ){
  31242. + p->nColumn = nCol;
  31243. + for(i=0; i<nCol; i++){
  31244. + if( colv[i]==0 ){
  31245. + z = 0;
  31246. + }else{
  31247. + z = malloc( strlen(colv[i])+1 );
  31248. + if( z==0 ){
  31249. + p->rc = SQLITE_NOMEM;
  31250. + return 1;
  31251. + }
  31252. + strcpy(z, colv[i]);
  31253. + }
  31254. + p->azResult[p->nData++] = z;
  31255. + }
  31256. + }else if( p->nColumn!=nCol ){
  31257. + sqliteSetString(&p->zErrMsg,
  31258. + "sqlite_get_table() called with two or more incompatible queries",
  31259. + (char*)0);
  31260. + p->rc = SQLITE_ERROR;
  31261. + return 1;
  31262. + }
  31263. +
  31264. + /* Copy over the row data
  31265. + */
  31266. + if( argv!=0 ){
  31267. + for(i=0; i<nCol; i++){
  31268. + if( argv[i]==0 ){
  31269. + z = 0;
  31270. + }else{
  31271. + z = malloc( strlen(argv[i])+1 );
  31272. + if( z==0 ){
  31273. + p->rc = SQLITE_NOMEM;
  31274. + return 1;
  31275. + }
  31276. + strcpy(z, argv[i]);
  31277. + }
  31278. + p->azResult[p->nData++] = z;
  31279. + }
  31280. + p->nRow++;
  31281. + }
  31282. + return 0;
  31283. +}
  31284. +
  31285. +/*
  31286. +** Query the database. But instead of invoking a callback for each row,
  31287. +** malloc() for space to hold the result and return the entire results
  31288. +** at the conclusion of the call.
  31289. +**
  31290. +** The result that is written to ***pazResult is held in memory obtained
  31291. +** from malloc(). But the caller cannot free this memory directly.
  31292. +** Instead, the entire table should be passed to sqlite_free_table() when
  31293. +** the calling procedure is finished using it.
  31294. +*/
  31295. +int sqlite_get_table(
  31296. + sqlite *db, /* The database on which the SQL executes */
  31297. + const char *zSql, /* The SQL to be executed */
  31298. + char ***pazResult, /* Write the result table here */
  31299. + int *pnRow, /* Write the number of rows in the result here */
  31300. + int *pnColumn, /* Write the number of columns of result here */
  31301. + char **pzErrMsg /* Write error messages here */
  31302. +){
  31303. + int rc;
  31304. + TabResult res;
  31305. + if( pazResult==0 ){ return SQLITE_ERROR; }
  31306. + *pazResult = 0;
  31307. + if( pnColumn ) *pnColumn = 0;
  31308. + if( pnRow ) *pnRow = 0;
  31309. + res.zErrMsg = 0;
  31310. + res.nResult = 0;
  31311. + res.nRow = 0;
  31312. + res.nColumn = 0;
  31313. + res.nData = 1;
  31314. + res.nAlloc = 20;
  31315. + res.rc = SQLITE_OK;
  31316. + res.azResult = malloc( sizeof(char*)*res.nAlloc );
  31317. + if( res.azResult==0 ){
  31318. + return SQLITE_NOMEM;
  31319. + }
  31320. + res.azResult[0] = 0;
  31321. + rc = sqlite_exec(db, zSql, sqlite_get_table_cb, &res, pzErrMsg);
  31322. + if( res.azResult ){
  31323. + res.azResult[0] = (char*)res.nData;
  31324. + }
  31325. + if( rc==SQLITE_ABORT ){
  31326. + sqlite_free_table(&res.azResult[1]);
  31327. + if( res.zErrMsg ){
  31328. + if( pzErrMsg ){
  31329. + free(*pzErrMsg);
  31330. + *pzErrMsg = res.zErrMsg;
  31331. + sqliteStrRealloc(pzErrMsg);
  31332. + }else{
  31333. + sqliteFree(res.zErrMsg);
  31334. + }
  31335. + }
  31336. + return res.rc;
  31337. + }
  31338. + sqliteFree(res.zErrMsg);
  31339. + if( rc!=SQLITE_OK ){
  31340. + sqlite_free_table(&res.azResult[1]);
  31341. + return rc;
  31342. + }
  31343. + if( res.nAlloc>res.nData ){
  31344. + char **azNew;
  31345. + azNew = realloc( res.azResult, sizeof(char*)*(res.nData+1) );
  31346. + if( azNew==0 ){
  31347. + sqlite_free_table(&res.azResult[1]);
  31348. + return SQLITE_NOMEM;
  31349. + }
  31350. + res.nAlloc = res.nData+1;
  31351. + res.azResult = azNew;
  31352. + }
  31353. + *pazResult = &res.azResult[1];
  31354. + if( pnColumn ) *pnColumn = res.nColumn;
  31355. + if( pnRow ) *pnRow = res.nRow;
  31356. + return rc;
  31357. +}
  31358. +
  31359. +/*
  31360. +** This routine frees the space the sqlite_get_table() malloced.
  31361. +*/
  31362. +void sqlite_free_table(
  31363. + char **azResult /* Result returned from from sqlite_get_table() */
  31364. +){
  31365. + if( azResult ){
  31366. + int i, n;
  31367. + azResult--;
  31368. + if( azResult==0 ) return;
  31369. + n = (int)(long)azResult[0];
  31370. + for(i=1; i<n; i++){ if( azResult[i] ) free(azResult[i]); }
  31371. + free(azResult);
  31372. + }
  31373. +}
  31374. --- /dev/null
  31375. +++ b/ext/sqlite/libsqlite/src/tokenize.c
  31376. @@ -0,0 +1,679 @@
  31377. +/*
  31378. +** 2001 September 15
  31379. +**
  31380. +** The author disclaims copyright to this source code. In place of
  31381. +** a legal notice, here is a blessing:
  31382. +**
  31383. +** May you do good and not evil.
  31384. +** May you find forgiveness for yourself and forgive others.
  31385. +** May you share freely, never taking more than you give.
  31386. +**
  31387. +*************************************************************************
  31388. +** An tokenizer for SQL
  31389. +**
  31390. +** This file contains C code that splits an SQL input string up into
  31391. +** individual tokens and sends those tokens one-by-one over to the
  31392. +** parser for analysis.
  31393. +**
  31394. +** $Id$
  31395. +*/
  31396. +#include "sqliteInt.h"
  31397. +#include "os.h"
  31398. +#include <ctype.h>
  31399. +#include <stdlib.h>
  31400. +
  31401. +/*
  31402. +** All the keywords of the SQL language are stored as in a hash
  31403. +** table composed of instances of the following structure.
  31404. +*/
  31405. +typedef struct Keyword Keyword;
  31406. +struct Keyword {
  31407. + char *zName; /* The keyword name */
  31408. + u8 tokenType; /* Token value for this keyword */
  31409. + u8 len; /* Length of this keyword */
  31410. + u8 iNext; /* Index in aKeywordTable[] of next with same hash */
  31411. +};
  31412. +
  31413. +/*
  31414. +** These are the keywords
  31415. +*/
  31416. +static Keyword aKeywordTable[] = {
  31417. + { "ABORT", TK_ABORT, },
  31418. + { "AFTER", TK_AFTER, },
  31419. + { "ALL", TK_ALL, },
  31420. + { "AND", TK_AND, },
  31421. + { "AS", TK_AS, },
  31422. + { "ASC", TK_ASC, },
  31423. + { "ATTACH", TK_ATTACH, },
  31424. + { "BEFORE", TK_BEFORE, },
  31425. + { "BEGIN", TK_BEGIN, },
  31426. + { "BETWEEN", TK_BETWEEN, },
  31427. + { "BY", TK_BY, },
  31428. + { "CASCADE", TK_CASCADE, },
  31429. + { "CASE", TK_CASE, },
  31430. + { "CHECK", TK_CHECK, },
  31431. + { "CLUSTER", TK_CLUSTER, },
  31432. + { "COLLATE", TK_COLLATE, },
  31433. + { "COMMIT", TK_COMMIT, },
  31434. + { "CONFLICT", TK_CONFLICT, },
  31435. + { "CONSTRAINT", TK_CONSTRAINT, },
  31436. + { "COPY", TK_COPY, },
  31437. + { "CREATE", TK_CREATE, },
  31438. + { "CROSS", TK_JOIN_KW, },
  31439. + { "DATABASE", TK_DATABASE, },
  31440. + { "DEFAULT", TK_DEFAULT, },
  31441. + { "DEFERRED", TK_DEFERRED, },
  31442. + { "DEFERRABLE", TK_DEFERRABLE, },
  31443. + { "DELETE", TK_DELETE, },
  31444. + { "DELIMITERS", TK_DELIMITERS, },
  31445. + { "DESC", TK_DESC, },
  31446. + { "DETACH", TK_DETACH, },
  31447. + { "DISTINCT", TK_DISTINCT, },
  31448. + { "DROP", TK_DROP, },
  31449. + { "END", TK_END, },
  31450. + { "EACH", TK_EACH, },
  31451. + { "ELSE", TK_ELSE, },
  31452. + { "EXCEPT", TK_EXCEPT, },
  31453. + { "EXPLAIN", TK_EXPLAIN, },
  31454. + { "FAIL", TK_FAIL, },
  31455. + { "FOR", TK_FOR, },
  31456. + { "FOREIGN", TK_FOREIGN, },
  31457. + { "FROM", TK_FROM, },
  31458. + { "FULL", TK_JOIN_KW, },
  31459. + { "GLOB", TK_GLOB, },
  31460. + { "GROUP", TK_GROUP, },
  31461. + { "HAVING", TK_HAVING, },
  31462. + { "IGNORE", TK_IGNORE, },
  31463. + { "IMMEDIATE", TK_IMMEDIATE, },
  31464. + { "IN", TK_IN, },
  31465. + { "INDEX", TK_INDEX, },
  31466. + { "INITIALLY", TK_INITIALLY, },
  31467. + { "INNER", TK_JOIN_KW, },
  31468. + { "INSERT", TK_INSERT, },
  31469. + { "INSTEAD", TK_INSTEAD, },
  31470. + { "INTERSECT", TK_INTERSECT, },
  31471. + { "INTO", TK_INTO, },
  31472. + { "IS", TK_IS, },
  31473. + { "ISNULL", TK_ISNULL, },
  31474. + { "JOIN", TK_JOIN, },
  31475. + { "KEY", TK_KEY, },
  31476. + { "LEFT", TK_JOIN_KW, },
  31477. + { "LIKE", TK_LIKE, },
  31478. + { "LIMIT", TK_LIMIT, },
  31479. + { "MATCH", TK_MATCH, },
  31480. + { "NATURAL", TK_JOIN_KW, },
  31481. + { "NOT", TK_NOT, },
  31482. + { "NOTNULL", TK_NOTNULL, },
  31483. + { "NULL", TK_NULL, },
  31484. + { "OF", TK_OF, },
  31485. + { "OFFSET", TK_OFFSET, },
  31486. + { "ON", TK_ON, },
  31487. + { "OR", TK_OR, },
  31488. + { "ORDER", TK_ORDER, },
  31489. + { "OUTER", TK_JOIN_KW, },
  31490. + { "PRAGMA", TK_PRAGMA, },
  31491. + { "PRIMARY", TK_PRIMARY, },
  31492. + { "RAISE", TK_RAISE, },
  31493. + { "REFERENCES", TK_REFERENCES, },
  31494. + { "REPLACE", TK_REPLACE, },
  31495. + { "RESTRICT", TK_RESTRICT, },
  31496. + { "RIGHT", TK_JOIN_KW, },
  31497. + { "ROLLBACK", TK_ROLLBACK, },
  31498. + { "ROW", TK_ROW, },
  31499. + { "SELECT", TK_SELECT, },
  31500. + { "SET", TK_SET, },
  31501. + { "STATEMENT", TK_STATEMENT, },
  31502. + { "TABLE", TK_TABLE, },
  31503. + { "TEMP", TK_TEMP, },
  31504. + { "TEMPORARY", TK_TEMP, },
  31505. + { "THEN", TK_THEN, },
  31506. + { "TRANSACTION", TK_TRANSACTION, },
  31507. + { "TRIGGER", TK_TRIGGER, },
  31508. + { "UNION", TK_UNION, },
  31509. + { "UNIQUE", TK_UNIQUE, },
  31510. + { "UPDATE", TK_UPDATE, },
  31511. + { "USING", TK_USING, },
  31512. + { "VACUUM", TK_VACUUM, },
  31513. + { "VALUES", TK_VALUES, },
  31514. + { "VIEW", TK_VIEW, },
  31515. + { "WHEN", TK_WHEN, },
  31516. + { "WHERE", TK_WHERE, },
  31517. +};
  31518. +
  31519. +/*
  31520. +** This is the hash table
  31521. +*/
  31522. +#define KEY_HASH_SIZE 101
  31523. +static u8 aiHashTable[KEY_HASH_SIZE];
  31524. +
  31525. +
  31526. +/*
  31527. +** This function looks up an identifier to determine if it is a
  31528. +** keyword. If it is a keyword, the token code of that keyword is
  31529. +** returned. If the input is not a keyword, TK_ID is returned.
  31530. +*/
  31531. +int sqliteKeywordCode(const char *z, int n){
  31532. + int h, i;
  31533. + Keyword *p;
  31534. + static char needInit = 1;
  31535. + if( needInit ){
  31536. + /* Initialize the keyword hash table */
  31537. + sqliteOsEnterMutex();
  31538. + if( needInit ){
  31539. + int nk;
  31540. + nk = sizeof(aKeywordTable)/sizeof(aKeywordTable[0]);
  31541. + for(i=0; i<nk; i++){
  31542. + aKeywordTable[i].len = strlen(aKeywordTable[i].zName);
  31543. + h = sqliteHashNoCase(aKeywordTable[i].zName, aKeywordTable[i].len);
  31544. + h %= KEY_HASH_SIZE;
  31545. + aKeywordTable[i].iNext = aiHashTable[h];
  31546. + aiHashTable[h] = i+1;
  31547. + }
  31548. + needInit = 0;
  31549. + }
  31550. + sqliteOsLeaveMutex();
  31551. + }
  31552. + h = sqliteHashNoCase(z, n) % KEY_HASH_SIZE;
  31553. + for(i=aiHashTable[h]; i; i=p->iNext){
  31554. + p = &aKeywordTable[i-1];
  31555. + if( p->len==n && sqliteStrNICmp(p->zName, z, n)==0 ){
  31556. + return p->tokenType;
  31557. + }
  31558. + }
  31559. + return TK_ID;
  31560. +}
  31561. +
  31562. +
  31563. +/*
  31564. +** If X is a character that can be used in an identifier and
  31565. +** X&0x80==0 then isIdChar[X] will be 1. If X&0x80==0x80 then
  31566. +** X is always an identifier character. (Hence all UTF-8
  31567. +** characters can be part of an identifier). isIdChar[X] will
  31568. +** be 0 for every character in the lower 128 ASCII characters
  31569. +** that cannot be used as part of an identifier.
  31570. +**
  31571. +** In this implementation, an identifier can be a string of
  31572. +** alphabetic characters, digits, and "_" plus any character
  31573. +** with the high-order bit set. The latter rule means that
  31574. +** any sequence of UTF-8 characters or characters taken from
  31575. +** an extended ISO8859 character set can form an identifier.
  31576. +*/
  31577. +static const char isIdChar[] = {
  31578. +/* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  31579. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  31580. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  31581. + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  31582. + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  31583. + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  31584. + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  31585. + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  31586. + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  31587. +};
  31588. +
  31589. +
  31590. +/*
  31591. +** Return the length of the token that begins at z[0].
  31592. +** Store the token type in *tokenType before returning.
  31593. +*/
  31594. +static int sqliteGetToken(const unsigned char *z, int *tokenType){
  31595. + int i;
  31596. + switch( *z ){
  31597. + case ' ': case '\t': case '\n': case '\f': case '\r': {
  31598. + for(i=1; isspace(z[i]); i++){}
  31599. + *tokenType = TK_SPACE;
  31600. + return i;
  31601. + }
  31602. + case '-': {
  31603. + if( z[1]=='-' ){
  31604. + for(i=2; z[i] && z[i]!='\n'; i++){}
  31605. + *tokenType = TK_COMMENT;
  31606. + return i;
  31607. + }
  31608. + *tokenType = TK_MINUS;
  31609. + return 1;
  31610. + }
  31611. + case '(': {
  31612. + *tokenType = TK_LP;
  31613. + return 1;
  31614. + }
  31615. + case ')': {
  31616. + *tokenType = TK_RP;
  31617. + return 1;
  31618. + }
  31619. + case ';': {
  31620. + *tokenType = TK_SEMI;
  31621. + return 1;
  31622. + }
  31623. + case '+': {
  31624. + *tokenType = TK_PLUS;
  31625. + return 1;
  31626. + }
  31627. + case '*': {
  31628. + *tokenType = TK_STAR;
  31629. + return 1;
  31630. + }
  31631. + case '/': {
  31632. + if( z[1]!='*' || z[2]==0 ){
  31633. + *tokenType = TK_SLASH;
  31634. + return 1;
  31635. + }
  31636. + for(i=3; z[i] && (z[i]!='/' || z[i-1]!='*'); i++){}
  31637. + if( z[i] ) i++;
  31638. + *tokenType = TK_COMMENT;
  31639. + return i;
  31640. + }
  31641. + case '%': {
  31642. + *tokenType = TK_REM;
  31643. + return 1;
  31644. + }
  31645. + case '=': {
  31646. + *tokenType = TK_EQ;
  31647. + return 1 + (z[1]=='=');
  31648. + }
  31649. + case '<': {
  31650. + if( z[1]=='=' ){
  31651. + *tokenType = TK_LE;
  31652. + return 2;
  31653. + }else if( z[1]=='>' ){
  31654. + *tokenType = TK_NE;
  31655. + return 2;
  31656. + }else if( z[1]=='<' ){
  31657. + *tokenType = TK_LSHIFT;
  31658. + return 2;
  31659. + }else{
  31660. + *tokenType = TK_LT;
  31661. + return 1;
  31662. + }
  31663. + }
  31664. + case '>': {
  31665. + if( z[1]=='=' ){
  31666. + *tokenType = TK_GE;
  31667. + return 2;
  31668. + }else if( z[1]=='>' ){
  31669. + *tokenType = TK_RSHIFT;
  31670. + return 2;
  31671. + }else{
  31672. + *tokenType = TK_GT;
  31673. + return 1;
  31674. + }
  31675. + }
  31676. + case '!': {
  31677. + if( z[1]!='=' ){
  31678. + *tokenType = TK_ILLEGAL;
  31679. + return 2;
  31680. + }else{
  31681. + *tokenType = TK_NE;
  31682. + return 2;
  31683. + }
  31684. + }
  31685. + case '|': {
  31686. + if( z[1]!='|' ){
  31687. + *tokenType = TK_BITOR;
  31688. + return 1;
  31689. + }else{
  31690. + *tokenType = TK_CONCAT;
  31691. + return 2;
  31692. + }
  31693. + }
  31694. + case ',': {
  31695. + *tokenType = TK_COMMA;
  31696. + return 1;
  31697. + }
  31698. + case '&': {
  31699. + *tokenType = TK_BITAND;
  31700. + return 1;
  31701. + }
  31702. + case '~': {
  31703. + *tokenType = TK_BITNOT;
  31704. + return 1;
  31705. + }
  31706. + case '\'': case '"': {
  31707. + int delim = z[0];
  31708. + for(i=1; z[i]; i++){
  31709. + if( z[i]==delim ){
  31710. + if( z[i+1]==delim ){
  31711. + i++;
  31712. + }else{
  31713. + break;
  31714. + }
  31715. + }
  31716. + }
  31717. + if( z[i] ) i++;
  31718. + *tokenType = TK_STRING;
  31719. + return i;
  31720. + }
  31721. + case '.': {
  31722. + *tokenType = TK_DOT;
  31723. + return 1;
  31724. + }
  31725. + case '0': case '1': case '2': case '3': case '4':
  31726. + case '5': case '6': case '7': case '8': case '9': {
  31727. + *tokenType = TK_INTEGER;
  31728. + for(i=1; isdigit(z[i]); i++){}
  31729. + if( z[i]=='.' && isdigit(z[i+1]) ){
  31730. + i += 2;
  31731. + while( isdigit(z[i]) ){ i++; }
  31732. + *tokenType = TK_FLOAT;
  31733. + }
  31734. + if( (z[i]=='e' || z[i]=='E') &&
  31735. + ( isdigit(z[i+1])
  31736. + || ((z[i+1]=='+' || z[i+1]=='-') && isdigit(z[i+2]))
  31737. + )
  31738. + ){
  31739. + i += 2;
  31740. + while( isdigit(z[i]) ){ i++; }
  31741. + *tokenType = TK_FLOAT;
  31742. + }
  31743. + return i;
  31744. + }
  31745. + case '[': {
  31746. + for(i=1; z[i] && z[i-1]!=']'; i++){}
  31747. + *tokenType = TK_ID;
  31748. + return i;
  31749. + }
  31750. + case '?': {
  31751. + *tokenType = TK_VARIABLE;
  31752. + return 1;
  31753. + }
  31754. + default: {
  31755. + if( (*z&0x80)==0 && !isIdChar[*z] ){
  31756. + break;
  31757. + }
  31758. + for(i=1; (z[i]&0x80)!=0 || isIdChar[z[i]]; i++){}
  31759. + *tokenType = sqliteKeywordCode((char*)z, i);
  31760. + return i;
  31761. + }
  31762. + }
  31763. + *tokenType = TK_ILLEGAL;
  31764. + return 1;
  31765. +}
  31766. +
  31767. +/*
  31768. +** Run the parser on the given SQL string. The parser structure is
  31769. +** passed in. An SQLITE_ status code is returned. If an error occurs
  31770. +** and pzErrMsg!=NULL then an error message might be written into
  31771. +** memory obtained from malloc() and *pzErrMsg made to point to that
  31772. +** error message. Or maybe not.
  31773. +*/
  31774. +int sqliteRunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  31775. + int nErr = 0;
  31776. + int i;
  31777. + void *pEngine;
  31778. + int tokenType;
  31779. + int lastTokenParsed = -1;
  31780. + sqlite *db = pParse->db;
  31781. + extern void *sqliteParserAlloc(void*(*)(int));
  31782. + extern void sqliteParserFree(void*, void(*)(void*));
  31783. + extern int sqliteParser(void*, int, Token, Parse*);
  31784. +
  31785. + db->flags &= ~SQLITE_Interrupt;
  31786. + pParse->rc = SQLITE_OK;
  31787. + i = 0;
  31788. + pEngine = sqliteParserAlloc((void*(*)(int))malloc);
  31789. + if( pEngine==0 ){
  31790. + sqliteSetString(pzErrMsg, "out of memory", (char*)0);
  31791. + return 1;
  31792. + }
  31793. + pParse->sLastToken.dyn = 0;
  31794. + pParse->zTail = zSql;
  31795. + while( sqlite_malloc_failed==0 && zSql[i]!=0 ){
  31796. + assert( i>=0 );
  31797. + pParse->sLastToken.z = &zSql[i];
  31798. + assert( pParse->sLastToken.dyn==0 );
  31799. + pParse->sLastToken.n = sqliteGetToken((unsigned char*)&zSql[i], &tokenType);
  31800. + i += pParse->sLastToken.n;
  31801. + switch( tokenType ){
  31802. + case TK_SPACE:
  31803. + case TK_COMMENT: {
  31804. + if( (db->flags & SQLITE_Interrupt)!=0 ){
  31805. + pParse->rc = SQLITE_INTERRUPT;
  31806. + sqliteSetString(pzErrMsg, "interrupt", (char*)0);
  31807. + goto abort_parse;
  31808. + }
  31809. + break;
  31810. + }
  31811. + case TK_ILLEGAL: {
  31812. + sqliteSetNString(pzErrMsg, "unrecognized token: \"", -1,
  31813. + pParse->sLastToken.z, pParse->sLastToken.n, "\"", 1, 0);
  31814. + nErr++;
  31815. + goto abort_parse;
  31816. + }
  31817. + case TK_SEMI: {
  31818. + pParse->zTail = &zSql[i];
  31819. + /* Fall thru into the default case */
  31820. + }
  31821. + default: {
  31822. + sqliteParser(pEngine, tokenType, pParse->sLastToken, pParse);
  31823. + lastTokenParsed = tokenType;
  31824. + if( pParse->rc!=SQLITE_OK ){
  31825. + goto abort_parse;
  31826. + }
  31827. + break;
  31828. + }
  31829. + }
  31830. + }
  31831. +abort_parse:
  31832. + if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  31833. + if( lastTokenParsed!=TK_SEMI ){
  31834. + sqliteParser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  31835. + pParse->zTail = &zSql[i];
  31836. + }
  31837. + sqliteParser(pEngine, 0, pParse->sLastToken, pParse);
  31838. + }
  31839. + sqliteParserFree(pEngine, free);
  31840. + if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  31841. + sqliteSetString(&pParse->zErrMsg, sqlite_error_string(pParse->rc),
  31842. + (char*)0);
  31843. + }
  31844. + if( pParse->zErrMsg ){
  31845. + if( pzErrMsg && *pzErrMsg==0 ){
  31846. + *pzErrMsg = pParse->zErrMsg;
  31847. + }else{
  31848. + sqliteFree(pParse->zErrMsg);
  31849. + }
  31850. + pParse->zErrMsg = 0;
  31851. + if( !nErr ) nErr++;
  31852. + }
  31853. + if( pParse->pVdbe && pParse->nErr>0 ){
  31854. + sqliteVdbeDelete(pParse->pVdbe);
  31855. + pParse->pVdbe = 0;
  31856. + }
  31857. + if( pParse->pNewTable ){
  31858. + sqliteDeleteTable(pParse->db, pParse->pNewTable);
  31859. + pParse->pNewTable = 0;
  31860. + }
  31861. + if( pParse->pNewTrigger ){
  31862. + sqliteDeleteTrigger(pParse->pNewTrigger);
  31863. + pParse->pNewTrigger = 0;
  31864. + }
  31865. + if( nErr>0 && (pParse->rc==SQLITE_OK || pParse->rc==SQLITE_DONE) ){
  31866. + pParse->rc = SQLITE_ERROR;
  31867. + }
  31868. + return nErr;
  31869. +}
  31870. +
  31871. +/*
  31872. +** Token types used by the sqlite_complete() routine. See the header
  31873. +** comments on that procedure for additional information.
  31874. +*/
  31875. +#define tkEXPLAIN 0
  31876. +#define tkCREATE 1
  31877. +#define tkTEMP 2
  31878. +#define tkTRIGGER 3
  31879. +#define tkEND 4
  31880. +#define tkSEMI 5
  31881. +#define tkWS 6
  31882. +#define tkOTHER 7
  31883. +
  31884. +/*
  31885. +** Return TRUE if the given SQL string ends in a semicolon.
  31886. +**
  31887. +** Special handling is require for CREATE TRIGGER statements.
  31888. +** Whenever the CREATE TRIGGER keywords are seen, the statement
  31889. +** must end with ";END;".
  31890. +**
  31891. +** This implementation uses a state machine with 7 states:
  31892. +**
  31893. +** (0) START At the beginning or end of an SQL statement. This routine
  31894. +** returns 1 if it ends in the START state and 0 if it ends
  31895. +** in any other state.
  31896. +**
  31897. +** (1) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  31898. +** a statement.
  31899. +**
  31900. +** (2) CREATE The keyword CREATE has been seen at the beginning of a
  31901. +** statement, possibly preceeded by EXPLAIN and/or followed by
  31902. +** TEMP or TEMPORARY
  31903. +**
  31904. +** (3) NORMAL We are in the middle of statement which ends with a single
  31905. +** semicolon.
  31906. +**
  31907. +** (4) TRIGGER We are in the middle of a trigger definition that must be
  31908. +** ended by a semicolon, the keyword END, and another semicolon.
  31909. +**
  31910. +** (5) SEMI We've seen the first semicolon in the ";END;" that occurs at
  31911. +** the end of a trigger definition.
  31912. +**
  31913. +** (6) END We've seen the ";END" of the ";END;" that occurs at the end
  31914. +** of a trigger difinition.
  31915. +**
  31916. +** Transitions between states above are determined by tokens extracted
  31917. +** from the input. The following tokens are significant:
  31918. +**
  31919. +** (0) tkEXPLAIN The "explain" keyword.
  31920. +** (1) tkCREATE The "create" keyword.
  31921. +** (2) tkTEMP The "temp" or "temporary" keyword.
  31922. +** (3) tkTRIGGER The "trigger" keyword.
  31923. +** (4) tkEND The "end" keyword.
  31924. +** (5) tkSEMI A semicolon.
  31925. +** (6) tkWS Whitespace
  31926. +** (7) tkOTHER Any other SQL token.
  31927. +**
  31928. +** Whitespace never causes a state transition and is always ignored.
  31929. +*/
  31930. +int sqlite_complete(const char *zSql){
  31931. + u8 state = 0; /* Current state, using numbers defined in header comment */
  31932. + u8 token; /* Value of the next token */
  31933. +
  31934. + /* The following matrix defines the transition from one state to another
  31935. + ** according to what token is seen. trans[state][token] returns the
  31936. + ** next state.
  31937. + */
  31938. + static const u8 trans[7][8] = {
  31939. + /* Token: */
  31940. + /* State: ** EXPLAIN CREATE TEMP TRIGGER END SEMI WS OTHER */
  31941. + /* 0 START: */ { 1, 2, 3, 3, 3, 0, 0, 3, },
  31942. + /* 1 EXPLAIN: */ { 3, 2, 3, 3, 3, 0, 1, 3, },
  31943. + /* 2 CREATE: */ { 3, 3, 2, 4, 3, 0, 2, 3, },
  31944. + /* 3 NORMAL: */ { 3, 3, 3, 3, 3, 0, 3, 3, },
  31945. + /* 4 TRIGGER: */ { 4, 4, 4, 4, 4, 5, 4, 4, },
  31946. + /* 5 SEMI: */ { 4, 4, 4, 4, 6, 5, 5, 4, },
  31947. + /* 6 END: */ { 4, 4, 4, 4, 4, 0, 6, 4, },
  31948. + };
  31949. +
  31950. + while( *zSql ){
  31951. + switch( *zSql ){
  31952. + case ';': { /* A semicolon */
  31953. + token = tkSEMI;
  31954. + break;
  31955. + }
  31956. + case ' ':
  31957. + case '\r':
  31958. + case '\t':
  31959. + case '\n':
  31960. + case '\f': { /* White space is ignored */
  31961. + token = tkWS;
  31962. + break;
  31963. + }
  31964. + case '/': { /* C-style comments */
  31965. + if( zSql[1]!='*' ){
  31966. + token = tkOTHER;
  31967. + break;
  31968. + }
  31969. + zSql += 2;
  31970. + while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  31971. + if( zSql[0]==0 ) return 0;
  31972. + zSql++;
  31973. + token = tkWS;
  31974. + break;
  31975. + }
  31976. + case '-': { /* SQL-style comments from "--" to end of line */
  31977. + if( zSql[1]!='-' ){
  31978. + token = tkOTHER;
  31979. + break;
  31980. + }
  31981. + while( *zSql && *zSql!='\n' ){ zSql++; }
  31982. + if( *zSql==0 ) return state==0;
  31983. + token = tkWS;
  31984. + break;
  31985. + }
  31986. + case '[': { /* Microsoft-style identifiers in [...] */
  31987. + zSql++;
  31988. + while( *zSql && *zSql!=']' ){ zSql++; }
  31989. + if( *zSql==0 ) return 0;
  31990. + token = tkOTHER;
  31991. + break;
  31992. + }
  31993. + case '"': /* single- and double-quoted strings */
  31994. + case '\'': {
  31995. + int c = *zSql;
  31996. + zSql++;
  31997. + while( *zSql && *zSql!=c ){ zSql++; }
  31998. + if( *zSql==0 ) return 0;
  31999. + token = tkOTHER;
  32000. + break;
  32001. + }
  32002. + default: {
  32003. + if( isIdChar[(u8)*zSql] ){
  32004. + /* Keywords and unquoted identifiers */
  32005. + int nId;
  32006. + for(nId=1; isIdChar[(u8)zSql[nId]]; nId++){}
  32007. + switch( *zSql ){
  32008. + case 'c': case 'C': {
  32009. + if( nId==6 && sqliteStrNICmp(zSql, "create", 6)==0 ){
  32010. + token = tkCREATE;
  32011. + }else{
  32012. + token = tkOTHER;
  32013. + }
  32014. + break;
  32015. + }
  32016. + case 't': case 'T': {
  32017. + if( nId==7 && sqliteStrNICmp(zSql, "trigger", 7)==0 ){
  32018. + token = tkTRIGGER;
  32019. + }else if( nId==4 && sqliteStrNICmp(zSql, "temp", 4)==0 ){
  32020. + token = tkTEMP;
  32021. + }else if( nId==9 && sqliteStrNICmp(zSql, "temporary", 9)==0 ){
  32022. + token = tkTEMP;
  32023. + }else{
  32024. + token = tkOTHER;
  32025. + }
  32026. + break;
  32027. + }
  32028. + case 'e': case 'E': {
  32029. + if( nId==3 && sqliteStrNICmp(zSql, "end", 3)==0 ){
  32030. + token = tkEND;
  32031. + }else if( nId==7 && sqliteStrNICmp(zSql, "explain", 7)==0 ){
  32032. + token = tkEXPLAIN;
  32033. + }else{
  32034. + token = tkOTHER;
  32035. + }
  32036. + break;
  32037. + }
  32038. + default: {
  32039. + token = tkOTHER;
  32040. + break;
  32041. + }
  32042. + }
  32043. + zSql += nId-1;
  32044. + }else{
  32045. + /* Operators and special symbols */
  32046. + token = tkOTHER;
  32047. + }
  32048. + break;
  32049. + }
  32050. + }
  32051. + state = trans[state][token];
  32052. + zSql++;
  32053. + }
  32054. + return state==0;
  32055. +}
  32056. --- /dev/null
  32057. +++ b/ext/sqlite/libsqlite/src/trigger.c
  32058. @@ -0,0 +1,764 @@
  32059. +/*
  32060. +**
  32061. +** The author disclaims copyright to this source code. In place of
  32062. +** a legal notice, here is a blessing:
  32063. +**
  32064. +** May you do good and not evil.
  32065. +** May you find forgiveness for yourself and forgive others.
  32066. +** May you share freely, never taking more than you give.
  32067. +**
  32068. +*************************************************************************
  32069. +*
  32070. +*/
  32071. +#include "sqliteInt.h"
  32072. +
  32073. +/*
  32074. +** Delete a linked list of TriggerStep structures.
  32075. +*/
  32076. +void sqliteDeleteTriggerStep(TriggerStep *pTriggerStep){
  32077. + while( pTriggerStep ){
  32078. + TriggerStep * pTmp = pTriggerStep;
  32079. + pTriggerStep = pTriggerStep->pNext;
  32080. +
  32081. + if( pTmp->target.dyn ) sqliteFree((char*)pTmp->target.z);
  32082. + sqliteExprDelete(pTmp->pWhere);
  32083. + sqliteExprListDelete(pTmp->pExprList);
  32084. + sqliteSelectDelete(pTmp->pSelect);
  32085. + sqliteIdListDelete(pTmp->pIdList);
  32086. +
  32087. + sqliteFree(pTmp);
  32088. + }
  32089. +}
  32090. +
  32091. +/*
  32092. +** This is called by the parser when it sees a CREATE TRIGGER statement
  32093. +** up to the point of the BEGIN before the trigger actions. A Trigger
  32094. +** structure is generated based on the information available and stored
  32095. +** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  32096. +** sqliteFinishTrigger() function is called to complete the trigger
  32097. +** construction process.
  32098. +*/
  32099. +void sqliteBeginTrigger(
  32100. + Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  32101. + Token *pName, /* The name of the trigger */
  32102. + int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  32103. + int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  32104. + IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  32105. + SrcList *pTableName,/* The name of the table/view the trigger applies to */
  32106. + int foreach, /* One of TK_ROW or TK_STATEMENT */
  32107. + Expr *pWhen, /* WHEN clause */
  32108. + int isTemp /* True if the TEMPORARY keyword is present */
  32109. +){
  32110. + Trigger *nt;
  32111. + Table *tab;
  32112. + char *zName = 0; /* Name of the trigger */
  32113. + sqlite *db = pParse->db;
  32114. + int iDb; /* When database to store the trigger in */
  32115. + DbFixer sFix;
  32116. +
  32117. + /* Check that:
  32118. + ** 1. the trigger name does not already exist.
  32119. + ** 2. the table (or view) does exist in the same database as the trigger.
  32120. + ** 3. that we are not trying to create a trigger on the sqlite_master table
  32121. + ** 4. That we are not trying to create an INSTEAD OF trigger on a table.
  32122. + ** 5. That we are not trying to create a BEFORE or AFTER trigger on a view.
  32123. + */
  32124. + if( sqlite_malloc_failed ) goto trigger_cleanup;
  32125. + assert( pTableName->nSrc==1 );
  32126. + if( db->init.busy
  32127. + && sqliteFixInit(&sFix, pParse, db->init.iDb, "trigger", pName)
  32128. + && sqliteFixSrcList(&sFix, pTableName)
  32129. + ){
  32130. + goto trigger_cleanup;
  32131. + }
  32132. + tab = sqliteSrcListLookup(pParse, pTableName);
  32133. + if( !tab ){
  32134. + goto trigger_cleanup;
  32135. + }
  32136. + iDb = isTemp ? 1 : tab->iDb;
  32137. + if( iDb>=2 && !db->init.busy ){
  32138. + sqliteErrorMsg(pParse, "triggers may not be added to auxiliary "
  32139. + "database %s", db->aDb[tab->iDb].zName);
  32140. + goto trigger_cleanup;
  32141. + }
  32142. +
  32143. + zName = sqliteStrNDup(pName->z, pName->n);
  32144. + sqliteDequote(zName);
  32145. + if( sqliteHashFind(&(db->aDb[iDb].trigHash), zName,pName->n+1) ){
  32146. + sqliteErrorMsg(pParse, "trigger %T already exists", pName);
  32147. + goto trigger_cleanup;
  32148. + }
  32149. + if( sqliteStrNICmp(tab->zName, "sqlite_", 7)==0 ){
  32150. + sqliteErrorMsg(pParse, "cannot create trigger on system table");
  32151. + pParse->nErr++;
  32152. + goto trigger_cleanup;
  32153. + }
  32154. + if( tab->pSelect && tr_tm != TK_INSTEAD ){
  32155. + sqliteErrorMsg(pParse, "cannot create %s trigger on view: %S",
  32156. + (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  32157. + goto trigger_cleanup;
  32158. + }
  32159. + if( !tab->pSelect && tr_tm == TK_INSTEAD ){
  32160. + sqliteErrorMsg(pParse, "cannot create INSTEAD OF"
  32161. + " trigger on table: %S", pTableName, 0);
  32162. + goto trigger_cleanup;
  32163. + }
  32164. +#ifndef SQLITE_OMIT_AUTHORIZATION
  32165. + {
  32166. + int code = SQLITE_CREATE_TRIGGER;
  32167. + const char *zDb = db->aDb[tab->iDb].zName;
  32168. + const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  32169. + if( tab->iDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  32170. + if( sqliteAuthCheck(pParse, code, zName, tab->zName, zDbTrig) ){
  32171. + goto trigger_cleanup;
  32172. + }
  32173. + if( sqliteAuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(tab->iDb), 0, zDb)){
  32174. + goto trigger_cleanup;
  32175. + }
  32176. + }
  32177. +#endif
  32178. +
  32179. + /* INSTEAD OF triggers can only appear on views and BEGIN triggers
  32180. + ** cannot appear on views. So we might as well translate every
  32181. + ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  32182. + ** elsewhere.
  32183. + */
  32184. + if (tr_tm == TK_INSTEAD){
  32185. + tr_tm = TK_BEFORE;
  32186. + }
  32187. +
  32188. + /* Build the Trigger object */
  32189. + nt = (Trigger*)sqliteMalloc(sizeof(Trigger));
  32190. + if( nt==0 ) goto trigger_cleanup;
  32191. + nt->name = zName;
  32192. + zName = 0;
  32193. + nt->table = sqliteStrDup(pTableName->a[0].zName);
  32194. + if( sqlite_malloc_failed ) goto trigger_cleanup;
  32195. + nt->iDb = iDb;
  32196. + nt->iTabDb = tab->iDb;
  32197. + nt->op = op;
  32198. + nt->tr_tm = tr_tm;
  32199. + nt->pWhen = sqliteExprDup(pWhen);
  32200. + nt->pColumns = sqliteIdListDup(pColumns);
  32201. + nt->foreach = foreach;
  32202. + sqliteTokenCopy(&nt->nameToken,pName);
  32203. + assert( pParse->pNewTrigger==0 );
  32204. + pParse->pNewTrigger = nt;
  32205. +
  32206. +trigger_cleanup:
  32207. + sqliteFree(zName);
  32208. + sqliteSrcListDelete(pTableName);
  32209. + sqliteIdListDelete(pColumns);
  32210. + sqliteExprDelete(pWhen);
  32211. +}
  32212. +
  32213. +/*
  32214. +** This routine is called after all of the trigger actions have been parsed
  32215. +** in order to complete the process of building the trigger.
  32216. +*/
  32217. +void sqliteFinishTrigger(
  32218. + Parse *pParse, /* Parser context */
  32219. + TriggerStep *pStepList, /* The triggered program */
  32220. + Token *pAll /* Token that describes the complete CREATE TRIGGER */
  32221. +){
  32222. + Trigger *nt = 0; /* The trigger whose construction is finishing up */
  32223. + sqlite *db = pParse->db; /* The database */
  32224. + DbFixer sFix;
  32225. +
  32226. + if( pParse->nErr || pParse->pNewTrigger==0 ) goto triggerfinish_cleanup;
  32227. + nt = pParse->pNewTrigger;
  32228. + pParse->pNewTrigger = 0;
  32229. + nt->step_list = pStepList;
  32230. + while( pStepList ){
  32231. + pStepList->pTrig = nt;
  32232. + pStepList = pStepList->pNext;
  32233. + }
  32234. + if( sqliteFixInit(&sFix, pParse, nt->iDb, "trigger", &nt->nameToken)
  32235. + && sqliteFixTriggerStep(&sFix, nt->step_list) ){
  32236. + goto triggerfinish_cleanup;
  32237. + }
  32238. +
  32239. + /* if we are not initializing, and this trigger is not on a TEMP table,
  32240. + ** build the sqlite_master entry
  32241. + */
  32242. + if( !db->init.busy ){
  32243. + static VdbeOpList insertTrig[] = {
  32244. + { OP_NewRecno, 0, 0, 0 },
  32245. + { OP_String, 0, 0, "trigger" },
  32246. + { OP_String, 0, 0, 0 }, /* 2: trigger name */
  32247. + { OP_String, 0, 0, 0 }, /* 3: table name */
  32248. + { OP_Integer, 0, 0, 0 },
  32249. + { OP_String, 0, 0, 0 }, /* 5: SQL */
  32250. + { OP_MakeRecord, 5, 0, 0 },
  32251. + { OP_PutIntKey, 0, 0, 0 },
  32252. + };
  32253. + int addr;
  32254. + Vdbe *v;
  32255. +
  32256. + /* Make an entry in the sqlite_master table */
  32257. + v = sqliteGetVdbe(pParse);
  32258. + if( v==0 ) goto triggerfinish_cleanup;
  32259. + sqliteBeginWriteOperation(pParse, 0, 0);
  32260. + sqliteOpenMasterTable(v, nt->iDb);
  32261. + addr = sqliteVdbeAddOpList(v, ArraySize(insertTrig), insertTrig);
  32262. + sqliteVdbeChangeP3(v, addr+2, nt->name, 0);
  32263. + sqliteVdbeChangeP3(v, addr+3, nt->table, 0);
  32264. + sqliteVdbeChangeP3(v, addr+5, pAll->z, pAll->n);
  32265. + if( nt->iDb==0 ){
  32266. + sqliteChangeCookie(db, v);
  32267. + }
  32268. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  32269. + sqliteEndWriteOperation(pParse);
  32270. + }
  32271. +
  32272. + if( !pParse->explain ){
  32273. + Table *pTab;
  32274. + sqliteHashInsert(&db->aDb[nt->iDb].trigHash,
  32275. + nt->name, strlen(nt->name)+1, nt);
  32276. + pTab = sqliteLocateTable(pParse, nt->table, db->aDb[nt->iTabDb].zName);
  32277. + assert( pTab!=0 );
  32278. + nt->pNext = pTab->pTrigger;
  32279. + pTab->pTrigger = nt;
  32280. + nt = 0;
  32281. + }
  32282. +
  32283. +triggerfinish_cleanup:
  32284. + sqliteDeleteTrigger(nt);
  32285. + sqliteDeleteTrigger(pParse->pNewTrigger);
  32286. + pParse->pNewTrigger = 0;
  32287. + sqliteDeleteTriggerStep(pStepList);
  32288. +}
  32289. +
  32290. +/*
  32291. +** Make a copy of all components of the given trigger step. This has
  32292. +** the effect of copying all Expr.token.z values into memory obtained
  32293. +** from sqliteMalloc(). As initially created, the Expr.token.z values
  32294. +** all point to the input string that was fed to the parser. But that
  32295. +** string is ephemeral - it will go away as soon as the sqlite_exec()
  32296. +** call that started the parser exits. This routine makes a persistent
  32297. +** copy of all the Expr.token.z strings so that the TriggerStep structure
  32298. +** will be valid even after the sqlite_exec() call returns.
  32299. +*/
  32300. +static void sqlitePersistTriggerStep(TriggerStep *p){
  32301. + if( p->target.z ){
  32302. + p->target.z = sqliteStrNDup(p->target.z, p->target.n);
  32303. + p->target.dyn = 1;
  32304. + }
  32305. + if( p->pSelect ){
  32306. + Select *pNew = sqliteSelectDup(p->pSelect);
  32307. + sqliteSelectDelete(p->pSelect);
  32308. + p->pSelect = pNew;
  32309. + }
  32310. + if( p->pWhere ){
  32311. + Expr *pNew = sqliteExprDup(p->pWhere);
  32312. + sqliteExprDelete(p->pWhere);
  32313. + p->pWhere = pNew;
  32314. + }
  32315. + if( p->pExprList ){
  32316. + ExprList *pNew = sqliteExprListDup(p->pExprList);
  32317. + sqliteExprListDelete(p->pExprList);
  32318. + p->pExprList = pNew;
  32319. + }
  32320. + if( p->pIdList ){
  32321. + IdList *pNew = sqliteIdListDup(p->pIdList);
  32322. + sqliteIdListDelete(p->pIdList);
  32323. + p->pIdList = pNew;
  32324. + }
  32325. +}
  32326. +
  32327. +/*
  32328. +** Turn a SELECT statement (that the pSelect parameter points to) into
  32329. +** a trigger step. Return a pointer to a TriggerStep structure.
  32330. +**
  32331. +** The parser calls this routine when it finds a SELECT statement in
  32332. +** body of a TRIGGER.
  32333. +*/
  32334. +TriggerStep *sqliteTriggerSelectStep(Select *pSelect){
  32335. + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  32336. + if( pTriggerStep==0 ) return 0;
  32337. +
  32338. + pTriggerStep->op = TK_SELECT;
  32339. + pTriggerStep->pSelect = pSelect;
  32340. + pTriggerStep->orconf = OE_Default;
  32341. + sqlitePersistTriggerStep(pTriggerStep);
  32342. +
  32343. + return pTriggerStep;
  32344. +}
  32345. +
  32346. +/*
  32347. +** Build a trigger step out of an INSERT statement. Return a pointer
  32348. +** to the new trigger step.
  32349. +**
  32350. +** The parser calls this routine when it sees an INSERT inside the
  32351. +** body of a trigger.
  32352. +*/
  32353. +TriggerStep *sqliteTriggerInsertStep(
  32354. + Token *pTableName, /* Name of the table into which we insert */
  32355. + IdList *pColumn, /* List of columns in pTableName to insert into */
  32356. + ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
  32357. + Select *pSelect, /* A SELECT statement that supplies values */
  32358. + int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  32359. +){
  32360. + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  32361. + if( pTriggerStep==0 ) return 0;
  32362. +
  32363. + assert(pEList == 0 || pSelect == 0);
  32364. + assert(pEList != 0 || pSelect != 0);
  32365. +
  32366. + pTriggerStep->op = TK_INSERT;
  32367. + pTriggerStep->pSelect = pSelect;
  32368. + pTriggerStep->target = *pTableName;
  32369. + pTriggerStep->pIdList = pColumn;
  32370. + pTriggerStep->pExprList = pEList;
  32371. + pTriggerStep->orconf = orconf;
  32372. + sqlitePersistTriggerStep(pTriggerStep);
  32373. +
  32374. + return pTriggerStep;
  32375. +}
  32376. +
  32377. +/*
  32378. +** Construct a trigger step that implements an UPDATE statement and return
  32379. +** a pointer to that trigger step. The parser calls this routine when it
  32380. +** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  32381. +*/
  32382. +TriggerStep *sqliteTriggerUpdateStep(
  32383. + Token *pTableName, /* Name of the table to be updated */
  32384. + ExprList *pEList, /* The SET clause: list of column and new values */
  32385. + Expr *pWhere, /* The WHERE clause */
  32386. + int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  32387. +){
  32388. + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  32389. + if( pTriggerStep==0 ) return 0;
  32390. +
  32391. + pTriggerStep->op = TK_UPDATE;
  32392. + pTriggerStep->target = *pTableName;
  32393. + pTriggerStep->pExprList = pEList;
  32394. + pTriggerStep->pWhere = pWhere;
  32395. + pTriggerStep->orconf = orconf;
  32396. + sqlitePersistTriggerStep(pTriggerStep);
  32397. +
  32398. + return pTriggerStep;
  32399. +}
  32400. +
  32401. +/*
  32402. +** Construct a trigger step that implements a DELETE statement and return
  32403. +** a pointer to that trigger step. The parser calls this routine when it
  32404. +** sees a DELETE statement inside the body of a CREATE TRIGGER.
  32405. +*/
  32406. +TriggerStep *sqliteTriggerDeleteStep(Token *pTableName, Expr *pWhere){
  32407. + TriggerStep *pTriggerStep = sqliteMalloc(sizeof(TriggerStep));
  32408. + if( pTriggerStep==0 ) return 0;
  32409. +
  32410. + pTriggerStep->op = TK_DELETE;
  32411. + pTriggerStep->target = *pTableName;
  32412. + pTriggerStep->pWhere = pWhere;
  32413. + pTriggerStep->orconf = OE_Default;
  32414. + sqlitePersistTriggerStep(pTriggerStep);
  32415. +
  32416. + return pTriggerStep;
  32417. +}
  32418. +
  32419. +/*
  32420. +** Recursively delete a Trigger structure
  32421. +*/
  32422. +void sqliteDeleteTrigger(Trigger *pTrigger){
  32423. + if( pTrigger==0 ) return;
  32424. + sqliteDeleteTriggerStep(pTrigger->step_list);
  32425. + sqliteFree(pTrigger->name);
  32426. + sqliteFree(pTrigger->table);
  32427. + sqliteExprDelete(pTrigger->pWhen);
  32428. + sqliteIdListDelete(pTrigger->pColumns);
  32429. + if( pTrigger->nameToken.dyn ) sqliteFree((char*)pTrigger->nameToken.z);
  32430. + sqliteFree(pTrigger);
  32431. +}
  32432. +
  32433. +/*
  32434. + * This function is called to drop a trigger from the database schema.
  32435. + *
  32436. + * This may be called directly from the parser and therefore identifies
  32437. + * the trigger by name. The sqliteDropTriggerPtr() routine does the
  32438. + * same job as this routine except it take a spointer to the trigger
  32439. + * instead of the trigger name.
  32440. + *
  32441. + * Note that this function does not delete the trigger entirely. Instead it
  32442. + * removes it from the internal schema and places it in the trigDrop hash
  32443. + * table. This is so that the trigger can be restored into the database schema
  32444. + * if the transaction is rolled back.
  32445. + */
  32446. +void sqliteDropTrigger(Parse *pParse, SrcList *pName){
  32447. + Trigger *pTrigger;
  32448. + int i;
  32449. + const char *zDb;
  32450. + const char *zName;
  32451. + int nName;
  32452. + sqlite *db = pParse->db;
  32453. +
  32454. + if( sqlite_malloc_failed ) goto drop_trigger_cleanup;
  32455. + assert( pName->nSrc==1 );
  32456. + zDb = pName->a[0].zDatabase;
  32457. + zName = pName->a[0].zName;
  32458. + nName = strlen(zName);
  32459. + for(i=0; i<db->nDb; i++){
  32460. + int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  32461. + if( zDb && sqliteStrICmp(db->aDb[j].zName, zDb) ) continue;
  32462. + pTrigger = sqliteHashFind(&(db->aDb[j].trigHash), zName, nName+1);
  32463. + if( pTrigger ) break;
  32464. + }
  32465. + if( !pTrigger ){
  32466. + sqliteErrorMsg(pParse, "no such trigger: %S", pName, 0);
  32467. + goto drop_trigger_cleanup;
  32468. + }
  32469. + sqliteDropTriggerPtr(pParse, pTrigger, 0);
  32470. +
  32471. +drop_trigger_cleanup:
  32472. + sqliteSrcListDelete(pName);
  32473. +}
  32474. +
  32475. +/*
  32476. +** Drop a trigger given a pointer to that trigger. If nested is false,
  32477. +** then also generate code to remove the trigger from the SQLITE_MASTER
  32478. +** table.
  32479. +*/
  32480. +void sqliteDropTriggerPtr(Parse *pParse, Trigger *pTrigger, int nested){
  32481. + Table *pTable;
  32482. + Vdbe *v;
  32483. + sqlite *db = pParse->db;
  32484. +
  32485. + assert( pTrigger->iDb<db->nDb );
  32486. + if( pTrigger->iDb>=2 ){
  32487. + sqliteErrorMsg(pParse, "triggers may not be removed from "
  32488. + "auxiliary database %s", db->aDb[pTrigger->iDb].zName);
  32489. + return;
  32490. + }
  32491. + pTable = sqliteFindTable(db, pTrigger->table,db->aDb[pTrigger->iTabDb].zName);
  32492. + assert(pTable);
  32493. + assert( pTable->iDb==pTrigger->iDb || pTrigger->iDb==1 );
  32494. +#ifndef SQLITE_OMIT_AUTHORIZATION
  32495. + {
  32496. + int code = SQLITE_DROP_TRIGGER;
  32497. + const char *zDb = db->aDb[pTrigger->iDb].zName;
  32498. + const char *zTab = SCHEMA_TABLE(pTrigger->iDb);
  32499. + if( pTrigger->iDb ) code = SQLITE_DROP_TEMP_TRIGGER;
  32500. + if( sqliteAuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
  32501. + sqliteAuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  32502. + return;
  32503. + }
  32504. + }
  32505. +#endif
  32506. +
  32507. + /* Generate code to destroy the database record of the trigger.
  32508. + */
  32509. + if( pTable!=0 && !nested && (v = sqliteGetVdbe(pParse))!=0 ){
  32510. + int base;
  32511. + static VdbeOpList dropTrigger[] = {
  32512. + { OP_Rewind, 0, ADDR(9), 0},
  32513. + { OP_String, 0, 0, 0}, /* 1 */
  32514. + { OP_Column, 0, 1, 0},
  32515. + { OP_Ne, 0, ADDR(8), 0},
  32516. + { OP_String, 0, 0, "trigger"},
  32517. + { OP_Column, 0, 0, 0},
  32518. + { OP_Ne, 0, ADDR(8), 0},
  32519. + { OP_Delete, 0, 0, 0},
  32520. + { OP_Next, 0, ADDR(1), 0}, /* 8 */
  32521. + };
  32522. +
  32523. + sqliteBeginWriteOperation(pParse, 0, 0);
  32524. + sqliteOpenMasterTable(v, pTrigger->iDb);
  32525. + base = sqliteVdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
  32526. + sqliteVdbeChangeP3(v, base+1, pTrigger->name, 0);
  32527. + if( pTrigger->iDb==0 ){
  32528. + sqliteChangeCookie(db, v);
  32529. + }
  32530. + sqliteVdbeAddOp(v, OP_Close, 0, 0);
  32531. + sqliteEndWriteOperation(pParse);
  32532. + }
  32533. +
  32534. + /*
  32535. + * If this is not an "explain", then delete the trigger structure.
  32536. + */
  32537. + if( !pParse->explain ){
  32538. + const char *zName = pTrigger->name;
  32539. + int nName = strlen(zName);
  32540. + if( pTable->pTrigger == pTrigger ){
  32541. + pTable->pTrigger = pTrigger->pNext;
  32542. + }else{
  32543. + Trigger *cc = pTable->pTrigger;
  32544. + while( cc ){
  32545. + if( cc->pNext == pTrigger ){
  32546. + cc->pNext = cc->pNext->pNext;
  32547. + break;
  32548. + }
  32549. + cc = cc->pNext;
  32550. + }
  32551. + assert(cc);
  32552. + }
  32553. + sqliteHashInsert(&(db->aDb[pTrigger->iDb].trigHash), zName, nName+1, 0);
  32554. + sqliteDeleteTrigger(pTrigger);
  32555. + }
  32556. +}
  32557. +
  32558. +/*
  32559. +** pEList is the SET clause of an UPDATE statement. Each entry
  32560. +** in pEList is of the format <id>=<expr>. If any of the entries
  32561. +** in pEList have an <id> which matches an identifier in pIdList,
  32562. +** then return TRUE. If pIdList==NULL, then it is considered a
  32563. +** wildcard that matches anything. Likewise if pEList==NULL then
  32564. +** it matches anything so always return true. Return false only
  32565. +** if there is no match.
  32566. +*/
  32567. +static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
  32568. + int e;
  32569. + if( !pIdList || !pEList ) return 1;
  32570. + for(e=0; e<pEList->nExpr; e++){
  32571. + if( sqliteIdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  32572. + }
  32573. + return 0;
  32574. +}
  32575. +
  32576. +/* A global variable that is TRUE if we should always set up temp tables for
  32577. + * for triggers, even if there are no triggers to code. This is used to test
  32578. + * how much overhead the triggers algorithm is causing.
  32579. + *
  32580. + * This flag can be set or cleared using the "trigger_overhead_test" pragma.
  32581. + * The pragma is not documented since it is not really part of the interface
  32582. + * to SQLite, just the test procedure.
  32583. +*/
  32584. +int always_code_trigger_setup = 0;
  32585. +
  32586. +/*
  32587. + * Returns true if a trigger matching op, tr_tm and foreach that is NOT already
  32588. + * on the Parse objects trigger-stack (to prevent recursive trigger firing) is
  32589. + * found in the list specified as pTrigger.
  32590. + */
  32591. +int sqliteTriggersExist(
  32592. + Parse *pParse, /* Used to check for recursive triggers */
  32593. + Trigger *pTrigger, /* A list of triggers associated with a table */
  32594. + int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  32595. + int tr_tm, /* one of TK_BEFORE, TK_AFTER */
  32596. + int foreach, /* one of TK_ROW or TK_STATEMENT */
  32597. + ExprList *pChanges /* Columns that change in an UPDATE statement */
  32598. +){
  32599. + Trigger * pTriggerCursor;
  32600. +
  32601. + if( always_code_trigger_setup ){
  32602. + return 1;
  32603. + }
  32604. +
  32605. + pTriggerCursor = pTrigger;
  32606. + while( pTriggerCursor ){
  32607. + if( pTriggerCursor->op == op &&
  32608. + pTriggerCursor->tr_tm == tr_tm &&
  32609. + pTriggerCursor->foreach == foreach &&
  32610. + checkColumnOverLap(pTriggerCursor->pColumns, pChanges) ){
  32611. + TriggerStack * ss;
  32612. + ss = pParse->trigStack;
  32613. + while( ss && ss->pTrigger != pTrigger ){
  32614. + ss = ss->pNext;
  32615. + }
  32616. + if( !ss )return 1;
  32617. + }
  32618. + pTriggerCursor = pTriggerCursor->pNext;
  32619. + }
  32620. +
  32621. + return 0;
  32622. +}
  32623. +
  32624. +/*
  32625. +** Convert the pStep->target token into a SrcList and return a pointer
  32626. +** to that SrcList.
  32627. +**
  32628. +** This routine adds a specific database name, if needed, to the target when
  32629. +** forming the SrcList. This prevents a trigger in one database from
  32630. +** referring to a target in another database. An exception is when the
  32631. +** trigger is in TEMP in which case it can refer to any other database it
  32632. +** wants.
  32633. +*/
  32634. +static SrcList *targetSrcList(
  32635. + Parse *pParse, /* The parsing context */
  32636. + TriggerStep *pStep /* The trigger containing the target token */
  32637. +){
  32638. + Token sDb; /* Dummy database name token */
  32639. + int iDb; /* Index of the database to use */
  32640. + SrcList *pSrc; /* SrcList to be returned */
  32641. +
  32642. + iDb = pStep->pTrig->iDb;
  32643. + if( iDb==0 || iDb>=2 ){
  32644. + assert( iDb<pParse->db->nDb );
  32645. + sDb.z = pParse->db->aDb[iDb].zName;
  32646. + sDb.n = strlen(sDb.z);
  32647. + pSrc = sqliteSrcListAppend(0, &sDb, &pStep->target);
  32648. + } else {
  32649. + pSrc = sqliteSrcListAppend(0, &pStep->target, 0);
  32650. + }
  32651. + return pSrc;
  32652. +}
  32653. +
  32654. +/*
  32655. +** Generate VDBE code for zero or more statements inside the body of a
  32656. +** trigger.
  32657. +*/
  32658. +static int codeTriggerProgram(
  32659. + Parse *pParse, /* The parser context */
  32660. + TriggerStep *pStepList, /* List of statements inside the trigger body */
  32661. + int orconfin /* Conflict algorithm. (OE_Abort, etc) */
  32662. +){
  32663. + TriggerStep * pTriggerStep = pStepList;
  32664. + int orconf;
  32665. +
  32666. + while( pTriggerStep ){
  32667. + int saveNTab = pParse->nTab;
  32668. +
  32669. + orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
  32670. + pParse->trigStack->orconf = orconf;
  32671. + switch( pTriggerStep->op ){
  32672. + case TK_SELECT: {
  32673. + Select * ss = sqliteSelectDup(pTriggerStep->pSelect);
  32674. + assert(ss);
  32675. + assert(ss->pSrc);
  32676. + sqliteSelect(pParse, ss, SRT_Discard, 0, 0, 0, 0);
  32677. + sqliteSelectDelete(ss);
  32678. + break;
  32679. + }
  32680. + case TK_UPDATE: {
  32681. + SrcList *pSrc;
  32682. + pSrc = targetSrcList(pParse, pTriggerStep);
  32683. + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
  32684. + sqliteUpdate(pParse, pSrc,
  32685. + sqliteExprListDup(pTriggerStep->pExprList),
  32686. + sqliteExprDup(pTriggerStep->pWhere), orconf);
  32687. + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
  32688. + break;
  32689. + }
  32690. + case TK_INSERT: {
  32691. + SrcList *pSrc;
  32692. + pSrc = targetSrcList(pParse, pTriggerStep);
  32693. + sqliteInsert(pParse, pSrc,
  32694. + sqliteExprListDup(pTriggerStep->pExprList),
  32695. + sqliteSelectDup(pTriggerStep->pSelect),
  32696. + sqliteIdListDup(pTriggerStep->pIdList), orconf);
  32697. + break;
  32698. + }
  32699. + case TK_DELETE: {
  32700. + SrcList *pSrc;
  32701. + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPush, 0, 0);
  32702. + pSrc = targetSrcList(pParse, pTriggerStep);
  32703. + sqliteDeleteFrom(pParse, pSrc, sqliteExprDup(pTriggerStep->pWhere));
  32704. + sqliteVdbeAddOp(pParse->pVdbe, OP_ListPop, 0, 0);
  32705. + break;
  32706. + }
  32707. + default:
  32708. + assert(0);
  32709. + }
  32710. + pParse->nTab = saveNTab;
  32711. + pTriggerStep = pTriggerStep->pNext;
  32712. + }
  32713. +
  32714. + return 0;
  32715. +}
  32716. +
  32717. +/*
  32718. +** This is called to code FOR EACH ROW triggers.
  32719. +**
  32720. +** When the code that this function generates is executed, the following
  32721. +** must be true:
  32722. +**
  32723. +** 1. No cursors may be open in the main database. (But newIdx and oldIdx
  32724. +** can be indices of cursors in temporary tables. See below.)
  32725. +**
  32726. +** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
  32727. +** a temporary vdbe cursor (index newIdx) must be open and pointing at
  32728. +** a row containing values to be substituted for new.* expressions in the
  32729. +** trigger program(s).
  32730. +**
  32731. +** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
  32732. +** a temporary vdbe cursor (index oldIdx) must be open and pointing at
  32733. +** a row containing values to be substituted for old.* expressions in the
  32734. +** trigger program(s).
  32735. +**
  32736. +*/
  32737. +int sqliteCodeRowTrigger(
  32738. + Parse *pParse, /* Parse context */
  32739. + int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  32740. + ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  32741. + int tr_tm, /* One of TK_BEFORE, TK_AFTER */
  32742. + Table *pTab, /* The table to code triggers from */
  32743. + int newIdx, /* The indice of the "new" row to access */
  32744. + int oldIdx, /* The indice of the "old" row to access */
  32745. + int orconf, /* ON CONFLICT policy */
  32746. + int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  32747. +){
  32748. + Trigger * pTrigger;
  32749. + TriggerStack * pTriggerStack;
  32750. +
  32751. + assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
  32752. + assert(tr_tm == TK_BEFORE || tr_tm == TK_AFTER );
  32753. +
  32754. + assert(newIdx != -1 || oldIdx != -1);
  32755. +
  32756. + pTrigger = pTab->pTrigger;
  32757. + while( pTrigger ){
  32758. + int fire_this = 0;
  32759. +
  32760. + /* determine whether we should code this trigger */
  32761. + if( pTrigger->op == op && pTrigger->tr_tm == tr_tm &&
  32762. + pTrigger->foreach == TK_ROW ){
  32763. + fire_this = 1;
  32764. + pTriggerStack = pParse->trigStack;
  32765. + while( pTriggerStack ){
  32766. + if( pTriggerStack->pTrigger == pTrigger ){
  32767. + fire_this = 0;
  32768. + }
  32769. + pTriggerStack = pTriggerStack->pNext;
  32770. + }
  32771. + if( op == TK_UPDATE && pTrigger->pColumns &&
  32772. + !checkColumnOverLap(pTrigger->pColumns, pChanges) ){
  32773. + fire_this = 0;
  32774. + }
  32775. + }
  32776. +
  32777. + if( fire_this && (pTriggerStack = sqliteMalloc(sizeof(TriggerStack)))!=0 ){
  32778. + int endTrigger;
  32779. + SrcList dummyTablist;
  32780. + Expr * whenExpr;
  32781. + AuthContext sContext;
  32782. +
  32783. + dummyTablist.nSrc = 0;
  32784. +
  32785. + /* Push an entry on to the trigger stack */
  32786. + pTriggerStack->pTrigger = pTrigger;
  32787. + pTriggerStack->newIdx = newIdx;
  32788. + pTriggerStack->oldIdx = oldIdx;
  32789. + pTriggerStack->pTab = pTab;
  32790. + pTriggerStack->pNext = pParse->trigStack;
  32791. + pTriggerStack->ignoreJump = ignoreJump;
  32792. + pParse->trigStack = pTriggerStack;
  32793. + sqliteAuthContextPush(pParse, &sContext, pTrigger->name);
  32794. +
  32795. + /* code the WHEN clause */
  32796. + endTrigger = sqliteVdbeMakeLabel(pParse->pVdbe);
  32797. + whenExpr = sqliteExprDup(pTrigger->pWhen);
  32798. + if( sqliteExprResolveIds(pParse, &dummyTablist, 0, whenExpr) ){
  32799. + pParse->trigStack = pParse->trigStack->pNext;
  32800. + sqliteFree(pTriggerStack);
  32801. + sqliteExprDelete(whenExpr);
  32802. + return 1;
  32803. + }
  32804. + sqliteExprIfFalse(pParse, whenExpr, endTrigger, 1);
  32805. + sqliteExprDelete(whenExpr);
  32806. +
  32807. + sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPush, 0, 0);
  32808. + codeTriggerProgram(pParse, pTrigger->step_list, orconf);
  32809. + sqliteVdbeAddOp(pParse->pVdbe, OP_ContextPop, 0, 0);
  32810. +
  32811. + /* Pop the entry off the trigger stack */
  32812. + pParse->trigStack = pParse->trigStack->pNext;
  32813. + sqliteAuthContextPop(&sContext);
  32814. + sqliteFree(pTriggerStack);
  32815. +
  32816. + sqliteVdbeResolveLabel(pParse->pVdbe, endTrigger);
  32817. + }
  32818. + pTrigger = pTrigger->pNext;
  32819. + }
  32820. +
  32821. + return 0;
  32822. +}
  32823. --- /dev/null
  32824. +++ b/ext/sqlite/libsqlite/src/update.c
  32825. @@ -0,0 +1,459 @@
  32826. +/*
  32827. +** 2001 September 15
  32828. +**
  32829. +** The author disclaims copyright to this source code. In place of
  32830. +** a legal notice, here is a blessing:
  32831. +**
  32832. +** May you do good and not evil.
  32833. +** May you find forgiveness for yourself and forgive others.
  32834. +** May you share freely, never taking more than you give.
  32835. +**
  32836. +*************************************************************************
  32837. +** This file contains C code routines that are called by the parser
  32838. +** to handle UPDATE statements.
  32839. +**
  32840. +** $Id$
  32841. +*/
  32842. +#include "sqliteInt.h"
  32843. +
  32844. +/*
  32845. +** Process an UPDATE statement.
  32846. +**
  32847. +** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  32848. +** \_______/ \________/ \______/ \________________/
  32849. +* onError pTabList pChanges pWhere
  32850. +*/
  32851. +void sqliteUpdate(
  32852. + Parse *pParse, /* The parser context */
  32853. + SrcList *pTabList, /* The table in which we should change things */
  32854. + ExprList *pChanges, /* Things to be changed */
  32855. + Expr *pWhere, /* The WHERE clause. May be null */
  32856. + int onError /* How to handle constraint errors */
  32857. +){
  32858. + int i, j; /* Loop counters */
  32859. + Table *pTab; /* The table to be updated */
  32860. + int loopStart; /* VDBE instruction address of the start of the loop */
  32861. + int jumpInst; /* Addr of VDBE instruction to jump out of loop */
  32862. + WhereInfo *pWInfo; /* Information about the WHERE clause */
  32863. + Vdbe *v; /* The virtual database engine */
  32864. + Index *pIdx; /* For looping over indices */
  32865. + int nIdx; /* Number of indices that need updating */
  32866. + int nIdxTotal; /* Total number of indices */
  32867. + int iCur; /* VDBE Cursor number of pTab */
  32868. + sqlite *db; /* The database structure */
  32869. + Index **apIdx = 0; /* An array of indices that need updating too */
  32870. + char *aIdxUsed = 0; /* aIdxUsed[i]==1 if the i-th index is used */
  32871. + int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  32872. + ** an expression for the i-th column of the table.
  32873. + ** aXRef[i]==-1 if the i-th column is not changed. */
  32874. + int chngRecno; /* True if the record number is being changed */
  32875. + Expr *pRecnoExpr; /* Expression defining the new record number */
  32876. + int openAll; /* True if all indices need to be opened */
  32877. + int isView; /* Trying to update a view */
  32878. + int iStackDepth; /* Index of memory cell holding stack depth */
  32879. + AuthContext sContext; /* The authorization context */
  32880. +
  32881. + int before_triggers; /* True if there are any BEFORE triggers */
  32882. + int after_triggers; /* True if there are any AFTER triggers */
  32883. + int row_triggers_exist = 0; /* True if any row triggers exist */
  32884. +
  32885. + int newIdx = -1; /* index of trigger "new" temp table */
  32886. + int oldIdx = -1; /* index of trigger "old" temp table */
  32887. +
  32888. + sContext.pParse = 0;
  32889. + if( pParse->nErr || sqlite_malloc_failed ) goto update_cleanup;
  32890. + db = pParse->db;
  32891. + assert( pTabList->nSrc==1 );
  32892. + iStackDepth = pParse->nMem++;
  32893. +
  32894. + /* Locate the table which we want to update.
  32895. + */
  32896. + pTab = sqliteSrcListLookup(pParse, pTabList);
  32897. + if( pTab==0 ) goto update_cleanup;
  32898. + before_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
  32899. + TK_UPDATE, TK_BEFORE, TK_ROW, pChanges);
  32900. + after_triggers = sqliteTriggersExist(pParse, pTab->pTrigger,
  32901. + TK_UPDATE, TK_AFTER, TK_ROW, pChanges);
  32902. + row_triggers_exist = before_triggers || after_triggers;
  32903. + isView = pTab->pSelect!=0;
  32904. + if( sqliteIsReadOnly(pParse, pTab, before_triggers) ){
  32905. + goto update_cleanup;
  32906. + }
  32907. + if( isView ){
  32908. + if( sqliteViewGetColumnNames(pParse, pTab) ){
  32909. + goto update_cleanup;
  32910. + }
  32911. + }
  32912. + aXRef = sqliteMalloc( sizeof(int) * pTab->nCol );
  32913. + if( aXRef==0 ) goto update_cleanup;
  32914. + for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  32915. +
  32916. + /* If there are FOR EACH ROW triggers, allocate cursors for the
  32917. + ** special OLD and NEW tables
  32918. + */
  32919. + if( row_triggers_exist ){
  32920. + newIdx = pParse->nTab++;
  32921. + oldIdx = pParse->nTab++;
  32922. + }
  32923. +
  32924. + /* Allocate a cursors for the main database table and for all indices.
  32925. + ** The index cursors might not be used, but if they are used they
  32926. + ** need to occur right after the database cursor. So go ahead and
  32927. + ** allocate enough space, just in case.
  32928. + */
  32929. + pTabList->a[0].iCursor = iCur = pParse->nTab++;
  32930. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  32931. + pParse->nTab++;
  32932. + }
  32933. +
  32934. + /* Resolve the column names in all the expressions of the
  32935. + ** of the UPDATE statement. Also find the column index
  32936. + ** for each column to be updated in the pChanges array. For each
  32937. + ** column to be updated, make sure we have authorization to change
  32938. + ** that column.
  32939. + */
  32940. + chngRecno = 0;
  32941. + for(i=0; i<pChanges->nExpr; i++){
  32942. + if( sqliteExprResolveIds(pParse, pTabList, 0, pChanges->a[i].pExpr) ){
  32943. + goto update_cleanup;
  32944. + }
  32945. + if( sqliteExprCheck(pParse, pChanges->a[i].pExpr, 0, 0) ){
  32946. + goto update_cleanup;
  32947. + }
  32948. + for(j=0; j<pTab->nCol; j++){
  32949. + if( sqliteStrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  32950. + if( j==pTab->iPKey ){
  32951. + chngRecno = 1;
  32952. + pRecnoExpr = pChanges->a[i].pExpr;
  32953. + }
  32954. + aXRef[j] = i;
  32955. + break;
  32956. + }
  32957. + }
  32958. + if( j>=pTab->nCol ){
  32959. + if( sqliteIsRowid(pChanges->a[i].zName) ){
  32960. + chngRecno = 1;
  32961. + pRecnoExpr = pChanges->a[i].pExpr;
  32962. + }else{
  32963. + sqliteErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  32964. + goto update_cleanup;
  32965. + }
  32966. + }
  32967. +#ifndef SQLITE_OMIT_AUTHORIZATION
  32968. + {
  32969. + int rc;
  32970. + rc = sqliteAuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  32971. + pTab->aCol[j].zName, db->aDb[pTab->iDb].zName);
  32972. + if( rc==SQLITE_DENY ){
  32973. + goto update_cleanup;
  32974. + }else if( rc==SQLITE_IGNORE ){
  32975. + aXRef[j] = -1;
  32976. + }
  32977. + }
  32978. +#endif
  32979. + }
  32980. +
  32981. + /* Allocate memory for the array apIdx[] and fill it with pointers to every
  32982. + ** index that needs to be updated. Indices only need updating if their
  32983. + ** key includes one of the columns named in pChanges or if the record
  32984. + ** number of the original table entry is changing.
  32985. + */
  32986. + for(nIdx=nIdxTotal=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdxTotal++){
  32987. + if( chngRecno ){
  32988. + i = 0;
  32989. + }else {
  32990. + for(i=0; i<pIdx->nColumn; i++){
  32991. + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
  32992. + }
  32993. + }
  32994. + if( i<pIdx->nColumn ) nIdx++;
  32995. + }
  32996. + if( nIdxTotal>0 ){
  32997. + apIdx = sqliteMalloc( sizeof(Index*) * nIdx + nIdxTotal );
  32998. + if( apIdx==0 ) goto update_cleanup;
  32999. + aIdxUsed = (char*)&apIdx[nIdx];
  33000. + }
  33001. + for(nIdx=j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  33002. + if( chngRecno ){
  33003. + i = 0;
  33004. + }else{
  33005. + for(i=0; i<pIdx->nColumn; i++){
  33006. + if( aXRef[pIdx->aiColumn[i]]>=0 ) break;
  33007. + }
  33008. + }
  33009. + if( i<pIdx->nColumn ){
  33010. + apIdx[nIdx++] = pIdx;
  33011. + aIdxUsed[j] = 1;
  33012. + }else{
  33013. + aIdxUsed[j] = 0;
  33014. + }
  33015. + }
  33016. +
  33017. + /* Resolve the column names in all the expressions in the
  33018. + ** WHERE clause.
  33019. + */
  33020. + if( pWhere ){
  33021. + if( sqliteExprResolveIds(pParse, pTabList, 0, pWhere) ){
  33022. + goto update_cleanup;
  33023. + }
  33024. + if( sqliteExprCheck(pParse, pWhere, 0, 0) ){
  33025. + goto update_cleanup;
  33026. + }
  33027. + }
  33028. +
  33029. + /* Start the view context
  33030. + */
  33031. + if( isView ){
  33032. + sqliteAuthContextPush(pParse, &sContext, pTab->zName);
  33033. + }
  33034. +
  33035. + /* Begin generating code.
  33036. + */
  33037. + v = sqliteGetVdbe(pParse);
  33038. + if( v==0 ) goto update_cleanup;
  33039. + sqliteBeginWriteOperation(pParse, 1, pTab->iDb);
  33040. +
  33041. + /* If we are trying to update a view, construct that view into
  33042. + ** a temporary table.
  33043. + */
  33044. + if( isView ){
  33045. + Select *pView;
  33046. + pView = sqliteSelectDup(pTab->pSelect);
  33047. + sqliteSelect(pParse, pView, SRT_TempTable, iCur, 0, 0, 0);
  33048. + sqliteSelectDelete(pView);
  33049. + }
  33050. +
  33051. + /* Begin the database scan
  33052. + */
  33053. + pWInfo = sqliteWhereBegin(pParse, pTabList, pWhere, 1, 0);
  33054. + if( pWInfo==0 ) goto update_cleanup;
  33055. +
  33056. + /* Remember the index of every item to be updated.
  33057. + */
  33058. + sqliteVdbeAddOp(v, OP_ListWrite, 0, 0);
  33059. +
  33060. + /* End the database scan loop.
  33061. + */
  33062. + sqliteWhereEnd(pWInfo);
  33063. +
  33064. + /* Initialize the count of updated rows
  33065. + */
  33066. + if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
  33067. + sqliteVdbeAddOp(v, OP_Integer, 0, 0);
  33068. + }
  33069. +
  33070. + if( row_triggers_exist ){
  33071. + /* Create pseudo-tables for NEW and OLD
  33072. + */
  33073. + sqliteVdbeAddOp(v, OP_OpenPseudo, oldIdx, 0);
  33074. + sqliteVdbeAddOp(v, OP_OpenPseudo, newIdx, 0);
  33075. +
  33076. + /* The top of the update loop for when there are triggers.
  33077. + */
  33078. + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
  33079. + sqliteVdbeAddOp(v, OP_StackDepth, 0, 0);
  33080. + sqliteVdbeAddOp(v, OP_MemStore, iStackDepth, 1);
  33081. + loopStart = sqliteVdbeAddOp(v, OP_MemLoad, iStackDepth, 0);
  33082. + sqliteVdbeAddOp(v, OP_StackReset, 0, 0);
  33083. + jumpInst = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
  33084. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  33085. +
  33086. + /* Open a cursor and make it point to the record that is
  33087. + ** being updated.
  33088. + */
  33089. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  33090. + if( !isView ){
  33091. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  33092. + sqliteVdbeAddOp(v, OP_OpenRead, iCur, pTab->tnum);
  33093. + }
  33094. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  33095. +
  33096. + /* Generate the OLD table
  33097. + */
  33098. + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
  33099. + sqliteVdbeAddOp(v, OP_RowData, iCur, 0);
  33100. + sqliteVdbeAddOp(v, OP_PutIntKey, oldIdx, 0);
  33101. +
  33102. + /* Generate the NEW table
  33103. + */
  33104. + if( chngRecno ){
  33105. + sqliteExprCode(pParse, pRecnoExpr);
  33106. + }else{
  33107. + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
  33108. + }
  33109. + for(i=0; i<pTab->nCol; i++){
  33110. + if( i==pTab->iPKey ){
  33111. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  33112. + continue;
  33113. + }
  33114. + j = aXRef[i];
  33115. + if( j<0 ){
  33116. + sqliteVdbeAddOp(v, OP_Column, iCur, i);
  33117. + }else{
  33118. + sqliteExprCode(pParse, pChanges->a[j].pExpr);
  33119. + }
  33120. + }
  33121. + sqliteVdbeAddOp(v, OP_MakeRecord, pTab->nCol, 0);
  33122. + sqliteVdbeAddOp(v, OP_PutIntKey, newIdx, 0);
  33123. + if( !isView ){
  33124. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  33125. + }
  33126. +
  33127. + /* Fire the BEFORE and INSTEAD OF triggers
  33128. + */
  33129. + if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_BEFORE, pTab,
  33130. + newIdx, oldIdx, onError, loopStart) ){
  33131. + goto update_cleanup;
  33132. + }
  33133. + }
  33134. +
  33135. + if( !isView ){
  33136. + /*
  33137. + ** Open every index that needs updating. Note that if any
  33138. + ** index could potentially invoke a REPLACE conflict resolution
  33139. + ** action, then we need to open all indices because we might need
  33140. + ** to be deleting some records.
  33141. + */
  33142. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  33143. + sqliteVdbeAddOp(v, OP_OpenWrite, iCur, pTab->tnum);
  33144. + if( onError==OE_Replace ){
  33145. + openAll = 1;
  33146. + }else{
  33147. + openAll = 0;
  33148. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  33149. + if( pIdx->onError==OE_Replace ){
  33150. + openAll = 1;
  33151. + break;
  33152. + }
  33153. + }
  33154. + }
  33155. + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  33156. + if( openAll || aIdxUsed[i] ){
  33157. + sqliteVdbeAddOp(v, OP_Integer, pIdx->iDb, 0);
  33158. + sqliteVdbeAddOp(v, OP_OpenWrite, iCur+i+1, pIdx->tnum);
  33159. + assert( pParse->nTab>iCur+i+1 );
  33160. + }
  33161. + }
  33162. +
  33163. + /* Loop over every record that needs updating. We have to load
  33164. + ** the old data for each record to be updated because some columns
  33165. + ** might not change and we will need to copy the old value.
  33166. + ** Also, the old data is needed to delete the old index entires.
  33167. + ** So make the cursor point at the old record.
  33168. + */
  33169. + if( !row_triggers_exist ){
  33170. + sqliteVdbeAddOp(v, OP_ListRewind, 0, 0);
  33171. + jumpInst = loopStart = sqliteVdbeAddOp(v, OP_ListRead, 0, 0);
  33172. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  33173. + }
  33174. + sqliteVdbeAddOp(v, OP_NotExists, iCur, loopStart);
  33175. +
  33176. + /* If the record number will change, push the record number as it
  33177. + ** will be after the update. (The old record number is currently
  33178. + ** on top of the stack.)
  33179. + */
  33180. + if( chngRecno ){
  33181. + sqliteExprCode(pParse, pRecnoExpr);
  33182. + sqliteVdbeAddOp(v, OP_MustBeInt, 0, 0);
  33183. + }
  33184. +
  33185. + /* Compute new data for this record.
  33186. + */
  33187. + for(i=0; i<pTab->nCol; i++){
  33188. + if( i==pTab->iPKey ){
  33189. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  33190. + continue;
  33191. + }
  33192. + j = aXRef[i];
  33193. + if( j<0 ){
  33194. + sqliteVdbeAddOp(v, OP_Column, iCur, i);
  33195. + }else{
  33196. + sqliteExprCode(pParse, pChanges->a[j].pExpr);
  33197. + }
  33198. + }
  33199. +
  33200. + /* Do constraint checks
  33201. + */
  33202. + sqliteGenerateConstraintChecks(pParse, pTab, iCur, aIdxUsed, chngRecno, 1,
  33203. + onError, loopStart);
  33204. +
  33205. + /* Delete the old indices for the current record.
  33206. + */
  33207. + sqliteGenerateRowIndexDelete(db, v, pTab, iCur, aIdxUsed);
  33208. +
  33209. + /* If changing the record number, delete the old record.
  33210. + */
  33211. + if( chngRecno ){
  33212. + sqliteVdbeAddOp(v, OP_Delete, iCur, 0);
  33213. + }
  33214. +
  33215. + /* Create the new index entries and the new record.
  33216. + */
  33217. + sqliteCompleteInsertion(pParse, pTab, iCur, aIdxUsed, chngRecno, 1, -1);
  33218. + }
  33219. +
  33220. + /* Increment the row counter
  33221. + */
  33222. + if( db->flags & SQLITE_CountRows && !pParse->trigStack){
  33223. + sqliteVdbeAddOp(v, OP_AddImm, 1, 0);
  33224. + }
  33225. +
  33226. + /* If there are triggers, close all the cursors after each iteration
  33227. + ** through the loop. The fire the after triggers.
  33228. + */
  33229. + if( row_triggers_exist ){
  33230. + if( !isView ){
  33231. + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  33232. + if( openAll || aIdxUsed[i] )
  33233. + sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
  33234. + }
  33235. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  33236. + pParse->nTab = iCur;
  33237. + }
  33238. + if( sqliteCodeRowTrigger(pParse, TK_UPDATE, pChanges, TK_AFTER, pTab,
  33239. + newIdx, oldIdx, onError, loopStart) ){
  33240. + goto update_cleanup;
  33241. + }
  33242. + }
  33243. +
  33244. + /* Repeat the above with the next record to be updated, until
  33245. + ** all record selected by the WHERE clause have been updated.
  33246. + */
  33247. + sqliteVdbeAddOp(v, OP_Goto, 0, loopStart);
  33248. + sqliteVdbeChangeP2(v, jumpInst, sqliteVdbeCurrentAddr(v));
  33249. + sqliteVdbeAddOp(v, OP_ListReset, 0, 0);
  33250. +
  33251. + /* Close all tables if there were no FOR EACH ROW triggers */
  33252. + if( !row_triggers_exist ){
  33253. + for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  33254. + if( openAll || aIdxUsed[i] ){
  33255. + sqliteVdbeAddOp(v, OP_Close, iCur+i+1, 0);
  33256. + }
  33257. + }
  33258. + sqliteVdbeAddOp(v, OP_Close, iCur, 0);
  33259. + pParse->nTab = iCur;
  33260. + }else{
  33261. + sqliteVdbeAddOp(v, OP_Close, newIdx, 0);
  33262. + sqliteVdbeAddOp(v, OP_Close, oldIdx, 0);
  33263. + }
  33264. +
  33265. + sqliteVdbeAddOp(v, OP_SetCounts, 0, 0);
  33266. + sqliteEndWriteOperation(pParse);
  33267. +
  33268. + /*
  33269. + ** Return the number of rows that were changed.
  33270. + */
  33271. + if( db->flags & SQLITE_CountRows && !pParse->trigStack ){
  33272. + sqliteVdbeOp3(v, OP_ColumnName, 0, 1, "rows updated", P3_STATIC);
  33273. + sqliteVdbeAddOp(v, OP_Callback, 1, 0);
  33274. + }
  33275. +
  33276. +update_cleanup:
  33277. + sqliteAuthContextPop(&sContext);
  33278. + sqliteFree(apIdx);
  33279. + sqliteFree(aXRef);
  33280. + sqliteSrcListDelete(pTabList);
  33281. + sqliteExprListDelete(pChanges);
  33282. + sqliteExprDelete(pWhere);
  33283. + return;
  33284. +}
  33285. --- /dev/null
  33286. +++ b/ext/sqlite/libsqlite/src/util.c
  33287. @@ -0,0 +1,1134 @@
  33288. +/*
  33289. +** 2001 September 15
  33290. +**
  33291. +** The author disclaims copyright to this source code. In place of
  33292. +** a legal notice, here is a blessing:
  33293. +**
  33294. +** May you do good and not evil.
  33295. +** May you find forgiveness for yourself and forgive others.
  33296. +** May you share freely, never taking more than you give.
  33297. +**
  33298. +*************************************************************************
  33299. +** Utility functions used throughout sqlite.
  33300. +**
  33301. +** This file contains functions for allocating memory, comparing
  33302. +** strings, and stuff like that.
  33303. +**
  33304. +** $Id$
  33305. +*/
  33306. +#include "sqliteInt.h"
  33307. +#include <stdarg.h>
  33308. +#include <ctype.h>
  33309. +
  33310. +/*
  33311. +** If malloc() ever fails, this global variable gets set to 1.
  33312. +** This causes the library to abort and never again function.
  33313. +*/
  33314. +int sqlite_malloc_failed = 0;
  33315. +
  33316. +/*
  33317. +** If MEMORY_DEBUG is defined, then use versions of malloc() and
  33318. +** free() that track memory usage and check for buffer overruns.
  33319. +*/
  33320. +#ifdef MEMORY_DEBUG
  33321. +
  33322. +/*
  33323. +** For keeping track of the number of mallocs and frees. This
  33324. +** is used to check for memory leaks.
  33325. +*/
  33326. +int sqlite_nMalloc; /* Number of sqliteMalloc() calls */
  33327. +int sqlite_nFree; /* Number of sqliteFree() calls */
  33328. +int sqlite_iMallocFail; /* Fail sqliteMalloc() after this many calls */
  33329. +#if MEMORY_DEBUG>1
  33330. +static int memcnt = 0;
  33331. +#endif
  33332. +
  33333. +/*
  33334. +** Number of 32-bit guard words
  33335. +*/
  33336. +#define N_GUARD 1
  33337. +
  33338. +/*
  33339. +** Allocate new memory and set it to zero. Return NULL if
  33340. +** no memory is available.
  33341. +*/
  33342. +void *sqliteMalloc_(int n, int bZero, char *zFile, int line){
  33343. + void *p;
  33344. + int *pi;
  33345. + int i, k;
  33346. + if( sqlite_iMallocFail>=0 ){
  33347. + sqlite_iMallocFail--;
  33348. + if( sqlite_iMallocFail==0 ){
  33349. + sqlite_malloc_failed++;
  33350. +#if MEMORY_DEBUG>1
  33351. + fprintf(stderr,"**** failed to allocate %d bytes at %s:%d\n",
  33352. + n, zFile,line);
  33353. +#endif
  33354. + sqlite_iMallocFail--;
  33355. + return 0;
  33356. + }
  33357. + }
  33358. + if( n==0 ) return 0;
  33359. + k = (n+sizeof(int)-1)/sizeof(int);
  33360. + pi = malloc( (N_GUARD*2+1+k)*sizeof(int));
  33361. + if( pi==0 ){
  33362. + sqlite_malloc_failed++;
  33363. + return 0;
  33364. + }
  33365. + sqlite_nMalloc++;
  33366. + for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  33367. + pi[N_GUARD] = n;
  33368. + for(i=0; i<N_GUARD; i++) pi[k+1+N_GUARD+i] = 0xdead3344;
  33369. + p = &pi[N_GUARD+1];
  33370. + memset(p, bZero==0, n);
  33371. +#if MEMORY_DEBUG>1
  33372. + fprintf(stderr,"%06d malloc %d bytes at 0x%x from %s:%d\n",
  33373. + ++memcnt, n, (int)p, zFile,line);
  33374. +#endif
  33375. + return p;
  33376. +}
  33377. +
  33378. +/*
  33379. +** Check to see if the given pointer was obtained from sqliteMalloc()
  33380. +** and is able to hold at least N bytes. Raise an exception if this
  33381. +** is not the case.
  33382. +**
  33383. +** This routine is used for testing purposes only.
  33384. +*/
  33385. +void sqliteCheckMemory(void *p, int N){
  33386. + int *pi = p;
  33387. + int n, i, k;
  33388. + pi -= N_GUARD+1;
  33389. + for(i=0; i<N_GUARD; i++){
  33390. + assert( pi[i]==0xdead1122 );
  33391. + }
  33392. + n = pi[N_GUARD];
  33393. + assert( N>=0 && N<n );
  33394. + k = (n+sizeof(int)-1)/sizeof(int);
  33395. + for(i=0; i<N_GUARD; i++){
  33396. + assert( pi[k+N_GUARD+1+i]==0xdead3344 );
  33397. + }
  33398. +}
  33399. +
  33400. +/*
  33401. +** Free memory previously obtained from sqliteMalloc()
  33402. +*/
  33403. +void sqliteFree_(void *p, char *zFile, int line){
  33404. + if( p ){
  33405. + int *pi, i, k, n;
  33406. + pi = p;
  33407. + pi -= N_GUARD+1;
  33408. + sqlite_nFree++;
  33409. + for(i=0; i<N_GUARD; i++){
  33410. + if( pi[i]!=0xdead1122 ){
  33411. + fprintf(stderr,"Low-end memory corruption at 0x%x\n", (int)p);
  33412. + return;
  33413. + }
  33414. + }
  33415. + n = pi[N_GUARD];
  33416. + k = (n+sizeof(int)-1)/sizeof(int);
  33417. + for(i=0; i<N_GUARD; i++){
  33418. + if( pi[k+N_GUARD+1+i]!=0xdead3344 ){
  33419. + fprintf(stderr,"High-end memory corruption at 0x%x\n", (int)p);
  33420. + return;
  33421. + }
  33422. + }
  33423. + memset(pi, 0xff, (k+N_GUARD*2+1)*sizeof(int));
  33424. +#if MEMORY_DEBUG>1
  33425. + fprintf(stderr,"%06d free %d bytes at 0x%x from %s:%d\n",
  33426. + ++memcnt, n, (int)p, zFile,line);
  33427. +#endif
  33428. + free(pi);
  33429. + }
  33430. +}
  33431. +
  33432. +/*
  33433. +** Resize a prior allocation. If p==0, then this routine
  33434. +** works just like sqliteMalloc(). If n==0, then this routine
  33435. +** works just like sqliteFree().
  33436. +*/
  33437. +void *sqliteRealloc_(void *oldP, int n, char *zFile, int line){
  33438. + int *oldPi, *pi, i, k, oldN, oldK;
  33439. + void *p;
  33440. + if( oldP==0 ){
  33441. + return sqliteMalloc_(n,1,zFile,line);
  33442. + }
  33443. + if( n==0 ){
  33444. + sqliteFree_(oldP,zFile,line);
  33445. + return 0;
  33446. + }
  33447. + oldPi = oldP;
  33448. + oldPi -= N_GUARD+1;
  33449. + if( oldPi[0]!=0xdead1122 ){
  33450. + fprintf(stderr,"Low-end memory corruption in realloc at 0x%x\n", (int)oldP);
  33451. + return 0;
  33452. + }
  33453. + oldN = oldPi[N_GUARD];
  33454. + oldK = (oldN+sizeof(int)-1)/sizeof(int);
  33455. + for(i=0; i<N_GUARD; i++){
  33456. + if( oldPi[oldK+N_GUARD+1+i]!=0xdead3344 ){
  33457. + fprintf(stderr,"High-end memory corruption in realloc at 0x%x\n",
  33458. + (int)oldP);
  33459. + return 0;
  33460. + }
  33461. + }
  33462. + k = (n + sizeof(int) - 1)/sizeof(int);
  33463. + pi = malloc( (k+N_GUARD*2+1)*sizeof(int) );
  33464. + if( pi==0 ){
  33465. + sqlite_malloc_failed++;
  33466. + return 0;
  33467. + }
  33468. + for(i=0; i<N_GUARD; i++) pi[i] = 0xdead1122;
  33469. + pi[N_GUARD] = n;
  33470. + for(i=0; i<N_GUARD; i++) pi[k+N_GUARD+1+i] = 0xdead3344;
  33471. + p = &pi[N_GUARD+1];
  33472. + memcpy(p, oldP, n>oldN ? oldN : n);
  33473. + if( n>oldN ){
  33474. + memset(&((char*)p)[oldN], 0, n-oldN);
  33475. + }
  33476. + memset(oldPi, 0xab, (oldK+N_GUARD+2)*sizeof(int));
  33477. + free(oldPi);
  33478. +#if MEMORY_DEBUG>1
  33479. + fprintf(stderr,"%06d realloc %d to %d bytes at 0x%x to 0x%x at %s:%d\n",
  33480. + ++memcnt, oldN, n, (int)oldP, (int)p, zFile, line);
  33481. +#endif
  33482. + return p;
  33483. +}
  33484. +
  33485. +/*
  33486. +** Make a duplicate of a string into memory obtained from malloc()
  33487. +** Free the original string using sqliteFree().
  33488. +**
  33489. +** This routine is called on all strings that are passed outside of
  33490. +** the SQLite library. That way clients can free the string using free()
  33491. +** rather than having to call sqliteFree().
  33492. +*/
  33493. +void sqliteStrRealloc(char **pz){
  33494. + char *zNew;
  33495. + if( pz==0 || *pz==0 ) return;
  33496. + zNew = malloc( strlen(*pz) + 1 );
  33497. + if( zNew==0 ){
  33498. + sqlite_malloc_failed++;
  33499. + sqliteFree(*pz);
  33500. + *pz = 0;
  33501. + }
  33502. + strcpy(zNew, *pz);
  33503. + sqliteFree(*pz);
  33504. + *pz = zNew;
  33505. +}
  33506. +
  33507. +/*
  33508. +** Make a copy of a string in memory obtained from sqliteMalloc()
  33509. +*/
  33510. +char *sqliteStrDup_(const char *z, char *zFile, int line){
  33511. + char *zNew;
  33512. + if( z==0 ) return 0;
  33513. + zNew = sqliteMalloc_(strlen(z)+1, 0, zFile, line);
  33514. + if( zNew ) strcpy(zNew, z);
  33515. + return zNew;
  33516. +}
  33517. +char *sqliteStrNDup_(const char *z, int n, char *zFile, int line){
  33518. + char *zNew;
  33519. + if( z==0 ) return 0;
  33520. + zNew = sqliteMalloc_(n+1, 0, zFile, line);
  33521. + if( zNew ){
  33522. + memcpy(zNew, z, n);
  33523. + zNew[n] = 0;
  33524. + }
  33525. + return zNew;
  33526. +}
  33527. +#endif /* MEMORY_DEBUG */
  33528. +
  33529. +/*
  33530. +** The following versions of malloc() and free() are for use in a
  33531. +** normal build.
  33532. +*/
  33533. +#if !defined(MEMORY_DEBUG)
  33534. +
  33535. +/*
  33536. +** Allocate new memory and set it to zero. Return NULL if
  33537. +** no memory is available. See also sqliteMallocRaw().
  33538. +*/
  33539. +void *sqliteMalloc(int n){
  33540. + void *p;
  33541. + if( (p = malloc(n))==0 ){
  33542. + if( n>0 ) sqlite_malloc_failed++;
  33543. + }else{
  33544. + memset(p, 0, n);
  33545. + }
  33546. + return p;
  33547. +}
  33548. +
  33549. +/*
  33550. +** Allocate new memory but do not set it to zero. Return NULL if
  33551. +** no memory is available. See also sqliteMalloc().
  33552. +*/
  33553. +void *sqliteMallocRaw(int n){
  33554. + void *p;
  33555. + if( (p = malloc(n))==0 ){
  33556. + if( n>0 ) sqlite_malloc_failed++;
  33557. + }
  33558. + return p;
  33559. +}
  33560. +
  33561. +/*
  33562. +** Free memory previously obtained from sqliteMalloc()
  33563. +*/
  33564. +void sqliteFree(void *p){
  33565. + if( p ){
  33566. + free(p);
  33567. + }
  33568. +}
  33569. +
  33570. +/*
  33571. +** Resize a prior allocation. If p==0, then this routine
  33572. +** works just like sqliteMalloc(). If n==0, then this routine
  33573. +** works just like sqliteFree().
  33574. +*/
  33575. +void *sqliteRealloc(void *p, int n){
  33576. + void *p2;
  33577. + if( p==0 ){
  33578. + return sqliteMalloc(n);
  33579. + }
  33580. + if( n==0 ){
  33581. + sqliteFree(p);
  33582. + return 0;
  33583. + }
  33584. + p2 = realloc(p, n);
  33585. + if( p2==0 ){
  33586. + sqlite_malloc_failed++;
  33587. + }
  33588. + return p2;
  33589. +}
  33590. +
  33591. +/*
  33592. +** Make a copy of a string in memory obtained from sqliteMalloc()
  33593. +*/
  33594. +char *sqliteStrDup(const char *z){
  33595. + char *zNew;
  33596. + if( z==0 ) return 0;
  33597. + zNew = sqliteMallocRaw(strlen(z)+1);
  33598. + if( zNew ) strcpy(zNew, z);
  33599. + return zNew;
  33600. +}
  33601. +char *sqliteStrNDup(const char *z, int n){
  33602. + char *zNew;
  33603. + if( z==0 ) return 0;
  33604. + zNew = sqliteMallocRaw(n+1);
  33605. + if( zNew ){
  33606. + memcpy(zNew, z, n);
  33607. + zNew[n] = 0;
  33608. + }
  33609. + return zNew;
  33610. +}
  33611. +#endif /* !defined(MEMORY_DEBUG) */
  33612. +
  33613. +/*
  33614. +** Create a string from the 2nd and subsequent arguments (up to the
  33615. +** first NULL argument), store the string in memory obtained from
  33616. +** sqliteMalloc() and make the pointer indicated by the 1st argument
  33617. +** point to that string. The 1st argument must either be NULL or
  33618. +** point to memory obtained from sqliteMalloc().
  33619. +*/
  33620. +void sqliteSetString(char **pz, ...){
  33621. + va_list ap;
  33622. + int nByte;
  33623. + const char *z;
  33624. + char *zResult;
  33625. +
  33626. + if( pz==0 ) return;
  33627. + nByte = 1;
  33628. + va_start(ap, pz);
  33629. + while( (z = va_arg(ap, const char*))!=0 ){
  33630. + nByte += strlen(z);
  33631. + }
  33632. + va_end(ap);
  33633. + sqliteFree(*pz);
  33634. + *pz = zResult = sqliteMallocRaw( nByte );
  33635. + if( zResult==0 ){
  33636. + return;
  33637. + }
  33638. + *zResult = 0;
  33639. + va_start(ap, pz);
  33640. + while( (z = va_arg(ap, const char*))!=0 ){
  33641. + strcpy(zResult, z);
  33642. + zResult += strlen(zResult);
  33643. + }
  33644. + va_end(ap);
  33645. +#ifdef MEMORY_DEBUG
  33646. +#if MEMORY_DEBUG>1
  33647. + fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
  33648. +#endif
  33649. +#endif
  33650. +}
  33651. +
  33652. +/*
  33653. +** Works like sqliteSetString, but each string is now followed by
  33654. +** a length integer which specifies how much of the source string
  33655. +** to copy (in bytes). -1 means use the whole string. The 1st
  33656. +** argument must either be NULL or point to memory obtained from
  33657. +** sqliteMalloc().
  33658. +*/
  33659. +void sqliteSetNString(char **pz, ...){
  33660. + va_list ap;
  33661. + int nByte;
  33662. + const char *z;
  33663. + char *zResult;
  33664. + int n;
  33665. +
  33666. + if( pz==0 ) return;
  33667. + nByte = 0;
  33668. + va_start(ap, pz);
  33669. + while( (z = va_arg(ap, const char*))!=0 ){
  33670. + n = va_arg(ap, int);
  33671. + if( n<=0 ) n = strlen(z);
  33672. + nByte += n;
  33673. + }
  33674. + va_end(ap);
  33675. + sqliteFree(*pz);
  33676. + *pz = zResult = sqliteMallocRaw( nByte + 1 );
  33677. + if( zResult==0 ) return;
  33678. + va_start(ap, pz);
  33679. + while( (z = va_arg(ap, const char*))!=0 ){
  33680. + n = va_arg(ap, int);
  33681. + if( n<=0 ) n = strlen(z);
  33682. + strncpy(zResult, z, n);
  33683. + zResult += n;
  33684. + }
  33685. + *zResult = 0;
  33686. +#ifdef MEMORY_DEBUG
  33687. +#if MEMORY_DEBUG>1
  33688. + fprintf(stderr,"string at 0x%x is %s\n", (int)*pz, *pz);
  33689. +#endif
  33690. +#endif
  33691. + va_end(ap);
  33692. +}
  33693. +
  33694. +/*
  33695. +** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  33696. +** The following formatting characters are allowed:
  33697. +**
  33698. +** %s Insert a string
  33699. +** %z A string that should be freed after use
  33700. +** %d Insert an integer
  33701. +** %T Insert a token
  33702. +** %S Insert the first element of a SrcList
  33703. +*/
  33704. +void sqliteErrorMsg(Parse *pParse, const char *zFormat, ...){
  33705. + va_list ap;
  33706. + pParse->nErr++;
  33707. + sqliteFree(pParse->zErrMsg);
  33708. + va_start(ap, zFormat);
  33709. + pParse->zErrMsg = sqliteVMPrintf(zFormat, ap);
  33710. + va_end(ap);
  33711. +}
  33712. +
  33713. +/*
  33714. +** Convert an SQL-style quoted string into a normal string by removing
  33715. +** the quote characters. The conversion is done in-place. If the
  33716. +** input does not begin with a quote character, then this routine
  33717. +** is a no-op.
  33718. +**
  33719. +** 2002-Feb-14: This routine is extended to remove MS-Access style
  33720. +** brackets from around identifers. For example: "[a-b-c]" becomes
  33721. +** "a-b-c".
  33722. +*/
  33723. +void sqliteDequote(char *z){
  33724. + int quote;
  33725. + int i, j;
  33726. + if( z==0 ) return;
  33727. + quote = z[0];
  33728. + switch( quote ){
  33729. + case '\'': break;
  33730. + case '"': break;
  33731. + case '[': quote = ']'; break;
  33732. + default: return;
  33733. + }
  33734. + for(i=1, j=0; z[i]; i++){
  33735. + if( z[i]==quote ){
  33736. + if( z[i+1]==quote ){
  33737. + z[j++] = quote;
  33738. + i++;
  33739. + }else{
  33740. + z[j++] = 0;
  33741. + break;
  33742. + }
  33743. + }else{
  33744. + z[j++] = z[i];
  33745. + }
  33746. + }
  33747. +}
  33748. +
  33749. +/* An array to map all upper-case characters into their corresponding
  33750. +** lower-case character.
  33751. +*/
  33752. +static unsigned char UpperToLower[] = {
  33753. + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  33754. + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  33755. + 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  33756. + 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  33757. + 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  33758. + 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  33759. + 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  33760. + 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  33761. + 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  33762. + 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  33763. + 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  33764. + 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  33765. + 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  33766. + 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  33767. + 252,253,254,255
  33768. +};
  33769. +
  33770. +/*
  33771. +** This function computes a hash on the name of a keyword.
  33772. +** Case is not significant.
  33773. +*/
  33774. +int sqliteHashNoCase(const char *z, int n){
  33775. + int h = 0;
  33776. + if( n<=0 ) n = strlen(z);
  33777. + while( n > 0 ){
  33778. + h = (h<<3) ^ h ^ UpperToLower[(unsigned char)*z++];
  33779. + n--;
  33780. + }
  33781. + return h & 0x7fffffff;
  33782. +}
  33783. +
  33784. +/*
  33785. +** Some systems have stricmp(). Others have strcasecmp(). Because
  33786. +** there is no consistency, we will define our own.
  33787. +*/
  33788. +int sqliteStrICmp(const char *zLeft, const char *zRight){
  33789. + register unsigned char *a, *b;
  33790. + a = (unsigned char *)zLeft;
  33791. + b = (unsigned char *)zRight;
  33792. + while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  33793. + return UpperToLower[*a] - UpperToLower[*b];
  33794. +}
  33795. +int sqliteStrNICmp(const char *zLeft, const char *zRight, int N){
  33796. + register unsigned char *a, *b;
  33797. + a = (unsigned char *)zLeft;
  33798. + b = (unsigned char *)zRight;
  33799. + while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  33800. + return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  33801. +}
  33802. +
  33803. +/*
  33804. +** Return TRUE if z is a pure numeric string. Return FALSE if the
  33805. +** string contains any character which is not part of a number.
  33806. +**
  33807. +** Am empty string is considered non-numeric.
  33808. +*/
  33809. +int sqliteIsNumber(const char *z){
  33810. + if( *z=='-' || *z=='+' ) z++;
  33811. + if( !isdigit(*z) ){
  33812. + return 0;
  33813. + }
  33814. + z++;
  33815. + while( isdigit(*z) ){ z++; }
  33816. + if( *z=='.' ){
  33817. + z++;
  33818. + if( !isdigit(*z) ) return 0;
  33819. + while( isdigit(*z) ){ z++; }
  33820. + }
  33821. + if( *z=='e' || *z=='E' ){
  33822. + z++;
  33823. + if( *z=='+' || *z=='-' ) z++;
  33824. + if( !isdigit(*z) ) return 0;
  33825. + while( isdigit(*z) ){ z++; }
  33826. + }
  33827. + return *z==0;
  33828. +}
  33829. +
  33830. +/*
  33831. +** The string z[] is an ascii representation of a real number.
  33832. +** Convert this string to a double.
  33833. +**
  33834. +** This routine assumes that z[] really is a valid number. If it
  33835. +** is not, the result is undefined.
  33836. +**
  33837. +** This routine is used instead of the library atof() function because
  33838. +** the library atof() might want to use "," as the decimal point instead
  33839. +** of "." depending on how locale is set. But that would cause problems
  33840. +** for SQL. So this routine always uses "." regardless of locale.
  33841. +*/
  33842. +double sqliteAtoF(const char *z, const char **pzEnd){
  33843. + int sign = 1;
  33844. + LONGDOUBLE_TYPE v1 = 0.0;
  33845. + if( *z=='-' ){
  33846. + sign = -1;
  33847. + z++;
  33848. + }else if( *z=='+' ){
  33849. + z++;
  33850. + }
  33851. + while( isdigit(*z) ){
  33852. + v1 = v1*10.0 + (*z - '0');
  33853. + z++;
  33854. + }
  33855. + if( *z=='.' ){
  33856. + LONGDOUBLE_TYPE divisor = 1.0;
  33857. + z++;
  33858. + while( isdigit(*z) ){
  33859. + v1 = v1*10.0 + (*z - '0');
  33860. + divisor *= 10.0;
  33861. + z++;
  33862. + }
  33863. + v1 /= divisor;
  33864. + }
  33865. + if( *z=='e' || *z=='E' ){
  33866. + int esign = 1;
  33867. + int eval = 0;
  33868. + LONGDOUBLE_TYPE scale = 1.0;
  33869. + z++;
  33870. + if( *z=='-' ){
  33871. + esign = -1;
  33872. + z++;
  33873. + }else if( *z=='+' ){
  33874. + z++;
  33875. + }
  33876. + while( isdigit(*z) ){
  33877. + eval = eval*10 + *z - '0';
  33878. + z++;
  33879. + }
  33880. + while( eval>=64 ){ scale *= 1.0e+64; eval -= 64; }
  33881. + while( eval>=16 ){ scale *= 1.0e+16; eval -= 16; }
  33882. + while( eval>=4 ){ scale *= 1.0e+4; eval -= 4; }
  33883. + while( eval>=1 ){ scale *= 1.0e+1; eval -= 1; }
  33884. + if( esign<0 ){
  33885. + v1 /= scale;
  33886. + }else{
  33887. + v1 *= scale;
  33888. + }
  33889. + }
  33890. + if( pzEnd ) *pzEnd = z;
  33891. + return sign<0 ? -v1 : v1;
  33892. +}
  33893. +
  33894. +/*
  33895. +** The string zNum represents an integer. There might be some other
  33896. +** information following the integer too, but that part is ignored.
  33897. +** If the integer that the prefix of zNum represents will fit in a
  33898. +** 32-bit signed integer, return TRUE. Otherwise return FALSE.
  33899. +**
  33900. +** This routine returns FALSE for the string -2147483648 even that
  33901. +** that number will, in theory fit in a 32-bit integer. But positive
  33902. +** 2147483648 will not fit in 32 bits. So it seems safer to return
  33903. +** false.
  33904. +*/
  33905. +int sqliteFitsIn32Bits(const char *zNum){
  33906. + int i, c;
  33907. + if( *zNum=='-' || *zNum=='+' ) zNum++;
  33908. + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){}
  33909. + return i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0);
  33910. +}
  33911. +
  33912. +/* This comparison routine is what we use for comparison operations
  33913. +** between numeric values in an SQL expression. "Numeric" is a little
  33914. +** bit misleading here. What we mean is that the strings have a
  33915. +** type of "numeric" from the point of view of SQL. The strings
  33916. +** do not necessarily contain numbers. They could contain text.
  33917. +**
  33918. +** If the input strings both look like actual numbers then they
  33919. +** compare in numerical order. Numerical strings are always less
  33920. +** than non-numeric strings so if one input string looks like a
  33921. +** number and the other does not, then the one that looks like
  33922. +** a number is the smaller. Non-numeric strings compare in
  33923. +** lexigraphical order (the same order as strcmp()).
  33924. +*/
  33925. +int sqliteCompare(const char *atext, const char *btext){
  33926. + int result;
  33927. + int isNumA, isNumB;
  33928. + if( atext==0 ){
  33929. + return -1;
  33930. + }else if( btext==0 ){
  33931. + return 1;
  33932. + }
  33933. + isNumA = sqliteIsNumber(atext);
  33934. + isNumB = sqliteIsNumber(btext);
  33935. + if( isNumA ){
  33936. + if( !isNumB ){
  33937. + result = -1;
  33938. + }else{
  33939. + double rA, rB;
  33940. + rA = sqliteAtoF(atext, 0);
  33941. + rB = sqliteAtoF(btext, 0);
  33942. + if( rA<rB ){
  33943. + result = -1;
  33944. + }else if( rA>rB ){
  33945. + result = +1;
  33946. + }else{
  33947. + result = 0;
  33948. + }
  33949. + }
  33950. + }else if( isNumB ){
  33951. + result = +1;
  33952. + }else {
  33953. + result = strcmp(atext, btext);
  33954. + }
  33955. + return result;
  33956. +}
  33957. +
  33958. +/*
  33959. +** This routine is used for sorting. Each key is a list of one or more
  33960. +** null-terminated elements. The list is terminated by two nulls in
  33961. +** a row. For example, the following text is a key with three elements
  33962. +**
  33963. +** Aone\000Dtwo\000Athree\000\000
  33964. +**
  33965. +** All elements begin with one of the characters "+-AD" and end with "\000"
  33966. +** with zero or more text elements in between. Except, NULL elements
  33967. +** consist of the special two-character sequence "N\000".
  33968. +**
  33969. +** Both arguments will have the same number of elements. This routine
  33970. +** returns negative, zero, or positive if the first argument is less
  33971. +** than, equal to, or greater than the first. (Result is a-b).
  33972. +**
  33973. +** Each element begins with one of the characters "+", "-", "A", "D".
  33974. +** This character determines the sort order and collating sequence:
  33975. +**
  33976. +** + Sort numerically in ascending order
  33977. +** - Sort numerically in descending order
  33978. +** A Sort as strings in ascending order
  33979. +** D Sort as strings in descending order.
  33980. +**
  33981. +** For the "+" and "-" sorting, pure numeric strings (strings for which the
  33982. +** isNum() function above returns TRUE) always compare less than strings
  33983. +** that are not pure numerics. Non-numeric strings compare in memcmp()
  33984. +** order. This is the same sort order as the sqliteCompare() function
  33985. +** above generates.
  33986. +**
  33987. +** The last point is a change from version 2.6.3 to version 2.7.0. In
  33988. +** version 2.6.3 and earlier, substrings of digits compare in numerical
  33989. +** and case was used only to break a tie.
  33990. +**
  33991. +** Elements that begin with 'A' or 'D' compare in memcmp() order regardless
  33992. +** of whether or not they look like a number.
  33993. +**
  33994. +** Note that the sort order imposed by the rules above is the same
  33995. +** from the ordering defined by the "<", "<=", ">", and ">=" operators
  33996. +** of expressions and for indices. This was not the case for version
  33997. +** 2.6.3 and earlier.
  33998. +*/
  33999. +int sqliteSortCompare(const char *a, const char *b){
  34000. + int res = 0;
  34001. + int isNumA, isNumB;
  34002. + int dir = 0;
  34003. +
  34004. + while( res==0 && *a && *b ){
  34005. + if( a[0]=='N' || b[0]=='N' ){
  34006. + if( a[0]==b[0] ){
  34007. + a += 2;
  34008. + b += 2;
  34009. + continue;
  34010. + }
  34011. + if( a[0]=='N' ){
  34012. + dir = b[0];
  34013. + res = -1;
  34014. + }else{
  34015. + dir = a[0];
  34016. + res = +1;
  34017. + }
  34018. + break;
  34019. + }
  34020. + assert( a[0]==b[0] );
  34021. + if( (dir=a[0])=='A' || a[0]=='D' ){
  34022. + res = strcmp(&a[1],&b[1]);
  34023. + if( res ) break;
  34024. + }else{
  34025. + isNumA = sqliteIsNumber(&a[1]);
  34026. + isNumB = sqliteIsNumber(&b[1]);
  34027. + if( isNumA ){
  34028. + double rA, rB;
  34029. + if( !isNumB ){
  34030. + res = -1;
  34031. + break;
  34032. + }
  34033. + rA = sqliteAtoF(&a[1], 0);
  34034. + rB = sqliteAtoF(&b[1], 0);
  34035. + if( rA<rB ){
  34036. + res = -1;
  34037. + break;
  34038. + }
  34039. + if( rA>rB ){
  34040. + res = +1;
  34041. + break;
  34042. + }
  34043. + }else if( isNumB ){
  34044. + res = +1;
  34045. + break;
  34046. + }else{
  34047. + res = strcmp(&a[1],&b[1]);
  34048. + if( res ) break;
  34049. + }
  34050. + }
  34051. + a += strlen(&a[1]) + 2;
  34052. + b += strlen(&b[1]) + 2;
  34053. + }
  34054. + if( dir=='-' || dir=='D' ) res = -res;
  34055. + return res;
  34056. +}
  34057. +
  34058. +/*
  34059. +** Some powers of 64. These constants are needed in the
  34060. +** sqliteRealToSortable() routine below.
  34061. +*/
  34062. +#define _64e3 (64.0 * 64.0 * 64.0)
  34063. +#define _64e4 (64.0 * 64.0 * 64.0 * 64.0)
  34064. +#define _64e15 (_64e3 * _64e4 * _64e4 * _64e4)
  34065. +#define _64e16 (_64e4 * _64e4 * _64e4 * _64e4)
  34066. +#define _64e63 (_64e15 * _64e16 * _64e16 * _64e16)
  34067. +#define _64e64 (_64e16 * _64e16 * _64e16 * _64e16)
  34068. +
  34069. +/*
  34070. +** The following procedure converts a double-precision floating point
  34071. +** number into a string. The resulting string has the property that
  34072. +** two such strings comparied using strcmp() or memcmp() will give the
  34073. +** same results as a numeric comparison of the original floating point
  34074. +** numbers.
  34075. +**
  34076. +** This routine is used to generate database keys from floating point
  34077. +** numbers such that the keys sort in the same order as the original
  34078. +** floating point numbers even though the keys are compared using
  34079. +** memcmp().
  34080. +**
  34081. +** The calling function should have allocated at least 14 characters
  34082. +** of space for the buffer z[].
  34083. +*/
  34084. +void sqliteRealToSortable(double r, char *z){
  34085. + int neg;
  34086. + int exp;
  34087. + int cnt = 0;
  34088. +
  34089. + /* This array maps integers between 0 and 63 into base-64 digits.
  34090. + ** The digits must be chosen such at their ASCII codes are increasing.
  34091. + ** This means we can not use the traditional base-64 digit set. */
  34092. + static const char zDigit[] =
  34093. + "0123456789"
  34094. + "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  34095. + "abcdefghijklmnopqrstuvwxyz"
  34096. + "|~";
  34097. + if( r<0.0 ){
  34098. + neg = 1;
  34099. + r = -r;
  34100. + *z++ = '-';
  34101. + } else {
  34102. + neg = 0;
  34103. + *z++ = '0';
  34104. + }
  34105. + exp = 0;
  34106. +
  34107. + if( r==0.0 ){
  34108. + exp = -1024;
  34109. + }else if( r<(0.5/64.0) ){
  34110. + while( r < 0.5/_64e64 && exp > -961 ){ r *= _64e64; exp -= 64; }
  34111. + while( r < 0.5/_64e16 && exp > -1009 ){ r *= _64e16; exp -= 16; }
  34112. + while( r < 0.5/_64e4 && exp > -1021 ){ r *= _64e4; exp -= 4; }
  34113. + while( r < 0.5/64.0 && exp > -1024 ){ r *= 64.0; exp -= 1; }
  34114. + }else if( r>=0.5 ){
  34115. + while( r >= 0.5*_64e63 && exp < 960 ){ r *= 1.0/_64e64; exp += 64; }
  34116. + while( r >= 0.5*_64e15 && exp < 1008 ){ r *= 1.0/_64e16; exp += 16; }
  34117. + while( r >= 0.5*_64e3 && exp < 1020 ){ r *= 1.0/_64e4; exp += 4; }
  34118. + while( r >= 0.5 && exp < 1023 ){ r *= 1.0/64.0; exp += 1; }
  34119. + }
  34120. + if( neg ){
  34121. + exp = -exp;
  34122. + r = -r;
  34123. + }
  34124. + exp += 1024;
  34125. + r += 0.5;
  34126. + if( exp<0 ) return;
  34127. + if( exp>=2048 || r>=1.0 ){
  34128. + strcpy(z, "~~~~~~~~~~~~");
  34129. + return;
  34130. + }
  34131. + *z++ = zDigit[(exp>>6)&0x3f];
  34132. + *z++ = zDigit[exp & 0x3f];
  34133. + while( r>0.0 && cnt<10 ){
  34134. + int digit;
  34135. + r *= 64.0;
  34136. + digit = (int)r;
  34137. + assert( digit>=0 && digit<64 );
  34138. + *z++ = zDigit[digit & 0x3f];
  34139. + r -= digit;
  34140. + cnt++;
  34141. + }
  34142. + *z = 0;
  34143. +}
  34144. +
  34145. +#ifdef SQLITE_UTF8
  34146. +/*
  34147. +** X is a pointer to the first byte of a UTF-8 character. Increment
  34148. +** X so that it points to the next character. This only works right
  34149. +** if X points to a well-formed UTF-8 string.
  34150. +*/
  34151. +#define sqliteNextChar(X) while( (0xc0&*++(X))==0x80 ){}
  34152. +#define sqliteCharVal(X) sqlite_utf8_to_int(X)
  34153. +
  34154. +#else /* !defined(SQLITE_UTF8) */
  34155. +/*
  34156. +** For iso8859 encoding, the next character is just the next byte.
  34157. +*/
  34158. +#define sqliteNextChar(X) (++(X));
  34159. +#define sqliteCharVal(X) ((int)*(X))
  34160. +
  34161. +#endif /* defined(SQLITE_UTF8) */
  34162. +
  34163. +
  34164. +#ifdef SQLITE_UTF8
  34165. +/*
  34166. +** Convert the UTF-8 character to which z points into a 31-bit
  34167. +** UCS character. This only works right if z points to a well-formed
  34168. +** UTF-8 string.
  34169. +*/
  34170. +static int sqlite_utf8_to_int(const unsigned char *z){
  34171. + int c;
  34172. + static const int initVal[] = {
  34173. + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  34174. + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
  34175. + 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44,
  34176. + 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
  34177. + 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
  34178. + 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
  34179. + 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
  34180. + 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
  34181. + 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
  34182. + 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
  34183. + 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
  34184. + 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
  34185. + 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 0, 1, 2,
  34186. + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  34187. + 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 0,
  34188. + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
  34189. + 0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 0, 1, 254,
  34190. + 255,
  34191. + };
  34192. + c = initVal[*(z++)];
  34193. + while( (0xc0&*z)==0x80 ){
  34194. + c = (c<<6) | (0x3f&*(z++));
  34195. + }
  34196. + return c;
  34197. +}
  34198. +#endif
  34199. +
  34200. +/*
  34201. +** Compare two UTF-8 strings for equality where the first string can
  34202. +** potentially be a "glob" expression. Return true (1) if they
  34203. +** are the same and false (0) if they are different.
  34204. +**
  34205. +** Globbing rules:
  34206. +**
  34207. +** '*' Matches any sequence of zero or more characters.
  34208. +**
  34209. +** '?' Matches exactly one character.
  34210. +**
  34211. +** [...] Matches one character from the enclosed list of
  34212. +** characters.
  34213. +**
  34214. +** [^...] Matches one character not in the enclosed list.
  34215. +**
  34216. +** With the [...] and [^...] matching, a ']' character can be included
  34217. +** in the list by making it the first character after '[' or '^'. A
  34218. +** range of characters can be specified using '-'. Example:
  34219. +** "[a-z]" matches any single lower-case letter. To match a '-', make
  34220. +** it the last character in the list.
  34221. +**
  34222. +** This routine is usually quick, but can be N**2 in the worst case.
  34223. +**
  34224. +** Hints: to match '*' or '?', put them in "[]". Like this:
  34225. +**
  34226. +** abc[*]xyz Matches "abc*xyz" only
  34227. +*/
  34228. +int
  34229. +sqliteGlobCompare(const unsigned char *zPattern, const unsigned char *zString){
  34230. + register int c;
  34231. + int invert;
  34232. + int seen;
  34233. + int c2;
  34234. +
  34235. + while( (c = *zPattern)!=0 ){
  34236. + switch( c ){
  34237. + case '*':
  34238. + while( (c=zPattern[1]) == '*' || c == '?' ){
  34239. + if( c=='?' ){
  34240. + if( *zString==0 ) return 0;
  34241. + sqliteNextChar(zString);
  34242. + }
  34243. + zPattern++;
  34244. + }
  34245. + if( c==0 ) return 1;
  34246. + if( c=='[' ){
  34247. + while( *zString && sqliteGlobCompare(&zPattern[1],zString)==0 ){
  34248. + sqliteNextChar(zString);
  34249. + }
  34250. + return *zString!=0;
  34251. + }else{
  34252. + while( (c2 = *zString)!=0 ){
  34253. + while( c2 != 0 && c2 != c ){ c2 = *++zString; }
  34254. + if( c2==0 ) return 0;
  34255. + if( sqliteGlobCompare(&zPattern[1],zString) ) return 1;
  34256. + sqliteNextChar(zString);
  34257. + }
  34258. + return 0;
  34259. + }
  34260. + case '?': {
  34261. + if( *zString==0 ) return 0;
  34262. + sqliteNextChar(zString);
  34263. + zPattern++;
  34264. + break;
  34265. + }
  34266. + case '[': {
  34267. + int prior_c = 0;
  34268. + seen = 0;
  34269. + invert = 0;
  34270. + c = sqliteCharVal(zString);
  34271. + if( c==0 ) return 0;
  34272. + c2 = *++zPattern;
  34273. + if( c2=='^' ){ invert = 1; c2 = *++zPattern; }
  34274. + if( c2==']' ){
  34275. + if( c==']' ) seen = 1;
  34276. + c2 = *++zPattern;
  34277. + }
  34278. + while( (c2 = sqliteCharVal(zPattern))!=0 && c2!=']' ){
  34279. + if( c2=='-' && zPattern[1]!=']' && zPattern[1]!=0 && prior_c>0 ){
  34280. + zPattern++;
  34281. + c2 = sqliteCharVal(zPattern);
  34282. + if( c>=prior_c && c<=c2 ) seen = 1;
  34283. + prior_c = 0;
  34284. + }else if( c==c2 ){
  34285. + seen = 1;
  34286. + prior_c = c2;
  34287. + }else{
  34288. + prior_c = c2;
  34289. + }
  34290. + sqliteNextChar(zPattern);
  34291. + }
  34292. + if( c2==0 || (seen ^ invert)==0 ) return 0;
  34293. + sqliteNextChar(zString);
  34294. + zPattern++;
  34295. + break;
  34296. + }
  34297. + default: {
  34298. + if( c != *zString ) return 0;
  34299. + zPattern++;
  34300. + zString++;
  34301. + break;
  34302. + }
  34303. + }
  34304. + }
  34305. + return *zString==0;
  34306. +}
  34307. +
  34308. +/*
  34309. +** Compare two UTF-8 strings for equality using the "LIKE" operator of
  34310. +** SQL. The '%' character matches any sequence of 0 or more
  34311. +** characters and '_' matches any single character. Case is
  34312. +** not significant.
  34313. +**
  34314. +** This routine is just an adaptation of the sqliteGlobCompare()
  34315. +** routine above.
  34316. +*/
  34317. +int
  34318. +sqliteLikeCompare(const unsigned char *zPattern, const unsigned char *zString){
  34319. + register int c;
  34320. + int c2;
  34321. +
  34322. + while( (c = UpperToLower[*zPattern])!=0 ){
  34323. + switch( c ){
  34324. + case '%': {
  34325. + while( (c=zPattern[1]) == '%' || c == '_' ){
  34326. + if( c=='_' ){
  34327. + if( *zString==0 ) return 0;
  34328. + sqliteNextChar(zString);
  34329. + }
  34330. + zPattern++;
  34331. + }
  34332. + if( c==0 ) return 1;
  34333. + c = UpperToLower[c];
  34334. + while( (c2=UpperToLower[*zString])!=0 ){
  34335. + while( c2 != 0 && c2 != c ){ c2 = UpperToLower[*++zString]; }
  34336. + if( c2==0 ) return 0;
  34337. + if( sqliteLikeCompare(&zPattern[1],zString) ) return 1;
  34338. + sqliteNextChar(zString);
  34339. + }
  34340. + return 0;
  34341. + }
  34342. + case '_': {
  34343. + if( *zString==0 ) return 0;
  34344. + sqliteNextChar(zString);
  34345. + zPattern++;
  34346. + break;
  34347. + }
  34348. + default: {
  34349. + if( c != UpperToLower[*zString] ) return 0;
  34350. + zPattern++;
  34351. + zString++;
  34352. + break;
  34353. + }
  34354. + }
  34355. + }
  34356. + return *zString==0;
  34357. +}
  34358. +
  34359. +/*
  34360. +** Change the sqlite.magic from SQLITE_MAGIC_OPEN to SQLITE_MAGIC_BUSY.
  34361. +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_OPEN
  34362. +** when this routine is called.
  34363. +**
  34364. +** This routine is a attempt to detect if two threads use the
  34365. +** same sqlite* pointer at the same time. There is a race
  34366. +** condition so it is possible that the error is not detected.
  34367. +** But usually the problem will be seen. The result will be an
  34368. +** error which can be used to debug the application that is
  34369. +** using SQLite incorrectly.
  34370. +**
  34371. +** Ticket #202: If db->magic is not a valid open value, take care not
  34372. +** to modify the db structure at all. It could be that db is a stale
  34373. +** pointer. In other words, it could be that there has been a prior
  34374. +** call to sqlite_close(db) and db has been deallocated. And we do
  34375. +** not want to write into deallocated memory.
  34376. +*/
  34377. +int sqliteSafetyOn(sqlite *db){
  34378. + if( db->magic==SQLITE_MAGIC_OPEN ){
  34379. + db->magic = SQLITE_MAGIC_BUSY;
  34380. + return 0;
  34381. + }else if( db->magic==SQLITE_MAGIC_BUSY || db->magic==SQLITE_MAGIC_ERROR
  34382. + || db->want_to_close ){
  34383. + db->magic = SQLITE_MAGIC_ERROR;
  34384. + db->flags |= SQLITE_Interrupt;
  34385. + }
  34386. + return 1;
  34387. +}
  34388. +
  34389. +/*
  34390. +** Change the magic from SQLITE_MAGIC_BUSY to SQLITE_MAGIC_OPEN.
  34391. +** Return an error (non-zero) if the magic was not SQLITE_MAGIC_BUSY
  34392. +** when this routine is called.
  34393. +*/
  34394. +int sqliteSafetyOff(sqlite *db){
  34395. + if( db->magic==SQLITE_MAGIC_BUSY ){
  34396. + db->magic = SQLITE_MAGIC_OPEN;
  34397. + return 0;
  34398. + }else if( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ERROR
  34399. + || db->want_to_close ){
  34400. + db->magic = SQLITE_MAGIC_ERROR;
  34401. + db->flags |= SQLITE_Interrupt;
  34402. + }
  34403. + return 1;
  34404. +}
  34405. +
  34406. +/*
  34407. +** Check to make sure we are not currently executing an sqlite_exec().
  34408. +** If we are currently in an sqlite_exec(), return true and set
  34409. +** sqlite.magic to SQLITE_MAGIC_ERROR. This will cause a complete
  34410. +** shutdown of the database.
  34411. +**
  34412. +** This routine is used to try to detect when API routines are called
  34413. +** at the wrong time or in the wrong sequence.
  34414. +*/
  34415. +int sqliteSafetyCheck(sqlite *db){
  34416. + if( db->pVdbe!=0 ){
  34417. + db->magic = SQLITE_MAGIC_ERROR;
  34418. + return 1;
  34419. + }
  34420. + return 0;
  34421. +}
  34422. --- /dev/null
  34423. +++ b/ext/sqlite/libsqlite/src/vacuum.c
  34424. @@ -0,0 +1,305 @@
  34425. +/*
  34426. +** 2003 April 6
  34427. +**
  34428. +** The author disclaims copyright to this source code. In place of
  34429. +** a legal notice, here is a blessing:
  34430. +**
  34431. +** May you do good and not evil.
  34432. +** May you find forgiveness for yourself and forgive others.
  34433. +** May you share freely, never taking more than you give.
  34434. +**
  34435. +*************************************************************************
  34436. +** This file contains code used to implement the VACUUM command.
  34437. +**
  34438. +** Most of the code in this file may be omitted by defining the
  34439. +** SQLITE_OMIT_VACUUM macro.
  34440. +**
  34441. +** $Id$
  34442. +*/
  34443. +#include "sqliteInt.h"
  34444. +#include "os.h"
  34445. +
  34446. +/*
  34447. +** A structure for holding a dynamic string - a string that can grow
  34448. +** without bound.
  34449. +*/
  34450. +typedef struct dynStr dynStr;
  34451. +struct dynStr {
  34452. + char *z; /* Text of the string in space obtained from sqliteMalloc() */
  34453. + int nAlloc; /* Amount of space allocated to z[] */
  34454. + int nUsed; /* Next unused slot in z[] */
  34455. +};
  34456. +
  34457. +/*
  34458. +** A structure that holds the vacuum context
  34459. +*/
  34460. +typedef struct vacuumStruct vacuumStruct;
  34461. +struct vacuumStruct {
  34462. + sqlite *dbOld; /* Original database */
  34463. + sqlite *dbNew; /* New database */
  34464. + char **pzErrMsg; /* Write errors here */
  34465. + int rc; /* Set to non-zero on an error */
  34466. + const char *zTable; /* Name of a table being copied */
  34467. + const char *zPragma; /* Pragma to execute with results */
  34468. + dynStr s1, s2; /* Two dynamic strings */
  34469. +};
  34470. +
  34471. +#if !defined(SQLITE_OMIT_VACUUM) || SQLITE_OMIT_VACUUM
  34472. +/*
  34473. +** Append text to a dynamic string
  34474. +*/
  34475. +static void appendText(dynStr *p, const char *zText, int nText){
  34476. + if( nText<0 ) nText = strlen(zText);
  34477. + if( p->z==0 || p->nUsed + nText + 1 >= p->nAlloc ){
  34478. + char *zNew;
  34479. + p->nAlloc = p->nUsed + nText + 1000;
  34480. + zNew = sqliteRealloc(p->z, p->nAlloc);
  34481. + if( zNew==0 ){
  34482. + sqliteFree(p->z);
  34483. + memset(p, 0, sizeof(*p));
  34484. + return;
  34485. + }
  34486. + p->z = zNew;
  34487. + }
  34488. + memcpy(&p->z[p->nUsed], zText, nText+1);
  34489. + p->nUsed += nText;
  34490. +}
  34491. +
  34492. +/*
  34493. +** Append text to a dynamic string, having first put the text in quotes.
  34494. +*/
  34495. +static void appendQuoted(dynStr *p, const char *zText){
  34496. + int i, j;
  34497. + appendText(p, "'", 1);
  34498. + for(i=j=0; zText[i]; i++){
  34499. + if( zText[i]=='\'' ){
  34500. + appendText(p, &zText[j], i-j+1);
  34501. + j = i + 1;
  34502. + appendText(p, "'", 1);
  34503. + }
  34504. + }
  34505. + if( j<i ){
  34506. + appendText(p, &zText[j], i-j);
  34507. + }
  34508. + appendText(p, "'", 1);
  34509. +}
  34510. +
  34511. +/*
  34512. +** Execute statements of SQL. If an error occurs, write the error
  34513. +** message into *pzErrMsg and return non-zero.
  34514. +*/
  34515. +static int execsql(char **pzErrMsg, sqlite *db, const char *zSql){
  34516. + char *zErrMsg = 0;
  34517. + int rc;
  34518. +
  34519. + /* printf("***** executing *****\n%s\n", zSql); */
  34520. + rc = sqlite_exec(db, zSql, 0, 0, &zErrMsg);
  34521. + if( zErrMsg ){
  34522. + sqliteSetString(pzErrMsg, zErrMsg, (char*)0);
  34523. + sqlite_freemem(zErrMsg);
  34524. + }
  34525. + return rc;
  34526. +}
  34527. +
  34528. +/*
  34529. +** This is the second stage callback. Each invocation contains all the
  34530. +** data for a single row of a single table in the original database. This
  34531. +** routine must write that information into the new database.
  34532. +*/
  34533. +static int vacuumCallback2(void *pArg, int argc, char **argv, char **NotUsed){
  34534. + vacuumStruct *p = (vacuumStruct*)pArg;
  34535. + const char *zSep = "(";
  34536. + int i;
  34537. +
  34538. + if( argv==0 ) return 0;
  34539. + p->s2.nUsed = 0;
  34540. + appendText(&p->s2, "INSERT INTO ", -1);
  34541. + appendQuoted(&p->s2, p->zTable);
  34542. + appendText(&p->s2, " VALUES", -1);
  34543. + for(i=0; i<argc; i++){
  34544. + appendText(&p->s2, zSep, 1);
  34545. + zSep = ",";
  34546. + if( argv[i]==0 ){
  34547. + appendText(&p->s2, "NULL", 4);
  34548. + }else{
  34549. + appendQuoted(&p->s2, argv[i]);
  34550. + }
  34551. + }
  34552. + appendText(&p->s2,")", 1);
  34553. + p->rc = execsql(p->pzErrMsg, p->dbNew, p->s2.z);
  34554. + return p->rc;
  34555. +}
  34556. +
  34557. +/*
  34558. +** This is the first stage callback. Each invocation contains three
  34559. +** arguments where are taken from the SQLITE_MASTER table of the original
  34560. +** database: (1) the entry type, (2) the entry name, and (3) the SQL for
  34561. +** the entry. In all cases, execute the SQL of the third argument.
  34562. +** For tables, run a query to select all entries in that table and
  34563. +** transfer them to the second-stage callback.
  34564. +*/
  34565. +static int vacuumCallback1(void *pArg, int argc, char **argv, char **NotUsed){
  34566. + vacuumStruct *p = (vacuumStruct*)pArg;
  34567. + int rc = 0;
  34568. + assert( argc==3 );
  34569. + if( argv==0 ) return 0;
  34570. + assert( argv[0]!=0 );
  34571. + assert( argv[1]!=0 );
  34572. + assert( argv[2]!=0 );
  34573. + rc = execsql(p->pzErrMsg, p->dbNew, argv[2]);
  34574. + if( rc==SQLITE_OK && strcmp(argv[0],"table")==0 ){
  34575. + char *zErrMsg = 0;
  34576. + p->s1.nUsed = 0;
  34577. + appendText(&p->s1, "SELECT * FROM ", -1);
  34578. + appendQuoted(&p->s1, argv[1]);
  34579. + p->zTable = argv[1];
  34580. + rc = sqlite_exec(p->dbOld, p->s1.z, vacuumCallback2, p, &zErrMsg);
  34581. + if( zErrMsg ){
  34582. + sqliteSetString(p->pzErrMsg, zErrMsg, (char*)0);
  34583. + sqlite_freemem(zErrMsg);
  34584. + }
  34585. + }
  34586. + if( rc!=SQLITE_ABORT ) p->rc = rc;
  34587. + return rc;
  34588. +}
  34589. +
  34590. +/*
  34591. +** Generate a random name of 20 character in length.
  34592. +*/
  34593. +static void randomName(unsigned char *zBuf){
  34594. + static const unsigned char zChars[] =
  34595. + "abcdefghijklmnopqrstuvwxyz"
  34596. + "0123456789";
  34597. + int i;
  34598. + sqliteRandomness(20, zBuf);
  34599. + for(i=0; i<20; i++){
  34600. + zBuf[i] = zChars[ zBuf[i]%(sizeof(zChars)-1) ];
  34601. + }
  34602. +}
  34603. +#endif
  34604. +
  34605. +/*
  34606. +** The non-standard VACUUM command is used to clean up the database,
  34607. +** collapse free space, etc. It is modelled after the VACUUM command
  34608. +** in PostgreSQL.
  34609. +**
  34610. +** In version 1.0.x of SQLite, the VACUUM command would call
  34611. +** gdbm_reorganize() on all the database tables. But beginning
  34612. +** with 2.0.0, SQLite no longer uses GDBM so this command has
  34613. +** become a no-op.
  34614. +*/
  34615. +void sqliteVacuum(Parse *pParse, Token *pTableName){
  34616. + Vdbe *v = sqliteGetVdbe(pParse);
  34617. + sqliteVdbeAddOp(v, OP_Vacuum, 0, 0);
  34618. + return;
  34619. +}
  34620. +
  34621. +/*
  34622. +** This routine implements the OP_Vacuum opcode of the VDBE.
  34623. +*/
  34624. +int sqliteRunVacuum(char **pzErrMsg, sqlite *db){
  34625. +#if !defined(SQLITE_OMIT_VACUUM) || SQLITE_OMIT_VACUUM
  34626. + const char *zFilename; /* full pathname of the database file */
  34627. + int nFilename; /* number of characters in zFilename[] */
  34628. + char *zTemp = 0; /* a temporary file in same directory as zFilename */
  34629. + sqlite *dbNew = 0; /* The new vacuumed database */
  34630. + int rc = SQLITE_OK; /* Return code from service routines */
  34631. + int i; /* Loop counter */
  34632. + char *zErrMsg; /* Error message */
  34633. + vacuumStruct sVac; /* Information passed to callbacks */
  34634. +
  34635. + if( db->flags & SQLITE_InTrans ){
  34636. + sqliteSetString(pzErrMsg, "cannot VACUUM from within a transaction",
  34637. + (char*)0);
  34638. + return SQLITE_ERROR;
  34639. + }
  34640. + if( db->flags & SQLITE_Interrupt ){
  34641. + return SQLITE_INTERRUPT;
  34642. + }
  34643. + memset(&sVac, 0, sizeof(sVac));
  34644. +
  34645. + /* Get the full pathname of the database file and create two
  34646. + ** temporary filenames in the same directory as the original file.
  34647. + */
  34648. + zFilename = sqliteBtreeGetFilename(db->aDb[0].pBt);
  34649. + if( zFilename==0 ){
  34650. + /* This only happens with the in-memory database. VACUUM is a no-op
  34651. + ** there, so just return */
  34652. + return SQLITE_OK;
  34653. + }
  34654. + nFilename = strlen(zFilename);
  34655. + zTemp = sqliteMalloc( nFilename+100 );
  34656. + if( zTemp==0 ) return SQLITE_NOMEM;
  34657. + strcpy(zTemp, zFilename);
  34658. + for(i=0; i<10; i++){
  34659. + zTemp[nFilename] = '-';
  34660. + randomName((unsigned char*)&zTemp[nFilename+1]);
  34661. + if( !sqliteOsFileExists(zTemp) ) break;
  34662. + }
  34663. + if( i>=10 ){
  34664. + sqliteSetString(pzErrMsg, "unable to create a temporary database file "
  34665. + "in the same directory as the original database", (char*)0);
  34666. + goto end_of_vacuum;
  34667. + }
  34668. +
  34669. +
  34670. + dbNew = sqlite_open(zTemp, 0, &zErrMsg);
  34671. + if( dbNew==0 ){
  34672. + sqliteSetString(pzErrMsg, "unable to open a temporary database at ",
  34673. + zTemp, " - ", zErrMsg, (char*)0);
  34674. + goto end_of_vacuum;
  34675. + }
  34676. + if( (rc = execsql(pzErrMsg, db, "BEGIN"))!=0 ) goto end_of_vacuum;
  34677. + if( (rc = execsql(pzErrMsg, dbNew, "PRAGMA synchronous=off; BEGIN"))!=0 ){
  34678. + goto end_of_vacuum;
  34679. + }
  34680. +
  34681. + sVac.dbOld = db;
  34682. + sVac.dbNew = dbNew;
  34683. + sVac.pzErrMsg = pzErrMsg;
  34684. + if( rc==SQLITE_OK ){
  34685. + rc = sqlite_exec(db,
  34686. + "SELECT type, name, sql FROM sqlite_master "
  34687. + "WHERE sql NOT NULL AND type!='view' "
  34688. + "UNION ALL "
  34689. + "SELECT type, name, sql FROM sqlite_master "
  34690. + "WHERE sql NOT NULL AND type=='view'",
  34691. + vacuumCallback1, &sVac, &zErrMsg);
  34692. + }
  34693. + if( rc==SQLITE_OK ){
  34694. + int meta1[SQLITE_N_BTREE_META];
  34695. + int meta2[SQLITE_N_BTREE_META];
  34696. + sqliteBtreeGetMeta(db->aDb[0].pBt, meta1);
  34697. + sqliteBtreeGetMeta(dbNew->aDb[0].pBt, meta2);
  34698. + meta2[1] = meta1[1]+1;
  34699. + meta2[3] = meta1[3];
  34700. + meta2[4] = meta1[4];
  34701. + meta2[6] = meta1[6];
  34702. + rc = sqliteBtreeUpdateMeta(dbNew->aDb[0].pBt, meta2);
  34703. + }
  34704. + if( rc==SQLITE_OK ){
  34705. + rc = sqliteBtreeCopyFile(db->aDb[0].pBt, dbNew->aDb[0].pBt);
  34706. + sqlite_exec(db, "COMMIT", 0, 0, 0);
  34707. + sqliteResetInternalSchema(db, 0);
  34708. + }
  34709. +
  34710. +end_of_vacuum:
  34711. + if( rc && zErrMsg!=0 ){
  34712. + sqliteSetString(pzErrMsg, "unable to vacuum database - ",
  34713. + zErrMsg, (char*)0);
  34714. + }
  34715. + sqlite_exec(db, "ROLLBACK", 0, 0, 0);
  34716. + if( (dbNew && (dbNew->flags & SQLITE_Interrupt))
  34717. + || (db->flags & SQLITE_Interrupt) ){
  34718. + rc = SQLITE_INTERRUPT;
  34719. + }
  34720. + if( dbNew ) sqlite_close(dbNew);
  34721. + sqliteOsDelete(zTemp);
  34722. + sqliteFree(zTemp);
  34723. + sqliteFree(sVac.s1.z);
  34724. + sqliteFree(sVac.s2.z);
  34725. + if( zErrMsg ) sqlite_freemem(zErrMsg);
  34726. + if( rc==SQLITE_ABORT && sVac.rc!=SQLITE_INTERRUPT ) sVac.rc = SQLITE_ERROR;
  34727. + return sVac.rc;
  34728. +#endif
  34729. +}
  34730. --- /dev/null
  34731. +++ b/ext/sqlite/libsqlite/src/vdbeaux.c
  34732. @@ -0,0 +1,1061 @@
  34733. +/*
  34734. +** 2003 September 6
  34735. +**
  34736. +** The author disclaims copyright to this source code. In place of
  34737. +** a legal notice, here is a blessing:
  34738. +**
  34739. +** May you do good and not evil.
  34740. +** May you find forgiveness for yourself and forgive others.
  34741. +** May you share freely, never taking more than you give.
  34742. +**
  34743. +*************************************************************************
  34744. +** This file contains code used for creating, destroying, and populating
  34745. +** a VDBE (or an "sqlite_vm" as it is known to the outside world.) Prior
  34746. +** to version 2.8.7, all this code was combined into the vdbe.c source file.
  34747. +** But that file was getting too big so this subroutines were split out.
  34748. +*/
  34749. +#include "sqliteInt.h"
  34750. +#include "os.h"
  34751. +#include <ctype.h>
  34752. +#include "vdbeInt.h"
  34753. +
  34754. +
  34755. +/*
  34756. +** When debugging the code generator in a symbolic debugger, one can
  34757. +** set the sqlite_vdbe_addop_trace to 1 and all opcodes will be printed
  34758. +** as they are added to the instruction stream.
  34759. +*/
  34760. +#ifndef NDEBUG
  34761. +int sqlite_vdbe_addop_trace = 0;
  34762. +#endif
  34763. +
  34764. +
  34765. +/*
  34766. +** Create a new virtual database engine.
  34767. +*/
  34768. +Vdbe *sqliteVdbeCreate(sqlite *db){
  34769. + Vdbe *p;
  34770. + p = sqliteMalloc( sizeof(Vdbe) );
  34771. + if( p==0 ) return 0;
  34772. + p->db = db;
  34773. + if( db->pVdbe ){
  34774. + db->pVdbe->pPrev = p;
  34775. + }
  34776. + p->pNext = db->pVdbe;
  34777. + p->pPrev = 0;
  34778. + db->pVdbe = p;
  34779. + p->magic = VDBE_MAGIC_INIT;
  34780. + return p;
  34781. +}
  34782. +
  34783. +/*
  34784. +** Turn tracing on or off
  34785. +*/
  34786. +void sqliteVdbeTrace(Vdbe *p, FILE *trace){
  34787. + p->trace = trace;
  34788. +}
  34789. +
  34790. +/*
  34791. +** Add a new instruction to the list of instructions current in the
  34792. +** VDBE. Return the address of the new instruction.
  34793. +**
  34794. +** Parameters:
  34795. +**
  34796. +** p Pointer to the VDBE
  34797. +**
  34798. +** op The opcode for this instruction
  34799. +**
  34800. +** p1, p2 First two of the three possible operands.
  34801. +**
  34802. +** Use the sqliteVdbeResolveLabel() function to fix an address and
  34803. +** the sqliteVdbeChangeP3() function to change the value of the P3
  34804. +** operand.
  34805. +*/
  34806. +int sqliteVdbeAddOp(Vdbe *p, int op, int p1, int p2){
  34807. + int i;
  34808. + VdbeOp *pOp;
  34809. +
  34810. + i = p->nOp;
  34811. + p->nOp++;
  34812. + assert( p->magic==VDBE_MAGIC_INIT );
  34813. + if( i>=p->nOpAlloc ){
  34814. + int oldSize = p->nOpAlloc;
  34815. + Op *aNew;
  34816. + p->nOpAlloc = p->nOpAlloc*2 + 100;
  34817. + aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
  34818. + if( aNew==0 ){
  34819. + p->nOpAlloc = oldSize;
  34820. + return 0;
  34821. + }
  34822. + p->aOp = aNew;
  34823. + memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
  34824. + }
  34825. + pOp = &p->aOp[i];
  34826. + pOp->opcode = op;
  34827. + pOp->p1 = p1;
  34828. + if( p2<0 && (-1-p2)<p->nLabel && p->aLabel[-1-p2]>=0 ){
  34829. + p2 = p->aLabel[-1-p2];
  34830. + }
  34831. + pOp->p2 = p2;
  34832. + pOp->p3 = 0;
  34833. + pOp->p3type = P3_NOTUSED;
  34834. +#ifndef NDEBUG
  34835. + if( sqlite_vdbe_addop_trace ) sqliteVdbePrintOp(0, i, &p->aOp[i]);
  34836. +#endif
  34837. + return i;
  34838. +}
  34839. +
  34840. +/*
  34841. +** Add an opcode that includes the p3 value.
  34842. +*/
  34843. +int sqliteVdbeOp3(Vdbe *p, int op, int p1, int p2, const char *zP3, int p3type){
  34844. + int addr = sqliteVdbeAddOp(p, op, p1, p2);
  34845. + sqliteVdbeChangeP3(p, addr, zP3, p3type);
  34846. + return addr;
  34847. +}
  34848. +
  34849. +/*
  34850. +** Add multiple opcodes. The list is terminated by an opcode of 0.
  34851. +*/
  34852. +int sqliteVdbeCode(Vdbe *p, ...){
  34853. + int addr;
  34854. + va_list ap;
  34855. + int opcode, p1, p2;
  34856. + va_start(ap, p);
  34857. + addr = p->nOp;
  34858. + while( (opcode = va_arg(ap,int))!=0 ){
  34859. + p1 = va_arg(ap,int);
  34860. + p2 = va_arg(ap,int);
  34861. + sqliteVdbeAddOp(p, opcode, p1, p2);
  34862. + }
  34863. + va_end(ap);
  34864. + return addr;
  34865. +}
  34866. +
  34867. +
  34868. +
  34869. +/*
  34870. +** Create a new symbolic label for an instruction that has yet to be
  34871. +** coded. The symbolic label is really just a negative number. The
  34872. +** label can be used as the P2 value of an operation. Later, when
  34873. +** the label is resolved to a specific address, the VDBE will scan
  34874. +** through its operation list and change all values of P2 which match
  34875. +** the label into the resolved address.
  34876. +**
  34877. +** The VDBE knows that a P2 value is a label because labels are
  34878. +** always negative and P2 values are suppose to be non-negative.
  34879. +** Hence, a negative P2 value is a label that has yet to be resolved.
  34880. +*/
  34881. +int sqliteVdbeMakeLabel(Vdbe *p){
  34882. + int i;
  34883. + i = p->nLabel++;
  34884. + assert( p->magic==VDBE_MAGIC_INIT );
  34885. + if( i>=p->nLabelAlloc ){
  34886. + int *aNew;
  34887. + p->nLabelAlloc = p->nLabelAlloc*2 + 10;
  34888. + aNew = sqliteRealloc( p->aLabel, p->nLabelAlloc*sizeof(p->aLabel[0]));
  34889. + if( aNew==0 ){
  34890. + sqliteFree(p->aLabel);
  34891. + }
  34892. + p->aLabel = aNew;
  34893. + }
  34894. + if( p->aLabel==0 ){
  34895. + p->nLabel = 0;
  34896. + p->nLabelAlloc = 0;
  34897. + return 0;
  34898. + }
  34899. + p->aLabel[i] = -1;
  34900. + return -1-i;
  34901. +}
  34902. +
  34903. +/*
  34904. +** Resolve label "x" to be the address of the next instruction to
  34905. +** be inserted. The parameter "x" must have been obtained from
  34906. +** a prior call to sqliteVdbeMakeLabel().
  34907. +*/
  34908. +void sqliteVdbeResolveLabel(Vdbe *p, int x){
  34909. + int j;
  34910. + assert( p->magic==VDBE_MAGIC_INIT );
  34911. + if( x<0 && (-x)<=p->nLabel && p->aOp ){
  34912. + if( p->aLabel[-1-x]==p->nOp ) return;
  34913. + assert( p->aLabel[-1-x]<0 );
  34914. + p->aLabel[-1-x] = p->nOp;
  34915. + for(j=0; j<p->nOp; j++){
  34916. + if( p->aOp[j].p2==x ) p->aOp[j].p2 = p->nOp;
  34917. + }
  34918. + }
  34919. +}
  34920. +
  34921. +/*
  34922. +** Return the address of the next instruction to be inserted.
  34923. +*/
  34924. +int sqliteVdbeCurrentAddr(Vdbe *p){
  34925. + assert( p->magic==VDBE_MAGIC_INIT );
  34926. + return p->nOp;
  34927. +}
  34928. +
  34929. +/*
  34930. +** Add a whole list of operations to the operation stack. Return the
  34931. +** address of the first operation added.
  34932. +*/
  34933. +int sqliteVdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
  34934. + int addr;
  34935. + assert( p->magic==VDBE_MAGIC_INIT );
  34936. + if( p->nOp + nOp >= p->nOpAlloc ){
  34937. + int oldSize = p->nOpAlloc;
  34938. + Op *aNew;
  34939. + p->nOpAlloc = p->nOpAlloc*2 + nOp + 10;
  34940. + aNew = sqliteRealloc(p->aOp, p->nOpAlloc*sizeof(Op));
  34941. + if( aNew==0 ){
  34942. + p->nOpAlloc = oldSize;
  34943. + return 0;
  34944. + }
  34945. + p->aOp = aNew;
  34946. + memset(&p->aOp[oldSize], 0, (p->nOpAlloc-oldSize)*sizeof(Op));
  34947. + }
  34948. + addr = p->nOp;
  34949. + if( nOp>0 ){
  34950. + int i;
  34951. + VdbeOpList const *pIn = aOp;
  34952. + for(i=0; i<nOp; i++, pIn++){
  34953. + int p2 = pIn->p2;
  34954. + VdbeOp *pOut = &p->aOp[i+addr];
  34955. + pOut->opcode = pIn->opcode;
  34956. + pOut->p1 = pIn->p1;
  34957. + pOut->p2 = p2<0 ? addr + ADDR(p2) : p2;
  34958. + pOut->p3 = pIn->p3;
  34959. + pOut->p3type = pIn->p3 ? P3_STATIC : P3_NOTUSED;
  34960. +#ifndef NDEBUG
  34961. + if( sqlite_vdbe_addop_trace ){
  34962. + sqliteVdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  34963. + }
  34964. +#endif
  34965. + }
  34966. + p->nOp += nOp;
  34967. + }
  34968. + return addr;
  34969. +}
  34970. +
  34971. +/*
  34972. +** Change the value of the P1 operand for a specific instruction.
  34973. +** This routine is useful when a large program is loaded from a
  34974. +** static array using sqliteVdbeAddOpList but we want to make a
  34975. +** few minor changes to the program.
  34976. +*/
  34977. +void sqliteVdbeChangeP1(Vdbe *p, int addr, int val){
  34978. + assert( p->magic==VDBE_MAGIC_INIT );
  34979. + if( p && addr>=0 && p->nOp>addr && p->aOp ){
  34980. + p->aOp[addr].p1 = val;
  34981. + }
  34982. +}
  34983. +
  34984. +/*
  34985. +** Change the value of the P2 operand for a specific instruction.
  34986. +** This routine is useful for setting a jump destination.
  34987. +*/
  34988. +void sqliteVdbeChangeP2(Vdbe *p, int addr, int val){
  34989. + assert( val>=0 );
  34990. + assert( p->magic==VDBE_MAGIC_INIT );
  34991. + if( p && addr>=0 && p->nOp>addr && p->aOp ){
  34992. + p->aOp[addr].p2 = val;
  34993. + }
  34994. +}
  34995. +
  34996. +/*
  34997. +** Change the value of the P3 operand for a specific instruction.
  34998. +** This routine is useful when a large program is loaded from a
  34999. +** static array using sqliteVdbeAddOpList but we want to make a
  35000. +** few minor changes to the program.
  35001. +**
  35002. +** If n>=0 then the P3 operand is dynamic, meaning that a copy of
  35003. +** the string is made into memory obtained from sqliteMalloc().
  35004. +** A value of n==0 means copy bytes of zP3 up to and including the
  35005. +** first null byte. If n>0 then copy n+1 bytes of zP3.
  35006. +**
  35007. +** If n==P3_STATIC it means that zP3 is a pointer to a constant static
  35008. +** string and we can just copy the pointer. n==P3_POINTER means zP3 is
  35009. +** a pointer to some object other than a string.
  35010. +**
  35011. +** If addr<0 then change P3 on the most recently inserted instruction.
  35012. +*/
  35013. +void sqliteVdbeChangeP3(Vdbe *p, int addr, const char *zP3, int n){
  35014. + Op *pOp;
  35015. + assert( p->magic==VDBE_MAGIC_INIT );
  35016. + if( p==0 || p->aOp==0 ) return;
  35017. + if( addr<0 || addr>=p->nOp ){
  35018. + addr = p->nOp - 1;
  35019. + if( addr<0 ) return;
  35020. + }
  35021. + pOp = &p->aOp[addr];
  35022. + if( pOp->p3 && pOp->p3type==P3_DYNAMIC ){
  35023. + sqliteFree(pOp->p3);
  35024. + pOp->p3 = 0;
  35025. + }
  35026. + if( zP3==0 ){
  35027. + pOp->p3 = 0;
  35028. + pOp->p3type = P3_NOTUSED;
  35029. + }else if( n<0 ){
  35030. + pOp->p3 = (char*)zP3;
  35031. + pOp->p3type = n;
  35032. + }else{
  35033. + sqliteSetNString(&pOp->p3, zP3, n, 0);
  35034. + pOp->p3type = P3_DYNAMIC;
  35035. + }
  35036. +}
  35037. +
  35038. +/*
  35039. +** If the P3 operand to the specified instruction appears
  35040. +** to be a quoted string token, then this procedure removes
  35041. +** the quotes.
  35042. +**
  35043. +** The quoting operator can be either a grave ascent (ASCII 0x27)
  35044. +** or a double quote character (ASCII 0x22). Two quotes in a row
  35045. +** resolve to be a single actual quote character within the string.
  35046. +*/
  35047. +void sqliteVdbeDequoteP3(Vdbe *p, int addr){
  35048. + Op *pOp;
  35049. + assert( p->magic==VDBE_MAGIC_INIT );
  35050. + if( p->aOp==0 ) return;
  35051. + if( addr<0 || addr>=p->nOp ){
  35052. + addr = p->nOp - 1;
  35053. + if( addr<0 ) return;
  35054. + }
  35055. + pOp = &p->aOp[addr];
  35056. + if( pOp->p3==0 || pOp->p3[0]==0 ) return;
  35057. + if( pOp->p3type==P3_POINTER ) return;
  35058. + if( pOp->p3type!=P3_DYNAMIC ){
  35059. + pOp->p3 = sqliteStrDup(pOp->p3);
  35060. + pOp->p3type = P3_DYNAMIC;
  35061. + }
  35062. + sqliteDequote(pOp->p3);
  35063. +}
  35064. +
  35065. +/*
  35066. +** On the P3 argument of the given instruction, change all
  35067. +** strings of whitespace characters into a single space and
  35068. +** delete leading and trailing whitespace.
  35069. +*/
  35070. +void sqliteVdbeCompressSpace(Vdbe *p, int addr){
  35071. + unsigned char *z;
  35072. + int i, j;
  35073. + Op *pOp;
  35074. + assert( p->magic==VDBE_MAGIC_INIT );
  35075. + if( p->aOp==0 || addr<0 || addr>=p->nOp ) return;
  35076. + pOp = &p->aOp[addr];
  35077. + if( pOp->p3type==P3_POINTER ){
  35078. + return;
  35079. + }
  35080. + if( pOp->p3type!=P3_DYNAMIC ){
  35081. + pOp->p3 = sqliteStrDup(pOp->p3);
  35082. + pOp->p3type = P3_DYNAMIC;
  35083. + }
  35084. + z = (unsigned char*)pOp->p3;
  35085. + if( z==0 ) return;
  35086. + i = j = 0;
  35087. + while( isspace(z[i]) ){ i++; }
  35088. + while( z[i] ){
  35089. + if( isspace(z[i]) ){
  35090. + z[j++] = ' ';
  35091. + while( isspace(z[++i]) ){}
  35092. + }else{
  35093. + z[j++] = z[i++];
  35094. + }
  35095. + }
  35096. + while( j>0 && isspace(z[j-1]) ){ j--; }
  35097. + z[j] = 0;
  35098. +}
  35099. +
  35100. +/*
  35101. +** Search for the current program for the given opcode and P2
  35102. +** value. Return the address plus 1 if found and 0 if not found.
  35103. +*/
  35104. +int sqliteVdbeFindOp(Vdbe *p, int op, int p2){
  35105. + int i;
  35106. + assert( p->magic==VDBE_MAGIC_INIT );
  35107. + for(i=0; i<p->nOp; i++){
  35108. + if( p->aOp[i].opcode==op && p->aOp[i].p2==p2 ) return i+1;
  35109. + }
  35110. + return 0;
  35111. +}
  35112. +
  35113. +/*
  35114. +** Return the opcode for a given address.
  35115. +*/
  35116. +VdbeOp *sqliteVdbeGetOp(Vdbe *p, int addr){
  35117. + assert( p->magic==VDBE_MAGIC_INIT );
  35118. + assert( addr>=0 && addr<p->nOp );
  35119. + return &p->aOp[addr];
  35120. +}
  35121. +
  35122. +/*
  35123. +** The following group or routines are employed by installable functions
  35124. +** to return their results.
  35125. +**
  35126. +** The sqlite_set_result_string() routine can be used to return a string
  35127. +** value or to return a NULL. To return a NULL, pass in NULL for zResult.
  35128. +** A copy is made of the string before this routine returns so it is safe
  35129. +** to pass in an ephemeral string.
  35130. +**
  35131. +** sqlite_set_result_error() works like sqlite_set_result_string() except
  35132. +** that it signals a fatal error. The string argument, if any, is the
  35133. +** error message. If the argument is NULL a generic substitute error message
  35134. +** is used.
  35135. +**
  35136. +** The sqlite_set_result_int() and sqlite_set_result_double() set the return
  35137. +** value of the user function to an integer or a double.
  35138. +**
  35139. +** These routines are defined here in vdbe.c because they depend on knowing
  35140. +** the internals of the sqlite_func structure which is only defined in
  35141. +** this source file.
  35142. +*/
  35143. +char *sqlite_set_result_string(sqlite_func *p, const char *zResult, int n){
  35144. + assert( !p->isStep );
  35145. + if( p->s.flags & MEM_Dyn ){
  35146. + sqliteFree(p->s.z);
  35147. + }
  35148. + if( zResult==0 ){
  35149. + p->s.flags = MEM_Null;
  35150. + n = 0;
  35151. + p->s.z = 0;
  35152. + p->s.n = 0;
  35153. + }else{
  35154. + if( n<0 ) n = strlen(zResult);
  35155. + if( n<NBFS-1 ){
  35156. + memcpy(p->s.zShort, zResult, n);
  35157. + p->s.zShort[n] = 0;
  35158. + p->s.flags = MEM_Str | MEM_Short;
  35159. + p->s.z = p->s.zShort;
  35160. + }else{
  35161. + p->s.z = sqliteMallocRaw( n+1 );
  35162. + if( p->s.z ){
  35163. + memcpy(p->s.z, zResult, n);
  35164. + p->s.z[n] = 0;
  35165. + }
  35166. + p->s.flags = MEM_Str | MEM_Dyn;
  35167. + }
  35168. + p->s.n = n+1;
  35169. + }
  35170. + return p->s.z;
  35171. +}
  35172. +void sqlite_set_result_int(sqlite_func *p, int iResult){
  35173. + assert( !p->isStep );
  35174. + if( p->s.flags & MEM_Dyn ){
  35175. + sqliteFree(p->s.z);
  35176. + }
  35177. + p->s.i = iResult;
  35178. + p->s.flags = MEM_Int;
  35179. +}
  35180. +void sqlite_set_result_double(sqlite_func *p, double rResult){
  35181. + assert( !p->isStep );
  35182. + if( p->s.flags & MEM_Dyn ){
  35183. + sqliteFree(p->s.z);
  35184. + }
  35185. + p->s.r = rResult;
  35186. + p->s.flags = MEM_Real;
  35187. +}
  35188. +void sqlite_set_result_error(sqlite_func *p, const char *zMsg, int n){
  35189. + assert( !p->isStep );
  35190. + sqlite_set_result_string(p, zMsg, n);
  35191. + p->isError = 1;
  35192. +}
  35193. +
  35194. +/*
  35195. +** Extract the user data from a sqlite_func structure and return a
  35196. +** pointer to it.
  35197. +*/
  35198. +void *sqlite_user_data(sqlite_func *p){
  35199. + assert( p && p->pFunc );
  35200. + return p->pFunc->pUserData;
  35201. +}
  35202. +
  35203. +/*
  35204. +** Allocate or return the aggregate context for a user function. A new
  35205. +** context is allocated on the first call. Subsequent calls return the
  35206. +** same context that was returned on prior calls.
  35207. +**
  35208. +** This routine is defined here in vdbe.c because it depends on knowing
  35209. +** the internals of the sqlite_func structure which is only defined in
  35210. +** this source file.
  35211. +*/
  35212. +void *sqlite_aggregate_context(sqlite_func *p, int nByte){
  35213. + assert( p && p->pFunc && p->pFunc->xStep );
  35214. + if( p->pAgg==0 ){
  35215. + if( nByte<=NBFS ){
  35216. + p->pAgg = (void*)p->s.z;
  35217. + memset(p->pAgg, 0, nByte);
  35218. + }else{
  35219. + p->pAgg = sqliteMalloc( nByte );
  35220. + }
  35221. + }
  35222. + return p->pAgg;
  35223. +}
  35224. +
  35225. +/*
  35226. +** Return the number of times the Step function of a aggregate has been
  35227. +** called.
  35228. +**
  35229. +** This routine is defined here in vdbe.c because it depends on knowing
  35230. +** the internals of the sqlite_func structure which is only defined in
  35231. +** this source file.
  35232. +*/
  35233. +int sqlite_aggregate_count(sqlite_func *p){
  35234. + assert( p && p->pFunc && p->pFunc->xStep );
  35235. + return p->cnt;
  35236. +}
  35237. +
  35238. +#if !defined(NDEBUG) || defined(VDBE_PROFILE)
  35239. +/*
  35240. +** Print a single opcode. This routine is used for debugging only.
  35241. +*/
  35242. +void sqliteVdbePrintOp(FILE *pOut, int pc, Op *pOp){
  35243. + char *zP3;
  35244. + char zPtr[40];
  35245. + if( pOp->p3type==P3_POINTER ){
  35246. + sprintf(zPtr, "ptr(%#lx)", (long)pOp->p3);
  35247. + zP3 = zPtr;
  35248. + }else{
  35249. + zP3 = pOp->p3;
  35250. + }
  35251. + if( pOut==0 ) pOut = stdout;
  35252. + fprintf(pOut,"%4d %-12s %4d %4d %s\n",
  35253. + pc, sqliteOpcodeNames[pOp->opcode], pOp->p1, pOp->p2, zP3 ? zP3 : "");
  35254. + fflush(pOut);
  35255. +}
  35256. +#endif
  35257. +
  35258. +/*
  35259. +** Give a listing of the program in the virtual machine.
  35260. +**
  35261. +** The interface is the same as sqliteVdbeExec(). But instead of
  35262. +** running the code, it invokes the callback once for each instruction.
  35263. +** This feature is used to implement "EXPLAIN".
  35264. +*/
  35265. +int sqliteVdbeList(
  35266. + Vdbe *p /* The VDBE */
  35267. +){
  35268. + sqlite *db = p->db;
  35269. + int i;
  35270. + int rc = SQLITE_OK;
  35271. + static char *azColumnNames[] = {
  35272. + "addr", "opcode", "p1", "p2", "p3",
  35273. + "int", "text", "int", "int", "text",
  35274. + 0
  35275. + };
  35276. +
  35277. + assert( p->popStack==0 );
  35278. + assert( p->explain );
  35279. + p->azColName = azColumnNames;
  35280. + p->azResColumn = p->zArgv;
  35281. + for(i=0; i<5; i++) p->zArgv[i] = p->aStack[i].zShort;
  35282. + i = p->pc;
  35283. + if( i>=p->nOp ){
  35284. + p->rc = SQLITE_OK;
  35285. + rc = SQLITE_DONE;
  35286. + }else if( db->flags & SQLITE_Interrupt ){
  35287. + db->flags &= ~SQLITE_Interrupt;
  35288. + if( db->magic!=SQLITE_MAGIC_BUSY ){
  35289. + p->rc = SQLITE_MISUSE;
  35290. + }else{
  35291. + p->rc = SQLITE_INTERRUPT;
  35292. + }
  35293. + rc = SQLITE_ERROR;
  35294. + sqliteSetString(&p->zErrMsg, sqlite_error_string(p->rc), (char*)0);
  35295. + }else{
  35296. + sprintf(p->zArgv[0],"%d",i);
  35297. + sprintf(p->zArgv[2],"%d", p->aOp[i].p1);
  35298. + sprintf(p->zArgv[3],"%d", p->aOp[i].p2);
  35299. + if( p->aOp[i].p3type==P3_POINTER ){
  35300. + sprintf(p->aStack[4].zShort, "ptr(%#lx)", (long)p->aOp[i].p3);
  35301. + p->zArgv[4] = p->aStack[4].zShort;
  35302. + }else{
  35303. + p->zArgv[4] = p->aOp[i].p3;
  35304. + }
  35305. + p->zArgv[1] = sqliteOpcodeNames[p->aOp[i].opcode];
  35306. + p->pc = i+1;
  35307. + p->azResColumn = p->zArgv;
  35308. + p->nResColumn = 5;
  35309. + p->rc = SQLITE_OK;
  35310. + rc = SQLITE_ROW;
  35311. + }
  35312. + return rc;
  35313. +}
  35314. +
  35315. +/*
  35316. +** Prepare a virtual machine for execution. This involves things such
  35317. +** as allocating stack space and initializing the program counter.
  35318. +** After the VDBE has be prepped, it can be executed by one or more
  35319. +** calls to sqliteVdbeExec().
  35320. +*/
  35321. +void sqliteVdbeMakeReady(
  35322. + Vdbe *p, /* The VDBE */
  35323. + int nVar, /* Number of '?' see in the SQL statement */
  35324. + int isExplain /* True if the EXPLAIN keywords is present */
  35325. +){
  35326. + int n;
  35327. +
  35328. + assert( p!=0 );
  35329. + assert( p->magic==VDBE_MAGIC_INIT );
  35330. +
  35331. + /* Add a HALT instruction to the very end of the program.
  35332. + */
  35333. + if( p->nOp==0 || (p->aOp && p->aOp[p->nOp-1].opcode!=OP_Halt) ){
  35334. + sqliteVdbeAddOp(p, OP_Halt, 0, 0);
  35335. + }
  35336. +
  35337. + /* No instruction ever pushes more than a single element onto the
  35338. + ** stack. And the stack never grows on successive executions of the
  35339. + ** same loop. So the total number of instructions is an upper bound
  35340. + ** on the maximum stack depth required.
  35341. + **
  35342. + ** Allocation all the stack space we will ever need.
  35343. + */
  35344. + if( p->aStack==0 ){
  35345. + p->nVar = nVar;
  35346. + assert( nVar>=0 );
  35347. + n = isExplain ? 10 : p->nOp;
  35348. + p->aStack = sqliteMalloc(
  35349. + n*(sizeof(p->aStack[0]) + 2*sizeof(char*)) /* aStack and zArgv */
  35350. + + p->nVar*(sizeof(char*)+sizeof(int)+1) /* azVar, anVar, abVar */
  35351. + );
  35352. + p->zArgv = (char**)&p->aStack[n];
  35353. + p->azColName = (char**)&p->zArgv[n];
  35354. + p->azVar = (char**)&p->azColName[n];
  35355. + p->anVar = (int*)&p->azVar[p->nVar];
  35356. + p->abVar = (u8*)&p->anVar[p->nVar];
  35357. + }
  35358. +
  35359. + sqliteHashInit(&p->agg.hash, SQLITE_HASH_BINARY, 0);
  35360. + p->agg.pSearch = 0;
  35361. +#ifdef MEMORY_DEBUG
  35362. + if( sqliteOsFileExists("vdbe_trace") ){
  35363. + p->trace = stdout;
  35364. + }
  35365. +#endif
  35366. + p->pTos = &p->aStack[-1];
  35367. + p->pc = 0;
  35368. + p->rc = SQLITE_OK;
  35369. + p->uniqueCnt = 0;
  35370. + p->returnDepth = 0;
  35371. + p->errorAction = OE_Abort;
  35372. + p->undoTransOnError = 0;
  35373. + p->popStack = 0;
  35374. + p->explain |= isExplain;
  35375. + p->magic = VDBE_MAGIC_RUN;
  35376. +#ifdef VDBE_PROFILE
  35377. + {
  35378. + int i;
  35379. + for(i=0; i<p->nOp; i++){
  35380. + p->aOp[i].cnt = 0;
  35381. + p->aOp[i].cycles = 0;
  35382. + }
  35383. + }
  35384. +#endif
  35385. +}
  35386. +
  35387. +
  35388. +/*
  35389. +** Remove any elements that remain on the sorter for the VDBE given.
  35390. +*/
  35391. +void sqliteVdbeSorterReset(Vdbe *p){
  35392. + while( p->pSort ){
  35393. + Sorter *pSorter = p->pSort;
  35394. + p->pSort = pSorter->pNext;
  35395. + sqliteFree(pSorter->zKey);
  35396. + sqliteFree(pSorter->pData);
  35397. + sqliteFree(pSorter);
  35398. + }
  35399. +}
  35400. +
  35401. +/*
  35402. +** Reset an Agg structure. Delete all its contents.
  35403. +**
  35404. +** For installable aggregate functions, if the step function has been
  35405. +** called, make sure the finalizer function has also been called. The
  35406. +** finalizer might need to free memory that was allocated as part of its
  35407. +** private context. If the finalizer has not been called yet, call it
  35408. +** now.
  35409. +*/
  35410. +void sqliteVdbeAggReset(Agg *pAgg){
  35411. + int i;
  35412. + HashElem *p;
  35413. + for(p = sqliteHashFirst(&pAgg->hash); p; p = sqliteHashNext(p)){
  35414. + AggElem *pElem = sqliteHashData(p);
  35415. + assert( pAgg->apFunc!=0 );
  35416. + for(i=0; i<pAgg->nMem; i++){
  35417. + Mem *pMem = &pElem->aMem[i];
  35418. + if( pAgg->apFunc[i] && (pMem->flags & MEM_AggCtx)!=0 ){
  35419. + sqlite_func ctx;
  35420. + ctx.pFunc = pAgg->apFunc[i];
  35421. + ctx.s.flags = MEM_Null;
  35422. + ctx.pAgg = pMem->z;
  35423. + ctx.cnt = pMem->i;
  35424. + ctx.isStep = 0;
  35425. + ctx.isError = 0;
  35426. + (*pAgg->apFunc[i]->xFinalize)(&ctx);
  35427. + if( pMem->z!=0 && pMem->z!=pMem->zShort ){
  35428. + sqliteFree(pMem->z);
  35429. + }
  35430. + if( ctx.s.flags & MEM_Dyn ){
  35431. + sqliteFree(ctx.s.z);
  35432. + }
  35433. + }else if( pMem->flags & MEM_Dyn ){
  35434. + sqliteFree(pMem->z);
  35435. + }
  35436. + }
  35437. + sqliteFree(pElem);
  35438. + }
  35439. + sqliteHashClear(&pAgg->hash);
  35440. + sqliteFree(pAgg->apFunc);
  35441. + pAgg->apFunc = 0;
  35442. + pAgg->pCurrent = 0;
  35443. + pAgg->pSearch = 0;
  35444. + pAgg->nMem = 0;
  35445. +}
  35446. +
  35447. +/*
  35448. +** Delete a keylist
  35449. +*/
  35450. +void sqliteVdbeKeylistFree(Keylist *p){
  35451. + while( p ){
  35452. + Keylist *pNext = p->pNext;
  35453. + sqliteFree(p);
  35454. + p = pNext;
  35455. + }
  35456. +}
  35457. +
  35458. +/*
  35459. +** Close a cursor and release all the resources that cursor happens
  35460. +** to hold.
  35461. +*/
  35462. +void sqliteVdbeCleanupCursor(Cursor *pCx){
  35463. + if( pCx->pCursor ){
  35464. + sqliteBtreeCloseCursor(pCx->pCursor);
  35465. + }
  35466. + if( pCx->pBt ){
  35467. + sqliteBtreeClose(pCx->pBt);
  35468. + }
  35469. + sqliteFree(pCx->pData);
  35470. + memset(pCx, 0, sizeof(Cursor));
  35471. +}
  35472. +
  35473. +/*
  35474. +** Close all cursors
  35475. +*/
  35476. +static void closeAllCursors(Vdbe *p){
  35477. + int i;
  35478. + for(i=0; i<p->nCursor; i++){
  35479. + sqliteVdbeCleanupCursor(&p->aCsr[i]);
  35480. + }
  35481. + sqliteFree(p->aCsr);
  35482. + p->aCsr = 0;
  35483. + p->nCursor = 0;
  35484. +}
  35485. +
  35486. +/*
  35487. +** Clean up the VM after execution.
  35488. +**
  35489. +** This routine will automatically close any cursors, lists, and/or
  35490. +** sorters that were left open. It also deletes the values of
  35491. +** variables in the azVariable[] array.
  35492. +*/
  35493. +static void Cleanup(Vdbe *p){
  35494. + int i;
  35495. + if( p->aStack ){
  35496. + Mem *pTos = p->pTos;
  35497. + while( pTos>=p->aStack ){
  35498. + if( pTos->flags & MEM_Dyn ){
  35499. + sqliteFree(pTos->z);
  35500. + }
  35501. + pTos--;
  35502. + }
  35503. + p->pTos = pTos;
  35504. + }
  35505. + closeAllCursors(p);
  35506. + if( p->aMem ){
  35507. + for(i=0; i<p->nMem; i++){
  35508. + if( p->aMem[i].flags & MEM_Dyn ){
  35509. + sqliteFree(p->aMem[i].z);
  35510. + }
  35511. + }
  35512. + }
  35513. + sqliteFree(p->aMem);
  35514. + p->aMem = 0;
  35515. + p->nMem = 0;
  35516. + if( p->pList ){
  35517. + sqliteVdbeKeylistFree(p->pList);
  35518. + p->pList = 0;
  35519. + }
  35520. + sqliteVdbeSorterReset(p);
  35521. + if( p->pFile ){
  35522. + if( p->pFile!=stdin ) fclose(p->pFile);
  35523. + p->pFile = 0;
  35524. + }
  35525. + if( p->azField ){
  35526. + sqliteFree(p->azField);
  35527. + p->azField = 0;
  35528. + }
  35529. + p->nField = 0;
  35530. + if( p->zLine ){
  35531. + sqliteFree(p->zLine);
  35532. + p->zLine = 0;
  35533. + }
  35534. + p->nLineAlloc = 0;
  35535. + sqliteVdbeAggReset(&p->agg);
  35536. + if( p->aSet ){
  35537. + for(i=0; i<p->nSet; i++){
  35538. + sqliteHashClear(&p->aSet[i].hash);
  35539. + }
  35540. + }
  35541. + sqliteFree(p->aSet);
  35542. + p->aSet = 0;
  35543. + p->nSet = 0;
  35544. + if( p->keylistStack ){
  35545. + int ii;
  35546. + for(ii = 0; ii < p->keylistStackDepth; ii++){
  35547. + sqliteVdbeKeylistFree(p->keylistStack[ii]);
  35548. + }
  35549. + sqliteFree(p->keylistStack);
  35550. + p->keylistStackDepth = 0;
  35551. + p->keylistStack = 0;
  35552. + }
  35553. + sqliteFree(p->contextStack);
  35554. + p->contextStack = 0;
  35555. + sqliteFree(p->zErrMsg);
  35556. + p->zErrMsg = 0;
  35557. +}
  35558. +
  35559. +/*
  35560. +** Clean up a VDBE after execution but do not delete the VDBE just yet.
  35561. +** Write any error messages into *pzErrMsg. Return the result code.
  35562. +**
  35563. +** After this routine is run, the VDBE should be ready to be executed
  35564. +** again.
  35565. +*/
  35566. +int sqliteVdbeReset(Vdbe *p, char **pzErrMsg){
  35567. + sqlite *db = p->db;
  35568. + int i;
  35569. +
  35570. + if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
  35571. + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
  35572. + return SQLITE_MISUSE;
  35573. + }
  35574. + if( p->zErrMsg ){
  35575. + if( pzErrMsg && *pzErrMsg==0 ){
  35576. + *pzErrMsg = p->zErrMsg;
  35577. + }else{
  35578. + sqliteFree(p->zErrMsg);
  35579. + }
  35580. + p->zErrMsg = 0;
  35581. + }else if( p->rc ){
  35582. + sqliteSetString(pzErrMsg, sqlite_error_string(p->rc), (char*)0);
  35583. + }
  35584. + Cleanup(p);
  35585. + if( p->rc!=SQLITE_OK ){
  35586. + switch( p->errorAction ){
  35587. + case OE_Abort: {
  35588. + if( !p->undoTransOnError ){
  35589. + for(i=0; i<db->nDb; i++){
  35590. + if( db->aDb[i].pBt ){
  35591. + sqliteBtreeRollbackCkpt(db->aDb[i].pBt);
  35592. + }
  35593. + }
  35594. + break;
  35595. + }
  35596. + /* Fall through to ROLLBACK */
  35597. + }
  35598. + case OE_Rollback: {
  35599. + sqliteRollbackAll(db);
  35600. + db->flags &= ~SQLITE_InTrans;
  35601. + db->onError = OE_Default;
  35602. + break;
  35603. + }
  35604. + default: {
  35605. + if( p->undoTransOnError ){
  35606. + sqliteRollbackAll(db);
  35607. + db->flags &= ~SQLITE_InTrans;
  35608. + db->onError = OE_Default;
  35609. + }
  35610. + break;
  35611. + }
  35612. + }
  35613. + sqliteRollbackInternalChanges(db);
  35614. + }
  35615. + for(i=0; i<db->nDb; i++){
  35616. + if( db->aDb[i].pBt && db->aDb[i].inTrans==2 ){
  35617. + sqliteBtreeCommitCkpt(db->aDb[i].pBt);
  35618. + db->aDb[i].inTrans = 1;
  35619. + }
  35620. + }
  35621. + assert( p->pTos<&p->aStack[p->pc] || sqlite_malloc_failed==1 );
  35622. +#ifdef VDBE_PROFILE
  35623. + {
  35624. + FILE *out = fopen("vdbe_profile.out", "a");
  35625. + if( out ){
  35626. + int i;
  35627. + fprintf(out, "---- ");
  35628. + for(i=0; i<p->nOp; i++){
  35629. + fprintf(out, "%02x", p->aOp[i].opcode);
  35630. + }
  35631. + fprintf(out, "\n");
  35632. + for(i=0; i<p->nOp; i++){
  35633. + fprintf(out, "%6d %10lld %8lld ",
  35634. + p->aOp[i].cnt,
  35635. + p->aOp[i].cycles,
  35636. + p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  35637. + );
  35638. + sqliteVdbePrintOp(out, i, &p->aOp[i]);
  35639. + }
  35640. + fclose(out);
  35641. + }
  35642. + }
  35643. +#endif
  35644. + p->magic = VDBE_MAGIC_INIT;
  35645. + return p->rc;
  35646. +}
  35647. +
  35648. +/*
  35649. +** Clean up and delete a VDBE after execution. Return an integer which is
  35650. +** the result code. Write any error message text into *pzErrMsg.
  35651. +*/
  35652. +int sqliteVdbeFinalize(Vdbe *p, char **pzErrMsg){
  35653. + int rc;
  35654. + sqlite *db;
  35655. +
  35656. + if( p->magic!=VDBE_MAGIC_RUN && p->magic!=VDBE_MAGIC_HALT ){
  35657. + sqliteSetString(pzErrMsg, sqlite_error_string(SQLITE_MISUSE), (char*)0);
  35658. + return SQLITE_MISUSE;
  35659. + }
  35660. + db = p->db;
  35661. + rc = sqliteVdbeReset(p, pzErrMsg);
  35662. + sqliteVdbeDelete(p);
  35663. + if( db->want_to_close && db->pVdbe==0 ){
  35664. + sqlite_close(db);
  35665. + }
  35666. + if( rc==SQLITE_SCHEMA ){
  35667. + sqliteResetInternalSchema(db, 0);
  35668. + }
  35669. + return rc;
  35670. +}
  35671. +
  35672. +/*
  35673. +** Set the values of all variables. Variable $1 in the original SQL will
  35674. +** be the string azValue[0]. $2 will have the value azValue[1]. And
  35675. +** so forth. If a value is out of range (for example $3 when nValue==2)
  35676. +** then its value will be NULL.
  35677. +**
  35678. +** This routine overrides any prior call.
  35679. +*/
  35680. +int sqlite_bind(sqlite_vm *pVm, int i, const char *zVal, int len, int copy){
  35681. + Vdbe *p = (Vdbe*)pVm;
  35682. + if( p->magic!=VDBE_MAGIC_RUN || p->pc!=0 ){
  35683. + return SQLITE_MISUSE;
  35684. + }
  35685. + if( i<1 || i>p->nVar ){
  35686. + return SQLITE_RANGE;
  35687. + }
  35688. + i--;
  35689. + if( p->abVar[i] ){
  35690. + sqliteFree(p->azVar[i]);
  35691. + }
  35692. + if( zVal==0 ){
  35693. + copy = 0;
  35694. + len = 0;
  35695. + }
  35696. + if( len<0 ){
  35697. + len = strlen(zVal)+1;
  35698. + }
  35699. + if( copy ){
  35700. + p->azVar[i] = sqliteMalloc( len );
  35701. + if( p->azVar[i] ) memcpy(p->azVar[i], zVal, len);
  35702. + }else{
  35703. + p->azVar[i] = (char*)zVal;
  35704. + }
  35705. + p->abVar[i] = copy;
  35706. + p->anVar[i] = len;
  35707. + return SQLITE_OK;
  35708. +}
  35709. +
  35710. +
  35711. +/*
  35712. +** Delete an entire VDBE.
  35713. +*/
  35714. +void sqliteVdbeDelete(Vdbe *p){
  35715. + int i;
  35716. + if( p==0 ) return;
  35717. + Cleanup(p);
  35718. + if( p->pPrev ){
  35719. + p->pPrev->pNext = p->pNext;
  35720. + }else{
  35721. + assert( p->db->pVdbe==p );
  35722. + p->db->pVdbe = p->pNext;
  35723. + }
  35724. + if( p->pNext ){
  35725. + p->pNext->pPrev = p->pPrev;
  35726. + }
  35727. + p->pPrev = p->pNext = 0;
  35728. + if( p->nOpAlloc==0 ){
  35729. + p->aOp = 0;
  35730. + p->nOp = 0;
  35731. + }
  35732. + for(i=0; i<p->nOp; i++){
  35733. + if( p->aOp[i].p3type==P3_DYNAMIC ){
  35734. + sqliteFree(p->aOp[i].p3);
  35735. + }
  35736. + }
  35737. + for(i=0; i<p->nVar; i++){
  35738. + if( p->abVar[i] ) sqliteFree(p->azVar[i]);
  35739. + }
  35740. + sqliteFree(p->aOp);
  35741. + sqliteFree(p->aLabel);
  35742. + sqliteFree(p->aStack);
  35743. + p->magic = VDBE_MAGIC_DEAD;
  35744. + sqliteFree(p);
  35745. +}
  35746. +
  35747. +/*
  35748. +** Convert an integer in between the native integer format and
  35749. +** the bigEndian format used as the record number for tables.
  35750. +**
  35751. +** The bigEndian format (most significant byte first) is used for
  35752. +** record numbers so that records will sort into the correct order
  35753. +** even though memcmp() is used to compare the keys. On machines
  35754. +** whose native integer format is little endian (ex: i486) the
  35755. +** order of bytes is reversed. On native big-endian machines
  35756. +** (ex: Alpha, Sparc, Motorola) the byte order is the same.
  35757. +**
  35758. +** This function is its own inverse. In other words
  35759. +**
  35760. +** X == byteSwap(byteSwap(X))
  35761. +*/
  35762. +int sqliteVdbeByteSwap(int x){
  35763. + union {
  35764. + char zBuf[sizeof(int)];
  35765. + int i;
  35766. + } ux;
  35767. + ux.zBuf[3] = x&0xff;
  35768. + ux.zBuf[2] = (x>>8)&0xff;
  35769. + ux.zBuf[1] = (x>>16)&0xff;
  35770. + ux.zBuf[0] = (x>>24)&0xff;
  35771. + return ux.i;
  35772. +}
  35773. +
  35774. +/*
  35775. +** If a MoveTo operation is pending on the given cursor, then do that
  35776. +** MoveTo now. Return an error code. If no MoveTo is pending, this
  35777. +** routine does nothing and returns SQLITE_OK.
  35778. +*/
  35779. +int sqliteVdbeCursorMoveto(Cursor *p){
  35780. + if( p->deferredMoveto ){
  35781. + int res;
  35782. + extern int sqlite_search_count;
  35783. + sqliteBtreeMoveto(p->pCursor, (char*)&p->movetoTarget, sizeof(int), &res);
  35784. + p->lastRecno = keyToInt(p->movetoTarget);
  35785. + p->recnoIsValid = res==0;
  35786. + if( res<0 ){
  35787. + sqliteBtreeNext(p->pCursor, &res);
  35788. + }
  35789. + sqlite_search_count++;
  35790. + p->deferredMoveto = 0;
  35791. + }
  35792. + return SQLITE_OK;
  35793. +}
  35794. --- /dev/null
  35795. +++ b/ext/sqlite/libsqlite/src/vdbe.c
  35796. @@ -0,0 +1,4921 @@
  35797. +/*
  35798. +** 2001 September 15
  35799. +**
  35800. +** The author disclaims copyright to this source code. In place of
  35801. +** a legal notice, here is a blessing:
  35802. +**
  35803. +** May you do good and not evil.
  35804. +** May you find forgiveness for yourself and forgive others.
  35805. +** May you share freely, never taking more than you give.
  35806. +**
  35807. +*************************************************************************
  35808. +** The code in this file implements execution method of the
  35809. +** Virtual Database Engine (VDBE). A separate file ("vdbeaux.c")
  35810. +** handles housekeeping details such as creating and deleting
  35811. +** VDBE instances. This file is solely interested in executing
  35812. +** the VDBE program.
  35813. +**
  35814. +** In the external interface, an "sqlite_vm*" is an opaque pointer
  35815. +** to a VDBE.
  35816. +**
  35817. +** The SQL parser generates a program which is then executed by
  35818. +** the VDBE to do the work of the SQL statement. VDBE programs are
  35819. +** similar in form to assembly language. The program consists of
  35820. +** a linear sequence of operations. Each operation has an opcode
  35821. +** and 3 operands. Operands P1 and P2 are integers. Operand P3
  35822. +** is a null-terminated string. The P2 operand must be non-negative.
  35823. +** Opcodes will typically ignore one or more operands. Many opcodes
  35824. +** ignore all three operands.
  35825. +**
  35826. +** Computation results are stored on a stack. Each entry on the
  35827. +** stack is either an integer, a null-terminated string, a floating point
  35828. +** number, or the SQL "NULL" value. An inplicit conversion from one
  35829. +** type to the other occurs as necessary.
  35830. +**
  35831. +** Most of the code in this file is taken up by the sqliteVdbeExec()
  35832. +** function which does the work of interpreting a VDBE program.
  35833. +** But other routines are also provided to help in building up
  35834. +** a program instruction by instruction.
  35835. +**
  35836. +** Various scripts scan this source file in order to generate HTML
  35837. +** documentation, headers files, or other derived files. The formatting
  35838. +** of the code in this file is, therefore, important. See other comments
  35839. +** in this file for details. If in doubt, do not deviate from existing
  35840. +** commenting and indentation practices when changing or adding code.
  35841. +**
  35842. +** $Id$
  35843. +*/
  35844. +#include "sqliteInt.h"
  35845. +#include "os.h"
  35846. +#include <ctype.h>
  35847. +#include "vdbeInt.h"
  35848. +
  35849. +/*
  35850. +** The following global variable is incremented every time a cursor
  35851. +** moves, either by the OP_MoveTo or the OP_Next opcode. The test
  35852. +** procedures use this information to make sure that indices are
  35853. +** working correctly. This variable has no function other than to
  35854. +** help verify the correct operation of the library.
  35855. +*/
  35856. +int sqlite_search_count = 0;
  35857. +
  35858. +/*
  35859. +** When this global variable is positive, it gets decremented once before
  35860. +** each instruction in the VDBE. When reaches zero, the SQLITE_Interrupt
  35861. +** of the db.flags field is set in order to simulate an interrupt.
  35862. +**
  35863. +** This facility is used for testing purposes only. It does not function
  35864. +** in an ordinary build.
  35865. +*/
  35866. +int sqlite_interrupt_count = 0;
  35867. +
  35868. +/*
  35869. +** Advance the virtual machine to the next output row.
  35870. +**
  35871. +** The return vale will be either SQLITE_BUSY, SQLITE_DONE,
  35872. +** SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE.
  35873. +**
  35874. +** SQLITE_BUSY means that the virtual machine attempted to open
  35875. +** a locked database and there is no busy callback registered.
  35876. +** Call sqlite_step() again to retry the open. *pN is set to 0
  35877. +** and *pazColName and *pazValue are both set to NULL.
  35878. +**
  35879. +** SQLITE_DONE means that the virtual machine has finished
  35880. +** executing. sqlite_step() should not be called again on this
  35881. +** virtual machine. *pN and *pazColName are set appropriately
  35882. +** but *pazValue is set to NULL.
  35883. +**
  35884. +** SQLITE_ROW means that the virtual machine has generated another
  35885. +** row of the result set. *pN is set to the number of columns in
  35886. +** the row. *pazColName is set to the names of the columns followed
  35887. +** by the column datatypes. *pazValue is set to the values of each
  35888. +** column in the row. The value of the i-th column is (*pazValue)[i].
  35889. +** The name of the i-th column is (*pazColName)[i] and the datatype
  35890. +** of the i-th column is (*pazColName)[i+*pN].
  35891. +**
  35892. +** SQLITE_ERROR means that a run-time error (such as a constraint
  35893. +** violation) has occurred. The details of the error will be returned
  35894. +** by the next call to sqlite_finalize(). sqlite_step() should not
  35895. +** be called again on the VM.
  35896. +**
  35897. +** SQLITE_MISUSE means that the this routine was called inappropriately.
  35898. +** Perhaps it was called on a virtual machine that had already been
  35899. +** finalized or on one that had previously returned SQLITE_ERROR or
  35900. +** SQLITE_DONE. Or it could be the case the the same database connection
  35901. +** is being used simulataneously by two or more threads.
  35902. +*/
  35903. +int sqlite_step(
  35904. + sqlite_vm *pVm, /* The virtual machine to execute */
  35905. + int *pN, /* OUT: Number of columns in result */
  35906. + const char ***pazValue, /* OUT: Column data */
  35907. + const char ***pazColName /* OUT: Column names and datatypes */
  35908. +){
  35909. + Vdbe *p = (Vdbe*)pVm;
  35910. + sqlite *db;
  35911. + int rc;
  35912. +
  35913. + if( !p || p->magic!=VDBE_MAGIC_RUN ){
  35914. + return SQLITE_MISUSE;
  35915. + }
  35916. + db = p->db;
  35917. + if( sqliteSafetyOn(db) ){
  35918. + p->rc = SQLITE_MISUSE;
  35919. + return SQLITE_MISUSE;
  35920. + }
  35921. + if( p->explain ){
  35922. + rc = sqliteVdbeList(p);
  35923. + }else{
  35924. + rc = sqliteVdbeExec(p);
  35925. + }
  35926. + if( rc==SQLITE_DONE || rc==SQLITE_ROW ){
  35927. + if( pazColName ) *pazColName = (const char**)p->azColName;
  35928. + if( pN ) *pN = p->nResColumn;
  35929. + }else{
  35930. + if( pazColName) *pazColName = 0;
  35931. + if( pN ) *pN = 0;
  35932. + }
  35933. + if( pazValue ){
  35934. + if( rc==SQLITE_ROW ){
  35935. + *pazValue = (const char**)p->azResColumn;
  35936. + }else{
  35937. + *pazValue = 0;
  35938. + }
  35939. + }
  35940. + if( sqliteSafetyOff(db) ){
  35941. + return SQLITE_MISUSE;
  35942. + }
  35943. + return rc;
  35944. +}
  35945. +
  35946. +/*
  35947. +** Insert a new aggregate element and make it the element that
  35948. +** has focus.
  35949. +**
  35950. +** Return 0 on success and 1 if memory is exhausted.
  35951. +*/
  35952. +static int AggInsert(Agg *p, char *zKey, int nKey){
  35953. + AggElem *pElem, *pOld;
  35954. + int i;
  35955. + Mem *pMem;
  35956. + pElem = sqliteMalloc( sizeof(AggElem) + nKey +
  35957. + (p->nMem-1)*sizeof(pElem->aMem[0]) );
  35958. + if( pElem==0 ) return 1;
  35959. + pElem->zKey = (char*)&pElem->aMem[p->nMem];
  35960. + memcpy(pElem->zKey, zKey, nKey);
  35961. + pElem->nKey = nKey;
  35962. + pOld = sqliteHashInsert(&p->hash, pElem->zKey, pElem->nKey, pElem);
  35963. + if( pOld!=0 ){
  35964. + assert( pOld==pElem ); /* Malloc failed on insert */
  35965. + sqliteFree(pOld);
  35966. + return 0;
  35967. + }
  35968. + for(i=0, pMem=pElem->aMem; i<p->nMem; i++, pMem++){
  35969. + pMem->flags = MEM_Null;
  35970. + }
  35971. + p->pCurrent = pElem;
  35972. + return 0;
  35973. +}
  35974. +
  35975. +/*
  35976. +** Get the AggElem currently in focus
  35977. +*/
  35978. +#define AggInFocus(P) ((P).pCurrent ? (P).pCurrent : _AggInFocus(&(P)))
  35979. +static AggElem *_AggInFocus(Agg *p){
  35980. + HashElem *pElem = sqliteHashFirst(&p->hash);
  35981. + if( pElem==0 ){
  35982. + AggInsert(p,"",1);
  35983. + pElem = sqliteHashFirst(&p->hash);
  35984. + }
  35985. + return pElem ? sqliteHashData(pElem) : 0;
  35986. +}
  35987. +
  35988. +/*
  35989. +** Convert the given stack entity into a string if it isn't one
  35990. +** already.
  35991. +*/
  35992. +#define Stringify(P) if(((P)->flags & MEM_Str)==0){hardStringify(P);}
  35993. +static int hardStringify(Mem *pStack){
  35994. + int fg = pStack->flags;
  35995. + if( fg & MEM_Real ){
  35996. + sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%.15g",pStack->r);
  35997. + }else if( fg & MEM_Int ){
  35998. + sqlite_snprintf(sizeof(pStack->zShort),pStack->zShort,"%d",pStack->i);
  35999. + }else{
  36000. + pStack->zShort[0] = 0;
  36001. + }
  36002. + pStack->z = pStack->zShort;
  36003. + pStack->n = strlen(pStack->zShort)+1;
  36004. + pStack->flags = MEM_Str | MEM_Short;
  36005. + return 0;
  36006. +}
  36007. +
  36008. +/*
  36009. +** Convert the given stack entity into a string that has been obtained
  36010. +** from sqliteMalloc(). This is different from Stringify() above in that
  36011. +** Stringify() will use the NBFS bytes of static string space if the string
  36012. +** will fit but this routine always mallocs for space.
  36013. +** Return non-zero if we run out of memory.
  36014. +*/
  36015. +#define Dynamicify(P) (((P)->flags & MEM_Dyn)==0 ? hardDynamicify(P):0)
  36016. +static int hardDynamicify(Mem *pStack){
  36017. + int fg = pStack->flags;
  36018. + char *z;
  36019. + if( (fg & MEM_Str)==0 ){
  36020. + hardStringify(pStack);
  36021. + }
  36022. + assert( (fg & MEM_Dyn)==0 );
  36023. + z = sqliteMallocRaw( pStack->n );
  36024. + if( z==0 ) return 1;
  36025. + memcpy(z, pStack->z, pStack->n);
  36026. + pStack->z = z;
  36027. + pStack->flags |= MEM_Dyn;
  36028. + return 0;
  36029. +}
  36030. +
  36031. +/*
  36032. +** An ephemeral string value (signified by the MEM_Ephem flag) contains
  36033. +** a pointer to a dynamically allocated string where some other entity
  36034. +** is responsible for deallocating that string. Because the stack entry
  36035. +** does not control the string, it might be deleted without the stack
  36036. +** entry knowing it.
  36037. +**
  36038. +** This routine converts an ephemeral string into a dynamically allocated
  36039. +** string that the stack entry itself controls. In other words, it
  36040. +** converts an MEM_Ephem string into an MEM_Dyn string.
  36041. +*/
  36042. +#define Deephemeralize(P) \
  36043. + if( ((P)->flags&MEM_Ephem)!=0 && hardDeephem(P) ){ goto no_mem;}
  36044. +static int hardDeephem(Mem *pStack){
  36045. + char *z;
  36046. + assert( (pStack->flags & MEM_Ephem)!=0 );
  36047. + z = sqliteMallocRaw( pStack->n );
  36048. + if( z==0 ) return 1;
  36049. + memcpy(z, pStack->z, pStack->n);
  36050. + pStack->z = z;
  36051. + pStack->flags &= ~MEM_Ephem;
  36052. + pStack->flags |= MEM_Dyn;
  36053. + return 0;
  36054. +}
  36055. +
  36056. +/*
  36057. +** Release the memory associated with the given stack level. This
  36058. +** leaves the Mem.flags field in an inconsistent state.
  36059. +*/
  36060. +#define Release(P) if((P)->flags&MEM_Dyn){ sqliteFree((P)->z); }
  36061. +
  36062. +/*
  36063. +** Pop the stack N times.
  36064. +*/
  36065. +static void popStack(Mem **ppTos, int N){
  36066. + Mem *pTos = *ppTos;
  36067. + while( N>0 ){
  36068. + N--;
  36069. + Release(pTos);
  36070. + pTos--;
  36071. + }
  36072. + *ppTos = pTos;
  36073. +}
  36074. +
  36075. +/*
  36076. +** Return TRUE if zNum is a 32-bit signed integer and write
  36077. +** the value of the integer into *pNum. If zNum is not an integer
  36078. +** or is an integer that is too large to be expressed with just 32
  36079. +** bits, then return false.
  36080. +**
  36081. +** Under Linux (RedHat 7.2) this routine is much faster than atoi()
  36082. +** for converting strings into integers.
  36083. +*/
  36084. +static int toInt(const char *zNum, int *pNum){
  36085. + int v = 0;
  36086. + int neg;
  36087. + int i, c;
  36088. + if( *zNum=='-' ){
  36089. + neg = 1;
  36090. + zNum++;
  36091. + }else if( *zNum=='+' ){
  36092. + neg = 0;
  36093. + zNum++;
  36094. + }else{
  36095. + neg = 0;
  36096. + }
  36097. + for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
  36098. + v = v*10 + c - '0';
  36099. + }
  36100. + *pNum = neg ? -v : v;
  36101. + return c==0 && i>0 && (i<10 || (i==10 && memcmp(zNum,"2147483647",10)<=0));
  36102. +}
  36103. +
  36104. +/*
  36105. +** Convert the given stack entity into a integer if it isn't one
  36106. +** already.
  36107. +**
  36108. +** Any prior string or real representation is invalidated.
  36109. +** NULLs are converted into 0.
  36110. +*/
  36111. +#define Integerify(P) if(((P)->flags&MEM_Int)==0){ hardIntegerify(P); }
  36112. +static void hardIntegerify(Mem *pStack){
  36113. + if( pStack->flags & MEM_Real ){
  36114. + pStack->i = (int)pStack->r;
  36115. + Release(pStack);
  36116. + }else if( pStack->flags & MEM_Str ){
  36117. + toInt(pStack->z, &pStack->i);
  36118. + Release(pStack);
  36119. + }else{
  36120. + pStack->i = 0;
  36121. + }
  36122. + pStack->flags = MEM_Int;
  36123. +}
  36124. +
  36125. +/*
  36126. +** Get a valid Real representation for the given stack element.
  36127. +**
  36128. +** Any prior string or integer representation is retained.
  36129. +** NULLs are converted into 0.0.
  36130. +*/
  36131. +#define Realify(P) if(((P)->flags&MEM_Real)==0){ hardRealify(P); }
  36132. +static void hardRealify(Mem *pStack){
  36133. + if( pStack->flags & MEM_Str ){
  36134. + pStack->r = sqliteAtoF(pStack->z, 0);
  36135. + }else if( pStack->flags & MEM_Int ){
  36136. + pStack->r = pStack->i;
  36137. + }else{
  36138. + pStack->r = 0.0;
  36139. + }
  36140. + pStack->flags |= MEM_Real;
  36141. +}
  36142. +
  36143. +/*
  36144. +** The parameters are pointers to the head of two sorted lists
  36145. +** of Sorter structures. Merge these two lists together and return
  36146. +** a single sorted list. This routine forms the core of the merge-sort
  36147. +** algorithm.
  36148. +**
  36149. +** In the case of a tie, left sorts in front of right.
  36150. +*/
  36151. +static Sorter *Merge(Sorter *pLeft, Sorter *pRight){
  36152. + Sorter sHead;
  36153. + Sorter *pTail;
  36154. + pTail = &sHead;
  36155. + pTail->pNext = 0;
  36156. + while( pLeft && pRight ){
  36157. + int c = sqliteSortCompare(pLeft->zKey, pRight->zKey);
  36158. + if( c<=0 ){
  36159. + pTail->pNext = pLeft;
  36160. + pLeft = pLeft->pNext;
  36161. + }else{
  36162. + pTail->pNext = pRight;
  36163. + pRight = pRight->pNext;
  36164. + }
  36165. + pTail = pTail->pNext;
  36166. + }
  36167. + if( pLeft ){
  36168. + pTail->pNext = pLeft;
  36169. + }else if( pRight ){
  36170. + pTail->pNext = pRight;
  36171. + }
  36172. + return sHead.pNext;
  36173. +}
  36174. +
  36175. +/*
  36176. +** The following routine works like a replacement for the standard
  36177. +** library routine fgets(). The difference is in how end-of-line (EOL)
  36178. +** is handled. Standard fgets() uses LF for EOL under unix, CRLF
  36179. +** under windows, and CR under mac. This routine accepts any of these
  36180. +** character sequences as an EOL mark. The EOL mark is replaced by
  36181. +** a single LF character in zBuf.
  36182. +*/
  36183. +static char *vdbe_fgets(char *zBuf, int nBuf, FILE *in){
  36184. + int i, c;
  36185. + for(i=0; i<nBuf-1 && (c=getc(in))!=EOF; i++){
  36186. + zBuf[i] = c;
  36187. + if( c=='\r' || c=='\n' ){
  36188. + if( c=='\r' ){
  36189. + zBuf[i] = '\n';
  36190. + c = getc(in);
  36191. + if( c!=EOF && c!='\n' ) ungetc(c, in);
  36192. + }
  36193. + i++;
  36194. + break;
  36195. + }
  36196. + }
  36197. + zBuf[i] = 0;
  36198. + return i>0 ? zBuf : 0;
  36199. +}
  36200. +
  36201. +/*
  36202. +** Make sure there is space in the Vdbe structure to hold at least
  36203. +** mxCursor cursors. If there is not currently enough space, then
  36204. +** allocate more.
  36205. +**
  36206. +** If a memory allocation error occurs, return 1. Return 0 if
  36207. +** everything works.
  36208. +*/
  36209. +static int expandCursorArraySize(Vdbe *p, int mxCursor){
  36210. + if( mxCursor>=p->nCursor ){
  36211. + Cursor *aCsr = sqliteRealloc( p->aCsr, (mxCursor+1)*sizeof(Cursor) );
  36212. + if( aCsr==0 ) return 1;
  36213. + p->aCsr = aCsr;
  36214. + memset(&p->aCsr[p->nCursor], 0, sizeof(Cursor)*(mxCursor+1-p->nCursor));
  36215. + p->nCursor = mxCursor+1;
  36216. + }
  36217. + return 0;
  36218. +}
  36219. +
  36220. +#ifdef VDBE_PROFILE
  36221. +/*
  36222. +** The following routine only works on pentium-class processors.
  36223. +** It uses the RDTSC opcode to read cycle count value out of the
  36224. +** processor and returns that value. This can be used for high-res
  36225. +** profiling.
  36226. +*/
  36227. +__inline__ unsigned long long int hwtime(void){
  36228. + unsigned long long int x;
  36229. + __asm__("rdtsc\n\t"
  36230. + "mov %%edx, %%ecx\n\t"
  36231. + :"=A" (x));
  36232. + return x;
  36233. +}
  36234. +#endif
  36235. +
  36236. +/*
  36237. +** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
  36238. +** sqlite_interrupt() routine has been called. If it has been, then
  36239. +** processing of the VDBE program is interrupted.
  36240. +**
  36241. +** This macro added to every instruction that does a jump in order to
  36242. +** implement a loop. This test used to be on every single instruction,
  36243. +** but that meant we more testing that we needed. By only testing the
  36244. +** flag on jump instructions, we get a (small) speed improvement.
  36245. +*/
  36246. +#define CHECK_FOR_INTERRUPT \
  36247. + if( db->flags & SQLITE_Interrupt ) goto abort_due_to_interrupt;
  36248. +
  36249. +
  36250. +/*
  36251. +** Execute as much of a VDBE program as we can then return.
  36252. +**
  36253. +** sqliteVdbeMakeReady() must be called before this routine in order to
  36254. +** close the program with a final OP_Halt and to set up the callbacks
  36255. +** and the error message pointer.
  36256. +**
  36257. +** Whenever a row or result data is available, this routine will either
  36258. +** invoke the result callback (if there is one) or return with
  36259. +** SQLITE_ROW.
  36260. +**
  36261. +** If an attempt is made to open a locked database, then this routine
  36262. +** will either invoke the busy callback (if there is one) or it will
  36263. +** return SQLITE_BUSY.
  36264. +**
  36265. +** If an error occurs, an error message is written to memory obtained
  36266. +** from sqliteMalloc() and p->zErrMsg is made to point to that memory.
  36267. +** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
  36268. +**
  36269. +** If the callback ever returns non-zero, then the program exits
  36270. +** immediately. There will be no error message but the p->rc field is
  36271. +** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
  36272. +**
  36273. +** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
  36274. +** routine to return SQLITE_ERROR.
  36275. +**
  36276. +** Other fatal errors return SQLITE_ERROR.
  36277. +**
  36278. +** After this routine has finished, sqliteVdbeFinalize() should be
  36279. +** used to clean up the mess that was left behind.
  36280. +*/
  36281. +int sqliteVdbeExec(
  36282. + Vdbe *p /* The VDBE */
  36283. +){
  36284. + int pc; /* The program counter */
  36285. + Op *pOp; /* Current operation */
  36286. + int rc = SQLITE_OK; /* Value to return */
  36287. + sqlite *db = p->db; /* The database */
  36288. + Mem *pTos; /* Top entry in the operand stack */
  36289. + char zBuf[100]; /* Space to sprintf() an integer */
  36290. +#ifdef VDBE_PROFILE
  36291. + unsigned long long start; /* CPU clock count at start of opcode */
  36292. + int origPc; /* Program counter at start of opcode */
  36293. +#endif
  36294. +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  36295. + int nProgressOps = 0; /* Opcodes executed since progress callback. */
  36296. +#endif
  36297. +
  36298. + if( p->magic!=VDBE_MAGIC_RUN ) return SQLITE_MISUSE;
  36299. + assert( db->magic==SQLITE_MAGIC_BUSY );
  36300. + assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  36301. + p->rc = SQLITE_OK;
  36302. + assert( p->explain==0 );
  36303. + if( sqlite_malloc_failed ) goto no_mem;
  36304. + pTos = p->pTos;
  36305. + if( p->popStack ){
  36306. + popStack(&pTos, p->popStack);
  36307. + p->popStack = 0;
  36308. + }
  36309. + CHECK_FOR_INTERRUPT;
  36310. + for(pc=p->pc; rc==SQLITE_OK; pc++){
  36311. + assert( pc>=0 && pc<p->nOp );
  36312. + assert( pTos<=&p->aStack[pc] );
  36313. +#ifdef VDBE_PROFILE
  36314. + origPc = pc;
  36315. + start = hwtime();
  36316. +#endif
  36317. + pOp = &p->aOp[pc];
  36318. +
  36319. + /* Only allow tracing if NDEBUG is not defined.
  36320. + */
  36321. +#ifndef NDEBUG
  36322. + if( p->trace ){
  36323. + sqliteVdbePrintOp(p->trace, pc, pOp);
  36324. + }
  36325. +#endif
  36326. +
  36327. + /* Check to see if we need to simulate an interrupt. This only happens
  36328. + ** if we have a special test build.
  36329. + */
  36330. +#ifdef SQLITE_TEST
  36331. + if( sqlite_interrupt_count>0 ){
  36332. + sqlite_interrupt_count--;
  36333. + if( sqlite_interrupt_count==0 ){
  36334. + sqlite_interrupt(db);
  36335. + }
  36336. + }
  36337. +#endif
  36338. +
  36339. +#ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  36340. + /* Call the progress callback if it is configured and the required number
  36341. + ** of VDBE ops have been executed (either since this invocation of
  36342. + ** sqliteVdbeExec() or since last time the progress callback was called).
  36343. + ** If the progress callback returns non-zero, exit the virtual machine with
  36344. + ** a return code SQLITE_ABORT.
  36345. + */
  36346. + if( db->xProgress ){
  36347. + if( db->nProgressOps==nProgressOps ){
  36348. + if( db->xProgress(db->pProgressArg)!=0 ){
  36349. + rc = SQLITE_ABORT;
  36350. + continue; /* skip to the next iteration of the for loop */
  36351. + }
  36352. + nProgressOps = 0;
  36353. + }
  36354. + nProgressOps++;
  36355. + }
  36356. +#endif
  36357. +
  36358. + switch( pOp->opcode ){
  36359. +
  36360. +/*****************************************************************************
  36361. +** What follows is a massive switch statement where each case implements a
  36362. +** separate instruction in the virtual machine. If we follow the usual
  36363. +** indentation conventions, each case should be indented by 6 spaces. But
  36364. +** that is a lot of wasted space on the left margin. So the code within
  36365. +** the switch statement will break with convention and be flush-left. Another
  36366. +** big comment (similar to this one) will mark the point in the code where
  36367. +** we transition back to normal indentation.
  36368. +**
  36369. +** The formatting of each case is important. The makefile for SQLite
  36370. +** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  36371. +** file looking for lines that begin with "case OP_". The opcodes.h files
  36372. +** will be filled with #defines that give unique integer values to each
  36373. +** opcode and the opcodes.c file is filled with an array of strings where
  36374. +** each string is the symbolic name for the corresponding opcode.
  36375. +**
  36376. +** Documentation about VDBE opcodes is generated by scanning this file
  36377. +** for lines of that contain "Opcode:". That line and all subsequent
  36378. +** comment lines are used in the generation of the opcode.html documentation
  36379. +** file.
  36380. +**
  36381. +** SUMMARY:
  36382. +**
  36383. +** Formatting is important to scripts that scan this file.
  36384. +** Do not deviate from the formatting style currently in use.
  36385. +**
  36386. +*****************************************************************************/
  36387. +
  36388. +/* Opcode: Goto * P2 *
  36389. +**
  36390. +** An unconditional jump to address P2.
  36391. +** The next instruction executed will be
  36392. +** the one at index P2 from the beginning of
  36393. +** the program.
  36394. +*/
  36395. +case OP_Goto: {
  36396. + CHECK_FOR_INTERRUPT;
  36397. + pc = pOp->p2 - 1;
  36398. + break;
  36399. +}
  36400. +
  36401. +/* Opcode: Gosub * P2 *
  36402. +**
  36403. +** Push the current address plus 1 onto the return address stack
  36404. +** and then jump to address P2.
  36405. +**
  36406. +** The return address stack is of limited depth. If too many
  36407. +** OP_Gosub operations occur without intervening OP_Returns, then
  36408. +** the return address stack will fill up and processing will abort
  36409. +** with a fatal error.
  36410. +*/
  36411. +case OP_Gosub: {
  36412. + if( p->returnDepth>=sizeof(p->returnStack)/sizeof(p->returnStack[0]) ){
  36413. + sqliteSetString(&p->zErrMsg, "return address stack overflow", (char*)0);
  36414. + p->rc = SQLITE_INTERNAL;
  36415. + return SQLITE_ERROR;
  36416. + }
  36417. + p->returnStack[p->returnDepth++] = pc+1;
  36418. + pc = pOp->p2 - 1;
  36419. + break;
  36420. +}
  36421. +
  36422. +/* Opcode: Return * * *
  36423. +**
  36424. +** Jump immediately to the next instruction after the last unreturned
  36425. +** OP_Gosub. If an OP_Return has occurred for all OP_Gosubs, then
  36426. +** processing aborts with a fatal error.
  36427. +*/
  36428. +case OP_Return: {
  36429. + if( p->returnDepth<=0 ){
  36430. + sqliteSetString(&p->zErrMsg, "return address stack underflow", (char*)0);
  36431. + p->rc = SQLITE_INTERNAL;
  36432. + return SQLITE_ERROR;
  36433. + }
  36434. + p->returnDepth--;
  36435. + pc = p->returnStack[p->returnDepth] - 1;
  36436. + break;
  36437. +}
  36438. +
  36439. +/* Opcode: Halt P1 P2 *
  36440. +**
  36441. +** Exit immediately. All open cursors, Lists, Sorts, etc are closed
  36442. +** automatically.
  36443. +**
  36444. +** P1 is the result code returned by sqlite_exec(). For a normal
  36445. +** halt, this should be SQLITE_OK (0). For errors, it can be some
  36446. +** other value. If P1!=0 then P2 will determine whether or not to
  36447. +** rollback the current transaction. Do not rollback if P2==OE_Fail.
  36448. +** Do the rollback if P2==OE_Rollback. If P2==OE_Abort, then back
  36449. +** out all changes that have occurred during this execution of the
  36450. +** VDBE, but do not rollback the transaction.
  36451. +**
  36452. +** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  36453. +** every program. So a jump past the last instruction of the program
  36454. +** is the same as executing Halt.
  36455. +*/
  36456. +case OP_Halt: {
  36457. + p->magic = VDBE_MAGIC_HALT;
  36458. + p->pTos = pTos;
  36459. + if( pOp->p1!=SQLITE_OK ){
  36460. + p->rc = pOp->p1;
  36461. + p->errorAction = pOp->p2;
  36462. + if( pOp->p3 ){
  36463. + sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
  36464. + }
  36465. + return SQLITE_ERROR;
  36466. + }else{
  36467. + p->rc = SQLITE_OK;
  36468. + return SQLITE_DONE;
  36469. + }
  36470. +}
  36471. +
  36472. +/* Opcode: Integer P1 * P3
  36473. +**
  36474. +** The integer value P1 is pushed onto the stack. If P3 is not zero
  36475. +** then it is assumed to be a string representation of the same integer.
  36476. +*/
  36477. +case OP_Integer: {
  36478. + pTos++;
  36479. + pTos->i = pOp->p1;
  36480. + pTos->flags = MEM_Int;
  36481. + if( pOp->p3 ){
  36482. + pTos->z = pOp->p3;
  36483. + pTos->flags |= MEM_Str | MEM_Static;
  36484. + pTos->n = strlen(pOp->p3)+1;
  36485. + }
  36486. + break;
  36487. +}
  36488. +
  36489. +/* Opcode: String * * P3
  36490. +**
  36491. +** The string value P3 is pushed onto the stack. If P3==0 then a
  36492. +** NULL is pushed onto the stack.
  36493. +*/
  36494. +case OP_String: {
  36495. + char *z = pOp->p3;
  36496. + pTos++;
  36497. + if( z==0 ){
  36498. + pTos->flags = MEM_Null;
  36499. + }else{
  36500. + pTos->z = z;
  36501. + pTos->n = strlen(z) + 1;
  36502. + pTos->flags = MEM_Str | MEM_Static;
  36503. + }
  36504. + break;
  36505. +}
  36506. +
  36507. +/* Opcode: Variable P1 * *
  36508. +**
  36509. +** Push the value of variable P1 onto the stack. A variable is
  36510. +** an unknown in the original SQL string as handed to sqlite_compile().
  36511. +** Any occurance of the '?' character in the original SQL is considered
  36512. +** a variable. Variables in the SQL string are number from left to
  36513. +** right beginning with 1. The values of variables are set using the
  36514. +** sqlite_bind() API.
  36515. +*/
  36516. +case OP_Variable: {
  36517. + int j = pOp->p1 - 1;
  36518. + pTos++;
  36519. + if( j>=0 && j<p->nVar && p->azVar[j]!=0 ){
  36520. + pTos->z = p->azVar[j];
  36521. + pTos->n = p->anVar[j];
  36522. + pTos->flags = MEM_Str | MEM_Static;
  36523. + }else{
  36524. + pTos->flags = MEM_Null;
  36525. + }
  36526. + break;
  36527. +}
  36528. +
  36529. +/* Opcode: Pop P1 * *
  36530. +**
  36531. +** P1 elements are popped off of the top of stack and discarded.
  36532. +*/
  36533. +case OP_Pop: {
  36534. + assert( pOp->p1>=0 );
  36535. + popStack(&pTos, pOp->p1);
  36536. + assert( pTos>=&p->aStack[-1] );
  36537. + break;
  36538. +}
  36539. +
  36540. +/* Opcode: Dup P1 P2 *
  36541. +**
  36542. +** A copy of the P1-th element of the stack
  36543. +** is made and pushed onto the top of the stack.
  36544. +** The top of the stack is element 0. So the
  36545. +** instruction "Dup 0 0 0" will make a copy of the
  36546. +** top of the stack.
  36547. +**
  36548. +** If the content of the P1-th element is a dynamically
  36549. +** allocated string, then a new copy of that string
  36550. +** is made if P2==0. If P2!=0, then just a pointer
  36551. +** to the string is copied.
  36552. +**
  36553. +** Also see the Pull instruction.
  36554. +*/
  36555. +case OP_Dup: {
  36556. + Mem *pFrom = &pTos[-pOp->p1];
  36557. + assert( pFrom<=pTos && pFrom>=p->aStack );
  36558. + pTos++;
  36559. + memcpy(pTos, pFrom, sizeof(*pFrom)-NBFS);
  36560. + if( pTos->flags & MEM_Str ){
  36561. + if( pOp->p2 && (pTos->flags & (MEM_Dyn|MEM_Ephem)) ){
  36562. + pTos->flags &= ~MEM_Dyn;
  36563. + pTos->flags |= MEM_Ephem;
  36564. + }else if( pTos->flags & MEM_Short ){
  36565. + memcpy(pTos->zShort, pFrom->zShort, pTos->n);
  36566. + pTos->z = pTos->zShort;
  36567. + }else if( (pTos->flags & MEM_Static)==0 ){
  36568. + pTos->z = sqliteMallocRaw(pFrom->n);
  36569. + if( sqlite_malloc_failed ) goto no_mem;
  36570. + memcpy(pTos->z, pFrom->z, pFrom->n);
  36571. + pTos->flags &= ~(MEM_Static|MEM_Ephem|MEM_Short);
  36572. + pTos->flags |= MEM_Dyn;
  36573. + }
  36574. + }
  36575. + break;
  36576. +}
  36577. +
  36578. +/* Opcode: Pull P1 * *
  36579. +**
  36580. +** The P1-th element is removed from its current location on
  36581. +** the stack and pushed back on top of the stack. The
  36582. +** top of the stack is element 0, so "Pull 0 0 0" is
  36583. +** a no-op. "Pull 1 0 0" swaps the top two elements of
  36584. +** the stack.
  36585. +**
  36586. +** See also the Dup instruction.
  36587. +*/
  36588. +case OP_Pull: {
  36589. + Mem *pFrom = &pTos[-pOp->p1];
  36590. + int i;
  36591. + Mem ts;
  36592. +
  36593. + ts = *pFrom;
  36594. + Deephemeralize(pTos);
  36595. + for(i=0; i<pOp->p1; i++, pFrom++){
  36596. + Deephemeralize(&pFrom[1]);
  36597. + *pFrom = pFrom[1];
  36598. + assert( (pFrom->flags & MEM_Ephem)==0 );
  36599. + if( pFrom->flags & MEM_Short ){
  36600. + assert( pFrom->flags & MEM_Str );
  36601. + assert( pFrom->z==pFrom[1].zShort );
  36602. + pFrom->z = pFrom->zShort;
  36603. + }
  36604. + }
  36605. + *pTos = ts;
  36606. + if( pTos->flags & MEM_Short ){
  36607. + assert( pTos->flags & MEM_Str );
  36608. + assert( pTos->z==pTos[-pOp->p1].zShort );
  36609. + pTos->z = pTos->zShort;
  36610. + }
  36611. + break;
  36612. +}
  36613. +
  36614. +/* Opcode: Push P1 * *
  36615. +**
  36616. +** Overwrite the value of the P1-th element down on the
  36617. +** stack (P1==0 is the top of the stack) with the value
  36618. +** of the top of the stack. Then pop the top of the stack.
  36619. +*/
  36620. +case OP_Push: {
  36621. + Mem *pTo = &pTos[-pOp->p1];
  36622. +
  36623. + assert( pTo>=p->aStack );
  36624. + Deephemeralize(pTos);
  36625. + Release(pTo);
  36626. + *pTo = *pTos;
  36627. + if( pTo->flags & MEM_Short ){
  36628. + assert( pTo->z==pTos->zShort );
  36629. + pTo->z = pTo->zShort;
  36630. + }
  36631. + pTos--;
  36632. + break;
  36633. +}
  36634. +
  36635. +
  36636. +/* Opcode: ColumnName P1 P2 P3
  36637. +**
  36638. +** P3 becomes the P1-th column name (first is 0). An array of pointers
  36639. +** to all column names is passed as the 4th parameter to the callback.
  36640. +** If P2==1 then this is the last column in the result set and thus the
  36641. +** number of columns in the result set will be P1. There must be at least
  36642. +** one OP_ColumnName with a P2==1 before invoking OP_Callback and the
  36643. +** number of columns specified in OP_Callback must one more than the P1
  36644. +** value of the OP_ColumnName that has P2==1.
  36645. +*/
  36646. +case OP_ColumnName: {
  36647. + assert( pOp->p1>=0 && pOp->p1<p->nOp );
  36648. + p->azColName[pOp->p1] = pOp->p3;
  36649. + p->nCallback = 0;
  36650. + if( pOp->p2 ) p->nResColumn = pOp->p1+1;
  36651. + break;
  36652. +}
  36653. +
  36654. +/* Opcode: Callback P1 * *
  36655. +**
  36656. +** Pop P1 values off the stack and form them into an array. Then
  36657. +** invoke the callback function using the newly formed array as the
  36658. +** 3rd parameter.
  36659. +*/
  36660. +case OP_Callback: {
  36661. + int i;
  36662. + char **azArgv = p->zArgv;
  36663. + Mem *pCol;
  36664. +
  36665. + pCol = &pTos[1-pOp->p1];
  36666. + assert( pCol>=p->aStack );
  36667. + for(i=0; i<pOp->p1; i++, pCol++){
  36668. + if( pCol->flags & MEM_Null ){
  36669. + azArgv[i] = 0;
  36670. + }else{
  36671. + Stringify(pCol);
  36672. + azArgv[i] = pCol->z;
  36673. + }
  36674. + }
  36675. + azArgv[i] = 0;
  36676. + p->nCallback++;
  36677. + p->azResColumn = azArgv;
  36678. + assert( p->nResColumn==pOp->p1 );
  36679. + p->popStack = pOp->p1;
  36680. + p->pc = pc + 1;
  36681. + p->pTos = pTos;
  36682. + return SQLITE_ROW;
  36683. +}
  36684. +
  36685. +/* Opcode: Concat P1 P2 P3
  36686. +**
  36687. +** Look at the first P1 elements of the stack. Append them all
  36688. +** together with the lowest element first. Use P3 as a separator.
  36689. +** Put the result on the top of the stack. The original P1 elements
  36690. +** are popped from the stack if P2==0 and retained if P2==1. If
  36691. +** any element of the stack is NULL, then the result is NULL.
  36692. +**
  36693. +** If P3 is NULL, then use no separator. When P1==1, this routine
  36694. +** makes a copy of the top stack element into memory obtained
  36695. +** from sqliteMalloc().
  36696. +*/
  36697. +case OP_Concat: {
  36698. + char *zNew;
  36699. + int nByte;
  36700. + int nField;
  36701. + int i, j;
  36702. + char *zSep;
  36703. + int nSep;
  36704. + Mem *pTerm;
  36705. +
  36706. + nField = pOp->p1;
  36707. + zSep = pOp->p3;
  36708. + if( zSep==0 ) zSep = "";
  36709. + nSep = strlen(zSep);
  36710. + assert( &pTos[1-nField] >= p->aStack );
  36711. + nByte = 1 - nSep;
  36712. + pTerm = &pTos[1-nField];
  36713. + for(i=0; i<nField; i++, pTerm++){
  36714. + if( pTerm->flags & MEM_Null ){
  36715. + nByte = -1;
  36716. + break;
  36717. + }else{
  36718. + Stringify(pTerm);
  36719. + nByte += pTerm->n - 1 + nSep;
  36720. + }
  36721. + }
  36722. + if( nByte<0 ){
  36723. + if( pOp->p2==0 ){
  36724. + popStack(&pTos, nField);
  36725. + }
  36726. + pTos++;
  36727. + pTos->flags = MEM_Null;
  36728. + break;
  36729. + }
  36730. + zNew = sqliteMallocRaw( nByte );
  36731. + if( zNew==0 ) goto no_mem;
  36732. + j = 0;
  36733. + pTerm = &pTos[1-nField];
  36734. + for(i=j=0; i<nField; i++, pTerm++){
  36735. + assert( pTerm->flags & MEM_Str );
  36736. + memcpy(&zNew[j], pTerm->z, pTerm->n-1);
  36737. + j += pTerm->n-1;
  36738. + if( nSep>0 && i<nField-1 ){
  36739. + memcpy(&zNew[j], zSep, nSep);
  36740. + j += nSep;
  36741. + }
  36742. + }
  36743. + zNew[j] = 0;
  36744. + if( pOp->p2==0 ){
  36745. + popStack(&pTos, nField);
  36746. + }
  36747. + pTos++;
  36748. + pTos->n = nByte;
  36749. + pTos->flags = MEM_Str|MEM_Dyn;
  36750. + pTos->z = zNew;
  36751. + break;
  36752. +}
  36753. +
  36754. +/* Opcode: Add * * *
  36755. +**
  36756. +** Pop the top two elements from the stack, add them together,
  36757. +** and push the result back onto the stack. If either element
  36758. +** is a string then it is converted to a double using the atof()
  36759. +** function before the addition.
  36760. +** If either operand is NULL, the result is NULL.
  36761. +*/
  36762. +/* Opcode: Multiply * * *
  36763. +**
  36764. +** Pop the top two elements from the stack, multiply them together,
  36765. +** and push the result back onto the stack. If either element
  36766. +** is a string then it is converted to a double using the atof()
  36767. +** function before the multiplication.
  36768. +** If either operand is NULL, the result is NULL.
  36769. +*/
  36770. +/* Opcode: Subtract * * *
  36771. +**
  36772. +** Pop the top two elements from the stack, subtract the
  36773. +** first (what was on top of the stack) from the second (the
  36774. +** next on stack)
  36775. +** and push the result back onto the stack. If either element
  36776. +** is a string then it is converted to a double using the atof()
  36777. +** function before the subtraction.
  36778. +** If either operand is NULL, the result is NULL.
  36779. +*/
  36780. +/* Opcode: Divide * * *
  36781. +**
  36782. +** Pop the top two elements from the stack, divide the
  36783. +** first (what was on top of the stack) from the second (the
  36784. +** next on stack)
  36785. +** and push the result back onto the stack. If either element
  36786. +** is a string then it is converted to a double using the atof()
  36787. +** function before the division. Division by zero returns NULL.
  36788. +** If either operand is NULL, the result is NULL.
  36789. +*/
  36790. +/* Opcode: Remainder * * *
  36791. +**
  36792. +** Pop the top two elements from the stack, divide the
  36793. +** first (what was on top of the stack) from the second (the
  36794. +** next on stack)
  36795. +** and push the remainder after division onto the stack. If either element
  36796. +** is a string then it is converted to a double using the atof()
  36797. +** function before the division. Division by zero returns NULL.
  36798. +** If either operand is NULL, the result is NULL.
  36799. +*/
  36800. +case OP_Add:
  36801. +case OP_Subtract:
  36802. +case OP_Multiply:
  36803. +case OP_Divide:
  36804. +case OP_Remainder: {
  36805. + Mem *pNos = &pTos[-1];
  36806. + assert( pNos>=p->aStack );
  36807. + if( ((pTos->flags | pNos->flags) & MEM_Null)!=0 ){
  36808. + Release(pTos);
  36809. + pTos--;
  36810. + Release(pTos);
  36811. + pTos->flags = MEM_Null;
  36812. + }else if( (pTos->flags & pNos->flags & MEM_Int)==MEM_Int ){
  36813. + int a, b;
  36814. + a = pTos->i;
  36815. + b = pNos->i;
  36816. + switch( pOp->opcode ){
  36817. + case OP_Add: b += a; break;
  36818. + case OP_Subtract: b -= a; break;
  36819. + case OP_Multiply: b *= a; break;
  36820. + case OP_Divide: {
  36821. + if( a==0 ) goto divide_by_zero;
  36822. + b /= a;
  36823. + break;
  36824. + }
  36825. + default: {
  36826. + if( a==0 ) goto divide_by_zero;
  36827. + b %= a;
  36828. + break;
  36829. + }
  36830. + }
  36831. + Release(pTos);
  36832. + pTos--;
  36833. + Release(pTos);
  36834. + pTos->i = b;
  36835. + pTos->flags = MEM_Int;
  36836. + }else{
  36837. + double a, b;
  36838. + Realify(pTos);
  36839. + Realify(pNos);
  36840. + a = pTos->r;
  36841. + b = pNos->r;
  36842. + switch( pOp->opcode ){
  36843. + case OP_Add: b += a; break;
  36844. + case OP_Subtract: b -= a; break;
  36845. + case OP_Multiply: b *= a; break;
  36846. + case OP_Divide: {
  36847. + if( a==0.0 ) goto divide_by_zero;
  36848. + b /= a;
  36849. + break;
  36850. + }
  36851. + default: {
  36852. + int ia = (int)a;
  36853. + int ib = (int)b;
  36854. + if( ia==0.0 ) goto divide_by_zero;
  36855. + b = ib % ia;
  36856. + break;
  36857. + }
  36858. + }
  36859. + Release(pTos);
  36860. + pTos--;
  36861. + Release(pTos);
  36862. + pTos->r = b;
  36863. + pTos->flags = MEM_Real;
  36864. + }
  36865. + break;
  36866. +
  36867. +divide_by_zero:
  36868. + Release(pTos);
  36869. + pTos--;
  36870. + Release(pTos);
  36871. + pTos->flags = MEM_Null;
  36872. + break;
  36873. +}
  36874. +
  36875. +/* Opcode: Function P1 * P3
  36876. +**
  36877. +** Invoke a user function (P3 is a pointer to a Function structure that
  36878. +** defines the function) with P1 string arguments taken from the stack.
  36879. +** Pop all arguments from the stack and push back the result.
  36880. +**
  36881. +** See also: AggFunc
  36882. +*/
  36883. +case OP_Function: {
  36884. + int n, i;
  36885. + Mem *pArg;
  36886. + char **azArgv;
  36887. + sqlite_func ctx;
  36888. +
  36889. + n = pOp->p1;
  36890. + pArg = &pTos[1-n];
  36891. + azArgv = p->zArgv;
  36892. + for(i=0; i<n; i++, pArg++){
  36893. + if( pArg->flags & MEM_Null ){
  36894. + azArgv[i] = 0;
  36895. + }else{
  36896. + Stringify(pArg);
  36897. + azArgv[i] = pArg->z;
  36898. + }
  36899. + }
  36900. + ctx.pFunc = (FuncDef*)pOp->p3;
  36901. + ctx.s.flags = MEM_Null;
  36902. + ctx.s.z = 0;
  36903. + ctx.isError = 0;
  36904. + ctx.isStep = 0;
  36905. + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
  36906. + (*ctx.pFunc->xFunc)(&ctx, n, (const char**)azArgv);
  36907. + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
  36908. + popStack(&pTos, n);
  36909. + pTos++;
  36910. + *pTos = ctx.s;
  36911. + if( pTos->flags & MEM_Short ){
  36912. + pTos->z = pTos->zShort;
  36913. + }
  36914. + if( ctx.isError ){
  36915. + sqliteSetString(&p->zErrMsg,
  36916. + (pTos->flags & MEM_Str)!=0 ? pTos->z : "user function error", (char*)0);
  36917. + rc = SQLITE_ERROR;
  36918. + }
  36919. + break;
  36920. +}
  36921. +
  36922. +/* Opcode: BitAnd * * *
  36923. +**
  36924. +** Pop the top two elements from the stack. Convert both elements
  36925. +** to integers. Push back onto the stack the bit-wise AND of the
  36926. +** two elements.
  36927. +** If either operand is NULL, the result is NULL.
  36928. +*/
  36929. +/* Opcode: BitOr * * *
  36930. +**
  36931. +** Pop the top two elements from the stack. Convert both elements
  36932. +** to integers. Push back onto the stack the bit-wise OR of the
  36933. +** two elements.
  36934. +** If either operand is NULL, the result is NULL.
  36935. +*/
  36936. +/* Opcode: ShiftLeft * * *
  36937. +**
  36938. +** Pop the top two elements from the stack. Convert both elements
  36939. +** to integers. Push back onto the stack the top element shifted
  36940. +** left by N bits where N is the second element on the stack.
  36941. +** If either operand is NULL, the result is NULL.
  36942. +*/
  36943. +/* Opcode: ShiftRight * * *
  36944. +**
  36945. +** Pop the top two elements from the stack. Convert both elements
  36946. +** to integers. Push back onto the stack the top element shifted
  36947. +** right by N bits where N is the second element on the stack.
  36948. +** If either operand is NULL, the result is NULL.
  36949. +*/
  36950. +case OP_BitAnd:
  36951. +case OP_BitOr:
  36952. +case OP_ShiftLeft:
  36953. +case OP_ShiftRight: {
  36954. + Mem *pNos = &pTos[-1];
  36955. + int a, b;
  36956. +
  36957. + assert( pNos>=p->aStack );
  36958. + if( (pTos->flags | pNos->flags) & MEM_Null ){
  36959. + popStack(&pTos, 2);
  36960. + pTos++;
  36961. + pTos->flags = MEM_Null;
  36962. + break;
  36963. + }
  36964. + Integerify(pTos);
  36965. + Integerify(pNos);
  36966. + a = pTos->i;
  36967. + b = pNos->i;
  36968. + switch( pOp->opcode ){
  36969. + case OP_BitAnd: a &= b; break;
  36970. + case OP_BitOr: a |= b; break;
  36971. + case OP_ShiftLeft: a <<= b; break;
  36972. + case OP_ShiftRight: a >>= b; break;
  36973. + default: /* CANT HAPPEN */ break;
  36974. + }
  36975. + assert( (pTos->flags & MEM_Dyn)==0 );
  36976. + assert( (pNos->flags & MEM_Dyn)==0 );
  36977. + pTos--;
  36978. + Release(pTos);
  36979. + pTos->i = a;
  36980. + pTos->flags = MEM_Int;
  36981. + break;
  36982. +}
  36983. +
  36984. +/* Opcode: AddImm P1 * *
  36985. +**
  36986. +** Add the value P1 to whatever is on top of the stack. The result
  36987. +** is always an integer.
  36988. +**
  36989. +** To force the top of the stack to be an integer, just add 0.
  36990. +*/
  36991. +case OP_AddImm: {
  36992. + assert( pTos>=p->aStack );
  36993. + Integerify(pTos);
  36994. + pTos->i += pOp->p1;
  36995. + break;
  36996. +}
  36997. +
  36998. +/* Opcode: ForceInt P1 P2 *
  36999. +**
  37000. +** Convert the top of the stack into an integer. If the current top of
  37001. +** the stack is not numeric (meaning that is is a NULL or a string that
  37002. +** does not look like an integer or floating point number) then pop the
  37003. +** stack and jump to P2. If the top of the stack is numeric then
  37004. +** convert it into the least integer that is greater than or equal to its
  37005. +** current value if P1==0, or to the least integer that is strictly
  37006. +** greater than its current value if P1==1.
  37007. +*/
  37008. +case OP_ForceInt: {
  37009. + int v;
  37010. + assert( pTos>=p->aStack );
  37011. + if( (pTos->flags & (MEM_Int|MEM_Real))==0
  37012. + && ((pTos->flags & MEM_Str)==0 || sqliteIsNumber(pTos->z)==0) ){
  37013. + Release(pTos);
  37014. + pTos--;
  37015. + pc = pOp->p2 - 1;
  37016. + break;
  37017. + }
  37018. + if( pTos->flags & MEM_Int ){
  37019. + v = pTos->i + (pOp->p1!=0);
  37020. + }else{
  37021. + Realify(pTos);
  37022. + v = (int)pTos->r;
  37023. + if( pTos->r>(double)v ) v++;
  37024. + if( pOp->p1 && pTos->r==(double)v ) v++;
  37025. + }
  37026. + Release(pTos);
  37027. + pTos->i = v;
  37028. + pTos->flags = MEM_Int;
  37029. + break;
  37030. +}
  37031. +
  37032. +/* Opcode: MustBeInt P1 P2 *
  37033. +**
  37034. +** Force the top of the stack to be an integer. If the top of the
  37035. +** stack is not an integer and cannot be converted into an integer
  37036. +** with out data loss, then jump immediately to P2, or if P2==0
  37037. +** raise an SQLITE_MISMATCH exception.
  37038. +**
  37039. +** If the top of the stack is not an integer and P2 is not zero and
  37040. +** P1 is 1, then the stack is popped. In all other cases, the depth
  37041. +** of the stack is unchanged.
  37042. +*/
  37043. +case OP_MustBeInt: {
  37044. + assert( pTos>=p->aStack );
  37045. + if( pTos->flags & MEM_Int ){
  37046. + /* Do nothing */
  37047. + }else if( pTos->flags & MEM_Real ){
  37048. + int i = (int)pTos->r;
  37049. + double r = (double)i;
  37050. + if( r!=pTos->r ){
  37051. + goto mismatch;
  37052. + }
  37053. + pTos->i = i;
  37054. + }else if( pTos->flags & MEM_Str ){
  37055. + int v;
  37056. + if( !toInt(pTos->z, &v) ){
  37057. + double r;
  37058. + if( !sqliteIsNumber(pTos->z) ){
  37059. + goto mismatch;
  37060. + }
  37061. + Realify(pTos);
  37062. + v = (int)pTos->r;
  37063. + r = (double)v;
  37064. + if( r!=pTos->r ){
  37065. + goto mismatch;
  37066. + }
  37067. + }
  37068. + pTos->i = v;
  37069. + }else{
  37070. + goto mismatch;
  37071. + }
  37072. + Release(pTos);
  37073. + pTos->flags = MEM_Int;
  37074. + break;
  37075. +
  37076. +mismatch:
  37077. + if( pOp->p2==0 ){
  37078. + rc = SQLITE_MISMATCH;
  37079. + goto abort_due_to_error;
  37080. + }else{
  37081. + if( pOp->p1 ) popStack(&pTos, 1);
  37082. + pc = pOp->p2 - 1;
  37083. + }
  37084. + break;
  37085. +}
  37086. +
  37087. +/* Opcode: Eq P1 P2 *
  37088. +**
  37089. +** Pop the top two elements from the stack. If they are equal, then
  37090. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37091. +**
  37092. +** If either operand is NULL (and thus if the result is unknown) then
  37093. +** take the jump if P1 is true.
  37094. +**
  37095. +** If both values are numeric, they are converted to doubles using atof()
  37096. +** and compared for equality that way. Otherwise the strcmp() library
  37097. +** routine is used for the comparison. For a pure text comparison
  37098. +** use OP_StrEq.
  37099. +**
  37100. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37101. +** stack if the jump would have been taken, or a 0 if not. Push a
  37102. +** NULL if either operand was NULL.
  37103. +*/
  37104. +/* Opcode: Ne P1 P2 *
  37105. +**
  37106. +** Pop the top two elements from the stack. If they are not equal, then
  37107. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37108. +**
  37109. +** If either operand is NULL (and thus if the result is unknown) then
  37110. +** take the jump if P1 is true.
  37111. +**
  37112. +** If both values are numeric, they are converted to doubles using atof()
  37113. +** and compared in that format. Otherwise the strcmp() library
  37114. +** routine is used for the comparison. For a pure text comparison
  37115. +** use OP_StrNe.
  37116. +**
  37117. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37118. +** stack if the jump would have been taken, or a 0 if not. Push a
  37119. +** NULL if either operand was NULL.
  37120. +*/
  37121. +/* Opcode: Lt P1 P2 *
  37122. +**
  37123. +** Pop the top two elements from the stack. If second element (the
  37124. +** next on stack) is less than the first (the top of stack), then
  37125. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37126. +** In other words, jump if NOS<TOS.
  37127. +**
  37128. +** If either operand is NULL (and thus if the result is unknown) then
  37129. +** take the jump if P1 is true.
  37130. +**
  37131. +** If both values are numeric, they are converted to doubles using atof()
  37132. +** and compared in that format. Numeric values are always less than
  37133. +** non-numeric values. If both operands are non-numeric, the strcmp() library
  37134. +** routine is used for the comparison. For a pure text comparison
  37135. +** use OP_StrLt.
  37136. +**
  37137. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37138. +** stack if the jump would have been taken, or a 0 if not. Push a
  37139. +** NULL if either operand was NULL.
  37140. +*/
  37141. +/* Opcode: Le P1 P2 *
  37142. +**
  37143. +** Pop the top two elements from the stack. If second element (the
  37144. +** next on stack) is less than or equal to the first (the top of stack),
  37145. +** then jump to instruction P2. In other words, jump if NOS<=TOS.
  37146. +**
  37147. +** If either operand is NULL (and thus if the result is unknown) then
  37148. +** take the jump if P1 is true.
  37149. +**
  37150. +** If both values are numeric, they are converted to doubles using atof()
  37151. +** and compared in that format. Numeric values are always less than
  37152. +** non-numeric values. If both operands are non-numeric, the strcmp() library
  37153. +** routine is used for the comparison. For a pure text comparison
  37154. +** use OP_StrLe.
  37155. +**
  37156. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37157. +** stack if the jump would have been taken, or a 0 if not. Push a
  37158. +** NULL if either operand was NULL.
  37159. +*/
  37160. +/* Opcode: Gt P1 P2 *
  37161. +**
  37162. +** Pop the top two elements from the stack. If second element (the
  37163. +** next on stack) is greater than the first (the top of stack),
  37164. +** then jump to instruction P2. In other words, jump if NOS>TOS.
  37165. +**
  37166. +** If either operand is NULL (and thus if the result is unknown) then
  37167. +** take the jump if P1 is true.
  37168. +**
  37169. +** If both values are numeric, they are converted to doubles using atof()
  37170. +** and compared in that format. Numeric values are always less than
  37171. +** non-numeric values. If both operands are non-numeric, the strcmp() library
  37172. +** routine is used for the comparison. For a pure text comparison
  37173. +** use OP_StrGt.
  37174. +**
  37175. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37176. +** stack if the jump would have been taken, or a 0 if not. Push a
  37177. +** NULL if either operand was NULL.
  37178. +*/
  37179. +/* Opcode: Ge P1 P2 *
  37180. +**
  37181. +** Pop the top two elements from the stack. If second element (the next
  37182. +** on stack) is greater than or equal to the first (the top of stack),
  37183. +** then jump to instruction P2. In other words, jump if NOS>=TOS.
  37184. +**
  37185. +** If either operand is NULL (and thus if the result is unknown) then
  37186. +** take the jump if P1 is true.
  37187. +**
  37188. +** If both values are numeric, they are converted to doubles using atof()
  37189. +** and compared in that format. Numeric values are always less than
  37190. +** non-numeric values. If both operands are non-numeric, the strcmp() library
  37191. +** routine is used for the comparison. For a pure text comparison
  37192. +** use OP_StrGe.
  37193. +**
  37194. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37195. +** stack if the jump would have been taken, or a 0 if not. Push a
  37196. +** NULL if either operand was NULL.
  37197. +*/
  37198. +case OP_Eq:
  37199. +case OP_Ne:
  37200. +case OP_Lt:
  37201. +case OP_Le:
  37202. +case OP_Gt:
  37203. +case OP_Ge: {
  37204. + Mem *pNos = &pTos[-1];
  37205. + int c, v;
  37206. + int ft, fn;
  37207. + assert( pNos>=p->aStack );
  37208. + ft = pTos->flags;
  37209. + fn = pNos->flags;
  37210. + if( (ft | fn) & MEM_Null ){
  37211. + popStack(&pTos, 2);
  37212. + if( pOp->p2 ){
  37213. + if( pOp->p1 ) pc = pOp->p2-1;
  37214. + }else{
  37215. + pTos++;
  37216. + pTos->flags = MEM_Null;
  37217. + }
  37218. + break;
  37219. + }else if( (ft & fn & MEM_Int)==MEM_Int ){
  37220. + c = pNos->i - pTos->i;
  37221. + }else if( (ft & MEM_Int)!=0 && (fn & MEM_Str)!=0 && toInt(pNos->z,&v) ){
  37222. + c = v - pTos->i;
  37223. + }else if( (fn & MEM_Int)!=0 && (ft & MEM_Str)!=0 && toInt(pTos->z,&v) ){
  37224. + c = pNos->i - v;
  37225. + }else{
  37226. + Stringify(pTos);
  37227. + Stringify(pNos);
  37228. + c = sqliteCompare(pNos->z, pTos->z);
  37229. + }
  37230. + switch( pOp->opcode ){
  37231. + case OP_Eq: c = c==0; break;
  37232. + case OP_Ne: c = c!=0; break;
  37233. + case OP_Lt: c = c<0; break;
  37234. + case OP_Le: c = c<=0; break;
  37235. + case OP_Gt: c = c>0; break;
  37236. + default: c = c>=0; break;
  37237. + }
  37238. + popStack(&pTos, 2);
  37239. + if( pOp->p2 ){
  37240. + if( c ) pc = pOp->p2-1;
  37241. + }else{
  37242. + pTos++;
  37243. + pTos->i = c;
  37244. + pTos->flags = MEM_Int;
  37245. + }
  37246. + break;
  37247. +}
  37248. +/* INSERT NO CODE HERE!
  37249. +**
  37250. +** The opcode numbers are extracted from this source file by doing
  37251. +**
  37252. +** grep '^case OP_' vdbe.c | ... >opcodes.h
  37253. +**
  37254. +** The opcodes are numbered in the order that they appear in this file.
  37255. +** But in order for the expression generating code to work right, the
  37256. +** string comparison operators that follow must be numbered exactly 6
  37257. +** greater than the numeric comparison opcodes above. So no other
  37258. +** cases can appear between the two.
  37259. +*/
  37260. +/* Opcode: StrEq P1 P2 *
  37261. +**
  37262. +** Pop the top two elements from the stack. If they are equal, then
  37263. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37264. +**
  37265. +** If either operand is NULL (and thus if the result is unknown) then
  37266. +** take the jump if P1 is true.
  37267. +**
  37268. +** The strcmp() library routine is used for the comparison. For a
  37269. +** numeric comparison, use OP_Eq.
  37270. +**
  37271. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37272. +** stack if the jump would have been taken, or a 0 if not. Push a
  37273. +** NULL if either operand was NULL.
  37274. +*/
  37275. +/* Opcode: StrNe P1 P2 *
  37276. +**
  37277. +** Pop the top two elements from the stack. If they are not equal, then
  37278. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37279. +**
  37280. +** If either operand is NULL (and thus if the result is unknown) then
  37281. +** take the jump if P1 is true.
  37282. +**
  37283. +** The strcmp() library routine is used for the comparison. For a
  37284. +** numeric comparison, use OP_Ne.
  37285. +**
  37286. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37287. +** stack if the jump would have been taken, or a 0 if not. Push a
  37288. +** NULL if either operand was NULL.
  37289. +*/
  37290. +/* Opcode: StrLt P1 P2 *
  37291. +**
  37292. +** Pop the top two elements from the stack. If second element (the
  37293. +** next on stack) is less than the first (the top of stack), then
  37294. +** jump to instruction P2. Otherwise, continue to the next instruction.
  37295. +** In other words, jump if NOS<TOS.
  37296. +**
  37297. +** If either operand is NULL (and thus if the result is unknown) then
  37298. +** take the jump if P1 is true.
  37299. +**
  37300. +** The strcmp() library routine is used for the comparison. For a
  37301. +** numeric comparison, use OP_Lt.
  37302. +**
  37303. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37304. +** stack if the jump would have been taken, or a 0 if not. Push a
  37305. +** NULL if either operand was NULL.
  37306. +*/
  37307. +/* Opcode: StrLe P1 P2 *
  37308. +**
  37309. +** Pop the top two elements from the stack. If second element (the
  37310. +** next on stack) is less than or equal to the first (the top of stack),
  37311. +** then jump to instruction P2. In other words, jump if NOS<=TOS.
  37312. +**
  37313. +** If either operand is NULL (and thus if the result is unknown) then
  37314. +** take the jump if P1 is true.
  37315. +**
  37316. +** The strcmp() library routine is used for the comparison. For a
  37317. +** numeric comparison, use OP_Le.
  37318. +**
  37319. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37320. +** stack if the jump would have been taken, or a 0 if not. Push a
  37321. +** NULL if either operand was NULL.
  37322. +*/
  37323. +/* Opcode: StrGt P1 P2 *
  37324. +**
  37325. +** Pop the top two elements from the stack. If second element (the
  37326. +** next on stack) is greater than the first (the top of stack),
  37327. +** then jump to instruction P2. In other words, jump if NOS>TOS.
  37328. +**
  37329. +** If either operand is NULL (and thus if the result is unknown) then
  37330. +** take the jump if P1 is true.
  37331. +**
  37332. +** The strcmp() library routine is used for the comparison. For a
  37333. +** numeric comparison, use OP_Gt.
  37334. +**
  37335. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37336. +** stack if the jump would have been taken, or a 0 if not. Push a
  37337. +** NULL if either operand was NULL.
  37338. +*/
  37339. +/* Opcode: StrGe P1 P2 *
  37340. +**
  37341. +** Pop the top two elements from the stack. If second element (the next
  37342. +** on stack) is greater than or equal to the first (the top of stack),
  37343. +** then jump to instruction P2. In other words, jump if NOS>=TOS.
  37344. +**
  37345. +** If either operand is NULL (and thus if the result is unknown) then
  37346. +** take the jump if P1 is true.
  37347. +**
  37348. +** The strcmp() library routine is used for the comparison. For a
  37349. +** numeric comparison, use OP_Ge.
  37350. +**
  37351. +** If P2 is zero, do not jump. Instead, push an integer 1 onto the
  37352. +** stack if the jump would have been taken, or a 0 if not. Push a
  37353. +** NULL if either operand was NULL.
  37354. +*/
  37355. +case OP_StrEq:
  37356. +case OP_StrNe:
  37357. +case OP_StrLt:
  37358. +case OP_StrLe:
  37359. +case OP_StrGt:
  37360. +case OP_StrGe: {
  37361. + Mem *pNos = &pTos[-1];
  37362. + int c;
  37363. + assert( pNos>=p->aStack );
  37364. + if( (pNos->flags | pTos->flags) & MEM_Null ){
  37365. + popStack(&pTos, 2);
  37366. + if( pOp->p2 ){
  37367. + if( pOp->p1 ) pc = pOp->p2-1;
  37368. + }else{
  37369. + pTos++;
  37370. + pTos->flags = MEM_Null;
  37371. + }
  37372. + break;
  37373. + }else{
  37374. + Stringify(pTos);
  37375. + Stringify(pNos);
  37376. + c = strcmp(pNos->z, pTos->z);
  37377. + }
  37378. + /* The asserts on each case of the following switch are there to verify
  37379. + ** that string comparison opcodes are always exactly 6 greater than the
  37380. + ** corresponding numeric comparison opcodes. The code generator depends
  37381. + ** on this fact.
  37382. + */
  37383. + switch( pOp->opcode ){
  37384. + case OP_StrEq: c = c==0; assert( pOp->opcode-6==OP_Eq ); break;
  37385. + case OP_StrNe: c = c!=0; assert( pOp->opcode-6==OP_Ne ); break;
  37386. + case OP_StrLt: c = c<0; assert( pOp->opcode-6==OP_Lt ); break;
  37387. + case OP_StrLe: c = c<=0; assert( pOp->opcode-6==OP_Le ); break;
  37388. + case OP_StrGt: c = c>0; assert( pOp->opcode-6==OP_Gt ); break;
  37389. + default: c = c>=0; assert( pOp->opcode-6==OP_Ge ); break;
  37390. + }
  37391. + popStack(&pTos, 2);
  37392. + if( pOp->p2 ){
  37393. + if( c ) pc = pOp->p2-1;
  37394. + }else{
  37395. + pTos++;
  37396. + pTos->flags = MEM_Int;
  37397. + pTos->i = c;
  37398. + }
  37399. + break;
  37400. +}
  37401. +
  37402. +/* Opcode: And * * *
  37403. +**
  37404. +** Pop two values off the stack. Take the logical AND of the
  37405. +** two values and push the resulting boolean value back onto the
  37406. +** stack.
  37407. +*/
  37408. +/* Opcode: Or * * *
  37409. +**
  37410. +** Pop two values off the stack. Take the logical OR of the
  37411. +** two values and push the resulting boolean value back onto the
  37412. +** stack.
  37413. +*/
  37414. +case OP_And:
  37415. +case OP_Or: {
  37416. + Mem *pNos = &pTos[-1];
  37417. + int v1, v2; /* 0==TRUE, 1==FALSE, 2==UNKNOWN or NULL */
  37418. +
  37419. + assert( pNos>=p->aStack );
  37420. + if( pTos->flags & MEM_Null ){
  37421. + v1 = 2;
  37422. + }else{
  37423. + Integerify(pTos);
  37424. + v1 = pTos->i==0;
  37425. + }
  37426. + if( pNos->flags & MEM_Null ){
  37427. + v2 = 2;
  37428. + }else{
  37429. + Integerify(pNos);
  37430. + v2 = pNos->i==0;
  37431. + }
  37432. + if( pOp->opcode==OP_And ){
  37433. + static const unsigned char and_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  37434. + v1 = and_logic[v1*3+v2];
  37435. + }else{
  37436. + static const unsigned char or_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  37437. + v1 = or_logic[v1*3+v2];
  37438. + }
  37439. + popStack(&pTos, 2);
  37440. + pTos++;
  37441. + if( v1==2 ){
  37442. + pTos->flags = MEM_Null;
  37443. + }else{
  37444. + pTos->i = v1==0;
  37445. + pTos->flags = MEM_Int;
  37446. + }
  37447. + break;
  37448. +}
  37449. +
  37450. +/* Opcode: Negative * * *
  37451. +**
  37452. +** Treat the top of the stack as a numeric quantity. Replace it
  37453. +** with its additive inverse. If the top of the stack is NULL
  37454. +** its value is unchanged.
  37455. +*/
  37456. +/* Opcode: AbsValue * * *
  37457. +**
  37458. +** Treat the top of the stack as a numeric quantity. Replace it
  37459. +** with its absolute value. If the top of the stack is NULL
  37460. +** its value is unchanged.
  37461. +*/
  37462. +case OP_Negative:
  37463. +case OP_AbsValue: {
  37464. + assert( pTos>=p->aStack );
  37465. + if( pTos->flags & MEM_Real ){
  37466. + Release(pTos);
  37467. + if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
  37468. + pTos->r = -pTos->r;
  37469. + }
  37470. + pTos->flags = MEM_Real;
  37471. + }else if( pTos->flags & MEM_Int ){
  37472. + Release(pTos);
  37473. + if( pOp->opcode==OP_Negative || pTos->i<0 ){
  37474. + pTos->i = -pTos->i;
  37475. + }
  37476. + pTos->flags = MEM_Int;
  37477. + }else if( pTos->flags & MEM_Null ){
  37478. + /* Do nothing */
  37479. + }else{
  37480. + Realify(pTos);
  37481. + Release(pTos);
  37482. + if( pOp->opcode==OP_Negative || pTos->r<0.0 ){
  37483. + pTos->r = -pTos->r;
  37484. + }
  37485. + pTos->flags = MEM_Real;
  37486. + }
  37487. + break;
  37488. +}
  37489. +
  37490. +/* Opcode: Not * * *
  37491. +**
  37492. +** Interpret the top of the stack as a boolean value. Replace it
  37493. +** with its complement. If the top of the stack is NULL its value
  37494. +** is unchanged.
  37495. +*/
  37496. +case OP_Not: {
  37497. + assert( pTos>=p->aStack );
  37498. + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
  37499. + Integerify(pTos);
  37500. + Release(pTos);
  37501. + pTos->i = !pTos->i;
  37502. + pTos->flags = MEM_Int;
  37503. + break;
  37504. +}
  37505. +
  37506. +/* Opcode: BitNot * * *
  37507. +**
  37508. +** Interpret the top of the stack as an value. Replace it
  37509. +** with its ones-complement. If the top of the stack is NULL its
  37510. +** value is unchanged.
  37511. +*/
  37512. +case OP_BitNot: {
  37513. + assert( pTos>=p->aStack );
  37514. + if( pTos->flags & MEM_Null ) break; /* Do nothing to NULLs */
  37515. + Integerify(pTos);
  37516. + Release(pTos);
  37517. + pTos->i = ~pTos->i;
  37518. + pTos->flags = MEM_Int;
  37519. + break;
  37520. +}
  37521. +
  37522. +/* Opcode: Noop * * *
  37523. +**
  37524. +** Do nothing. This instruction is often useful as a jump
  37525. +** destination.
  37526. +*/
  37527. +case OP_Noop: {
  37528. + break;
  37529. +}
  37530. +
  37531. +/* Opcode: If P1 P2 *
  37532. +**
  37533. +** Pop a single boolean from the stack. If the boolean popped is
  37534. +** true, then jump to p2. Otherwise continue to the next instruction.
  37535. +** An integer is false if zero and true otherwise. A string is
  37536. +** false if it has zero length and true otherwise.
  37537. +**
  37538. +** If the value popped of the stack is NULL, then take the jump if P1
  37539. +** is true and fall through if P1 is false.
  37540. +*/
  37541. +/* Opcode: IfNot P1 P2 *
  37542. +**
  37543. +** Pop a single boolean from the stack. If the boolean popped is
  37544. +** false, then jump to p2. Otherwise continue to the next instruction.
  37545. +** An integer is false if zero and true otherwise. A string is
  37546. +** false if it has zero length and true otherwise.
  37547. +**
  37548. +** If the value popped of the stack is NULL, then take the jump if P1
  37549. +** is true and fall through if P1 is false.
  37550. +*/
  37551. +case OP_If:
  37552. +case OP_IfNot: {
  37553. + int c;
  37554. + assert( pTos>=p->aStack );
  37555. + if( pTos->flags & MEM_Null ){
  37556. + c = pOp->p1;
  37557. + }else{
  37558. + Integerify(pTos);
  37559. + c = pTos->i;
  37560. + if( pOp->opcode==OP_IfNot ) c = !c;
  37561. + }
  37562. + assert( (pTos->flags & MEM_Dyn)==0 );
  37563. + pTos--;
  37564. + if( c ) pc = pOp->p2-1;
  37565. + break;
  37566. +}
  37567. +
  37568. +/* Opcode: IsNull P1 P2 *
  37569. +**
  37570. +** If any of the top abs(P1) values on the stack are NULL, then jump
  37571. +** to P2. Pop the stack P1 times if P1>0. If P1<0 leave the stack
  37572. +** unchanged.
  37573. +*/
  37574. +case OP_IsNull: {
  37575. + int i, cnt;
  37576. + Mem *pTerm;
  37577. + cnt = pOp->p1;
  37578. + if( cnt<0 ) cnt = -cnt;
  37579. + pTerm = &pTos[1-cnt];
  37580. + assert( pTerm>=p->aStack );
  37581. + for(i=0; i<cnt; i++, pTerm++){
  37582. + if( pTerm->flags & MEM_Null ){
  37583. + pc = pOp->p2-1;
  37584. + break;
  37585. + }
  37586. + }
  37587. + if( pOp->p1>0 ) popStack(&pTos, cnt);
  37588. + break;
  37589. +}
  37590. +
  37591. +/* Opcode: NotNull P1 P2 *
  37592. +**
  37593. +** Jump to P2 if the top P1 values on the stack are all not NULL. Pop the
  37594. +** stack if P1 times if P1 is greater than zero. If P1 is less than
  37595. +** zero then leave the stack unchanged.
  37596. +*/
  37597. +case OP_NotNull: {
  37598. + int i, cnt;
  37599. + cnt = pOp->p1;
  37600. + if( cnt<0 ) cnt = -cnt;
  37601. + assert( &pTos[1-cnt] >= p->aStack );
  37602. + for(i=0; i<cnt && (pTos[1+i-cnt].flags & MEM_Null)==0; i++){}
  37603. + if( i>=cnt ) pc = pOp->p2-1;
  37604. + if( pOp->p1>0 ) popStack(&pTos, cnt);
  37605. + break;
  37606. +}
  37607. +
  37608. +/* Opcode: MakeRecord P1 P2 *
  37609. +**
  37610. +** Convert the top P1 entries of the stack into a single entry
  37611. +** suitable for use as a data record in a database table. The
  37612. +** details of the format are irrelavant as long as the OP_Column
  37613. +** opcode can decode the record later. Refer to source code
  37614. +** comments for the details of the record format.
  37615. +**
  37616. +** If P2 is true (non-zero) and one or more of the P1 entries
  37617. +** that go into building the record is NULL, then add some extra
  37618. +** bytes to the record to make it distinct for other entries created
  37619. +** during the same run of the VDBE. The extra bytes added are a
  37620. +** counter that is reset with each run of the VDBE, so records
  37621. +** created this way will not necessarily be distinct across runs.
  37622. +** But they should be distinct for transient tables (created using
  37623. +** OP_OpenTemp) which is what they are intended for.
  37624. +**
  37625. +** (Later:) The P2==1 option was intended to make NULLs distinct
  37626. +** for the UNION operator. But I have since discovered that NULLs
  37627. +** are indistinct for UNION. So this option is never used.
  37628. +*/
  37629. +case OP_MakeRecord: {
  37630. + char *zNewRecord;
  37631. + int nByte;
  37632. + int nField;
  37633. + int i, j;
  37634. + int idxWidth;
  37635. + u32 addr;
  37636. + Mem *pRec;
  37637. + int addUnique = 0; /* True to cause bytes to be added to make the
  37638. + ** generated record distinct */
  37639. + char zTemp[NBFS]; /* Temp space for small records */
  37640. +
  37641. + /* Assuming the record contains N fields, the record format looks
  37642. + ** like this:
  37643. + **
  37644. + ** -------------------------------------------------------------------
  37645. + ** | idx0 | idx1 | ... | idx(N-1) | idx(N) | data0 | ... | data(N-1) |
  37646. + ** -------------------------------------------------------------------
  37647. + **
  37648. + ** All data fields are converted to strings before being stored and
  37649. + ** are stored with their null terminators. NULL entries omit the
  37650. + ** null terminator. Thus an empty string uses 1 byte and a NULL uses
  37651. + ** zero bytes. Data(0) is taken from the lowest element of the stack
  37652. + ** and data(N-1) is the top of the stack.
  37653. + **
  37654. + ** Each of the idx() entries is either 1, 2, or 3 bytes depending on
  37655. + ** how big the total record is. Idx(0) contains the offset to the start
  37656. + ** of data(0). Idx(k) contains the offset to the start of data(k).
  37657. + ** Idx(N) contains the total number of bytes in the record.
  37658. + */
  37659. + nField = pOp->p1;
  37660. + pRec = &pTos[1-nField];
  37661. + assert( pRec>=p->aStack );
  37662. + nByte = 0;
  37663. + for(i=0; i<nField; i++, pRec++){
  37664. + if( pRec->flags & MEM_Null ){
  37665. + addUnique = pOp->p2;
  37666. + }else{
  37667. + Stringify(pRec);
  37668. + nByte += pRec->n;
  37669. + }
  37670. + }
  37671. + if( addUnique ) nByte += sizeof(p->uniqueCnt);
  37672. + if( nByte + nField + 1 < 256 ){
  37673. + idxWidth = 1;
  37674. + }else if( nByte + 2*nField + 2 < 65536 ){
  37675. + idxWidth = 2;
  37676. + }else{
  37677. + idxWidth = 3;
  37678. + }
  37679. + nByte += idxWidth*(nField + 1);
  37680. + if( nByte>MAX_BYTES_PER_ROW ){
  37681. + rc = SQLITE_TOOBIG;
  37682. + goto abort_due_to_error;
  37683. + }
  37684. + if( nByte<=NBFS ){
  37685. + zNewRecord = zTemp;
  37686. + }else{
  37687. + zNewRecord = sqliteMallocRaw( nByte );
  37688. + if( zNewRecord==0 ) goto no_mem;
  37689. + }
  37690. + j = 0;
  37691. + addr = idxWidth*(nField+1) + addUnique*sizeof(p->uniqueCnt);
  37692. + for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
  37693. + zNewRecord[j++] = addr & 0xff;
  37694. + if( idxWidth>1 ){
  37695. + zNewRecord[j++] = (addr>>8)&0xff;
  37696. + if( idxWidth>2 ){
  37697. + zNewRecord[j++] = (addr>>16)&0xff;
  37698. + }
  37699. + }
  37700. + if( (pRec->flags & MEM_Null)==0 ){
  37701. + addr += pRec->n;
  37702. + }
  37703. + }
  37704. + zNewRecord[j++] = addr & 0xff;
  37705. + if( idxWidth>1 ){
  37706. + zNewRecord[j++] = (addr>>8)&0xff;
  37707. + if( idxWidth>2 ){
  37708. + zNewRecord[j++] = (addr>>16)&0xff;
  37709. + }
  37710. + }
  37711. + if( addUnique ){
  37712. + memcpy(&zNewRecord[j], &p->uniqueCnt, sizeof(p->uniqueCnt));
  37713. + p->uniqueCnt++;
  37714. + j += sizeof(p->uniqueCnt);
  37715. + }
  37716. + for(i=0, pRec=&pTos[1-nField]; i<nField; i++, pRec++){
  37717. + if( (pRec->flags & MEM_Null)==0 ){
  37718. + memcpy(&zNewRecord[j], pRec->z, pRec->n);
  37719. + j += pRec->n;
  37720. + }
  37721. + }
  37722. + popStack(&pTos, nField);
  37723. + pTos++;
  37724. + pTos->n = nByte;
  37725. + if( nByte<=NBFS ){
  37726. + assert( zNewRecord==zTemp );
  37727. + memcpy(pTos->zShort, zTemp, nByte);
  37728. + pTos->z = pTos->zShort;
  37729. + pTos->flags = MEM_Str | MEM_Short;
  37730. + }else{
  37731. + assert( zNewRecord!=zTemp );
  37732. + pTos->z = zNewRecord;
  37733. + pTos->flags = MEM_Str | MEM_Dyn;
  37734. + }
  37735. + break;
  37736. +}
  37737. +
  37738. +/* Opcode: MakeKey P1 P2 P3
  37739. +**
  37740. +** Convert the top P1 entries of the stack into a single entry suitable
  37741. +** for use as the key in an index. The top P1 records are
  37742. +** converted to strings and merged. The null-terminators
  37743. +** are retained and used as separators.
  37744. +** The lowest entry in the stack is the first field and the top of the
  37745. +** stack becomes the last.
  37746. +**
  37747. +** If P2 is not zero, then the original entries remain on the stack
  37748. +** and the new key is pushed on top. If P2 is zero, the original
  37749. +** data is popped off the stack first then the new key is pushed
  37750. +** back in its place.
  37751. +**
  37752. +** P3 is a string that is P1 characters long. Each character is either
  37753. +** an 'n' or a 't' to indicates if the argument should be intepreted as
  37754. +** numeric or text type. The first character of P3 corresponds to the
  37755. +** lowest element on the stack. If P3 is NULL then all arguments are
  37756. +** assumed to be of the numeric type.
  37757. +**
  37758. +** The type makes a difference in that text-type fields may not be
  37759. +** introduced by 'b' (as described in the next paragraph). The
  37760. +** first character of a text-type field must be either 'a' (if it is NULL)
  37761. +** or 'c'. Numeric fields will be introduced by 'b' if their content
  37762. +** looks like a well-formed number. Otherwise the 'a' or 'c' will be
  37763. +** used.
  37764. +**
  37765. +** The key is a concatenation of fields. Each field is terminated by
  37766. +** a single 0x00 character. A NULL field is introduced by an 'a' and
  37767. +** is followed immediately by its 0x00 terminator. A numeric field is
  37768. +** introduced by a single character 'b' and is followed by a sequence
  37769. +** of characters that represent the number such that a comparison of
  37770. +** the character string using memcpy() sorts the numbers in numerical
  37771. +** order. The character strings for numbers are generated using the
  37772. +** sqliteRealToSortable() function. A text field is introduced by a
  37773. +** 'c' character and is followed by the exact text of the field. The
  37774. +** use of an 'a', 'b', or 'c' character at the beginning of each field
  37775. +** guarantees that NULLs sort before numbers and that numbers sort
  37776. +** before text. 0x00 characters do not occur except as separators
  37777. +** between fields.
  37778. +**
  37779. +** See also: MakeIdxKey, SortMakeKey
  37780. +*/
  37781. +/* Opcode: MakeIdxKey P1 P2 P3
  37782. +**
  37783. +** Convert the top P1 entries of the stack into a single entry suitable
  37784. +** for use as the key in an index. In addition, take one additional integer
  37785. +** off of the stack, treat that integer as a four-byte record number, and
  37786. +** append the four bytes to the key. Thus a total of P1+1 entries are
  37787. +** popped from the stack for this instruction and a single entry is pushed
  37788. +** back. The first P1 entries that are popped are strings and the last
  37789. +** entry (the lowest on the stack) is an integer record number.
  37790. +**
  37791. +** The converstion of the first P1 string entries occurs just like in
  37792. +** MakeKey. Each entry is separated from the others by a null.
  37793. +** The entire concatenation is null-terminated. The lowest entry
  37794. +** in the stack is the first field and the top of the stack becomes the
  37795. +** last.
  37796. +**
  37797. +** If P2 is not zero and one or more of the P1 entries that go into the
  37798. +** generated key is NULL, then jump to P2 after the new key has been
  37799. +** pushed on the stack. In other words, jump to P2 if the key is
  37800. +** guaranteed to be unique. This jump can be used to skip a subsequent
  37801. +** uniqueness test.
  37802. +**
  37803. +** P3 is a string that is P1 characters long. Each character is either
  37804. +** an 'n' or a 't' to indicates if the argument should be numeric or
  37805. +** text. The first character corresponds to the lowest element on the
  37806. +** stack. If P3 is null then all arguments are assumed to be numeric.
  37807. +**
  37808. +** See also: MakeKey, SortMakeKey
  37809. +*/
  37810. +case OP_MakeIdxKey:
  37811. +case OP_MakeKey: {
  37812. + char *zNewKey;
  37813. + int nByte;
  37814. + int nField;
  37815. + int addRowid;
  37816. + int i, j;
  37817. + int containsNull = 0;
  37818. + Mem *pRec;
  37819. + char zTemp[NBFS];
  37820. +
  37821. + addRowid = pOp->opcode==OP_MakeIdxKey;
  37822. + nField = pOp->p1;
  37823. + pRec = &pTos[1-nField];
  37824. + assert( pRec>=p->aStack );
  37825. + nByte = 0;
  37826. + for(j=0, i=0; i<nField; i++, j++, pRec++){
  37827. + int flags = pRec->flags;
  37828. + int len;
  37829. + char *z;
  37830. + if( flags & MEM_Null ){
  37831. + nByte += 2;
  37832. + containsNull = 1;
  37833. + }else if( pOp->p3 && pOp->p3[j]=='t' ){
  37834. + Stringify(pRec);
  37835. + pRec->flags &= ~(MEM_Int|MEM_Real);
  37836. + nByte += pRec->n+1;
  37837. + }else if( (flags & (MEM_Real|MEM_Int))!=0 || sqliteIsNumber(pRec->z) ){
  37838. + if( (flags & (MEM_Real|MEM_Int))==MEM_Int ){
  37839. + pRec->r = pRec->i;
  37840. + }else if( (flags & (MEM_Real|MEM_Int))==0 ){
  37841. + pRec->r = sqliteAtoF(pRec->z, 0);
  37842. + }
  37843. + Release(pRec);
  37844. + z = pRec->zShort;
  37845. + sqliteRealToSortable(pRec->r, z);
  37846. + len = strlen(z);
  37847. + pRec->z = 0;
  37848. + pRec->flags = MEM_Real;
  37849. + pRec->n = len+1;
  37850. + nByte += pRec->n+1;
  37851. + }else{
  37852. + nByte += pRec->n+1;
  37853. + }
  37854. + }
  37855. + if( nByte+sizeof(u32)>MAX_BYTES_PER_ROW ){
  37856. + rc = SQLITE_TOOBIG;
  37857. + goto abort_due_to_error;
  37858. + }
  37859. + if( addRowid ) nByte += sizeof(u32);
  37860. + if( nByte<=NBFS ){
  37861. + zNewKey = zTemp;
  37862. + }else{
  37863. + zNewKey = sqliteMallocRaw( nByte );
  37864. + if( zNewKey==0 ) goto no_mem;
  37865. + }
  37866. + j = 0;
  37867. + pRec = &pTos[1-nField];
  37868. + for(i=0; i<nField; i++, pRec++){
  37869. + if( pRec->flags & MEM_Null ){
  37870. + zNewKey[j++] = 'a';
  37871. + zNewKey[j++] = 0;
  37872. + }else if( pRec->flags==MEM_Real ){
  37873. + zNewKey[j++] = 'b';
  37874. + memcpy(&zNewKey[j], pRec->zShort, pRec->n);
  37875. + j += pRec->n;
  37876. + }else{
  37877. + assert( pRec->flags & MEM_Str );
  37878. + zNewKey[j++] = 'c';
  37879. + memcpy(&zNewKey[j], pRec->z, pRec->n);
  37880. + j += pRec->n;
  37881. + }
  37882. + }
  37883. + if( addRowid ){
  37884. + u32 iKey;
  37885. + pRec = &pTos[-nField];
  37886. + assert( pRec>=p->aStack );
  37887. + Integerify(pRec);
  37888. + iKey = intToKey(pRec->i);
  37889. + memcpy(&zNewKey[j], &iKey, sizeof(u32));
  37890. + popStack(&pTos, nField+1);
  37891. + if( pOp->p2 && containsNull ) pc = pOp->p2 - 1;
  37892. + }else{
  37893. + if( pOp->p2==0 ) popStack(&pTos, nField);
  37894. + }
  37895. + pTos++;
  37896. + pTos->n = nByte;
  37897. + if( nByte<=NBFS ){
  37898. + assert( zNewKey==zTemp );
  37899. + pTos->z = pTos->zShort;
  37900. + memcpy(pTos->zShort, zTemp, nByte);
  37901. + pTos->flags = MEM_Str | MEM_Short;
  37902. + }else{
  37903. + pTos->z = zNewKey;
  37904. + pTos->flags = MEM_Str | MEM_Dyn;
  37905. + }
  37906. + break;
  37907. +}
  37908. +
  37909. +/* Opcode: IncrKey * * *
  37910. +**
  37911. +** The top of the stack should contain an index key generated by
  37912. +** The MakeKey opcode. This routine increases the least significant
  37913. +** byte of that key by one. This is used so that the MoveTo opcode
  37914. +** will move to the first entry greater than the key rather than to
  37915. +** the key itself.
  37916. +*/
  37917. +case OP_IncrKey: {
  37918. + assert( pTos>=p->aStack );
  37919. + /* The IncrKey opcode is only applied to keys generated by
  37920. + ** MakeKey or MakeIdxKey and the results of those operands
  37921. + ** are always dynamic strings or zShort[] strings. So we
  37922. + ** are always free to modify the string in place.
  37923. + */
  37924. + assert( pTos->flags & (MEM_Dyn|MEM_Short) );
  37925. + pTos->z[pTos->n-1]++;
  37926. + break;
  37927. +}
  37928. +
  37929. +/* Opcode: Checkpoint P1 * *
  37930. +**
  37931. +** Begin a checkpoint. A checkpoint is the beginning of a operation that
  37932. +** is part of a larger transaction but which might need to be rolled back
  37933. +** itself without effecting the containing transaction. A checkpoint will
  37934. +** be automatically committed or rollback when the VDBE halts.
  37935. +**
  37936. +** The checkpoint is begun on the database file with index P1. The main
  37937. +** database file has an index of 0 and the file used for temporary tables
  37938. +** has an index of 1.
  37939. +*/
  37940. +case OP_Checkpoint: {
  37941. + int i = pOp->p1;
  37942. + if( i>=0 && i<db->nDb && db->aDb[i].pBt && db->aDb[i].inTrans==1 ){
  37943. + rc = sqliteBtreeBeginCkpt(db->aDb[i].pBt);
  37944. + if( rc==SQLITE_OK ) db->aDb[i].inTrans = 2;
  37945. + }
  37946. + break;
  37947. +}
  37948. +
  37949. +/* Opcode: Transaction P1 * *
  37950. +**
  37951. +** Begin a transaction. The transaction ends when a Commit or Rollback
  37952. +** opcode is encountered. Depending on the ON CONFLICT setting, the
  37953. +** transaction might also be rolled back if an error is encountered.
  37954. +**
  37955. +** P1 is the index of the database file on which the transaction is
  37956. +** started. Index 0 is the main database file and index 1 is the
  37957. +** file used for temporary tables.
  37958. +**
  37959. +** A write lock is obtained on the database file when a transaction is
  37960. +** started. No other process can read or write the file while the
  37961. +** transaction is underway. Starting a transaction also creates a
  37962. +** rollback journal. A transaction must be started before any changes
  37963. +** can be made to the database.
  37964. +*/
  37965. +case OP_Transaction: {
  37966. + int busy = 1;
  37967. + int i = pOp->p1;
  37968. + assert( i>=0 && i<db->nDb );
  37969. + if( db->aDb[i].inTrans ) break;
  37970. + while( db->aDb[i].pBt!=0 && busy ){
  37971. + rc = sqliteBtreeBeginTrans(db->aDb[i].pBt);
  37972. + switch( rc ){
  37973. + case SQLITE_BUSY: {
  37974. + if( db->xBusyCallback==0 ){
  37975. + p->pc = pc;
  37976. + p->undoTransOnError = 1;
  37977. + p->rc = SQLITE_BUSY;
  37978. + p->pTos = pTos;
  37979. + return SQLITE_BUSY;
  37980. + }else if( (*db->xBusyCallback)(db->pBusyArg, "", busy++)==0 ){
  37981. + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
  37982. + busy = 0;
  37983. + }
  37984. + break;
  37985. + }
  37986. + case SQLITE_READONLY: {
  37987. + rc = SQLITE_OK;
  37988. + /* Fall thru into the next case */
  37989. + }
  37990. + case SQLITE_OK: {
  37991. + p->inTempTrans = 0;
  37992. + busy = 0;
  37993. + break;
  37994. + }
  37995. + default: {
  37996. + goto abort_due_to_error;
  37997. + }
  37998. + }
  37999. + }
  38000. + db->aDb[i].inTrans = 1;
  38001. + p->undoTransOnError = 1;
  38002. + break;
  38003. +}
  38004. +
  38005. +/* Opcode: Commit * * *
  38006. +**
  38007. +** Cause all modifications to the database that have been made since the
  38008. +** last Transaction to actually take effect. No additional modifications
  38009. +** are allowed until another transaction is started. The Commit instruction
  38010. +** deletes the journal file and releases the write lock on the database.
  38011. +** A read lock continues to be held if there are still cursors open.
  38012. +*/
  38013. +case OP_Commit: {
  38014. + int i;
  38015. + if( db->xCommitCallback!=0 ){
  38016. + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
  38017. + if( db->xCommitCallback(db->pCommitArg)!=0 ){
  38018. + rc = SQLITE_CONSTRAINT;
  38019. + }
  38020. + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
  38021. + }
  38022. + for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  38023. + if( db->aDb[i].inTrans ){
  38024. + rc = sqliteBtreeCommit(db->aDb[i].pBt);
  38025. + db->aDb[i].inTrans = 0;
  38026. + }
  38027. + }
  38028. + if( rc==SQLITE_OK ){
  38029. + sqliteCommitInternalChanges(db);
  38030. + }else{
  38031. + sqliteRollbackAll(db);
  38032. + }
  38033. + break;
  38034. +}
  38035. +
  38036. +/* Opcode: Rollback P1 * *
  38037. +**
  38038. +** Cause all modifications to the database that have been made since the
  38039. +** last Transaction to be undone. The database is restored to its state
  38040. +** before the Transaction opcode was executed. No additional modifications
  38041. +** are allowed until another transaction is started.
  38042. +**
  38043. +** P1 is the index of the database file that is committed. An index of 0
  38044. +** is used for the main database and an index of 1 is used for the file used
  38045. +** to hold temporary tables.
  38046. +**
  38047. +** This instruction automatically closes all cursors and releases both
  38048. +** the read and write locks on the indicated database.
  38049. +*/
  38050. +case OP_Rollback: {
  38051. + sqliteRollbackAll(db);
  38052. + break;
  38053. +}
  38054. +
  38055. +/* Opcode: ReadCookie P1 P2 *
  38056. +**
  38057. +** Read cookie number P2 from database P1 and push it onto the stack.
  38058. +** P2==0 is the schema version. P2==1 is the database format.
  38059. +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  38060. +** the main database file and P1==1 is the database file used to store
  38061. +** temporary tables.
  38062. +**
  38063. +** There must be a read-lock on the database (either a transaction
  38064. +** must be started or there must be an open cursor) before
  38065. +** executing this instruction.
  38066. +*/
  38067. +case OP_ReadCookie: {
  38068. + int aMeta[SQLITE_N_BTREE_META];
  38069. + assert( pOp->p2<SQLITE_N_BTREE_META );
  38070. + assert( pOp->p1>=0 && pOp->p1<db->nDb );
  38071. + assert( db->aDb[pOp->p1].pBt!=0 );
  38072. + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
  38073. + pTos++;
  38074. + pTos->i = aMeta[1+pOp->p2];
  38075. + pTos->flags = MEM_Int;
  38076. + break;
  38077. +}
  38078. +
  38079. +/* Opcode: SetCookie P1 P2 *
  38080. +**
  38081. +** Write the top of the stack into cookie number P2 of database P1.
  38082. +** P2==0 is the schema version. P2==1 is the database format.
  38083. +** P2==2 is the recommended pager cache size, and so forth. P1==0 is
  38084. +** the main database file and P1==1 is the database file used to store
  38085. +** temporary tables.
  38086. +**
  38087. +** A transaction must be started before executing this opcode.
  38088. +*/
  38089. +case OP_SetCookie: {
  38090. + int aMeta[SQLITE_N_BTREE_META];
  38091. + assert( pOp->p2<SQLITE_N_BTREE_META );
  38092. + assert( pOp->p1>=0 && pOp->p1<db->nDb );
  38093. + assert( db->aDb[pOp->p1].pBt!=0 );
  38094. + assert( pTos>=p->aStack );
  38095. + Integerify(pTos)
  38096. + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
  38097. + if( rc==SQLITE_OK ){
  38098. + aMeta[1+pOp->p2] = pTos->i;
  38099. + rc = sqliteBtreeUpdateMeta(db->aDb[pOp->p1].pBt, aMeta);
  38100. + }
  38101. + Release(pTos);
  38102. + pTos--;
  38103. + break;
  38104. +}
  38105. +
  38106. +/* Opcode: VerifyCookie P1 P2 *
  38107. +**
  38108. +** Check the value of global database parameter number 0 (the
  38109. +** schema version) and make sure it is equal to P2.
  38110. +** P1 is the database number which is 0 for the main database file
  38111. +** and 1 for the file holding temporary tables and some higher number
  38112. +** for auxiliary databases.
  38113. +**
  38114. +** The cookie changes its value whenever the database schema changes.
  38115. +** This operation is used to detect when that the cookie has changed
  38116. +** and that the current process needs to reread the schema.
  38117. +**
  38118. +** Either a transaction needs to have been started or an OP_Open needs
  38119. +** to be executed (to establish a read lock) before this opcode is
  38120. +** invoked.
  38121. +*/
  38122. +case OP_VerifyCookie: {
  38123. + int aMeta[SQLITE_N_BTREE_META];
  38124. + assert( pOp->p1>=0 && pOp->p1<db->nDb );
  38125. + rc = sqliteBtreeGetMeta(db->aDb[pOp->p1].pBt, aMeta);
  38126. + if( rc==SQLITE_OK && aMeta[1]!=pOp->p2 ){
  38127. + sqliteSetString(&p->zErrMsg, "database schema has changed", (char*)0);
  38128. + rc = SQLITE_SCHEMA;
  38129. + }
  38130. + break;
  38131. +}
  38132. +
  38133. +/* Opcode: OpenRead P1 P2 P3
  38134. +**
  38135. +** Open a read-only cursor for the database table whose root page is
  38136. +** P2 in a database file. The database file is determined by an
  38137. +** integer from the top of the stack. 0 means the main database and
  38138. +** 1 means the database used for temporary tables. Give the new
  38139. +** cursor an identifier of P1. The P1 values need not be contiguous
  38140. +** but all P1 values should be small integers. It is an error for
  38141. +** P1 to be negative.
  38142. +**
  38143. +** If P2==0 then take the root page number from the next of the stack.
  38144. +**
  38145. +** There will be a read lock on the database whenever there is an
  38146. +** open cursor. If the database was unlocked prior to this instruction
  38147. +** then a read lock is acquired as part of this instruction. A read
  38148. +** lock allows other processes to read the database but prohibits
  38149. +** any other process from modifying the database. The read lock is
  38150. +** released when all cursors are closed. If this instruction attempts
  38151. +** to get a read lock but fails, the script terminates with an
  38152. +** SQLITE_BUSY error code.
  38153. +**
  38154. +** The P3 value is the name of the table or index being opened.
  38155. +** The P3 value is not actually used by this opcode and may be
  38156. +** omitted. But the code generator usually inserts the index or
  38157. +** table name into P3 to make the code easier to read.
  38158. +**
  38159. +** See also OpenWrite.
  38160. +*/
  38161. +/* Opcode: OpenWrite P1 P2 P3
  38162. +**
  38163. +** Open a read/write cursor named P1 on the table or index whose root
  38164. +** page is P2. If P2==0 then take the root page number from the stack.
  38165. +**
  38166. +** The P3 value is the name of the table or index being opened.
  38167. +** The P3 value is not actually used by this opcode and may be
  38168. +** omitted. But the code generator usually inserts the index or
  38169. +** table name into P3 to make the code easier to read.
  38170. +**
  38171. +** This instruction works just like OpenRead except that it opens the cursor
  38172. +** in read/write mode. For a given table, there can be one or more read-only
  38173. +** cursors or a single read/write cursor but not both.
  38174. +**
  38175. +** See also OpenRead.
  38176. +*/
  38177. +case OP_OpenRead:
  38178. +case OP_OpenWrite: {
  38179. + int busy = 0;
  38180. + int i = pOp->p1;
  38181. + int p2 = pOp->p2;
  38182. + int wrFlag;
  38183. + Btree *pX;
  38184. + int iDb;
  38185. +
  38186. + assert( pTos>=p->aStack );
  38187. + Integerify(pTos);
  38188. + iDb = pTos->i;
  38189. + pTos--;
  38190. + assert( iDb>=0 && iDb<db->nDb );
  38191. + pX = db->aDb[iDb].pBt;
  38192. + assert( pX!=0 );
  38193. + wrFlag = pOp->opcode==OP_OpenWrite;
  38194. + if( p2<=0 ){
  38195. + assert( pTos>=p->aStack );
  38196. + Integerify(pTos);
  38197. + p2 = pTos->i;
  38198. + pTos--;
  38199. + if( p2<2 ){
  38200. + sqliteSetString(&p->zErrMsg, "root page number less than 2", (char*)0);
  38201. + rc = SQLITE_INTERNAL;
  38202. + break;
  38203. + }
  38204. + }
  38205. + assert( i>=0 );
  38206. + if( expandCursorArraySize(p, i) ) goto no_mem;
  38207. + sqliteVdbeCleanupCursor(&p->aCsr[i]);
  38208. + memset(&p->aCsr[i], 0, sizeof(Cursor));
  38209. + p->aCsr[i].nullRow = 1;
  38210. + if( pX==0 ) break;
  38211. + do{
  38212. + rc = sqliteBtreeCursor(pX, p2, wrFlag, &p->aCsr[i].pCursor);
  38213. + switch( rc ){
  38214. + case SQLITE_BUSY: {
  38215. + if( db->xBusyCallback==0 ){
  38216. + p->pc = pc;
  38217. + p->rc = SQLITE_BUSY;
  38218. + p->pTos = &pTos[1 + (pOp->p2<=0)]; /* Operands must remain on stack */
  38219. + return SQLITE_BUSY;
  38220. + }else if( (*db->xBusyCallback)(db->pBusyArg, pOp->p3, ++busy)==0 ){
  38221. + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
  38222. + busy = 0;
  38223. + }
  38224. + break;
  38225. + }
  38226. + case SQLITE_OK: {
  38227. + busy = 0;
  38228. + break;
  38229. + }
  38230. + default: {
  38231. + goto abort_due_to_error;
  38232. + }
  38233. + }
  38234. + }while( busy );
  38235. + break;
  38236. +}
  38237. +
  38238. +/* Opcode: OpenTemp P1 P2 *
  38239. +**
  38240. +** Open a new cursor to a transient table.
  38241. +** The transient cursor is always opened read/write even if
  38242. +** the main database is read-only. The transient table is deleted
  38243. +** automatically when the cursor is closed.
  38244. +**
  38245. +** The cursor points to a BTree table if P2==0 and to a BTree index
  38246. +** if P2==1. A BTree table must have an integer key and can have arbitrary
  38247. +** data. A BTree index has no data but can have an arbitrary key.
  38248. +**
  38249. +** This opcode is used for tables that exist for the duration of a single
  38250. +** SQL statement only. Tables created using CREATE TEMPORARY TABLE
  38251. +** are opened using OP_OpenRead or OP_OpenWrite. "Temporary" in the
  38252. +** context of this opcode means for the duration of a single SQL statement
  38253. +** whereas "Temporary" in the context of CREATE TABLE means for the duration
  38254. +** of the connection to the database. Same word; different meanings.
  38255. +*/
  38256. +case OP_OpenTemp: {
  38257. + int i = pOp->p1;
  38258. + Cursor *pCx;
  38259. + assert( i>=0 );
  38260. + if( expandCursorArraySize(p, i) ) goto no_mem;
  38261. + pCx = &p->aCsr[i];
  38262. + sqliteVdbeCleanupCursor(pCx);
  38263. + memset(pCx, 0, sizeof(*pCx));
  38264. + pCx->nullRow = 1;
  38265. + rc = sqliteBtreeFactory(db, 0, 1, TEMP_PAGES, &pCx->pBt);
  38266. +
  38267. + if( rc==SQLITE_OK ){
  38268. + rc = sqliteBtreeBeginTrans(pCx->pBt);
  38269. + }
  38270. + if( rc==SQLITE_OK ){
  38271. + if( pOp->p2 ){
  38272. + int pgno;
  38273. + rc = sqliteBtreeCreateIndex(pCx->pBt, &pgno);
  38274. + if( rc==SQLITE_OK ){
  38275. + rc = sqliteBtreeCursor(pCx->pBt, pgno, 1, &pCx->pCursor);
  38276. + }
  38277. + }else{
  38278. + rc = sqliteBtreeCursor(pCx->pBt, 2, 1, &pCx->pCursor);
  38279. + }
  38280. + }
  38281. + break;
  38282. +}
  38283. +
  38284. +/* Opcode: OpenPseudo P1 * *
  38285. +**
  38286. +** Open a new cursor that points to a fake table that contains a single
  38287. +** row of data. Any attempt to write a second row of data causes the
  38288. +** first row to be deleted. All data is deleted when the cursor is
  38289. +** closed.
  38290. +**
  38291. +** A pseudo-table created by this opcode is useful for holding the
  38292. +** NEW or OLD tables in a trigger.
  38293. +*/
  38294. +case OP_OpenPseudo: {
  38295. + int i = pOp->p1;
  38296. + Cursor *pCx;
  38297. + assert( i>=0 );
  38298. + if( expandCursorArraySize(p, i) ) goto no_mem;
  38299. + pCx = &p->aCsr[i];
  38300. + sqliteVdbeCleanupCursor(pCx);
  38301. + memset(pCx, 0, sizeof(*pCx));
  38302. + pCx->nullRow = 1;
  38303. + pCx->pseudoTable = 1;
  38304. + break;
  38305. +}
  38306. +
  38307. +/* Opcode: Close P1 * *
  38308. +**
  38309. +** Close a cursor previously opened as P1. If P1 is not
  38310. +** currently open, this instruction is a no-op.
  38311. +*/
  38312. +case OP_Close: {
  38313. + int i = pOp->p1;
  38314. + if( i>=0 && i<p->nCursor ){
  38315. + sqliteVdbeCleanupCursor(&p->aCsr[i]);
  38316. + }
  38317. + break;
  38318. +}
  38319. +
  38320. +/* Opcode: MoveTo P1 P2 *
  38321. +**
  38322. +** Pop the top of the stack and use its value as a key. Reposition
  38323. +** cursor P1 so that it points to an entry with a matching key. If
  38324. +** the table contains no record with a matching key, then the cursor
  38325. +** is left pointing at the first record that is greater than the key.
  38326. +** If there are no records greater than the key and P2 is not zero,
  38327. +** then an immediate jump to P2 is made.
  38328. +**
  38329. +** See also: Found, NotFound, Distinct, MoveLt
  38330. +*/
  38331. +/* Opcode: MoveLt P1 P2 *
  38332. +**
  38333. +** Pop the top of the stack and use its value as a key. Reposition
  38334. +** cursor P1 so that it points to the entry with the largest key that is
  38335. +** less than the key popped from the stack.
  38336. +** If there are no records less than than the key and P2
  38337. +** is not zero then an immediate jump to P2 is made.
  38338. +**
  38339. +** See also: MoveTo
  38340. +*/
  38341. +case OP_MoveLt:
  38342. +case OP_MoveTo: {
  38343. + int i = pOp->p1;
  38344. + Cursor *pC;
  38345. +
  38346. + assert( pTos>=p->aStack );
  38347. + assert( i>=0 && i<p->nCursor );
  38348. + pC = &p->aCsr[i];
  38349. + if( pC->pCursor!=0 ){
  38350. + int res, oc;
  38351. + pC->nullRow = 0;
  38352. + if( pTos->flags & MEM_Int ){
  38353. + int iKey = intToKey(pTos->i);
  38354. + if( pOp->p2==0 && pOp->opcode==OP_MoveTo ){
  38355. + pC->movetoTarget = iKey;
  38356. + pC->deferredMoveto = 1;
  38357. + Release(pTos);
  38358. + pTos--;
  38359. + break;
  38360. + }
  38361. + sqliteBtreeMoveto(pC->pCursor, (char*)&iKey, sizeof(int), &res);
  38362. + pC->lastRecno = pTos->i;
  38363. + pC->recnoIsValid = res==0;
  38364. + }else{
  38365. + Stringify(pTos);
  38366. + sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
  38367. + pC->recnoIsValid = 0;
  38368. + }
  38369. + pC->deferredMoveto = 0;
  38370. + sqlite_search_count++;
  38371. + oc = pOp->opcode;
  38372. + if( oc==OP_MoveTo && res<0 ){
  38373. + sqliteBtreeNext(pC->pCursor, &res);
  38374. + pC->recnoIsValid = 0;
  38375. + if( res && pOp->p2>0 ){
  38376. + pc = pOp->p2 - 1;
  38377. + }
  38378. + }else if( oc==OP_MoveLt ){
  38379. + if( res>=0 ){
  38380. + sqliteBtreePrevious(pC->pCursor, &res);
  38381. + pC->recnoIsValid = 0;
  38382. + }else{
  38383. + /* res might be negative because the table is empty. Check to
  38384. + ** see if this is the case.
  38385. + */
  38386. + int keysize;
  38387. + res = sqliteBtreeKeySize(pC->pCursor,&keysize)!=0 || keysize==0;
  38388. + }
  38389. + if( res && pOp->p2>0 ){
  38390. + pc = pOp->p2 - 1;
  38391. + }
  38392. + }
  38393. + }
  38394. + Release(pTos);
  38395. + pTos--;
  38396. + break;
  38397. +}
  38398. +
  38399. +/* Opcode: Distinct P1 P2 *
  38400. +**
  38401. +** Use the top of the stack as a string key. If a record with that key does
  38402. +** not exist in the table of cursor P1, then jump to P2. If the record
  38403. +** does already exist, then fall thru. The cursor is left pointing
  38404. +** at the record if it exists. The key is not popped from the stack.
  38405. +**
  38406. +** This operation is similar to NotFound except that this operation
  38407. +** does not pop the key from the stack.
  38408. +**
  38409. +** See also: Found, NotFound, MoveTo, IsUnique, NotExists
  38410. +*/
  38411. +/* Opcode: Found P1 P2 *
  38412. +**
  38413. +** Use the top of the stack as a string key. If a record with that key
  38414. +** does exist in table of P1, then jump to P2. If the record
  38415. +** does not exist, then fall thru. The cursor is left pointing
  38416. +** to the record if it exists. The key is popped from the stack.
  38417. +**
  38418. +** See also: Distinct, NotFound, MoveTo, IsUnique, NotExists
  38419. +*/
  38420. +/* Opcode: NotFound P1 P2 *
  38421. +**
  38422. +** Use the top of the stack as a string key. If a record with that key
  38423. +** does not exist in table of P1, then jump to P2. If the record
  38424. +** does exist, then fall thru. The cursor is left pointing to the
  38425. +** record if it exists. The key is popped from the stack.
  38426. +**
  38427. +** The difference between this operation and Distinct is that
  38428. +** Distinct does not pop the key from the stack.
  38429. +**
  38430. +** See also: Distinct, Found, MoveTo, NotExists, IsUnique
  38431. +*/
  38432. +case OP_Distinct:
  38433. +case OP_NotFound:
  38434. +case OP_Found: {
  38435. + int i = pOp->p1;
  38436. + int alreadyExists = 0;
  38437. + Cursor *pC;
  38438. + assert( pTos>=p->aStack );
  38439. + assert( i>=0 && i<p->nCursor );
  38440. + if( (pC = &p->aCsr[i])->pCursor!=0 ){
  38441. + int res, rx;
  38442. + Stringify(pTos);
  38443. + rx = sqliteBtreeMoveto(pC->pCursor, pTos->z, pTos->n, &res);
  38444. + alreadyExists = rx==SQLITE_OK && res==0;
  38445. + pC->deferredMoveto = 0;
  38446. + }
  38447. + if( pOp->opcode==OP_Found ){
  38448. + if( alreadyExists ) pc = pOp->p2 - 1;
  38449. + }else{
  38450. + if( !alreadyExists ) pc = pOp->p2 - 1;
  38451. + }
  38452. + if( pOp->opcode!=OP_Distinct ){
  38453. + Release(pTos);
  38454. + pTos--;
  38455. + }
  38456. + break;
  38457. +}
  38458. +
  38459. +/* Opcode: IsUnique P1 P2 *
  38460. +**
  38461. +** The top of the stack is an integer record number. Call this
  38462. +** record number R. The next on the stack is an index key created
  38463. +** using MakeIdxKey. Call it K. This instruction pops R from the
  38464. +** stack but it leaves K unchanged.
  38465. +**
  38466. +** P1 is an index. So all but the last four bytes of K are an
  38467. +** index string. The last four bytes of K are a record number.
  38468. +**
  38469. +** This instruction asks if there is an entry in P1 where the
  38470. +** index string matches K but the record number is different
  38471. +** from R. If there is no such entry, then there is an immediate
  38472. +** jump to P2. If any entry does exist where the index string
  38473. +** matches K but the record number is not R, then the record
  38474. +** number for that entry is pushed onto the stack and control
  38475. +** falls through to the next instruction.
  38476. +**
  38477. +** See also: Distinct, NotFound, NotExists, Found
  38478. +*/
  38479. +case OP_IsUnique: {
  38480. + int i = pOp->p1;
  38481. + Mem *pNos = &pTos[-1];
  38482. + BtCursor *pCrsr;
  38483. + int R;
  38484. +
  38485. + /* Pop the value R off the top of the stack
  38486. + */
  38487. + assert( pNos>=p->aStack );
  38488. + Integerify(pTos);
  38489. + R = pTos->i;
  38490. + pTos--;
  38491. + assert( i>=0 && i<=p->nCursor );
  38492. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  38493. + int res, rc;
  38494. + int v; /* The record number on the P1 entry that matches K */
  38495. + char *zKey; /* The value of K */
  38496. + int nKey; /* Number of bytes in K */
  38497. +
  38498. + /* Make sure K is a string and make zKey point to K
  38499. + */
  38500. + Stringify(pNos);
  38501. + zKey = pNos->z;
  38502. + nKey = pNos->n;
  38503. + assert( nKey >= 4 );
  38504. +
  38505. + /* Search for an entry in P1 where all but the last four bytes match K.
  38506. + ** If there is no such entry, jump immediately to P2.
  38507. + */
  38508. + assert( p->aCsr[i].deferredMoveto==0 );
  38509. + rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
  38510. + if( rc!=SQLITE_OK ) goto abort_due_to_error;
  38511. + if( res<0 ){
  38512. + rc = sqliteBtreeNext(pCrsr, &res);
  38513. + if( res ){
  38514. + pc = pOp->p2 - 1;
  38515. + break;
  38516. + }
  38517. + }
  38518. + rc = sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &res);
  38519. + if( rc!=SQLITE_OK ) goto abort_due_to_error;
  38520. + if( res>0 ){
  38521. + pc = pOp->p2 - 1;
  38522. + break;
  38523. + }
  38524. +
  38525. + /* At this point, pCrsr is pointing to an entry in P1 where all but
  38526. + ** the last for bytes of the key match K. Check to see if the last
  38527. + ** four bytes of the key are different from R. If the last four
  38528. + ** bytes equal R then jump immediately to P2.
  38529. + */
  38530. + sqliteBtreeKey(pCrsr, nKey - 4, 4, (char*)&v);
  38531. + v = keyToInt(v);
  38532. + if( v==R ){
  38533. + pc = pOp->p2 - 1;
  38534. + break;
  38535. + }
  38536. +
  38537. + /* The last four bytes of the key are different from R. Convert the
  38538. + ** last four bytes of the key into an integer and push it onto the
  38539. + ** stack. (These bytes are the record number of an entry that
  38540. + ** violates a UNIQUE constraint.)
  38541. + */
  38542. + pTos++;
  38543. + pTos->i = v;
  38544. + pTos->flags = MEM_Int;
  38545. + }
  38546. + break;
  38547. +}
  38548. +
  38549. +/* Opcode: NotExists P1 P2 *
  38550. +**
  38551. +** Use the top of the stack as a integer key. If a record with that key
  38552. +** does not exist in table of P1, then jump to P2. If the record
  38553. +** does exist, then fall thru. The cursor is left pointing to the
  38554. +** record if it exists. The integer key is popped from the stack.
  38555. +**
  38556. +** The difference between this operation and NotFound is that this
  38557. +** operation assumes the key is an integer and NotFound assumes it
  38558. +** is a string.
  38559. +**
  38560. +** See also: Distinct, Found, MoveTo, NotFound, IsUnique
  38561. +*/
  38562. +case OP_NotExists: {
  38563. + int i = pOp->p1;
  38564. + BtCursor *pCrsr;
  38565. + assert( pTos>=p->aStack );
  38566. + assert( i>=0 && i<p->nCursor );
  38567. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  38568. + int res, rx, iKey;
  38569. + assert( pTos->flags & MEM_Int );
  38570. + iKey = intToKey(pTos->i);
  38571. + rx = sqliteBtreeMoveto(pCrsr, (char*)&iKey, sizeof(int), &res);
  38572. + p->aCsr[i].lastRecno = pTos->i;
  38573. + p->aCsr[i].recnoIsValid = res==0;
  38574. + p->aCsr[i].nullRow = 0;
  38575. + if( rx!=SQLITE_OK || res!=0 ){
  38576. + pc = pOp->p2 - 1;
  38577. + p->aCsr[i].recnoIsValid = 0;
  38578. + }
  38579. + }
  38580. + Release(pTos);
  38581. + pTos--;
  38582. + break;
  38583. +}
  38584. +
  38585. +/* Opcode: NewRecno P1 * *
  38586. +**
  38587. +** Get a new integer record number used as the key to a table.
  38588. +** The record number is not previously used as a key in the database
  38589. +** table that cursor P1 points to. The new record number is pushed
  38590. +** onto the stack.
  38591. +*/
  38592. +case OP_NewRecno: {
  38593. + int i = pOp->p1;
  38594. + int v = 0;
  38595. + Cursor *pC;
  38596. + assert( i>=0 && i<p->nCursor );
  38597. + if( (pC = &p->aCsr[i])->pCursor==0 ){
  38598. + v = 0;
  38599. + }else{
  38600. + /* The next rowid or record number (different terms for the same
  38601. + ** thing) is obtained in a two-step algorithm.
  38602. + **
  38603. + ** First we attempt to find the largest existing rowid and add one
  38604. + ** to that. But if the largest existing rowid is already the maximum
  38605. + ** positive integer, we have to fall through to the second
  38606. + ** probabilistic algorithm
  38607. + **
  38608. + ** The second algorithm is to select a rowid at random and see if
  38609. + ** it already exists in the table. If it does not exist, we have
  38610. + ** succeeded. If the random rowid does exist, we select a new one
  38611. + ** and try again, up to 1000 times.
  38612. + **
  38613. + ** For a table with less than 2 billion entries, the probability
  38614. + ** of not finding a unused rowid is about 1.0e-300. This is a
  38615. + ** non-zero probability, but it is still vanishingly small and should
  38616. + ** never cause a problem. You are much, much more likely to have a
  38617. + ** hardware failure than for this algorithm to fail.
  38618. + **
  38619. + ** The analysis in the previous paragraph assumes that you have a good
  38620. + ** source of random numbers. Is a library function like lrand48()
  38621. + ** good enough? Maybe. Maybe not. It's hard to know whether there
  38622. + ** might be subtle bugs is some implementations of lrand48() that
  38623. + ** could cause problems. To avoid uncertainty, SQLite uses its own
  38624. + ** random number generator based on the RC4 algorithm.
  38625. + **
  38626. + ** To promote locality of reference for repetitive inserts, the
  38627. + ** first few attempts at chosing a random rowid pick values just a little
  38628. + ** larger than the previous rowid. This has been shown experimentally
  38629. + ** to double the speed of the COPY operation.
  38630. + */
  38631. + int res, rx, cnt, x;
  38632. + cnt = 0;
  38633. + if( !pC->useRandomRowid ){
  38634. + if( pC->nextRowidValid ){
  38635. + v = pC->nextRowid;
  38636. + }else{
  38637. + rx = sqliteBtreeLast(pC->pCursor, &res);
  38638. + if( res ){
  38639. + v = 1;
  38640. + }else{
  38641. + sqliteBtreeKey(pC->pCursor, 0, sizeof(v), (void*)&v);
  38642. + v = keyToInt(v);
  38643. + if( v==0x7fffffff ){
  38644. + pC->useRandomRowid = 1;
  38645. + }else{
  38646. + v++;
  38647. + }
  38648. + }
  38649. + }
  38650. + if( v<0x7fffffff ){
  38651. + pC->nextRowidValid = 1;
  38652. + pC->nextRowid = v+1;
  38653. + }else{
  38654. + pC->nextRowidValid = 0;
  38655. + }
  38656. + }
  38657. + if( pC->useRandomRowid ){
  38658. + v = db->priorNewRowid;
  38659. + cnt = 0;
  38660. + do{
  38661. + if( v==0 || cnt>2 ){
  38662. + sqliteRandomness(sizeof(v), &v);
  38663. + if( cnt<5 ) v &= 0xffffff;
  38664. + }else{
  38665. + unsigned char r;
  38666. + sqliteRandomness(1, &r);
  38667. + v += r + 1;
  38668. + }
  38669. + if( v==0 ) continue;
  38670. + x = intToKey(v);
  38671. + rx = sqliteBtreeMoveto(pC->pCursor, &x, sizeof(int), &res);
  38672. + cnt++;
  38673. + }while( cnt<1000 && rx==SQLITE_OK && res==0 );
  38674. + db->priorNewRowid = v;
  38675. + if( rx==SQLITE_OK && res==0 ){
  38676. + rc = SQLITE_FULL;
  38677. + goto abort_due_to_error;
  38678. + }
  38679. + }
  38680. + pC->recnoIsValid = 0;
  38681. + pC->deferredMoveto = 0;
  38682. + }
  38683. + pTos++;
  38684. + pTos->i = v;
  38685. + pTos->flags = MEM_Int;
  38686. + break;
  38687. +}
  38688. +
  38689. +/* Opcode: PutIntKey P1 P2 *
  38690. +**
  38691. +** Write an entry into the table of cursor P1. A new entry is
  38692. +** created if it doesn't already exist or the data for an existing
  38693. +** entry is overwritten. The data is the value on the top of the
  38694. +** stack. The key is the next value down on the stack. The key must
  38695. +** be an integer. The stack is popped twice by this instruction.
  38696. +**
  38697. +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  38698. +** incremented (otherwise not). If the OPFLAG_CSCHANGE flag is set,
  38699. +** then the current statement change count is incremented (otherwise not).
  38700. +** If the OPFLAG_LASTROWID flag of P2 is set, then rowid is
  38701. +** stored for subsequent return by the sqlite_last_insert_rowid() function
  38702. +** (otherwise it's unmodified).
  38703. +*/
  38704. +/* Opcode: PutStrKey P1 * *
  38705. +**
  38706. +** Write an entry into the table of cursor P1. A new entry is
  38707. +** created if it doesn't already exist or the data for an existing
  38708. +** entry is overwritten. The data is the value on the top of the
  38709. +** stack. The key is the next value down on the stack. The key must
  38710. +** be a string. The stack is popped twice by this instruction.
  38711. +**
  38712. +** P1 may not be a pseudo-table opened using the OpenPseudo opcode.
  38713. +*/
  38714. +case OP_PutIntKey:
  38715. +case OP_PutStrKey: {
  38716. + Mem *pNos = &pTos[-1];
  38717. + int i = pOp->p1;
  38718. + Cursor *pC;
  38719. + assert( pNos>=p->aStack );
  38720. + assert( i>=0 && i<p->nCursor );
  38721. + if( ((pC = &p->aCsr[i])->pCursor!=0 || pC->pseudoTable) ){
  38722. + char *zKey;
  38723. + int nKey, iKey;
  38724. + if( pOp->opcode==OP_PutStrKey ){
  38725. + Stringify(pNos);
  38726. + nKey = pNos->n;
  38727. + zKey = pNos->z;
  38728. + }else{
  38729. + assert( pNos->flags & MEM_Int );
  38730. + nKey = sizeof(int);
  38731. + iKey = intToKey(pNos->i);
  38732. + zKey = (char*)&iKey;
  38733. + if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
  38734. + if( pOp->p2 & OPFLAG_LASTROWID ) db->lastRowid = pNos->i;
  38735. + if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
  38736. + if( pC->nextRowidValid && pTos->i>=pC->nextRowid ){
  38737. + pC->nextRowidValid = 0;
  38738. + }
  38739. + }
  38740. + if( pTos->flags & MEM_Null ){
  38741. + pTos->z = 0;
  38742. + pTos->n = 0;
  38743. + }else{
  38744. + assert( pTos->flags & MEM_Str );
  38745. + }
  38746. + if( pC->pseudoTable ){
  38747. + /* PutStrKey does not work for pseudo-tables.
  38748. + ** The following assert makes sure we are not trying to use
  38749. + ** PutStrKey on a pseudo-table
  38750. + */
  38751. + assert( pOp->opcode==OP_PutIntKey );
  38752. + sqliteFree(pC->pData);
  38753. + pC->iKey = iKey;
  38754. + pC->nData = pTos->n;
  38755. + if( pTos->flags & MEM_Dyn ){
  38756. + pC->pData = pTos->z;
  38757. + pTos->flags = MEM_Null;
  38758. + }else{
  38759. + pC->pData = sqliteMallocRaw( pC->nData );
  38760. + if( pC->pData ){
  38761. + memcpy(pC->pData, pTos->z, pC->nData);
  38762. + }
  38763. + }
  38764. + pC->nullRow = 0;
  38765. + }else{
  38766. + rc = sqliteBtreeInsert(pC->pCursor, zKey, nKey, pTos->z, pTos->n);
  38767. + }
  38768. + pC->recnoIsValid = 0;
  38769. + pC->deferredMoveto = 0;
  38770. + }
  38771. + popStack(&pTos, 2);
  38772. + break;
  38773. +}
  38774. +
  38775. +/* Opcode: Delete P1 P2 *
  38776. +**
  38777. +** Delete the record at which the P1 cursor is currently pointing.
  38778. +**
  38779. +** The cursor will be left pointing at either the next or the previous
  38780. +** record in the table. If it is left pointing at the next record, then
  38781. +** the next Next instruction will be a no-op. Hence it is OK to delete
  38782. +** a record from within an Next loop.
  38783. +**
  38784. +** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  38785. +** incremented (otherwise not). If OPFLAG_CSCHANGE flag is set,
  38786. +** then the current statement change count is incremented (otherwise not).
  38787. +**
  38788. +** If P1 is a pseudo-table, then this instruction is a no-op.
  38789. +*/
  38790. +case OP_Delete: {
  38791. + int i = pOp->p1;
  38792. + Cursor *pC;
  38793. + assert( i>=0 && i<p->nCursor );
  38794. + pC = &p->aCsr[i];
  38795. + if( pC->pCursor!=0 ){
  38796. + sqliteVdbeCursorMoveto(pC);
  38797. + rc = sqliteBtreeDelete(pC->pCursor);
  38798. + pC->nextRowidValid = 0;
  38799. + }
  38800. + if( pOp->p2 & OPFLAG_NCHANGE ) db->nChange++;
  38801. + if( pOp->p2 & OPFLAG_CSCHANGE ) db->csChange++;
  38802. + break;
  38803. +}
  38804. +
  38805. +/* Opcode: SetCounts * * *
  38806. +**
  38807. +** Called at end of statement. Updates lsChange (last statement change count)
  38808. +** and resets csChange (current statement change count) to 0.
  38809. +*/
  38810. +case OP_SetCounts: {
  38811. + db->lsChange=db->csChange;
  38812. + db->csChange=0;
  38813. + break;
  38814. +}
  38815. +
  38816. +/* Opcode: KeyAsData P1 P2 *
  38817. +**
  38818. +** Turn the key-as-data mode for cursor P1 either on (if P2==1) or
  38819. +** off (if P2==0). In key-as-data mode, the OP_Column opcode pulls
  38820. +** data off of the key rather than the data. This is used for
  38821. +** processing compound selects.
  38822. +*/
  38823. +case OP_KeyAsData: {
  38824. + int i = pOp->p1;
  38825. + assert( i>=0 && i<p->nCursor );
  38826. + p->aCsr[i].keyAsData = pOp->p2;
  38827. + break;
  38828. +}
  38829. +
  38830. +/* Opcode: RowData P1 * *
  38831. +**
  38832. +** Push onto the stack the complete row data for cursor P1.
  38833. +** There is no interpretation of the data. It is just copied
  38834. +** onto the stack exactly as it is found in the database file.
  38835. +**
  38836. +** If the cursor is not pointing to a valid row, a NULL is pushed
  38837. +** onto the stack.
  38838. +*/
  38839. +/* Opcode: RowKey P1 * *
  38840. +**
  38841. +** Push onto the stack the complete row key for cursor P1.
  38842. +** There is no interpretation of the key. It is just copied
  38843. +** onto the stack exactly as it is found in the database file.
  38844. +**
  38845. +** If the cursor is not pointing to a valid row, a NULL is pushed
  38846. +** onto the stack.
  38847. +*/
  38848. +case OP_RowKey:
  38849. +case OP_RowData: {
  38850. + int i = pOp->p1;
  38851. + Cursor *pC;
  38852. + int n;
  38853. +
  38854. + pTos++;
  38855. + assert( i>=0 && i<p->nCursor );
  38856. + pC = &p->aCsr[i];
  38857. + if( pC->nullRow ){
  38858. + pTos->flags = MEM_Null;
  38859. + }else if( pC->pCursor!=0 ){
  38860. + BtCursor *pCrsr = pC->pCursor;
  38861. + sqliteVdbeCursorMoveto(pC);
  38862. + if( pC->nullRow ){
  38863. + pTos->flags = MEM_Null;
  38864. + break;
  38865. + }else if( pC->keyAsData || pOp->opcode==OP_RowKey ){
  38866. + sqliteBtreeKeySize(pCrsr, &n);
  38867. + }else{
  38868. + sqliteBtreeDataSize(pCrsr, &n);
  38869. + }
  38870. + pTos->n = n;
  38871. + if( n<=NBFS ){
  38872. + pTos->flags = MEM_Str | MEM_Short;
  38873. + pTos->z = pTos->zShort;
  38874. + }else{
  38875. + char *z = sqliteMallocRaw( n );
  38876. + if( z==0 ) goto no_mem;
  38877. + pTos->flags = MEM_Str | MEM_Dyn;
  38878. + pTos->z = z;
  38879. + }
  38880. + if( pC->keyAsData || pOp->opcode==OP_RowKey ){
  38881. + sqliteBtreeKey(pCrsr, 0, n, pTos->z);
  38882. + }else{
  38883. + sqliteBtreeData(pCrsr, 0, n, pTos->z);
  38884. + }
  38885. + }else if( pC->pseudoTable ){
  38886. + pTos->n = pC->nData;
  38887. + pTos->z = pC->pData;
  38888. + pTos->flags = MEM_Str|MEM_Ephem;
  38889. + }else{
  38890. + pTos->flags = MEM_Null;
  38891. + }
  38892. + break;
  38893. +}
  38894. +
  38895. +/* Opcode: Column P1 P2 *
  38896. +**
  38897. +** Interpret the data that cursor P1 points to as
  38898. +** a structure built using the MakeRecord instruction.
  38899. +** (See the MakeRecord opcode for additional information about
  38900. +** the format of the data.)
  38901. +** Push onto the stack the value of the P2-th column contained
  38902. +** in the data.
  38903. +**
  38904. +** If the KeyAsData opcode has previously executed on this cursor,
  38905. +** then the field might be extracted from the key rather than the
  38906. +** data.
  38907. +**
  38908. +** If P1 is negative, then the record is stored on the stack rather
  38909. +** than in a table. For P1==-1, the top of the stack is used.
  38910. +** For P1==-2, the next on the stack is used. And so forth. The
  38911. +** value pushed is always just a pointer into the record which is
  38912. +** stored further down on the stack. The column value is not copied.
  38913. +*/
  38914. +case OP_Column: {
  38915. + int amt, offset, end, payloadSize;
  38916. + int i = pOp->p1;
  38917. + int p2 = pOp->p2;
  38918. + Cursor *pC;
  38919. + char *zRec;
  38920. + BtCursor *pCrsr;
  38921. + int idxWidth;
  38922. + unsigned char aHdr[10];
  38923. +
  38924. + assert( i<p->nCursor );
  38925. + pTos++;
  38926. + if( i<0 ){
  38927. + assert( &pTos[i]>=p->aStack );
  38928. + assert( pTos[i].flags & MEM_Str );
  38929. + zRec = pTos[i].z;
  38930. + payloadSize = pTos[i].n;
  38931. + }else if( (pC = &p->aCsr[i])->pCursor!=0 ){
  38932. + sqliteVdbeCursorMoveto(pC);
  38933. + zRec = 0;
  38934. + pCrsr = pC->pCursor;
  38935. + if( pC->nullRow ){
  38936. + payloadSize = 0;
  38937. + }else if( pC->keyAsData ){
  38938. + sqliteBtreeKeySize(pCrsr, &payloadSize);
  38939. + }else{
  38940. + sqliteBtreeDataSize(pCrsr, &payloadSize);
  38941. + }
  38942. + }else if( pC->pseudoTable ){
  38943. + payloadSize = pC->nData;
  38944. + zRec = pC->pData;
  38945. + assert( payloadSize==0 || zRec!=0 );
  38946. + }else{
  38947. + payloadSize = 0;
  38948. + }
  38949. +
  38950. + /* Figure out how many bytes in the column data and where the column
  38951. + ** data begins.
  38952. + */
  38953. + if( payloadSize==0 ){
  38954. + pTos->flags = MEM_Null;
  38955. + break;
  38956. + }else if( payloadSize<256 ){
  38957. + idxWidth = 1;
  38958. + }else if( payloadSize<65536 ){
  38959. + idxWidth = 2;
  38960. + }else{
  38961. + idxWidth = 3;
  38962. + }
  38963. +
  38964. + /* Figure out where the requested column is stored and how big it is.
  38965. + */
  38966. + if( payloadSize < idxWidth*(p2+1) ){
  38967. + rc = SQLITE_CORRUPT;
  38968. + goto abort_due_to_error;
  38969. + }
  38970. + if( zRec ){
  38971. + memcpy(aHdr, &zRec[idxWidth*p2], idxWidth*2);
  38972. + }else if( pC->keyAsData ){
  38973. + sqliteBtreeKey(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
  38974. + }else{
  38975. + sqliteBtreeData(pCrsr, idxWidth*p2, idxWidth*2, (char*)aHdr);
  38976. + }
  38977. + offset = aHdr[0];
  38978. + end = aHdr[idxWidth];
  38979. + if( idxWidth>1 ){
  38980. + offset |= aHdr[1]<<8;
  38981. + end |= aHdr[idxWidth+1]<<8;
  38982. + if( idxWidth>2 ){
  38983. + offset |= aHdr[2]<<16;
  38984. + end |= aHdr[idxWidth+2]<<16;
  38985. + }
  38986. + }
  38987. + amt = end - offset;
  38988. + if( amt<0 || offset<0 || end>payloadSize ){
  38989. + rc = SQLITE_CORRUPT;
  38990. + goto abort_due_to_error;
  38991. + }
  38992. +
  38993. + /* amt and offset now hold the offset to the start of data and the
  38994. + ** amount of data. Go get the data and put it on the stack.
  38995. + */
  38996. + pTos->n = amt;
  38997. + if( amt==0 ){
  38998. + pTos->flags = MEM_Null;
  38999. + }else if( zRec ){
  39000. + pTos->flags = MEM_Str | MEM_Ephem;
  39001. + pTos->z = &zRec[offset];
  39002. + }else{
  39003. + if( amt<=NBFS ){
  39004. + pTos->flags = MEM_Str | MEM_Short;
  39005. + pTos->z = pTos->zShort;
  39006. + }else{
  39007. + char *z = sqliteMallocRaw( amt );
  39008. + if( z==0 ) goto no_mem;
  39009. + pTos->flags = MEM_Str | MEM_Dyn;
  39010. + pTos->z = z;
  39011. + }
  39012. + if( pC->keyAsData ){
  39013. + sqliteBtreeKey(pCrsr, offset, amt, pTos->z);
  39014. + }else{
  39015. + sqliteBtreeData(pCrsr, offset, amt, pTos->z);
  39016. + }
  39017. + }
  39018. + break;
  39019. +}
  39020. +
  39021. +/* Opcode: Recno P1 * *
  39022. +**
  39023. +** Push onto the stack an integer which is the first 4 bytes of the
  39024. +** the key to the current entry in a sequential scan of the database
  39025. +** file P1. The sequential scan should have been started using the
  39026. +** Next opcode.
  39027. +*/
  39028. +case OP_Recno: {
  39029. + int i = pOp->p1;
  39030. + Cursor *pC;
  39031. + int v;
  39032. +
  39033. + assert( i>=0 && i<p->nCursor );
  39034. + pC = &p->aCsr[i];
  39035. + sqliteVdbeCursorMoveto(pC);
  39036. + pTos++;
  39037. + if( pC->recnoIsValid ){
  39038. + v = pC->lastRecno;
  39039. + }else if( pC->pseudoTable ){
  39040. + v = keyToInt(pC->iKey);
  39041. + }else if( pC->nullRow || pC->pCursor==0 ){
  39042. + pTos->flags = MEM_Null;
  39043. + break;
  39044. + }else{
  39045. + assert( pC->pCursor!=0 );
  39046. + sqliteBtreeKey(pC->pCursor, 0, sizeof(u32), (char*)&v);
  39047. + v = keyToInt(v);
  39048. + }
  39049. + pTos->i = v;
  39050. + pTos->flags = MEM_Int;
  39051. + break;
  39052. +}
  39053. +
  39054. +/* Opcode: FullKey P1 * *
  39055. +**
  39056. +** Extract the complete key from the record that cursor P1 is currently
  39057. +** pointing to and push the key onto the stack as a string.
  39058. +**
  39059. +** Compare this opcode to Recno. The Recno opcode extracts the first
  39060. +** 4 bytes of the key and pushes those bytes onto the stack as an
  39061. +** integer. This instruction pushes the entire key as a string.
  39062. +**
  39063. +** This opcode may not be used on a pseudo-table.
  39064. +*/
  39065. +case OP_FullKey: {
  39066. + int i = pOp->p1;
  39067. + BtCursor *pCrsr;
  39068. +
  39069. + assert( p->aCsr[i].keyAsData );
  39070. + assert( !p->aCsr[i].pseudoTable );
  39071. + assert( i>=0 && i<p->nCursor );
  39072. + pTos++;
  39073. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  39074. + int amt;
  39075. + char *z;
  39076. +
  39077. + sqliteVdbeCursorMoveto(&p->aCsr[i]);
  39078. + sqliteBtreeKeySize(pCrsr, &amt);
  39079. + if( amt<=0 ){
  39080. + rc = SQLITE_CORRUPT;
  39081. + goto abort_due_to_error;
  39082. + }
  39083. + if( amt>NBFS ){
  39084. + z = sqliteMallocRaw( amt );
  39085. + if( z==0 ) goto no_mem;
  39086. + pTos->flags = MEM_Str | MEM_Dyn;
  39087. + }else{
  39088. + z = pTos->zShort;
  39089. + pTos->flags = MEM_Str | MEM_Short;
  39090. + }
  39091. + sqliteBtreeKey(pCrsr, 0, amt, z);
  39092. + pTos->z = z;
  39093. + pTos->n = amt;
  39094. + }
  39095. + break;
  39096. +}
  39097. +
  39098. +/* Opcode: NullRow P1 * *
  39099. +**
  39100. +** Move the cursor P1 to a null row. Any OP_Column operations
  39101. +** that occur while the cursor is on the null row will always push
  39102. +** a NULL onto the stack.
  39103. +*/
  39104. +case OP_NullRow: {
  39105. + int i = pOp->p1;
  39106. +
  39107. + assert( i>=0 && i<p->nCursor );
  39108. + p->aCsr[i].nullRow = 1;
  39109. + p->aCsr[i].recnoIsValid = 0;
  39110. + break;
  39111. +}
  39112. +
  39113. +/* Opcode: Last P1 P2 *
  39114. +**
  39115. +** The next use of the Recno or Column or Next instruction for P1
  39116. +** will refer to the last entry in the database table or index.
  39117. +** If the table or index is empty and P2>0, then jump immediately to P2.
  39118. +** If P2 is 0 or if the table or index is not empty, fall through
  39119. +** to the following instruction.
  39120. +*/
  39121. +case OP_Last: {
  39122. + int i = pOp->p1;
  39123. + Cursor *pC;
  39124. + BtCursor *pCrsr;
  39125. +
  39126. + assert( i>=0 && i<p->nCursor );
  39127. + pC = &p->aCsr[i];
  39128. + if( (pCrsr = pC->pCursor)!=0 ){
  39129. + int res;
  39130. + rc = sqliteBtreeLast(pCrsr, &res);
  39131. + pC->nullRow = res;
  39132. + pC->deferredMoveto = 0;
  39133. + if( res && pOp->p2>0 ){
  39134. + pc = pOp->p2 - 1;
  39135. + }
  39136. + }else{
  39137. + pC->nullRow = 0;
  39138. + }
  39139. + break;
  39140. +}
  39141. +
  39142. +/* Opcode: Rewind P1 P2 *
  39143. +**
  39144. +** The next use of the Recno or Column or Next instruction for P1
  39145. +** will refer to the first entry in the database table or index.
  39146. +** If the table or index is empty and P2>0, then jump immediately to P2.
  39147. +** If P2 is 0 or if the table or index is not empty, fall through
  39148. +** to the following instruction.
  39149. +*/
  39150. +case OP_Rewind: {
  39151. + int i = pOp->p1;
  39152. + Cursor *pC;
  39153. + BtCursor *pCrsr;
  39154. +
  39155. + assert( i>=0 && i<p->nCursor );
  39156. + pC = &p->aCsr[i];
  39157. + if( (pCrsr = pC->pCursor)!=0 ){
  39158. + int res;
  39159. + rc = sqliteBtreeFirst(pCrsr, &res);
  39160. + pC->atFirst = res==0;
  39161. + pC->nullRow = res;
  39162. + pC->deferredMoveto = 0;
  39163. + if( res && pOp->p2>0 ){
  39164. + pc = pOp->p2 - 1;
  39165. + }
  39166. + }else{
  39167. + pC->nullRow = 0;
  39168. + }
  39169. + break;
  39170. +}
  39171. +
  39172. +/* Opcode: Next P1 P2 *
  39173. +**
  39174. +** Advance cursor P1 so that it points to the next key/data pair in its
  39175. +** table or index. If there are no more key/value pairs then fall through
  39176. +** to the following instruction. But if the cursor advance was successful,
  39177. +** jump immediately to P2.
  39178. +**
  39179. +** See also: Prev
  39180. +*/
  39181. +/* Opcode: Prev P1 P2 *
  39182. +**
  39183. +** Back up cursor P1 so that it points to the previous key/data pair in its
  39184. +** table or index. If there is no previous key/value pairs then fall through
  39185. +** to the following instruction. But if the cursor backup was successful,
  39186. +** jump immediately to P2.
  39187. +*/
  39188. +case OP_Prev:
  39189. +case OP_Next: {
  39190. + Cursor *pC;
  39191. + BtCursor *pCrsr;
  39192. +
  39193. + CHECK_FOR_INTERRUPT;
  39194. + assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  39195. + pC = &p->aCsr[pOp->p1];
  39196. + if( (pCrsr = pC->pCursor)!=0 ){
  39197. + int res;
  39198. + if( pC->nullRow ){
  39199. + res = 1;
  39200. + }else{
  39201. + assert( pC->deferredMoveto==0 );
  39202. + rc = pOp->opcode==OP_Next ? sqliteBtreeNext(pCrsr, &res) :
  39203. + sqliteBtreePrevious(pCrsr, &res);
  39204. + pC->nullRow = res;
  39205. + }
  39206. + if( res==0 ){
  39207. + pc = pOp->p2 - 1;
  39208. + sqlite_search_count++;
  39209. + }
  39210. + }else{
  39211. + pC->nullRow = 1;
  39212. + }
  39213. + pC->recnoIsValid = 0;
  39214. + break;
  39215. +}
  39216. +
  39217. +/* Opcode: IdxPut P1 P2 P3
  39218. +**
  39219. +** The top of the stack holds a SQL index key made using the
  39220. +** MakeIdxKey instruction. This opcode writes that key into the
  39221. +** index P1. Data for the entry is nil.
  39222. +**
  39223. +** If P2==1, then the key must be unique. If the key is not unique,
  39224. +** the program aborts with a SQLITE_CONSTRAINT error and the database
  39225. +** is rolled back. If P3 is not null, then it becomes part of the
  39226. +** error message returned with the SQLITE_CONSTRAINT.
  39227. +*/
  39228. +case OP_IdxPut: {
  39229. + int i = pOp->p1;
  39230. + BtCursor *pCrsr;
  39231. + assert( pTos>=p->aStack );
  39232. + assert( i>=0 && i<p->nCursor );
  39233. + assert( pTos->flags & MEM_Str );
  39234. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  39235. + int nKey = pTos->n;
  39236. + const char *zKey = pTos->z;
  39237. + if( pOp->p2 ){
  39238. + int res, n;
  39239. + assert( nKey >= 4 );
  39240. + rc = sqliteBtreeMoveto(pCrsr, zKey, nKey-4, &res);
  39241. + if( rc!=SQLITE_OK ) goto abort_due_to_error;
  39242. + while( res!=0 ){
  39243. + int c;
  39244. + sqliteBtreeKeySize(pCrsr, &n);
  39245. + if( n==nKey
  39246. + && sqliteBtreeKeyCompare(pCrsr, zKey, nKey-4, 4, &c)==SQLITE_OK
  39247. + && c==0
  39248. + ){
  39249. + rc = SQLITE_CONSTRAINT;
  39250. + if( pOp->p3 && pOp->p3[0] ){
  39251. + sqliteSetString(&p->zErrMsg, pOp->p3, (char*)0);
  39252. + }
  39253. + goto abort_due_to_error;
  39254. + }
  39255. + if( res<0 ){
  39256. + sqliteBtreeNext(pCrsr, &res);
  39257. + res = +1;
  39258. + }else{
  39259. + break;
  39260. + }
  39261. + }
  39262. + }
  39263. + rc = sqliteBtreeInsert(pCrsr, zKey, nKey, "", 0);
  39264. + assert( p->aCsr[i].deferredMoveto==0 );
  39265. + }
  39266. + Release(pTos);
  39267. + pTos--;
  39268. + break;
  39269. +}
  39270. +
  39271. +/* Opcode: IdxDelete P1 * *
  39272. +**
  39273. +** The top of the stack is an index key built using the MakeIdxKey opcode.
  39274. +** This opcode removes that entry from the index.
  39275. +*/
  39276. +case OP_IdxDelete: {
  39277. + int i = pOp->p1;
  39278. + BtCursor *pCrsr;
  39279. + assert( pTos>=p->aStack );
  39280. + assert( pTos->flags & MEM_Str );
  39281. + assert( i>=0 && i<p->nCursor );
  39282. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  39283. + int rx, res;
  39284. + rx = sqliteBtreeMoveto(pCrsr, pTos->z, pTos->n, &res);
  39285. + if( rx==SQLITE_OK && res==0 ){
  39286. + rc = sqliteBtreeDelete(pCrsr);
  39287. + }
  39288. + assert( p->aCsr[i].deferredMoveto==0 );
  39289. + }
  39290. + Release(pTos);
  39291. + pTos--;
  39292. + break;
  39293. +}
  39294. +
  39295. +/* Opcode: IdxRecno P1 * *
  39296. +**
  39297. +** Push onto the stack an integer which is the last 4 bytes of the
  39298. +** the key to the current entry in index P1. These 4 bytes should
  39299. +** be the record number of the table entry to which this index entry
  39300. +** points.
  39301. +**
  39302. +** See also: Recno, MakeIdxKey.
  39303. +*/
  39304. +case OP_IdxRecno: {
  39305. + int i = pOp->p1;
  39306. + BtCursor *pCrsr;
  39307. +
  39308. + assert( i>=0 && i<p->nCursor );
  39309. + pTos++;
  39310. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  39311. + int v;
  39312. + int sz;
  39313. + assert( p->aCsr[i].deferredMoveto==0 );
  39314. + sqliteBtreeKeySize(pCrsr, &sz);
  39315. + if( sz<sizeof(u32) ){
  39316. + pTos->flags = MEM_Null;
  39317. + }else{
  39318. + sqliteBtreeKey(pCrsr, sz - sizeof(u32), sizeof(u32), (char*)&v);
  39319. + v = keyToInt(v);
  39320. + pTos->i = v;
  39321. + pTos->flags = MEM_Int;
  39322. + }
  39323. + }else{
  39324. + pTos->flags = MEM_Null;
  39325. + }
  39326. + break;
  39327. +}
  39328. +
  39329. +/* Opcode: IdxGT P1 P2 *
  39330. +**
  39331. +** Compare the top of the stack against the key on the index entry that
  39332. +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
  39333. +** index entry. If the index entry is greater than the top of the stack
  39334. +** then jump to P2. Otherwise fall through to the next instruction.
  39335. +** In either case, the stack is popped once.
  39336. +*/
  39337. +/* Opcode: IdxGE P1 P2 *
  39338. +**
  39339. +** Compare the top of the stack against the key on the index entry that
  39340. +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
  39341. +** index entry. If the index entry is greater than or equal to
  39342. +** the top of the stack
  39343. +** then jump to P2. Otherwise fall through to the next instruction.
  39344. +** In either case, the stack is popped once.
  39345. +*/
  39346. +/* Opcode: IdxLT P1 P2 *
  39347. +**
  39348. +** Compare the top of the stack against the key on the index entry that
  39349. +** cursor P1 is currently pointing to. Ignore the last 4 bytes of the
  39350. +** index entry. If the index entry is less than the top of the stack
  39351. +** then jump to P2. Otherwise fall through to the next instruction.
  39352. +** In either case, the stack is popped once.
  39353. +*/
  39354. +case OP_IdxLT:
  39355. +case OP_IdxGT:
  39356. +case OP_IdxGE: {
  39357. + int i= pOp->p1;
  39358. + BtCursor *pCrsr;
  39359. +
  39360. + assert( i>=0 && i<p->nCursor );
  39361. + assert( pTos>=p->aStack );
  39362. + if( (pCrsr = p->aCsr[i].pCursor)!=0 ){
  39363. + int res, rc;
  39364. +
  39365. + Stringify(pTos);
  39366. + assert( p->aCsr[i].deferredMoveto==0 );
  39367. + rc = sqliteBtreeKeyCompare(pCrsr, pTos->z, pTos->n, 4, &res);
  39368. + if( rc!=SQLITE_OK ){
  39369. + break;
  39370. + }
  39371. + if( pOp->opcode==OP_IdxLT ){
  39372. + res = -res;
  39373. + }else if( pOp->opcode==OP_IdxGE ){
  39374. + res++;
  39375. + }
  39376. + if( res>0 ){
  39377. + pc = pOp->p2 - 1 ;
  39378. + }
  39379. + }
  39380. + Release(pTos);
  39381. + pTos--;
  39382. + break;
  39383. +}
  39384. +
  39385. +/* Opcode: IdxIsNull P1 P2 *
  39386. +**
  39387. +** The top of the stack contains an index entry such as might be generated
  39388. +** by the MakeIdxKey opcode. This routine looks at the first P1 fields of
  39389. +** that key. If any of the first P1 fields are NULL, then a jump is made
  39390. +** to address P2. Otherwise we fall straight through.
  39391. +**
  39392. +** The index entry is always popped from the stack.
  39393. +*/
  39394. +case OP_IdxIsNull: {
  39395. + int i = pOp->p1;
  39396. + int k, n;
  39397. + const char *z;
  39398. +
  39399. + assert( pTos>=p->aStack );
  39400. + assert( pTos->flags & MEM_Str );
  39401. + z = pTos->z;
  39402. + n = pTos->n;
  39403. + for(k=0; k<n && i>0; i--){
  39404. + if( z[k]=='a' ){
  39405. + pc = pOp->p2-1;
  39406. + break;
  39407. + }
  39408. + while( k<n && z[k] ){ k++; }
  39409. + k++;
  39410. + }
  39411. + Release(pTos);
  39412. + pTos--;
  39413. + break;
  39414. +}
  39415. +
  39416. +/* Opcode: Destroy P1 P2 *
  39417. +**
  39418. +** Delete an entire database table or index whose root page in the database
  39419. +** file is given by P1.
  39420. +**
  39421. +** The table being destroyed is in the main database file if P2==0. If
  39422. +** P2==1 then the table to be clear is in the auxiliary database file
  39423. +** that is used to store tables create using CREATE TEMPORARY TABLE.
  39424. +**
  39425. +** See also: Clear
  39426. +*/
  39427. +case OP_Destroy: {
  39428. + rc = sqliteBtreeDropTable(db->aDb[pOp->p2].pBt, pOp->p1);
  39429. + break;
  39430. +}
  39431. +
  39432. +/* Opcode: Clear P1 P2 *
  39433. +**
  39434. +** Delete all contents of the database table or index whose root page
  39435. +** in the database file is given by P1. But, unlike Destroy, do not
  39436. +** remove the table or index from the database file.
  39437. +**
  39438. +** The table being clear is in the main database file if P2==0. If
  39439. +** P2==1 then the table to be clear is in the auxiliary database file
  39440. +** that is used to store tables create using CREATE TEMPORARY TABLE.
  39441. +**
  39442. +** See also: Destroy
  39443. +*/
  39444. +case OP_Clear: {
  39445. + rc = sqliteBtreeClearTable(db->aDb[pOp->p2].pBt, pOp->p1);
  39446. + break;
  39447. +}
  39448. +
  39449. +/* Opcode: CreateTable * P2 P3
  39450. +**
  39451. +** Allocate a new table in the main database file if P2==0 or in the
  39452. +** auxiliary database file if P2==1. Push the page number
  39453. +** for the root page of the new table onto the stack.
  39454. +**
  39455. +** The root page number is also written to a memory location that P3
  39456. +** points to. This is the mechanism is used to write the root page
  39457. +** number into the parser's internal data structures that describe the
  39458. +** new table.
  39459. +**
  39460. +** The difference between a table and an index is this: A table must
  39461. +** have a 4-byte integer key and can have arbitrary data. An index
  39462. +** has an arbitrary key but no data.
  39463. +**
  39464. +** See also: CreateIndex
  39465. +*/
  39466. +/* Opcode: CreateIndex * P2 P3
  39467. +**
  39468. +** Allocate a new index in the main database file if P2==0 or in the
  39469. +** auxiliary database file if P2==1. Push the page number of the
  39470. +** root page of the new index onto the stack.
  39471. +**
  39472. +** See documentation on OP_CreateTable for additional information.
  39473. +*/
  39474. +case OP_CreateIndex:
  39475. +case OP_CreateTable: {
  39476. + int pgno;
  39477. + assert( pOp->p3!=0 && pOp->p3type==P3_POINTER );
  39478. + assert( pOp->p2>=0 && pOp->p2<db->nDb );
  39479. + assert( db->aDb[pOp->p2].pBt!=0 );
  39480. + if( pOp->opcode==OP_CreateTable ){
  39481. + rc = sqliteBtreeCreateTable(db->aDb[pOp->p2].pBt, &pgno);
  39482. + }else{
  39483. + rc = sqliteBtreeCreateIndex(db->aDb[pOp->p2].pBt, &pgno);
  39484. + }
  39485. + pTos++;
  39486. + if( rc==SQLITE_OK ){
  39487. + pTos->i = pgno;
  39488. + pTos->flags = MEM_Int;
  39489. + *(u32*)pOp->p3 = pgno;
  39490. + pOp->p3 = 0;
  39491. + }else{
  39492. + pTos->flags = MEM_Null;
  39493. + }
  39494. + break;
  39495. +}
  39496. +
  39497. +/* Opcode: IntegrityCk P1 P2 *
  39498. +**
  39499. +** Do an analysis of the currently open database. Push onto the
  39500. +** stack the text of an error message describing any problems.
  39501. +** If there are no errors, push a "ok" onto the stack.
  39502. +**
  39503. +** P1 is the index of a set that contains the root page numbers
  39504. +** for all tables and indices in the main database file. The set
  39505. +** is cleared by this opcode. In other words, after this opcode
  39506. +** has executed, the set will be empty.
  39507. +**
  39508. +** If P2 is not zero, the check is done on the auxiliary database
  39509. +** file, not the main database file.
  39510. +**
  39511. +** This opcode is used for testing purposes only.
  39512. +*/
  39513. +case OP_IntegrityCk: {
  39514. + int nRoot;
  39515. + int *aRoot;
  39516. + int iSet = pOp->p1;
  39517. + Set *pSet;
  39518. + int j;
  39519. + HashElem *i;
  39520. + char *z;
  39521. +
  39522. + assert( iSet>=0 && iSet<p->nSet );
  39523. + pTos++;
  39524. + pSet = &p->aSet[iSet];
  39525. + nRoot = sqliteHashCount(&pSet->hash);
  39526. + aRoot = sqliteMallocRaw( sizeof(int)*(nRoot+1) );
  39527. + if( aRoot==0 ) goto no_mem;
  39528. + for(j=0, i=sqliteHashFirst(&pSet->hash); i; i=sqliteHashNext(i), j++){
  39529. + toInt((char*)sqliteHashKey(i), &aRoot[j]);
  39530. + }
  39531. + aRoot[j] = 0;
  39532. + sqliteHashClear(&pSet->hash);
  39533. + pSet->prev = 0;
  39534. + z = sqliteBtreeIntegrityCheck(db->aDb[pOp->p2].pBt, aRoot, nRoot);
  39535. + if( z==0 || z[0]==0 ){
  39536. + if( z ) sqliteFree(z);
  39537. + pTos->z = "ok";
  39538. + pTos->n = 3;
  39539. + pTos->flags = MEM_Str | MEM_Static;
  39540. + }else{
  39541. + pTos->z = z;
  39542. + pTos->n = strlen(z) + 1;
  39543. + pTos->flags = MEM_Str | MEM_Dyn;
  39544. + }
  39545. + sqliteFree(aRoot);
  39546. + break;
  39547. +}
  39548. +
  39549. +/* Opcode: ListWrite * * *
  39550. +**
  39551. +** Write the integer on the top of the stack
  39552. +** into the temporary storage list.
  39553. +*/
  39554. +case OP_ListWrite: {
  39555. + Keylist *pKeylist;
  39556. + assert( pTos>=p->aStack );
  39557. + pKeylist = p->pList;
  39558. + if( pKeylist==0 || pKeylist->nUsed>=pKeylist->nKey ){
  39559. + pKeylist = sqliteMallocRaw( sizeof(Keylist)+999*sizeof(pKeylist->aKey[0]) );
  39560. + if( pKeylist==0 ) goto no_mem;
  39561. + pKeylist->nKey = 1000;
  39562. + pKeylist->nRead = 0;
  39563. + pKeylist->nUsed = 0;
  39564. + pKeylist->pNext = p->pList;
  39565. + p->pList = pKeylist;
  39566. + }
  39567. + Integerify(pTos);
  39568. + pKeylist->aKey[pKeylist->nUsed++] = pTos->i;
  39569. + Release(pTos);
  39570. + pTos--;
  39571. + break;
  39572. +}
  39573. +
  39574. +/* Opcode: ListRewind * * *
  39575. +**
  39576. +** Rewind the temporary buffer back to the beginning.
  39577. +*/
  39578. +case OP_ListRewind: {
  39579. + /* What this opcode codes, really, is reverse the order of the
  39580. + ** linked list of Keylist structures so that they are read out
  39581. + ** in the same order that they were read in. */
  39582. + Keylist *pRev, *pTop;
  39583. + pRev = 0;
  39584. + while( p->pList ){
  39585. + pTop = p->pList;
  39586. + p->pList = pTop->pNext;
  39587. + pTop->pNext = pRev;
  39588. + pRev = pTop;
  39589. + }
  39590. + p->pList = pRev;
  39591. + break;
  39592. +}
  39593. +
  39594. +/* Opcode: ListRead * P2 *
  39595. +**
  39596. +** Attempt to read an integer from the temporary storage buffer
  39597. +** and push it onto the stack. If the storage buffer is empty,
  39598. +** push nothing but instead jump to P2.
  39599. +*/
  39600. +case OP_ListRead: {
  39601. + Keylist *pKeylist;
  39602. + CHECK_FOR_INTERRUPT;
  39603. + pKeylist = p->pList;
  39604. + if( pKeylist!=0 ){
  39605. + assert( pKeylist->nRead>=0 );
  39606. + assert( pKeylist->nRead<pKeylist->nUsed );
  39607. + assert( pKeylist->nRead<pKeylist->nKey );
  39608. + pTos++;
  39609. + pTos->i = pKeylist->aKey[pKeylist->nRead++];
  39610. + pTos->flags = MEM_Int;
  39611. + if( pKeylist->nRead>=pKeylist->nUsed ){
  39612. + p->pList = pKeylist->pNext;
  39613. + sqliteFree(pKeylist);
  39614. + }
  39615. + }else{
  39616. + pc = pOp->p2 - 1;
  39617. + }
  39618. + break;
  39619. +}
  39620. +
  39621. +/* Opcode: ListReset * * *
  39622. +**
  39623. +** Reset the temporary storage buffer so that it holds nothing.
  39624. +*/
  39625. +case OP_ListReset: {
  39626. + if( p->pList ){
  39627. + sqliteVdbeKeylistFree(p->pList);
  39628. + p->pList = 0;
  39629. + }
  39630. + break;
  39631. +}
  39632. +
  39633. +/* Opcode: ListPush * * *
  39634. +**
  39635. +** Save the current Vdbe list such that it can be restored by a ListPop
  39636. +** opcode. The list is empty after this is executed.
  39637. +*/
  39638. +case OP_ListPush: {
  39639. + p->keylistStackDepth++;
  39640. + assert(p->keylistStackDepth > 0);
  39641. + p->keylistStack = sqliteRealloc(p->keylistStack,
  39642. + sizeof(Keylist *) * p->keylistStackDepth);
  39643. + if( p->keylistStack==0 ) goto no_mem;
  39644. + p->keylistStack[p->keylistStackDepth - 1] = p->pList;
  39645. + p->pList = 0;
  39646. + break;
  39647. +}
  39648. +
  39649. +/* Opcode: ListPop * * *
  39650. +**
  39651. +** Restore the Vdbe list to the state it was in when ListPush was last
  39652. +** executed.
  39653. +*/
  39654. +case OP_ListPop: {
  39655. + assert(p->keylistStackDepth > 0);
  39656. + p->keylistStackDepth--;
  39657. + sqliteVdbeKeylistFree(p->pList);
  39658. + p->pList = p->keylistStack[p->keylistStackDepth];
  39659. + p->keylistStack[p->keylistStackDepth] = 0;
  39660. + if( p->keylistStackDepth == 0 ){
  39661. + sqliteFree(p->keylistStack);
  39662. + p->keylistStack = 0;
  39663. + }
  39664. + break;
  39665. +}
  39666. +
  39667. +/* Opcode: ContextPush * * *
  39668. +**
  39669. +** Save the current Vdbe context such that it can be restored by a ContextPop
  39670. +** opcode. The context stores the last insert row id, the last statement change
  39671. +** count, and the current statement change count.
  39672. +*/
  39673. +case OP_ContextPush: {
  39674. + p->contextStackDepth++;
  39675. + assert(p->contextStackDepth > 0);
  39676. + p->contextStack = sqliteRealloc(p->contextStack,
  39677. + sizeof(Context) * p->contextStackDepth);
  39678. + if( p->contextStack==0 ) goto no_mem;
  39679. + p->contextStack[p->contextStackDepth - 1].lastRowid = p->db->lastRowid;
  39680. + p->contextStack[p->contextStackDepth - 1].lsChange = p->db->lsChange;
  39681. + p->contextStack[p->contextStackDepth - 1].csChange = p->db->csChange;
  39682. + break;
  39683. +}
  39684. +
  39685. +/* Opcode: ContextPop * * *
  39686. +**
  39687. +** Restore the Vdbe context to the state it was in when contextPush was last
  39688. +** executed. The context stores the last insert row id, the last statement
  39689. +** change count, and the current statement change count.
  39690. +*/
  39691. +case OP_ContextPop: {
  39692. + assert(p->contextStackDepth > 0);
  39693. + p->contextStackDepth--;
  39694. + p->db->lastRowid = p->contextStack[p->contextStackDepth].lastRowid;
  39695. + p->db->lsChange = p->contextStack[p->contextStackDepth].lsChange;
  39696. + p->db->csChange = p->contextStack[p->contextStackDepth].csChange;
  39697. + if( p->contextStackDepth == 0 ){
  39698. + sqliteFree(p->contextStack);
  39699. + p->contextStack = 0;
  39700. + }
  39701. + break;
  39702. +}
  39703. +
  39704. +/* Opcode: SortPut * * *
  39705. +**
  39706. +** The TOS is the key and the NOS is the data. Pop both from the stack
  39707. +** and put them on the sorter. The key and data should have been
  39708. +** made using SortMakeKey and SortMakeRec, respectively.
  39709. +*/
  39710. +case OP_SortPut: {
  39711. + Mem *pNos = &pTos[-1];
  39712. + Sorter *pSorter;
  39713. + assert( pNos>=p->aStack );
  39714. + if( Dynamicify(pTos) || Dynamicify(pNos) ) goto no_mem;
  39715. + pSorter = sqliteMallocRaw( sizeof(Sorter) );
  39716. + if( pSorter==0 ) goto no_mem;
  39717. + pSorter->pNext = p->pSort;
  39718. + p->pSort = pSorter;
  39719. + assert( pTos->flags & MEM_Dyn );
  39720. + pSorter->nKey = pTos->n;
  39721. + pSorter->zKey = pTos->z;
  39722. + assert( pNos->flags & MEM_Dyn );
  39723. + pSorter->nData = pNos->n;
  39724. + pSorter->pData = pNos->z;
  39725. + pTos -= 2;
  39726. + break;
  39727. +}
  39728. +
  39729. +/* Opcode: SortMakeRec P1 * *
  39730. +**
  39731. +** The top P1 elements are the arguments to a callback. Form these
  39732. +** elements into a single data entry that can be stored on a sorter
  39733. +** using SortPut and later fed to a callback using SortCallback.
  39734. +*/
  39735. +case OP_SortMakeRec: {
  39736. + char *z;
  39737. + char **azArg;
  39738. + int nByte;
  39739. + int nField;
  39740. + int i;
  39741. + Mem *pRec;
  39742. +
  39743. + nField = pOp->p1;
  39744. + pRec = &pTos[1-nField];
  39745. + assert( pRec>=p->aStack );
  39746. + nByte = 0;
  39747. + for(i=0; i<nField; i++, pRec++){
  39748. + if( (pRec->flags & MEM_Null)==0 ){
  39749. + Stringify(pRec);
  39750. + nByte += pRec->n;
  39751. + }
  39752. + }
  39753. + nByte += sizeof(char*)*(nField+1);
  39754. + azArg = sqliteMallocRaw( nByte );
  39755. + if( azArg==0 ) goto no_mem;
  39756. + z = (char*)&azArg[nField+1];
  39757. + for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
  39758. + if( pRec->flags & MEM_Null ){
  39759. + azArg[i] = 0;
  39760. + }else{
  39761. + azArg[i] = z;
  39762. + memcpy(z, pRec->z, pRec->n);
  39763. + z += pRec->n;
  39764. + }
  39765. + }
  39766. + popStack(&pTos, nField);
  39767. + pTos++;
  39768. + pTos->n = nByte;
  39769. + pTos->z = (char*)azArg;
  39770. + pTos->flags = MEM_Str | MEM_Dyn;
  39771. + break;
  39772. +}
  39773. +
  39774. +/* Opcode: SortMakeKey * * P3
  39775. +**
  39776. +** Convert the top few entries of the stack into a sort key. The
  39777. +** number of stack entries consumed is the number of characters in
  39778. +** the string P3. One character from P3 is prepended to each entry.
  39779. +** The first character of P3 is prepended to the element lowest in
  39780. +** the stack and the last character of P3 is prepended to the top of
  39781. +** the stack. All stack entries are separated by a \000 character
  39782. +** in the result. The whole key is terminated by two \000 characters
  39783. +** in a row.
  39784. +**
  39785. +** "N" is substituted in place of the P3 character for NULL values.
  39786. +**
  39787. +** See also the MakeKey and MakeIdxKey opcodes.
  39788. +*/
  39789. +case OP_SortMakeKey: {
  39790. + char *zNewKey;
  39791. + int nByte;
  39792. + int nField;
  39793. + int i, j, k;
  39794. + Mem *pRec;
  39795. +
  39796. + nField = strlen(pOp->p3);
  39797. + pRec = &pTos[1-nField];
  39798. + nByte = 1;
  39799. + for(i=0; i<nField; i++, pRec++){
  39800. + if( pRec->flags & MEM_Null ){
  39801. + nByte += 2;
  39802. + }else{
  39803. + Stringify(pRec);
  39804. + nByte += pRec->n+2;
  39805. + }
  39806. + }
  39807. + zNewKey = sqliteMallocRaw( nByte );
  39808. + if( zNewKey==0 ) goto no_mem;
  39809. + j = 0;
  39810. + k = 0;
  39811. + for(pRec=&pTos[1-nField], i=0; i<nField; i++, pRec++){
  39812. + if( pRec->flags & MEM_Null ){
  39813. + zNewKey[j++] = 'N';
  39814. + zNewKey[j++] = 0;
  39815. + k++;
  39816. + }else{
  39817. + zNewKey[j++] = pOp->p3[k++];
  39818. + memcpy(&zNewKey[j], pRec->z, pRec->n-1);
  39819. + j += pRec->n-1;
  39820. + zNewKey[j++] = 0;
  39821. + }
  39822. + }
  39823. + zNewKey[j] = 0;
  39824. + assert( j<nByte );
  39825. + popStack(&pTos, nField);
  39826. + pTos++;
  39827. + pTos->n = nByte;
  39828. + pTos->flags = MEM_Str|MEM_Dyn;
  39829. + pTos->z = zNewKey;
  39830. + break;
  39831. +}
  39832. +
  39833. +/* Opcode: Sort * * *
  39834. +**
  39835. +** Sort all elements on the sorter. The algorithm is a
  39836. +** mergesort.
  39837. +*/
  39838. +case OP_Sort: {
  39839. + int i;
  39840. + Sorter *pElem;
  39841. + Sorter *apSorter[NSORT];
  39842. + for(i=0; i<NSORT; i++){
  39843. + apSorter[i] = 0;
  39844. + }
  39845. + while( p->pSort ){
  39846. + pElem = p->pSort;
  39847. + p->pSort = pElem->pNext;
  39848. + pElem->pNext = 0;
  39849. + for(i=0; i<NSORT-1; i++){
  39850. + if( apSorter[i]==0 ){
  39851. + apSorter[i] = pElem;
  39852. + break;
  39853. + }else{
  39854. + pElem = Merge(apSorter[i], pElem);
  39855. + apSorter[i] = 0;
  39856. + }
  39857. + }
  39858. + if( i>=NSORT-1 ){
  39859. + apSorter[NSORT-1] = Merge(apSorter[NSORT-1],pElem);
  39860. + }
  39861. + }
  39862. + pElem = 0;
  39863. + for(i=0; i<NSORT; i++){
  39864. + pElem = Merge(apSorter[i], pElem);
  39865. + }
  39866. + p->pSort = pElem;
  39867. + break;
  39868. +}
  39869. +
  39870. +/* Opcode: SortNext * P2 *
  39871. +**
  39872. +** Push the data for the topmost element in the sorter onto the
  39873. +** stack, then remove the element from the sorter. If the sorter
  39874. +** is empty, push nothing on the stack and instead jump immediately
  39875. +** to instruction P2.
  39876. +*/
  39877. +case OP_SortNext: {
  39878. + Sorter *pSorter = p->pSort;
  39879. + CHECK_FOR_INTERRUPT;
  39880. + if( pSorter!=0 ){
  39881. + p->pSort = pSorter->pNext;
  39882. + pTos++;
  39883. + pTos->z = pSorter->pData;
  39884. + pTos->n = pSorter->nData;
  39885. + pTos->flags = MEM_Str|MEM_Dyn;
  39886. + sqliteFree(pSorter->zKey);
  39887. + sqliteFree(pSorter);
  39888. + }else{
  39889. + pc = pOp->p2 - 1;
  39890. + }
  39891. + break;
  39892. +}
  39893. +
  39894. +/* Opcode: SortCallback P1 * *
  39895. +**
  39896. +** The top of the stack contains a callback record built using
  39897. +** the SortMakeRec operation with the same P1 value as this
  39898. +** instruction. Pop this record from the stack and invoke the
  39899. +** callback on it.
  39900. +*/
  39901. +case OP_SortCallback: {
  39902. + assert( pTos>=p->aStack );
  39903. + assert( pTos->flags & MEM_Str );
  39904. + p->nCallback++;
  39905. + p->pc = pc+1;
  39906. + p->azResColumn = (char**)pTos->z;
  39907. + assert( p->nResColumn==pOp->p1 );
  39908. + p->popStack = 1;
  39909. + p->pTos = pTos;
  39910. + return SQLITE_ROW;
  39911. +}
  39912. +
  39913. +/* Opcode: SortReset * * *
  39914. +**
  39915. +** Remove any elements that remain on the sorter.
  39916. +*/
  39917. +case OP_SortReset: {
  39918. + sqliteVdbeSorterReset(p);
  39919. + break;
  39920. +}
  39921. +
  39922. +/* Opcode: FileOpen * * P3
  39923. +**
  39924. +** Open the file named by P3 for reading using the FileRead opcode.
  39925. +** If P3 is "stdin" then open standard input for reading.
  39926. +*/
  39927. +case OP_FileOpen: {
  39928. + assert( pOp->p3!=0 );
  39929. + if( p->pFile ){
  39930. + if( p->pFile!=stdin ) fclose(p->pFile);
  39931. + p->pFile = 0;
  39932. + }
  39933. + if( sqliteStrICmp(pOp->p3,"stdin")==0 ){
  39934. + p->pFile = stdin;
  39935. + }else{
  39936. + p->pFile = fopen(pOp->p3, "r");
  39937. + }
  39938. + if( p->pFile==0 ){
  39939. + sqliteSetString(&p->zErrMsg,"unable to open file: ", pOp->p3, (char*)0);
  39940. + rc = SQLITE_ERROR;
  39941. + }
  39942. + break;
  39943. +}
  39944. +
  39945. +/* Opcode: FileRead P1 P2 P3
  39946. +**
  39947. +** Read a single line of input from the open file (the file opened using
  39948. +** FileOpen). If we reach end-of-file, jump immediately to P2. If
  39949. +** we are able to get another line, split the line apart using P3 as
  39950. +** a delimiter. There should be P1 fields. If the input line contains
  39951. +** more than P1 fields, ignore the excess. If the input line contains
  39952. +** fewer than P1 fields, assume the remaining fields contain NULLs.
  39953. +**
  39954. +** Input ends if a line consists of just "\.". A field containing only
  39955. +** "\N" is a null field. The backslash \ character can be used be used
  39956. +** to escape newlines or the delimiter.
  39957. +*/
  39958. +case OP_FileRead: {
  39959. + int n, eol, nField, i, c, nDelim;
  39960. + char *zDelim, *z;
  39961. + CHECK_FOR_INTERRUPT;
  39962. + if( p->pFile==0 ) goto fileread_jump;
  39963. + nField = pOp->p1;
  39964. + if( nField<=0 ) goto fileread_jump;
  39965. + if( nField!=p->nField || p->azField==0 ){
  39966. + char **azField = sqliteRealloc(p->azField, sizeof(char*)*nField+1);
  39967. + if( azField==0 ){ goto no_mem; }
  39968. + p->azField = azField;
  39969. + p->nField = nField;
  39970. + }
  39971. + n = 0;
  39972. + eol = 0;
  39973. + while( eol==0 ){
  39974. + if( p->zLine==0 || n+200>p->nLineAlloc ){
  39975. + char *zLine;
  39976. + p->nLineAlloc = p->nLineAlloc*2 + 300;
  39977. + zLine = sqliteRealloc(p->zLine, p->nLineAlloc);
  39978. + if( zLine==0 ){
  39979. + p->nLineAlloc = 0;
  39980. + sqliteFree(p->zLine);
  39981. + p->zLine = 0;
  39982. + goto no_mem;
  39983. + }
  39984. + p->zLine = zLine;
  39985. + }
  39986. + if( vdbe_fgets(&p->zLine[n], p->nLineAlloc-n, p->pFile)==0 ){
  39987. + eol = 1;
  39988. + p->zLine[n] = 0;
  39989. + }else{
  39990. + int c;
  39991. + while( (c = p->zLine[n])!=0 ){
  39992. + if( c=='\\' ){
  39993. + if( p->zLine[n+1]==0 ) break;
  39994. + n += 2;
  39995. + }else if( c=='\n' ){
  39996. + p->zLine[n] = 0;
  39997. + eol = 1;
  39998. + break;
  39999. + }else{
  40000. + n++;
  40001. + }
  40002. + }
  40003. + }
  40004. + }
  40005. + if( n==0 ) goto fileread_jump;
  40006. + z = p->zLine;
  40007. + if( z[0]=='\\' && z[1]=='.' && z[2]==0 ){
  40008. + goto fileread_jump;
  40009. + }
  40010. + zDelim = pOp->p3;
  40011. + if( zDelim==0 ) zDelim = "\t";
  40012. + c = zDelim[0];
  40013. + nDelim = strlen(zDelim);
  40014. + p->azField[0] = z;
  40015. + for(i=1; *z!=0 && i<=nField; i++){
  40016. + int from, to;
  40017. + from = to = 0;
  40018. + if( z[0]=='\\' && z[1]=='N'
  40019. + && (z[2]==0 || strncmp(&z[2],zDelim,nDelim)==0) ){
  40020. + if( i<=nField ) p->azField[i-1] = 0;
  40021. + z += 2 + nDelim;
  40022. + if( i<nField ) p->azField[i] = z;
  40023. + continue;
  40024. + }
  40025. + while( z[from] ){
  40026. + if( z[from]=='\\' && z[from+1]!=0 ){
  40027. + int tx = z[from+1];
  40028. + switch( tx ){
  40029. + case 'b': tx = '\b'; break;
  40030. + case 'f': tx = '\f'; break;
  40031. + case 'n': tx = '\n'; break;
  40032. + case 'r': tx = '\r'; break;
  40033. + case 't': tx = '\t'; break;
  40034. + case 'v': tx = '\v'; break;
  40035. + default: break;
  40036. + }
  40037. + z[to++] = tx;
  40038. + from += 2;
  40039. + continue;
  40040. + }
  40041. + if( z[from]==c && strncmp(&z[from],zDelim,nDelim)==0 ) break;
  40042. + z[to++] = z[from++];
  40043. + }
  40044. + if( z[from] ){
  40045. + z[to] = 0;
  40046. + z += from + nDelim;
  40047. + if( i<nField ) p->azField[i] = z;
  40048. + }else{
  40049. + z[to] = 0;
  40050. + z = "";
  40051. + }
  40052. + }
  40053. + while( i<nField ){
  40054. + p->azField[i++] = 0;
  40055. + }
  40056. + break;
  40057. +
  40058. + /* If we reach end-of-file, or if anything goes wrong, jump here.
  40059. + ** This code will cause a jump to P2 */
  40060. +fileread_jump:
  40061. + pc = pOp->p2 - 1;
  40062. + break;
  40063. +}
  40064. +
  40065. +/* Opcode: FileColumn P1 * *
  40066. +**
  40067. +** Push onto the stack the P1-th column of the most recently read line
  40068. +** from the input file.
  40069. +*/
  40070. +case OP_FileColumn: {
  40071. + int i = pOp->p1;
  40072. + char *z;
  40073. + assert( i>=0 && i<p->nField );
  40074. + if( p->azField ){
  40075. + z = p->azField[i];
  40076. + }else{
  40077. + z = 0;
  40078. + }
  40079. + pTos++;
  40080. + if( z ){
  40081. + pTos->n = strlen(z) + 1;
  40082. + pTos->z = z;
  40083. + pTos->flags = MEM_Str | MEM_Ephem;
  40084. + }else{
  40085. + pTos->flags = MEM_Null;
  40086. + }
  40087. + break;
  40088. +}
  40089. +
  40090. +/* Opcode: MemStore P1 P2 *
  40091. +**
  40092. +** Write the top of the stack into memory location P1.
  40093. +** P1 should be a small integer since space is allocated
  40094. +** for all memory locations between 0 and P1 inclusive.
  40095. +**
  40096. +** After the data is stored in the memory location, the
  40097. +** stack is popped once if P2 is 1. If P2 is zero, then
  40098. +** the original data remains on the stack.
  40099. +*/
  40100. +case OP_MemStore: {
  40101. + int i = pOp->p1;
  40102. + Mem *pMem;
  40103. + assert( pTos>=p->aStack );
  40104. + if( i>=p->nMem ){
  40105. + int nOld = p->nMem;
  40106. + Mem *aMem;
  40107. + p->nMem = i + 5;
  40108. + aMem = sqliteRealloc(p->aMem, p->nMem*sizeof(p->aMem[0]));
  40109. + if( aMem==0 ) goto no_mem;
  40110. + if( aMem!=p->aMem ){
  40111. + int j;
  40112. + for(j=0; j<nOld; j++){
  40113. + if( aMem[j].flags & MEM_Short ){
  40114. + aMem[j].z = aMem[j].zShort;
  40115. + }
  40116. + }
  40117. + }
  40118. + p->aMem = aMem;
  40119. + if( nOld<p->nMem ){
  40120. + memset(&p->aMem[nOld], 0, sizeof(p->aMem[0])*(p->nMem-nOld));
  40121. + }
  40122. + }
  40123. + Deephemeralize(pTos);
  40124. + pMem = &p->aMem[i];
  40125. + Release(pMem);
  40126. + *pMem = *pTos;
  40127. + if( pMem->flags & MEM_Dyn ){
  40128. + if( pOp->p2 ){
  40129. + pTos->flags = MEM_Null;
  40130. + }else{
  40131. + pMem->z = sqliteMallocRaw( pMem->n );
  40132. + if( pMem->z==0 ) goto no_mem;
  40133. + memcpy(pMem->z, pTos->z, pMem->n);
  40134. + }
  40135. + }else if( pMem->flags & MEM_Short ){
  40136. + pMem->z = pMem->zShort;
  40137. + }
  40138. + if( pOp->p2 ){
  40139. + Release(pTos);
  40140. + pTos--;
  40141. + }
  40142. + break;
  40143. +}
  40144. +
  40145. +/* Opcode: MemLoad P1 * *
  40146. +**
  40147. +** Push a copy of the value in memory location P1 onto the stack.
  40148. +**
  40149. +** If the value is a string, then the value pushed is a pointer to
  40150. +** the string that is stored in the memory location. If the memory
  40151. +** location is subsequently changed (using OP_MemStore) then the
  40152. +** value pushed onto the stack will change too.
  40153. +*/
  40154. +case OP_MemLoad: {
  40155. + int i = pOp->p1;
  40156. + assert( i>=0 && i<p->nMem );
  40157. + pTos++;
  40158. + memcpy(pTos, &p->aMem[i], sizeof(pTos[0])-NBFS);;
  40159. + if( pTos->flags & MEM_Str ){
  40160. + pTos->flags |= MEM_Ephem;
  40161. + pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
  40162. + }
  40163. + break;
  40164. +}
  40165. +
  40166. +/* Opcode: MemIncr P1 P2 *
  40167. +**
  40168. +** Increment the integer valued memory cell P1 by 1. If P2 is not zero
  40169. +** and the result after the increment is greater than zero, then jump
  40170. +** to P2.
  40171. +**
  40172. +** This instruction throws an error if the memory cell is not initially
  40173. +** an integer.
  40174. +*/
  40175. +case OP_MemIncr: {
  40176. + int i = pOp->p1;
  40177. + Mem *pMem;
  40178. + assert( i>=0 && i<p->nMem );
  40179. + pMem = &p->aMem[i];
  40180. + assert( pMem->flags==MEM_Int );
  40181. + pMem->i++;
  40182. + if( pOp->p2>0 && pMem->i>0 ){
  40183. + pc = pOp->p2 - 1;
  40184. + }
  40185. + break;
  40186. +}
  40187. +
  40188. +/* Opcode: AggReset * P2 *
  40189. +**
  40190. +** Reset the aggregator so that it no longer contains any data.
  40191. +** Future aggregator elements will contain P2 values each.
  40192. +*/
  40193. +case OP_AggReset: {
  40194. + sqliteVdbeAggReset(&p->agg);
  40195. + p->agg.nMem = pOp->p2;
  40196. + p->agg.apFunc = sqliteMalloc( p->agg.nMem*sizeof(p->agg.apFunc[0]) );
  40197. + if( p->agg.apFunc==0 ) goto no_mem;
  40198. + break;
  40199. +}
  40200. +
  40201. +/* Opcode: AggInit * P2 P3
  40202. +**
  40203. +** Initialize the function parameters for an aggregate function.
  40204. +** The aggregate will operate out of aggregate column P2.
  40205. +** P3 is a pointer to the FuncDef structure for the function.
  40206. +*/
  40207. +case OP_AggInit: {
  40208. + int i = pOp->p2;
  40209. + assert( i>=0 && i<p->agg.nMem );
  40210. + p->agg.apFunc[i] = (FuncDef*)pOp->p3;
  40211. + break;
  40212. +}
  40213. +
  40214. +/* Opcode: AggFunc * P2 P3
  40215. +**
  40216. +** Execute the step function for an aggregate. The
  40217. +** function has P2 arguments. P3 is a pointer to the FuncDef
  40218. +** structure that specifies the function.
  40219. +**
  40220. +** The top of the stack must be an integer which is the index of
  40221. +** the aggregate column that corresponds to this aggregate function.
  40222. +** Ideally, this index would be another parameter, but there are
  40223. +** no free parameters left. The integer is popped from the stack.
  40224. +*/
  40225. +case OP_AggFunc: {
  40226. + int n = pOp->p2;
  40227. + int i;
  40228. + Mem *pMem, *pRec;
  40229. + char **azArgv = p->zArgv;
  40230. + sqlite_func ctx;
  40231. +
  40232. + assert( n>=0 );
  40233. + assert( pTos->flags==MEM_Int );
  40234. + pRec = &pTos[-n];
  40235. + assert( pRec>=p->aStack );
  40236. + for(i=0; i<n; i++, pRec++){
  40237. + if( pRec->flags & MEM_Null ){
  40238. + azArgv[i] = 0;
  40239. + }else{
  40240. + Stringify(pRec);
  40241. + azArgv[i] = pRec->z;
  40242. + }
  40243. + }
  40244. + i = pTos->i;
  40245. + assert( i>=0 && i<p->agg.nMem );
  40246. + ctx.pFunc = (FuncDef*)pOp->p3;
  40247. + pMem = &p->agg.pCurrent->aMem[i];
  40248. + ctx.s.z = pMem->zShort; /* Space used for small aggregate contexts */
  40249. + ctx.pAgg = pMem->z;
  40250. + ctx.cnt = ++pMem->i;
  40251. + ctx.isError = 0;
  40252. + ctx.isStep = 1;
  40253. + (ctx.pFunc->xStep)(&ctx, n, (const char**)azArgv);
  40254. + pMem->z = ctx.pAgg;
  40255. + pMem->flags = MEM_AggCtx;
  40256. + popStack(&pTos, n+1);
  40257. + if( ctx.isError ){
  40258. + rc = SQLITE_ERROR;
  40259. + }
  40260. + break;
  40261. +}
  40262. +
  40263. +/* Opcode: AggFocus * P2 *
  40264. +**
  40265. +** Pop the top of the stack and use that as an aggregator key. If
  40266. +** an aggregator with that same key already exists, then make the
  40267. +** aggregator the current aggregator and jump to P2. If no aggregator
  40268. +** with the given key exists, create one and make it current but
  40269. +** do not jump.
  40270. +**
  40271. +** The order of aggregator opcodes is important. The order is:
  40272. +** AggReset AggFocus AggNext. In other words, you must execute
  40273. +** AggReset first, then zero or more AggFocus operations, then
  40274. +** zero or more AggNext operations. You must not execute an AggFocus
  40275. +** in between an AggNext and an AggReset.
  40276. +*/
  40277. +case OP_AggFocus: {
  40278. + AggElem *pElem;
  40279. + char *zKey;
  40280. + int nKey;
  40281. +
  40282. + assert( pTos>=p->aStack );
  40283. + Stringify(pTos);
  40284. + zKey = pTos->z;
  40285. + nKey = pTos->n;
  40286. + pElem = sqliteHashFind(&p->agg.hash, zKey, nKey);
  40287. + if( pElem ){
  40288. + p->agg.pCurrent = pElem;
  40289. + pc = pOp->p2 - 1;
  40290. + }else{
  40291. + AggInsert(&p->agg, zKey, nKey);
  40292. + if( sqlite_malloc_failed ) goto no_mem;
  40293. + }
  40294. + Release(pTos);
  40295. + pTos--;
  40296. + break;
  40297. +}
  40298. +
  40299. +/* Opcode: AggSet * P2 *
  40300. +**
  40301. +** Move the top of the stack into the P2-th field of the current
  40302. +** aggregate. String values are duplicated into new memory.
  40303. +*/
  40304. +case OP_AggSet: {
  40305. + AggElem *pFocus = AggInFocus(p->agg);
  40306. + Mem *pMem;
  40307. + int i = pOp->p2;
  40308. + assert( pTos>=p->aStack );
  40309. + if( pFocus==0 ) goto no_mem;
  40310. + assert( i>=0 && i<p->agg.nMem );
  40311. + Deephemeralize(pTos);
  40312. + pMem = &pFocus->aMem[i];
  40313. + Release(pMem);
  40314. + *pMem = *pTos;
  40315. + if( pMem->flags & MEM_Dyn ){
  40316. + pTos->flags = MEM_Null;
  40317. + }else if( pMem->flags & MEM_Short ){
  40318. + pMem->z = pMem->zShort;
  40319. + }
  40320. + Release(pTos);
  40321. + pTos--;
  40322. + break;
  40323. +}
  40324. +
  40325. +/* Opcode: AggGet * P2 *
  40326. +**
  40327. +** Push a new entry onto the stack which is a copy of the P2-th field
  40328. +** of the current aggregate. Strings are not duplicated so
  40329. +** string values will be ephemeral.
  40330. +*/
  40331. +case OP_AggGet: {
  40332. + AggElem *pFocus = AggInFocus(p->agg);
  40333. + Mem *pMem;
  40334. + int i = pOp->p2;
  40335. + if( pFocus==0 ) goto no_mem;
  40336. + assert( i>=0 && i<p->agg.nMem );
  40337. + pTos++;
  40338. + pMem = &pFocus->aMem[i];
  40339. + *pTos = *pMem;
  40340. + if( pTos->flags & MEM_Str ){
  40341. + pTos->flags &= ~(MEM_Dyn|MEM_Static|MEM_Short);
  40342. + pTos->flags |= MEM_Ephem;
  40343. + }
  40344. + if( pTos->flags & MEM_AggCtx ){
  40345. + Release(pTos);
  40346. + pTos->flags = MEM_Null;
  40347. + }
  40348. + break;
  40349. +}
  40350. +
  40351. +/* Opcode: AggNext * P2 *
  40352. +**
  40353. +** Make the next aggregate value the current aggregate. The prior
  40354. +** aggregate is deleted. If all aggregate values have been consumed,
  40355. +** jump to P2.
  40356. +**
  40357. +** The order of aggregator opcodes is important. The order is:
  40358. +** AggReset AggFocus AggNext. In other words, you must execute
  40359. +** AggReset first, then zero or more AggFocus operations, then
  40360. +** zero or more AggNext operations. You must not execute an AggFocus
  40361. +** in between an AggNext and an AggReset.
  40362. +*/
  40363. +case OP_AggNext: {
  40364. + CHECK_FOR_INTERRUPT;
  40365. + if( p->agg.pSearch==0 ){
  40366. + p->agg.pSearch = sqliteHashFirst(&p->agg.hash);
  40367. + }else{
  40368. + p->agg.pSearch = sqliteHashNext(p->agg.pSearch);
  40369. + }
  40370. + if( p->agg.pSearch==0 ){
  40371. + pc = pOp->p2 - 1;
  40372. + } else {
  40373. + int i;
  40374. + sqlite_func ctx;
  40375. + Mem *aMem;
  40376. + p->agg.pCurrent = sqliteHashData(p->agg.pSearch);
  40377. + aMem = p->agg.pCurrent->aMem;
  40378. + for(i=0; i<p->agg.nMem; i++){
  40379. + int freeCtx;
  40380. + if( p->agg.apFunc[i]==0 ) continue;
  40381. + if( p->agg.apFunc[i]->xFinalize==0 ) continue;
  40382. + ctx.s.flags = MEM_Null;
  40383. + ctx.s.z = aMem[i].zShort;
  40384. + ctx.pAgg = (void*)aMem[i].z;
  40385. + freeCtx = aMem[i].z && aMem[i].z!=aMem[i].zShort;
  40386. + ctx.cnt = aMem[i].i;
  40387. + ctx.isStep = 0;
  40388. + ctx.pFunc = p->agg.apFunc[i];
  40389. + (*p->agg.apFunc[i]->xFinalize)(&ctx);
  40390. + if( freeCtx ){
  40391. + sqliteFree( aMem[i].z );
  40392. + }
  40393. + aMem[i] = ctx.s;
  40394. + if( aMem[i].flags & MEM_Short ){
  40395. + aMem[i].z = aMem[i].zShort;
  40396. + }
  40397. + }
  40398. + }
  40399. + break;
  40400. +}
  40401. +
  40402. +/* Opcode: SetInsert P1 * P3
  40403. +**
  40404. +** If Set P1 does not exist then create it. Then insert value
  40405. +** P3 into that set. If P3 is NULL, then insert the top of the
  40406. +** stack into the set.
  40407. +*/
  40408. +case OP_SetInsert: {
  40409. + int i = pOp->p1;
  40410. + if( p->nSet<=i ){
  40411. + int k;
  40412. + Set *aSet = sqliteRealloc(p->aSet, (i+1)*sizeof(p->aSet[0]) );
  40413. + if( aSet==0 ) goto no_mem;
  40414. + p->aSet = aSet;
  40415. + for(k=p->nSet; k<=i; k++){
  40416. + sqliteHashInit(&p->aSet[k].hash, SQLITE_HASH_BINARY, 1);
  40417. + }
  40418. + p->nSet = i+1;
  40419. + }
  40420. + if( pOp->p3 ){
  40421. + sqliteHashInsert(&p->aSet[i].hash, pOp->p3, strlen(pOp->p3)+1, p);
  40422. + }else{
  40423. + assert( pTos>=p->aStack );
  40424. + Stringify(pTos);
  40425. + sqliteHashInsert(&p->aSet[i].hash, pTos->z, pTos->n, p);
  40426. + Release(pTos);
  40427. + pTos--;
  40428. + }
  40429. + if( sqlite_malloc_failed ) goto no_mem;
  40430. + break;
  40431. +}
  40432. +
  40433. +/* Opcode: SetFound P1 P2 *
  40434. +**
  40435. +** Pop the stack once and compare the value popped off with the
  40436. +** contents of set P1. If the element popped exists in set P1,
  40437. +** then jump to P2. Otherwise fall through.
  40438. +*/
  40439. +case OP_SetFound: {
  40440. + int i = pOp->p1;
  40441. + assert( pTos>=p->aStack );
  40442. + Stringify(pTos);
  40443. + if( i>=0 && i<p->nSet && sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)){
  40444. + pc = pOp->p2 - 1;
  40445. + }
  40446. + Release(pTos);
  40447. + pTos--;
  40448. + break;
  40449. +}
  40450. +
  40451. +/* Opcode: SetNotFound P1 P2 *
  40452. +**
  40453. +** Pop the stack once and compare the value popped off with the
  40454. +** contents of set P1. If the element popped does not exists in
  40455. +** set P1, then jump to P2. Otherwise fall through.
  40456. +*/
  40457. +case OP_SetNotFound: {
  40458. + int i = pOp->p1;
  40459. + assert( pTos>=p->aStack );
  40460. + Stringify(pTos);
  40461. + if( i<0 || i>=p->nSet ||
  40462. + sqliteHashFind(&p->aSet[i].hash, pTos->z, pTos->n)==0 ){
  40463. + pc = pOp->p2 - 1;
  40464. + }
  40465. + Release(pTos);
  40466. + pTos--;
  40467. + break;
  40468. +}
  40469. +
  40470. +/* Opcode: SetFirst P1 P2 *
  40471. +**
  40472. +** Read the first element from set P1 and push it onto the stack. If the
  40473. +** set is empty, push nothing and jump immediately to P2. This opcode is
  40474. +** used in combination with OP_SetNext to loop over all elements of a set.
  40475. +*/
  40476. +/* Opcode: SetNext P1 P2 *
  40477. +**
  40478. +** Read the next element from set P1 and push it onto the stack. If there
  40479. +** are no more elements in the set, do not do the push and fall through.
  40480. +** Otherwise, jump to P2 after pushing the next set element.
  40481. +*/
  40482. +case OP_SetFirst:
  40483. +case OP_SetNext: {
  40484. + Set *pSet;
  40485. + CHECK_FOR_INTERRUPT;
  40486. + if( pOp->p1<0 || pOp->p1>=p->nSet ){
  40487. + if( pOp->opcode==OP_SetFirst ) pc = pOp->p2 - 1;
  40488. + break;
  40489. + }
  40490. + pSet = &p->aSet[pOp->p1];
  40491. + if( pOp->opcode==OP_SetFirst ){
  40492. + pSet->prev = sqliteHashFirst(&pSet->hash);
  40493. + if( pSet->prev==0 ){
  40494. + pc = pOp->p2 - 1;
  40495. + break;
  40496. + }
  40497. + }else{
  40498. + if( pSet->prev ){
  40499. + pSet->prev = sqliteHashNext(pSet->prev);
  40500. + }
  40501. + if( pSet->prev==0 ){
  40502. + break;
  40503. + }else{
  40504. + pc = pOp->p2 - 1;
  40505. + }
  40506. + }
  40507. + pTos++;
  40508. + pTos->z = sqliteHashKey(pSet->prev);
  40509. + pTos->n = sqliteHashKeysize(pSet->prev);
  40510. + pTos->flags = MEM_Str | MEM_Ephem;
  40511. + break;
  40512. +}
  40513. +
  40514. +/* Opcode: Vacuum * * *
  40515. +**
  40516. +** Vacuum the entire database. This opcode will cause other virtual
  40517. +** machines to be created and run. It may not be called from within
  40518. +** a transaction.
  40519. +*/
  40520. +case OP_Vacuum: {
  40521. + if( sqliteSafetyOff(db) ) goto abort_due_to_misuse;
  40522. + rc = sqliteRunVacuum(&p->zErrMsg, db);
  40523. + if( sqliteSafetyOn(db) ) goto abort_due_to_misuse;
  40524. + break;
  40525. +}
  40526. +
  40527. +/* Opcode: StackDepth * * *
  40528. +**
  40529. +** Push an integer onto the stack which is the depth of the stack prior
  40530. +** to that integer being pushed.
  40531. +*/
  40532. +case OP_StackDepth: {
  40533. + int depth = (&pTos[1]) - p->aStack;
  40534. + pTos++;
  40535. + pTos->i = depth;
  40536. + pTos->flags = MEM_Int;
  40537. + break;
  40538. +}
  40539. +
  40540. +/* Opcode: StackReset * * *
  40541. +**
  40542. +** Pop a single integer off of the stack. Then pop the stack
  40543. +** as many times as necessary to get the depth of the stack down
  40544. +** to the value of the integer that was popped.
  40545. +*/
  40546. +case OP_StackReset: {
  40547. + int depth, goal;
  40548. + assert( pTos>=p->aStack );
  40549. + Integerify(pTos);
  40550. + goal = pTos->i;
  40551. + depth = (&pTos[1]) - p->aStack;
  40552. + assert( goal<depth );
  40553. + popStack(&pTos, depth-goal);
  40554. + break;
  40555. +}
  40556. +
  40557. +/* An other opcode is illegal...
  40558. +*/
  40559. +default: {
  40560. + sqlite_snprintf(sizeof(zBuf),zBuf,"%d",pOp->opcode);
  40561. + sqliteSetString(&p->zErrMsg, "unknown opcode ", zBuf, (char*)0);
  40562. + rc = SQLITE_INTERNAL;
  40563. + break;
  40564. +}
  40565. +
  40566. +/*****************************************************************************
  40567. +** The cases of the switch statement above this line should all be indented
  40568. +** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  40569. +** readability. From this point on down, the normal indentation rules are
  40570. +** restored.
  40571. +*****************************************************************************/
  40572. + }
  40573. +
  40574. +#ifdef VDBE_PROFILE
  40575. + {
  40576. + long long elapse = hwtime() - start;
  40577. + pOp->cycles += elapse;
  40578. + pOp->cnt++;
  40579. +#if 0
  40580. + fprintf(stdout, "%10lld ", elapse);
  40581. + sqliteVdbePrintOp(stdout, origPc, &p->aOp[origPc]);
  40582. +#endif
  40583. + }
  40584. +#endif
  40585. +
  40586. + /* The following code adds nothing to the actual functionality
  40587. + ** of the program. It is only here for testing and debugging.
  40588. + ** On the other hand, it does burn CPU cycles every time through
  40589. + ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  40590. + */
  40591. +#ifndef NDEBUG
  40592. + /* Sanity checking on the top element of the stack */
  40593. + if( pTos>=p->aStack ){
  40594. + assert( pTos->flags!=0 ); /* Must define some type */
  40595. + if( pTos->flags & MEM_Str ){
  40596. + int x = pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short);
  40597. + assert( x!=0 ); /* Strings must define a string subtype */
  40598. + assert( (x & (x-1))==0 ); /* Only one string subtype can be defined */
  40599. + assert( pTos->z!=0 ); /* Strings must have a value */
  40600. + /* Mem.z points to Mem.zShort iff the subtype is MEM_Short */
  40601. + assert( (pTos->flags & MEM_Short)==0 || pTos->z==pTos->zShort );
  40602. + assert( (pTos->flags & MEM_Short)!=0 || pTos->z!=pTos->zShort );
  40603. + }else{
  40604. + /* Cannot define a string subtype for non-string objects */
  40605. + assert( (pTos->flags & (MEM_Static|MEM_Dyn|MEM_Ephem|MEM_Short))==0 );
  40606. + }
  40607. + /* MEM_Null excludes all other types */
  40608. + assert( pTos->flags==MEM_Null || (pTos->flags&MEM_Null)==0 );
  40609. + }
  40610. + if( pc<-1 || pc>=p->nOp ){
  40611. + sqliteSetString(&p->zErrMsg, "jump destination out of range", (char*)0);
  40612. + rc = SQLITE_INTERNAL;
  40613. + }
  40614. + if( p->trace && pTos>=p->aStack ){
  40615. + int i;
  40616. + fprintf(p->trace, "Stack:");
  40617. + for(i=0; i>-5 && &pTos[i]>=p->aStack; i--){
  40618. + if( pTos[i].flags & MEM_Null ){
  40619. + fprintf(p->trace, " NULL");
  40620. + }else if( (pTos[i].flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  40621. + fprintf(p->trace, " si:%d", pTos[i].i);
  40622. + }else if( pTos[i].flags & MEM_Int ){
  40623. + fprintf(p->trace, " i:%d", pTos[i].i);
  40624. + }else if( pTos[i].flags & MEM_Real ){
  40625. + fprintf(p->trace, " r:%g", pTos[i].r);
  40626. + }else if( pTos[i].flags & MEM_Str ){
  40627. + int j, k;
  40628. + char zBuf[100];
  40629. + zBuf[0] = ' ';
  40630. + if( pTos[i].flags & MEM_Dyn ){
  40631. + zBuf[1] = 'z';
  40632. + assert( (pTos[i].flags & (MEM_Static|MEM_Ephem))==0 );
  40633. + }else if( pTos[i].flags & MEM_Static ){
  40634. + zBuf[1] = 't';
  40635. + assert( (pTos[i].flags & (MEM_Dyn|MEM_Ephem))==0 );
  40636. + }else if( pTos[i].flags & MEM_Ephem ){
  40637. + zBuf[1] = 'e';
  40638. + assert( (pTos[i].flags & (MEM_Static|MEM_Dyn))==0 );
  40639. + }else{
  40640. + zBuf[1] = 's';
  40641. + }
  40642. + zBuf[2] = '[';
  40643. + k = 3;
  40644. + for(j=0; j<20 && j<pTos[i].n; j++){
  40645. + int c = pTos[i].z[j];
  40646. + if( c==0 && j==pTos[i].n-1 ) break;
  40647. + if( isprint(c) && !isspace(c) ){
  40648. + zBuf[k++] = c;
  40649. + }else{
  40650. + zBuf[k++] = '.';
  40651. + }
  40652. + }
  40653. + zBuf[k++] = ']';
  40654. + zBuf[k++] = 0;
  40655. + fprintf(p->trace, "%s", zBuf);
  40656. + }else{
  40657. + fprintf(p->trace, " ???");
  40658. + }
  40659. + }
  40660. + if( rc!=0 ) fprintf(p->trace," rc=%d",rc);
  40661. + fprintf(p->trace,"\n");
  40662. + }
  40663. +#endif
  40664. + } /* The end of the for(;;) loop the loops through opcodes */
  40665. +
  40666. + /* If we reach this point, it means that execution is finished.
  40667. + */
  40668. +vdbe_halt:
  40669. + CHECK_FOR_INTERRUPT
  40670. + if( rc ){
  40671. + p->rc = rc;
  40672. + rc = SQLITE_ERROR;
  40673. + }else{
  40674. + rc = SQLITE_DONE;
  40675. + }
  40676. + p->magic = VDBE_MAGIC_HALT;
  40677. + p->pTos = pTos;
  40678. + return rc;
  40679. +
  40680. + /* Jump to here if a malloc() fails. It's hard to get a malloc()
  40681. + ** to fail on a modern VM computer, so this code is untested.
  40682. + */
  40683. +no_mem:
  40684. + sqliteSetString(&p->zErrMsg, "out of memory", (char*)0);
  40685. + rc = SQLITE_NOMEM;
  40686. + goto vdbe_halt;
  40687. +
  40688. + /* Jump to here for an SQLITE_MISUSE error.
  40689. + */
  40690. +abort_due_to_misuse:
  40691. + rc = SQLITE_MISUSE;
  40692. + /* Fall thru into abort_due_to_error */
  40693. +
  40694. + /* Jump to here for any other kind of fatal error. The "rc" variable
  40695. + ** should hold the error number.
  40696. + */
  40697. +abort_due_to_error:
  40698. + if( p->zErrMsg==0 ){
  40699. + if( sqlite_malloc_failed ) rc = SQLITE_NOMEM;
  40700. + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
  40701. + }
  40702. + goto vdbe_halt;
  40703. +
  40704. + /* Jump to here if the sqlite_interrupt() API sets the interrupt
  40705. + ** flag.
  40706. + */
  40707. +abort_due_to_interrupt:
  40708. + assert( db->flags & SQLITE_Interrupt );
  40709. + db->flags &= ~SQLITE_Interrupt;
  40710. + if( db->magic!=SQLITE_MAGIC_BUSY ){
  40711. + rc = SQLITE_MISUSE;
  40712. + }else{
  40713. + rc = SQLITE_INTERRUPT;
  40714. + }
  40715. + sqliteSetString(&p->zErrMsg, sqlite_error_string(rc), (char*)0);
  40716. + goto vdbe_halt;
  40717. +}
  40718. --- /dev/null
  40719. +++ b/ext/sqlite/libsqlite/src/vdbe.h
  40720. @@ -0,0 +1,112 @@
  40721. +/*
  40722. +** 2001 September 15
  40723. +**
  40724. +** The author disclaims copyright to this source code. In place of
  40725. +** a legal notice, here is a blessing:
  40726. +**
  40727. +** May you do good and not evil.
  40728. +** May you find forgiveness for yourself and forgive others.
  40729. +** May you share freely, never taking more than you give.
  40730. +**
  40731. +*************************************************************************
  40732. +** Header file for the Virtual DataBase Engine (VDBE)
  40733. +**
  40734. +** This header defines the interface to the virtual database engine
  40735. +** or VDBE. The VDBE implements an abstract machine that runs a
  40736. +** simple program to access and modify the underlying database.
  40737. +**
  40738. +** $Id$
  40739. +*/
  40740. +#ifndef _SQLITE_VDBE_H_
  40741. +#define _SQLITE_VDBE_H_
  40742. +#include <stdio.h>
  40743. +
  40744. +/*
  40745. +** A single VDBE is an opaque structure named "Vdbe". Only routines
  40746. +** in the source file sqliteVdbe.c are allowed to see the insides
  40747. +** of this structure.
  40748. +*/
  40749. +typedef struct Vdbe Vdbe;
  40750. +
  40751. +/*
  40752. +** A single instruction of the virtual machine has an opcode
  40753. +** and as many as three operands. The instruction is recorded
  40754. +** as an instance of the following structure:
  40755. +*/
  40756. +struct VdbeOp {
  40757. + u8 opcode; /* What operation to perform */
  40758. + int p1; /* First operand */
  40759. + int p2; /* Second parameter (often the jump destination) */
  40760. + char *p3; /* Third parameter */
  40761. + int p3type; /* P3_STATIC, P3_DYNAMIC or P3_POINTER */
  40762. +#ifdef VDBE_PROFILE
  40763. + int cnt; /* Number of times this instruction was executed */
  40764. + long long cycles; /* Total time spend executing this instruction */
  40765. +#endif
  40766. +};
  40767. +typedef struct VdbeOp VdbeOp;
  40768. +
  40769. +/*
  40770. +** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  40771. +** it takes up less space.
  40772. +*/
  40773. +struct VdbeOpList {
  40774. + u8 opcode; /* What operation to perform */
  40775. + signed char p1; /* First operand */
  40776. + short int p2; /* Second parameter (often the jump destination) */
  40777. + char *p3; /* Third parameter */
  40778. +};
  40779. +typedef struct VdbeOpList VdbeOpList;
  40780. +
  40781. +/*
  40782. +** Allowed values of VdbeOp.p3type
  40783. +*/
  40784. +#define P3_NOTUSED 0 /* The P3 parameter is not used */
  40785. +#define P3_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  40786. +#define P3_STATIC (-2) /* Pointer to a static string */
  40787. +#define P3_POINTER (-3) /* P3 is a pointer to some structure or object */
  40788. +
  40789. +/*
  40790. +** The following macro converts a relative address in the p2 field
  40791. +** of a VdbeOp structure into a negative number so that
  40792. +** sqliteVdbeAddOpList() knows that the address is relative. Calling
  40793. +** the macro again restores the address.
  40794. +*/
  40795. +#define ADDR(X) (-1-(X))
  40796. +
  40797. +/*
  40798. +** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  40799. +** header file that defines a number for each opcode used by the VDBE.
  40800. +*/
  40801. +#include "opcodes.h"
  40802. +
  40803. +/*
  40804. +** Prototypes for the VDBE interface. See comments on the implementation
  40805. +** for a description of what each of these routines does.
  40806. +*/
  40807. +Vdbe *sqliteVdbeCreate(sqlite*);
  40808. +void sqliteVdbeCreateCallback(Vdbe*, int*);
  40809. +int sqliteVdbeAddOp(Vdbe*,int,int,int);
  40810. +int sqliteVdbeOp3(Vdbe*,int,int,int,const char *zP3,int);
  40811. +int sqliteVdbeCode(Vdbe*,...);
  40812. +int sqliteVdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
  40813. +void sqliteVdbeChangeP1(Vdbe*, int addr, int P1);
  40814. +void sqliteVdbeChangeP2(Vdbe*, int addr, int P2);
  40815. +void sqliteVdbeChangeP3(Vdbe*, int addr, const char *zP1, int N);
  40816. +void sqliteVdbeDequoteP3(Vdbe*, int addr);
  40817. +int sqliteVdbeFindOp(Vdbe*, int, int);
  40818. +VdbeOp *sqliteVdbeGetOp(Vdbe*, int);
  40819. +int sqliteVdbeMakeLabel(Vdbe*);
  40820. +void sqliteVdbeDelete(Vdbe*);
  40821. +void sqliteVdbeMakeReady(Vdbe*,int,int);
  40822. +int sqliteVdbeExec(Vdbe*);
  40823. +int sqliteVdbeList(Vdbe*);
  40824. +int sqliteVdbeFinalize(Vdbe*,char**);
  40825. +void sqliteVdbeResolveLabel(Vdbe*, int);
  40826. +int sqliteVdbeCurrentAddr(Vdbe*);
  40827. +void sqliteVdbeTrace(Vdbe*,FILE*);
  40828. +void sqliteVdbeCompressSpace(Vdbe*,int);
  40829. +int sqliteVdbeReset(Vdbe*,char **);
  40830. +int sqliteVdbeSetVariables(Vdbe*,int,const char**);
  40831. +
  40832. +#endif
  40833. --- /dev/null
  40834. +++ b/ext/sqlite/libsqlite/src/vdbeInt.h
  40835. @@ -0,0 +1,303 @@
  40836. +/*
  40837. +** 2003 September 6
  40838. +**
  40839. +** The author disclaims copyright to this source code. In place of
  40840. +** a legal notice, here is a blessing:
  40841. +**
  40842. +** May you do good and not evil.
  40843. +** May you find forgiveness for yourself and forgive others.
  40844. +** May you share freely, never taking more than you give.
  40845. +**
  40846. +*************************************************************************
  40847. +** This is the header file for information that is private to the
  40848. +** VDBE. This information used to all be at the top of the single
  40849. +** source code file "vdbe.c". When that file became too big (over
  40850. +** 6000 lines long) it was split up into several smaller files and
  40851. +** this header information was factored out.
  40852. +*/
  40853. +
  40854. +/*
  40855. +** When converting from the native format to the key format and back
  40856. +** again, in addition to changing the byte order we invert the high-order
  40857. +** bit of the most significant byte. This causes negative numbers to
  40858. +** sort before positive numbers in the memcmp() function.
  40859. +*/
  40860. +#define keyToInt(X) (sqliteVdbeByteSwap(X) ^ 0x80000000)
  40861. +#define intToKey(X) (sqliteVdbeByteSwap((X) ^ 0x80000000))
  40862. +
  40863. +/*
  40864. +** The makefile scans this source file and creates the following
  40865. +** array of string constants which are the names of all VDBE opcodes.
  40866. +** This array is defined in a separate source code file named opcode.c
  40867. +** which is automatically generated by the makefile.
  40868. +*/
  40869. +extern char *sqliteOpcodeNames[];
  40870. +
  40871. +/*
  40872. +** SQL is translated into a sequence of instructions to be
  40873. +** executed by a virtual machine. Each instruction is an instance
  40874. +** of the following structure.
  40875. +*/
  40876. +typedef struct VdbeOp Op;
  40877. +
  40878. +/*
  40879. +** Boolean values
  40880. +*/
  40881. +typedef unsigned char Bool;
  40882. +
  40883. +/*
  40884. +** A cursor is a pointer into a single BTree within a database file.
  40885. +** The cursor can seek to a BTree entry with a particular key, or
  40886. +** loop over all entries of the Btree. You can also insert new BTree
  40887. +** entries or retrieve the key or data from the entry that the cursor
  40888. +** is currently pointing to.
  40889. +**
  40890. +** Every cursor that the virtual machine has open is represented by an
  40891. +** instance of the following structure.
  40892. +**
  40893. +** If the Cursor.isTriggerRow flag is set it means that this cursor is
  40894. +** really a single row that represents the NEW or OLD pseudo-table of
  40895. +** a row trigger. The data for the row is stored in Cursor.pData and
  40896. +** the rowid is in Cursor.iKey.
  40897. +*/
  40898. +struct Cursor {
  40899. + BtCursor *pCursor; /* The cursor structure of the backend */
  40900. + int lastRecno; /* Last recno from a Next or NextIdx operation */
  40901. + int nextRowid; /* Next rowid returned by OP_NewRowid */
  40902. + Bool recnoIsValid; /* True if lastRecno is valid */
  40903. + Bool keyAsData; /* The OP_Column command works on key instead of data */
  40904. + Bool atFirst; /* True if pointing to first entry */
  40905. + Bool useRandomRowid; /* Generate new record numbers semi-randomly */
  40906. + Bool nullRow; /* True if pointing to a row with no data */
  40907. + Bool nextRowidValid; /* True if the nextRowid field is valid */
  40908. + Bool pseudoTable; /* This is a NEW or OLD pseudo-tables of a trigger */
  40909. + Bool deferredMoveto; /* A call to sqliteBtreeMoveto() is needed */
  40910. + int movetoTarget; /* Argument to the deferred sqliteBtreeMoveto() */
  40911. + Btree *pBt; /* Separate file holding temporary table */
  40912. + int nData; /* Number of bytes in pData */
  40913. + char *pData; /* Data for a NEW or OLD pseudo-table */
  40914. + int iKey; /* Key for the NEW or OLD pseudo-table row */
  40915. +};
  40916. +typedef struct Cursor Cursor;
  40917. +
  40918. +/*
  40919. +** A sorter builds a list of elements to be sorted. Each element of
  40920. +** the list is an instance of the following structure.
  40921. +*/
  40922. +typedef struct Sorter Sorter;
  40923. +struct Sorter {
  40924. + int nKey; /* Number of bytes in the key */
  40925. + char *zKey; /* The key by which we will sort */
  40926. + int nData; /* Number of bytes in the data */
  40927. + char *pData; /* The data associated with this key */
  40928. + Sorter *pNext; /* Next in the list */
  40929. +};
  40930. +
  40931. +/*
  40932. +** Number of buckets used for merge-sort.
  40933. +*/
  40934. +#define NSORT 30
  40935. +
  40936. +/*
  40937. +** Number of bytes of string storage space available to each stack
  40938. +** layer without having to malloc. NBFS is short for Number of Bytes
  40939. +** For Strings.
  40940. +*/
  40941. +#define NBFS 32
  40942. +
  40943. +/*
  40944. +** A single level of the stack or a single memory cell
  40945. +** is an instance of the following structure.
  40946. +*/
  40947. +struct Mem {
  40948. + int i; /* Integer value */
  40949. + int n; /* Number of characters in string value, including '\0' */
  40950. + int flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  40951. + double r; /* Real value */
  40952. + char *z; /* String value */
  40953. + char zShort[NBFS]; /* Space for short strings */
  40954. +};
  40955. +typedef struct Mem Mem;
  40956. +
  40957. +/*
  40958. +** Allowed values for Mem.flags
  40959. +*/
  40960. +#define MEM_Null 0x0001 /* Value is NULL */
  40961. +#define MEM_Str 0x0002 /* Value is a string */
  40962. +#define MEM_Int 0x0004 /* Value is an integer */
  40963. +#define MEM_Real 0x0008 /* Value is a real number */
  40964. +#define MEM_Dyn 0x0010 /* Need to call sqliteFree() on Mem.z */
  40965. +#define MEM_Static 0x0020 /* Mem.z points to a static string */
  40966. +#define MEM_Ephem 0x0040 /* Mem.z points to an ephemeral string */
  40967. +#define MEM_Short 0x0080 /* Mem.z points to Mem.zShort */
  40968. +
  40969. +/* The following MEM_ value appears only in AggElem.aMem.s.flag fields.
  40970. +** It indicates that the corresponding AggElem.aMem.z points to a
  40971. +** aggregate function context that needs to be finalized.
  40972. +*/
  40973. +#define MEM_AggCtx 0x0100 /* Mem.z points to an agg function context */
  40974. +
  40975. +/*
  40976. +** The "context" argument for a installable function. A pointer to an
  40977. +** instance of this structure is the first argument to the routines used
  40978. +** implement the SQL functions.
  40979. +**
  40980. +** There is a typedef for this structure in sqlite.h. So all routines,
  40981. +** even the public interface to SQLite, can use a pointer to this structure.
  40982. +** But this file is the only place where the internal details of this
  40983. +** structure are known.
  40984. +**
  40985. +** This structure is defined inside of vdbe.c because it uses substructures
  40986. +** (Mem) which are only defined there.
  40987. +*/
  40988. +struct sqlite_func {
  40989. + FuncDef *pFunc; /* Pointer to function information. MUST BE FIRST */
  40990. + Mem s; /* The return value is stored here */
  40991. + void *pAgg; /* Aggregate context */
  40992. + u8 isError; /* Set to true for an error */
  40993. + u8 isStep; /* Current in the step function */
  40994. + int cnt; /* Number of times that the step function has been called */
  40995. +};
  40996. +
  40997. +/*
  40998. +** An Agg structure describes an Aggregator. Each Agg consists of
  40999. +** zero or more Aggregator elements (AggElem). Each AggElem contains
  41000. +** a key and one or more values. The values are used in processing
  41001. +** aggregate functions in a SELECT. The key is used to implement
  41002. +** the GROUP BY clause of a select.
  41003. +*/
  41004. +typedef struct Agg Agg;
  41005. +typedef struct AggElem AggElem;
  41006. +struct Agg {
  41007. + int nMem; /* Number of values stored in each AggElem */
  41008. + AggElem *pCurrent; /* The AggElem currently in focus */
  41009. + HashElem *pSearch; /* The hash element for pCurrent */
  41010. + Hash hash; /* Hash table of all aggregate elements */
  41011. + FuncDef **apFunc; /* Information about aggregate functions */
  41012. +};
  41013. +struct AggElem {
  41014. + char *zKey; /* The key to this AggElem */
  41015. + int nKey; /* Number of bytes in the key, including '\0' at end */
  41016. + Mem aMem[1]; /* The values for this AggElem */
  41017. +};
  41018. +
  41019. +/*
  41020. +** A Set structure is used for quick testing to see if a value
  41021. +** is part of a small set. Sets are used to implement code like
  41022. +** this:
  41023. +** x.y IN ('hi','hoo','hum')
  41024. +*/
  41025. +typedef struct Set Set;
  41026. +struct Set {
  41027. + Hash hash; /* A set is just a hash table */
  41028. + HashElem *prev; /* Previously accessed hash elemen */
  41029. +};
  41030. +
  41031. +/*
  41032. +** A Keylist is a bunch of keys into a table. The keylist can
  41033. +** grow without bound. The keylist stores the ROWIDs of database
  41034. +** records that need to be deleted or updated.
  41035. +*/
  41036. +typedef struct Keylist Keylist;
  41037. +struct Keylist {
  41038. + int nKey; /* Number of slots in aKey[] */
  41039. + int nUsed; /* Next unwritten slot in aKey[] */
  41040. + int nRead; /* Next unread slot in aKey[] */
  41041. + Keylist *pNext; /* Next block of keys */
  41042. + int aKey[1]; /* One or more keys. Extra space allocated as needed */
  41043. +};
  41044. +
  41045. +/*
  41046. +** A Context stores the last insert rowid, the last statement change count,
  41047. +** and the current statement change count (i.e. changes since last statement).
  41048. +** Elements of Context structure type make up the ContextStack, which is
  41049. +** updated by the ContextPush and ContextPop opcodes (used by triggers)
  41050. +*/
  41051. +typedef struct Context Context;
  41052. +struct Context {
  41053. + int lastRowid; /* Last insert rowid (from db->lastRowid) */
  41054. + int lsChange; /* Last statement change count (from db->lsChange) */
  41055. + int csChange; /* Current statement change count (from db->csChange) */
  41056. +};
  41057. +
  41058. +/*
  41059. +** An instance of the virtual machine. This structure contains the complete
  41060. +** state of the virtual machine.
  41061. +**
  41062. +** The "sqlite_vm" structure pointer that is returned by sqlite_compile()
  41063. +** is really a pointer to an instance of this structure.
  41064. +*/
  41065. +struct Vdbe {
  41066. + sqlite *db; /* The whole database */
  41067. + Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  41068. + FILE *trace; /* Write an execution trace here, if not NULL */
  41069. + int nOp; /* Number of instructions in the program */
  41070. + int nOpAlloc; /* Number of slots allocated for aOp[] */
  41071. + Op *aOp; /* Space to hold the virtual machine's program */
  41072. + int nLabel; /* Number of labels used */
  41073. + int nLabelAlloc; /* Number of slots allocated in aLabel[] */
  41074. + int *aLabel; /* Space to hold the labels */
  41075. + Mem *aStack; /* The operand stack, except string values */
  41076. + Mem *pTos; /* Top entry in the operand stack */
  41077. + char **zArgv; /* Text values used by the callback */
  41078. + char **azColName; /* Becomes the 4th parameter to callbacks */
  41079. + int nCursor; /* Number of slots in aCsr[] */
  41080. + Cursor *aCsr; /* One element of this array for each open cursor */
  41081. + Sorter *pSort; /* A linked list of objects to be sorted */
  41082. + FILE *pFile; /* At most one open file handler */
  41083. + int nField; /* Number of file fields */
  41084. + char **azField; /* Data for each file field */
  41085. + int nVar; /* Number of entries in azVariable[] */
  41086. + char **azVar; /* Values for the OP_Variable opcode */
  41087. + int *anVar; /* Length of each value in azVariable[] */
  41088. + u8 *abVar; /* TRUE if azVariable[i] needs to be sqliteFree()ed */
  41089. + char *zLine; /* A single line from the input file */
  41090. + int nLineAlloc; /* Number of spaces allocated for zLine */
  41091. + int magic; /* Magic number for sanity checking */
  41092. + int nMem; /* Number of memory locations currently allocated */
  41093. + Mem *aMem; /* The memory locations */
  41094. + Agg agg; /* Aggregate information */
  41095. + int nSet; /* Number of sets allocated */
  41096. + Set *aSet; /* An array of sets */
  41097. + int nCallback; /* Number of callbacks invoked so far */
  41098. + Keylist *pList; /* A list of ROWIDs */
  41099. + int keylistStackDepth; /* The size of the "keylist" stack */
  41100. + Keylist **keylistStack; /* The stack used by opcodes ListPush & ListPop */
  41101. + int contextStackDepth; /* The size of the "context" stack */
  41102. + Context *contextStack; /* Stack used by opcodes ContextPush & ContextPop*/
  41103. + int pc; /* The program counter */
  41104. + int rc; /* Value to return */
  41105. + unsigned uniqueCnt; /* Used by OP_MakeRecord when P2!=0 */
  41106. + int errorAction; /* Recovery action to do in case of an error */
  41107. + int undoTransOnError; /* If error, either ROLLBACK or COMMIT */
  41108. + int inTempTrans; /* True if temp database is transactioned */
  41109. + int returnStack[100]; /* Return address stack for OP_Gosub & OP_Return */
  41110. + int returnDepth; /* Next unused element in returnStack[] */
  41111. + int nResColumn; /* Number of columns in one row of the result set */
  41112. + char **azResColumn; /* Values for one row of result */
  41113. + int popStack; /* Pop the stack this much on entry to VdbeExec() */
  41114. + char *zErrMsg; /* Error message written here */
  41115. + u8 explain; /* True if EXPLAIN present on SQL command */
  41116. +};
  41117. +
  41118. +/*
  41119. +** The following are allowed values for Vdbe.magic
  41120. +*/
  41121. +#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  41122. +#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  41123. +#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  41124. +#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  41125. +
  41126. +/*
  41127. +** Function prototypes
  41128. +*/
  41129. +void sqliteVdbeCleanupCursor(Cursor*);
  41130. +void sqliteVdbeSorterReset(Vdbe*);
  41131. +void sqliteVdbeAggReset(Agg*);
  41132. +void sqliteVdbeKeylistFree(Keylist*);
  41133. +void sqliteVdbePopStack(Vdbe*,int);
  41134. +int sqliteVdbeCursorMoveto(Cursor*);
  41135. +int sqliteVdbeByteSwap(int);
  41136. +#if !defined(NDEBUG) || defined(VDBE_PROFILE)
  41137. +void sqliteVdbePrintOp(FILE*, int, Op*);
  41138. +#endif
  41139. --- /dev/null
  41140. +++ b/ext/sqlite/libsqlite/src/where.c
  41141. @@ -0,0 +1,1235 @@
  41142. +/*
  41143. +** 2001 September 15
  41144. +**
  41145. +** The author disclaims copyright to this source code. In place of
  41146. +** a legal notice, here is a blessing:
  41147. +**
  41148. +** May you do good and not evil.
  41149. +** May you find forgiveness for yourself and forgive others.
  41150. +** May you share freely, never taking more than you give.
  41151. +**
  41152. +*************************************************************************
  41153. +** This module contains C code that generates VDBE code used to process
  41154. +** the WHERE clause of SQL statements.
  41155. +**
  41156. +** $Id$
  41157. +*/
  41158. +#include "sqliteInt.h"
  41159. +
  41160. +/*
  41161. +** The query generator uses an array of instances of this structure to
  41162. +** help it analyze the subexpressions of the WHERE clause. Each WHERE
  41163. +** clause subexpression is separated from the others by an AND operator.
  41164. +*/
  41165. +typedef struct ExprInfo ExprInfo;
  41166. +struct ExprInfo {
  41167. + Expr *p; /* Pointer to the subexpression */
  41168. + u8 indexable; /* True if this subexprssion is usable by an index */
  41169. + short int idxLeft; /* p->pLeft is a column in this table number. -1 if
  41170. + ** p->pLeft is not the column of any table */
  41171. + short int idxRight; /* p->pRight is a column in this table number. -1 if
  41172. + ** p->pRight is not the column of any table */
  41173. + unsigned prereqLeft; /* Bitmask of tables referenced by p->pLeft */
  41174. + unsigned prereqRight; /* Bitmask of tables referenced by p->pRight */
  41175. + unsigned prereqAll; /* Bitmask of tables referenced by p */
  41176. +};
  41177. +
  41178. +/*
  41179. +** An instance of the following structure keeps track of a mapping
  41180. +** between VDBE cursor numbers and bitmasks. The VDBE cursor numbers
  41181. +** are small integers contained in SrcList_item.iCursor and Expr.iTable
  41182. +** fields. For any given WHERE clause, we want to track which cursors
  41183. +** are being used, so we assign a single bit in a 32-bit word to track
  41184. +** that cursor. Then a 32-bit integer is able to show the set of all
  41185. +** cursors being used.
  41186. +*/
  41187. +typedef struct ExprMaskSet ExprMaskSet;
  41188. +struct ExprMaskSet {
  41189. + int n; /* Number of assigned cursor values */
  41190. + int ix[31]; /* Cursor assigned to each bit */
  41191. +};
  41192. +
  41193. +/*
  41194. +** Determine the number of elements in an array.
  41195. +*/
  41196. +#define ARRAYSIZE(X) (sizeof(X)/sizeof(X[0]))
  41197. +
  41198. +/*
  41199. +** This routine is used to divide the WHERE expression into subexpressions
  41200. +** separated by the AND operator.
  41201. +**
  41202. +** aSlot[] is an array of subexpressions structures.
  41203. +** There are nSlot spaces left in this array. This routine attempts to
  41204. +** split pExpr into subexpressions and fills aSlot[] with those subexpressions.
  41205. +** The return value is the number of slots filled.
  41206. +*/
  41207. +static int exprSplit(int nSlot, ExprInfo *aSlot, Expr *pExpr){
  41208. + int cnt = 0;
  41209. + if( pExpr==0 || nSlot<1 ) return 0;
  41210. + if( nSlot==1 || pExpr->op!=TK_AND ){
  41211. + aSlot[0].p = pExpr;
  41212. + return 1;
  41213. + }
  41214. + if( pExpr->pLeft->op!=TK_AND ){
  41215. + aSlot[0].p = pExpr->pLeft;
  41216. + cnt = 1 + exprSplit(nSlot-1, &aSlot[1], pExpr->pRight);
  41217. + }else{
  41218. + cnt = exprSplit(nSlot, aSlot, pExpr->pLeft);
  41219. + cnt += exprSplit(nSlot-cnt, &aSlot[cnt], pExpr->pRight);
  41220. + }
  41221. + return cnt;
  41222. +}
  41223. +
  41224. +/*
  41225. +** Initialize an expression mask set
  41226. +*/
  41227. +#define initMaskSet(P) memset(P, 0, sizeof(*P))
  41228. +
  41229. +/*
  41230. +** Return the bitmask for the given cursor. Assign a new bitmask
  41231. +** if this is the first time the cursor has been seen.
  41232. +*/
  41233. +static int getMask(ExprMaskSet *pMaskSet, int iCursor){
  41234. + int i;
  41235. + for(i=0; i<pMaskSet->n; i++){
  41236. + if( pMaskSet->ix[i]==iCursor ) return 1<<i;
  41237. + }
  41238. + if( i==pMaskSet->n && i<ARRAYSIZE(pMaskSet->ix) ){
  41239. + pMaskSet->n++;
  41240. + pMaskSet->ix[i] = iCursor;
  41241. + return 1<<i;
  41242. + }
  41243. + return 0;
  41244. +}
  41245. +
  41246. +/*
  41247. +** Destroy an expression mask set
  41248. +*/
  41249. +#define freeMaskSet(P) /* NO-OP */
  41250. +
  41251. +/*
  41252. +** This routine walks (recursively) an expression tree and generates
  41253. +** a bitmask indicating which tables are used in that expression
  41254. +** tree.
  41255. +**
  41256. +** In order for this routine to work, the calling function must have
  41257. +** previously invoked sqliteExprResolveIds() on the expression. See
  41258. +** the header comment on that routine for additional information.
  41259. +** The sqliteExprResolveIds() routines looks for column names and
  41260. +** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
  41261. +** the VDBE cursor number of the table.
  41262. +*/
  41263. +static int exprTableUsage(ExprMaskSet *pMaskSet, Expr *p){
  41264. + unsigned int mask = 0;
  41265. + if( p==0 ) return 0;
  41266. + if( p->op==TK_COLUMN ){
  41267. + mask = getMask(pMaskSet, p->iTable);
  41268. + if( mask==0 ) mask = -1;
  41269. + return mask;
  41270. + }
  41271. + if( p->pRight ){
  41272. + mask = exprTableUsage(pMaskSet, p->pRight);
  41273. + }
  41274. + if( p->pLeft ){
  41275. + mask |= exprTableUsage(pMaskSet, p->pLeft);
  41276. + }
  41277. + if( p->pList ){
  41278. + int i;
  41279. + for(i=0; i<p->pList->nExpr; i++){
  41280. + mask |= exprTableUsage(pMaskSet, p->pList->a[i].pExpr);
  41281. + }
  41282. + }
  41283. + return mask;
  41284. +}
  41285. +
  41286. +/*
  41287. +** Return TRUE if the given operator is one of the operators that is
  41288. +** allowed for an indexable WHERE clause. The allowed operators are
  41289. +** "=", "<", ">", "<=", ">=", and "IN".
  41290. +*/
  41291. +static int allowedOp(int op){
  41292. + switch( op ){
  41293. + case TK_LT:
  41294. + case TK_LE:
  41295. + case TK_GT:
  41296. + case TK_GE:
  41297. + case TK_EQ:
  41298. + case TK_IN:
  41299. + return 1;
  41300. + default:
  41301. + return 0;
  41302. + }
  41303. +}
  41304. +
  41305. +/*
  41306. +** The input to this routine is an ExprInfo structure with only the
  41307. +** "p" field filled in. The job of this routine is to analyze the
  41308. +** subexpression and populate all the other fields of the ExprInfo
  41309. +** structure.
  41310. +*/
  41311. +static void exprAnalyze(ExprMaskSet *pMaskSet, ExprInfo *pInfo){
  41312. + Expr *pExpr = pInfo->p;
  41313. + pInfo->prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  41314. + pInfo->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  41315. + pInfo->prereqAll = exprTableUsage(pMaskSet, pExpr);
  41316. + pInfo->indexable = 0;
  41317. + pInfo->idxLeft = -1;
  41318. + pInfo->idxRight = -1;
  41319. + if( allowedOp(pExpr->op) && (pInfo->prereqRight & pInfo->prereqLeft)==0 ){
  41320. + if( pExpr->pRight && pExpr->pRight->op==TK_COLUMN ){
  41321. + pInfo->idxRight = pExpr->pRight->iTable;
  41322. + pInfo->indexable = 1;
  41323. + }
  41324. + if( pExpr->pLeft->op==TK_COLUMN ){
  41325. + pInfo->idxLeft = pExpr->pLeft->iTable;
  41326. + pInfo->indexable = 1;
  41327. + }
  41328. + }
  41329. +}
  41330. +
  41331. +/*
  41332. +** pOrderBy is an ORDER BY clause from a SELECT statement. pTab is the
  41333. +** left-most table in the FROM clause of that same SELECT statement and
  41334. +** the table has a cursor number of "base".
  41335. +**
  41336. +** This routine attempts to find an index for pTab that generates the
  41337. +** correct record sequence for the given ORDER BY clause. The return value
  41338. +** is a pointer to an index that does the job. NULL is returned if the
  41339. +** table has no index that will generate the correct sort order.
  41340. +**
  41341. +** If there are two or more indices that generate the correct sort order
  41342. +** and pPreferredIdx is one of those indices, then return pPreferredIdx.
  41343. +**
  41344. +** nEqCol is the number of columns of pPreferredIdx that are used as
  41345. +** equality constraints. Any index returned must have exactly this same
  41346. +** set of columns. The ORDER BY clause only matches index columns beyond the
  41347. +** the first nEqCol columns.
  41348. +**
  41349. +** All terms of the ORDER BY clause must be either ASC or DESC. The
  41350. +** *pbRev value is set to 1 if the ORDER BY clause is all DESC and it is
  41351. +** set to 0 if the ORDER BY clause is all ASC.
  41352. +*/
  41353. +static Index *findSortingIndex(
  41354. + Table *pTab, /* The table to be sorted */
  41355. + int base, /* Cursor number for pTab */
  41356. + ExprList *pOrderBy, /* The ORDER BY clause */
  41357. + Index *pPreferredIdx, /* Use this index, if possible and not NULL */
  41358. + int nEqCol, /* Number of index columns used with == constraints */
  41359. + int *pbRev /* Set to 1 if ORDER BY is DESC */
  41360. +){
  41361. + int i, j;
  41362. + Index *pMatch;
  41363. + Index *pIdx;
  41364. + int sortOrder;
  41365. +
  41366. + assert( pOrderBy!=0 );
  41367. + assert( pOrderBy->nExpr>0 );
  41368. + sortOrder = pOrderBy->a[0].sortOrder & SQLITE_SO_DIRMASK;
  41369. + for(i=0; i<pOrderBy->nExpr; i++){
  41370. + Expr *p;
  41371. + if( (pOrderBy->a[i].sortOrder & SQLITE_SO_DIRMASK)!=sortOrder ){
  41372. + /* Indices can only be used if all ORDER BY terms are either
  41373. + ** DESC or ASC. Indices cannot be used on a mixture. */
  41374. + return 0;
  41375. + }
  41376. + if( (pOrderBy->a[i].sortOrder & SQLITE_SO_TYPEMASK)!=SQLITE_SO_UNK ){
  41377. + /* Do not sort by index if there is a COLLATE clause */
  41378. + return 0;
  41379. + }
  41380. + p = pOrderBy->a[i].pExpr;
  41381. + if( p->op!=TK_COLUMN || p->iTable!=base ){
  41382. + /* Can not use an index sort on anything that is not a column in the
  41383. + ** left-most table of the FROM clause */
  41384. + return 0;
  41385. + }
  41386. + }
  41387. +
  41388. + /* If we get this far, it means the ORDER BY clause consists only of
  41389. + ** ascending columns in the left-most table of the FROM clause. Now
  41390. + ** check for a matching index.
  41391. + */
  41392. + pMatch = 0;
  41393. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  41394. + int nExpr = pOrderBy->nExpr;
  41395. + if( pIdx->nColumn < nEqCol || pIdx->nColumn < nExpr ) continue;
  41396. + for(i=j=0; i<nEqCol; i++){
  41397. + if( pPreferredIdx->aiColumn[i]!=pIdx->aiColumn[i] ) break;
  41398. + if( j<nExpr && pOrderBy->a[j].pExpr->iColumn==pIdx->aiColumn[i] ){ j++; }
  41399. + }
  41400. + if( i<nEqCol ) continue;
  41401. + for(i=0; i+j<nExpr; i++){
  41402. + if( pOrderBy->a[i+j].pExpr->iColumn!=pIdx->aiColumn[i+nEqCol] ) break;
  41403. + }
  41404. + if( i+j>=nExpr ){
  41405. + pMatch = pIdx;
  41406. + if( pIdx==pPreferredIdx ) break;
  41407. + }
  41408. + }
  41409. + if( pMatch && pbRev ){
  41410. + *pbRev = sortOrder==SQLITE_SO_DESC;
  41411. + }
  41412. + return pMatch;
  41413. +}
  41414. +
  41415. +/*
  41416. +** Disable a term in the WHERE clause. Except, do not disable the term
  41417. +** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  41418. +** or USING clause of that join.
  41419. +**
  41420. +** Consider the term t2.z='ok' in the following queries:
  41421. +**
  41422. +** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  41423. +** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  41424. +** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  41425. +**
  41426. +** The t2.z='ok' is disabled in the in (2) because it did not originate
  41427. +** in the ON clause. The term is disabled in (3) because it is not part
  41428. +** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  41429. +**
  41430. +** Disabling a term causes that term to not be tested in the inner loop
  41431. +** of the join. Disabling is an optimization. We would get the correct
  41432. +** results if nothing were ever disabled, but joins might run a little
  41433. +** slower. The trick is to disable as much as we can without disabling
  41434. +** too much. If we disabled in (1), we'd get the wrong answer.
  41435. +** See ticket #813.
  41436. +*/
  41437. +static void disableTerm(WhereLevel *pLevel, Expr **ppExpr){
  41438. + Expr *pExpr = *ppExpr;
  41439. + if( pLevel->iLeftJoin==0 || ExprHasProperty(pExpr, EP_FromJoin) ){
  41440. + *ppExpr = 0;
  41441. + }
  41442. +}
  41443. +
  41444. +/*
  41445. +** Generate the beginning of the loop used for WHERE clause processing.
  41446. +** The return value is a pointer to an (opaque) structure that contains
  41447. +** information needed to terminate the loop. Later, the calling routine
  41448. +** should invoke sqliteWhereEnd() with the return value of this function
  41449. +** in order to complete the WHERE clause processing.
  41450. +**
  41451. +** If an error occurs, this routine returns NULL.
  41452. +**
  41453. +** The basic idea is to do a nested loop, one loop for each table in
  41454. +** the FROM clause of a select. (INSERT and UPDATE statements are the
  41455. +** same as a SELECT with only a single table in the FROM clause.) For
  41456. +** example, if the SQL is this:
  41457. +**
  41458. +** SELECT * FROM t1, t2, t3 WHERE ...;
  41459. +**
  41460. +** Then the code generated is conceptually like the following:
  41461. +**
  41462. +** foreach row1 in t1 do \ Code generated
  41463. +** foreach row2 in t2 do |-- by sqliteWhereBegin()
  41464. +** foreach row3 in t3 do /
  41465. +** ...
  41466. +** end \ Code generated
  41467. +** end |-- by sqliteWhereEnd()
  41468. +** end /
  41469. +**
  41470. +** There are Btree cursors associated with each table. t1 uses cursor
  41471. +** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  41472. +** And so forth. This routine generates code to open those VDBE cursors
  41473. +** and sqliteWhereEnd() generates the code to close them.
  41474. +**
  41475. +** If the WHERE clause is empty, the foreach loops must each scan their
  41476. +** entire tables. Thus a three-way join is an O(N^3) operation. But if
  41477. +** the tables have indices and there are terms in the WHERE clause that
  41478. +** refer to those indices, a complete table scan can be avoided and the
  41479. +** code will run much faster. Most of the work of this routine is checking
  41480. +** to see if there are indices that can be used to speed up the loop.
  41481. +**
  41482. +** Terms of the WHERE clause are also used to limit which rows actually
  41483. +** make it to the "..." in the middle of the loop. After each "foreach",
  41484. +** terms of the WHERE clause that use only terms in that loop and outer
  41485. +** loops are evaluated and if false a jump is made around all subsequent
  41486. +** inner loops (or around the "..." if the test occurs within the inner-
  41487. +** most loop)
  41488. +**
  41489. +** OUTER JOINS
  41490. +**
  41491. +** An outer join of tables t1 and t2 is conceptally coded as follows:
  41492. +**
  41493. +** foreach row1 in t1 do
  41494. +** flag = 0
  41495. +** foreach row2 in t2 do
  41496. +** start:
  41497. +** ...
  41498. +** flag = 1
  41499. +** end
  41500. +** if flag==0 then
  41501. +** move the row2 cursor to a null row
  41502. +** goto start
  41503. +** fi
  41504. +** end
  41505. +**
  41506. +** ORDER BY CLAUSE PROCESSING
  41507. +**
  41508. +** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
  41509. +** if there is one. If there is no ORDER BY clause or if this routine
  41510. +** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
  41511. +**
  41512. +** If an index can be used so that the natural output order of the table
  41513. +** scan is correct for the ORDER BY clause, then that index is used and
  41514. +** *ppOrderBy is set to NULL. This is an optimization that prevents an
  41515. +** unnecessary sort of the result set if an index appropriate for the
  41516. +** ORDER BY clause already exists.
  41517. +**
  41518. +** If the where clause loops cannot be arranged to provide the correct
  41519. +** output order, then the *ppOrderBy is unchanged.
  41520. +*/
  41521. +WhereInfo *sqliteWhereBegin(
  41522. + Parse *pParse, /* The parser context */
  41523. + SrcList *pTabList, /* A list of all tables to be scanned */
  41524. + Expr *pWhere, /* The WHERE clause */
  41525. + int pushKey, /* If TRUE, leave the table key on the stack */
  41526. + ExprList **ppOrderBy /* An ORDER BY clause, or NULL */
  41527. +){
  41528. + int i; /* Loop counter */
  41529. + WhereInfo *pWInfo; /* Will become the return value of this function */
  41530. + Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  41531. + int brk, cont = 0; /* Addresses used during code generation */
  41532. + int nExpr; /* Number of subexpressions in the WHERE clause */
  41533. + int loopMask; /* One bit set for each outer loop */
  41534. + int haveKey; /* True if KEY is on the stack */
  41535. + ExprMaskSet maskSet; /* The expression mask set */
  41536. + int iDirectEq[32]; /* Term of the form ROWID==X for the N-th table */
  41537. + int iDirectLt[32]; /* Term of the form ROWID<X or ROWID<=X */
  41538. + int iDirectGt[32]; /* Term of the form ROWID>X or ROWID>=X */
  41539. + ExprInfo aExpr[101]; /* The WHERE clause is divided into these expressions */
  41540. +
  41541. + /* pushKey is only allowed if there is a single table (as in an INSERT or
  41542. + ** UPDATE statement)
  41543. + */
  41544. + assert( pushKey==0 || pTabList->nSrc==1 );
  41545. +
  41546. + /* Split the WHERE clause into separate subexpressions where each
  41547. + ** subexpression is separated by an AND operator. If the aExpr[]
  41548. + ** array fills up, the last entry might point to an expression which
  41549. + ** contains additional unfactored AND operators.
  41550. + */
  41551. + initMaskSet(&maskSet);
  41552. + memset(aExpr, 0, sizeof(aExpr));
  41553. + nExpr = exprSplit(ARRAYSIZE(aExpr), aExpr, pWhere);
  41554. + if( nExpr==ARRAYSIZE(aExpr) ){
  41555. + sqliteErrorMsg(pParse, "WHERE clause too complex - no more "
  41556. + "than %d terms allowed", (int)ARRAYSIZE(aExpr)-1);
  41557. + return 0;
  41558. + }
  41559. +
  41560. + /* Allocate and initialize the WhereInfo structure that will become the
  41561. + ** return value.
  41562. + */
  41563. + pWInfo = sqliteMalloc( sizeof(WhereInfo) + pTabList->nSrc*sizeof(WhereLevel));
  41564. + if( sqlite_malloc_failed ){
  41565. + sqliteFree(pWInfo);
  41566. + return 0;
  41567. + }
  41568. + pWInfo->pParse = pParse;
  41569. + pWInfo->pTabList = pTabList;
  41570. + pWInfo->peakNTab = pWInfo->savedNTab = pParse->nTab;
  41571. + pWInfo->iBreak = sqliteVdbeMakeLabel(v);
  41572. +
  41573. + /* Special case: a WHERE clause that is constant. Evaluate the
  41574. + ** expression and either jump over all of the code or fall thru.
  41575. + */
  41576. + if( pWhere && (pTabList->nSrc==0 || sqliteExprIsConstant(pWhere)) ){
  41577. + sqliteExprIfFalse(pParse, pWhere, pWInfo->iBreak, 1);
  41578. + pWhere = 0;
  41579. + }
  41580. +
  41581. + /* Analyze all of the subexpressions.
  41582. + */
  41583. + for(i=0; i<nExpr; i++){
  41584. + exprAnalyze(&maskSet, &aExpr[i]);
  41585. +
  41586. + /* If we are executing a trigger body, remove all references to
  41587. + ** new.* and old.* tables from the prerequisite masks.
  41588. + */
  41589. + if( pParse->trigStack ){
  41590. + int x;
  41591. + if( (x = pParse->trigStack->newIdx) >= 0 ){
  41592. + int mask = ~getMask(&maskSet, x);
  41593. + aExpr[i].prereqRight &= mask;
  41594. + aExpr[i].prereqLeft &= mask;
  41595. + aExpr[i].prereqAll &= mask;
  41596. + }
  41597. + if( (x = pParse->trigStack->oldIdx) >= 0 ){
  41598. + int mask = ~getMask(&maskSet, x);
  41599. + aExpr[i].prereqRight &= mask;
  41600. + aExpr[i].prereqLeft &= mask;
  41601. + aExpr[i].prereqAll &= mask;
  41602. + }
  41603. + }
  41604. + }
  41605. +
  41606. + /* Figure out what index to use (if any) for each nested loop.
  41607. + ** Make pWInfo->a[i].pIdx point to the index to use for the i-th nested
  41608. + ** loop where i==0 is the outer loop and i==pTabList->nSrc-1 is the inner
  41609. + ** loop.
  41610. + **
  41611. + ** If terms exist that use the ROWID of any table, then set the
  41612. + ** iDirectEq[], iDirectLt[], or iDirectGt[] elements for that table
  41613. + ** to the index of the term containing the ROWID. We always prefer
  41614. + ** to use a ROWID which can directly access a table rather than an
  41615. + ** index which requires reading an index first to get the rowid then
  41616. + ** doing a second read of the actual database table.
  41617. + **
  41618. + ** Actually, if there are more than 32 tables in the join, only the
  41619. + ** first 32 tables are candidates for indices. This is (again) due
  41620. + ** to the limit of 32 bits in an integer bitmask.
  41621. + */
  41622. + loopMask = 0;
  41623. + for(i=0; i<pTabList->nSrc && i<ARRAYSIZE(iDirectEq); i++){
  41624. + int j;
  41625. + int iCur = pTabList->a[i].iCursor; /* The cursor for this table */
  41626. + int mask = getMask(&maskSet, iCur); /* Cursor mask for this table */
  41627. + Table *pTab = pTabList->a[i].pTab;
  41628. + Index *pIdx;
  41629. + Index *pBestIdx = 0;
  41630. + int bestScore = 0;
  41631. +
  41632. + /* Check to see if there is an expression that uses only the
  41633. + ** ROWID field of this table. For terms of the form ROWID==expr
  41634. + ** set iDirectEq[i] to the index of the term. For terms of the
  41635. + ** form ROWID<expr or ROWID<=expr set iDirectLt[i] to the term index.
  41636. + ** For terms like ROWID>expr or ROWID>=expr set iDirectGt[i].
  41637. + **
  41638. + ** (Added:) Treat ROWID IN expr like ROWID=expr.
  41639. + */
  41640. + pWInfo->a[i].iCur = -1;
  41641. + iDirectEq[i] = -1;
  41642. + iDirectLt[i] = -1;
  41643. + iDirectGt[i] = -1;
  41644. + for(j=0; j<nExpr; j++){
  41645. + if( aExpr[j].idxLeft==iCur && aExpr[j].p->pLeft->iColumn<0
  41646. + && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
  41647. + switch( aExpr[j].p->op ){
  41648. + case TK_IN:
  41649. + case TK_EQ: iDirectEq[i] = j; break;
  41650. + case TK_LE:
  41651. + case TK_LT: iDirectLt[i] = j; break;
  41652. + case TK_GE:
  41653. + case TK_GT: iDirectGt[i] = j; break;
  41654. + }
  41655. + }
  41656. + if( aExpr[j].idxRight==iCur && aExpr[j].p->pRight->iColumn<0
  41657. + && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
  41658. + switch( aExpr[j].p->op ){
  41659. + case TK_EQ: iDirectEq[i] = j; break;
  41660. + case TK_LE:
  41661. + case TK_LT: iDirectGt[i] = j; break;
  41662. + case TK_GE:
  41663. + case TK_GT: iDirectLt[i] = j; break;
  41664. + }
  41665. + }
  41666. + }
  41667. + if( iDirectEq[i]>=0 ){
  41668. + loopMask |= mask;
  41669. + pWInfo->a[i].pIdx = 0;
  41670. + continue;
  41671. + }
  41672. +
  41673. + /* Do a search for usable indices. Leave pBestIdx pointing to
  41674. + ** the "best" index. pBestIdx is left set to NULL if no indices
  41675. + ** are usable.
  41676. + **
  41677. + ** The best index is determined as follows. For each of the
  41678. + ** left-most terms that is fixed by an equality operator, add
  41679. + ** 8 to the score. The right-most term of the index may be
  41680. + ** constrained by an inequality. Add 1 if for an "x<..." constraint
  41681. + ** and add 2 for an "x>..." constraint. Chose the index that
  41682. + ** gives the best score.
  41683. + **
  41684. + ** This scoring system is designed so that the score can later be
  41685. + ** used to determine how the index is used. If the score&7 is 0
  41686. + ** then all constraints are equalities. If score&1 is not 0 then
  41687. + ** there is an inequality used as a termination key. (ex: "x<...")
  41688. + ** If score&2 is not 0 then there is an inequality used as the
  41689. + ** start key. (ex: "x>..."). A score or 4 is the special case
  41690. + ** of an IN operator constraint. (ex: "x IN ...").
  41691. + **
  41692. + ** The IN operator (as in "<expr> IN (...)") is treated the same as
  41693. + ** an equality comparison except that it can only be used on the
  41694. + ** left-most column of an index and other terms of the WHERE clause
  41695. + ** cannot be used in conjunction with the IN operator to help satisfy
  41696. + ** other columns of the index.
  41697. + */
  41698. + for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  41699. + int eqMask = 0; /* Index columns covered by an x=... term */
  41700. + int ltMask = 0; /* Index columns covered by an x<... term */
  41701. + int gtMask = 0; /* Index columns covered by an x>... term */
  41702. + int inMask = 0; /* Index columns covered by an x IN .. term */
  41703. + int nEq, m, score;
  41704. +
  41705. + if( pIdx->nColumn>32 ) continue; /* Ignore indices too many columns */
  41706. + for(j=0; j<nExpr; j++){
  41707. + if( aExpr[j].idxLeft==iCur
  41708. + && (aExpr[j].prereqRight & loopMask)==aExpr[j].prereqRight ){
  41709. + int iColumn = aExpr[j].p->pLeft->iColumn;
  41710. + int k;
  41711. + for(k=0; k<pIdx->nColumn; k++){
  41712. + if( pIdx->aiColumn[k]==iColumn ){
  41713. + switch( aExpr[j].p->op ){
  41714. + case TK_IN: {
  41715. + if( k==0 ) inMask |= 1;
  41716. + break;
  41717. + }
  41718. + case TK_EQ: {
  41719. + eqMask |= 1<<k;
  41720. + break;
  41721. + }
  41722. + case TK_LE:
  41723. + case TK_LT: {
  41724. + ltMask |= 1<<k;
  41725. + break;
  41726. + }
  41727. + case TK_GE:
  41728. + case TK_GT: {
  41729. + gtMask |= 1<<k;
  41730. + break;
  41731. + }
  41732. + default: {
  41733. + /* CANT_HAPPEN */
  41734. + assert( 0 );
  41735. + break;
  41736. + }
  41737. + }
  41738. + break;
  41739. + }
  41740. + }
  41741. + }
  41742. + if( aExpr[j].idxRight==iCur
  41743. + && (aExpr[j].prereqLeft & loopMask)==aExpr[j].prereqLeft ){
  41744. + int iColumn = aExpr[j].p->pRight->iColumn;
  41745. + int k;
  41746. + for(k=0; k<pIdx->nColumn; k++){
  41747. + if( pIdx->aiColumn[k]==iColumn ){
  41748. + switch( aExpr[j].p->op ){
  41749. + case TK_EQ: {
  41750. + eqMask |= 1<<k;
  41751. + break;
  41752. + }
  41753. + case TK_LE:
  41754. + case TK_LT: {
  41755. + gtMask |= 1<<k;
  41756. + break;
  41757. + }
  41758. + case TK_GE:
  41759. + case TK_GT: {
  41760. + ltMask |= 1<<k;
  41761. + break;
  41762. + }
  41763. + default: {
  41764. + /* CANT_HAPPEN */
  41765. + assert( 0 );
  41766. + break;
  41767. + }
  41768. + }
  41769. + break;
  41770. + }
  41771. + }
  41772. + }
  41773. + }
  41774. +
  41775. + /* The following loop ends with nEq set to the number of columns
  41776. + ** on the left of the index with == constraints.
  41777. + */
  41778. + for(nEq=0; nEq<pIdx->nColumn; nEq++){
  41779. + m = (1<<(nEq+1))-1;
  41780. + if( (m & eqMask)!=m ) break;
  41781. + }
  41782. + score = nEq*8; /* Base score is 8 times number of == constraints */
  41783. + m = 1<<nEq;
  41784. + if( m & ltMask ) score++; /* Increase score for a < constraint */
  41785. + if( m & gtMask ) score+=2; /* Increase score for a > constraint */
  41786. + if( score==0 && inMask ) score = 4; /* Default score for IN constraint */
  41787. + if( score>bestScore ){
  41788. + pBestIdx = pIdx;
  41789. + bestScore = score;
  41790. + }
  41791. + }
  41792. + pWInfo->a[i].pIdx = pBestIdx;
  41793. + pWInfo->a[i].score = bestScore;
  41794. + pWInfo->a[i].bRev = 0;
  41795. + loopMask |= mask;
  41796. + if( pBestIdx ){
  41797. + pWInfo->a[i].iCur = pParse->nTab++;
  41798. + pWInfo->peakNTab = pParse->nTab;
  41799. + }
  41800. + }
  41801. +
  41802. + /* Check to see if the ORDER BY clause is or can be satisfied by the
  41803. + ** use of an index on the first table.
  41804. + */
  41805. + if( ppOrderBy && *ppOrderBy && pTabList->nSrc>0 ){
  41806. + Index *pSortIdx;
  41807. + Index *pIdx;
  41808. + Table *pTab;
  41809. + int bRev = 0;
  41810. +
  41811. + pTab = pTabList->a[0].pTab;
  41812. + pIdx = pWInfo->a[0].pIdx;
  41813. + if( pIdx && pWInfo->a[0].score==4 ){
  41814. + /* If there is already an IN index on the left-most table,
  41815. + ** it will not give the correct sort order.
  41816. + ** So, pretend that no suitable index is found.
  41817. + */
  41818. + pSortIdx = 0;
  41819. + }else if( iDirectEq[0]>=0 || iDirectLt[0]>=0 || iDirectGt[0]>=0 ){
  41820. + /* If the left-most column is accessed using its ROWID, then do
  41821. + ** not try to sort by index.
  41822. + */
  41823. + pSortIdx = 0;
  41824. + }else{
  41825. + int nEqCol = (pWInfo->a[0].score+4)/8;
  41826. + pSortIdx = findSortingIndex(pTab, pTabList->a[0].iCursor,
  41827. + *ppOrderBy, pIdx, nEqCol, &bRev);
  41828. + }
  41829. + if( pSortIdx && (pIdx==0 || pIdx==pSortIdx) ){
  41830. + if( pIdx==0 ){
  41831. + pWInfo->a[0].pIdx = pSortIdx;
  41832. + pWInfo->a[0].iCur = pParse->nTab++;
  41833. + pWInfo->peakNTab = pParse->nTab;
  41834. + }
  41835. + pWInfo->a[0].bRev = bRev;
  41836. + *ppOrderBy = 0;
  41837. + }
  41838. + }
  41839. +
  41840. + /* Open all tables in the pTabList and all indices used by those tables.
  41841. + */
  41842. + for(i=0; i<pTabList->nSrc; i++){
  41843. + Table *pTab;
  41844. + Index *pIx;
  41845. +
  41846. + pTab = pTabList->a[i].pTab;
  41847. + if( pTab->isTransient || pTab->pSelect ) continue;
  41848. + sqliteVdbeAddOp(v, OP_Integer, pTab->iDb, 0);
  41849. + sqliteVdbeOp3(v, OP_OpenRead, pTabList->a[i].iCursor, pTab->tnum,
  41850. + pTab->zName, P3_STATIC);
  41851. + sqliteCodeVerifySchema(pParse, pTab->iDb);
  41852. + if( (pIx = pWInfo->a[i].pIdx)!=0 ){
  41853. + sqliteVdbeAddOp(v, OP_Integer, pIx->iDb, 0);
  41854. + sqliteVdbeOp3(v, OP_OpenRead, pWInfo->a[i].iCur, pIx->tnum, pIx->zName,0);
  41855. + }
  41856. + }
  41857. +
  41858. + /* Generate the code to do the search
  41859. + */
  41860. + loopMask = 0;
  41861. + for(i=0; i<pTabList->nSrc; i++){
  41862. + int j, k;
  41863. + int iCur = pTabList->a[i].iCursor;
  41864. + Index *pIdx;
  41865. + WhereLevel *pLevel = &pWInfo->a[i];
  41866. +
  41867. + /* If this is the right table of a LEFT OUTER JOIN, allocate and
  41868. + ** initialize a memory cell that records if this table matches any
  41869. + ** row of the left table of the join.
  41870. + */
  41871. + if( i>0 && (pTabList->a[i-1].jointype & JT_LEFT)!=0 ){
  41872. + if( !pParse->nMem ) pParse->nMem++;
  41873. + pLevel->iLeftJoin = pParse->nMem++;
  41874. + sqliteVdbeAddOp(v, OP_String, 0, 0);
  41875. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
  41876. + }
  41877. +
  41878. + pIdx = pLevel->pIdx;
  41879. + pLevel->inOp = OP_Noop;
  41880. + if( i<ARRAYSIZE(iDirectEq) && iDirectEq[i]>=0 ){
  41881. + /* Case 1: We can directly reference a single row using an
  41882. + ** equality comparison against the ROWID field. Or
  41883. + ** we reference multiple rows using a "rowid IN (...)"
  41884. + ** construct.
  41885. + */
  41886. + k = iDirectEq[i];
  41887. + assert( k<nExpr );
  41888. + assert( aExpr[k].p!=0 );
  41889. + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
  41890. + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
  41891. + if( aExpr[k].idxLeft==iCur ){
  41892. + Expr *pX = aExpr[k].p;
  41893. + if( pX->op!=TK_IN ){
  41894. + sqliteExprCode(pParse, aExpr[k].p->pRight);
  41895. + }else if( pX->pList ){
  41896. + sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
  41897. + pLevel->inOp = OP_SetNext;
  41898. + pLevel->inP1 = pX->iTable;
  41899. + pLevel->inP2 = sqliteVdbeCurrentAddr(v);
  41900. + }else{
  41901. + assert( pX->pSelect );
  41902. + sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
  41903. + sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
  41904. + pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
  41905. + pLevel->inOp = OP_Next;
  41906. + pLevel->inP1 = pX->iTable;
  41907. + }
  41908. + }else{
  41909. + sqliteExprCode(pParse, aExpr[k].p->pLeft);
  41910. + }
  41911. + disableTerm(pLevel, &aExpr[k].p);
  41912. + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
  41913. + sqliteVdbeAddOp(v, OP_MustBeInt, 1, brk);
  41914. + haveKey = 0;
  41915. + sqliteVdbeAddOp(v, OP_NotExists, iCur, brk);
  41916. + pLevel->op = OP_Noop;
  41917. + }else if( pIdx!=0 && pLevel->score>0 && pLevel->score%4==0 ){
  41918. + /* Case 2: There is an index and all terms of the WHERE clause that
  41919. + ** refer to the index use the "==" or "IN" operators.
  41920. + */
  41921. + int start;
  41922. + int testOp;
  41923. + int nColumn = (pLevel->score+4)/8;
  41924. + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
  41925. + for(j=0; j<nColumn; j++){
  41926. + for(k=0; k<nExpr; k++){
  41927. + Expr *pX = aExpr[k].p;
  41928. + if( pX==0 ) continue;
  41929. + if( aExpr[k].idxLeft==iCur
  41930. + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
  41931. + && pX->pLeft->iColumn==pIdx->aiColumn[j]
  41932. + ){
  41933. + if( pX->op==TK_EQ ){
  41934. + sqliteExprCode(pParse, pX->pRight);
  41935. + disableTerm(pLevel, &aExpr[k].p);
  41936. + break;
  41937. + }
  41938. + if( pX->op==TK_IN && nColumn==1 ){
  41939. + if( pX->pList ){
  41940. + sqliteVdbeAddOp(v, OP_SetFirst, pX->iTable, brk);
  41941. + pLevel->inOp = OP_SetNext;
  41942. + pLevel->inP1 = pX->iTable;
  41943. + pLevel->inP2 = sqliteVdbeCurrentAddr(v);
  41944. + }else{
  41945. + assert( pX->pSelect );
  41946. + sqliteVdbeAddOp(v, OP_Rewind, pX->iTable, brk);
  41947. + sqliteVdbeAddOp(v, OP_KeyAsData, pX->iTable, 1);
  41948. + pLevel->inP2 = sqliteVdbeAddOp(v, OP_FullKey, pX->iTable, 0);
  41949. + pLevel->inOp = OP_Next;
  41950. + pLevel->inP1 = pX->iTable;
  41951. + }
  41952. + disableTerm(pLevel, &aExpr[k].p);
  41953. + break;
  41954. + }
  41955. + }
  41956. + if( aExpr[k].idxRight==iCur
  41957. + && aExpr[k].p->op==TK_EQ
  41958. + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
  41959. + && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
  41960. + ){
  41961. + sqliteExprCode(pParse, aExpr[k].p->pLeft);
  41962. + disableTerm(pLevel, &aExpr[k].p);
  41963. + break;
  41964. + }
  41965. + }
  41966. + }
  41967. + pLevel->iMem = pParse->nMem++;
  41968. + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
  41969. + sqliteVdbeAddOp(v, OP_NotNull, -nColumn, sqliteVdbeCurrentAddr(v)+3);
  41970. + sqliteVdbeAddOp(v, OP_Pop, nColumn, 0);
  41971. + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
  41972. + sqliteVdbeAddOp(v, OP_MakeKey, nColumn, 0);
  41973. + sqliteAddIdxKeyType(v, pIdx);
  41974. + if( nColumn==pIdx->nColumn || pLevel->bRev ){
  41975. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 0);
  41976. + testOp = OP_IdxGT;
  41977. + }else{
  41978. + sqliteVdbeAddOp(v, OP_Dup, 0, 0);
  41979. + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
  41980. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  41981. + testOp = OP_IdxGE;
  41982. + }
  41983. + if( pLevel->bRev ){
  41984. + /* Scan in reverse order */
  41985. + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
  41986. + sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
  41987. + start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  41988. + sqliteVdbeAddOp(v, OP_IdxLT, pLevel->iCur, brk);
  41989. + pLevel->op = OP_Prev;
  41990. + }else{
  41991. + /* Scan in the forward order */
  41992. + sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
  41993. + start = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  41994. + sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
  41995. + pLevel->op = OP_Next;
  41996. + }
  41997. + sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
  41998. + sqliteVdbeAddOp(v, OP_IdxIsNull, nColumn, cont);
  41999. + sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
  42000. + if( i==pTabList->nSrc-1 && pushKey ){
  42001. + haveKey = 1;
  42002. + }else{
  42003. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  42004. + haveKey = 0;
  42005. + }
  42006. + pLevel->p1 = pLevel->iCur;
  42007. + pLevel->p2 = start;
  42008. + }else if( i<ARRAYSIZE(iDirectLt) && (iDirectLt[i]>=0 || iDirectGt[i]>=0) ){
  42009. + /* Case 3: We have an inequality comparison against the ROWID field.
  42010. + */
  42011. + int testOp = OP_Noop;
  42012. + int start;
  42013. +
  42014. + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
  42015. + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
  42016. + if( iDirectGt[i]>=0 ){
  42017. + k = iDirectGt[i];
  42018. + assert( k<nExpr );
  42019. + assert( aExpr[k].p!=0 );
  42020. + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
  42021. + if( aExpr[k].idxLeft==iCur ){
  42022. + sqliteExprCode(pParse, aExpr[k].p->pRight);
  42023. + }else{
  42024. + sqliteExprCode(pParse, aExpr[k].p->pLeft);
  42025. + }
  42026. + sqliteVdbeAddOp(v, OP_ForceInt,
  42027. + aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT, brk);
  42028. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, brk);
  42029. + disableTerm(pLevel, &aExpr[k].p);
  42030. + }else{
  42031. + sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
  42032. + }
  42033. + if( iDirectLt[i]>=0 ){
  42034. + k = iDirectLt[i];
  42035. + assert( k<nExpr );
  42036. + assert( aExpr[k].p!=0 );
  42037. + assert( aExpr[k].idxLeft==iCur || aExpr[k].idxRight==iCur );
  42038. + if( aExpr[k].idxLeft==iCur ){
  42039. + sqliteExprCode(pParse, aExpr[k].p->pRight);
  42040. + }else{
  42041. + sqliteExprCode(pParse, aExpr[k].p->pLeft);
  42042. + }
  42043. + /* sqliteVdbeAddOp(v, OP_MustBeInt, 0, sqliteVdbeCurrentAddr(v)+1); */
  42044. + pLevel->iMem = pParse->nMem++;
  42045. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  42046. + if( aExpr[k].p->op==TK_LT || aExpr[k].p->op==TK_GT ){
  42047. + testOp = OP_Ge;
  42048. + }else{
  42049. + testOp = OP_Gt;
  42050. + }
  42051. + disableTerm(pLevel, &aExpr[k].p);
  42052. + }
  42053. + start = sqliteVdbeCurrentAddr(v);
  42054. + pLevel->op = OP_Next;
  42055. + pLevel->p1 = iCur;
  42056. + pLevel->p2 = start;
  42057. + if( testOp!=OP_Noop ){
  42058. + sqliteVdbeAddOp(v, OP_Recno, iCur, 0);
  42059. + sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  42060. + sqliteVdbeAddOp(v, testOp, 0, brk);
  42061. + }
  42062. + haveKey = 0;
  42063. + }else if( pIdx==0 ){
  42064. + /* Case 4: There is no usable index. We must do a complete
  42065. + ** scan of the entire database table.
  42066. + */
  42067. + int start;
  42068. +
  42069. + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
  42070. + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
  42071. + sqliteVdbeAddOp(v, OP_Rewind, iCur, brk);
  42072. + start = sqliteVdbeCurrentAddr(v);
  42073. + pLevel->op = OP_Next;
  42074. + pLevel->p1 = iCur;
  42075. + pLevel->p2 = start;
  42076. + haveKey = 0;
  42077. + }else{
  42078. + /* Case 5: The WHERE clause term that refers to the right-most
  42079. + ** column of the index is an inequality. For example, if
  42080. + ** the index is on (x,y,z) and the WHERE clause is of the
  42081. + ** form "x=5 AND y<10" then this case is used. Only the
  42082. + ** right-most column can be an inequality - the rest must
  42083. + ** use the "==" operator.
  42084. + **
  42085. + ** This case is also used when there are no WHERE clause
  42086. + ** constraints but an index is selected anyway, in order
  42087. + ** to force the output order to conform to an ORDER BY.
  42088. + */
  42089. + int score = pLevel->score;
  42090. + int nEqColumn = score/8;
  42091. + int start;
  42092. + int leFlag, geFlag;
  42093. + int testOp;
  42094. +
  42095. + /* Evaluate the equality constraints
  42096. + */
  42097. + for(j=0; j<nEqColumn; j++){
  42098. + for(k=0; k<nExpr; k++){
  42099. + if( aExpr[k].p==0 ) continue;
  42100. + if( aExpr[k].idxLeft==iCur
  42101. + && aExpr[k].p->op==TK_EQ
  42102. + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
  42103. + && aExpr[k].p->pLeft->iColumn==pIdx->aiColumn[j]
  42104. + ){
  42105. + sqliteExprCode(pParse, aExpr[k].p->pRight);
  42106. + disableTerm(pLevel, &aExpr[k].p);
  42107. + break;
  42108. + }
  42109. + if( aExpr[k].idxRight==iCur
  42110. + && aExpr[k].p->op==TK_EQ
  42111. + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
  42112. + && aExpr[k].p->pRight->iColumn==pIdx->aiColumn[j]
  42113. + ){
  42114. + sqliteExprCode(pParse, aExpr[k].p->pLeft);
  42115. + disableTerm(pLevel, &aExpr[k].p);
  42116. + break;
  42117. + }
  42118. + }
  42119. + }
  42120. +
  42121. + /* Duplicate the equality term values because they will all be
  42122. + ** used twice: once to make the termination key and once to make the
  42123. + ** start key.
  42124. + */
  42125. + for(j=0; j<nEqColumn; j++){
  42126. + sqliteVdbeAddOp(v, OP_Dup, nEqColumn-1, 0);
  42127. + }
  42128. +
  42129. + /* Labels for the beginning and end of the loop
  42130. + */
  42131. + cont = pLevel->cont = sqliteVdbeMakeLabel(v);
  42132. + brk = pLevel->brk = sqliteVdbeMakeLabel(v);
  42133. +
  42134. + /* Generate the termination key. This is the key value that
  42135. + ** will end the search. There is no termination key if there
  42136. + ** are no equality terms and no "X<..." term.
  42137. + **
  42138. + ** 2002-Dec-04: On a reverse-order scan, the so-called "termination"
  42139. + ** key computed here really ends up being the start key.
  42140. + */
  42141. + if( (score & 1)!=0 ){
  42142. + for(k=0; k<nExpr; k++){
  42143. + Expr *pExpr = aExpr[k].p;
  42144. + if( pExpr==0 ) continue;
  42145. + if( aExpr[k].idxLeft==iCur
  42146. + && (pExpr->op==TK_LT || pExpr->op==TK_LE)
  42147. + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
  42148. + && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
  42149. + ){
  42150. + sqliteExprCode(pParse, pExpr->pRight);
  42151. + leFlag = pExpr->op==TK_LE;
  42152. + disableTerm(pLevel, &aExpr[k].p);
  42153. + break;
  42154. + }
  42155. + if( aExpr[k].idxRight==iCur
  42156. + && (pExpr->op==TK_GT || pExpr->op==TK_GE)
  42157. + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
  42158. + && pExpr->pRight->iColumn==pIdx->aiColumn[j]
  42159. + ){
  42160. + sqliteExprCode(pParse, pExpr->pLeft);
  42161. + leFlag = pExpr->op==TK_GE;
  42162. + disableTerm(pLevel, &aExpr[k].p);
  42163. + break;
  42164. + }
  42165. + }
  42166. + testOp = OP_IdxGE;
  42167. + }else{
  42168. + testOp = nEqColumn>0 ? OP_IdxGE : OP_Noop;
  42169. + leFlag = 1;
  42170. + }
  42171. + if( testOp!=OP_Noop ){
  42172. + int nCol = nEqColumn + (score & 1);
  42173. + pLevel->iMem = pParse->nMem++;
  42174. + sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
  42175. + sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
  42176. + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
  42177. + sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
  42178. + sqliteAddIdxKeyType(v, pIdx);
  42179. + if( leFlag ){
  42180. + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
  42181. + }
  42182. + if( pLevel->bRev ){
  42183. + sqliteVdbeAddOp(v, OP_MoveLt, pLevel->iCur, brk);
  42184. + }else{
  42185. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  42186. + }
  42187. + }else if( pLevel->bRev ){
  42188. + sqliteVdbeAddOp(v, OP_Last, pLevel->iCur, brk);
  42189. + }
  42190. +
  42191. + /* Generate the start key. This is the key that defines the lower
  42192. + ** bound on the search. There is no start key if there are no
  42193. + ** equality terms and if there is no "X>..." term. In
  42194. + ** that case, generate a "Rewind" instruction in place of the
  42195. + ** start key search.
  42196. + **
  42197. + ** 2002-Dec-04: In the case of a reverse-order search, the so-called
  42198. + ** "start" key really ends up being used as the termination key.
  42199. + */
  42200. + if( (score & 2)!=0 ){
  42201. + for(k=0; k<nExpr; k++){
  42202. + Expr *pExpr = aExpr[k].p;
  42203. + if( pExpr==0 ) continue;
  42204. + if( aExpr[k].idxLeft==iCur
  42205. + && (pExpr->op==TK_GT || pExpr->op==TK_GE)
  42206. + && (aExpr[k].prereqRight & loopMask)==aExpr[k].prereqRight
  42207. + && pExpr->pLeft->iColumn==pIdx->aiColumn[j]
  42208. + ){
  42209. + sqliteExprCode(pParse, pExpr->pRight);
  42210. + geFlag = pExpr->op==TK_GE;
  42211. + disableTerm(pLevel, &aExpr[k].p);
  42212. + break;
  42213. + }
  42214. + if( aExpr[k].idxRight==iCur
  42215. + && (pExpr->op==TK_LT || pExpr->op==TK_LE)
  42216. + && (aExpr[k].prereqLeft & loopMask)==aExpr[k].prereqLeft
  42217. + && pExpr->pRight->iColumn==pIdx->aiColumn[j]
  42218. + ){
  42219. + sqliteExprCode(pParse, pExpr->pLeft);
  42220. + geFlag = pExpr->op==TK_LE;
  42221. + disableTerm(pLevel, &aExpr[k].p);
  42222. + break;
  42223. + }
  42224. + }
  42225. + }else{
  42226. + geFlag = 1;
  42227. + }
  42228. + if( nEqColumn>0 || (score&2)!=0 ){
  42229. + int nCol = nEqColumn + ((score&2)!=0);
  42230. + sqliteVdbeAddOp(v, OP_NotNull, -nCol, sqliteVdbeCurrentAddr(v)+3);
  42231. + sqliteVdbeAddOp(v, OP_Pop, nCol, 0);
  42232. + sqliteVdbeAddOp(v, OP_Goto, 0, brk);
  42233. + sqliteVdbeAddOp(v, OP_MakeKey, nCol, 0);
  42234. + sqliteAddIdxKeyType(v, pIdx);
  42235. + if( !geFlag ){
  42236. + sqliteVdbeAddOp(v, OP_IncrKey, 0, 0);
  42237. + }
  42238. + if( pLevel->bRev ){
  42239. + pLevel->iMem = pParse->nMem++;
  42240. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iMem, 1);
  42241. + testOp = OP_IdxLT;
  42242. + }else{
  42243. + sqliteVdbeAddOp(v, OP_MoveTo, pLevel->iCur, brk);
  42244. + }
  42245. + }else if( pLevel->bRev ){
  42246. + testOp = OP_Noop;
  42247. + }else{
  42248. + sqliteVdbeAddOp(v, OP_Rewind, pLevel->iCur, brk);
  42249. + }
  42250. +
  42251. + /* Generate the the top of the loop. If there is a termination
  42252. + ** key we have to test for that key and abort at the top of the
  42253. + ** loop.
  42254. + */
  42255. + start = sqliteVdbeCurrentAddr(v);
  42256. + if( testOp!=OP_Noop ){
  42257. + sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iMem, 0);
  42258. + sqliteVdbeAddOp(v, testOp, pLevel->iCur, brk);
  42259. + }
  42260. + sqliteVdbeAddOp(v, OP_RowKey, pLevel->iCur, 0);
  42261. + sqliteVdbeAddOp(v, OP_IdxIsNull, nEqColumn + (score & 1), cont);
  42262. + sqliteVdbeAddOp(v, OP_IdxRecno, pLevel->iCur, 0);
  42263. + if( i==pTabList->nSrc-1 && pushKey ){
  42264. + haveKey = 1;
  42265. + }else{
  42266. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  42267. + haveKey = 0;
  42268. + }
  42269. +
  42270. + /* Record the instruction used to terminate the loop.
  42271. + */
  42272. + pLevel->op = pLevel->bRev ? OP_Prev : OP_Next;
  42273. + pLevel->p1 = pLevel->iCur;
  42274. + pLevel->p2 = start;
  42275. + }
  42276. + loopMask |= getMask(&maskSet, iCur);
  42277. +
  42278. + /* Insert code to test every subexpression that can be completely
  42279. + ** computed using the current set of tables.
  42280. + */
  42281. + for(j=0; j<nExpr; j++){
  42282. + if( aExpr[j].p==0 ) continue;
  42283. + if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
  42284. + if( pLevel->iLeftJoin && !ExprHasProperty(aExpr[j].p,EP_FromJoin) ){
  42285. + continue;
  42286. + }
  42287. + if( haveKey ){
  42288. + haveKey = 0;
  42289. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  42290. + }
  42291. + sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
  42292. + aExpr[j].p = 0;
  42293. + }
  42294. + brk = cont;
  42295. +
  42296. + /* For a LEFT OUTER JOIN, generate code that will record the fact that
  42297. + ** at least one row of the right table has matched the left table.
  42298. + */
  42299. + if( pLevel->iLeftJoin ){
  42300. + pLevel->top = sqliteVdbeCurrentAddr(v);
  42301. + sqliteVdbeAddOp(v, OP_Integer, 1, 0);
  42302. + sqliteVdbeAddOp(v, OP_MemStore, pLevel->iLeftJoin, 1);
  42303. + for(j=0; j<nExpr; j++){
  42304. + if( aExpr[j].p==0 ) continue;
  42305. + if( (aExpr[j].prereqAll & loopMask)!=aExpr[j].prereqAll ) continue;
  42306. + if( haveKey ){
  42307. + /* Cannot happen. "haveKey" can only be true if pushKey is true
  42308. + ** an pushKey can only be true for DELETE and UPDATE and there are
  42309. + ** no outer joins with DELETE and UPDATE.
  42310. + */
  42311. + haveKey = 0;
  42312. + sqliteVdbeAddOp(v, OP_MoveTo, iCur, 0);
  42313. + }
  42314. + sqliteExprIfFalse(pParse, aExpr[j].p, cont, 1);
  42315. + aExpr[j].p = 0;
  42316. + }
  42317. + }
  42318. + }
  42319. + pWInfo->iContinue = cont;
  42320. + if( pushKey && !haveKey ){
  42321. + sqliteVdbeAddOp(v, OP_Recno, pTabList->a[0].iCursor, 0);
  42322. + }
  42323. + freeMaskSet(&maskSet);
  42324. + return pWInfo;
  42325. +}
  42326. +
  42327. +/*
  42328. +** Generate the end of the WHERE loop. See comments on
  42329. +** sqliteWhereBegin() for additional information.
  42330. +*/
  42331. +void sqliteWhereEnd(WhereInfo *pWInfo){
  42332. + Vdbe *v = pWInfo->pParse->pVdbe;
  42333. + int i;
  42334. + WhereLevel *pLevel;
  42335. + SrcList *pTabList = pWInfo->pTabList;
  42336. +
  42337. + for(i=pTabList->nSrc-1; i>=0; i--){
  42338. + pLevel = &pWInfo->a[i];
  42339. + sqliteVdbeResolveLabel(v, pLevel->cont);
  42340. + if( pLevel->op!=OP_Noop ){
  42341. + sqliteVdbeAddOp(v, pLevel->op, pLevel->p1, pLevel->p2);
  42342. + }
  42343. + sqliteVdbeResolveLabel(v, pLevel->brk);
  42344. + if( pLevel->inOp!=OP_Noop ){
  42345. + sqliteVdbeAddOp(v, pLevel->inOp, pLevel->inP1, pLevel->inP2);
  42346. + }
  42347. + if( pLevel->iLeftJoin ){
  42348. + int addr;
  42349. + addr = sqliteVdbeAddOp(v, OP_MemLoad, pLevel->iLeftJoin, 0);
  42350. + sqliteVdbeAddOp(v, OP_NotNull, 1, addr+4 + (pLevel->iCur>=0));
  42351. + sqliteVdbeAddOp(v, OP_NullRow, pTabList->a[i].iCursor, 0);
  42352. + if( pLevel->iCur>=0 ){
  42353. + sqliteVdbeAddOp(v, OP_NullRow, pLevel->iCur, 0);
  42354. + }
  42355. + sqliteVdbeAddOp(v, OP_Goto, 0, pLevel->top);
  42356. + }
  42357. + }
  42358. + sqliteVdbeResolveLabel(v, pWInfo->iBreak);
  42359. + for(i=0; i<pTabList->nSrc; i++){
  42360. + Table *pTab = pTabList->a[i].pTab;
  42361. + assert( pTab!=0 );
  42362. + if( pTab->isTransient || pTab->pSelect ) continue;
  42363. + pLevel = &pWInfo->a[i];
  42364. + sqliteVdbeAddOp(v, OP_Close, pTabList->a[i].iCursor, 0);
  42365. + if( pLevel->pIdx!=0 ){
  42366. + sqliteVdbeAddOp(v, OP_Close, pLevel->iCur, 0);
  42367. + }
  42368. + }
  42369. +#if 0 /* Never reuse a cursor */
  42370. + if( pWInfo->pParse->nTab==pWInfo->peakNTab ){
  42371. + pWInfo->pParse->nTab = pWInfo->savedNTab;
  42372. + }
  42373. +#endif
  42374. + sqliteFree(pWInfo);
  42375. + return;
  42376. +}
  42377. --- /dev/null
  42378. +++ b/ext/sqlite/libsqlite/VERSION
  42379. @@ -0,0 +1 @@
  42380. +2.8.17
  42381. --- /dev/null
  42382. +++ b/ext/sqlite/Makefile.frag
  42383. @@ -0,0 +1,2 @@
  42384. +$(srcdir)/libsqlite/src/parse.c: $(srcdir)/libsqlite/src/parse.y
  42385. + @$(LEMON) $(srcdir)/libsqlite/src/parse.y
  42386. --- /dev/null
  42387. +++ b/ext/sqlite/package.xml
  42388. @@ -0,0 +1,136 @@
  42389. +<?xml version="1.0" encoding="ISO-8859-1" ?>
  42390. +<!DOCTYPE package SYSTEM "../pear/package.dtd">
  42391. +<package>
  42392. + <name>SQLite</name>
  42393. + <summary>SQLite database bindings</summary>
  42394. + <maintainers>
  42395. + <maintainer>
  42396. + <user>wez</user>
  42397. + <name>Wez Furlong</name>
  42398. + <email>wez@php.net</email>
  42399. + <role>lead</role>
  42400. + </maintainer>
  42401. + <maintainer>
  42402. + <user>tal</user>
  42403. + <name>Tal Peer</name>
  42404. + <email>tal@php.net</email>
  42405. + <role>developer</role>
  42406. + </maintainer>
  42407. + <maintainer>
  42408. + <user>helly</user>
  42409. + <name>Marcus Börger</name>
  42410. + <email>helly@php.net</email>
  42411. + <role>lead</role>
  42412. + </maintainer>
  42413. + <maintainer>
  42414. + <user>iliaa</user>
  42415. + <name>Ilia Alshanetsky</name>
  42416. + <email>ilia@php.net</email>
  42417. + <role>developer</role>
  42418. + </maintainer>
  42419. + </maintainers>
  42420. + <description>
  42421. +SQLite is a C library that implements an embeddable SQL database engine.
  42422. +Programs that link with the SQLite library can have SQL database access
  42423. +without running a separate RDBMS process.
  42424. +This extension allows you to access SQLite databases from within PHP.
  42425. +
  42426. +Windows binary available from:
  42427. +http://snaps.php.net/win32/PECL_STABLE/php_sqlite.dll
  42428. + </description>
  42429. + <license>PHP</license>
  42430. + <release>
  42431. + <state>stable</state>
  42432. + <version>2.0-dev</version>
  42433. + <date>TBA</date>
  42434. + <notes>
  42435. + Added:
  42436. + OO API (Marcus).
  42437. + </notes>
  42438. + <filelist>
  42439. + <file role="src" name="config.m4"/>
  42440. + <file role="src" name="config.w32"/>
  42441. + <file role="src" name="sqlite.c"/>
  42442. + <file role="src" name="sqlite.dsp"/>
  42443. + <file role="src" name="php_sqlite.h"/>
  42444. + <file role="src" name="php_sqlite.def"/>
  42445. + <file role="doc" name="CREDITS"/>
  42446. + <file role="doc" name="README"/>
  42447. + <file role="doc" name="TODO"/>
  42448. + <file role="doc" name="sqlite.php"/>
  42449. + <file role="test" name="tests/sqlite_001.phpt"/>
  42450. + <file role="test" name="tests/sqlite_002.phpt"/>
  42451. + <file role="test" name="tests/sqlite_003.phpt"/>
  42452. + <file role="test" name="tests/sqlite_004.phpt"/>
  42453. + <file role="test" name="tests/sqlite_005.phpt"/>
  42454. + <file role="test" name="tests/sqlite_006.phpt"/>
  42455. + <file role="test" name="tests/sqlite_007.phpt"/>
  42456. + <file role="test" name="tests/sqlite_008.phpt"/>
  42457. + <file role="test" name="tests/sqlite_009.phpt"/>
  42458. + <file role="test" name="tests/sqlite_010.phpt"/>
  42459. + <file role="test" name="tests/sqlite_011.phpt"/>
  42460. + <file role="test" name="tests/sqlite_012.phpt"/>
  42461. + <file role="test" name="tests/sqlite_013.phpt"/>
  42462. + <file role="test" name="tests/sqlite_014.phpt"/>
  42463. + <file role="test" name="tests/sqlite_015.phpt"/>
  42464. + <file role="test" name="tests/sqlite_016.phpt"/>
  42465. + <file role="test" name="tests/sqlite_017.phpt"/>
  42466. + <file role="test" name="tests/blankdb.inc"/>
  42467. +
  42468. + <dir name="libsqlite">
  42469. + <file role="doc" name="README"/>
  42470. + <file role="src" name="VERSION"/>
  42471. +
  42472. + <dir name="src">
  42473. + <file role="src" name="attach.c"/>
  42474. + <file role="src" name="auth.c"/>
  42475. + <file role="src" name="btree.c"/>
  42476. + <file role="src" name="btree_rb.c"/>
  42477. + <file role="src" name="build.c"/>
  42478. + <file role="src" name="copy.c"/>
  42479. + <file role="src" name="delete.c"/>
  42480. + <file role="src" name="encode.c"/>
  42481. + <file role="src" name="expr.c"/>
  42482. + <file role="src" name="func.c"/>
  42483. + <file role="src" name="hash.c"/>
  42484. + <file role="src" name="insert.c"/>
  42485. + <file role="src" name="main.c"/>
  42486. + <file role="src" name="opcodes.c"/>
  42487. + <file role="src" name="os.c"/>
  42488. + <file role="src" name="pager.c"/>
  42489. + <file role="src" name="parse.c"/>
  42490. + <file role="src" name="parse.y"/>
  42491. + <file role="src" name="pragma.c"/>
  42492. + <file role="src" name="printf.c"/>
  42493. + <file role="src" name="random.c"/>
  42494. + <file role="src" name="select.c"/>
  42495. + <file role="src" name="table.c"/>
  42496. + <file role="src" name="tokenize.c"/>
  42497. + <file role="src" name="trigger.c"/>
  42498. + <file role="src" name="update.c"/>
  42499. + <file role="src" name="util.c"/>
  42500. + <file role="src" name="vacuum.c"/>
  42501. + <file role="src" name="vdbe.c"/>
  42502. + <file role="src" name="where.c"/>
  42503. + <file role="src" name="btree.h"/>
  42504. + <file role="src" name="hash.h"/>
  42505. + <file role="src" name="opcodes.h"/>
  42506. + <file role="src" name="os.h"/>
  42507. + <file role="src" name="pager.h"/>
  42508. + <file role="src" name="parse.h"/>
  42509. + <file role="src" name="sqlite_config.w32.h"/>
  42510. + <file role="src" name="sqlite.h.in"/>
  42511. + <file role="src" name="sqliteInt.h"/>
  42512. + <file role="src" name="sqlite.w32.h"/>
  42513. + <file role="src" name="vdbe.h"/>
  42514. + </dir>
  42515. + </dir>
  42516. + </filelist>
  42517. + <deps>
  42518. + <dep type="php" rel="ge" version="5" />
  42519. + </deps>
  42520. + </release>
  42521. +</package>
  42522. +<!--
  42523. +vim:et:ts=1:sw=1
  42524. +-->
  42525. --- /dev/null
  42526. +++ b/ext/sqlite/pdo_sqlite2.c
  42527. @@ -0,0 +1,638 @@
  42528. +/*
  42529. + +----------------------------------------------------------------------+
  42530. + | PHP Version 5 |
  42531. + +----------------------------------------------------------------------+
  42532. + | Copyright (c) 1997-2012 The PHP Group |
  42533. + +----------------------------------------------------------------------+
  42534. + | This source file is subject to version 3.01 of the PHP license, |
  42535. + | that is bundled with this package in the file LICENSE, and is |
  42536. + | available through the world-wide-web at the following url: |
  42537. + | http://www.php.net/license/3_01.txt |
  42538. + | If you did not receive a copy of the PHP license and are unable to |
  42539. + | obtain it through the world-wide-web, please send a note to |
  42540. + | license@php.net so we can mail you a copy immediately. |
  42541. + +----------------------------------------------------------------------+
  42542. + | Author: Wez Furlong <wez@php.net> |
  42543. + +----------------------------------------------------------------------+
  42544. +*/
  42545. +
  42546. +/* $Id$ */
  42547. +#ifdef HAVE_CONFIG_H
  42548. +#include "config.h"
  42549. +#endif
  42550. +#include "php.h"
  42551. +
  42552. +#ifdef PHP_SQLITE2_HAVE_PDO
  42553. +#include "sqlite.h"
  42554. +#include "pdo/php_pdo.h"
  42555. +#include "pdo/php_pdo_driver.h"
  42556. +#include "zend_exceptions.h"
  42557. +
  42558. +#define php_sqlite_encode_binary(in, n, out) sqlite_encode_binary((const unsigned char *)in, n, (unsigned char *)out)
  42559. +#define php_sqlite_decode_binary(in, out) sqlite_decode_binary((const unsigned char *)in, (unsigned char *)out)
  42560. +
  42561. +
  42562. +typedef struct {
  42563. + const char *file;
  42564. + int line;
  42565. + unsigned int errcode;
  42566. + char *errmsg;
  42567. +} pdo_sqlite2_error_info;
  42568. +
  42569. +typedef struct {
  42570. + sqlite *db;
  42571. + pdo_sqlite2_error_info einfo;
  42572. +} pdo_sqlite2_db_handle;
  42573. +
  42574. +typedef struct {
  42575. + pdo_sqlite2_db_handle *H;
  42576. + sqlite_vm *vm;
  42577. + const char **rowdata, **colnames;
  42578. + int ncols;
  42579. + unsigned pre_fetched:1;
  42580. + unsigned done:1;
  42581. + pdo_sqlite2_error_info einfo;
  42582. +} pdo_sqlite2_stmt;
  42583. +
  42584. +extern int _pdo_sqlite2_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, char *errmsg, const char *file, int line TSRMLS_DC);
  42585. +#define pdo_sqlite2_error(msg, s) _pdo_sqlite2_error(s, NULL, msg, __FILE__, __LINE__ TSRMLS_CC)
  42586. +#define pdo_sqlite2_error_stmt(msg, s) _pdo_sqlite2_error(stmt->dbh, stmt, msg, __FILE__, __LINE__ TSRMLS_CC)
  42587. +
  42588. +extern struct pdo_stmt_methods sqlite2_stmt_methods;
  42589. +
  42590. +static int pdo_sqlite2_stmt_dtor(pdo_stmt_t *stmt TSRMLS_DC)
  42591. +{
  42592. + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
  42593. +
  42594. + if (S->vm) {
  42595. + char *errmsg = NULL;
  42596. + sqlite_finalize(S->vm, &errmsg);
  42597. + if (errmsg) {
  42598. + sqlite_freemem(errmsg);
  42599. + }
  42600. + S->vm = NULL;
  42601. + }
  42602. + if (S->einfo.errmsg) {
  42603. + pefree(S->einfo.errmsg, stmt->dbh->is_persistent);
  42604. + }
  42605. + efree(S);
  42606. + return 1;
  42607. +}
  42608. +
  42609. +static int pdo_sqlite2_stmt_execute(pdo_stmt_t *stmt TSRMLS_DC)
  42610. +{
  42611. + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
  42612. + char *errmsg = NULL;
  42613. + const char *tail;
  42614. +
  42615. + if (stmt->executed && !S->done) {
  42616. + sqlite_finalize(S->vm, &errmsg);
  42617. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42618. + errmsg = NULL;
  42619. + S->vm = NULL;
  42620. + }
  42621. +
  42622. + S->einfo.errcode = sqlite_compile(S->H->db, stmt->active_query_string, &tail, &S->vm, &errmsg);
  42623. + if (S->einfo.errcode != SQLITE_OK) {
  42624. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42625. + return 0;
  42626. + }
  42627. +
  42628. + S->done = 0;
  42629. + S->einfo.errcode = sqlite_step(S->vm, &S->ncols, &S->rowdata, &S->colnames);
  42630. + switch (S->einfo.errcode) {
  42631. + case SQLITE_ROW:
  42632. + S->pre_fetched = 1;
  42633. + stmt->column_count = S->ncols;
  42634. + return 1;
  42635. +
  42636. + case SQLITE_DONE:
  42637. + stmt->column_count = S->ncols;
  42638. + stmt->row_count = sqlite_changes(S->H->db);
  42639. + S->einfo.errcode = sqlite_reset(S->vm, &errmsg);
  42640. + if (S->einfo.errcode != SQLITE_OK) {
  42641. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42642. + }
  42643. + S->done = 1;
  42644. + return 1;
  42645. +
  42646. + case SQLITE_ERROR:
  42647. + case SQLITE_MISUSE:
  42648. + case SQLITE_BUSY:
  42649. + default:
  42650. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42651. + return 0;
  42652. + }
  42653. +}
  42654. +
  42655. +static int pdo_sqlite2_stmt_param_hook(pdo_stmt_t *stmt, struct pdo_bound_param_data *param,
  42656. + enum pdo_param_event event_type TSRMLS_DC)
  42657. +{
  42658. + return 1;
  42659. +}
  42660. +
  42661. +static int pdo_sqlite2_stmt_fetch(pdo_stmt_t *stmt,
  42662. + enum pdo_fetch_orientation ori, long offset TSRMLS_DC)
  42663. +{
  42664. + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
  42665. + char *errmsg = NULL;
  42666. +
  42667. + if (!S->vm) {
  42668. + return 0;
  42669. + }
  42670. + if (S->pre_fetched) {
  42671. + S->pre_fetched = 0;
  42672. + return 1;
  42673. + }
  42674. + if (S->done) {
  42675. + return 0;
  42676. + }
  42677. +
  42678. + S->einfo.errcode = sqlite_step(S->vm, &S->ncols, &S->rowdata, &S->colnames);
  42679. + switch (S->einfo.errcode) {
  42680. + case SQLITE_ROW:
  42681. + return 1;
  42682. +
  42683. + case SQLITE_DONE:
  42684. + S->done = 1;
  42685. + S->einfo.errcode = sqlite_reset(S->vm, &errmsg);
  42686. + if (S->einfo.errcode != SQLITE_OK) {
  42687. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42688. + errmsg = NULL;
  42689. + }
  42690. + return 0;
  42691. +
  42692. + default:
  42693. + pdo_sqlite2_error_stmt(errmsg, stmt);
  42694. + return 0;
  42695. + }
  42696. +}
  42697. +
  42698. +static int pdo_sqlite2_stmt_describe(pdo_stmt_t *stmt, int colno TSRMLS_DC)
  42699. +{
  42700. + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
  42701. +
  42702. + if(colno >= S->ncols) {
  42703. + /* error invalid column */
  42704. + pdo_sqlite2_error_stmt(NULL, stmt);
  42705. + return 0;
  42706. + }
  42707. +
  42708. + stmt->columns[colno].name = estrdup(S->colnames[colno]);
  42709. + stmt->columns[colno].namelen = strlen(stmt->columns[colno].name);
  42710. + stmt->columns[colno].maxlen = 0xffffffff;
  42711. + stmt->columns[colno].precision = 0;
  42712. + stmt->columns[colno].param_type = PDO_PARAM_STR;
  42713. +
  42714. + return 1;
  42715. +}
  42716. +
  42717. +static int pdo_sqlite2_stmt_get_col(pdo_stmt_t *stmt, int colno, char **ptr, unsigned long *len, int *caller_frees TSRMLS_DC)
  42718. +{
  42719. + pdo_sqlite2_stmt *S = (pdo_sqlite2_stmt*)stmt->driver_data;
  42720. + if (!S->vm) {
  42721. + return 0;
  42722. + }
  42723. + if(colno >= S->ncols) {
  42724. + /* error invalid column */
  42725. + pdo_sqlite2_error_stmt(NULL, stmt);
  42726. + return 0;
  42727. + }
  42728. + if (S->rowdata[colno]) {
  42729. + if (S->rowdata[colno][0] == '\x01') {
  42730. + /* encoded */
  42731. + *caller_frees = 1;
  42732. + *ptr = emalloc(strlen(S->rowdata[colno]));
  42733. + *len = php_sqlite_decode_binary(S->rowdata[colno]+1, *ptr);
  42734. + (*(char**)ptr)[*len] = '\0';
  42735. + } else {
  42736. + *ptr = (char*)S->rowdata[colno];
  42737. + *len = strlen(*ptr);
  42738. + }
  42739. + } else {
  42740. + *ptr = NULL;
  42741. + *len = 0;
  42742. + }
  42743. + return 1;
  42744. +}
  42745. +
  42746. +struct pdo_stmt_methods sqlite2_stmt_methods = {
  42747. + pdo_sqlite2_stmt_dtor,
  42748. + pdo_sqlite2_stmt_execute,
  42749. + pdo_sqlite2_stmt_fetch,
  42750. + pdo_sqlite2_stmt_describe,
  42751. + pdo_sqlite2_stmt_get_col,
  42752. + pdo_sqlite2_stmt_param_hook,
  42753. + NULL, /* set_attr */
  42754. + NULL, /* get_attr */
  42755. + NULL
  42756. +};
  42757. +
  42758. +
  42759. +int _pdo_sqlite2_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, char *errmsg, const char *file, int line TSRMLS_DC) /* {{{ */
  42760. +{
  42761. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42762. + pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code;
  42763. + pdo_sqlite2_error_info *einfo = &H->einfo;
  42764. + pdo_sqlite2_stmt *S;
  42765. +
  42766. + if (stmt) {
  42767. + S = stmt->driver_data;
  42768. + einfo = &S->einfo;
  42769. + }
  42770. +
  42771. + einfo->file = file;
  42772. + einfo->line = line;
  42773. +
  42774. + if (einfo->errmsg) {
  42775. + pefree(einfo->errmsg, dbh->is_persistent);
  42776. + einfo->errmsg = NULL;
  42777. + }
  42778. +
  42779. + if (einfo->errcode != SQLITE_OK) {
  42780. + if (errmsg) {
  42781. + einfo->errmsg = pestrdup(errmsg, dbh->is_persistent);
  42782. + sqlite_freemem(errmsg);
  42783. + } else {
  42784. + einfo->errmsg = pestrdup(sqlite_error_string(einfo->errcode), dbh->is_persistent);
  42785. + }
  42786. + } else { /* no error */
  42787. + strcpy(*pdo_err, PDO_ERR_NONE);
  42788. + return 0;
  42789. + }
  42790. + switch (einfo->errcode) {
  42791. + case SQLITE_NOTFOUND:
  42792. + strcpy(*pdo_err, "42S02");
  42793. + break;
  42794. +
  42795. + case SQLITE_INTERRUPT:
  42796. + strcpy(*pdo_err, "01002");
  42797. + break;
  42798. +
  42799. + case SQLITE_NOLFS:
  42800. + strcpy(*pdo_err, "HYC00");
  42801. + break;
  42802. +
  42803. + case SQLITE_TOOBIG:
  42804. + strcpy(*pdo_err, "22001");
  42805. + break;
  42806. +
  42807. + case SQLITE_CONSTRAINT:
  42808. + strcpy(*pdo_err, "23000");
  42809. + break;
  42810. +
  42811. + case SQLITE_ERROR:
  42812. + default:
  42813. + strcpy(*pdo_err, "HY000");
  42814. + break;
  42815. + }
  42816. +
  42817. + if (!dbh->methods) {
  42818. + zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC, "SQLSTATE[%s] [%d] %s",
  42819. + *pdo_err, einfo->errcode, einfo->errmsg);
  42820. + }
  42821. +
  42822. + return einfo->errcode;
  42823. +}
  42824. +/* }}} */
  42825. +
  42826. +static int pdo_sqlite2_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info TSRMLS_DC)
  42827. +{
  42828. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42829. + pdo_sqlite2_error_info *einfo = &H->einfo;
  42830. + pdo_sqlite2_stmt *S;
  42831. +
  42832. + if (stmt) {
  42833. + S = stmt->driver_data;
  42834. + einfo = &S->einfo;
  42835. + }
  42836. +
  42837. + if (einfo->errcode) {
  42838. + add_next_index_long(info, einfo->errcode);
  42839. + if (einfo->errmsg) {
  42840. + add_next_index_string(info, einfo->errmsg, 1);
  42841. + }
  42842. + }
  42843. +
  42844. + return 1;
  42845. +}
  42846. +
  42847. +static int sqlite2_handle_closer(pdo_dbh_t *dbh TSRMLS_DC) /* {{{ */
  42848. +{
  42849. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42850. +
  42851. + if (H) {
  42852. + if (H->db) {
  42853. + sqlite_close(H->db);
  42854. + H->db = NULL;
  42855. + }
  42856. + if (H->einfo.errmsg) {
  42857. + pefree(H->einfo.errmsg, dbh->is_persistent);
  42858. + H->einfo.errmsg = NULL;
  42859. + }
  42860. + pefree(H, dbh->is_persistent);
  42861. + dbh->driver_data = NULL;
  42862. + }
  42863. + return 0;
  42864. +}
  42865. +/* }}} */
  42866. +
  42867. +static int sqlite2_handle_preparer(pdo_dbh_t *dbh, const char *sql, long sql_len, pdo_stmt_t *stmt, zval *driver_options TSRMLS_DC)
  42868. +{
  42869. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42870. + pdo_sqlite2_stmt *S = ecalloc(1, sizeof(pdo_sqlite2_stmt));
  42871. +
  42872. + S->H = H;
  42873. + stmt->driver_data = S;
  42874. + stmt->methods = &sqlite2_stmt_methods;
  42875. + stmt->supports_placeholders = PDO_PLACEHOLDER_NONE;
  42876. +
  42877. + if (PDO_CURSOR_FWDONLY != pdo_attr_lval(driver_options, PDO_ATTR_CURSOR, PDO_CURSOR_FWDONLY TSRMLS_CC)) {
  42878. + H->einfo.errcode = SQLITE_ERROR;
  42879. + pdo_sqlite2_error(NULL, dbh);
  42880. + return 0;
  42881. + }
  42882. +
  42883. + return 1;
  42884. +}
  42885. +
  42886. +static long sqlite2_handle_doer(pdo_dbh_t *dbh, const char *sql, long sql_len TSRMLS_DC)
  42887. +{
  42888. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42889. + char *errmsg = NULL;
  42890. +
  42891. + if ((H->einfo.errcode = sqlite_exec(H->db, sql, NULL, NULL, &errmsg)) != SQLITE_OK) {
  42892. + pdo_sqlite2_error(errmsg, dbh);
  42893. + return -1;
  42894. + } else {
  42895. + return sqlite_changes(H->db);
  42896. + }
  42897. +}
  42898. +
  42899. +static char *pdo_sqlite2_last_insert_id(pdo_dbh_t *dbh, const char *name, unsigned int *len TSRMLS_DC)
  42900. +{
  42901. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42902. + char *id;
  42903. +
  42904. + id = php_pdo_int64_to_str(sqlite_last_insert_rowid(H->db) TSRMLS_CC);
  42905. + *len = strlen(id);
  42906. + return id;
  42907. +}
  42908. +
  42909. +static int sqlite2_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, int unquotedlen, char **quoted, int *quotedlen, enum pdo_param_type paramtype TSRMLS_DC)
  42910. +{
  42911. + char *ret;
  42912. +
  42913. + if (unquotedlen && (unquoted[0] == '\x01' || memchr(unquoted, '\0', unquotedlen) != NULL)) {
  42914. + /* binary string */
  42915. + int len;
  42916. + ret = safe_emalloc(1 + unquotedlen / 254, 257, 5);
  42917. + ret[0] = '\'';
  42918. + ret[1] = '\x01';
  42919. + len = php_sqlite_encode_binary(unquoted, unquotedlen, ret+2);
  42920. + ret[len + 2] = '\'';
  42921. + ret[len + 3] = '\0';
  42922. + *quoted = ret;
  42923. + *quotedlen = len + 3;
  42924. + /* fprintf(stderr, "Quoting:%d:%.*s:\n", *quotedlen, *quotedlen, *quoted); */
  42925. + return 1;
  42926. + } else if (unquotedlen) {
  42927. + ret = sqlite_mprintf("'%q'", unquoted);
  42928. + if (ret) {
  42929. + *quoted = estrdup(ret);
  42930. + *quotedlen = strlen(ret);
  42931. + sqlite_freemem(ret);
  42932. + return 1;
  42933. + }
  42934. + return 0;
  42935. + } else {
  42936. + *quoted = estrdup("''");
  42937. + *quotedlen = 2;
  42938. + return 1;
  42939. + }
  42940. +}
  42941. +
  42942. +static int sqlite2_handle_begin(pdo_dbh_t *dbh TSRMLS_DC)
  42943. +{
  42944. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42945. + char *errmsg = NULL;
  42946. +
  42947. + if (sqlite_exec(H->db, "BEGIN", NULL, NULL, &errmsg) != SQLITE_OK) {
  42948. + pdo_sqlite2_error(errmsg, dbh);
  42949. + return 0;
  42950. + }
  42951. + return 1;
  42952. +}
  42953. +
  42954. +static int sqlite2_handle_commit(pdo_dbh_t *dbh TSRMLS_DC)
  42955. +{
  42956. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42957. + char *errmsg = NULL;
  42958. +
  42959. + if (sqlite_exec(H->db, "COMMIT", NULL, NULL, &errmsg) != SQLITE_OK) {
  42960. + pdo_sqlite2_error(errmsg, dbh);
  42961. + return 0;
  42962. + }
  42963. + return 1;
  42964. +}
  42965. +
  42966. +static int sqlite2_handle_rollback(pdo_dbh_t *dbh TSRMLS_DC)
  42967. +{
  42968. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42969. + char *errmsg = NULL;
  42970. +
  42971. + if (sqlite_exec(H->db, "ROLLBACK", NULL, NULL, &errmsg) != SQLITE_OK) {
  42972. + pdo_sqlite2_error(errmsg, dbh);
  42973. + return 0;
  42974. + }
  42975. + return 1;
  42976. +}
  42977. +
  42978. +static int pdo_sqlite2_get_attribute(pdo_dbh_t *dbh, long attr, zval *return_value TSRMLS_DC)
  42979. +{
  42980. + switch (attr) {
  42981. + case PDO_ATTR_CLIENT_VERSION:
  42982. + case PDO_ATTR_SERVER_VERSION:
  42983. + ZVAL_STRING(return_value, (char *)sqlite_libversion(), 1);
  42984. + break;
  42985. +
  42986. + default:
  42987. + return 0;
  42988. + }
  42989. +
  42990. + return 1;
  42991. +}
  42992. +
  42993. +static int pdo_sqlite2_set_attr(pdo_dbh_t *dbh, long attr, zval *val TSRMLS_DC)
  42994. +{
  42995. + pdo_sqlite2_db_handle *H = (pdo_sqlite2_db_handle *)dbh->driver_data;
  42996. +
  42997. + switch (attr) {
  42998. + case PDO_ATTR_TIMEOUT:
  42999. + convert_to_long(val);
  43000. + sqlite_busy_timeout(H->db, Z_LVAL_P(val) * 1000);
  43001. + return 1;
  43002. + }
  43003. + return 0;
  43004. +}
  43005. +
  43006. +static PHP_FUNCTION(sqlite2_create_function)
  43007. +{
  43008. + /* TODO: implement this stuff */
  43009. +}
  43010. +
  43011. +static const zend_function_entry dbh_methods[] = {
  43012. + PHP_FE(sqlite2_create_function, NULL)
  43013. + {NULL, NULL, NULL}
  43014. +};
  43015. +
  43016. +static const zend_function_entry *get_driver_methods(pdo_dbh_t *dbh, int kind TSRMLS_DC)
  43017. +{
  43018. + switch (kind) {
  43019. + case PDO_DBH_DRIVER_METHOD_KIND_DBH:
  43020. + return dbh_methods;
  43021. +
  43022. + default:
  43023. + return NULL;
  43024. + }
  43025. +}
  43026. +
  43027. +static struct pdo_dbh_methods sqlite2_methods = {
  43028. + sqlite2_handle_closer,
  43029. + sqlite2_handle_preparer,
  43030. + sqlite2_handle_doer,
  43031. + sqlite2_handle_quoter,
  43032. + sqlite2_handle_begin,
  43033. + sqlite2_handle_commit,
  43034. + sqlite2_handle_rollback,
  43035. + pdo_sqlite2_set_attr,
  43036. + pdo_sqlite2_last_insert_id,
  43037. + pdo_sqlite2_fetch_error_func,
  43038. + pdo_sqlite2_get_attribute,
  43039. + NULL, /* check_liveness: not needed */
  43040. + get_driver_methods
  43041. +};
  43042. +
  43043. +static char *make_filename_safe(const char *filename TSRMLS_DC)
  43044. +{
  43045. + if (*filename && strncmp(filename, ":memory:", sizeof(":memory:")-1)) {
  43046. + char *fullpath = expand_filepath(filename, NULL TSRMLS_CC);
  43047. +
  43048. + if (!fullpath) {
  43049. + return NULL;
  43050. + }
  43051. +
  43052. + if (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
  43053. + efree(fullpath);
  43054. + return NULL;
  43055. + }
  43056. +
  43057. + if (php_check_open_basedir(fullpath TSRMLS_CC)) {
  43058. + efree(fullpath);
  43059. + return NULL;
  43060. + }
  43061. + return fullpath;
  43062. + }
  43063. + return estrdup(filename);
  43064. +}
  43065. +
  43066. +static int authorizer(void *autharg, int access_type, const char *arg3, const char *arg4,
  43067. + const char *arg5, const char *arg6)
  43068. +{
  43069. + char *filename;
  43070. + switch (access_type) {
  43071. + case SQLITE_COPY: {
  43072. + TSRMLS_FETCH();
  43073. + filename = make_filename_safe(arg4 TSRMLS_CC);
  43074. + if (!filename) {
  43075. + return SQLITE_DENY;
  43076. + }
  43077. + efree(filename);
  43078. + return SQLITE_OK;
  43079. + }
  43080. +
  43081. + case SQLITE_ATTACH: {
  43082. + TSRMLS_FETCH();
  43083. + filename = make_filename_safe(arg3 TSRMLS_CC);
  43084. + if (!filename) {
  43085. + return SQLITE_DENY;
  43086. + }
  43087. + efree(filename);
  43088. + return SQLITE_OK;
  43089. + }
  43090. +
  43091. + default:
  43092. + /* access allowed */
  43093. + return SQLITE_OK;
  43094. + }
  43095. +}
  43096. +
  43097. +static int pdo_sqlite2_handle_factory(pdo_dbh_t *dbh, zval *driver_options TSRMLS_DC) /* {{{ */
  43098. +{
  43099. + pdo_sqlite2_db_handle *H;
  43100. + int ret = 0;
  43101. + long timeout = 60;
  43102. + char *filename;
  43103. + char *errmsg = NULL;
  43104. +
  43105. + H = pecalloc(1, sizeof(pdo_sqlite2_db_handle), dbh->is_persistent);
  43106. +
  43107. + H->einfo.errcode = 0;
  43108. + H->einfo.errmsg = NULL;
  43109. + dbh->driver_data = H;
  43110. +
  43111. + filename = make_filename_safe(dbh->data_source TSRMLS_CC);
  43112. +
  43113. + if (!filename) {
  43114. + zend_throw_exception_ex(php_pdo_get_exception(), 0 TSRMLS_CC,
  43115. + "safe_mode/open_basedir prohibits opening %s",
  43116. + dbh->data_source);
  43117. + goto cleanup;
  43118. + }
  43119. +
  43120. + H->db = sqlite_open(filename, 0666, &errmsg);
  43121. + efree(filename);
  43122. +
  43123. + if (!H->db) {
  43124. + H->einfo.errcode = SQLITE_ERROR;
  43125. + pdo_sqlite2_error(errmsg, dbh);
  43126. + goto cleanup;
  43127. + }
  43128. +
  43129. + sqlite_set_authorizer(H->db, authorizer, NULL);
  43130. +
  43131. + if (driver_options) {
  43132. + timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, timeout TSRMLS_CC);
  43133. + }
  43134. + sqlite_busy_timeout(H->db, timeout * 1000);
  43135. +
  43136. + dbh->alloc_own_columns = 1;
  43137. + dbh->max_escaped_char_length = 2;
  43138. +
  43139. + ret = 1;
  43140. +
  43141. +cleanup:
  43142. + dbh->methods = &sqlite2_methods;
  43143. +
  43144. + return ret;
  43145. +}
  43146. +/* }}} */
  43147. +
  43148. +pdo_driver_t pdo_sqlite2_driver = {
  43149. + PDO_DRIVER_HEADER(sqlite2),
  43150. + pdo_sqlite2_handle_factory
  43151. +};
  43152. +
  43153. +
  43154. +
  43155. +#endif
  43156. +
  43157. +
  43158. +/*
  43159. + * Local variables:
  43160. + * tab-width: 4
  43161. + * c-basic-offset: 4
  43162. + * End:
  43163. + * vim600: noet sw=4 ts=4 fdm=marker
  43164. + * vim<600: noet sw=4 ts=4
  43165. + */
  43166. --- /dev/null
  43167. +++ b/ext/sqlite/php_sqlite.def
  43168. @@ -0,0 +1,43 @@
  43169. +EXPORTS
  43170. +sqlite_open
  43171. +sqlite_close
  43172. +sqlite_exec
  43173. +sqlite_last_insert_rowid
  43174. +sqlite_changes
  43175. +sqlite_error_string
  43176. +sqlite_interrupt
  43177. +sqlite_complete
  43178. +sqlite_busy_handler
  43179. +sqlite_busy_timeout
  43180. +sqlite_get_table
  43181. +sqlite_free_table
  43182. +sqlite_exec_printf
  43183. +sqlite_exec_vprintf
  43184. +sqlite_get_table_printf
  43185. +sqlite_get_table_vprintf
  43186. +sqlite_mprintf
  43187. +sqlite_vmprintf
  43188. +sqlite_freemem
  43189. +sqlite_libversion
  43190. +sqlite_libencoding
  43191. +sqlite_create_function
  43192. +sqlite_create_aggregate
  43193. +sqlite_function_type
  43194. +sqlite_set_result_string
  43195. +sqlite_set_result_int
  43196. +sqlite_set_result_double
  43197. +sqlite_set_result_error
  43198. +sqlite_user_data
  43199. +sqlite_aggregate_context
  43200. +sqlite_aggregate_count
  43201. +sqlite_set_authorizer
  43202. +sqlite_trace
  43203. +sqlite_compile
  43204. +sqlite_step
  43205. +sqlite_finalize
  43206. +; some experimental stuff
  43207. +sqlite_last_statement_changes
  43208. +sqlite_reset
  43209. +sqlite_bind
  43210. +sqlite_progress_handler
  43211. +sqlite_commit_hook
  43212. --- /dev/null
  43213. +++ b/ext/sqlite/php_sqlite.h
  43214. @@ -0,0 +1,107 @@
  43215. +/*
  43216. + +----------------------------------------------------------------------+
  43217. + | PHP Version 5 |
  43218. + +----------------------------------------------------------------------+
  43219. + | Copyright (c) 1997-2012 The PHP Group |
  43220. + +----------------------------------------------------------------------+
  43221. + | This source file is subject to version 3.01 of the PHP license, |
  43222. + | that is bundled with this package in the file LICENSE, and is |
  43223. + | available through the world-wide-web at the following url: |
  43224. + | http://www.php.net/license/3_01.txt |
  43225. + | If you did not receive a copy of the PHP license and are unable to |
  43226. + | obtain it through the world-wide-web, please send a note to |
  43227. + | license@php.net so we can mail you a copy immediately. |
  43228. + +----------------------------------------------------------------------+
  43229. + | Authors: Wez Furlong <wez@thebrainroom.com> |
  43230. + | Tal Peer <tal@php.net> |
  43231. + | Marcus Boerger <helly@php.net> |
  43232. + +----------------------------------------------------------------------+
  43233. +
  43234. + $Id$
  43235. +*/
  43236. +
  43237. +#ifndef PHP_SQLITE_H
  43238. +#define PHP_SQLITE_H
  43239. +
  43240. +extern zend_module_entry sqlite_module_entry;
  43241. +#define phpext_sqlite_ptr &sqlite_module_entry
  43242. +
  43243. +#ifdef ZTS
  43244. +#include "TSRM.h"
  43245. +#endif
  43246. +
  43247. +PHP_MINIT_FUNCTION(sqlite);
  43248. +PHP_MSHUTDOWN_FUNCTION(sqlite);
  43249. +PHP_RSHUTDOWN_FUNCTION(sqlite);
  43250. +PHP_MINFO_FUNCTION(sqlite);
  43251. +
  43252. +PHP_FUNCTION(sqlite_open);
  43253. +PHP_FUNCTION(sqlite_popen);
  43254. +PHP_FUNCTION(sqlite_close);
  43255. +PHP_FUNCTION(sqlite_query);
  43256. +PHP_FUNCTION(sqlite_exec);
  43257. +PHP_FUNCTION(sqlite_unbuffered_query);
  43258. +PHP_FUNCTION(sqlite_array_query);
  43259. +PHP_FUNCTION(sqlite_single_query);
  43260. +
  43261. +PHP_FUNCTION(sqlite_fetch_array);
  43262. +PHP_FUNCTION(sqlite_fetch_object);
  43263. +PHP_FUNCTION(sqlite_fetch_single);
  43264. +PHP_FUNCTION(sqlite_fetch_all);
  43265. +PHP_FUNCTION(sqlite_current);
  43266. +PHP_FUNCTION(sqlite_column);
  43267. +
  43268. +PHP_FUNCTION(sqlite_num_rows);
  43269. +PHP_FUNCTION(sqlite_num_fields);
  43270. +PHP_FUNCTION(sqlite_field_name);
  43271. +PHP_FUNCTION(sqlite_seek);
  43272. +PHP_FUNCTION(sqlite_rewind);
  43273. +PHP_FUNCTION(sqlite_next);
  43274. +PHP_FUNCTION(sqlite_prev);
  43275. +PHP_FUNCTION(sqlite_key);
  43276. +
  43277. +PHP_FUNCTION(sqlite_valid);
  43278. +PHP_FUNCTION(sqlite_has_prev);
  43279. +
  43280. +PHP_FUNCTION(sqlite_libversion);
  43281. +PHP_FUNCTION(sqlite_libencoding);
  43282. +
  43283. +PHP_FUNCTION(sqlite_changes);
  43284. +PHP_FUNCTION(sqlite_last_insert_rowid);
  43285. +
  43286. +PHP_FUNCTION(sqlite_escape_string);
  43287. +
  43288. +PHP_FUNCTION(sqlite_busy_timeout);
  43289. +
  43290. +PHP_FUNCTION(sqlite_last_error);
  43291. +PHP_FUNCTION(sqlite_error_string);
  43292. +
  43293. +PHP_FUNCTION(sqlite_create_aggregate);
  43294. +PHP_FUNCTION(sqlite_create_function);
  43295. +PHP_FUNCTION(sqlite_udf_decode_binary);
  43296. +PHP_FUNCTION(sqlite_udf_encode_binary);
  43297. +
  43298. +PHP_FUNCTION(sqlite_factory);
  43299. +
  43300. +PHP_FUNCTION(sqlite_fetch_column_types);
  43301. +
  43302. +ZEND_BEGIN_MODULE_GLOBALS(sqlite)
  43303. + long assoc_case;
  43304. +ZEND_END_MODULE_GLOBALS(sqlite)
  43305. +
  43306. +#ifdef ZTS
  43307. +#define SQLITE_G(v) TSRMG(sqlite_globals_id, zend_sqlite_globals *, v)
  43308. +#else
  43309. +#define SQLITE_G(v) (sqlite_globals.v)
  43310. +#endif
  43311. +
  43312. +#endif
  43313. +
  43314. +
  43315. +/*
  43316. + * Local variables:
  43317. + * tab-width: 4
  43318. + * c-basic-offset: 4
  43319. + * indent-tabs-mode: t
  43320. + * End:
  43321. + */
  43322. --- /dev/null
  43323. +++ b/ext/sqlite/README
  43324. @@ -0,0 +1,14 @@
  43325. +This is an extension for the SQLite Embeddable SQL Database Engine.
  43326. +http://www.sqlite.org/
  43327. +
  43328. +SQLite is a C library that implements an embeddable SQL database engine.
  43329. +Programs that link with the SQLite library can have SQL database access
  43330. +without running a separate RDBMS process.
  43331. +
  43332. +SQLite is not a client library used to connect to a big database server.
  43333. +SQLite is the server. The SQLite library reads and writes directly to and from
  43334. +the database files on disk
  43335. +
  43336. +
  43337. +
  43338. +vim:tw=78:et
  43339. --- /dev/null
  43340. +++ b/ext/sqlite/sess_sqlite.c
  43341. @@ -0,0 +1,201 @@
  43342. +/*
  43343. + +----------------------------------------------------------------------+
  43344. + | PHP Version 5 |
  43345. + +----------------------------------------------------------------------+
  43346. + | Copyright (c) 1997-2012 The PHP Group |
  43347. + +----------------------------------------------------------------------+
  43348. + | This source file is subject to version 3.01 of the PHP license, |
  43349. + | that is bundled with this package in the file LICENSE, and is |
  43350. + | available through the world-wide-web at the following url: |
  43351. + | http://www.php.net/license/3_01.txt |
  43352. + | If you did not receive a copy of the PHP license and are unable to |
  43353. + | obtain it through the world-wide-web, please send a note to |
  43354. + | license@php.net so we can mail you a copy immediately. |
  43355. + +----------------------------------------------------------------------+
  43356. + | Authors: John Coggeshall <john@php.net> |
  43357. + | Wez Furlong <wez@thebrainroom.com> |
  43358. + +----------------------------------------------------------------------+
  43359. + */
  43360. +
  43361. +/* $Id$ */
  43362. +
  43363. +#include "php.h"
  43364. +
  43365. +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
  43366. +
  43367. +#include "ext/session/php_session.h"
  43368. +#include "ext/standard/php_lcg.h"
  43369. +#include <sqlite.h>
  43370. +#define SQLITE_RETVAL(__r) ((__r) == SQLITE_OK ? SUCCESS : FAILURE)
  43371. +#define PS_SQLITE_DATA sqlite *db = (sqlite*)PS_GET_MOD_DATA()
  43372. +extern int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
  43373. +extern int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
  43374. +
  43375. +PS_FUNCS(sqlite);
  43376. +
  43377. +ps_module ps_mod_sqlite = {
  43378. + PS_MOD(sqlite)
  43379. +};
  43380. +
  43381. +PS_OPEN_FUNC(sqlite)
  43382. +{
  43383. + char *errmsg = NULL;
  43384. + sqlite *db;
  43385. +
  43386. + /* TODO: do we need a safe_mode check here? */
  43387. + db = sqlite_open(save_path, 0666, &errmsg);
  43388. + if (db == NULL) {
  43389. + php_error_docref(NULL TSRMLS_CC, E_WARNING,
  43390. + "SQLite: failed to open/create session database `%s' - %s", save_path, errmsg);
  43391. + sqlite_freemem(errmsg);
  43392. + return FAILURE;
  43393. + }
  43394. +
  43395. + /* allow up to 1 minute when busy */
  43396. + sqlite_busy_timeout(db, 60000);
  43397. +
  43398. + sqlite_exec(db, "PRAGMA default_synchronous = OFF", NULL, NULL, NULL);
  43399. + sqlite_exec(db, "PRAGMA count_changes = OFF", NULL, NULL, NULL);
  43400. +
  43401. + /* This will fail if the table already exists, but that's not a big problem. I'm
  43402. + unclear as to how to check for a table's existence in SQLite -- that would be better here. */
  43403. + sqlite_exec(db,
  43404. + "CREATE TABLE session_data ("
  43405. + " sess_id PRIMARY KEY,"
  43406. + " value TEXT, "
  43407. + " updated INTEGER "
  43408. + ")", NULL, NULL, NULL);
  43409. +
  43410. + PS_SET_MOD_DATA(db);
  43411. +
  43412. + return SUCCESS;
  43413. +}
  43414. +
  43415. +PS_CLOSE_FUNC(sqlite)
  43416. +{
  43417. + PS_SQLITE_DATA;
  43418. +
  43419. + sqlite_close(db);
  43420. +
  43421. + return SUCCESS;
  43422. +}
  43423. +
  43424. +PS_READ_FUNC(sqlite)
  43425. +{
  43426. + PS_SQLITE_DATA;
  43427. + char *query;
  43428. + const char *tail;
  43429. + sqlite_vm *vm;
  43430. + int colcount, result;
  43431. + const char **rowdata, **colnames;
  43432. + char *error;
  43433. +
  43434. + *val = NULL;
  43435. + *vallen = 0;
  43436. +
  43437. + query = sqlite_mprintf("SELECT value FROM session_data WHERE sess_id='%q' LIMIT 1", key);
  43438. + if (query == NULL) {
  43439. + /* no memory */
  43440. + return FAILURE;
  43441. + }
  43442. +
  43443. + if (sqlite_compile(db, query, &tail, &vm, &error) != SQLITE_OK) {
  43444. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: Could not compile session read query: %s", error);
  43445. + sqlite_freemem(error);
  43446. + sqlite_freemem(query);
  43447. + return FAILURE;
  43448. + }
  43449. +
  43450. + switch ((result = sqlite_step(vm, &colcount, &rowdata, &colnames))) {
  43451. + case SQLITE_ROW:
  43452. + if (rowdata[0] != NULL) {
  43453. + *vallen = strlen(rowdata[0]);
  43454. + if (*vallen) {
  43455. + *val = emalloc(*vallen);
  43456. + *vallen = sqlite_decode_binary(rowdata[0], *val);
  43457. + (*val)[*vallen] = '\0';
  43458. + } else {
  43459. + *val = STR_EMPTY_ALLOC();
  43460. + }
  43461. + }
  43462. + break;
  43463. + default:
  43464. + sqlite_freemem(error);
  43465. + error = NULL;
  43466. + }
  43467. +
  43468. + if (SQLITE_OK != sqlite_finalize(vm, &error)) {
  43469. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: session read: error %s", error);
  43470. + sqlite_freemem(error);
  43471. + error = NULL;
  43472. + }
  43473. +
  43474. + sqlite_freemem(query);
  43475. +
  43476. + return *val == NULL ? FAILURE : SUCCESS;
  43477. +}
  43478. +
  43479. +PS_WRITE_FUNC(sqlite)
  43480. +{
  43481. + PS_SQLITE_DATA;
  43482. + char *error;
  43483. + time_t t;
  43484. + char *binary;
  43485. + int binlen;
  43486. + int rv;
  43487. +
  43488. + t = time(NULL);
  43489. +
  43490. + binary = safe_emalloc(1 + vallen / 254, 257, 3);
  43491. + binlen = sqlite_encode_binary((const unsigned char*)val, vallen, binary);
  43492. +
  43493. + rv = sqlite_exec_printf(db, "REPLACE INTO session_data VALUES('%q', '%q', %d)", NULL, NULL, &error, key, binary, t);
  43494. + if (rv != SQLITE_OK) {
  43495. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "SQLite: session write query failed: %s", error);
  43496. + sqlite_freemem(error);
  43497. + }
  43498. + efree(binary);
  43499. +
  43500. + return SQLITE_RETVAL(rv);
  43501. +}
  43502. +
  43503. +PS_DESTROY_FUNC(sqlite)
  43504. +{
  43505. + int rv;
  43506. + PS_SQLITE_DATA;
  43507. +
  43508. + rv = sqlite_exec_printf(db, "DELETE FROM session_data WHERE sess_id='%q'", NULL, NULL, NULL, key);
  43509. +
  43510. + return SQLITE_RETVAL(rv);
  43511. +}
  43512. +
  43513. +PS_GC_FUNC(sqlite)
  43514. +{
  43515. + PS_SQLITE_DATA;
  43516. + int rv;
  43517. + time_t t = time(NULL);
  43518. +
  43519. + rv = sqlite_exec_printf(db,
  43520. + "DELETE FROM session_data WHERE (%d - updated) > %d",
  43521. + NULL, NULL, NULL, t, maxlifetime);
  43522. +
  43523. + /* because SQLite does not actually clear the deleted data from the database
  43524. + * we need to occassionaly do so manually to prevent the sessions database
  43525. + * from growing endlessly.
  43526. + */
  43527. + if ((int) ((float) PS(gc_divisor) * PS(gc_divisor) * php_combined_lcg(TSRMLS_C)) < PS(gc_probability)) {
  43528. + rv = sqlite_exec_printf(db, "VACUUM", NULL, NULL, NULL);
  43529. + }
  43530. + return SQLITE_RETVAL(rv);
  43531. +}
  43532. +
  43533. +#endif /* HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION) */
  43534. +
  43535. +/*
  43536. + * Local variables:
  43537. + * tab-width: 4
  43538. + * c-basic-offset: 4
  43539. + * End:
  43540. + * vim600: sw=4 ts=4 fdm=marker
  43541. + * vim<600: sw=4 ts=4
  43542. + */
  43543. --- /dev/null
  43544. +++ b/ext/sqlite/sqlite.c
  43545. @@ -0,0 +1,3448 @@
  43546. +/*
  43547. + +----------------------------------------------------------------------+
  43548. + | PHP Version 5 |
  43549. + +----------------------------------------------------------------------+
  43550. + | Copyright (c) 1997-2012 The PHP Group |
  43551. + +----------------------------------------------------------------------+
  43552. + | This source file is subject to version 3.01 of the PHP license, |
  43553. + | that is bundled with this package in the file LICENSE, and is |
  43554. + | available through the world-wide-web at the following url: |
  43555. + | http://www.php.net/license/3_01.txt |
  43556. + | If you did not receive a copy of the PHP license and are unable to |
  43557. + | obtain it through the world-wide-web, please send a note to |
  43558. + | license@php.net so we can mail you a copy immediately. |
  43559. + +----------------------------------------------------------------------+
  43560. + | Authors: Wez Furlong <wez@thebrainroom.com> |
  43561. + | Tal Peer <tal@php.net> |
  43562. + | Marcus Boerger <helly@php.net> |
  43563. + +----------------------------------------------------------------------+
  43564. +
  43565. + $Id$
  43566. +*/
  43567. +
  43568. +#ifdef HAVE_CONFIG_H
  43569. +#include "config.h"
  43570. +#endif
  43571. +
  43572. +#define PHP_SQLITE_MODULE_VERSION "2.0-dev"
  43573. +
  43574. +#include "php.h"
  43575. +#include "php_ini.h"
  43576. +#include "ext/standard/info.h"
  43577. +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
  43578. +#include "ext/session/php_session.h"
  43579. +#endif
  43580. +#include "php_sqlite.h"
  43581. +
  43582. +#if HAVE_TIME_H
  43583. +# include <time.h>
  43584. +#endif
  43585. +#if HAVE_UNISTD_H
  43586. +#include <unistd.h>
  43587. +#endif
  43588. +
  43589. +#include <sqlite.h>
  43590. +
  43591. +#include "zend_exceptions.h"
  43592. +#include "zend_interfaces.h"
  43593. +
  43594. +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
  43595. +extern PHPAPI zend_class_entry *spl_ce_RuntimeException;
  43596. +extern PHPAPI zend_class_entry *spl_ce_Countable;
  43597. +#endif
  43598. +
  43599. +#if PHP_SQLITE2_HAVE_PDO
  43600. +# include "pdo/php_pdo.h"
  43601. +# include "pdo/php_pdo_driver.h"
  43602. +extern pdo_driver_t pdo_sqlite2_driver;
  43603. +#endif
  43604. +
  43605. +#ifndef safe_emalloc
  43606. +# define safe_emalloc(a,b,c) emalloc((a)*(b)+(c))
  43607. +#endif
  43608. +
  43609. +ZEND_DECLARE_MODULE_GLOBALS(sqlite)
  43610. +static PHP_GINIT_FUNCTION(sqlite);
  43611. +
  43612. +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
  43613. +extern ps_module ps_mod_sqlite;
  43614. +#define ps_sqlite_ptr &ps_mod_sqlite
  43615. +#endif
  43616. +
  43617. +extern int sqlite_encode_binary(const unsigned char *in, int n, unsigned char *out);
  43618. +extern int sqlite_decode_binary(const unsigned char *in, unsigned char *out);
  43619. +
  43620. +#define php_sqlite_encode_binary(in, n, out) sqlite_encode_binary((const unsigned char *)in, n, (unsigned char *)out)
  43621. +#define php_sqlite_decode_binary(in, out) in && *in ? sqlite_decode_binary((const unsigned char *)in, (unsigned char *)out) : 0
  43622. +
  43623. +static int sqlite_count_elements(zval *object, long *count TSRMLS_DC);
  43624. +
  43625. +static int le_sqlite_db, le_sqlite_result, le_sqlite_pdb;
  43626. +
  43627. +static inline void php_sqlite_strtoupper(char *s)
  43628. +{
  43629. + while (*s!='\0') {
  43630. + *s = toupper(*s);
  43631. + s++;
  43632. + }
  43633. +}
  43634. +
  43635. +static inline void php_sqlite_strtolower(char *s)
  43636. +{
  43637. + while (*s!='\0') {
  43638. + *s = tolower(*s);
  43639. + s++;
  43640. + }
  43641. +}
  43642. +
  43643. +/* {{{ PHP_INI
  43644. + */
  43645. +PHP_INI_BEGIN()
  43646. +STD_PHP_INI_ENTRY_EX("sqlite.assoc_case", "0", PHP_INI_ALL, OnUpdateLong, assoc_case, zend_sqlite_globals, sqlite_globals, display_link_numbers)
  43647. +PHP_INI_END()
  43648. +/* }}} */
  43649. +
  43650. +#define DB_FROM_ZVAL(db, zv) ZEND_FETCH_RESOURCE2(db, struct php_sqlite_db *, zv, -1, "sqlite database", le_sqlite_db, le_sqlite_pdb)
  43651. +
  43652. +#define DB_FROM_OBJECT(db, object) \
  43653. + { \
  43654. + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC); \
  43655. + db = obj->u.db; \
  43656. + if (!db) { \
  43657. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "The database wasn't opened"); \
  43658. + RETURN_NULL(); \
  43659. + } \
  43660. + }
  43661. +
  43662. +#define RES_FROM_OBJECT_RESTORE_ERH(res, object, error_handling) \
  43663. + { \
  43664. + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC); \
  43665. + res = obj->u.res; \
  43666. + if (!res) { \
  43667. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "No result set available"); \
  43668. + if (error_handling) \
  43669. + zend_restore_error_handling(error_handling TSRMLS_CC); \
  43670. + RETURN_NULL(); \
  43671. + } \
  43672. + }
  43673. +
  43674. +#define RES_FROM_OBJECT(res, object) RES_FROM_OBJECT_RESTORE_ERH(res, object, NULL)
  43675. +
  43676. +#define PHP_SQLITE_EMPTY_QUERY \
  43677. + if (!sql_len || !*sql) { \
  43678. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot execute empty query."); \
  43679. + RETURN_FALSE; \
  43680. + }
  43681. +
  43682. +struct php_sqlite_result {
  43683. + struct php_sqlite_db *db;
  43684. + sqlite_vm *vm;
  43685. + int buffered;
  43686. + int ncolumns;
  43687. + int nrows;
  43688. + int curr_row;
  43689. + char **col_names;
  43690. + int alloc_rows;
  43691. + int mode;
  43692. + char **table;
  43693. +};
  43694. +
  43695. +struct php_sqlite_db {
  43696. + sqlite *db;
  43697. + int last_err_code;
  43698. + zend_bool is_persistent;
  43699. + long rsrc_id;
  43700. +
  43701. + HashTable callbacks;
  43702. +};
  43703. +
  43704. +struct php_sqlite_agg_functions {
  43705. + struct php_sqlite_db *db;
  43706. + int is_valid;
  43707. + zval *step;
  43708. + zval *fini;
  43709. +};
  43710. +
  43711. +static void php_sqlite_fetch_array(struct php_sqlite_result *res, int mode, zend_bool decode_binary, int move_next, zval *return_value TSRMLS_DC);
  43712. +static int php_sqlite_fetch(struct php_sqlite_result *rres TSRMLS_DC);
  43713. +
  43714. +enum { PHPSQLITE_ASSOC = 1, PHPSQLITE_NUM = 2, PHPSQLITE_BOTH = PHPSQLITE_ASSOC|PHPSQLITE_NUM };
  43715. +
  43716. +/* {{{ arginfo */
  43717. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_popen, 0, 0, 1)
  43718. + ZEND_ARG_INFO(0, filename)
  43719. + ZEND_ARG_INFO(0, mode)
  43720. + ZEND_ARG_INFO(1, error_message)
  43721. +ZEND_END_ARG_INFO()
  43722. +
  43723. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_open, 0, 0, 1)
  43724. + ZEND_ARG_INFO(0, filename)
  43725. + ZEND_ARG_INFO(0, mode)
  43726. + ZEND_ARG_INFO(1, error_message)
  43727. +ZEND_END_ARG_INFO()
  43728. +
  43729. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_factory, 0, 0, 1)
  43730. + ZEND_ARG_INFO(0, filename)
  43731. + ZEND_ARG_INFO(0, mode)
  43732. + ZEND_ARG_INFO(1, error_message)
  43733. +ZEND_END_ARG_INFO()
  43734. +
  43735. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_busy_timeout, 0, 0, 2)
  43736. + ZEND_ARG_INFO(0, db)
  43737. + ZEND_ARG_INFO(0, ms)
  43738. +ZEND_END_ARG_INFO()
  43739. +
  43740. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_busy_timeout, 0, 0, 1)
  43741. + ZEND_ARG_INFO(0, ms)
  43742. +ZEND_END_ARG_INFO()
  43743. +
  43744. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_close, 0, 0, 1)
  43745. + ZEND_ARG_INFO(0, db)
  43746. +ZEND_END_ARG_INFO()
  43747. +
  43748. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_unbuffered_query, 0, 0, 2)
  43749. + ZEND_ARG_INFO(0, query)
  43750. + ZEND_ARG_INFO(0, db)
  43751. + ZEND_ARG_INFO(0, result_type)
  43752. + ZEND_ARG_INFO(1, error_message)
  43753. +ZEND_END_ARG_INFO()
  43754. +
  43755. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_unbuffered_query, 0, 0, 1)
  43756. + ZEND_ARG_INFO(0, query)
  43757. + ZEND_ARG_INFO(0, result_type)
  43758. + ZEND_ARG_INFO(1, error_message)
  43759. +ZEND_END_ARG_INFO()
  43760. +
  43761. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_column_types, 0, 0, 2)
  43762. + ZEND_ARG_INFO(0, table_name)
  43763. + ZEND_ARG_INFO(0, db)
  43764. + ZEND_ARG_INFO(0, result_type)
  43765. +ZEND_END_ARG_INFO()
  43766. +
  43767. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_column_types, 0, 0, 1)
  43768. + ZEND_ARG_INFO(0, table_name)
  43769. + ZEND_ARG_INFO(0, result_type)
  43770. +ZEND_END_ARG_INFO()
  43771. +
  43772. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_query, 0, 0, 2)
  43773. + ZEND_ARG_INFO(0, query)
  43774. + ZEND_ARG_INFO(0, db)
  43775. + ZEND_ARG_INFO(0, result_type)
  43776. + ZEND_ARG_INFO(1, error_message)
  43777. +ZEND_END_ARG_INFO()
  43778. +
  43779. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_query, 0, 0, 1)
  43780. + ZEND_ARG_INFO(0, query)
  43781. + ZEND_ARG_INFO(0, result_type)
  43782. + ZEND_ARG_INFO(1, error_message)
  43783. +ZEND_END_ARG_INFO()
  43784. +
  43785. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_exec, 0, 0, 2)
  43786. + ZEND_ARG_INFO(0, query)
  43787. + ZEND_ARG_INFO(0, db)
  43788. + ZEND_ARG_INFO(1, error_message)
  43789. +ZEND_END_ARG_INFO()
  43790. +
  43791. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_exec, 0, 0, 1)
  43792. + ZEND_ARG_INFO(0, query)
  43793. + ZEND_ARG_INFO(1, error_message)
  43794. +ZEND_END_ARG_INFO()
  43795. +
  43796. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_all, 0, 0, 1)
  43797. + ZEND_ARG_INFO(0, result)
  43798. + ZEND_ARG_INFO(0, result_type)
  43799. + ZEND_ARG_INFO(0, decode_binary)
  43800. +ZEND_END_ARG_INFO()
  43801. +
  43802. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_all, 0, 0, 0)
  43803. + ZEND_ARG_INFO(0, result_type)
  43804. + ZEND_ARG_INFO(0, decode_binary)
  43805. +ZEND_END_ARG_INFO()
  43806. +
  43807. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_array, 0, 0, 1)
  43808. + ZEND_ARG_INFO(0, result)
  43809. + ZEND_ARG_INFO(0, result_type)
  43810. + ZEND_ARG_INFO(0, decode_binary)
  43811. +ZEND_END_ARG_INFO()
  43812. +
  43813. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_array, 0, 0, 0)
  43814. + ZEND_ARG_INFO(0, result_type)
  43815. + ZEND_ARG_INFO(0, decode_binary)
  43816. +ZEND_END_ARG_INFO()
  43817. +
  43818. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_object, 0, 0, 1)
  43819. + ZEND_ARG_INFO(0, result)
  43820. + ZEND_ARG_INFO(0, class_name)
  43821. + ZEND_ARG_INFO(0, ctor_params)
  43822. + ZEND_ARG_INFO(0, decode_binary)
  43823. +ZEND_END_ARG_INFO()
  43824. +
  43825. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_object, 0, 0, 0)
  43826. + ZEND_ARG_INFO(0, class_name)
  43827. + ZEND_ARG_INFO(0, ctor_params)
  43828. + ZEND_ARG_INFO(0, decode_binary)
  43829. +ZEND_END_ARG_INFO()
  43830. +
  43831. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_array_query, 0, 0, 2)
  43832. + ZEND_ARG_INFO(0, db)
  43833. + ZEND_ARG_INFO(0, query)
  43834. + ZEND_ARG_INFO(0, result_type)
  43835. + ZEND_ARG_INFO(0, decode_binary)
  43836. +ZEND_END_ARG_INFO()
  43837. +
  43838. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_array_query, 0, 0, 1)
  43839. + ZEND_ARG_INFO(0, query)
  43840. + ZEND_ARG_INFO(0, result_type)
  43841. + ZEND_ARG_INFO(0, decode_binary)
  43842. +ZEND_END_ARG_INFO()
  43843. +
  43844. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_single_query, 0, 0, 2)
  43845. + ZEND_ARG_INFO(0, db)
  43846. + ZEND_ARG_INFO(0, query)
  43847. + ZEND_ARG_INFO(0, first_row_only)
  43848. + ZEND_ARG_INFO(0, decode_binary)
  43849. +ZEND_END_ARG_INFO()
  43850. +
  43851. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_single_query, 0, 0, 1)
  43852. + ZEND_ARG_INFO(0, query)
  43853. + ZEND_ARG_INFO(0, first_row_only)
  43854. + ZEND_ARG_INFO(0, decode_binary)
  43855. +ZEND_END_ARG_INFO()
  43856. +
  43857. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_fetch_single, 0, 0, 1)
  43858. + ZEND_ARG_INFO(0, result)
  43859. + ZEND_ARG_INFO(0, decode_binary)
  43860. +ZEND_END_ARG_INFO()
  43861. +
  43862. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_fetch_single, 0, 0, 0)
  43863. + ZEND_ARG_INFO(0, decode_binary)
  43864. +ZEND_END_ARG_INFO()
  43865. +
  43866. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_current, 0, 0, 1)
  43867. + ZEND_ARG_INFO(0, result)
  43868. + ZEND_ARG_INFO(0, result_type)
  43869. + ZEND_ARG_INFO(0, decode_binary)
  43870. +ZEND_END_ARG_INFO()
  43871. +
  43872. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_current, 0, 0, 0)
  43873. + ZEND_ARG_INFO(0, result_type)
  43874. + ZEND_ARG_INFO(0, decode_binary)
  43875. +ZEND_END_ARG_INFO()
  43876. +
  43877. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_column, 0, 0, 2)
  43878. + ZEND_ARG_INFO(0, result)
  43879. + ZEND_ARG_INFO(0, index_or_name)
  43880. + ZEND_ARG_INFO(0, decode_binary)
  43881. +ZEND_END_ARG_INFO()
  43882. +
  43883. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_column, 0, 0, 1)
  43884. + ZEND_ARG_INFO(0, index_or_name)
  43885. + ZEND_ARG_INFO(0, decode_binary)
  43886. +ZEND_END_ARG_INFO()
  43887. +
  43888. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_libversion, 0)
  43889. +ZEND_END_ARG_INFO()
  43890. +
  43891. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_libencoding, 0)
  43892. +ZEND_END_ARG_INFO()
  43893. +
  43894. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_changes, 0, 0, 1)
  43895. + ZEND_ARG_INFO(0, db)
  43896. +ZEND_END_ARG_INFO()
  43897. +
  43898. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_changes, 0)
  43899. +ZEND_END_ARG_INFO()
  43900. +
  43901. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_last_insert_rowid, 0, 0, 1)
  43902. + ZEND_ARG_INFO(0, db)
  43903. +ZEND_END_ARG_INFO()
  43904. +
  43905. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_last_insert_rowid, 0)
  43906. +ZEND_END_ARG_INFO()
  43907. +
  43908. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_num_rows, 0, 0, 1)
  43909. + ZEND_ARG_INFO(0, result)
  43910. +ZEND_END_ARG_INFO()
  43911. +
  43912. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_num_rows, 0)
  43913. +ZEND_END_ARG_INFO()
  43914. +
  43915. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_valid, 0, 0, 1)
  43916. + ZEND_ARG_INFO(0, result)
  43917. +ZEND_END_ARG_INFO()
  43918. +
  43919. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_valid, 0)
  43920. +ZEND_END_ARG_INFO()
  43921. +
  43922. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_has_prev, 0, 0, 1)
  43923. + ZEND_ARG_INFO(0, result)
  43924. +ZEND_END_ARG_INFO()
  43925. +
  43926. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_has_prev, 0)
  43927. +ZEND_END_ARG_INFO()
  43928. +
  43929. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_num_fields, 0, 0, 1)
  43930. + ZEND_ARG_INFO(0, result)
  43931. +ZEND_END_ARG_INFO()
  43932. +
  43933. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_num_fields, 0)
  43934. +ZEND_END_ARG_INFO()
  43935. +
  43936. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_field_name, 0, 0, 2)
  43937. + ZEND_ARG_INFO(0, result)
  43938. + ZEND_ARG_INFO(0, field_index)
  43939. +ZEND_END_ARG_INFO()
  43940. +
  43941. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_field_name, 0, 0, 1)
  43942. + ZEND_ARG_INFO(0, field_index)
  43943. +ZEND_END_ARG_INFO()
  43944. +
  43945. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_seek, 0, 0, 2)
  43946. + ZEND_ARG_INFO(0, result)
  43947. + ZEND_ARG_INFO(0, row)
  43948. +ZEND_END_ARG_INFO()
  43949. +
  43950. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_seek, 0, 0, 1)
  43951. + ZEND_ARG_INFO(0, row)
  43952. +ZEND_END_ARG_INFO()
  43953. +
  43954. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_rewind, 0, 0, 1)
  43955. + ZEND_ARG_INFO(0, result)
  43956. +ZEND_END_ARG_INFO()
  43957. +
  43958. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_rewind, 0)
  43959. +ZEND_END_ARG_INFO()
  43960. +
  43961. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_next, 0, 0, 1)
  43962. + ZEND_ARG_INFO(0, result)
  43963. +ZEND_END_ARG_INFO()
  43964. +
  43965. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_next, 0)
  43966. +ZEND_END_ARG_INFO()
  43967. +
  43968. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_key, 0, 0, 1)
  43969. + ZEND_ARG_INFO(0, result)
  43970. +ZEND_END_ARG_INFO()
  43971. +
  43972. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_key, 0)
  43973. +ZEND_END_ARG_INFO()
  43974. +
  43975. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_prev, 0, 0, 1)
  43976. + ZEND_ARG_INFO(0, result)
  43977. +ZEND_END_ARG_INFO()
  43978. +
  43979. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_prev, 0)
  43980. +ZEND_END_ARG_INFO()
  43981. +
  43982. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_escape_string, 0, 0, 1)
  43983. + ZEND_ARG_INFO(0, item)
  43984. +ZEND_END_ARG_INFO()
  43985. +
  43986. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_last_error, 0, 0, 1)
  43987. + ZEND_ARG_INFO(0, db)
  43988. +ZEND_END_ARG_INFO()
  43989. +
  43990. +ZEND_BEGIN_ARG_INFO(arginfo_sqlite_method_last_error, 0)
  43991. +ZEND_END_ARG_INFO()
  43992. +
  43993. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_error_string, 0, 0, 1)
  43994. + ZEND_ARG_INFO(0, error_code)
  43995. +ZEND_END_ARG_INFO()
  43996. +
  43997. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_create_aggregate, 0, 0, 4)
  43998. + ZEND_ARG_INFO(0, db)
  43999. + ZEND_ARG_INFO(0, funcname)
  44000. + ZEND_ARG_INFO(0, step_func)
  44001. + ZEND_ARG_INFO(0, finalize_func)
  44002. + ZEND_ARG_INFO(0, num_args)
  44003. +ZEND_END_ARG_INFO()
  44004. +
  44005. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_create_aggregate, 0, 0, 3)
  44006. + ZEND_ARG_INFO(0, funcname)
  44007. + ZEND_ARG_INFO(0, step_func)
  44008. + ZEND_ARG_INFO(0, finalize_func)
  44009. + ZEND_ARG_INFO(0, num_args)
  44010. +ZEND_END_ARG_INFO()
  44011. +
  44012. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_create_function, 0, 0, 3)
  44013. + ZEND_ARG_INFO(0, db)
  44014. + ZEND_ARG_INFO(0, funcname)
  44015. + ZEND_ARG_INFO(0, callback)
  44016. + ZEND_ARG_INFO(0, num_args)
  44017. +ZEND_END_ARG_INFO()
  44018. +
  44019. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_method_create_function, 0, 0, 2)
  44020. + ZEND_ARG_INFO(0, funcname)
  44021. + ZEND_ARG_INFO(0, callback)
  44022. + ZEND_ARG_INFO(0, num_args)
  44023. +ZEND_END_ARG_INFO()
  44024. +
  44025. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_udf_encode_binary, 0, 0, 1)
  44026. + ZEND_ARG_INFO(0, data)
  44027. +ZEND_END_ARG_INFO()
  44028. +
  44029. +ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite_udf_decode_binary, 0, 0, 1)
  44030. + ZEND_ARG_INFO(0, data)
  44031. +ZEND_END_ARG_INFO()
  44032. +/* }}} */
  44033. +
  44034. +const zend_function_entry sqlite_functions[] = {
  44035. + PHP_FE(sqlite_open, arginfo_sqlite_open)
  44036. + PHP_FE(sqlite_popen, arginfo_sqlite_popen)
  44037. + PHP_FE(sqlite_close, arginfo_sqlite_close)
  44038. + PHP_FE(sqlite_query, arginfo_sqlite_query)
  44039. + PHP_FE(sqlite_exec, arginfo_sqlite_exec)
  44040. + PHP_FE(sqlite_array_query, arginfo_sqlite_array_query)
  44041. + PHP_FE(sqlite_single_query, arginfo_sqlite_single_query)
  44042. + PHP_FE(sqlite_fetch_array, arginfo_sqlite_fetch_array)
  44043. + PHP_FE(sqlite_fetch_object, arginfo_sqlite_fetch_object)
  44044. + PHP_FE(sqlite_fetch_single, arginfo_sqlite_fetch_single)
  44045. + PHP_FALIAS(sqlite_fetch_string, sqlite_fetch_single, arginfo_sqlite_fetch_single)
  44046. + PHP_FE(sqlite_fetch_all, arginfo_sqlite_fetch_all)
  44047. + PHP_FE(sqlite_current, arginfo_sqlite_current)
  44048. + PHP_FE(sqlite_column, arginfo_sqlite_column)
  44049. + PHP_FE(sqlite_libversion, arginfo_sqlite_libversion)
  44050. + PHP_FE(sqlite_libencoding, arginfo_sqlite_libencoding)
  44051. + PHP_FE(sqlite_changes, arginfo_sqlite_changes)
  44052. + PHP_FE(sqlite_last_insert_rowid, arginfo_sqlite_last_insert_rowid)
  44053. + PHP_FE(sqlite_num_rows, arginfo_sqlite_num_rows)
  44054. + PHP_FE(sqlite_num_fields, arginfo_sqlite_num_fields)
  44055. + PHP_FE(sqlite_field_name, arginfo_sqlite_field_name)
  44056. + PHP_FE(sqlite_seek, arginfo_sqlite_seek)
  44057. + PHP_FE(sqlite_rewind, arginfo_sqlite_rewind)
  44058. + PHP_FE(sqlite_next, arginfo_sqlite_next)
  44059. + PHP_FE(sqlite_prev, arginfo_sqlite_prev)
  44060. + PHP_FE(sqlite_valid, arginfo_sqlite_valid)
  44061. + PHP_FALIAS(sqlite_has_more, sqlite_valid, arginfo_sqlite_valid)
  44062. + PHP_FE(sqlite_has_prev, arginfo_sqlite_has_prev)
  44063. + PHP_FE(sqlite_escape_string, arginfo_sqlite_escape_string)
  44064. + PHP_FE(sqlite_busy_timeout, arginfo_sqlite_busy_timeout)
  44065. + PHP_FE(sqlite_last_error, arginfo_sqlite_last_error)
  44066. + PHP_FE(sqlite_error_string, arginfo_sqlite_error_string)
  44067. + PHP_FE(sqlite_unbuffered_query, arginfo_sqlite_unbuffered_query)
  44068. + PHP_FE(sqlite_create_aggregate, arginfo_sqlite_create_aggregate)
  44069. + PHP_FE(sqlite_create_function, arginfo_sqlite_create_function)
  44070. + PHP_FE(sqlite_factory, arginfo_sqlite_factory)
  44071. + PHP_FE(sqlite_udf_encode_binary, arginfo_sqlite_udf_encode_binary)
  44072. + PHP_FE(sqlite_udf_decode_binary, arginfo_sqlite_udf_decode_binary)
  44073. + PHP_FE(sqlite_fetch_column_types, arginfo_sqlite_fetch_column_types)
  44074. + {NULL, NULL, NULL}
  44075. +};
  44076. +
  44077. +const zend_function_entry sqlite_funcs_db[] = {
  44078. + PHP_ME_MAPPING(__construct, sqlite_open, arginfo_sqlite_open, 0)
  44079. +/* PHP_ME_MAPPING(close, sqlite_close, NULL, 0)*/
  44080. + PHP_ME_MAPPING(query, sqlite_query, arginfo_sqlite_method_query, 0)
  44081. + PHP_ME_MAPPING(queryExec, sqlite_exec, arginfo_sqlite_method_exec, 0)
  44082. + PHP_ME_MAPPING(arrayQuery, sqlite_array_query, arginfo_sqlite_method_array_query, 0)
  44083. + PHP_ME_MAPPING(singleQuery, sqlite_single_query, arginfo_sqlite_method_single_query, 0)
  44084. + PHP_ME_MAPPING(unbufferedQuery, sqlite_unbuffered_query, arginfo_sqlite_method_unbuffered_query, 0)
  44085. + PHP_ME_MAPPING(lastInsertRowid, sqlite_last_insert_rowid, arginfo_sqlite_method_last_insert_rowid, 0)
  44086. + PHP_ME_MAPPING(changes, sqlite_changes, arginfo_sqlite_method_changes, 0)
  44087. + PHP_ME_MAPPING(createAggregate, sqlite_create_aggregate, arginfo_sqlite_method_create_aggregate, 0)
  44088. + PHP_ME_MAPPING(createFunction, sqlite_create_function, arginfo_sqlite_method_create_function, 0)
  44089. + PHP_ME_MAPPING(busyTimeout, sqlite_busy_timeout, arginfo_sqlite_method_busy_timeout, 0)
  44090. + PHP_ME_MAPPING(lastError, sqlite_last_error, arginfo_sqlite_method_last_error, 0)
  44091. + PHP_ME_MAPPING(fetchColumnTypes, sqlite_fetch_column_types, arginfo_sqlite_method_fetch_column_types, 0)
  44092. +/* PHP_ME_MAPPING(error_string, sqlite_error_string, NULL, 0) static */
  44093. +/* PHP_ME_MAPPING(escape_string, sqlite_escape_string, NULL, 0) static */
  44094. + {NULL, NULL, NULL}
  44095. +};
  44096. +
  44097. +const zend_function_entry sqlite_funcs_query[] = {
  44098. + PHP_ME_MAPPING(fetch, sqlite_fetch_array, arginfo_sqlite_method_fetch_array, 0)
  44099. + PHP_ME_MAPPING(fetchObject, sqlite_fetch_object, arginfo_sqlite_method_fetch_object, 0)
  44100. + PHP_ME_MAPPING(fetchSingle, sqlite_fetch_single, arginfo_sqlite_method_fetch_single, 0)
  44101. + PHP_ME_MAPPING(fetchAll, sqlite_fetch_all, arginfo_sqlite_method_fetch_all, 0)
  44102. + PHP_ME_MAPPING(column, sqlite_column, arginfo_sqlite_method_column, 0)
  44103. + PHP_ME_MAPPING(numFields, sqlite_num_fields, arginfo_sqlite_method_num_fields, 0)
  44104. + PHP_ME_MAPPING(fieldName, sqlite_field_name, arginfo_sqlite_method_field_name, 0)
  44105. + /* iterator */
  44106. + PHP_ME_MAPPING(current, sqlite_current, arginfo_sqlite_method_current, 0)
  44107. + PHP_ME_MAPPING(key, sqlite_key, arginfo_sqlite_method_key, 0)
  44108. + PHP_ME_MAPPING(next, sqlite_next, arginfo_sqlite_method_next, 0)
  44109. + PHP_ME_MAPPING(valid, sqlite_valid, arginfo_sqlite_method_valid, 0)
  44110. + PHP_ME_MAPPING(rewind, sqlite_rewind, arginfo_sqlite_method_rewind, 0)
  44111. + /* countable */
  44112. + PHP_ME_MAPPING(count, sqlite_num_rows, arginfo_sqlite_method_num_rows, 0)
  44113. + /* additional */
  44114. + PHP_ME_MAPPING(prev, sqlite_prev, arginfo_sqlite_method_prev, 0)
  44115. + PHP_ME_MAPPING(hasPrev, sqlite_has_prev, arginfo_sqlite_method_has_prev, 0)
  44116. + PHP_ME_MAPPING(numRows, sqlite_num_rows, arginfo_sqlite_method_num_rows, 0)
  44117. + PHP_ME_MAPPING(seek, sqlite_seek, arginfo_sqlite_method_seek, 0)
  44118. + {NULL, NULL, NULL}
  44119. +};
  44120. +
  44121. +const zend_function_entry sqlite_funcs_ub_query[] = {
  44122. + PHP_ME_MAPPING(fetch, sqlite_fetch_array, arginfo_sqlite_method_fetch_array, 0)
  44123. + PHP_ME_MAPPING(fetchObject, sqlite_fetch_object, arginfo_sqlite_method_fetch_object, 0)
  44124. + PHP_ME_MAPPING(fetchSingle, sqlite_fetch_single, arginfo_sqlite_method_fetch_single, 0)
  44125. + PHP_ME_MAPPING(fetchAll, sqlite_fetch_all, arginfo_sqlite_method_fetch_all, 0)
  44126. + PHP_ME_MAPPING(column, sqlite_column, arginfo_sqlite_method_column, 0)
  44127. + PHP_ME_MAPPING(numFields, sqlite_num_fields, arginfo_sqlite_method_num_fields, 0)
  44128. + PHP_ME_MAPPING(fieldName, sqlite_field_name, arginfo_sqlite_method_field_name, 0)
  44129. + /* iterator */
  44130. + PHP_ME_MAPPING(current, sqlite_current, arginfo_sqlite_method_current, 0)
  44131. + PHP_ME_MAPPING(next, sqlite_next, arginfo_sqlite_method_next, 0)
  44132. + PHP_ME_MAPPING(valid, sqlite_valid, arginfo_sqlite_method_valid, 0)
  44133. + {NULL, NULL, NULL}
  44134. +};
  44135. +
  44136. +const zend_function_entry sqlite_funcs_exception[] = {
  44137. + {NULL, NULL, NULL}
  44138. +};
  44139. +
  44140. +/* Dependancies */
  44141. +static const zend_module_dep sqlite_deps[] = {
  44142. +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
  44143. + ZEND_MOD_REQUIRED("spl")
  44144. +#endif
  44145. +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
  44146. + ZEND_MOD_REQUIRED("session")
  44147. +#endif
  44148. +#ifdef PHP_SQLITE2_HAVE_PDO
  44149. + ZEND_MOD_REQUIRED("pdo")
  44150. +#endif
  44151. + {NULL, NULL, NULL}
  44152. +};
  44153. +
  44154. +zend_module_entry sqlite_module_entry = {
  44155. +#if ZEND_MODULE_API_NO >= 20050922
  44156. + STANDARD_MODULE_HEADER_EX, NULL,
  44157. + sqlite_deps,
  44158. +#elif ZEND_MODULE_API_NO >= 20010901
  44159. + STANDARD_MODULE_HEADER,
  44160. +#endif
  44161. + "SQLite",
  44162. + sqlite_functions,
  44163. + PHP_MINIT(sqlite),
  44164. + PHP_MSHUTDOWN(sqlite),
  44165. + NULL,
  44166. + PHP_RSHUTDOWN(sqlite),
  44167. + PHP_MINFO(sqlite),
  44168. +#if ZEND_MODULE_API_NO >= 20010901
  44169. + PHP_SQLITE_MODULE_VERSION,
  44170. +#endif
  44171. +#if ZEND_MODULE_API_NO >= 20060613
  44172. + PHP_MODULE_GLOBALS(sqlite),
  44173. + PHP_GINIT(sqlite),
  44174. + NULL,
  44175. + NULL,
  44176. + STANDARD_MODULE_PROPERTIES_EX
  44177. +#else
  44178. + STANDARD_MODULE_PROPERTIES
  44179. +#endif
  44180. +};
  44181. +
  44182. +
  44183. +#ifdef COMPILE_DL_SQLITE
  44184. +ZEND_GET_MODULE(sqlite)
  44185. +#endif
  44186. +
  44187. +static int php_sqlite_callback_invalidator(struct php_sqlite_agg_functions *funcs TSRMLS_DC)
  44188. +{
  44189. + if (!funcs->is_valid) {
  44190. + return 0;
  44191. + }
  44192. +
  44193. + if (funcs->step) {
  44194. + zval_ptr_dtor(&funcs->step);
  44195. + funcs->step = NULL;
  44196. + }
  44197. +
  44198. + if (funcs->fini) {
  44199. + zval_ptr_dtor(&funcs->fini);
  44200. + funcs->fini = NULL;
  44201. + }
  44202. +
  44203. + funcs->is_valid = 0;
  44204. +
  44205. + return 0;
  44206. +}
  44207. +
  44208. +
  44209. +static void php_sqlite_callback_dtor(void *pDest)
  44210. +{
  44211. + struct php_sqlite_agg_functions *funcs = (struct php_sqlite_agg_functions*)pDest;
  44212. +
  44213. + if (funcs->is_valid) {
  44214. + TSRMLS_FETCH();
  44215. +
  44216. + php_sqlite_callback_invalidator(funcs TSRMLS_CC);
  44217. + }
  44218. +}
  44219. +
  44220. +static ZEND_RSRC_DTOR_FUNC(php_sqlite_db_dtor)
  44221. +{
  44222. + if (rsrc->ptr) {
  44223. + struct php_sqlite_db *db = (struct php_sqlite_db*)rsrc->ptr;
  44224. +
  44225. + sqlite_close(db->db);
  44226. +
  44227. + zend_hash_destroy(&db->callbacks);
  44228. +
  44229. + pefree(db, db->is_persistent);
  44230. +
  44231. + rsrc->ptr = NULL;
  44232. + }
  44233. +}
  44234. +
  44235. +static void real_result_dtor(struct php_sqlite_result *res TSRMLS_DC)
  44236. +{
  44237. + int i, j, base;
  44238. +
  44239. + if (res->vm) {
  44240. + sqlite_finalize(res->vm, NULL);
  44241. + }
  44242. +
  44243. + if (res->table) {
  44244. + if (!res->buffered && res->nrows) {
  44245. + res->nrows = 1; /* only one row is stored */
  44246. + }
  44247. + for (i = 0; i < res->nrows; i++) {
  44248. + base = i * res->ncolumns;
  44249. + for (j = 0; j < res->ncolumns; j++) {
  44250. + if (res->table[base + j] != NULL) {
  44251. + efree(res->table[base + j]);
  44252. + }
  44253. + }
  44254. + }
  44255. + efree(res->table);
  44256. + }
  44257. + if (res->col_names) {
  44258. + for (j = 0; j < res->ncolumns; j++) {
  44259. + efree(res->col_names[j]);
  44260. + }
  44261. + efree(res->col_names);
  44262. + }
  44263. +
  44264. + if (res->db) {
  44265. + zend_list_delete(res->db->rsrc_id);
  44266. + }
  44267. + efree(res);
  44268. +}
  44269. +
  44270. +static int _clean_unfinished_results(zend_rsrc_list_entry *le, void *db TSRMLS_DC)
  44271. +{
  44272. + if (Z_TYPE_P(le) == le_sqlite_result) {
  44273. + struct php_sqlite_result *res = (struct php_sqlite_result *)le->ptr;
  44274. + if (res->db->rsrc_id == ((struct php_sqlite_db*)db)->rsrc_id) {
  44275. + return ZEND_HASH_APPLY_REMOVE;
  44276. + }
  44277. + }
  44278. + return ZEND_HASH_APPLY_KEEP;
  44279. +}
  44280. +
  44281. +static ZEND_RSRC_DTOR_FUNC(php_sqlite_result_dtor)
  44282. +{
  44283. + struct php_sqlite_result *res = (struct php_sqlite_result *)rsrc->ptr;
  44284. + real_result_dtor(res TSRMLS_CC);
  44285. +}
  44286. +
  44287. +static int php_sqlite_forget_persistent_id_numbers(zend_rsrc_list_entry *rsrc TSRMLS_DC)
  44288. +{
  44289. + struct php_sqlite_db *db = (struct php_sqlite_db*)rsrc->ptr;
  44290. +
  44291. + if (Z_TYPE_P(rsrc) != le_sqlite_pdb) {
  44292. + return 0;
  44293. + }
  44294. +
  44295. + /* prevent bad mojo if someone tries to use a previously registered function in the next request */
  44296. + zend_hash_apply(&db->callbacks, (apply_func_t)php_sqlite_callback_invalidator TSRMLS_CC);
  44297. +
  44298. + db->rsrc_id = FAILURE;
  44299. +
  44300. + /* don't leave pending commits hanging around */
  44301. + sqlite_exec(db->db, "ROLLBACK", NULL, NULL, NULL);
  44302. +
  44303. + return 0;
  44304. +}
  44305. +
  44306. +PHP_RSHUTDOWN_FUNCTION(sqlite)
  44307. +{
  44308. + zend_hash_apply(&EG(persistent_list), (apply_func_t)php_sqlite_forget_persistent_id_numbers TSRMLS_CC);
  44309. + return SUCCESS;
  44310. +}
  44311. +
  44312. +/* {{{ PHP Function interface */
  44313. +static void php_sqlite_generic_function_callback(sqlite_func *func, int argc, const char **argv)
  44314. +{
  44315. + zval *retval = NULL;
  44316. + zval ***zargs = NULL;
  44317. + zval funcname;
  44318. + int i, res;
  44319. + char *callable = NULL, *errbuf=NULL;
  44320. + TSRMLS_FETCH();
  44321. +
  44322. + /* sanity check the args */
  44323. + if (argc == 0) {
  44324. + sqlite_set_result_error(func, "not enough parameters", -1);
  44325. + return;
  44326. + }
  44327. +
  44328. + ZVAL_STRING(&funcname, (char*)argv[0], 1);
  44329. +
  44330. + if (!zend_make_callable(&funcname, &callable TSRMLS_CC)) {
  44331. + spprintf(&errbuf, 0, "function `%s' is not a function name", callable);
  44332. + sqlite_set_result_error(func, errbuf, -1);
  44333. + efree(errbuf);
  44334. + efree(callable);
  44335. + zval_dtor(&funcname);
  44336. + return;
  44337. + }
  44338. +
  44339. + if (argc > 1) {
  44340. + zargs = (zval ***)safe_emalloc((argc - 1), sizeof(zval **), 0);
  44341. +
  44342. + for (i = 0; i < argc-1; i++) {
  44343. + zargs[i] = emalloc(sizeof(zval *));
  44344. + MAKE_STD_ZVAL(*zargs[i]);
  44345. + ZVAL_STRING(*zargs[i], (char*)argv[i+1], 1);
  44346. + }
  44347. + }
  44348. +
  44349. + res = call_user_function_ex(EG(function_table),
  44350. + NULL,
  44351. + &funcname,
  44352. + &retval,
  44353. + argc-1,
  44354. + zargs,
  44355. + 0, NULL TSRMLS_CC);
  44356. +
  44357. + zval_dtor(&funcname);
  44358. +
  44359. + if (res == SUCCESS) {
  44360. + if (retval == NULL) {
  44361. + sqlite_set_result_string(func, NULL, 0);
  44362. + } else {
  44363. + switch (Z_TYPE_P(retval)) {
  44364. + case IS_STRING:
  44365. + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
  44366. + break;
  44367. + case IS_LONG:
  44368. + case IS_BOOL:
  44369. + sqlite_set_result_int(func, Z_LVAL_P(retval));
  44370. + break;
  44371. + case IS_DOUBLE:
  44372. + sqlite_set_result_double(func, Z_DVAL_P(retval));
  44373. + break;
  44374. + case IS_NULL:
  44375. + default:
  44376. + sqlite_set_result_string(func, NULL, 0);
  44377. + }
  44378. + }
  44379. + } else {
  44380. + char *errbuf;
  44381. + spprintf(&errbuf, 0, "call_user_function_ex failed for function %s()", callable);
  44382. + sqlite_set_result_error(func, errbuf, -1);
  44383. + efree(errbuf);
  44384. + }
  44385. +
  44386. + efree(callable);
  44387. +
  44388. + if (retval) {
  44389. + zval_ptr_dtor(&retval);
  44390. + }
  44391. +
  44392. + if (zargs) {
  44393. + for (i = 0; i < argc-1; i++) {
  44394. + zval_ptr_dtor(zargs[i]);
  44395. + efree(zargs[i]);
  44396. + }
  44397. + efree(zargs);
  44398. + }
  44399. +}
  44400. +/* }}} */
  44401. +
  44402. +/* {{{ callback for sqlite_create_function */
  44403. +static void php_sqlite_function_callback(sqlite_func *func, int argc, const char **argv)
  44404. +{
  44405. + zval *retval = NULL;
  44406. + zval ***zargs = NULL;
  44407. + int i, res;
  44408. + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
  44409. + TSRMLS_FETCH();
  44410. +
  44411. + if (!funcs->is_valid) {
  44412. + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
  44413. + return;
  44414. + }
  44415. +
  44416. + if (argc > 0) {
  44417. + zargs = (zval ***)safe_emalloc(argc, sizeof(zval **), 0);
  44418. +
  44419. + for (i = 0; i < argc; i++) {
  44420. + zargs[i] = emalloc(sizeof(zval *));
  44421. + MAKE_STD_ZVAL(*zargs[i]);
  44422. +
  44423. + if (argv[i] == NULL) {
  44424. + ZVAL_NULL(*zargs[i]);
  44425. + } else {
  44426. + ZVAL_STRING(*zargs[i], (char*)argv[i], 1);
  44427. + }
  44428. + }
  44429. + }
  44430. +
  44431. + res = call_user_function_ex(EG(function_table),
  44432. + NULL,
  44433. + funcs->step,
  44434. + &retval,
  44435. + argc,
  44436. + zargs,
  44437. + 0, NULL TSRMLS_CC);
  44438. +
  44439. + if (res == SUCCESS) {
  44440. + if (retval == NULL) {
  44441. + sqlite_set_result_string(func, NULL, 0);
  44442. + } else {
  44443. + switch (Z_TYPE_P(retval)) {
  44444. + case IS_STRING:
  44445. + /* TODO: for binary results, need to encode the string */
  44446. + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
  44447. + break;
  44448. + case IS_LONG:
  44449. + case IS_BOOL:
  44450. + sqlite_set_result_int(func, Z_LVAL_P(retval));
  44451. + break;
  44452. + case IS_DOUBLE:
  44453. + sqlite_set_result_double(func, Z_DVAL_P(retval));
  44454. + break;
  44455. + case IS_NULL:
  44456. + default:
  44457. + sqlite_set_result_string(func, NULL, 0);
  44458. + }
  44459. + }
  44460. + } else {
  44461. + sqlite_set_result_error(func, "call_user_function_ex failed", -1);
  44462. + }
  44463. +
  44464. + if (retval) {
  44465. + zval_ptr_dtor(&retval);
  44466. + }
  44467. +
  44468. + if (zargs) {
  44469. + for (i = 0; i < argc; i++) {
  44470. + zval_ptr_dtor(zargs[i]);
  44471. + efree(zargs[i]);
  44472. + }
  44473. + efree(zargs);
  44474. + }
  44475. +}
  44476. +/* }}} */
  44477. +
  44478. +/* {{{ callback for sqlite_create_aggregate: step function */
  44479. +static void php_sqlite_agg_step_function_callback(sqlite_func *func, int argc, const char **argv)
  44480. +{
  44481. + zval *retval = NULL;
  44482. + zval ***zargs;
  44483. + zval **context_p;
  44484. + int i, res, zargc;
  44485. + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
  44486. + TSRMLS_FETCH();
  44487. +
  44488. + if (!funcs->is_valid) {
  44489. + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
  44490. + return;
  44491. + }
  44492. +
  44493. + /* sanity check the args */
  44494. + if (argc < 1) {
  44495. + return;
  44496. + }
  44497. +
  44498. + zargc = argc + 1;
  44499. + zargs = (zval ***)safe_emalloc(zargc, sizeof(zval **), 0);
  44500. +
  44501. + /* first arg is always the context zval */
  44502. + context_p = (zval **)sqlite_aggregate_context(func, sizeof(*context_p));
  44503. +
  44504. + if (*context_p == NULL) {
  44505. + MAKE_STD_ZVAL(*context_p);
  44506. + Z_SET_ISREF_PP(context_p);
  44507. + Z_TYPE_PP(context_p) = IS_NULL;
  44508. + }
  44509. +
  44510. + zargs[0] = context_p;
  44511. +
  44512. + /* copy the other args */
  44513. + for (i = 0; i < argc; i++) {
  44514. + zargs[i+1] = emalloc(sizeof(zval *));
  44515. + MAKE_STD_ZVAL(*zargs[i+1]);
  44516. + if (argv[i] == NULL) {
  44517. + ZVAL_NULL(*zargs[i+1]);
  44518. + } else {
  44519. + ZVAL_STRING(*zargs[i+1], (char*)argv[i], 1);
  44520. + }
  44521. + }
  44522. +
  44523. + res = call_user_function_ex(EG(function_table),
  44524. + NULL,
  44525. + funcs->step,
  44526. + &retval,
  44527. + zargc,
  44528. + zargs,
  44529. + 0, NULL TSRMLS_CC);
  44530. +
  44531. + if (res != SUCCESS) {
  44532. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "call_user_function_ex failed");
  44533. + }
  44534. +
  44535. + if (retval) {
  44536. + zval_ptr_dtor(&retval);
  44537. + }
  44538. +
  44539. + if (zargs) {
  44540. + for (i = 1; i < zargc; i++) {
  44541. + zval_ptr_dtor(zargs[i]);
  44542. + efree(zargs[i]);
  44543. + }
  44544. + efree(zargs);
  44545. + }
  44546. +}
  44547. +/* }}} */
  44548. +
  44549. +/* {{{ callback for sqlite_create_aggregate: finalize function */
  44550. +static void php_sqlite_agg_fini_function_callback(sqlite_func *func)
  44551. +{
  44552. + zval *retval = NULL;
  44553. + int res;
  44554. + struct php_sqlite_agg_functions *funcs = sqlite_user_data(func);
  44555. + zval **context_p;
  44556. + TSRMLS_FETCH();
  44557. +
  44558. + if (!funcs->is_valid) {
  44559. + sqlite_set_result_error(func, "this function has not been correctly defined for this request", -1);
  44560. + return;
  44561. + }
  44562. +
  44563. + context_p = (zval **)sqlite_aggregate_context(func, sizeof(*context_p));
  44564. +
  44565. + res = call_user_function_ex(EG(function_table),
  44566. + NULL,
  44567. + funcs->fini,
  44568. + &retval,
  44569. + 1,
  44570. + &context_p,
  44571. + 0, NULL TSRMLS_CC);
  44572. +
  44573. + if (res == SUCCESS) {
  44574. + if (retval == NULL) {
  44575. + sqlite_set_result_string(func, NULL, 0);
  44576. + } else {
  44577. + switch (Z_TYPE_P(retval)) {
  44578. + case IS_STRING:
  44579. + /* TODO: for binary results, need to encode the string */
  44580. + sqlite_set_result_string(func, Z_STRVAL_P(retval), Z_STRLEN_P(retval));
  44581. + break;
  44582. + case IS_LONG:
  44583. + case IS_BOOL:
  44584. + sqlite_set_result_int(func, Z_LVAL_P(retval));
  44585. + break;
  44586. + case IS_DOUBLE:
  44587. + sqlite_set_result_double(func, Z_DVAL_P(retval));
  44588. + break;
  44589. + case IS_NULL:
  44590. + default:
  44591. + sqlite_set_result_string(func, NULL, 0);
  44592. + }
  44593. + }
  44594. + } else {
  44595. + sqlite_set_result_error(func, "call_user_function_ex failed", -1);
  44596. + }
  44597. +
  44598. + if (retval) {
  44599. + zval_ptr_dtor(&retval);
  44600. + }
  44601. +
  44602. + zval_ptr_dtor(context_p);
  44603. +}
  44604. +/* }}} */
  44605. +
  44606. +/* {{{ Authorization Callback */
  44607. +static int php_sqlite_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4,
  44608. + const char *arg5, const char *arg6)
  44609. +{
  44610. + switch (access_type) {
  44611. + case SQLITE_COPY:
  44612. + if (strncmp(arg4, ":memory:", sizeof(":memory:") - 1)) {
  44613. + TSRMLS_FETCH();
  44614. + if (PG(safe_mode) && (!php_checkuid(arg4, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
  44615. + return SQLITE_DENY;
  44616. + }
  44617. +
  44618. + if (php_check_open_basedir(arg4 TSRMLS_CC)) {
  44619. + return SQLITE_DENY;
  44620. + }
  44621. + }
  44622. + return SQLITE_OK;
  44623. +#ifdef SQLITE_ATTACH
  44624. + case SQLITE_ATTACH:
  44625. + if (strncmp(arg3, ":memory:", sizeof(":memory:") - 1)) {
  44626. + TSRMLS_FETCH();
  44627. + if (PG(safe_mode) && (!php_checkuid(arg3, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
  44628. + return SQLITE_DENY;
  44629. + }
  44630. +
  44631. + if (php_check_open_basedir(arg3 TSRMLS_CC)) {
  44632. + return SQLITE_DENY;
  44633. + }
  44634. + }
  44635. + return SQLITE_OK;
  44636. +#endif
  44637. +
  44638. + default:
  44639. + /* access allowed */
  44640. + return SQLITE_OK;
  44641. + }
  44642. +}
  44643. +/* }}} */
  44644. +
  44645. +/* {{{ OO init/structure stuff */
  44646. +#define REGISTER_SQLITE_CLASS(name, c_name, parent) \
  44647. + { \
  44648. + zend_class_entry ce; \
  44649. + INIT_CLASS_ENTRY(ce, "SQLite" # name, sqlite_funcs_ ## c_name); \
  44650. + ce.create_object = sqlite_object_new_ ## c_name; \
  44651. + sqlite_ce_ ## c_name = zend_register_internal_class_ex(&ce, parent, NULL TSRMLS_CC); \
  44652. + memcpy(&sqlite_object_handlers_ ## c_name, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); \
  44653. + sqlite_object_handlers_ ## c_name.clone_obj = NULL; \
  44654. + sqlite_ce_ ## c_name->ce_flags |= ZEND_ACC_FINAL_CLASS; \
  44655. + }
  44656. +
  44657. +zend_class_entry *sqlite_ce_db, *sqlite_ce_exception;
  44658. +zend_class_entry *sqlite_ce_query, *sqlite_ce_ub_query;
  44659. +
  44660. +static zend_object_handlers sqlite_object_handlers_db;
  44661. +static zend_object_handlers sqlite_object_handlers_query;
  44662. +static zend_object_handlers sqlite_object_handlers_ub_query;
  44663. +static zend_object_handlers sqlite_object_handlers_exception;
  44664. +
  44665. +typedef enum {
  44666. + is_db,
  44667. + is_result
  44668. +} sqlite_obj_type;
  44669. +
  44670. +typedef struct _sqlite_object {
  44671. + zend_object std;
  44672. + sqlite_obj_type type;
  44673. + union {
  44674. + struct php_sqlite_db *db;
  44675. + struct php_sqlite_result *res;
  44676. + void *ptr;
  44677. + } u;
  44678. +} sqlite_object;
  44679. +
  44680. +static int sqlite_free_persistent(zend_rsrc_list_entry *le, void *ptr TSRMLS_DC)
  44681. +{
  44682. + return le->ptr == ptr ? ZEND_HASH_APPLY_REMOVE : ZEND_HASH_APPLY_KEEP;
  44683. +}
  44684. +
  44685. +static void sqlite_object_free_storage(void *object TSRMLS_DC)
  44686. +{
  44687. + sqlite_object *intern = (sqlite_object *)object;
  44688. +
  44689. + zend_object_std_dtor(&intern->std TSRMLS_CC);
  44690. +
  44691. + if (intern->u.ptr) {
  44692. + if (intern->type == is_db) {
  44693. + if (intern->u.db->rsrc_id) {
  44694. + zend_list_delete(intern->u.db->rsrc_id);
  44695. + zend_hash_apply_with_argument(&EG(persistent_list), (apply_func_arg_t) sqlite_free_persistent, &intern->u.ptr TSRMLS_CC);
  44696. + }
  44697. + } else {
  44698. + real_result_dtor(intern->u.res TSRMLS_CC);
  44699. + }
  44700. + }
  44701. +
  44702. + efree(object);
  44703. +}
  44704. +
  44705. +static void sqlite_object_new(zend_class_entry *class_type, zend_object_handlers *handlers, zend_object_value *retval TSRMLS_DC)
  44706. +{
  44707. + sqlite_object *intern;
  44708. + zval *tmp;
  44709. +
  44710. + intern = emalloc(sizeof(sqlite_object));
  44711. + memset(intern, 0, sizeof(sqlite_object));
  44712. +
  44713. + zend_object_std_init(&intern->std, class_type TSRMLS_CC);
  44714. + zend_hash_copy(intern->std.properties, &class_type->default_properties, (copy_ctor_func_t) zval_add_ref, (void *) &tmp, sizeof(zval *));
  44715. +
  44716. + retval->handle = zend_objects_store_put(intern, (zend_objects_store_dtor_t)zend_objects_destroy_object, (zend_objects_free_object_storage_t) sqlite_object_free_storage, NULL TSRMLS_CC);
  44717. + retval->handlers = handlers;
  44718. +}
  44719. +
  44720. +static zend_object_value sqlite_object_new_db(zend_class_entry *class_type TSRMLS_DC)
  44721. +{
  44722. + zend_object_value retval;
  44723. +
  44724. + sqlite_object_new(class_type, &sqlite_object_handlers_db, &retval TSRMLS_CC);
  44725. + return retval;
  44726. +}
  44727. +
  44728. +static zend_object_value sqlite_object_new_query(zend_class_entry *class_type TSRMLS_DC)
  44729. +{
  44730. + zend_object_value retval;
  44731. +
  44732. + sqlite_object_new(class_type, &sqlite_object_handlers_query, &retval TSRMLS_CC);
  44733. + return retval;
  44734. +}
  44735. +
  44736. +static zend_object_value sqlite_object_new_ub_query(zend_class_entry *class_type TSRMLS_DC)
  44737. +{
  44738. + zend_object_value retval;
  44739. +
  44740. + sqlite_object_new(class_type, &sqlite_object_handlers_ub_query, &retval TSRMLS_CC);
  44741. + return retval;
  44742. +}
  44743. +
  44744. +static zend_object_value sqlite_object_new_exception(zend_class_entry *class_type TSRMLS_DC)
  44745. +{
  44746. + zend_object_value retval;
  44747. +
  44748. + sqlite_object_new(class_type, &sqlite_object_handlers_exception, &retval TSRMLS_CC);
  44749. + return retval;
  44750. +}
  44751. +
  44752. +#define SQLITE_REGISTER_OBJECT(_type, _object, _ptr) \
  44753. + { \
  44754. + sqlite_object *obj; \
  44755. + obj = (sqlite_object*)zend_object_store_get_object(_object TSRMLS_CC); \
  44756. + obj->type = is_ ## _type; \
  44757. + obj->u._type = _ptr; \
  44758. + }
  44759. +
  44760. +static zend_class_entry *sqlite_get_ce_query(const zval *object TSRMLS_DC)
  44761. +{
  44762. + return sqlite_ce_query;
  44763. +}
  44764. +
  44765. +static zend_class_entry *sqlite_get_ce_ub_query(const zval *object TSRMLS_DC)
  44766. +{
  44767. + return sqlite_ce_ub_query;
  44768. +}
  44769. +
  44770. +static zval * sqlite_instanciate(zend_class_entry *pce, zval *object TSRMLS_DC)
  44771. +{
  44772. + if (!object) {
  44773. + ALLOC_ZVAL(object);
  44774. + }
  44775. + Z_TYPE_P(object) = IS_OBJECT;
  44776. + object_init_ex(object, pce);
  44777. + Z_SET_REFCOUNT_P(object, 1);
  44778. + Z_SET_ISREF_P(object);
  44779. + return object;
  44780. +}
  44781. +
  44782. +typedef struct _sqlite_object_iterator {
  44783. + zend_object_iterator it;
  44784. + struct php_sqlite_result *res;
  44785. + zval *value;
  44786. +} sqlite_object_iterator;
  44787. +
  44788. +void sqlite_iterator_dtor(zend_object_iterator *iter TSRMLS_DC)
  44789. +{
  44790. + zval *object = (zval*)((sqlite_object_iterator*)iter)->it.data;
  44791. +
  44792. + if (((sqlite_object_iterator*)iter)->value) {
  44793. + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
  44794. + ((sqlite_object_iterator*)iter)->value = NULL;
  44795. + }
  44796. + zval_ptr_dtor(&object);
  44797. + efree(iter);
  44798. +}
  44799. +
  44800. +void sqlite_iterator_rewind(zend_object_iterator *iter TSRMLS_DC)
  44801. +{
  44802. + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
  44803. +
  44804. + if (((sqlite_object_iterator*)iter)->value) {
  44805. + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
  44806. + ((sqlite_object_iterator*)iter)->value = NULL;
  44807. + }
  44808. + if (res) {
  44809. + res->curr_row = 0;
  44810. + }
  44811. +}
  44812. +
  44813. +int sqlite_iterator_valid(zend_object_iterator *iter TSRMLS_DC)
  44814. +{
  44815. + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
  44816. +
  44817. + if (res && res->curr_row < res->nrows && res->nrows) { /* curr_row may be -1 */
  44818. + return SUCCESS;
  44819. + } else {
  44820. + return FAILURE;
  44821. + }
  44822. +}
  44823. +
  44824. +void sqlite_iterator_get_current_data(zend_object_iterator *iter, zval ***data TSRMLS_DC)
  44825. +{
  44826. + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
  44827. +
  44828. + *data = &((sqlite_object_iterator*)iter)->value;
  44829. + if (res && !**data) {
  44830. + MAKE_STD_ZVAL(**data);
  44831. + php_sqlite_fetch_array(res, res->mode, 1, 0, **data TSRMLS_CC);
  44832. + }
  44833. +
  44834. +}
  44835. +
  44836. +int sqlite_iterator_get_current_key(zend_object_iterator *iter, char **str_key, uint *str_key_len, ulong *int_key TSRMLS_DC)
  44837. +{
  44838. + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
  44839. +
  44840. + *str_key = NULL;
  44841. + *str_key_len = 0;
  44842. + *int_key = res ? res->curr_row : 0;
  44843. + return HASH_KEY_IS_LONG;
  44844. +}
  44845. +
  44846. +void sqlite_iterator_move_forward(zend_object_iterator *iter TSRMLS_DC)
  44847. +{
  44848. + struct php_sqlite_result *res = ((sqlite_object_iterator*)iter)->res;
  44849. +
  44850. + if (((sqlite_object_iterator*)iter)->value) {
  44851. + zval_ptr_dtor(&((sqlite_object_iterator*)iter)->value);
  44852. + ((sqlite_object_iterator*)iter)->value = NULL;
  44853. + }
  44854. + if (res) {
  44855. + if (!res->buffered && res->vm) {
  44856. + php_sqlite_fetch(res TSRMLS_CC);
  44857. + }
  44858. + if (res->curr_row >= res->nrows) {
  44859. + /* php_error_docref(NULL TSRMLS_CC, E_WARNING, "no more rows available"); */
  44860. + return;
  44861. + }
  44862. +
  44863. + res->curr_row++;
  44864. + }
  44865. +}
  44866. +
  44867. +zend_object_iterator_funcs sqlite_ub_query_iterator_funcs = {
  44868. + sqlite_iterator_dtor,
  44869. + sqlite_iterator_valid,
  44870. + sqlite_iterator_get_current_data,
  44871. + sqlite_iterator_get_current_key,
  44872. + sqlite_iterator_move_forward,
  44873. + NULL
  44874. +};
  44875. +
  44876. +zend_object_iterator_funcs sqlite_query_iterator_funcs = {
  44877. + sqlite_iterator_dtor,
  44878. + sqlite_iterator_valid,
  44879. + sqlite_iterator_get_current_data,
  44880. + sqlite_iterator_get_current_key,
  44881. + sqlite_iterator_move_forward,
  44882. + sqlite_iterator_rewind
  44883. +};
  44884. +
  44885. +zend_object_iterator *sqlite_get_iterator(zend_class_entry *ce, zval *object, int by_ref TSRMLS_DC)
  44886. +{
  44887. + sqlite_object_iterator *iterator = emalloc(sizeof(sqlite_object_iterator));
  44888. +
  44889. + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC);
  44890. +
  44891. + if (by_ref) {
  44892. + zend_error(E_RECOVERABLE_ERROR, "An iterator cannot be used with foreach by reference");
  44893. + }
  44894. + Z_ADDREF_P(object);
  44895. + iterator->it.data = (void*)object;
  44896. + iterator->it.funcs = ce->iterator_funcs.funcs;
  44897. + iterator->res = obj->u.res;
  44898. + iterator->value = NULL;
  44899. + return (zend_object_iterator*)iterator;
  44900. +}
  44901. +/* }}} */
  44902. +
  44903. +static PHP_GINIT_FUNCTION(sqlite)
  44904. +{
  44905. + sqlite_globals->assoc_case = 0;
  44906. +}
  44907. +
  44908. +PHP_MINIT_FUNCTION(sqlite)
  44909. +{
  44910. + REGISTER_SQLITE_CLASS(Database, db, NULL);
  44911. + REGISTER_SQLITE_CLASS(Result, query, NULL);
  44912. + REGISTER_SQLITE_CLASS(Unbuffered, ub_query, NULL);
  44913. +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
  44914. + REGISTER_SQLITE_CLASS(Exception, exception, spl_ce_RuntimeException);
  44915. +#else
  44916. + REGISTER_SQLITE_CLASS(Exception, exception, zend_exception_get_default(TSRMLS_C));
  44917. +#endif
  44918. +
  44919. + sqlite_ce_db->ce_flags &= ~ZEND_ACC_FINAL_CLASS;
  44920. + sqlite_ce_db->constructor->common.fn_flags |= ZEND_ACC_FINAL;
  44921. +
  44922. + sqlite_object_handlers_query.get_class_entry = sqlite_get_ce_query;
  44923. + sqlite_object_handlers_ub_query.get_class_entry = sqlite_get_ce_ub_query;
  44924. + sqlite_object_handlers_ub_query.count_elements = sqlite_count_elements;
  44925. +
  44926. + sqlite_ce_ub_query->get_iterator = sqlite_get_iterator;
  44927. + sqlite_ce_ub_query->iterator_funcs.funcs = &sqlite_ub_query_iterator_funcs;
  44928. +
  44929. +#if defined(HAVE_SPL) && ((PHP_MAJOR_VERSION > 5) || (PHP_MAJOR_VERSION == 5 && PHP_MINOR_VERSION >= 1))
  44930. + zend_class_implements(sqlite_ce_query TSRMLS_CC, 2, zend_ce_iterator, spl_ce_Countable);
  44931. +#else
  44932. + zend_class_implements(sqlite_ce_query TSRMLS_CC, 1, zend_ce_iterator);
  44933. +#endif
  44934. + sqlite_ce_query->get_iterator = sqlite_get_iterator;
  44935. + sqlite_ce_query->iterator_funcs.funcs = &sqlite_query_iterator_funcs;
  44936. +
  44937. + REGISTER_INI_ENTRIES();
  44938. +
  44939. +#if HAVE_PHP_SESSION && !defined(COMPILE_DL_SESSION)
  44940. + php_session_register_module(ps_sqlite_ptr);
  44941. +#endif
  44942. +
  44943. + le_sqlite_db = zend_register_list_destructors_ex(php_sqlite_db_dtor, NULL, "sqlite database", module_number);
  44944. + le_sqlite_pdb = zend_register_list_destructors_ex(NULL, php_sqlite_db_dtor, "sqlite database (persistent)", module_number);
  44945. + le_sqlite_result = zend_register_list_destructors_ex(php_sqlite_result_dtor, NULL, "sqlite result", module_number);
  44946. +
  44947. + REGISTER_LONG_CONSTANT("SQLITE_BOTH", PHPSQLITE_BOTH, CONST_CS|CONST_PERSISTENT);
  44948. + REGISTER_LONG_CONSTANT("SQLITE_NUM", PHPSQLITE_NUM, CONST_CS|CONST_PERSISTENT);
  44949. + REGISTER_LONG_CONSTANT("SQLITE_ASSOC", PHPSQLITE_ASSOC, CONST_CS|CONST_PERSISTENT);
  44950. +
  44951. + REGISTER_LONG_CONSTANT("SQLITE_OK", SQLITE_OK, CONST_CS|CONST_PERSISTENT);
  44952. + REGISTER_LONG_CONSTANT("SQLITE_ERROR", SQLITE_ERROR, CONST_CS|CONST_PERSISTENT);
  44953. + REGISTER_LONG_CONSTANT("SQLITE_INTERNAL", SQLITE_INTERNAL, CONST_CS|CONST_PERSISTENT);
  44954. + REGISTER_LONG_CONSTANT("SQLITE_PERM", SQLITE_PERM, CONST_CS|CONST_PERSISTENT);
  44955. + REGISTER_LONG_CONSTANT("SQLITE_ABORT", SQLITE_ABORT, CONST_CS|CONST_PERSISTENT);
  44956. + REGISTER_LONG_CONSTANT("SQLITE_BUSY", SQLITE_BUSY, CONST_CS|CONST_PERSISTENT);
  44957. + REGISTER_LONG_CONSTANT("SQLITE_LOCKED", SQLITE_LOCKED, CONST_CS|CONST_PERSISTENT);
  44958. + REGISTER_LONG_CONSTANT("SQLITE_NOMEM", SQLITE_NOMEM, CONST_CS|CONST_PERSISTENT);
  44959. + REGISTER_LONG_CONSTANT("SQLITE_READONLY", SQLITE_READONLY, CONST_CS|CONST_PERSISTENT);
  44960. + REGISTER_LONG_CONSTANT("SQLITE_INTERRUPT", SQLITE_INTERRUPT, CONST_CS|CONST_PERSISTENT);
  44961. + REGISTER_LONG_CONSTANT("SQLITE_IOERR", SQLITE_IOERR, CONST_CS|CONST_PERSISTENT);
  44962. + REGISTER_LONG_CONSTANT("SQLITE_CORRUPT", SQLITE_CORRUPT, CONST_CS|CONST_PERSISTENT);
  44963. + REGISTER_LONG_CONSTANT("SQLITE_NOTFOUND", SQLITE_NOTFOUND, CONST_CS|CONST_PERSISTENT);
  44964. + REGISTER_LONG_CONSTANT("SQLITE_FULL", SQLITE_FULL, CONST_CS|CONST_PERSISTENT);
  44965. + REGISTER_LONG_CONSTANT("SQLITE_CANTOPEN", SQLITE_CANTOPEN, CONST_CS|CONST_PERSISTENT);
  44966. + REGISTER_LONG_CONSTANT("SQLITE_PROTOCOL", SQLITE_PROTOCOL, CONST_CS|CONST_PERSISTENT);
  44967. + REGISTER_LONG_CONSTANT("SQLITE_EMPTY", SQLITE_EMPTY, CONST_CS|CONST_PERSISTENT);
  44968. + REGISTER_LONG_CONSTANT("SQLITE_SCHEMA", SQLITE_SCHEMA, CONST_CS|CONST_PERSISTENT);
  44969. + REGISTER_LONG_CONSTANT("SQLITE_TOOBIG", SQLITE_TOOBIG, CONST_CS|CONST_PERSISTENT);
  44970. + REGISTER_LONG_CONSTANT("SQLITE_CONSTRAINT", SQLITE_CONSTRAINT, CONST_CS|CONST_PERSISTENT);
  44971. + REGISTER_LONG_CONSTANT("SQLITE_MISMATCH", SQLITE_MISMATCH, CONST_CS|CONST_PERSISTENT);
  44972. + REGISTER_LONG_CONSTANT("SQLITE_MISUSE", SQLITE_MISUSE, CONST_CS|CONST_PERSISTENT);
  44973. + REGISTER_LONG_CONSTANT("SQLITE_NOLFS", SQLITE_NOLFS, CONST_CS|CONST_PERSISTENT);
  44974. + REGISTER_LONG_CONSTANT("SQLITE_AUTH", SQLITE_AUTH, CONST_CS|CONST_PERSISTENT);
  44975. + REGISTER_LONG_CONSTANT("SQLITE_NOTADB", SQLITE_NOTADB, CONST_CS|CONST_PERSISTENT);
  44976. +#ifdef SQLITE_FORMAT
  44977. + REGISTER_LONG_CONSTANT("SQLITE_FORMAT", SQLITE_FORMAT, CONST_CS|CONST_PERSISTENT);
  44978. +#endif
  44979. + REGISTER_LONG_CONSTANT("SQLITE_ROW", SQLITE_ROW, CONST_CS|CONST_PERSISTENT);
  44980. + REGISTER_LONG_CONSTANT("SQLITE_DONE", SQLITE_DONE, CONST_CS|CONST_PERSISTENT);
  44981. +
  44982. +#ifdef PHP_SQLITE2_HAVE_PDO
  44983. + if (FAILURE == php_pdo_register_driver(&pdo_sqlite2_driver)) {
  44984. + return FAILURE;
  44985. + }
  44986. +#endif
  44987. +
  44988. + return SUCCESS;
  44989. +}
  44990. +
  44991. +PHP_MSHUTDOWN_FUNCTION(sqlite)
  44992. +{
  44993. + UNREGISTER_INI_ENTRIES();
  44994. +
  44995. +#ifdef PHP_SQLITE2_HAVE_PDO
  44996. + php_pdo_unregister_driver(&pdo_sqlite2_driver);
  44997. +#endif
  44998. +
  44999. + return SUCCESS;
  45000. +}
  45001. +
  45002. +PHP_MINFO_FUNCTION(sqlite)
  45003. +{
  45004. + php_info_print_table_start();
  45005. + php_info_print_table_header(2, "SQLite support", "enabled");
  45006. + php_info_print_table_row(2, "PECL Module version", PHP_SQLITE_MODULE_VERSION " $Id$");
  45007. + php_info_print_table_row(2, "SQLite Library", sqlite_libversion());
  45008. + php_info_print_table_row(2, "SQLite Encoding", sqlite_libencoding());
  45009. + php_info_print_table_end();
  45010. +
  45011. + DISPLAY_INI_ENTRIES();
  45012. +}
  45013. +
  45014. +static struct php_sqlite_db *php_sqlite_open(char *filename, int mode, char *persistent_id, zval *return_value, zval *errmsg, zval *object TSRMLS_DC)
  45015. +{
  45016. + char *errtext = NULL;
  45017. + sqlite *sdb = NULL;
  45018. + struct php_sqlite_db *db = NULL;
  45019. +
  45020. + sdb = sqlite_open(filename, mode, &errtext);
  45021. +
  45022. + if (sdb == NULL) {
  45023. +
  45024. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45025. +
  45026. + if (errmsg) {
  45027. + ZVAL_STRING(errmsg, errtext, 1);
  45028. + }
  45029. +
  45030. + sqlite_freemem(errtext);
  45031. +
  45032. + /* if object is not an object then we're called from the factory() function */
  45033. + if (object && Z_TYPE_P(object) != IS_OBJECT) {
  45034. + RETVAL_NULL();
  45035. + } else {
  45036. + RETVAL_FALSE;
  45037. + }
  45038. + return NULL;
  45039. + }
  45040. +
  45041. + db = (struct php_sqlite_db *)pemalloc(sizeof(struct php_sqlite_db), persistent_id ? 1 : 0);
  45042. + db->is_persistent = persistent_id ? 1 : 0;
  45043. + db->last_err_code = SQLITE_OK;
  45044. + db->db = sdb;
  45045. +
  45046. + zend_hash_init(&db->callbacks, 0, NULL, php_sqlite_callback_dtor, db->is_persistent);
  45047. +
  45048. + /* register the PHP functions */
  45049. + sqlite_create_function(sdb, "php", -1, php_sqlite_generic_function_callback, 0);
  45050. +
  45051. + /* set default busy handler; keep retrying up until 1 minute has passed,
  45052. + * then fail with a busy status code */
  45053. + sqlite_busy_timeout(sdb, 60000);
  45054. +
  45055. + /* authorizer hook so we can enforce safe mode
  45056. + * Note: the declaration of php_sqlite_authorizer is correct for 2.8.2 of libsqlite,
  45057. + * and IS backwards binary compatible with earlier versions */
  45058. + if (PG(safe_mode) || (PG(open_basedir) && *PG(open_basedir))) {
  45059. + sqlite_set_authorizer(sdb, php_sqlite_authorizer, NULL);
  45060. + }
  45061. +
  45062. + db->rsrc_id = ZEND_REGISTER_RESOURCE(object ? NULL : return_value, db, persistent_id ? le_sqlite_pdb : le_sqlite_db);
  45063. + if (object) {
  45064. + /* if object is not an object then we're called from the factory() function */
  45065. + if (Z_TYPE_P(object) != IS_OBJECT) {
  45066. + sqlite_instanciate(sqlite_ce_db, object TSRMLS_CC);
  45067. + }
  45068. + /* and now register the object */
  45069. + SQLITE_REGISTER_OBJECT(db, object, db)
  45070. + }
  45071. +
  45072. + if (persistent_id) {
  45073. + zend_rsrc_list_entry le;
  45074. +
  45075. + Z_TYPE(le) = le_sqlite_pdb;
  45076. + le.ptr = db;
  45077. +
  45078. + if (FAILURE == zend_hash_update(&EG(persistent_list), persistent_id,
  45079. + strlen(persistent_id)+1,
  45080. + (void *)&le, sizeof(le), NULL)) {
  45081. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Failed to register persistent resource");
  45082. + }
  45083. + }
  45084. +
  45085. + return db;
  45086. +}
  45087. +
  45088. +/* {{{ proto resource sqlite_popen(string filename [, int mode [, string &error_message]])
  45089. + Opens a persistent handle to a SQLite database. Will create the database if it does not exist. */
  45090. +PHP_FUNCTION(sqlite_popen)
  45091. +{
  45092. + long mode = 0666;
  45093. + char *filename, *fullpath, *hashkey;
  45094. + int filename_len, hashkeylen;
  45095. + zval *errmsg = NULL;
  45096. + struct php_sqlite_db *db = NULL;
  45097. + zend_rsrc_list_entry *le;
  45098. +
  45099. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
  45100. + &filename, &filename_len, &mode, &errmsg)) {
  45101. + return;
  45102. + }
  45103. + if (errmsg) {
  45104. + zval_dtor(errmsg);
  45105. + ZVAL_NULL(errmsg);
  45106. + }
  45107. +
  45108. + if (strlen(filename) != filename_len) {
  45109. + RETURN_FALSE;
  45110. + }
  45111. + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
  45112. + /* resolve the fully-qualified path name to use as the hash key */
  45113. + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
  45114. + RETURN_FALSE;
  45115. + }
  45116. +
  45117. + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
  45118. + php_check_open_basedir(fullpath TSRMLS_CC)) {
  45119. + efree(fullpath);
  45120. + RETURN_FALSE;
  45121. + }
  45122. + } else {
  45123. + fullpath = estrndup(filename, filename_len);
  45124. + }
  45125. +
  45126. + hashkeylen = spprintf(&hashkey, 0, "sqlite_pdb_%s:%ld", fullpath, mode);
  45127. +
  45128. + /* do we have an existing persistent connection ? */
  45129. + if (SUCCESS == zend_hash_find(&EG(persistent_list), hashkey, hashkeylen+1, (void*)&le)) {
  45130. + if (Z_TYPE_P(le) == le_sqlite_pdb) {
  45131. + db = (struct php_sqlite_db*)le->ptr;
  45132. +
  45133. + if (db->rsrc_id == FAILURE) {
  45134. + /* give it a valid resource id for this request */
  45135. + db->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, db, le_sqlite_pdb);
  45136. + } else {
  45137. + int type;
  45138. + /* sanity check to ensure that the resource is still a valid regular resource
  45139. + * number */
  45140. + if (zend_list_find(db->rsrc_id, &type) == db) {
  45141. + /* already accessed this request; map it */
  45142. + zend_list_addref(db->rsrc_id);
  45143. + ZVAL_RESOURCE(return_value, db->rsrc_id);
  45144. + } else {
  45145. + db->rsrc_id = ZEND_REGISTER_RESOURCE(return_value, db, le_sqlite_pdb);
  45146. + }
  45147. + }
  45148. +
  45149. + /* all set */
  45150. + goto done;
  45151. + }
  45152. +
  45153. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Some other type of persistent resource is using this hash key!?");
  45154. + RETVAL_FALSE;
  45155. + goto done;
  45156. + }
  45157. +
  45158. + /* now we need to open the database */
  45159. + php_sqlite_open(fullpath, (int)mode, hashkey, return_value, errmsg, NULL TSRMLS_CC);
  45160. +done:
  45161. + efree(fullpath);
  45162. + efree(hashkey);
  45163. +}
  45164. +/* }}} */
  45165. +
  45166. +/* {{{ proto resource sqlite_open(string filename [, int mode [, string &error_message]])
  45167. + Opens a SQLite database. Will create the database if it does not exist. */
  45168. +PHP_FUNCTION(sqlite_open)
  45169. +{
  45170. + long mode = 0666;
  45171. + char *filename, *fullpath = NULL;
  45172. + int filename_len;
  45173. + zval *errmsg = NULL;
  45174. + zval *object = getThis();
  45175. + zend_error_handling error_handling;
  45176. +
  45177. + zend_replace_error_handling(object ? EH_THROW : EH_NORMAL, sqlite_ce_exception, &error_handling TSRMLS_CC);
  45178. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
  45179. + &filename, &filename_len, &mode, &errmsg)) {
  45180. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45181. + return;
  45182. + }
  45183. + if (errmsg) {
  45184. + zval_dtor(errmsg);
  45185. + ZVAL_NULL(errmsg);
  45186. + }
  45187. +
  45188. + if (strlen(filename) != filename_len) {
  45189. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45190. + RETURN_FALSE;
  45191. + }
  45192. +
  45193. + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
  45194. + /* resolve the fully-qualified path name to use as the hash key */
  45195. + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
  45196. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45197. + if (object) {
  45198. + RETURN_NULL();
  45199. + } else {
  45200. + RETURN_FALSE;
  45201. + }
  45202. + }
  45203. +
  45204. + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
  45205. + php_check_open_basedir(fullpath TSRMLS_CC)) {
  45206. + efree(fullpath);
  45207. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45208. + if (object) {
  45209. + RETURN_NULL();
  45210. + } else {
  45211. + RETURN_FALSE;
  45212. + }
  45213. + }
  45214. + }
  45215. +
  45216. + php_sqlite_open(fullpath ? fullpath : filename, (int)mode, NULL, return_value, errmsg, object TSRMLS_CC);
  45217. +
  45218. + if (fullpath) {
  45219. + efree(fullpath);
  45220. + }
  45221. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45222. +}
  45223. +/* }}} */
  45224. +
  45225. +/* {{{ proto object sqlite_factory(string filename [, int mode [, string &error_message]])
  45226. + Opens a SQLite database and creates an object for it. Will create the database if it does not exist. */
  45227. +PHP_FUNCTION(sqlite_factory)
  45228. +{
  45229. + long mode = 0666;
  45230. + char *filename, *fullpath = NULL;
  45231. + int filename_len;
  45232. + zval *errmsg = NULL;
  45233. + zend_error_handling error_handling;
  45234. +
  45235. + zend_replace_error_handling(EH_THROW, sqlite_ce_exception, &error_handling TSRMLS_CC);
  45236. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/",
  45237. + &filename, &filename_len, &mode, &errmsg)) {
  45238. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45239. + RETURN_NULL();
  45240. + }
  45241. + if (errmsg) {
  45242. + zval_dtor(errmsg);
  45243. + ZVAL_NULL(errmsg);
  45244. + }
  45245. +
  45246. + if (strlen(filename) != filename_len) {
  45247. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45248. + RETURN_FALSE;
  45249. + }
  45250. +
  45251. + if (strncmp(filename, ":memory:", sizeof(":memory:") - 1)) {
  45252. + /* resolve the fully-qualified path name to use as the hash key */
  45253. + if (!(fullpath = expand_filepath(filename, NULL TSRMLS_CC))) {
  45254. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45255. + RETURN_NULL();
  45256. + }
  45257. +
  45258. + if ((PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) ||
  45259. + php_check_open_basedir(fullpath TSRMLS_CC)) {
  45260. + efree(fullpath);
  45261. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45262. + RETURN_NULL();
  45263. + }
  45264. + }
  45265. +
  45266. + php_sqlite_open(fullpath ? fullpath : filename, (int)mode, NULL, return_value, errmsg, return_value TSRMLS_CC);
  45267. + if (fullpath) {
  45268. + efree(fullpath);
  45269. + }
  45270. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45271. +}
  45272. +/* }}} */
  45273. +
  45274. +/* {{{ proto void sqlite_busy_timeout(resource db, int ms)
  45275. + Set busy timeout duration. If ms <= 0, all busy handlers are disabled. */
  45276. +PHP_FUNCTION(sqlite_busy_timeout)
  45277. +{
  45278. + zval *zdb;
  45279. + struct php_sqlite_db *db;
  45280. + long ms;
  45281. + zval *object = getThis();
  45282. +
  45283. + if (object) {
  45284. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &ms)) {
  45285. + return;
  45286. + }
  45287. + DB_FROM_OBJECT(db, object);
  45288. + } else {
  45289. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zdb, &ms)) {
  45290. + return;
  45291. + }
  45292. + DB_FROM_ZVAL(db, &zdb);
  45293. + }
  45294. +
  45295. + sqlite_busy_timeout(db->db, ms);
  45296. +}
  45297. +/* }}} */
  45298. +
  45299. +/* {{{ proto void sqlite_close(resource db)
  45300. + Closes an open sqlite database. */
  45301. +PHP_FUNCTION(sqlite_close)
  45302. +{
  45303. + zval *zdb;
  45304. + struct php_sqlite_db *db;
  45305. + zval *object = getThis();
  45306. +
  45307. + if (object) {
  45308. + php_error_docref(NULL TSRMLS_CC, E_NOTICE, "Ignored, you must destruct the object instead");
  45309. + } else {
  45310. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
  45311. + return;
  45312. + }
  45313. + DB_FROM_ZVAL(db, &zdb);
  45314. + }
  45315. +
  45316. + zend_hash_apply_with_argument(&EG(regular_list),
  45317. + (apply_func_arg_t) _clean_unfinished_results,
  45318. + db TSRMLS_CC);
  45319. +
  45320. + zend_list_delete(Z_RESVAL_P(zdb));
  45321. +}
  45322. +/* }}} */
  45323. +
  45324. +/* {{{ php_sqlite_fetch */
  45325. +static int php_sqlite_fetch(struct php_sqlite_result *rres TSRMLS_DC)
  45326. +{
  45327. + const char **rowdata, **colnames;
  45328. + int ret, i, base;
  45329. + char *errtext = NULL;
  45330. +
  45331. +next_row:
  45332. + ret = sqlite_step(rres->vm, &rres->ncolumns, &rowdata, &colnames);
  45333. + if (!rres->nrows) {
  45334. + /* first row - lets copy the column names */
  45335. + rres->col_names = safe_emalloc(rres->ncolumns, sizeof(char *), 0);
  45336. + for (i = 0; i < rres->ncolumns; i++) {
  45337. + rres->col_names[i] = estrdup((char*)colnames[i]);
  45338. +
  45339. + if (SQLITE_G(assoc_case) == 1) {
  45340. + php_sqlite_strtoupper(rres->col_names[i]);
  45341. + } else if (SQLITE_G(assoc_case) == 2) {
  45342. + php_sqlite_strtolower(rres->col_names[i]);
  45343. + }
  45344. + }
  45345. + if (!rres->buffered) {
  45346. + /* non buffered mode - also fetch memory for on single row */
  45347. + rres->table = safe_emalloc(rres->ncolumns, sizeof(char *), 0);
  45348. + }
  45349. + }
  45350. +
  45351. + switch (ret) {
  45352. + case SQLITE_ROW:
  45353. + if (rres->buffered) {
  45354. + /* add the row to our collection */
  45355. + if (rres->nrows + 1 >= rres->alloc_rows) {
  45356. + rres->alloc_rows = rres->alloc_rows ? rres->alloc_rows * 2 : 16;
  45357. + rres->table = safe_erealloc(rres->table, rres->alloc_rows, rres->ncolumns*sizeof(char *), 0);
  45358. + }
  45359. + base = rres->nrows * rres->ncolumns;
  45360. + for (i = 0; i < rres->ncolumns; i++) {
  45361. + if (rowdata[i]) {
  45362. + rres->table[base + i] = estrdup(rowdata[i]);
  45363. + } else {
  45364. + rres->table[base + i] = NULL;
  45365. + }
  45366. + }
  45367. + rres->nrows++;
  45368. + goto next_row;
  45369. + } else {
  45370. + /* non buffered: only fetch one row but first free data if not first row */
  45371. + if (rres->nrows++) {
  45372. + for (i = 0; i < rres->ncolumns; i++) {
  45373. + if (rres->table[i]) {
  45374. + efree(rres->table[i]);
  45375. + }
  45376. + }
  45377. + }
  45378. + for (i = 0; i < rres->ncolumns; i++) {
  45379. + if (rowdata[i]) {
  45380. + rres->table[i] = estrdup(rowdata[i]);
  45381. + } else {
  45382. + rres->table[i] = NULL;
  45383. + }
  45384. + }
  45385. + }
  45386. + ret = SQLITE_OK;
  45387. + break;
  45388. +
  45389. + case SQLITE_BUSY:
  45390. + case SQLITE_ERROR:
  45391. + case SQLITE_MISUSE:
  45392. + case SQLITE_DONE:
  45393. + default:
  45394. + if (rres->vm) {
  45395. + ret = sqlite_finalize(rres->vm, &errtext);
  45396. + }
  45397. + rres->vm = NULL;
  45398. + if (ret != SQLITE_OK) {
  45399. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45400. + sqlite_freemem(errtext);
  45401. + }
  45402. + break;
  45403. + }
  45404. + rres->db->last_err_code = ret;
  45405. +
  45406. + return ret;
  45407. +}
  45408. +/* }}} */
  45409. +
  45410. +/* {{{ sqlite_query */
  45411. +void sqlite_query(zval *object, struct php_sqlite_db *db, char *sql, long sql_len, int mode, int buffered, zval *return_value, struct php_sqlite_result **prres, zval *errmsg TSRMLS_DC)
  45412. +{
  45413. + struct php_sqlite_result res, *rres;
  45414. + int ret;
  45415. + char *errtext = NULL;
  45416. + const char *tail;
  45417. +
  45418. + memset(&res, 0, sizeof(res));
  45419. + res.buffered = buffered;
  45420. + res.mode = mode;
  45421. +
  45422. + ret = sqlite_compile(db->db, sql, &tail, &res.vm, &errtext);
  45423. + db->last_err_code = ret;
  45424. +
  45425. + if (ret != SQLITE_OK) {
  45426. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45427. + if (errmsg) {
  45428. + ZVAL_STRING(errmsg, errtext, 1);
  45429. + }
  45430. + sqlite_freemem(errtext);
  45431. + goto terminate;
  45432. + } else if (!res.vm) { /* empty query */
  45433. +terminate:
  45434. + if (return_value) {
  45435. + RETURN_FALSE;
  45436. + } else {
  45437. + return;
  45438. + }
  45439. + }
  45440. +
  45441. + if (!prres) {
  45442. + rres = NULL;
  45443. + prres = &rres;
  45444. + }
  45445. + if (!*prres) {
  45446. + *prres = (struct php_sqlite_result*)emalloc(sizeof(**prres));
  45447. + }
  45448. + memcpy(*prres, &res, sizeof(**prres));
  45449. + (*prres)->db = db;
  45450. + zend_list_addref(db->rsrc_id);
  45451. +
  45452. +
  45453. + /* now the result set is ready for stepping: get first row */
  45454. + if (php_sqlite_fetch((*prres) TSRMLS_CC) != SQLITE_OK) {
  45455. + real_result_dtor((*prres) TSRMLS_CC);
  45456. + *prres = NULL;
  45457. + if (return_value) {
  45458. + RETURN_FALSE;
  45459. + } else {
  45460. + return;
  45461. + }
  45462. + }
  45463. +
  45464. + (*prres)->curr_row = 0;
  45465. +
  45466. + if (object) {
  45467. + sqlite_object *obj;
  45468. + if (buffered) {
  45469. + sqlite_instanciate(sqlite_ce_query, return_value TSRMLS_CC);
  45470. + } else {
  45471. + sqlite_instanciate(sqlite_ce_ub_query, return_value TSRMLS_CC);
  45472. + }
  45473. + obj = (sqlite_object *) zend_object_store_get_object(return_value TSRMLS_CC);
  45474. + obj->type = is_result;
  45475. + obj->u.res = (*prres);
  45476. + } else if (return_value) {
  45477. + ZEND_REGISTER_RESOURCE(object ? NULL : return_value, (*prres), le_sqlite_result);
  45478. + }
  45479. +}
  45480. +/* }}} */
  45481. +
  45482. +/* {{{ proto resource sqlite_unbuffered_query(string query, resource db [ , int result_type [, string &error_message]])
  45483. + Executes a query that does not prefetch and buffer all data. */
  45484. +PHP_FUNCTION(sqlite_unbuffered_query)
  45485. +{
  45486. + zval *zdb;
  45487. + struct php_sqlite_db *db;
  45488. + char *sql;
  45489. + int sql_len;
  45490. + long mode = PHPSQLITE_BOTH;
  45491. + char *errtext = NULL;
  45492. + zval *errmsg = NULL;
  45493. + zval *object = getThis();
  45494. +
  45495. + if (object) {
  45496. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/", &sql, &sql_len, &mode, &errmsg)) {
  45497. + return;
  45498. + }
  45499. + DB_FROM_OBJECT(db, object);
  45500. + } else {
  45501. + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  45502. + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lz/", &sql, &sql_len, &zdb, &mode, &errmsg) &&
  45503. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lz/", &zdb, &sql, &sql_len, &mode, &errmsg)) {
  45504. + return;
  45505. + }
  45506. + DB_FROM_ZVAL(db, &zdb);
  45507. + }
  45508. +
  45509. + if (errmsg) {
  45510. + zval_dtor(errmsg);
  45511. + ZVAL_NULL(errmsg);
  45512. + }
  45513. +
  45514. + PHP_SQLITE_EMPTY_QUERY;
  45515. +
  45516. + /* avoid doing work if we can */
  45517. + if (!return_value_used) {
  45518. + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
  45519. +
  45520. + if (db->last_err_code != SQLITE_OK) {
  45521. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45522. + if (errmsg) {
  45523. + ZVAL_STRING(errmsg, errtext, 1);
  45524. + }
  45525. + sqlite_freemem(errtext);
  45526. + }
  45527. + return;
  45528. + }
  45529. +
  45530. + sqlite_query(object, db, sql, sql_len, (int)mode, 0, return_value, NULL, errmsg TSRMLS_CC);
  45531. +}
  45532. +/* }}} */
  45533. +
  45534. +/* {{{ proto resource sqlite_fetch_column_types(string table_name, resource db [, int result_type])
  45535. + Return an array of column types from a particular table. */
  45536. +PHP_FUNCTION(sqlite_fetch_column_types)
  45537. +{
  45538. + zval *zdb;
  45539. + struct php_sqlite_db *db;
  45540. + char *tbl, *sql;
  45541. + int tbl_len;
  45542. + char *errtext = NULL;
  45543. + zval *object = getThis();
  45544. + struct php_sqlite_result res;
  45545. + const char **rowdata, **colnames, *tail;
  45546. + int i, ncols;
  45547. + long result_type = PHPSQLITE_ASSOC;
  45548. +
  45549. + if (object) {
  45550. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &tbl, &tbl_len, &result_type)) {
  45551. + return;
  45552. + }
  45553. + DB_FROM_OBJECT(db, object);
  45554. + } else {
  45555. + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  45556. + ZEND_NUM_ARGS() TSRMLS_CC, "sr|l", &tbl, &tbl_len, &zdb, &result_type) &&
  45557. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|l", &zdb, &tbl, &tbl_len, &result_type)) {
  45558. + return;
  45559. + }
  45560. + DB_FROM_ZVAL(db, &zdb);
  45561. + }
  45562. +
  45563. + if (!(sql = sqlite_mprintf("SELECT * FROM '%q' LIMIT 1", tbl))) {
  45564. + RETURN_FALSE;
  45565. + }
  45566. +
  45567. + sqlite_exec(db->db, "PRAGMA show_datatypes = ON", NULL, NULL, NULL);
  45568. +
  45569. + db->last_err_code = sqlite_compile(db->db, sql, &tail, &res.vm, &errtext);
  45570. +
  45571. + sqlite_freemem(sql);
  45572. +
  45573. + if (db->last_err_code != SQLITE_OK) {
  45574. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45575. + sqlite_freemem(errtext);
  45576. + RETVAL_FALSE;
  45577. + goto done;
  45578. + }
  45579. +
  45580. + sqlite_step(res.vm, &ncols, &rowdata, &colnames);
  45581. +
  45582. + array_init(return_value);
  45583. +
  45584. + for (i = 0; i < ncols; i++) {
  45585. + if (result_type == PHPSQLITE_ASSOC) {
  45586. + char *colname = estrdup((char *)colnames[i]);
  45587. +
  45588. + if (SQLITE_G(assoc_case) == 1) {
  45589. + php_sqlite_strtoupper(colname);
  45590. + } else if (SQLITE_G(assoc_case) == 2) {
  45591. + php_sqlite_strtolower(colname);
  45592. + }
  45593. +
  45594. + add_assoc_string(return_value, colname, colnames[ncols + i] ? (char *)colnames[ncols + i] : "", 1);
  45595. + efree(colname);
  45596. + }
  45597. + if (result_type == PHPSQLITE_NUM) {
  45598. + add_index_string(return_value, i, colnames[ncols + i] ? (char *)colnames[ncols + i] : "", 1);
  45599. + }
  45600. + }
  45601. + if (res.vm) {
  45602. + sqlite_finalize(res.vm, NULL);
  45603. + }
  45604. +done:
  45605. + sqlite_exec(db->db, "PRAGMA show_datatypes = OFF", NULL, NULL, NULL);
  45606. +}
  45607. +/* }}} */
  45608. +
  45609. +/* {{{ proto resource sqlite_query(string query, resource db [, int result_type [, string &error_message]])
  45610. + Executes a query against a given database and returns a result handle. */
  45611. +PHP_FUNCTION(sqlite_query)
  45612. +{
  45613. + zval *zdb;
  45614. + struct php_sqlite_db *db;
  45615. + char *sql;
  45616. + int sql_len;
  45617. + long mode = PHPSQLITE_BOTH;
  45618. + char *errtext = NULL;
  45619. + zval *errmsg = NULL;
  45620. + zval *object = getThis();
  45621. +
  45622. + if (object) {
  45623. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lz/", &sql, &sql_len, &mode, &errmsg)) {
  45624. + return;
  45625. + }
  45626. + DB_FROM_OBJECT(db, object);
  45627. + } else {
  45628. + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  45629. + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lz/", &sql, &sql_len, &zdb, &mode, &errmsg) &&
  45630. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lz/", &zdb, &sql, &sql_len, &mode, &errmsg)) {
  45631. + return;
  45632. + }
  45633. + DB_FROM_ZVAL(db, &zdb);
  45634. + }
  45635. +
  45636. + if (errmsg) {
  45637. + zval_dtor(errmsg);
  45638. + ZVAL_NULL(errmsg);
  45639. + }
  45640. +
  45641. + PHP_SQLITE_EMPTY_QUERY;
  45642. +
  45643. + /* avoid doing work if we can */
  45644. + if (!return_value_used) {
  45645. + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
  45646. +
  45647. + if (db->last_err_code != SQLITE_OK) {
  45648. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45649. + if (errmsg) {
  45650. + ZVAL_STRING(errmsg, errtext, 1);
  45651. + }
  45652. + sqlite_freemem(errtext);
  45653. + }
  45654. + return;
  45655. + }
  45656. +
  45657. + sqlite_query(object, db, sql, sql_len, (int)mode, 1, return_value, NULL, errmsg TSRMLS_CC);
  45658. +}
  45659. +/* }}} */
  45660. +
  45661. +/* {{{ proto boolean sqlite_exec(string query, resource db[, string &error_message])
  45662. + Executes a result-less query against a given database */
  45663. +PHP_FUNCTION(sqlite_exec)
  45664. +{
  45665. + zval *zdb;
  45666. + struct php_sqlite_db *db;
  45667. + char *sql;
  45668. + int sql_len;
  45669. + char *errtext = NULL;
  45670. + zval *errmsg = NULL;
  45671. + zval *object = getThis();
  45672. +
  45673. + if (object) {
  45674. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|z/", &sql, &sql_len, &errmsg)) {
  45675. + return;
  45676. + }
  45677. + DB_FROM_OBJECT(db, object);
  45678. + } else {
  45679. + if(FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  45680. + ZEND_NUM_ARGS() TSRMLS_CC, "sr", &sql, &sql_len, &zdb) &&
  45681. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|z/", &zdb, &sql, &sql_len, &errmsg)) {
  45682. + return;
  45683. + }
  45684. + DB_FROM_ZVAL(db, &zdb);
  45685. + }
  45686. +
  45687. + if (errmsg) {
  45688. + zval_dtor(errmsg);
  45689. + ZVAL_NULL(errmsg);
  45690. + }
  45691. +
  45692. + PHP_SQLITE_EMPTY_QUERY;
  45693. +
  45694. + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
  45695. +
  45696. + if (db->last_err_code != SQLITE_OK) {
  45697. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  45698. + if (errmsg) {
  45699. + ZVAL_STRING(errmsg, errtext, 1);
  45700. + }
  45701. + sqlite_freemem(errtext);
  45702. + RETURN_FALSE;
  45703. + }
  45704. +
  45705. + RETURN_TRUE;
  45706. +}
  45707. +/* }}} */
  45708. +
  45709. +/* {{{ php_sqlite_fetch_array */
  45710. +static void php_sqlite_fetch_array(struct php_sqlite_result *res, int mode, zend_bool decode_binary, int move_next, zval *return_value TSRMLS_DC)
  45711. +{
  45712. + int j, n = res->ncolumns, buffered = res->buffered;
  45713. + const char **rowdata, **colnames;
  45714. +
  45715. + /* check range of the row */
  45716. + if (res->curr_row >= res->nrows) {
  45717. + /* no more */
  45718. + RETURN_FALSE;
  45719. + }
  45720. + colnames = (const char**)res->col_names;
  45721. + if (res->buffered) {
  45722. + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
  45723. + } else {
  45724. + rowdata = (const char**)res->table;
  45725. + }
  45726. +
  45727. + /* now populate the result */
  45728. + array_init(return_value);
  45729. +
  45730. + for (j = 0; j < n; j++) {
  45731. + zval *decoded;
  45732. + MAKE_STD_ZVAL(decoded);
  45733. +
  45734. + if (rowdata[j] == NULL) {
  45735. + ZVAL_NULL(decoded);
  45736. + } else if (decode_binary && rowdata[j][0] == '\x01') {
  45737. + Z_STRVAL_P(decoded) = emalloc(strlen(rowdata[j]));
  45738. + Z_STRLEN_P(decoded) = php_sqlite_decode_binary(rowdata[j]+1, Z_STRVAL_P(decoded));
  45739. + Z_STRVAL_P(decoded)[Z_STRLEN_P(decoded)] = '\0';
  45740. + Z_TYPE_P(decoded) = IS_STRING;
  45741. + if (!buffered) {
  45742. + efree((char*)rowdata[j]);
  45743. + rowdata[j] = NULL;
  45744. + }
  45745. + } else {
  45746. + ZVAL_STRING(decoded, (char*)rowdata[j], buffered);
  45747. + if (!buffered) {
  45748. + rowdata[j] = NULL;
  45749. + }
  45750. + }
  45751. +
  45752. + if (mode & PHPSQLITE_NUM) {
  45753. + if (mode & PHPSQLITE_ASSOC) {
  45754. + add_index_zval(return_value, j, decoded);
  45755. + Z_ADDREF_P(decoded);
  45756. + add_assoc_zval(return_value, (char*)colnames[j], decoded);
  45757. + } else {
  45758. + add_next_index_zval(return_value, decoded);
  45759. + }
  45760. + } else {
  45761. + add_assoc_zval(return_value, (char*)colnames[j], decoded);
  45762. + }
  45763. + }
  45764. +
  45765. + if (move_next) {
  45766. + if (!res->buffered) {
  45767. + /* non buffered: fetch next row */
  45768. + php_sqlite_fetch(res TSRMLS_CC);
  45769. + }
  45770. + /* advance the row pointer */
  45771. + res->curr_row++;
  45772. + }
  45773. +}
  45774. +/* }}} */
  45775. +
  45776. +/* {{{ php_sqlite_fetch_column */
  45777. +static void php_sqlite_fetch_column(struct php_sqlite_result *res, zval *which, zend_bool decode_binary, zval *return_value TSRMLS_DC)
  45778. +{
  45779. + int j;
  45780. + const char **rowdata, **colnames;
  45781. +
  45782. + /* check range of the row */
  45783. + if (res->curr_row >= res->nrows) {
  45784. + /* no more */
  45785. + RETURN_FALSE;
  45786. + }
  45787. + colnames = (const char**)res->col_names;
  45788. +
  45789. + if (Z_TYPE_P(which) == IS_LONG) {
  45790. + j = Z_LVAL_P(which);
  45791. + } else {
  45792. + convert_to_string_ex(&which);
  45793. + for (j = 0; j < res->ncolumns; j++) {
  45794. + if (!strcasecmp((char*)colnames[j], Z_STRVAL_P(which))) {
  45795. + break;
  45796. + }
  45797. + }
  45798. + }
  45799. + if (j < 0 || j >= res->ncolumns) {
  45800. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "No such column %d", j);
  45801. + RETURN_FALSE;
  45802. + }
  45803. +
  45804. + if (res->buffered) {
  45805. + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
  45806. + } else {
  45807. + rowdata = (const char**)res->table;
  45808. + }
  45809. +
  45810. + if (rowdata[j] == NULL) {
  45811. + RETURN_NULL();
  45812. + } else if (decode_binary && rowdata[j] != NULL && rowdata[j][0] == '\x01') {
  45813. + int l = strlen(rowdata[j]);
  45814. + char *decoded = emalloc(l);
  45815. + l = php_sqlite_decode_binary(rowdata[j]+1, decoded);
  45816. + decoded[l] = '\0';
  45817. + RETVAL_STRINGL(decoded, l, 0);
  45818. + if (!res->buffered) {
  45819. + efree((char*)rowdata[j]);
  45820. + rowdata[j] = NULL;
  45821. + }
  45822. + } else {
  45823. + RETVAL_STRING((char*)rowdata[j], res->buffered);
  45824. + if (!res->buffered) {
  45825. + rowdata[j] = NULL;
  45826. + }
  45827. + }
  45828. +}
  45829. +/* }}} */
  45830. +
  45831. +/* {{{ proto array sqlite_fetch_all(resource result [, int result_type [, bool decode_binary]])
  45832. + Fetches all rows from a result set as an array of arrays. */
  45833. +PHP_FUNCTION(sqlite_fetch_all)
  45834. +{
  45835. + zval *zres, *ent;
  45836. + long mode = PHPSQLITE_BOTH;
  45837. + zend_bool decode_binary = 1;
  45838. + struct php_sqlite_result *res;
  45839. + zval *object = getThis();
  45840. +
  45841. + if (object) {
  45842. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
  45843. + return;
  45844. + }
  45845. + RES_FROM_OBJECT(res, object);
  45846. + if (!ZEND_NUM_ARGS()) {
  45847. + mode = res->mode;
  45848. + }
  45849. + } else {
  45850. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
  45851. + return;
  45852. + }
  45853. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  45854. + if (ZEND_NUM_ARGS() < 2) {
  45855. + mode = res->mode;
  45856. + }
  45857. + }
  45858. +
  45859. + if (res->curr_row >= res->nrows && res->nrows) {
  45860. + if (!res->buffered) {
  45861. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "One or more rowsets were already returned; returning NULL this time");
  45862. + } else {
  45863. + res->curr_row = 0;
  45864. + }
  45865. + }
  45866. +
  45867. + array_init(return_value);
  45868. +
  45869. + while (res->curr_row < res->nrows) {
  45870. + MAKE_STD_ZVAL(ent);
  45871. + php_sqlite_fetch_array(res, mode, decode_binary, 1, ent TSRMLS_CC);
  45872. + add_next_index_zval(return_value, ent);
  45873. + }
  45874. +}
  45875. +/* }}} */
  45876. +
  45877. +/* {{{ proto array sqlite_fetch_array(resource result [, int result_type [, bool decode_binary]])
  45878. + Fetches the next row from a result set as an array. */
  45879. +PHP_FUNCTION(sqlite_fetch_array)
  45880. +{
  45881. + zval *zres;
  45882. + long mode = PHPSQLITE_BOTH;
  45883. + zend_bool decode_binary = 1;
  45884. + struct php_sqlite_result *res;
  45885. + zval *object = getThis();
  45886. +
  45887. + if (object) {
  45888. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
  45889. + return;
  45890. + }
  45891. + RES_FROM_OBJECT(res, object);
  45892. + if (!ZEND_NUM_ARGS()) {
  45893. + mode = res->mode;
  45894. + }
  45895. + } else {
  45896. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
  45897. + return;
  45898. + }
  45899. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  45900. + if (ZEND_NUM_ARGS() < 2) {
  45901. + mode = res->mode;
  45902. + }
  45903. + }
  45904. +
  45905. + php_sqlite_fetch_array(res, mode, decode_binary, 1, return_value TSRMLS_CC);
  45906. +}
  45907. +/* }}} */
  45908. +
  45909. +/* {{{ proto object sqlite_fetch_object(resource result [, string class_name [, NULL|array ctor_params [, bool decode_binary]]])
  45910. + Fetches the next row from a result set as an object. */
  45911. + /* note that you can do array(&$val) for param ctor_params */
  45912. +PHP_FUNCTION(sqlite_fetch_object)
  45913. +{
  45914. + zval *zres;
  45915. + zend_bool decode_binary = 1;
  45916. + struct php_sqlite_result *res;
  45917. + zval *object = getThis();
  45918. + char *class_name = NULL;
  45919. + int class_name_len;
  45920. + zend_class_entry *ce;
  45921. + zval dataset;
  45922. + zend_fcall_info fci;
  45923. + zend_fcall_info_cache fcc;
  45924. + zval *retval_ptr;
  45925. + zval *ctor_params = NULL;
  45926. + zend_error_handling error_handling;
  45927. +
  45928. + zend_replace_error_handling(object ? EH_THROW : EH_NORMAL, sqlite_ce_exception, &error_handling TSRMLS_CC);
  45929. + if (object) {
  45930. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|szb", &class_name, &class_name_len, &ctor_params, &decode_binary)) {
  45931. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45932. + return;
  45933. + }
  45934. + RES_FROM_OBJECT_RESTORE_ERH(res, object, &error_handling);
  45935. + if (!class_name) {
  45936. + ce = zend_standard_class_def;
  45937. + } else {
  45938. + ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
  45939. + }
  45940. + } else {
  45941. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|szb", &zres, &class_name, &class_name_len, &ctor_params, &decode_binary)) {
  45942. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45943. + return;
  45944. + }
  45945. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  45946. + if (!class_name) {
  45947. + ce = zend_standard_class_def;
  45948. + } else {
  45949. + ce = zend_fetch_class(class_name, class_name_len, ZEND_FETCH_CLASS_AUTO TSRMLS_CC);
  45950. + }
  45951. + }
  45952. +
  45953. + if (!ce) {
  45954. + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Could not find class '%s'", class_name);
  45955. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45956. + return;
  45957. + }
  45958. +
  45959. + if (res->curr_row < res->nrows) {
  45960. + php_sqlite_fetch_array(res, PHPSQLITE_ASSOC, decode_binary, 1, &dataset TSRMLS_CC);
  45961. + } else {
  45962. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45963. + RETURN_FALSE;
  45964. + }
  45965. +
  45966. + object_and_properties_init(return_value, ce, NULL);
  45967. + zend_merge_properties(return_value, Z_ARRVAL(dataset), 1 TSRMLS_CC);
  45968. +
  45969. + zend_restore_error_handling(&error_handling TSRMLS_CC);
  45970. +
  45971. + if (ce->constructor) {
  45972. + fci.size = sizeof(fci);
  45973. + fci.function_table = &ce->function_table;
  45974. + fci.function_name = NULL;
  45975. + fci.symbol_table = NULL;
  45976. + fci.object_ptr = return_value;
  45977. + fci.retval_ptr_ptr = &retval_ptr;
  45978. + if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
  45979. + if (Z_TYPE_P(ctor_params) == IS_ARRAY) {
  45980. + HashTable *ht = Z_ARRVAL_P(ctor_params);
  45981. + Bucket *p;
  45982. +
  45983. + fci.param_count = 0;
  45984. + fci.params = safe_emalloc(sizeof(zval*), ht->nNumOfElements, 0);
  45985. + p = ht->pListHead;
  45986. + while (p != NULL) {
  45987. + fci.params[fci.param_count++] = (zval**)p->pData;
  45988. + p = p->pListNext;
  45989. + }
  45990. + } else {
  45991. + /* Two problems why we throw exceptions here: PHP is typeless
  45992. + * and hence passing one argument that's not an array could be
  45993. + * by mistake and the other way round is possible, too. The
  45994. + * single value is an array. Also we'd have to make that one
  45995. + * argument passed by reference.
  45996. + */
  45997. + zend_throw_exception(sqlite_ce_exception, "Parameter ctor_params must be an array", 0 TSRMLS_CC);
  45998. + return;
  45999. + }
  46000. + } else {
  46001. + fci.param_count = 0;
  46002. + fci.params = NULL;
  46003. + }
  46004. + fci.no_separation = 1;
  46005. +
  46006. + fcc.initialized = 1;
  46007. + fcc.function_handler = ce->constructor;
  46008. + fcc.calling_scope = EG(scope);
  46009. + fcc.called_scope = Z_OBJCE_P(return_value);
  46010. + fcc.object_ptr = return_value;
  46011. +
  46012. + if (zend_call_function(&fci, &fcc TSRMLS_CC) == FAILURE) {
  46013. + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Could not execute %s::%s()", class_name, ce->constructor->common.function_name);
  46014. + } else {
  46015. + if (retval_ptr) {
  46016. + zval_ptr_dtor(&retval_ptr);
  46017. + }
  46018. + }
  46019. + if (fci.params) {
  46020. + efree(fci.params);
  46021. + }
  46022. + } else if (ctor_params && Z_TYPE_P(ctor_params) != IS_NULL) {
  46023. + zend_throw_exception_ex(sqlite_ce_exception, 0 TSRMLS_CC, "Class %s does not have a constructor, use NULL for parameter ctor_params or omit it", class_name);
  46024. + }
  46025. +}
  46026. +/* }}} */
  46027. +
  46028. +/* {{{ proto array sqlite_array_query(resource db, string query [ , int result_type [, bool decode_binary]])
  46029. + Executes a query against a given database and returns an array of arrays. */
  46030. +PHP_FUNCTION(sqlite_array_query)
  46031. +{
  46032. + zval *zdb, *ent;
  46033. + struct php_sqlite_db *db;
  46034. + struct php_sqlite_result *rres;
  46035. + char *sql;
  46036. + int sql_len;
  46037. + long mode = PHPSQLITE_BOTH;
  46038. + char *errtext = NULL;
  46039. + zend_bool decode_binary = 1;
  46040. + zval *object = getThis();
  46041. +
  46042. + if (object) {
  46043. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|lb", &sql, &sql_len, &mode, &decode_binary)) {
  46044. + return;
  46045. + }
  46046. + DB_FROM_OBJECT(db, object);
  46047. + } else {
  46048. + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  46049. + ZEND_NUM_ARGS() TSRMLS_CC, "sr|lb", &sql, &sql_len, &zdb, &mode, &decode_binary) &&
  46050. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|lb", &zdb, &sql, &sql_len, &mode, &decode_binary)) {
  46051. + return;
  46052. + }
  46053. + DB_FROM_ZVAL(db, &zdb);
  46054. + }
  46055. +
  46056. + PHP_SQLITE_EMPTY_QUERY;
  46057. +
  46058. + /* avoid doing work if we can */
  46059. + if (!return_value_used) {
  46060. + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
  46061. +
  46062. + if (db->last_err_code != SQLITE_OK) {
  46063. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  46064. + sqlite_freemem(errtext);
  46065. + }
  46066. + return;
  46067. + }
  46068. +
  46069. + rres = (struct php_sqlite_result *)ecalloc(1, sizeof(*rres));
  46070. + sqlite_query(NULL, db, sql, sql_len, (int)mode, 0, NULL, &rres, NULL TSRMLS_CC);
  46071. + if (db->last_err_code != SQLITE_OK) {
  46072. + if (rres) {
  46073. + efree(rres);
  46074. + }
  46075. + RETURN_FALSE;
  46076. + }
  46077. +
  46078. + array_init(return_value);
  46079. +
  46080. + while (rres->curr_row < rres->nrows) {
  46081. + MAKE_STD_ZVAL(ent);
  46082. + php_sqlite_fetch_array(rres, mode, decode_binary, 1, ent TSRMLS_CC);
  46083. + add_next_index_zval(return_value, ent);
  46084. + }
  46085. + real_result_dtor(rres TSRMLS_CC);
  46086. +}
  46087. +/* }}} */
  46088. +
  46089. +/* {{{ php_sqlite_fetch_single */
  46090. +static void php_sqlite_fetch_single(struct php_sqlite_result *res, zend_bool decode_binary, zval *return_value TSRMLS_DC)
  46091. +{
  46092. + const char **rowdata;
  46093. + char *decoded;
  46094. + int decoded_len;
  46095. +
  46096. + /* check range of the row */
  46097. + if (res->curr_row >= res->nrows) {
  46098. + /* no more */
  46099. + RETURN_FALSE;
  46100. + }
  46101. +
  46102. + if (res->buffered) {
  46103. + rowdata = (const char**)&res->table[res->curr_row * res->ncolumns];
  46104. + } else {
  46105. + rowdata = (const char**)res->table;
  46106. + }
  46107. +
  46108. + if (decode_binary && rowdata[0] != NULL && rowdata[0][0] == '\x01') {
  46109. + decoded = emalloc(strlen(rowdata[0]));
  46110. + decoded_len = php_sqlite_decode_binary(rowdata[0]+1, decoded);
  46111. + if (!res->buffered) {
  46112. + efree((char*)rowdata[0]);
  46113. + rowdata[0] = NULL;
  46114. + }
  46115. + } else if (rowdata[0]) {
  46116. + decoded_len = strlen((char*)rowdata[0]);
  46117. + if (res->buffered) {
  46118. + decoded = estrndup((char*)rowdata[0], decoded_len);
  46119. + } else {
  46120. + decoded = (char*)rowdata[0];
  46121. + rowdata[0] = NULL;
  46122. + }
  46123. + } else {
  46124. + decoded = NULL;
  46125. + decoded_len = 0;
  46126. + }
  46127. +
  46128. + if (!res->buffered) {
  46129. + /* non buffered: fetch next row */
  46130. + php_sqlite_fetch(res TSRMLS_CC);
  46131. + }
  46132. + /* advance the row pointer */
  46133. + res->curr_row++;
  46134. +
  46135. + if (decoded == NULL) {
  46136. + RETURN_NULL();
  46137. + } else {
  46138. + RETURN_STRINGL(decoded, decoded_len, 0);
  46139. + }
  46140. +}
  46141. +/* }}} */
  46142. +
  46143. +
  46144. +/* {{{ proto array sqlite_single_query(resource db, string query [, bool first_row_only [, bool decode_binary]])
  46145. + Executes a query and returns either an array for one single column or the value of the first row. */
  46146. +PHP_FUNCTION(sqlite_single_query)
  46147. +{
  46148. + zval *zdb, *ent;
  46149. + struct php_sqlite_db *db;
  46150. + struct php_sqlite_result *rres;
  46151. + char *sql;
  46152. + int sql_len;
  46153. + char *errtext = NULL;
  46154. + zend_bool decode_binary = 1;
  46155. + zend_bool srow = 1;
  46156. + zval *object = getThis();
  46157. +
  46158. + if (object) {
  46159. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|bb", &sql, &sql_len, &srow, &decode_binary)) {
  46160. + return;
  46161. + }
  46162. + RES_FROM_OBJECT(db, object);
  46163. + } else {
  46164. + if (FAILURE == zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET,
  46165. + ZEND_NUM_ARGS() TSRMLS_CC, "sr|bb", &sql, &sql_len, &zdb, &srow, &decode_binary) &&
  46166. + FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rs|bb", &zdb, &sql, &sql_len, &srow, &decode_binary)) {
  46167. + return;
  46168. + }
  46169. + DB_FROM_ZVAL(db, &zdb);
  46170. + }
  46171. +
  46172. + PHP_SQLITE_EMPTY_QUERY;
  46173. +
  46174. + /* avoid doing work if we can */
  46175. + if (!return_value_used) {
  46176. + db->last_err_code = sqlite_exec(db->db, sql, NULL, NULL, &errtext);
  46177. +
  46178. + if (db->last_err_code != SQLITE_OK) {
  46179. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "%s", errtext);
  46180. + sqlite_freemem(errtext);
  46181. + }
  46182. + return;
  46183. + }
  46184. +
  46185. + rres = (struct php_sqlite_result *)ecalloc(1, sizeof(*rres));
  46186. + sqlite_query(NULL, db, sql, sql_len, PHPSQLITE_NUM, 0, NULL, &rres, NULL TSRMLS_CC);
  46187. + if (db->last_err_code != SQLITE_OK) {
  46188. + if (rres) {
  46189. + efree(rres);
  46190. + }
  46191. + RETURN_FALSE;
  46192. + }
  46193. +
  46194. + if (!srow) {
  46195. + array_init(return_value);
  46196. + }
  46197. +
  46198. + while (rres->curr_row < rres->nrows) {
  46199. + MAKE_STD_ZVAL(ent);
  46200. + php_sqlite_fetch_single(rres, decode_binary, ent TSRMLS_CC);
  46201. +
  46202. + /* if set and we only have 1 row in the result set, return the result as a string. */
  46203. + if (srow) {
  46204. + if (rres->curr_row == 1 && rres->curr_row >= rres->nrows) {
  46205. + *return_value = *ent;
  46206. + zval_copy_ctor(return_value);
  46207. + zval_dtor(ent);
  46208. + FREE_ZVAL(ent);
  46209. + break;
  46210. + } else {
  46211. + srow = 0;
  46212. + array_init(return_value);
  46213. + }
  46214. + }
  46215. + add_next_index_zval(return_value, ent);
  46216. + }
  46217. +
  46218. + real_result_dtor(rres TSRMLS_CC);
  46219. +}
  46220. +/* }}} */
  46221. +
  46222. +
  46223. +/* {{{ proto string sqlite_fetch_single(resource result [, bool decode_binary])
  46224. + Fetches the first column of a result set as a string. */
  46225. +PHP_FUNCTION(sqlite_fetch_single)
  46226. +{
  46227. + zval *zres;
  46228. + zend_bool decode_binary = 1;
  46229. + struct php_sqlite_result *res;
  46230. + zval *object = getThis();
  46231. +
  46232. + if (object) {
  46233. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|b", &decode_binary)) {
  46234. + return;
  46235. + }
  46236. + RES_FROM_OBJECT(res, object);
  46237. + } else {
  46238. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|b", &zres, &decode_binary)) {
  46239. + return;
  46240. + }
  46241. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46242. + }
  46243. +
  46244. + php_sqlite_fetch_single(res, decode_binary, return_value TSRMLS_CC);
  46245. +}
  46246. +/* }}} */
  46247. +
  46248. +/* {{{ proto array sqlite_current(resource result [, int result_type [, bool decode_binary]])
  46249. + Fetches the current row from a result set as an array. */
  46250. +PHP_FUNCTION(sqlite_current)
  46251. +{
  46252. + zval *zres;
  46253. + long mode = PHPSQLITE_BOTH;
  46254. + zend_bool decode_binary = 1;
  46255. + struct php_sqlite_result *res;
  46256. + zval *object = getThis();
  46257. +
  46258. + if (object) {
  46259. + if (ZEND_NUM_ARGS() && FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|lb", &mode, &decode_binary)) {
  46260. + return;
  46261. + }
  46262. + RES_FROM_OBJECT(res, object);
  46263. + if (!ZEND_NUM_ARGS()) {
  46264. + mode = res->mode;
  46265. + }
  46266. + } else {
  46267. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|lb", &zres, &mode, &decode_binary)) {
  46268. + return;
  46269. + }
  46270. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46271. + if (ZEND_NUM_ARGS() < 2) {
  46272. + mode = res->mode;
  46273. + }
  46274. + }
  46275. +
  46276. + php_sqlite_fetch_array(res, mode, decode_binary, 0, return_value TSRMLS_CC);
  46277. +}
  46278. +/* }}} */
  46279. +
  46280. +/* {{{ proto mixed sqlite_column(resource result, mixed index_or_name [, bool decode_binary])
  46281. + Fetches a column from the current row of a result set. */
  46282. +PHP_FUNCTION(sqlite_column)
  46283. +{
  46284. + zval *zres;
  46285. + zval *which;
  46286. + zend_bool decode_binary = 1;
  46287. + struct php_sqlite_result *res;
  46288. + zval *object = getThis();
  46289. +
  46290. + if (object) {
  46291. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|b", &which, &decode_binary)) {
  46292. + return;
  46293. + }
  46294. + RES_FROM_OBJECT(res, object);
  46295. + } else {
  46296. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rz|b", &zres, &which, &decode_binary)) {
  46297. + return;
  46298. + }
  46299. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46300. + }
  46301. +
  46302. + php_sqlite_fetch_column(res, which, decode_binary, return_value TSRMLS_CC);
  46303. +}
  46304. +/* }}} */
  46305. +
  46306. +/* {{{ proto string sqlite_libversion()
  46307. + Returns the version of the linked SQLite library. */
  46308. +PHP_FUNCTION(sqlite_libversion)
  46309. +{
  46310. + if (zend_parse_parameters_none() == FAILURE) {
  46311. + return;
  46312. + }
  46313. + RETURN_STRING((char*)sqlite_libversion(), 1);
  46314. +}
  46315. +/* }}} */
  46316. +
  46317. +/* {{{ proto string sqlite_libencoding()
  46318. + Returns the encoding (iso8859 or UTF-8) of the linked SQLite library. */
  46319. +PHP_FUNCTION(sqlite_libencoding)
  46320. +{
  46321. + if (zend_parse_parameters_none() == FAILURE) {
  46322. + return;
  46323. + }
  46324. + RETURN_STRING((char*)sqlite_libencoding(), 1);
  46325. +}
  46326. +/* }}} */
  46327. +
  46328. +/* {{{ proto int sqlite_changes(resource db)
  46329. + Returns the number of rows that were changed by the most recent SQL statement. */
  46330. +PHP_FUNCTION(sqlite_changes)
  46331. +{
  46332. + zval *zdb;
  46333. + struct php_sqlite_db *db;
  46334. + zval *object = getThis();
  46335. +
  46336. + if (object) {
  46337. + if (zend_parse_parameters_none() == FAILURE) {
  46338. + return;
  46339. + }
  46340. + DB_FROM_OBJECT(db, object);
  46341. + } else {
  46342. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
  46343. + return;
  46344. + }
  46345. + DB_FROM_ZVAL(db, &zdb);
  46346. + }
  46347. +
  46348. + RETURN_LONG(sqlite_changes(db->db));
  46349. +}
  46350. +/* }}} */
  46351. +
  46352. +/* {{{ proto int sqlite_last_insert_rowid(resource db)
  46353. + Returns the rowid of the most recently inserted row. */
  46354. +PHP_FUNCTION(sqlite_last_insert_rowid)
  46355. +{
  46356. + zval *zdb;
  46357. + struct php_sqlite_db *db;
  46358. + zval *object = getThis();
  46359. +
  46360. + if (object) {
  46361. + if (zend_parse_parameters_none() == FAILURE) {
  46362. + return;
  46363. + }
  46364. + DB_FROM_OBJECT(db, object);
  46365. + } else {
  46366. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
  46367. + return;
  46368. + }
  46369. + DB_FROM_ZVAL(db, &zdb);
  46370. + }
  46371. +
  46372. + RETURN_LONG(sqlite_last_insert_rowid(db->db));
  46373. +}
  46374. +/* }}} */
  46375. +
  46376. +static int sqlite_count_elements(zval *object, long *count TSRMLS_DC) /* {{{ */
  46377. +{
  46378. + sqlite_object *obj = (sqlite_object*) zend_object_store_get_object(object TSRMLS_CC);
  46379. +
  46380. + if (obj->u.res == NULL) {
  46381. + zend_throw_exception(sqlite_ce_exception, "Row count is not available for this query", 0 TSRMLS_CC);
  46382. + return FAILURE;
  46383. + }
  46384. +
  46385. + if (obj->u.res->buffered) {
  46386. + * count = obj->u.res->nrows;
  46387. + return SUCCESS;
  46388. + } else {
  46389. + zend_throw_exception(sqlite_ce_exception, "Row count is not available for unbuffered queries", 0 TSRMLS_CC);
  46390. + return FAILURE;
  46391. + }
  46392. +} /* }}} */
  46393. +
  46394. +/* {{{ proto int sqlite_num_rows(resource result)
  46395. + Returns the number of rows in a buffered result set. */
  46396. +PHP_FUNCTION(sqlite_num_rows)
  46397. +{
  46398. + zval *zres;
  46399. + struct php_sqlite_result *res;
  46400. + zval *object = getThis();
  46401. +
  46402. + if (object) {
  46403. + if (zend_parse_parameters_none() == FAILURE) {
  46404. + return;
  46405. + }
  46406. + RES_FROM_OBJECT(res, object);
  46407. + } else {
  46408. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46409. + return;
  46410. + }
  46411. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46412. + }
  46413. +
  46414. + if (res->buffered) {
  46415. + RETURN_LONG(res->nrows);
  46416. + } else {
  46417. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Row count is not available for unbuffered queries");
  46418. + RETURN_FALSE;
  46419. + }
  46420. +}
  46421. +/* }}} */
  46422. +
  46423. +/* {{{ proto bool sqlite_valid(resource result)
  46424. + Returns whether more rows are available. */
  46425. +PHP_FUNCTION(sqlite_valid)
  46426. +{
  46427. + zval *zres;
  46428. + struct php_sqlite_result *res;
  46429. + zval *object = getThis();
  46430. +
  46431. + if (object) {
  46432. + if (zend_parse_parameters_none() == FAILURE) {
  46433. + return;
  46434. + }
  46435. + RES_FROM_OBJECT(res, object);
  46436. + } else {
  46437. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46438. + return;
  46439. + }
  46440. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46441. + }
  46442. +
  46443. + RETURN_BOOL(res->curr_row < res->nrows && res->nrows); /* curr_row may be -1 */
  46444. +}
  46445. +/* }}} */
  46446. +
  46447. +/* {{{ proto bool sqlite_has_prev(resource result)
  46448. + * Returns whether a previous row is available. */
  46449. +PHP_FUNCTION(sqlite_has_prev)
  46450. +{
  46451. + zval *zres;
  46452. + struct php_sqlite_result *res;
  46453. + zval *object = getThis();
  46454. +
  46455. + if (object) {
  46456. + if (zend_parse_parameters_none() == FAILURE) {
  46457. + return;
  46458. + }
  46459. + RES_FROM_OBJECT(res, object);
  46460. + } else {
  46461. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46462. + return;
  46463. + }
  46464. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46465. + }
  46466. +
  46467. + if(!res->buffered) {
  46468. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "you cannot use sqlite_has_prev on unbuffered querys");
  46469. + RETURN_FALSE;
  46470. + }
  46471. +
  46472. + RETURN_BOOL(res->curr_row);
  46473. +}
  46474. +/* }}} */
  46475. +
  46476. +/* {{{ proto int sqlite_num_fields(resource result)
  46477. + Returns the number of fields in a result set. */
  46478. +PHP_FUNCTION(sqlite_num_fields)
  46479. +{
  46480. + zval *zres;
  46481. + struct php_sqlite_result *res;
  46482. + zval *object = getThis();
  46483. +
  46484. + if (object) {
  46485. + if (zend_parse_parameters_none() == FAILURE) {
  46486. + return;
  46487. + }
  46488. + RES_FROM_OBJECT(res, object);
  46489. + } else {
  46490. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46491. + return;
  46492. + }
  46493. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46494. + }
  46495. +
  46496. + RETURN_LONG(res->ncolumns);
  46497. +}
  46498. +/* }}} */
  46499. +
  46500. +/* {{{ proto string sqlite_field_name(resource result, int field_index)
  46501. + Returns the name of a particular field of a result set. */
  46502. +PHP_FUNCTION(sqlite_field_name)
  46503. +{
  46504. + zval *zres;
  46505. + struct php_sqlite_result *res;
  46506. + long field;
  46507. + zval *object = getThis();
  46508. +
  46509. + if (object) {
  46510. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &field)) {
  46511. + return;
  46512. + }
  46513. + RES_FROM_OBJECT(res, object);
  46514. + } else {
  46515. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &field)) {
  46516. + return;
  46517. + }
  46518. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46519. + }
  46520. +
  46521. + if (field < 0 || field >= res->ncolumns) {
  46522. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "field %ld out of range", field);
  46523. + RETURN_FALSE;
  46524. + }
  46525. +
  46526. + RETURN_STRING(res->col_names[field], 1);
  46527. +}
  46528. +/* }}} */
  46529. +
  46530. +/* {{{ proto bool sqlite_seek(resource result, int row)
  46531. + Seek to a particular row number of a buffered result set. */
  46532. +PHP_FUNCTION(sqlite_seek)
  46533. +{
  46534. + zval *zres;
  46535. + struct php_sqlite_result *res;
  46536. + long row;
  46537. + zval *object = getThis();
  46538. +
  46539. + if (object) {
  46540. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &row)) {
  46541. + return;
  46542. + }
  46543. + RES_FROM_OBJECT(res, object);
  46544. + } else {
  46545. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rl", &zres, &row)) {
  46546. + return;
  46547. + }
  46548. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46549. + }
  46550. +
  46551. + if (!res->buffered) {
  46552. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot seek an unbuffered result set");
  46553. + RETURN_FALSE;
  46554. + }
  46555. +
  46556. + if (row < 0 || row >= res->nrows) {
  46557. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "row %ld out of range", row);
  46558. + RETURN_FALSE;
  46559. + }
  46560. +
  46561. + res->curr_row = row;
  46562. + RETURN_TRUE;
  46563. +}
  46564. +/* }}} */
  46565. +
  46566. +/* {{{ proto bool sqlite_rewind(resource result)
  46567. + Seek to the first row number of a buffered result set. */
  46568. +PHP_FUNCTION(sqlite_rewind)
  46569. +{
  46570. + zval *zres;
  46571. + struct php_sqlite_result *res;
  46572. + zval *object = getThis();
  46573. +
  46574. + if (object) {
  46575. + if (zend_parse_parameters_none() == FAILURE) {
  46576. + return;
  46577. + }
  46578. + RES_FROM_OBJECT(res, object);
  46579. + } else {
  46580. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46581. + return;
  46582. + }
  46583. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46584. + }
  46585. +
  46586. + if (!res->buffered) {
  46587. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "Cannot rewind an unbuffered result set");
  46588. + RETURN_FALSE;
  46589. + }
  46590. +
  46591. + if (!res->nrows) {
  46592. + php_error_docref(NULL TSRMLS_CC, E_NOTICE, "no rows received");
  46593. + RETURN_FALSE;
  46594. + }
  46595. +
  46596. + res->curr_row = 0;
  46597. + RETURN_TRUE;
  46598. +}
  46599. +/* }}} */
  46600. +
  46601. +/* {{{ proto bool sqlite_next(resource result)
  46602. + Seek to the next row number of a result set. */
  46603. +PHP_FUNCTION(sqlite_next)
  46604. +{
  46605. + zval *zres;
  46606. + struct php_sqlite_result *res;
  46607. + zval *object = getThis();
  46608. +
  46609. + if (object) {
  46610. + if (zend_parse_parameters_none() == FAILURE) {
  46611. + return;
  46612. + }
  46613. + RES_FROM_OBJECT(res, object);
  46614. + } else {
  46615. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46616. + return;
  46617. + }
  46618. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46619. + }
  46620. +
  46621. + if (!res->buffered && res->vm) {
  46622. + php_sqlite_fetch(res TSRMLS_CC);
  46623. + }
  46624. +
  46625. + if (res->curr_row >= res->nrows) {
  46626. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "no more rows available");
  46627. + RETURN_FALSE;
  46628. + }
  46629. +
  46630. + res->curr_row++;
  46631. +
  46632. + RETURN_TRUE;
  46633. +}
  46634. +/* }}} */
  46635. +
  46636. +/* {{{ proto int sqlite_key(resource result)
  46637. + Return the current row index of a buffered result. */
  46638. +PHP_FUNCTION(sqlite_key)
  46639. +{
  46640. + zval *zres;
  46641. + struct php_sqlite_result *res;
  46642. + zval *object = getThis();
  46643. +
  46644. + if (object) {
  46645. + if (zend_parse_parameters_none() == FAILURE) {
  46646. + return;
  46647. + }
  46648. + RES_FROM_OBJECT(res, object);
  46649. + } else {
  46650. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46651. + return;
  46652. + }
  46653. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46654. + }
  46655. +
  46656. + RETURN_LONG(res->curr_row);
  46657. +}
  46658. +/* }}} */
  46659. +
  46660. +/* {{{ proto bool sqlite_prev(resource result)
  46661. + * Seek to the previous row number of a result set. */
  46662. +PHP_FUNCTION(sqlite_prev)
  46663. +{
  46664. + zval *zres;
  46665. + struct php_sqlite_result *res;
  46666. + zval *object = getThis();
  46667. +
  46668. + if (object) {
  46669. + if (zend_parse_parameters_none() == FAILURE) {
  46670. + return;
  46671. + }
  46672. + RES_FROM_OBJECT(res, object);
  46673. + } else {
  46674. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zres)) {
  46675. + return;
  46676. + }
  46677. + ZEND_FETCH_RESOURCE(res, struct php_sqlite_result *, &zres, -1, "sqlite result", le_sqlite_result);
  46678. + }
  46679. +
  46680. + if (!res->buffered) {
  46681. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "you cannot use sqlite_prev on unbuffered querys");
  46682. + RETURN_FALSE;
  46683. + }
  46684. +
  46685. + if (res->curr_row <= 0) {
  46686. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "no previous row available");
  46687. + RETURN_FALSE;
  46688. + }
  46689. +
  46690. + res->curr_row--;
  46691. +
  46692. + RETURN_TRUE;
  46693. +}
  46694. +/* }}} */
  46695. +
  46696. +/* {{{ proto string sqlite_escape_string(string item)
  46697. + Escapes a string for use as a query parameter. */
  46698. +PHP_FUNCTION(sqlite_escape_string)
  46699. +{
  46700. + char *string = NULL;
  46701. + int stringlen;
  46702. + char *ret;
  46703. +
  46704. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &string, &stringlen)) {
  46705. + return;
  46706. + }
  46707. +
  46708. + if (stringlen && (string[0] == '\x01' || memchr(string, '\0', stringlen) != NULL)) {
  46709. + /* binary string */
  46710. + int enclen;
  46711. +
  46712. + ret = safe_emalloc(1 + stringlen / 254, 257, 3);
  46713. + ret[0] = '\x01';
  46714. + enclen = php_sqlite_encode_binary(string, stringlen, ret+1);
  46715. + RETVAL_STRINGL(ret, enclen+1, 0);
  46716. +
  46717. + } else if (stringlen) {
  46718. + ret = sqlite_mprintf("%q", string);
  46719. + if (ret) {
  46720. + RETVAL_STRING(ret, 1);
  46721. + sqlite_freemem(ret);
  46722. + }
  46723. + } else {
  46724. + RETURN_EMPTY_STRING();
  46725. + }
  46726. +}
  46727. +/* }}} */
  46728. +
  46729. +/* {{{ proto int sqlite_last_error(resource db)
  46730. + Returns the error code of the last error for a database. */
  46731. +PHP_FUNCTION(sqlite_last_error)
  46732. +{
  46733. + zval *zdb;
  46734. + struct php_sqlite_db *db;
  46735. + zval *object = getThis();
  46736. +
  46737. + if (object) {
  46738. + if (zend_parse_parameters_none() == FAILURE) {
  46739. + return;
  46740. + }
  46741. + DB_FROM_OBJECT(db, object);
  46742. + } else {
  46743. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &zdb)) {
  46744. + return;
  46745. + }
  46746. + DB_FROM_ZVAL(db, &zdb);
  46747. + }
  46748. +
  46749. + RETURN_LONG(db->last_err_code);
  46750. +}
  46751. +/* }}} */
  46752. +
  46753. +/* {{{ proto string sqlite_error_string(int error_code)
  46754. + Returns the textual description of an error code. */
  46755. +PHP_FUNCTION(sqlite_error_string)
  46756. +{
  46757. + long code;
  46758. + const char *msg;
  46759. +
  46760. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "l", &code)) {
  46761. + return;
  46762. + }
  46763. +
  46764. + msg = sqlite_error_string(code);
  46765. +
  46766. + if (msg) {
  46767. + RETURN_STRING((char*)msg, 1);
  46768. + } else {
  46769. + RETURN_NULL();
  46770. + }
  46771. +}
  46772. +/* }}} */
  46773. +
  46774. +/* manages duplicate registrations of a particular function, and
  46775. + * also handles the case where the db is using a persistent connection */
  46776. +enum callback_prep_t { DO_REG, SKIP_REG, ERR };
  46777. +
  46778. +static enum callback_prep_t prep_callback_struct(struct php_sqlite_db *db, int is_agg,
  46779. + char *funcname,
  46780. + zval *step, zval *fini, struct php_sqlite_agg_functions **funcs)
  46781. +{
  46782. + struct php_sqlite_agg_functions *alloc_funcs, func_tmp;
  46783. + char *hashkey;
  46784. + int hashkeylen;
  46785. + enum callback_prep_t ret;
  46786. +
  46787. + hashkeylen = spprintf(&hashkey, 0, "%s-%s", is_agg ? "agg" : "reg", funcname);
  46788. +
  46789. + /* is it already registered ? */
  46790. + if (SUCCESS == zend_hash_find(&db->callbacks, hashkey, hashkeylen+1, (void*)&alloc_funcs)) {
  46791. + /* override the previous definition */
  46792. +
  46793. + if (alloc_funcs->is_valid) {
  46794. + /* release these */
  46795. +
  46796. + if (alloc_funcs->step) {
  46797. + zval_ptr_dtor(&alloc_funcs->step);
  46798. + alloc_funcs->step = NULL;
  46799. + }
  46800. +
  46801. + if (alloc_funcs->fini) {
  46802. + zval_ptr_dtor(&alloc_funcs->fini);
  46803. + alloc_funcs->fini = NULL;
  46804. + }
  46805. + }
  46806. +
  46807. + ret = SKIP_REG;
  46808. + } else {
  46809. + /* add a new one */
  46810. + func_tmp.db = db;
  46811. +
  46812. + ret = SUCCESS == zend_hash_update(&db->callbacks, hashkey, hashkeylen+1,
  46813. + (void*)&func_tmp, sizeof(func_tmp), (void**)&alloc_funcs) ? DO_REG : ERR;
  46814. + }
  46815. +
  46816. + efree(hashkey);
  46817. +
  46818. + MAKE_STD_ZVAL(alloc_funcs->step);
  46819. + *(alloc_funcs->step) = *step;
  46820. + zval_copy_ctor(alloc_funcs->step);
  46821. + INIT_PZVAL(alloc_funcs->step);
  46822. +
  46823. + if (is_agg) {
  46824. + MAKE_STD_ZVAL(alloc_funcs->fini);
  46825. + *(alloc_funcs->fini) = *fini;
  46826. + zval_copy_ctor(alloc_funcs->fini);
  46827. + INIT_PZVAL(alloc_funcs->fini);
  46828. + } else {
  46829. + alloc_funcs->fini = NULL;
  46830. + }
  46831. + alloc_funcs->is_valid = 1;
  46832. + *funcs = alloc_funcs;
  46833. +
  46834. + return ret;
  46835. +}
  46836. +
  46837. +
  46838. +/* {{{ proto bool sqlite_create_aggregate(resource db, string funcname, mixed step_func, mixed finalize_func[, long num_args])
  46839. + Registers an aggregate function for queries. */
  46840. +PHP_FUNCTION(sqlite_create_aggregate)
  46841. +{
  46842. + char *funcname = NULL;
  46843. + int funcname_len;
  46844. + zval *zstep, *zfinal, *zdb;
  46845. + struct php_sqlite_db *db;
  46846. + struct php_sqlite_agg_functions *funcs;
  46847. + char *callable = NULL;
  46848. + long num_args = -1;
  46849. + zval *object = getThis();
  46850. +
  46851. + if (object) {
  46852. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "szz|l", &funcname, &funcname_len, &zstep, &zfinal, &num_args)) {
  46853. + return;
  46854. + }
  46855. + DB_FROM_OBJECT(db, object);
  46856. + } else {
  46857. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rszz|l", &zdb, &funcname, &funcname_len, &zstep, &zfinal, &num_args)) {
  46858. + return;
  46859. + }
  46860. + DB_FROM_ZVAL(db, &zdb);
  46861. + }
  46862. +
  46863. + if (!zend_is_callable(zstep, 0, &callable TSRMLS_CC)) {
  46864. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "step function `%s' is not callable", callable);
  46865. + efree(callable);
  46866. + return;
  46867. + }
  46868. + efree(callable);
  46869. +
  46870. + if (!zend_is_callable(zfinal, 0, &callable TSRMLS_CC)) {
  46871. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "finalize function `%s' is not callable", callable);
  46872. + efree(callable);
  46873. + return;
  46874. + }
  46875. + efree(callable);
  46876. +
  46877. +
  46878. + if (prep_callback_struct(db, 1, funcname, zstep, zfinal, &funcs) == DO_REG) {
  46879. + sqlite_create_aggregate(db->db, funcname, num_args,
  46880. + php_sqlite_agg_step_function_callback,
  46881. + php_sqlite_agg_fini_function_callback, funcs);
  46882. + }
  46883. +
  46884. +
  46885. +}
  46886. +/* }}} */
  46887. +
  46888. +/* {{{ proto bool sqlite_create_function(resource db, string funcname, mixed callback[, long num_args])
  46889. + Registers a "regular" function for queries. */
  46890. +PHP_FUNCTION(sqlite_create_function)
  46891. +{
  46892. + char *funcname = NULL;
  46893. + int funcname_len;
  46894. + zval *zcall, *zdb;
  46895. + struct php_sqlite_db *db;
  46896. + struct php_sqlite_agg_functions *funcs;
  46897. + char *callable = NULL;
  46898. + long num_args = -1;
  46899. +
  46900. + zval *object = getThis();
  46901. +
  46902. + if (object) {
  46903. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz|l", &funcname, &funcname_len, &zcall, &num_args)) {
  46904. + return;
  46905. + }
  46906. + DB_FROM_OBJECT(db, object);
  46907. + } else {
  46908. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "rsz|l", &zdb, &funcname, &funcname_len, &zcall, &num_args)) {
  46909. + return;
  46910. + }
  46911. + DB_FROM_ZVAL(db, &zdb);
  46912. + }
  46913. +
  46914. + if (!zend_is_callable(zcall, 0, &callable TSRMLS_CC)) {
  46915. + php_error_docref(NULL TSRMLS_CC, E_WARNING, "function `%s' is not callable", callable);
  46916. + efree(callable);
  46917. + return;
  46918. + }
  46919. + efree(callable);
  46920. +
  46921. + if (prep_callback_struct(db, 0, funcname, zcall, NULL, &funcs) == DO_REG) {
  46922. + sqlite_create_function(db->db, funcname, num_args, php_sqlite_function_callback, funcs);
  46923. + }
  46924. +}
  46925. +/* }}} */
  46926. +
  46927. +/* {{{ proto string sqlite_udf_encode_binary(string data)
  46928. + Apply binary encoding (if required) to a string to return from an UDF. */
  46929. +PHP_FUNCTION(sqlite_udf_encode_binary)
  46930. +{
  46931. + char *data = NULL;
  46932. + int datalen;
  46933. +
  46934. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!", &data, &datalen)) {
  46935. + return;
  46936. + }
  46937. +
  46938. + if (data == NULL) {
  46939. + RETURN_NULL();
  46940. + }
  46941. + if (datalen && (data[0] == '\x01' || memchr(data, '\0', datalen) != NULL)) {
  46942. + /* binary string */
  46943. + int enclen;
  46944. + char *ret;
  46945. +
  46946. + ret = safe_emalloc(1 + datalen / 254, 257, 3);
  46947. + ret[0] = '\x01';
  46948. + enclen = php_sqlite_encode_binary(data, datalen, ret+1);
  46949. + RETVAL_STRINGL(ret, enclen+1, 0);
  46950. + } else {
  46951. + RETVAL_STRINGL(data, datalen, 1);
  46952. + }
  46953. +}
  46954. +/* }}} */
  46955. +
  46956. +/* {{{ proto string sqlite_udf_decode_binary(string data)
  46957. + Decode binary encoding on a string parameter passed to an UDF. */
  46958. +PHP_FUNCTION(sqlite_udf_decode_binary)
  46959. +{
  46960. + char *data = NULL;
  46961. + int datalen;
  46962. +
  46963. + if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s!", &data, &datalen)) {
  46964. + return;
  46965. + }
  46966. +
  46967. + if (data == NULL) {
  46968. + RETURN_NULL();
  46969. + }
  46970. + if (datalen && data[0] == '\x01') {
  46971. + /* encoded string */
  46972. + int enclen;
  46973. + char *ret;
  46974. +
  46975. + ret = emalloc(datalen);
  46976. + enclen = php_sqlite_decode_binary(data+1, ret);
  46977. + ret[enclen] = '\0';
  46978. + RETVAL_STRINGL(ret, enclen, 0);
  46979. + } else {
  46980. + RETVAL_STRINGL(data, datalen, 1);
  46981. + }
  46982. +}
  46983. +/* }}} */
  46984. +
  46985. +
  46986. +/*
  46987. + * Local variables:
  46988. + * tab-width: 4
  46989. + * c-basic-offset: 4
  46990. + * End:
  46991. + * vim600: sw=4 ts=4 fdm=marker
  46992. + * vim<600: sw=4 ts=4
  46993. + */
  46994. --- /dev/null
  46995. +++ b/ext/sqlite/sqlite.dsp
  46996. @@ -0,0 +1,339 @@
  46997. +# Microsoft Developer Studio Project File - Name="sqlite" - Package Owner=<4>
  46998. +# Microsoft Developer Studio Generated Build File, Format Version 6.00
  46999. +# ** DO NOT EDIT **
  47000. +
  47001. +# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
  47002. +
  47003. +CFG=sqlite - Win32 Debug_TS
  47004. +!MESSAGE This is not a valid makefile. To build this project using NMAKE,
  47005. +!MESSAGE use the Export Makefile command and run
  47006. +!MESSAGE
  47007. +!MESSAGE NMAKE /f "sqlite.mak".
  47008. +!MESSAGE
  47009. +!MESSAGE You can specify a configuration when running NMAKE
  47010. +!MESSAGE by defining the macro CFG on the command line. For example:
  47011. +!MESSAGE
  47012. +!MESSAGE NMAKE /f "sqlite.mak" CFG="sqlite - Win32 Debug_TS"
  47013. +!MESSAGE
  47014. +!MESSAGE Possible choices for configuration are:
  47015. +!MESSAGE
  47016. +!MESSAGE "sqlite - Win32 Release_TS" (based on "Win32 (x86) Dynamic-Link Library")
  47017. +!MESSAGE "sqlite - Win32 Debug_TS" (based on "Win32 (x86) Dynamic-Link Library")
  47018. +!MESSAGE
  47019. +
  47020. +# Begin Project
  47021. +# PROP AllowPerConfigDependencies 0
  47022. +# PROP Scc_ProjName ""
  47023. +# PROP Scc_LocalPath ""
  47024. +CPP=cl.exe
  47025. +MTL=midl.exe
  47026. +RSC=rc.exe
  47027. +
  47028. +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
  47029. +
  47030. +# PROP BASE Use_MFC 0
  47031. +# PROP BASE Use_Debug_Libraries 0
  47032. +# PROP BASE Output_Dir "Release_TS"
  47033. +# PROP BASE Intermediate_Dir "Release_TS"
  47034. +# PROP BASE Ignore_Export_Lib 0
  47035. +# PROP BASE Target_Dir ""
  47036. +# PROP Use_MFC 0
  47037. +# PROP Use_Debug_Libraries 0
  47038. +# PROP Output_Dir "Release_TS"
  47039. +# PROP Intermediate_Dir "Release_TS"
  47040. +# PROP Ignore_Export_Lib 0
  47041. +# PROP Target_Dir ""
  47042. +# ADD BASE CPP /nologo /MD /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SQLITE_EXPORTS" /YX /FD /c
  47043. +# ADD CPP /nologo /MD /W3 /GX /O2 /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /I "..\..\win32" /I "..\..\..\php_build" /D ZEND_DEBUG=0 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "COMPILE_DL_SQLITE" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_SQLITE=1 /D "PHP_SQLITE_EXPORTS" /FR /YX /FD /c
  47044. +# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
  47045. +# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
  47046. +# ADD BASE RSC /l 0x407 /d "NDEBUG"
  47047. +# ADD RSC /l 0x407 /d "NDEBUG"
  47048. +BSC32=bscmake.exe
  47049. +# ADD BASE BSC32 /nologo
  47050. +# ADD BSC32 /nologo
  47051. +LINK32=link.exe
  47052. +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
  47053. +# ADD LINK32 php5ts.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386 /out:"..\..\Release_TS\php_sqlite.dll" /libpath:"..\..\Release_TS" /libpath:"..\..\Release_TS_Inline" /libpath:"..\..\..\php_build\release"
  47054. +
  47055. +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
  47056. +
  47057. +# PROP BASE Use_MFC 0
  47058. +# PROP BASE Use_Debug_Libraries 1
  47059. +# PROP BASE Output_Dir "Debug_TS"
  47060. +# PROP BASE Intermediate_Dir "Debug_TS"
  47061. +# PROP BASE Target_Dir ""
  47062. +# PROP Use_MFC 0
  47063. +# PROP Use_Debug_Libraries 1
  47064. +# PROP Output_Dir "Debug_TS"
  47065. +# PROP Intermediate_Dir "Debug_TS"
  47066. +# PROP Ignore_Export_Lib 0
  47067. +# PROP Target_Dir ""
  47068. +# ADD BASE CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SQLITE_EXPORTS" /YX /FD /GZ /c
  47069. +# ADD CPP /nologo /MDd /W3 /Gm /GX /ZI /Od /I "..\.." /I "..\..\main" /I "..\..\Zend" /I "..\..\TSRM" /I "..\..\win32" /I "..\..\..\php_build" /D ZEND_DEBUG=1 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "COMPILE_DL_SQLITE" /D ZTS=1 /D "ZEND_WIN32" /D "PHP_WIN32" /D HAVE_SQLITE=1 /D "PHP_SQLITE_EXPORTS" /YX /FD /GZ /c
  47070. +# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
  47071. +# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
  47072. +# ADD BASE RSC /l 0x407 /d "_DEBUG"
  47073. +# ADD RSC /l 0x407 /d "_DEBUG"
  47074. +BSC32=bscmake.exe
  47075. +# ADD BASE BSC32 /nologo
  47076. +# ADD BSC32 /nologo
  47077. +LINK32=link.exe
  47078. +# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
  47079. +# ADD LINK32 php5ts_debug.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /out:"..\..\Debug_TS\php_sqlite.dll" /pdbtype:sept /libpath:"..\..\Debug_TS" /libpath:"..\..\..\php_build\release"
  47080. +
  47081. +!ENDIF
  47082. +
  47083. +# Begin Target
  47084. +
  47085. +# Name "sqlite - Win32 Release_TS"
  47086. +# Name "sqlite - Win32 Debug_TS"
  47087. +# Begin Group "Source Files"
  47088. +
  47089. +# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
  47090. +# Begin Group "libsqlite"
  47091. +
  47092. +# PROP Default_Filter ""
  47093. +# Begin Source File
  47094. +
  47095. +SOURCE=.\libsqlite\src\attach.c
  47096. +# End Source File
  47097. +# Begin Source File
  47098. +
  47099. +SOURCE=.\libsqlite\src\auth.c
  47100. +# End Source File
  47101. +# Begin Source File
  47102. +
  47103. +SOURCE=.\libsqlite\src\btree.c
  47104. +# End Source File
  47105. +# Begin Source File
  47106. +
  47107. +SOURCE=.\libsqlite\src\btree.h
  47108. +# End Source File
  47109. +# Begin Source File
  47110. +
  47111. +SOURCE=.\libsqlite\src\btree_rb.c
  47112. +# End Source File
  47113. +# Begin Source File
  47114. +
  47115. +SOURCE=.\libsqlite\src\build.c
  47116. +# End Source File
  47117. +# Begin Source File
  47118. +
  47119. +SOURCE=.\libsqlite\src\config.h
  47120. +# End Source File
  47121. +# Begin Source File
  47122. +
  47123. +SOURCE=.\libsqlite\src\copy.c
  47124. +# End Source File
  47125. +# Begin Source File
  47126. +
  47127. +SOURCE=.\libsqlite\src\date.c
  47128. +# End Source File
  47129. +# Begin Source File
  47130. +
  47131. +SOURCE=.\libsqlite\src\delete.c
  47132. +# End Source File
  47133. +# Begin Source File
  47134. +
  47135. +SOURCE=.\libsqlite\src\encode.c
  47136. +# End Source File
  47137. +# Begin Source File
  47138. +
  47139. +SOURCE=.\libsqlite\src\expr.c
  47140. +# End Source File
  47141. +# Begin Source File
  47142. +
  47143. +SOURCE=.\libsqlite\src\func.c
  47144. +# End Source File
  47145. +# Begin Source File
  47146. +
  47147. +SOURCE=.\libsqlite\src\hash.c
  47148. +# End Source File
  47149. +# Begin Source File
  47150. +
  47151. +SOURCE=.\libsqlite\src\hash.h
  47152. +# End Source File
  47153. +# Begin Source File
  47154. +
  47155. +SOURCE=.\libsqlite\src\insert.c
  47156. +# End Source File
  47157. +# Begin Source File
  47158. +
  47159. +SOURCE=.\libsqlite\src\main.c
  47160. +# End Source File
  47161. +# Begin Source File
  47162. +
  47163. +SOURCE=.\libsqlite\src\opcodes.c
  47164. +# End Source File
  47165. +# Begin Source File
  47166. +
  47167. +SOURCE=.\libsqlite\src\opcodes.h
  47168. +# End Source File
  47169. +# Begin Source File
  47170. +
  47171. +SOURCE=.\libsqlite\src\os.c
  47172. +# End Source File
  47173. +# Begin Source File
  47174. +
  47175. +SOURCE=.\libsqlite\src\os.h
  47176. +# End Source File
  47177. +# Begin Source File
  47178. +
  47179. +SOURCE=.\libsqlite\src\pager.c
  47180. +# End Source File
  47181. +# Begin Source File
  47182. +
  47183. +SOURCE=.\libsqlite\src\pager.h
  47184. +# End Source File
  47185. +# Begin Source File
  47186. +
  47187. +SOURCE=.\libsqlite\src\parse.c
  47188. +# End Source File
  47189. +# Begin Source File
  47190. +
  47191. +SOURCE=.\libsqlite\src\parse.h
  47192. +# End Source File
  47193. +# Begin Source File
  47194. +
  47195. +SOURCE=.\libsqlite\src\pragma.c
  47196. +# End Source File
  47197. +# Begin Source File
  47198. +
  47199. +SOURCE=.\libsqlite\src\printf.c
  47200. +# End Source File
  47201. +# Begin Source File
  47202. +
  47203. +SOURCE=.\libsqlite\src\random.c
  47204. +# End Source File
  47205. +# Begin Source File
  47206. +
  47207. +SOURCE=.\libsqlite\src\select.c
  47208. +# End Source File
  47209. +# Begin Source File
  47210. +
  47211. +SOURCE=.\libsqlite\src\sqlite.h
  47212. +# End Source File
  47213. +# Begin Source File
  47214. +
  47215. +SOURCE=.\libsqlite\src\sqlite.w32.h
  47216. +
  47217. +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
  47218. +
  47219. +# Begin Custom Build
  47220. +InputDir=.\libsqlite\src
  47221. +InputPath=.\libsqlite\src\sqlite.w32.h
  47222. +
  47223. +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  47224. + copy $(InputPath) $(InputDir)\sqlite.h
  47225. +
  47226. +# End Custom Build
  47227. +
  47228. +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
  47229. +
  47230. +# Begin Custom Build
  47231. +InputDir=.\libsqlite\src
  47232. +InputPath=.\libsqlite\src\sqlite.w32.h
  47233. +
  47234. +"$(InputDir)\sqlite.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  47235. + copy $(InputPath) $(InputDir)\sqlite.h
  47236. +
  47237. +# End Custom Build
  47238. +
  47239. +!ENDIF
  47240. +
  47241. +# End Source File
  47242. +# Begin Source File
  47243. +
  47244. +SOURCE=.\libsqlite\src\sqlite_config.w32.h
  47245. +
  47246. +!IF "$(CFG)" == "sqlite - Win32 Release_TS"
  47247. +
  47248. +# Begin Custom Build
  47249. +InputDir=.\libsqlite\src
  47250. +InputPath=.\libsqlite\src\sqlite_config.w32.h
  47251. +
  47252. +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  47253. + copy $(InputPath) $(InputDir)\config.h
  47254. +
  47255. +# End Custom Build
  47256. +
  47257. +!ELSEIF "$(CFG)" == "sqlite - Win32 Debug_TS"
  47258. +
  47259. +# Begin Custom Build
  47260. +InputDir=.\libsqlite\src
  47261. +InputPath=.\libsqlite\src\sqlite_config.w32.h
  47262. +
  47263. +"$(InputDir)\config.h" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
  47264. + copy $(InputPath) $(InputDir)\config.h
  47265. +
  47266. +# End Custom Build
  47267. +
  47268. +!ENDIF
  47269. +
  47270. +# End Source File
  47271. +# Begin Source File
  47272. +
  47273. +SOURCE=.\libsqlite\src\sqliteInt.h
  47274. +# End Source File
  47275. +# Begin Source File
  47276. +
  47277. +SOURCE=.\libsqlite\src\table.c
  47278. +# End Source File
  47279. +# Begin Source File
  47280. +
  47281. +SOURCE=.\libsqlite\src\tokenize.c
  47282. +# End Source File
  47283. +# Begin Source File
  47284. +
  47285. +SOURCE=.\libsqlite\src\trigger.c
  47286. +# End Source File
  47287. +# Begin Source File
  47288. +
  47289. +SOURCE=.\libsqlite\src\update.c
  47290. +# End Source File
  47291. +# Begin Source File
  47292. +
  47293. +SOURCE=.\libsqlite\src\util.c
  47294. +# End Source File
  47295. +# Begin Source File
  47296. +
  47297. +SOURCE=.\libsqlite\src\vacuum.c
  47298. +# End Source File
  47299. +# Begin Source File
  47300. +
  47301. +SOURCE=.\libsqlite\src\vdbe.c
  47302. +# End Source File
  47303. +# Begin Source File
  47304. +
  47305. +SOURCE=.\libsqlite\src\vdbe.h
  47306. +# End Source File
  47307. +# Begin Source File
  47308. +
  47309. +SOURCE=.\libsqlite\src\vdbeaux.c
  47310. +# End Source File
  47311. +# Begin Source File
  47312. +
  47313. +SOURCE=.\libsqlite\src\where.c
  47314. +# End Source File
  47315. +# End Group
  47316. +# Begin Source File
  47317. +
  47318. +SOURCE=.\php_sqlite.def
  47319. +# End Source File
  47320. +# Begin Source File
  47321. +
  47322. +SOURCE=.\sqlite.c
  47323. +# ADD CPP /I "libsqlite\src"
  47324. +# End Source File
  47325. +# End Group
  47326. +# Begin Group "Header Files"
  47327. +
  47328. +# PROP Default_Filter "h;hpp;hxx;hm;inl"
  47329. +# Begin Source File
  47330. +
  47331. +SOURCE=.\php_sqlite.h
  47332. +# End Source File
  47333. +# End Group
  47334. +# End Target
  47335. +# End Project
  47336. --- /dev/null
  47337. +++ b/ext/sqlite/sqlite.php
  47338. @@ -0,0 +1,36 @@
  47339. +<?php
  47340. +if (!extension_loaded("sqlite")) {
  47341. + dl("sqlite.so");
  47342. + if (!extension_loaded("sqlite")) {
  47343. + exit("Please enable SQLite support\n");
  47344. + }
  47345. +}
  47346. +
  47347. +debug_zval_dump(sqlite_libversion());
  47348. +debug_zval_dump(sqlite_libencoding());
  47349. +
  47350. +$s = sqlite_open("weztest.sqlite", 0666, $err);
  47351. +
  47352. +debug_zval_dump($err);
  47353. +debug_zval_dump($s);
  47354. +
  47355. +$r = sqlite_query("create table foo (a INTEGER PRIMARY KEY, b INTEGER )", $s);
  47356. +debug_zval_dump(sqlite_last_error($s));
  47357. +debug_zval_dump(sqlite_error_string(sqlite_last_error($s)));
  47358. +
  47359. +$r = sqlite_query("select *, php('md5', sql) as o from sqlite_master", $s);
  47360. +debug_zval_dump($r);
  47361. +debug_zval_dump(sqlite_num_rows($r));
  47362. +debug_zval_dump(sqlite_num_fields($r));
  47363. +
  47364. +for ($j = 0; $j < sqlite_num_fields($r); $j++) {
  47365. + echo "Field $j is " . sqlite_field_name($r, $j) . "\n";
  47366. +}
  47367. +
  47368. +while ($row = sqlite_fetch_array($r, SQLITE_ASSOC)) {
  47369. + print_r($row);
  47370. +}
  47371. +
  47372. +sqlite_close($s);
  47373. +
  47374. +?>
  47375. --- /dev/null
  47376. +++ b/ext/sqlite/tests/blankdb.inc
  47377. @@ -0,0 +1,3 @@
  47378. +<?php #vim:ft=php
  47379. +$db = sqlite_open(":memory:");
  47380. +?>
  47381. --- /dev/null
  47382. +++ b/ext/sqlite/tests/blankdb_oo.inc
  47383. @@ -0,0 +1,3 @@
  47384. +<?php #vim:ft=php
  47385. +$db = new SQLiteDatabase(":memory:");
  47386. +?>
  47387. --- /dev/null
  47388. +++ b/ext/sqlite/tests/bug26911.phpt
  47389. @@ -0,0 +1,12 @@
  47390. +--TEST--
  47391. +Bug #26911 (crash when fetching data from empty queries)
  47392. +--SKIPIF--
  47393. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  47394. +--FILE--
  47395. +<?php
  47396. + $db = sqlite_open(":memory:");
  47397. + $a = sqlite_query($db, " ");
  47398. + echo "I am ok\n";
  47399. +?>
  47400. +--EXPECT--
  47401. +I am ok
  47402. --- /dev/null
  47403. +++ b/ext/sqlite/tests/bug28112.phpt
  47404. @@ -0,0 +1,16 @@
  47405. +--TEST--
  47406. +Bug #28112 (sqlite_query() crashing apache on malformed query)
  47407. +--SKIPIF--
  47408. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  47409. +--FILE--
  47410. +<?php
  47411. +
  47412. +if (!($db = sqlite_open(":memory:", 666, $error))) die ("Couldn't open the database");
  47413. +sqlite_query($db, "create table frob (foo INTEGER PRIMARY KEY, bar text);");
  47414. +$res = @sqlite_array_query($db, "");
  47415. +
  47416. +?>
  47417. +===DONE===
  47418. +<?php exit(0); ?>
  47419. +--EXPECTF--
  47420. +===DONE===
  47421. --- /dev/null
  47422. +++ b/ext/sqlite/tests/bug35248.phpt
  47423. @@ -0,0 +1,15 @@
  47424. +--TEST--
  47425. +Bug #35248 (sqlite_query does not return parse error message)
  47426. +--SKIPIF--
  47427. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  47428. +--FILE--
  47429. +<?php
  47430. + $db = sqlite_open(":memory:");
  47431. + $res = @sqlite_query($db, "asdfesdfa", SQLITE_NUM, $err);
  47432. + var_dump($err);
  47433. + $res = @sqlite_unbuffered_query($db, "asdfesdfa", SQLITE_NUM, $err);
  47434. + var_dump($err);
  47435. +?>
  47436. +--EXPECT--
  47437. +string(30) "near "asdfesdfa": syntax error"
  47438. +string(30) "near "asdfesdfa": syntax error"
  47439. --- /dev/null
  47440. +++ b/ext/sqlite/tests/bug38759.phpt
  47441. @@ -0,0 +1,18 @@
  47442. +--TEST--
  47443. +Bug #38759 (sqlite2 empty query causes segfault)
  47444. +--SKIPIF--
  47445. +<?php
  47446. +if (!extension_loaded("pdo")) print "skip";
  47447. +if (!extension_loaded("sqlite")) print "skip";
  47448. +?>
  47449. +--FILE--
  47450. +<?php
  47451. +
  47452. +$dbh = new PDO('sqlite2::memory:');
  47453. +var_dump($dbh->query(" "));
  47454. +
  47455. +echo "Done\n";
  47456. +?>
  47457. +--EXPECTF--
  47458. +bool(false)
  47459. +Done
  47460. --- /dev/null
  47461. +++ b/ext/sqlite/tests/bug48679.phpt
  47462. @@ -0,0 +1,20 @@
  47463. +--TEST--
  47464. +Bug #48679 (sqlite2 count on unbuffered query causes segfault)
  47465. +--SKIPIF--
  47466. +<?php
  47467. +if (!extension_loaded("sqlite")) print "skip";
  47468. +?>
  47469. +--FILE--
  47470. +<?php
  47471. +
  47472. +try {
  47473. + $x = new sqliteunbuffered;
  47474. + count($x);
  47475. +} catch (SQLiteException $e) {
  47476. + var_dump($e->getMessage());
  47477. +}
  47478. +echo "Done\n";
  47479. +?>
  47480. +--EXPECT--
  47481. +string(41) "Row count is not available for this query"
  47482. +Done
  47483. --- /dev/null
  47484. +++ b/ext/sqlite/tests/pdo/common.phpt
  47485. @@ -0,0 +1,12 @@
  47486. +--TEST--
  47487. +SQLite2
  47488. +--SKIPIF--
  47489. +<?php # vim:ft=php
  47490. +if (!extension_loaded('pdo') || !extension_loaded('sqlite')) print 'skip'; ?>
  47491. +--REDIRECTTEST--
  47492. +return array(
  47493. + 'ENV' => array(
  47494. + 'PDOTEST_DSN' => 'sqlite2::memory:'
  47495. + ),
  47496. + 'TESTS' => 'ext/pdo/tests'
  47497. + );
  47498. --- /dev/null
  47499. +++ b/ext/sqlite/tests/sqlite_001.phpt
  47500. @@ -0,0 +1,16 @@
  47501. +--TEST--
  47502. +sqlite: sqlite_open/close
  47503. +--INI--
  47504. +sqlite.assoc_case=0
  47505. +--SKIPIF--
  47506. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  47507. +--FILE--
  47508. +<?php
  47509. +require_once('blankdb.inc');
  47510. +echo "$db\n";
  47511. +sqlite_close($db);
  47512. +echo "Done\n";
  47513. +?>
  47514. +--EXPECTF--
  47515. +Resource id #%d
  47516. +Done
  47517. --- /dev/null
  47518. +++ b/ext/sqlite/tests/sqlite_002.phpt
  47519. @@ -0,0 +1,32 @@
  47520. +--TEST--
  47521. +sqlite: Simple insert/select
  47522. +--INI--
  47523. +sqlite.assoc_case=0
  47524. +--SKIPIF--
  47525. +<?php # vim:ft=php
  47526. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47527. +--FILE--
  47528. +<?php
  47529. +include "blankdb.inc";
  47530. +
  47531. +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
  47532. +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
  47533. +$r = sqlite_query("SELECT * from foo", $db);
  47534. +var_dump(sqlite_fetch_array($r));
  47535. +sqlite_close($db);
  47536. +?>
  47537. +--EXPECT--
  47538. +array(6) {
  47539. + [0]=>
  47540. + string(10) "2002-01-02"
  47541. + ["c1"]=>
  47542. + string(10) "2002-01-02"
  47543. + [1]=>
  47544. + string(8) "12:49:00"
  47545. + ["c2"]=>
  47546. + string(8) "12:49:00"
  47547. + [2]=>
  47548. + NULL
  47549. + ["c3"]=>
  47550. + NULL
  47551. +}
  47552. --- /dev/null
  47553. +++ b/ext/sqlite/tests/sqlite_003.phpt
  47554. @@ -0,0 +1,52 @@
  47555. +--TEST--
  47556. +sqlite: Simple insert/select, different result represenatation
  47557. +--INI--
  47558. +sqlite.assoc_case=0
  47559. +--SKIPIF--
  47560. +<?php
  47561. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47562. +--FILE--
  47563. +<?php
  47564. +include "blankdb.inc";
  47565. +
  47566. +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
  47567. +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
  47568. +$r = sqlite_query("SELECT * from foo", $db);
  47569. +var_dump(sqlite_fetch_array($r, SQLITE_BOTH));
  47570. +$r = sqlite_query("SELECT * from foo", $db);
  47571. +var_dump(sqlite_fetch_array($r, SQLITE_NUM));
  47572. +$r = sqlite_query("SELECT * from foo", $db);
  47573. +var_dump(sqlite_fetch_array($r, SQLITE_ASSOC));
  47574. +sqlite_close($db);
  47575. +?>
  47576. +--EXPECT--
  47577. +array(6) {
  47578. + [0]=>
  47579. + string(10) "2002-01-02"
  47580. + ["c1"]=>
  47581. + string(10) "2002-01-02"
  47582. + [1]=>
  47583. + string(8) "12:49:00"
  47584. + ["c2"]=>
  47585. + string(8) "12:49:00"
  47586. + [2]=>
  47587. + NULL
  47588. + ["c3"]=>
  47589. + NULL
  47590. +}
  47591. +array(3) {
  47592. + [0]=>
  47593. + string(10) "2002-01-02"
  47594. + [1]=>
  47595. + string(8) "12:49:00"
  47596. + [2]=>
  47597. + NULL
  47598. +}
  47599. +array(3) {
  47600. + ["c1"]=>
  47601. + string(10) "2002-01-02"
  47602. + ["c2"]=>
  47603. + string(8) "12:49:00"
  47604. + ["c3"]=>
  47605. + NULL
  47606. +}
  47607. --- /dev/null
  47608. +++ b/ext/sqlite/tests/sqlite_004.phpt
  47609. @@ -0,0 +1,49 @@
  47610. +--TEST--
  47611. +sqlite: binary encoding
  47612. +--INI--
  47613. +sqlite.assoc_case=0
  47614. +--SKIPIF--
  47615. +<?php # vim:ft=php
  47616. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47617. +--FILE--
  47618. +<?php
  47619. +include "blankdb.inc";
  47620. +
  47621. +$strings = array(
  47622. + "hello",
  47623. + "hello\x01o",
  47624. + "\x01hello there",
  47625. + "hello\x00there",
  47626. + ""
  47627. +);
  47628. +
  47629. +sqlite_query("CREATE TABLE strings(a)", $db);
  47630. +
  47631. +foreach ($strings as $str) {
  47632. + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
  47633. +}
  47634. +
  47635. +$i = 0;
  47636. +$r = sqlite_query("SELECT * from strings", $db);
  47637. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  47638. + if ($row[0] !== $strings[$i]) {
  47639. + echo "FAIL!\n";
  47640. + var_dump($row[0]);
  47641. + var_dump($strings[$i]);
  47642. + } else {
  47643. + echo "OK!\n";
  47644. + }
  47645. + $i++;
  47646. +}
  47647. +
  47648. +sqlite_close($db);
  47649. +
  47650. +echo "DONE!\n";
  47651. +?>
  47652. +--EXPECT--
  47653. +OK!
  47654. +OK!
  47655. +OK!
  47656. +OK!
  47657. +OK!
  47658. +DONE!
  47659. --- /dev/null
  47660. +++ b/ext/sqlite/tests/sqlite_005.phpt
  47661. @@ -0,0 +1,50 @@
  47662. +--TEST--
  47663. +sqlite: aggregate functions
  47664. +--INI--
  47665. +sqlite.assoc_case=0
  47666. +--SKIPIF--
  47667. +<?php # vim:ft=php
  47668. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47669. +--FILE--
  47670. +<?php
  47671. +include "blankdb.inc";
  47672. +
  47673. +$data = array(
  47674. + "one",
  47675. + "two",
  47676. + "three"
  47677. + );
  47678. +
  47679. +sqlite_query("CREATE TABLE strings(a)", $db);
  47680. +
  47681. +foreach ($data as $str) {
  47682. + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
  47683. +}
  47684. +
  47685. +function cat_step(&$context, $string)
  47686. +{
  47687. + $context .= $string;
  47688. +}
  47689. +
  47690. +function cat_fin(&$context)
  47691. +{
  47692. + return $context;
  47693. +}
  47694. +
  47695. +sqlite_create_aggregate($db, "cat", "cat_step", "cat_fin");
  47696. +
  47697. +$r = sqlite_query("SELECT cat(a) from strings", $db);
  47698. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  47699. + var_dump($row);
  47700. +}
  47701. +
  47702. +sqlite_close($db);
  47703. +
  47704. +echo "DONE!\n";
  47705. +?>
  47706. +--EXPECT--
  47707. +array(1) {
  47708. + [0]=>
  47709. + string(11) "onetwothree"
  47710. +}
  47711. +DONE!
  47712. --- /dev/null
  47713. +++ b/ext/sqlite/tests/sqlite_006.phpt
  47714. @@ -0,0 +1,55 @@
  47715. +--TEST--
  47716. +sqlite: regular functions
  47717. +--INI--
  47718. +sqlite.assoc_case=0
  47719. +--SKIPIF--
  47720. +<?php # vim:ft=php
  47721. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47722. +--FILE--
  47723. +<?php
  47724. +include "blankdb.inc";
  47725. +
  47726. +$data = array(
  47727. + array("one", "uno"),
  47728. + array("two", "dos"),
  47729. + array("three", "tres"),
  47730. + );
  47731. +
  47732. +sqlite_query("CREATE TABLE strings(a,b)", $db);
  47733. +
  47734. +function implode_args()
  47735. +{
  47736. + $args = func_get_args();
  47737. + $sep = array_shift($args);
  47738. + return implode($sep, $args);
  47739. +}
  47740. +
  47741. +foreach ($data as $row) {
  47742. + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($row[0]) . "','" . sqlite_escape_string($row[1]) . "')", $db);
  47743. +}
  47744. +
  47745. +sqlite_create_function($db, "implode", "implode_args");
  47746. +
  47747. +$r = sqlite_query("SELECT implode('-', a, b) from strings", $db);
  47748. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  47749. + var_dump($row);
  47750. +}
  47751. +
  47752. +sqlite_close($db);
  47753. +
  47754. +echo "DONE!\n";
  47755. +?>
  47756. +--EXPECT--
  47757. +array(1) {
  47758. + [0]=>
  47759. + string(7) "one-uno"
  47760. +}
  47761. +array(1) {
  47762. + [0]=>
  47763. + string(7) "two-dos"
  47764. +}
  47765. +array(1) {
  47766. + [0]=>
  47767. + string(10) "three-tres"
  47768. +}
  47769. +DONE!
  47770. --- /dev/null
  47771. +++ b/ext/sqlite/tests/sqlite_007.phpt
  47772. @@ -0,0 +1,52 @@
  47773. +--TEST--
  47774. +sqlite: Simple insert/select (unbuffered)
  47775. +--INI--
  47776. +sqlite.assoc_case=0
  47777. +--SKIPIF--
  47778. +<?php
  47779. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47780. +--FILE--
  47781. +<?php
  47782. +include "blankdb.inc";
  47783. +
  47784. +sqlite_query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))", $db);
  47785. +sqlite_query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)", $db);
  47786. +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
  47787. +var_dump(sqlite_fetch_array($r, SQLITE_BOTH));
  47788. +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
  47789. +var_dump(sqlite_fetch_array($r, SQLITE_NUM));
  47790. +$r = sqlite_unbuffered_query("SELECT * from foo", $db);
  47791. +var_dump(sqlite_fetch_array($r, SQLITE_ASSOC));
  47792. +sqlite_close($db);
  47793. +?>
  47794. +--EXPECT--
  47795. +array(6) {
  47796. + [0]=>
  47797. + string(10) "2002-01-02"
  47798. + ["c1"]=>
  47799. + string(10) "2002-01-02"
  47800. + [1]=>
  47801. + string(8) "12:49:00"
  47802. + ["c2"]=>
  47803. + string(8) "12:49:00"
  47804. + [2]=>
  47805. + NULL
  47806. + ["c3"]=>
  47807. + NULL
  47808. +}
  47809. +array(3) {
  47810. + [0]=>
  47811. + string(10) "2002-01-02"
  47812. + [1]=>
  47813. + string(8) "12:49:00"
  47814. + [2]=>
  47815. + NULL
  47816. +}
  47817. +array(3) {
  47818. + ["c1"]=>
  47819. + string(10) "2002-01-02"
  47820. + ["c2"]=>
  47821. + string(8) "12:49:00"
  47822. + ["c3"]=>
  47823. + NULL
  47824. +}
  47825. --- /dev/null
  47826. +++ b/ext/sqlite/tests/sqlite_008.phpt
  47827. @@ -0,0 +1,46 @@
  47828. +--TEST--
  47829. +sqlite: fetch all (buffered)
  47830. +--INI--
  47831. +sqlite.assoc_case=0
  47832. +--SKIPIF--
  47833. +<?php # vim:ft=php
  47834. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47835. +--FILE--
  47836. +<?php
  47837. +include "blankdb.inc";
  47838. +
  47839. +$data = array(
  47840. + "one",
  47841. + "two",
  47842. + "three"
  47843. + );
  47844. +
  47845. +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
  47846. +
  47847. +foreach ($data as $str) {
  47848. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  47849. +}
  47850. +
  47851. +$r = sqlite_query("SELECT a from strings", $db);
  47852. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  47853. + var_dump($row);
  47854. +}
  47855. +
  47856. +sqlite_close($db);
  47857. +
  47858. +echo "DONE!\n";
  47859. +?>
  47860. +--EXPECT--
  47861. +array(1) {
  47862. + [0]=>
  47863. + string(3) "one"
  47864. +}
  47865. +array(1) {
  47866. + [0]=>
  47867. + string(3) "two"
  47868. +}
  47869. +array(1) {
  47870. + [0]=>
  47871. + string(5) "three"
  47872. +}
  47873. +DONE!
  47874. --- /dev/null
  47875. +++ b/ext/sqlite/tests/sqlite_009.phpt
  47876. @@ -0,0 +1,46 @@
  47877. +--TEST--
  47878. +sqlite: fetch all (unbuffered)
  47879. +--INI--
  47880. +sqlite.assoc_case=0
  47881. +--SKIPIF--
  47882. +<?php # vim:ft=php
  47883. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47884. +--FILE--
  47885. +<?php
  47886. +include "blankdb.inc";
  47887. +
  47888. +$data = array(
  47889. + "one",
  47890. + "two",
  47891. + "three"
  47892. + );
  47893. +
  47894. +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
  47895. +
  47896. +foreach ($data as $str) {
  47897. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  47898. +}
  47899. +
  47900. +$r = sqlite_unbuffered_query("SELECT a from strings", $db);
  47901. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  47902. + var_dump($row);
  47903. +}
  47904. +
  47905. +sqlite_close($db);
  47906. +
  47907. +echo "DONE!\n";
  47908. +?>
  47909. +--EXPECT--
  47910. +array(1) {
  47911. + [0]=>
  47912. + string(3) "one"
  47913. +}
  47914. +array(1) {
  47915. + [0]=>
  47916. + string(3) "two"
  47917. +}
  47918. +array(1) {
  47919. + [0]=>
  47920. + string(5) "three"
  47921. +}
  47922. +DONE!
  47923. --- /dev/null
  47924. +++ b/ext/sqlite/tests/sqlite_010.phpt
  47925. @@ -0,0 +1,81 @@
  47926. +--TEST--
  47927. +sqlite: fetch all (iterator)
  47928. +--INI--
  47929. +sqlite.assoc_case=0
  47930. +--SKIPIF--
  47931. +<?php # vim:ft=php
  47932. +if (!extension_loaded("sqlite")) print "skip"; ?>
  47933. +--FILE--
  47934. +<?php
  47935. +include "blankdb.inc";
  47936. +
  47937. +$data = array(
  47938. + "one",
  47939. + "two",
  47940. + "three"
  47941. + );
  47942. +
  47943. +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
  47944. +
  47945. +foreach ($data as $str) {
  47946. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  47947. +}
  47948. +
  47949. +$r = sqlite_unbuffered_query("SELECT a from strings", $db);
  47950. +while (sqlite_valid($r)) {
  47951. + var_dump(sqlite_current($r, SQLITE_NUM));
  47952. + sqlite_next($r);
  47953. +}
  47954. +$r = sqlite_query("SELECT a from strings", $db);
  47955. +while (sqlite_valid($r)) {
  47956. + var_dump(sqlite_current($r, SQLITE_NUM));
  47957. + sqlite_next($r);
  47958. +}
  47959. +sqlite_rewind($r);
  47960. +while (sqlite_valid($r)) {
  47961. + var_dump(sqlite_current($r, SQLITE_NUM));
  47962. + sqlite_next($r);
  47963. +}
  47964. +
  47965. +sqlite_close($db);
  47966. +
  47967. +echo "DONE!\n";
  47968. +?>
  47969. +--EXPECT--
  47970. +array(1) {
  47971. + [0]=>
  47972. + string(3) "one"
  47973. +}
  47974. +array(1) {
  47975. + [0]=>
  47976. + string(3) "two"
  47977. +}
  47978. +array(1) {
  47979. + [0]=>
  47980. + string(5) "three"
  47981. +}
  47982. +array(1) {
  47983. + [0]=>
  47984. + string(3) "one"
  47985. +}
  47986. +array(1) {
  47987. + [0]=>
  47988. + string(3) "two"
  47989. +}
  47990. +array(1) {
  47991. + [0]=>
  47992. + string(5) "three"
  47993. +}
  47994. +array(1) {
  47995. + [0]=>
  47996. + string(3) "one"
  47997. +}
  47998. +array(1) {
  47999. + [0]=>
  48000. + string(3) "two"
  48001. +}
  48002. +array(1) {
  48003. + [0]=>
  48004. + string(5) "three"
  48005. +}
  48006. +DONE!
  48007. --- /dev/null
  48008. +++ b/ext/sqlite/tests/sqlite_011.phpt
  48009. @@ -0,0 +1,34 @@
  48010. +--TEST--
  48011. +sqlite: returned associative column names
  48012. +--INI--
  48013. +sqlite.assoc_case=0
  48014. +--SKIPIF--
  48015. +<?php
  48016. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48017. +--FILE--
  48018. +<?php
  48019. +include "blankdb.inc";
  48020. +
  48021. +sqlite_query("CREATE TABLE foo (c1 char, c2 char, c3 char)", $db);
  48022. +sqlite_query("CREATE TABLE bar (c1 char, c2 char, c3 char)", $db);
  48023. +sqlite_query("INSERT INTO foo VALUES ('1', '2', '3')", $db);
  48024. +sqlite_query("INSERT INTO bar VALUES ('4', '5', '6')", $db);
  48025. +$r = sqlite_query("SELECT * from foo, bar", $db, SQLITE_ASSOC);
  48026. +var_dump(sqlite_fetch_array($r));
  48027. +sqlite_close($db);
  48028. +?>
  48029. +--EXPECT--
  48030. +array(6) {
  48031. + ["foo.c1"]=>
  48032. + string(1) "1"
  48033. + ["foo.c2"]=>
  48034. + string(1) "2"
  48035. + ["foo.c3"]=>
  48036. + string(1) "3"
  48037. + ["bar.c1"]=>
  48038. + string(1) "4"
  48039. + ["bar.c2"]=>
  48040. + string(1) "5"
  48041. + ["bar.c3"]=>
  48042. + string(1) "6"
  48043. +}
  48044. --- /dev/null
  48045. +++ b/ext/sqlite/tests/sqlite_012.phpt
  48046. @@ -0,0 +1,38 @@
  48047. +--TEST--
  48048. +sqlite: read field names
  48049. +--INI--
  48050. +sqlite.assoc_case=0
  48051. +--SKIPIF--
  48052. +<?php # vim:ft=php
  48053. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48054. +--FILE--
  48055. +<?php
  48056. +include "blankdb.inc";
  48057. +
  48058. +sqlite_query("CREATE TABLE strings(foo VARCHAR, bar VARCHAR, baz VARCHAR)", $db);
  48059. +
  48060. +echo "Buffered\n";
  48061. +$r = sqlite_query("SELECT * from strings", $db);
  48062. +for($i=0; $i<sqlite_num_fields($r); $i++) {
  48063. + var_dump(sqlite_field_name($r, $i));
  48064. +}
  48065. +echo "Unbuffered\n";
  48066. +$r = sqlite_unbuffered_query("SELECT * from strings", $db);
  48067. +for($i=0; $i<sqlite_num_fields($r); $i++) {
  48068. + var_dump(sqlite_field_name($r, $i));
  48069. +}
  48070. +
  48071. +sqlite_close($db);
  48072. +
  48073. +echo "DONE!\n";
  48074. +?>
  48075. +--EXPECT--
  48076. +Buffered
  48077. +string(3) "foo"
  48078. +string(3) "bar"
  48079. +string(3) "baz"
  48080. +Unbuffered
  48081. +string(3) "foo"
  48082. +string(3) "bar"
  48083. +string(3) "baz"
  48084. +DONE!
  48085. --- /dev/null
  48086. +++ b/ext/sqlite/tests/sqlite_013.phpt
  48087. @@ -0,0 +1,78 @@
  48088. +--TEST--
  48089. +sqlite: fetch column
  48090. +--INI--
  48091. +sqlite.assoc_case=0
  48092. +--SKIPIF--
  48093. +<?php # vim:ft=php
  48094. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48095. +--FILE--
  48096. +<?php
  48097. +include "blankdb.inc";
  48098. +
  48099. +$data = array(
  48100. + array (0 => 'one', 1 => 'two'),
  48101. + array (0 => 'three', 1 => 'four')
  48102. + );
  48103. +
  48104. +sqlite_query("CREATE TABLE strings(a VARCHAR, b VARCHAR)", $db);
  48105. +
  48106. +foreach ($data as $str) {
  48107. + sqlite_query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')", $db);
  48108. +}
  48109. +
  48110. +echo "====BUFFERED====\n";
  48111. +$r = sqlite_query("SELECT a, b from strings", $db);
  48112. +while (sqlite_valid($r)) {
  48113. + var_dump(sqlite_current($r, SQLITE_NUM));
  48114. + var_dump(sqlite_column($r, 0));
  48115. + var_dump(sqlite_column($r, 1));
  48116. + var_dump(sqlite_column($r, 'a'));
  48117. + var_dump(sqlite_column($r, 'b'));
  48118. + sqlite_next($r);
  48119. +}
  48120. +echo "====UNBUFFERED====\n";
  48121. +$r = sqlite_unbuffered_query("SELECT a, b from strings", $db);
  48122. +while (sqlite_valid($r)) {
  48123. + var_dump(sqlite_column($r, 0));
  48124. + var_dump(sqlite_column($r, 'b'));
  48125. + var_dump(sqlite_column($r, 1));
  48126. + var_dump(sqlite_column($r, 'a'));
  48127. + sqlite_next($r);
  48128. +}
  48129. +
  48130. +sqlite_close($db);
  48131. +
  48132. +echo "DONE!\n";
  48133. +?>
  48134. +--EXPECT--
  48135. +====BUFFERED====
  48136. +array(2) {
  48137. + [0]=>
  48138. + string(3) "one"
  48139. + [1]=>
  48140. + string(3) "two"
  48141. +}
  48142. +string(3) "one"
  48143. +string(3) "two"
  48144. +string(3) "one"
  48145. +string(3) "two"
  48146. +array(2) {
  48147. + [0]=>
  48148. + string(5) "three"
  48149. + [1]=>
  48150. + string(4) "four"
  48151. +}
  48152. +string(5) "three"
  48153. +string(4) "four"
  48154. +string(5) "three"
  48155. +string(4) "four"
  48156. +====UNBUFFERED====
  48157. +string(3) "one"
  48158. +string(3) "two"
  48159. +NULL
  48160. +NULL
  48161. +string(5) "three"
  48162. +string(4) "four"
  48163. +NULL
  48164. +NULL
  48165. +DONE!
  48166. --- /dev/null
  48167. +++ b/ext/sqlite/tests/sqlite_014.phpt
  48168. @@ -0,0 +1,120 @@
  48169. +--TEST--
  48170. +sqlite: fetch all (fetch_all)
  48171. +--INI--
  48172. +sqlite.assoc_case=0
  48173. +--SKIPIF--
  48174. +<?php # vim:ft=php
  48175. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48176. +--FILE--
  48177. +<?php
  48178. +include "blankdb.inc";
  48179. +
  48180. +$data = array(
  48181. + "one",
  48182. + "two",
  48183. + "three"
  48184. + );
  48185. +
  48186. +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
  48187. +
  48188. +foreach ($data as $str) {
  48189. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  48190. +}
  48191. +
  48192. +echo "unbuffered twice\n";
  48193. +$r = sqlite_unbuffered_query("SELECT a from strings", $db, SQLITE_NUM);
  48194. +var_dump(sqlite_fetch_all($r));
  48195. +var_dump(sqlite_fetch_all($r));
  48196. +
  48197. +echo "unbuffered with fetch_array\n";
  48198. +$r = sqlite_unbuffered_query("SELECT a from strings", $db, SQLITE_NUM);
  48199. +var_dump(sqlite_fetch_array($r));
  48200. +var_dump(sqlite_fetch_all($r));
  48201. +
  48202. +echo "buffered\n";
  48203. +$r = sqlite_query("SELECT a from strings", $db, SQLITE_NUM);
  48204. +var_dump(sqlite_fetch_all($r));
  48205. +var_dump(sqlite_fetch_array($r));
  48206. +var_dump(sqlite_fetch_all($r));
  48207. +
  48208. +sqlite_close($db);
  48209. +
  48210. +echo "DONE!\n";
  48211. +?>
  48212. +--EXPECTF--
  48213. +unbuffered twice
  48214. +array(3) {
  48215. + [0]=>
  48216. + array(1) {
  48217. + [0]=>
  48218. + string(3) "one"
  48219. + }
  48220. + [1]=>
  48221. + array(1) {
  48222. + [0]=>
  48223. + string(3) "two"
  48224. + }
  48225. + [2]=>
  48226. + array(1) {
  48227. + [0]=>
  48228. + string(5) "three"
  48229. + }
  48230. +}
  48231. +
  48232. +Warning: sqlite_fetch_all(): One or more rowsets were already returned; returning NULL this time in %ssqlite_014.php on line %d
  48233. +array(0) {
  48234. +}
  48235. +unbuffered with fetch_array
  48236. +array(1) {
  48237. + [0]=>
  48238. + string(3) "one"
  48239. +}
  48240. +array(2) {
  48241. + [0]=>
  48242. + array(1) {
  48243. + [0]=>
  48244. + string(3) "two"
  48245. + }
  48246. + [1]=>
  48247. + array(1) {
  48248. + [0]=>
  48249. + string(5) "three"
  48250. + }
  48251. +}
  48252. +buffered
  48253. +array(3) {
  48254. + [0]=>
  48255. + array(1) {
  48256. + [0]=>
  48257. + string(3) "one"
  48258. + }
  48259. + [1]=>
  48260. + array(1) {
  48261. + [0]=>
  48262. + string(3) "two"
  48263. + }
  48264. + [2]=>
  48265. + array(1) {
  48266. + [0]=>
  48267. + string(5) "three"
  48268. + }
  48269. +}
  48270. +bool(false)
  48271. +array(3) {
  48272. + [0]=>
  48273. + array(1) {
  48274. + [0]=>
  48275. + string(3) "one"
  48276. + }
  48277. + [1]=>
  48278. + array(1) {
  48279. + [0]=>
  48280. + string(3) "two"
  48281. + }
  48282. + [2]=>
  48283. + array(1) {
  48284. + [0]=>
  48285. + string(5) "three"
  48286. + }
  48287. +}
  48288. +DONE!
  48289. --- /dev/null
  48290. +++ b/ext/sqlite/tests/sqlite_015.phpt
  48291. @@ -0,0 +1,49 @@
  48292. +--TEST--
  48293. +sqlite: fetch all (array_query)
  48294. +--INI--
  48295. +sqlite.assoc_case=0
  48296. +--SKIPIF--
  48297. +<?php # vim:ft=php
  48298. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48299. +--FILE--
  48300. +<?php
  48301. +include "blankdb.inc";
  48302. +
  48303. +$data = array(
  48304. + "one",
  48305. + "two",
  48306. + "three"
  48307. + );
  48308. +
  48309. +sqlite_query("CREATE TABLE strings(a VARCHAR)", $db);
  48310. +
  48311. +foreach ($data as $str) {
  48312. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  48313. +}
  48314. +
  48315. +$res = sqlite_array_query("SELECT a from strings", $db, SQLITE_NUM);
  48316. +var_dump($res);
  48317. +
  48318. +$db = null;
  48319. +
  48320. +echo "DONE!\n";
  48321. +?>
  48322. +--EXPECTF--
  48323. +array(3) {
  48324. + [0]=>
  48325. + array(1) {
  48326. + [0]=>
  48327. + string(3) "one"
  48328. + }
  48329. + [1]=>
  48330. + array(1) {
  48331. + [0]=>
  48332. + string(3) "two"
  48333. + }
  48334. + [2]=>
  48335. + array(1) {
  48336. + [0]=>
  48337. + string(5) "three"
  48338. + }
  48339. +}
  48340. +DONE!
  48341. --- /dev/null
  48342. +++ b/ext/sqlite/tests/sqlite_016.phpt
  48343. @@ -0,0 +1,45 @@
  48344. +--TEST--
  48345. +sqlite: fetch single
  48346. +--INI--
  48347. +sqlite.assoc_case=0
  48348. +--SKIPIF--
  48349. +<?php # vim:ft=php
  48350. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48351. +--FILE--
  48352. +<?php
  48353. +include "blankdb.inc";
  48354. +
  48355. +$data = array(
  48356. + array (0 => 'one', 1 => 'two'),
  48357. + array (0 => 'three', 1 => 'four')
  48358. + );
  48359. +
  48360. +sqlite_query("CREATE TABLE strings(a VARCHAR, b VARCHAR)", $db);
  48361. +
  48362. +foreach ($data as $str) {
  48363. + sqlite_query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')", $db);
  48364. +}
  48365. +
  48366. +echo "====BUFFERED====\n";
  48367. +$r = sqlite_query("SELECT a, b from strings", $db);
  48368. +while (sqlite_valid($r)) {
  48369. + var_dump(sqlite_fetch_single($r));
  48370. +}
  48371. +echo "====UNBUFFERED====\n";
  48372. +$r = sqlite_unbuffered_query("SELECT a, b from strings", $db);
  48373. +while (sqlite_valid($r)) {
  48374. + var_dump(sqlite_fetch_single($r));
  48375. +}
  48376. +
  48377. +sqlite_close($db);
  48378. +
  48379. +echo "DONE!\n";
  48380. +?>
  48381. +--EXPECT--
  48382. +====BUFFERED====
  48383. +string(3) "one"
  48384. +string(5) "three"
  48385. +====UNBUFFERED====
  48386. +string(3) "one"
  48387. +string(5) "three"
  48388. +DONE!
  48389. --- /dev/null
  48390. +++ b/ext/sqlite/tests/sqlite_017.phpt
  48391. @@ -0,0 +1,33 @@
  48392. +--TEST--
  48393. +sqlite: UDF binary handling functions
  48394. +--SKIPIF--
  48395. +<?php # vim:ft=php
  48396. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48397. +--FILE--
  48398. +<?php
  48399. +
  48400. +$data = array(
  48401. + "hello there",
  48402. + "this has a \x00 char in the middle",
  48403. + "\x01 this has an 0x01 at the start",
  48404. + "this has \x01 in the middle"
  48405. + );
  48406. +
  48407. +foreach ($data as $item) {
  48408. + $coded = sqlite_udf_encode_binary($item);
  48409. + echo bin2hex($coded) . "\n";
  48410. + $decoded = sqlite_udf_decode_binary($coded);
  48411. + if ($item != $decoded) {
  48412. + echo "FAIL! $item decoded is $decoded\n";
  48413. + }
  48414. +}
  48415. +
  48416. +echo "OK!\n";
  48417. +
  48418. +?>
  48419. +--EXPECT--
  48420. +68656c6c6f207468657265
  48421. +0101736768721f6760721f601fff1f626760711f686d1f7367641f6c6863636b64
  48422. +0102ff1e726667711e665f711e5f6c1e2e762e2f1e5f721e7266631e71725f7072
  48423. +7468697320686173200120696e20746865206d6964646c65
  48424. +OK!
  48425. --- /dev/null
  48426. +++ b/ext/sqlite/tests/sqlite_018.phpt
  48427. @@ -0,0 +1,14 @@
  48428. +--TEST--
  48429. +sqlite: crash on bad queries inside sqlite_array_query()
  48430. +--SKIPIF--
  48431. +<?php # vim:ft=php
  48432. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48433. +--FILE--
  48434. +<?php
  48435. +include "blankdb.inc";
  48436. +
  48437. +sqlite_array_query($db, "SELECT foo FROM foobar");
  48438. +sqlite_close($db);
  48439. +?>
  48440. +--EXPECTF--
  48441. +Warning: sqlite_array_query(): no such table: foobar in %s on line %d
  48442. --- /dev/null
  48443. +++ b/ext/sqlite/tests/sqlite_019.phpt
  48444. @@ -0,0 +1,47 @@
  48445. +--TEST--
  48446. +sqlite: single query
  48447. +--SKIPIF--
  48448. +<?php # vim:ft=php
  48449. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48450. +--FILE--
  48451. +<?php
  48452. +include "blankdb.inc";
  48453. +
  48454. +sqlite_query($db, "CREATE TABLE test_db ( id INTEGER PRIMARY KEY, data VARCHAR(100) )");
  48455. +for ($i = 0; $i < 10; $i++) {
  48456. + sqlite_query($db, "INSERT INTO test_db (data) VALUES('{$i}data')");
  48457. +}
  48458. +sqlite_query($db, "INSERT INTO test_db (data) VALUES(NULL)");
  48459. +
  48460. +var_dump(sqlite_single_query($db, "SELECT id FROM test_db WHERE id=5"));
  48461. +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id=4"));
  48462. +var_dump(sqlite_single_query($db, "SELECT data FROM test_db WHERE id=6"));
  48463. +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id < 5"));
  48464. +var_dump(sqlite_single_query($db, "SELECT * FROM test db WHERE id < 4"));
  48465. +var_dump(sqlite_single_query($db, "SELECT * FROM test_db WHERE id=999999"));
  48466. +var_dump(sqlite_single_query($db, "SELECT id FROM test_db WHERE id=5", FALSE));
  48467. +
  48468. +sqlite_close($db);
  48469. +?>
  48470. +--EXPECTF--
  48471. +string(1) "5"
  48472. +string(1) "4"
  48473. +string(5) "5data"
  48474. +array(4) {
  48475. + [0]=>
  48476. + string(1) "1"
  48477. + [1]=>
  48478. + string(1) "2"
  48479. + [2]=>
  48480. + string(1) "3"
  48481. + [3]=>
  48482. + string(1) "4"
  48483. +}
  48484. +
  48485. +Warning: sqlite_single_query(): no such table: test in %s on line %d
  48486. +bool(false)
  48487. +NULL
  48488. +array(1) {
  48489. + [0]=>
  48490. + string(1) "5"
  48491. +}
  48492. --- /dev/null
  48493. +++ b/ext/sqlite/tests/sqlite_022.phpt
  48494. @@ -0,0 +1,101 @@
  48495. +--TEST--
  48496. +sqlite: sqlite_seek
  48497. +--INI--
  48498. +sqlite.assoc_case=0
  48499. +--SKIPIF--
  48500. +<?php # vim:ft=php
  48501. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48502. +--FILE--
  48503. +<?php
  48504. +include "blankdb.inc";
  48505. +
  48506. +$data = array(
  48507. + "one",
  48508. + "two",
  48509. + "three"
  48510. + );
  48511. +
  48512. +sqlite_query("CREATE TABLE strings(a)", $db);
  48513. +
  48514. +foreach ($data as $str) {
  48515. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  48516. +}
  48517. +
  48518. +$res = sqlite_query("SELECT a FROM strings", $db, SQLITE_NUM);
  48519. +for ($idx = -1; $idx < 4; $idx++) {
  48520. + echo "====SEEK:$idx====\n";
  48521. + sqlite_seek($res, $idx);
  48522. + var_dump(sqlite_current($res));
  48523. +}
  48524. +echo "====AGAIN====\n";
  48525. +for ($idx = -1; $idx < 4; $idx++) {
  48526. + echo "====SEEK:$idx====\n";
  48527. + sqlite_seek($res, $idx);
  48528. + var_dump(sqlite_current($res));
  48529. +}
  48530. +
  48531. +sqlite_close($db);
  48532. +
  48533. +echo "====DONE!====\n";
  48534. +?>
  48535. +--EXPECTF--
  48536. +====SEEK:-1====
  48537. +
  48538. +Warning: sqlite_seek(): row -1 out of range in %ssqlite_022.php on line %d
  48539. +array(1) {
  48540. + [0]=>
  48541. + string(3) "one"
  48542. +}
  48543. +====SEEK:0====
  48544. +array(1) {
  48545. + [0]=>
  48546. + string(3) "one"
  48547. +}
  48548. +====SEEK:1====
  48549. +array(1) {
  48550. + [0]=>
  48551. + string(3) "two"
  48552. +}
  48553. +====SEEK:2====
  48554. +array(1) {
  48555. + [0]=>
  48556. + string(5) "three"
  48557. +}
  48558. +====SEEK:3====
  48559. +
  48560. +Warning: sqlite_seek(): row 3 out of range in %ssqlite_022.php on line %d
  48561. +array(1) {
  48562. + [0]=>
  48563. + string(5) "three"
  48564. +}
  48565. +====AGAIN====
  48566. +====SEEK:-1====
  48567. +
  48568. +Warning: sqlite_seek(): row -1 out of range in %ssqlite_022.php on line %d
  48569. +array(1) {
  48570. + [0]=>
  48571. + string(5) "three"
  48572. +}
  48573. +====SEEK:0====
  48574. +array(1) {
  48575. + [0]=>
  48576. + string(3) "one"
  48577. +}
  48578. +====SEEK:1====
  48579. +array(1) {
  48580. + [0]=>
  48581. + string(3) "two"
  48582. +}
  48583. +====SEEK:2====
  48584. +array(1) {
  48585. + [0]=>
  48586. + string(5) "three"
  48587. +}
  48588. +====SEEK:3====
  48589. +
  48590. +Warning: sqlite_seek(): row 3 out of range in %ssqlite_022.php on line %d
  48591. +array(1) {
  48592. + [0]=>
  48593. + string(5) "three"
  48594. +}
  48595. +====DONE!====
  48596. --- /dev/null
  48597. +++ b/ext/sqlite/tests/sqlite_023.phpt
  48598. @@ -0,0 +1,105 @@
  48599. +--TEST--
  48600. +sqlite: sqlite_[has_]prev
  48601. +--INI--
  48602. +sqlite.assoc_case=0
  48603. +--SKIPIF--
  48604. +<?php # vim:ft=php
  48605. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48606. +--FILE--
  48607. +<?php
  48608. +include "blankdb.inc";
  48609. +
  48610. +$data = array(
  48611. + "one",
  48612. + "two",
  48613. + "three"
  48614. + );
  48615. +
  48616. +sqlite_query("CREATE TABLE strings(a)", $db);
  48617. +
  48618. +foreach ($data as $str) {
  48619. + sqlite_query("INSERT INTO strings VALUES('$str')", $db);
  48620. +}
  48621. +
  48622. +$r = sqlite_query("SELECT a FROM strings", $db, SQLITE_NUM);
  48623. +
  48624. +echo "====TRAVERSE====\n";
  48625. +for(sqlite_rewind($r); sqlite_valid($r); sqlite_next($r)) {
  48626. + var_dump(sqlite_current($r));
  48627. +
  48628. +}
  48629. +echo "====REVERSE====\n";
  48630. +do {
  48631. + sqlite_prev($r);
  48632. + var_dump(sqlite_current($r));
  48633. +} while(sqlite_has_prev($r));
  48634. +
  48635. +echo "====UNBUFFERED====\n";
  48636. +
  48637. +$r = sqlite_unbuffered_query("SELECT a FROM strings", $db, SQLITE_NUM);
  48638. +
  48639. +echo "====TRAVERSE====\n";
  48640. +for(sqlite_rewind($r); sqlite_valid($r); sqlite_next($r)) {
  48641. + var_dump(sqlite_current($r));
  48642. +
  48643. +}
  48644. +echo "====REVERSE====\n";
  48645. +do {
  48646. + sqlite_prev($r);
  48647. + var_dump(sqlite_current($r));
  48648. +} while(sqlite_has_prev($r));
  48649. +
  48650. +sqlite_close($db);
  48651. +
  48652. +echo "====DONE!====\n";
  48653. +?>
  48654. +--EXPECTF--
  48655. +====TRAVERSE====
  48656. +array(1) {
  48657. + [0]=>
  48658. + string(3) "one"
  48659. +}
  48660. +array(1) {
  48661. + [0]=>
  48662. + string(3) "two"
  48663. +}
  48664. +array(1) {
  48665. + [0]=>
  48666. + string(5) "three"
  48667. +}
  48668. +====REVERSE====
  48669. +array(1) {
  48670. + [0]=>
  48671. + string(5) "three"
  48672. +}
  48673. +array(1) {
  48674. + [0]=>
  48675. + string(3) "two"
  48676. +}
  48677. +array(1) {
  48678. + [0]=>
  48679. + string(3) "one"
  48680. +}
  48681. +====UNBUFFERED====
  48682. +====TRAVERSE====
  48683. +
  48684. +Warning: sqlite_rewind(): Cannot rewind an unbuffered result set in %ssqlite_023.php on line %d
  48685. +array(1) {
  48686. + [0]=>
  48687. + string(3) "one"
  48688. +}
  48689. +array(1) {
  48690. + [0]=>
  48691. + string(3) "two"
  48692. +}
  48693. +array(1) {
  48694. + [0]=>
  48695. + string(5) "three"
  48696. +}
  48697. +====REVERSE====
  48698. +
  48699. +Warning: sqlite_prev(): you cannot use sqlite_prev on unbuffered querys in %ssqlite_023.php on line %d
  48700. +bool(false)
  48701. +
  48702. +Warning: sqlite_has_prev(): you cannot use sqlite_has_prev on unbuffered querys in %ssqlite_023.php on line %d
  48703. +====DONE!====
  48704. --- /dev/null
  48705. +++ b/ext/sqlite/tests/sqlite_024.phpt
  48706. @@ -0,0 +1,76 @@
  48707. +--TEST--
  48708. +sqlite: sqlite_fetch_object
  48709. +--INI--
  48710. +sqlite.assoc_case=0
  48711. +--SKIPIF--
  48712. +<?php # vim:ft=php
  48713. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48714. +--FILE--
  48715. +<?php
  48716. +include "blankdb.inc";
  48717. +
  48718. +class class24 {
  48719. + function __construct() {
  48720. + echo __METHOD__ . "\n";
  48721. + }
  48722. +}
  48723. +
  48724. +$data = array(
  48725. + "one",
  48726. + "two",
  48727. + "three"
  48728. + );
  48729. +
  48730. +sqlite_query($db, "CREATE TABLE strings(a)");
  48731. +
  48732. +foreach ($data as $str) {
  48733. + sqlite_query($db, "INSERT INTO strings VALUES('$str')");
  48734. +}
  48735. +
  48736. +echo "====class24====\n";
  48737. +$res = sqlite_query($db, "SELECT a FROM strings", SQLITE_ASSOC);
  48738. +while (sqlite_valid($res)) {
  48739. + var_dump(sqlite_fetch_object($res, 'class24'));
  48740. +}
  48741. +
  48742. +echo "====stdclass====\n";
  48743. +$res = sqlite_query($db, "SELECT a FROM strings", SQLITE_ASSOC);
  48744. +while (sqlite_valid($res)) {
  48745. + var_dump(sqlite_fetch_object($res));
  48746. +}
  48747. +
  48748. +sqlite_close($db);
  48749. +
  48750. +echo "====DONE!====\n";
  48751. +?>
  48752. +--EXPECTF--
  48753. +====class24====
  48754. +class24::__construct
  48755. +object(class24)#%d (1) {
  48756. + ["a"]=>
  48757. + string(3) "one"
  48758. +}
  48759. +class24::__construct
  48760. +object(class24)#%d (1) {
  48761. + ["a"]=>
  48762. + string(3) "two"
  48763. +}
  48764. +class24::__construct
  48765. +object(class24)#%d (1) {
  48766. + ["a"]=>
  48767. + string(5) "three"
  48768. +}
  48769. +====stdclass====
  48770. +object(stdClass)#%d (1) {
  48771. + ["a"]=>
  48772. + string(3) "one"
  48773. +}
  48774. +object(stdClass)#%d (1) {
  48775. + ["a"]=>
  48776. + string(3) "two"
  48777. +}
  48778. +object(stdClass)#%d (1) {
  48779. + ["a"]=>
  48780. + string(5) "three"
  48781. +}
  48782. +====DONE!====
  48783. --- /dev/null
  48784. +++ b/ext/sqlite/tests/sqlite_025.phpt
  48785. @@ -0,0 +1,38 @@
  48786. +--TEST--
  48787. +sqlite: sqlite_fetch_object in a loop
  48788. +--INI--
  48789. +sqlite.assoc_case=0
  48790. +--SKIPIF--
  48791. +<?php # vim:ft=php
  48792. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48793. +--FILE--
  48794. +<?php
  48795. +include "blankdb.inc";
  48796. +
  48797. +sqlite_query($db, "CREATE TABLE strings(a)");
  48798. +
  48799. +foreach (array("one", "two", "three") as $str) {
  48800. + sqlite_query($db, "INSERT INTO strings VALUES('$str')");
  48801. +}
  48802. +
  48803. +$res = sqlite_query("SELECT * FROM strings", $db);
  48804. +
  48805. +while (($obj = sqlite_fetch_object($res))) {
  48806. + var_dump($obj);
  48807. +}
  48808. +
  48809. +sqlite_close($db);
  48810. +?>
  48811. +--EXPECTF--
  48812. +object(stdClass)#1 (1) {
  48813. + ["a"]=>
  48814. + string(3) "one"
  48815. +}
  48816. +object(stdClass)#2 (1) {
  48817. + ["a"]=>
  48818. + string(3) "two"
  48819. +}
  48820. +object(stdClass)#1 (1) {
  48821. + ["a"]=>
  48822. + string(5) "three"
  48823. +}
  48824. \ No newline at end of file
  48825. --- /dev/null
  48826. +++ b/ext/sqlite/tests/sqlite_026.phpt
  48827. @@ -0,0 +1,27 @@
  48828. +--TEST--
  48829. +sqlite: sqlite_fetch_column_types
  48830. +--SKIPIF--
  48831. +<?php # vim:ft=php
  48832. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48833. +--FILE--
  48834. +<?php
  48835. +include "blankdb.inc";
  48836. +
  48837. +sqlite_query($db, "CREATE TABLE strings(a, b INTEGER, c VARCHAR(10), d)");
  48838. +sqlite_query($db, "INSERT INTO strings VALUES('1', '2', '3', 'abc')");
  48839. +
  48840. +var_dump(sqlite_fetch_column_types($db, "strings"));
  48841. +
  48842. +sqlite_close($db);
  48843. +?>
  48844. +--EXPECT--
  48845. +array(4) {
  48846. + ["a"]=>
  48847. + string(0) ""
  48848. + ["b"]=>
  48849. + string(7) "INTEGER"
  48850. + ["c"]=>
  48851. + string(11) "VARCHAR(10)"
  48852. + ["d"]=>
  48853. + string(0) ""
  48854. +}
  48855. --- /dev/null
  48856. +++ b/ext/sqlite/tests/sqlite_027.phpt
  48857. @@ -0,0 +1,15 @@
  48858. +--TEST--
  48859. +sqlite: crash inside sqlite_escape_string() & sqlite_udf_encode_binary
  48860. +--SKIPIF--
  48861. +<?php # vim:ft=php
  48862. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48863. +--INI--
  48864. +memory_limit=-1
  48865. +--FILE--
  48866. +<?php
  48867. + var_dump(strlen(sqlite_escape_string(str_repeat("\0", 20000000))));
  48868. + var_dump(strlen(sqlite_udf_encode_binary(str_repeat("\0", 20000000))));
  48869. +?>
  48870. +--EXPECT--
  48871. +int(20000002)
  48872. +int(20000002)
  48873. --- /dev/null
  48874. +++ b/ext/sqlite/tests/sqlite_closures_001.phpt
  48875. @@ -0,0 +1,54 @@
  48876. +--TEST--
  48877. +sqlite: aggregate functions with closures
  48878. +--INI--
  48879. +sqlite.assoc_case=0
  48880. +--SKIPIF--
  48881. +<?php # vim:ft=php
  48882. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48883. +--FILE--
  48884. +<?php
  48885. +include "blankdb.inc";
  48886. +
  48887. +$data = array(
  48888. + "one",
  48889. + "two",
  48890. + "three"
  48891. + );
  48892. +
  48893. +sqlite_query("CREATE TABLE strings(a)", $db);
  48894. +
  48895. +foreach ($data as $str) {
  48896. + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($str) . "')", $db);
  48897. +}
  48898. +
  48899. +function cat_step(&$context, $string)
  48900. +{
  48901. + $context .= $string;
  48902. +}
  48903. +
  48904. +function cat_fin(&$context)
  48905. +{
  48906. + return $context;
  48907. +}
  48908. +
  48909. +sqlite_create_aggregate($db, "cat", function (&$context, $string) {
  48910. + $context .= $string;
  48911. +}, function (&$context) {
  48912. + return $context;
  48913. +});
  48914. +
  48915. +$r = sqlite_query("SELECT cat(a) from strings", $db);
  48916. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  48917. + var_dump($row);
  48918. +}
  48919. +
  48920. +sqlite_close($db);
  48921. +
  48922. +echo "DONE!\n";
  48923. +?>
  48924. +--EXPECT--
  48925. +array(1) {
  48926. + [0]=>
  48927. + string(11) "onetwothree"
  48928. +}
  48929. +DONE!
  48930. --- /dev/null
  48931. +++ b/ext/sqlite/tests/sqlite_closures_002.phpt
  48932. @@ -0,0 +1,52 @@
  48933. +--TEST--
  48934. +sqlite: regular functions with closures
  48935. +--INI--
  48936. +sqlite.assoc_case=0
  48937. +--SKIPIF--
  48938. +<?php # vim:ft=php
  48939. +if (!extension_loaded("sqlite")) print "skip"; ?>
  48940. +--FILE--
  48941. +<?php
  48942. +include "blankdb.inc";
  48943. +
  48944. +$data = array(
  48945. + array("one", "uno"),
  48946. + array("two", "dos"),
  48947. + array("three", "tres"),
  48948. + );
  48949. +
  48950. +sqlite_query("CREATE TABLE strings(a,b)", $db);
  48951. +
  48952. +foreach ($data as $row) {
  48953. + sqlite_query("INSERT INTO strings VALUES('" . sqlite_escape_string($row[0]) . "','" . sqlite_escape_string($row[1]) . "')", $db);
  48954. +}
  48955. +
  48956. +sqlite_create_function($db, "implode", function () {
  48957. + $args = func_get_args();
  48958. + $sep = array_shift($args);
  48959. + return implode($sep, $args);
  48960. +});
  48961. +
  48962. +$r = sqlite_query("SELECT implode('-', a, b) from strings", $db);
  48963. +while ($row = sqlite_fetch_array($r, SQLITE_NUM)) {
  48964. + var_dump($row);
  48965. +}
  48966. +
  48967. +sqlite_close($db);
  48968. +
  48969. +echo "DONE!\n";
  48970. +?>
  48971. +--EXPECT--
  48972. +array(1) {
  48973. + [0]=>
  48974. + string(7) "one-uno"
  48975. +}
  48976. +array(1) {
  48977. + [0]=>
  48978. + string(7) "two-dos"
  48979. +}
  48980. +array(1) {
  48981. + [0]=>
  48982. + string(10) "three-tres"
  48983. +}
  48984. +DONE!
  48985. --- /dev/null
  48986. +++ b/ext/sqlite/tests/sqlitedatabase_arrayquery.phpt
  48987. @@ -0,0 +1,23 @@
  48988. +--TEST--
  48989. +Testing SQLiteDatabase::ArrayQuery with NULL-byte string
  48990. +--SKIPIF--
  48991. +<?php
  48992. +if (!extension_loaded("sqlite")) print "skip";
  48993. +?>
  48994. +--FILE--
  48995. +<?php
  48996. +
  48997. +$method = new ReflectionMethod('sqlitedatabase::arrayquery');
  48998. +
  48999. +$class = $method->getDeclaringClass()->newInstanceArgs(array(':memory:'));
  49000. +
  49001. +$p = "\0";
  49002. +
  49003. +$method->invokeArgs($class, array_fill(0, 2, $p));
  49004. +$method->invokeArgs($class, array_fill(0, 1, $p));
  49005. +
  49006. +?>
  49007. +--EXPECTF--
  49008. +Warning: SQLiteDatabase::arrayQuery() expects parameter 2 to be long, string given in %s on line %d
  49009. +
  49010. +Warning: SQLiteDatabase::arrayQuery(): Cannot execute empty query. in %s on line %d
  49011. --- /dev/null
  49012. +++ b/ext/sqlite/tests/sqlite_exec_basic.phpt
  49013. @@ -0,0 +1,34 @@
  49014. +--TEST--
  49015. +Test sqlite_exec() function : basic functionality
  49016. +--SKIPIF--
  49017. +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
  49018. +--FILE--
  49019. +<?php
  49020. +/* Prototype : boolean sqlite_exec(string query, resource db[, string &error_message])
  49021. + * Description: Executes a result-less query against a given database
  49022. + * Source code: ext/sqlite/sqlite.c
  49023. + * Alias to functions:
  49024. + */
  49025. +
  49026. +echo "*** Testing sqlite_exec() : basic functionality ***\n";
  49027. +
  49028. +// set up variables
  49029. +$query = 'CREATE TABLE foobar (id INTEGER PRIMARY KEY, name CHAR(255));';
  49030. +$error_message = null;
  49031. +
  49032. +// procedural
  49033. +$db = sqlite_open(':memory:');
  49034. +var_dump( sqlite_exec($db, $query) );
  49035. +sqlite_close($db);
  49036. +
  49037. +// oo-style
  49038. +$db = new SQLiteDatabase(':memory:');
  49039. +var_dump( $db->queryExec($query, $error_message) );
  49040. +
  49041. +?>
  49042. +===DONE===
  49043. +--EXPECTF--
  49044. +*** Testing sqlite_exec() : basic functionality ***
  49045. +bool(true)
  49046. +bool(true)
  49047. +===DONE===
  49048. --- /dev/null
  49049. +++ b/ext/sqlite/tests/sqlite_exec_error.phpt
  49050. @@ -0,0 +1,44 @@
  49051. +--TEST--
  49052. +Test sqlite_exec() function : error behaviour and functionality
  49053. +--SKIPIF--
  49054. +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
  49055. +--FILE--
  49056. +<?php
  49057. +/* Prototype : boolean sqlite_exec(string query, resource db[, string &error_message])
  49058. + * Description: Executes a result-less query against a given database
  49059. + * Source code: ext/sqlite/sqlite.c
  49060. + * Alias to functions:
  49061. + */
  49062. +
  49063. +echo "*** Testing sqlite_exec() : error functionality ***\n";
  49064. +
  49065. +// set up variables
  49066. +$fail = 'CRE ATE TABLE';
  49067. +$error_message = null;
  49068. +
  49069. +// procedural
  49070. +$db = sqlite_open(':memory:');
  49071. +var_dump( sqlite_exec($db, $fail, $error_message) );
  49072. +var_dump( $error_message );
  49073. +var_dump( sqlite_exec($db) );
  49074. +sqlite_close($db);
  49075. +
  49076. +// oo-style
  49077. +$db = new SQLiteDatabase(':memory:');
  49078. +var_dump( $db->queryExec($fail, $error_message, 'fooparam') );
  49079. +
  49080. +?>
  49081. +===DONE===
  49082. +--EXPECTF--
  49083. +*** Testing sqlite_exec() : error functionality ***
  49084. +
  49085. +Warning: sqlite_exec(): near "CRE": syntax error in %s on line %d
  49086. +bool(false)
  49087. +%string|unicode%(24) "near "CRE": syntax error"
  49088. +
  49089. +Warning: sqlite_exec() expects at least 2 parameters, 1 given in %s on line %d
  49090. +NULL
  49091. +
  49092. +Warning: SQLiteDatabase::queryExec() expects at most 2 parameters, 3 given in %s on line %d
  49093. +NULL
  49094. +===DONE===
  49095. --- /dev/null
  49096. +++ b/ext/sqlite/tests/sqlite_last_error_basic.phpt
  49097. @@ -0,0 +1,48 @@
  49098. +--TEST--
  49099. +Test sqlite_last_error() function : basic functionality
  49100. +--SKIPIF--
  49101. +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
  49102. +--FILE--
  49103. +<?php
  49104. +/* Prototype : int sqlite_last_error(resource db)
  49105. + * Description: Returns the error code of the last error for a database.
  49106. + * Source code: ext/sqlite/sqlite.c
  49107. + * Alias to functions:
  49108. + */
  49109. +
  49110. +echo "*** Testing sqlite_last_error() : basic functionality ***\n";
  49111. +
  49112. +// set up variables
  49113. +$query = 'CREATE TAB LE foobar (id INTEGER PRIMARY KEY, name CHAR(255));';
  49114. +$query_ok = 'CREATE TABLE foobar (id INTEGER, name CHAR(255));';
  49115. +
  49116. +// procedural
  49117. +$db = sqlite_open(':memory:');
  49118. +var_dump( sqlite_last_error($db) === SQLITE_OK );
  49119. +sqlite_exec($db, $query);
  49120. +var_dump( sqlite_last_error($db) === SQLITE_ERROR );
  49121. +sqlite_exec($db, $query_ok);
  49122. +var_dump( sqlite_last_error($db) === SQLITE_OK );
  49123. +sqlite_close($db);
  49124. +
  49125. +// oo-style
  49126. +$db = new SQLiteDatabase(':memory:');
  49127. +$db->queryExec($query);
  49128. +var_dump( $db->lastError() === SQLITE_ERROR );
  49129. +$db->queryExec($query_ok);
  49130. +var_dump( $db->lastError() === SQLITE_OK );
  49131. +
  49132. +?>
  49133. +===DONE===
  49134. +--EXPECTF--
  49135. +*** Testing sqlite_last_error() : basic functionality ***
  49136. +bool(true)
  49137. +
  49138. +Warning: sqlite_exec(): near "TAB": syntax error in %s on line %d
  49139. +bool(true)
  49140. +bool(true)
  49141. +
  49142. +Warning: SQLiteDatabase::queryExec(): near "TAB": syntax error in %s on line %d
  49143. +bool(true)
  49144. +bool(true)
  49145. +===DONE===
  49146. --- /dev/null
  49147. +++ b/ext/sqlite/tests/sqlite_last_error_error.phpt
  49148. @@ -0,0 +1,47 @@
  49149. +--TEST--
  49150. +Test sqlite_last_error() function : error conditions
  49151. +--SKIPIF--
  49152. +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
  49153. +--FILE--
  49154. +<?php
  49155. +/* Prototype : int sqlite_last_error(resource db)
  49156. + * Description: Returns the error code of the last error for a database.
  49157. + * Source code: ext/sqlite/sqlite.c
  49158. + * Alias to functions:
  49159. + */
  49160. +
  49161. +echo "*** Testing sqlite_last_error() : error conditions ***\n";
  49162. +
  49163. +// Zero arguments
  49164. +echo "\n-- Testing sqlite_last_error() function with Zero arguments --\n";
  49165. +var_dump( sqlite_last_error() );
  49166. +
  49167. +//Test sqlite_last_error with one more than the expected number of arguments
  49168. +echo "\n-- Testing sqlite_last_error() function with more than expected no. of arguments --\n";
  49169. +
  49170. +$db = sqlite_open(':memory:');
  49171. +$extra_arg = 10;
  49172. +var_dump( sqlite_last_error($db, $extra_arg) );
  49173. +sqlite_close($db);
  49174. +
  49175. +$db = new SQLiteDatabase(':memory:');
  49176. +var_dump( $db->lastError($extra_arg) );
  49177. +
  49178. +?>
  49179. +===DONE===
  49180. +--EXPECTF--
  49181. +*** Testing sqlite_last_error() : error conditions ***
  49182. +
  49183. +-- Testing sqlite_last_error() function with Zero arguments --
  49184. +
  49185. +Warning: sqlite_last_error() expects exactly 1 parameter, 0 given in %s on line %d
  49186. +NULL
  49187. +
  49188. +-- Testing sqlite_last_error() function with more than expected no. of arguments --
  49189. +
  49190. +Warning: sqlite_last_error() expects exactly 1 parameter, 2 given in %s on line %d
  49191. +NULL
  49192. +
  49193. +Warning: SQLiteDatabase::lastError() expects exactly 0 parameters, 1 given in %s on line %d
  49194. +NULL
  49195. +===DONE===
  49196. --- /dev/null
  49197. +++ b/ext/sqlite/tests/sqlite_oo_001.phpt
  49198. @@ -0,0 +1,17 @@
  49199. +--TEST--
  49200. +sqlite-oo: sqlite_open/close
  49201. +--INI--
  49202. +sqlite.assoc_case=0
  49203. +--SKIPIF--
  49204. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  49205. +--FILE--
  49206. +<?php
  49207. +require_once('blankdb_oo.inc');
  49208. +var_dump($db);
  49209. +$db = NULL;
  49210. +echo "Done\n";
  49211. +?>
  49212. +--EXPECTF--
  49213. +object(SQLiteDatabase)#%d (0) {
  49214. +}
  49215. +Done
  49216. --- /dev/null
  49217. +++ b/ext/sqlite/tests/sqlite_oo_002.phpt
  49218. @@ -0,0 +1,41 @@
  49219. +--TEST--
  49220. +sqlite-oo: Simple insert/select
  49221. +--INI--
  49222. +sqlite.assoc_case=0
  49223. +--SKIPIF--
  49224. +<?php # vim:ft=php
  49225. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49226. +--FILE--
  49227. +<?php
  49228. +require_once('blankdb_oo.inc');
  49229. +var_dump($db);
  49230. +
  49231. +var_dump($db->query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))"));
  49232. +var_dump($db->query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)"));
  49233. +$r = $db->query("SELECT * from foo");
  49234. +var_dump($r);
  49235. +var_dump($r->fetch());
  49236. +?>
  49237. +--EXPECTF--
  49238. +object(SQLiteDatabase)#%d (0) {
  49239. +}
  49240. +object(SQLiteResult)#%d (0) {
  49241. +}
  49242. +object(SQLiteResult)#%d (0) {
  49243. +}
  49244. +object(SQLiteResult)#%d (0) {
  49245. +}
  49246. +array(6) {
  49247. + [0]=>
  49248. + string(10) "2002-01-02"
  49249. + ["c1"]=>
  49250. + string(10) "2002-01-02"
  49251. + [1]=>
  49252. + string(8) "12:49:00"
  49253. + ["c2"]=>
  49254. + string(8) "12:49:00"
  49255. + [2]=>
  49256. + NULL
  49257. + ["c3"]=>
  49258. + NULL
  49259. +}
  49260. --- /dev/null
  49261. +++ b/ext/sqlite/tests/sqlite_oo_003.phpt
  49262. @@ -0,0 +1,51 @@
  49263. +--TEST--
  49264. +sqlite-oo: Simple insert/select, different result representation
  49265. +--INI--
  49266. +sqlite.assoc_case=0
  49267. +--SKIPIF--
  49268. +<?php # vim:ft=php
  49269. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49270. +--FILE--
  49271. +<?php
  49272. +include "blankdb_oo.inc";
  49273. +
  49274. +$db->query("CREATE TABLE foo(c1 date, c2 time, c3 varchar(64))");
  49275. +$db->query("INSERT INTO foo VALUES ('2002-01-02', '12:49:00', NULL)");
  49276. +$r = $db->query("SELECT * from foo");
  49277. +var_dump($r->fetch(SQLITE_BOTH));
  49278. +$r = $db->query("SELECT * from foo");
  49279. +var_dump($r->fetch(SQLITE_NUM));
  49280. +$r = $db->query("SELECT * from foo");
  49281. +var_dump($r->fetch(SQLITE_ASSOC));
  49282. +?>
  49283. +--EXPECT--
  49284. +array(6) {
  49285. + [0]=>
  49286. + string(10) "2002-01-02"
  49287. + ["c1"]=>
  49288. + string(10) "2002-01-02"
  49289. + [1]=>
  49290. + string(8) "12:49:00"
  49291. + ["c2"]=>
  49292. + string(8) "12:49:00"
  49293. + [2]=>
  49294. + NULL
  49295. + ["c3"]=>
  49296. + NULL
  49297. +}
  49298. +array(3) {
  49299. + [0]=>
  49300. + string(10) "2002-01-02"
  49301. + [1]=>
  49302. + string(8) "12:49:00"
  49303. + [2]=>
  49304. + NULL
  49305. +}
  49306. +array(3) {
  49307. + ["c1"]=>
  49308. + string(10) "2002-01-02"
  49309. + ["c2"]=>
  49310. + string(8) "12:49:00"
  49311. + ["c3"]=>
  49312. + NULL
  49313. +}
  49314. --- /dev/null
  49315. +++ b/ext/sqlite/tests/sqlite_oo_008.phpt
  49316. @@ -0,0 +1,43 @@
  49317. +--TEST--
  49318. +sqlite-oo: fetch all (buffered)
  49319. +--INI--
  49320. +sqlite.assoc_case=0
  49321. +--SKIPIF--
  49322. +<?php # vim:ft=php
  49323. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49324. +--FILE--
  49325. +<?php
  49326. +include "blankdb_oo.inc";
  49327. +
  49328. +$data = array(
  49329. + "one",
  49330. + "two",
  49331. + "three"
  49332. + );
  49333. +
  49334. +$db->query("CREATE TABLE strings(a VARCHAR)");
  49335. +
  49336. +foreach ($data as $str) {
  49337. + $db->query("INSERT INTO strings VALUES('$str')");
  49338. +}
  49339. +
  49340. +$r = $db->query("SELECT a from strings");
  49341. +while ($row = $r->fetch(SQLITE_NUM)) {
  49342. + var_dump($row);
  49343. +}
  49344. +echo "DONE!\n";
  49345. +?>
  49346. +--EXPECT--
  49347. +array(1) {
  49348. + [0]=>
  49349. + string(3) "one"
  49350. +}
  49351. +array(1) {
  49352. + [0]=>
  49353. + string(3) "two"
  49354. +}
  49355. +array(1) {
  49356. + [0]=>
  49357. + string(5) "three"
  49358. +}
  49359. +DONE!
  49360. --- /dev/null
  49361. +++ b/ext/sqlite/tests/sqlite_oo_009.phpt
  49362. @@ -0,0 +1,43 @@
  49363. +--TEST--
  49364. +sqlite-oo: fetch all (unbuffered)
  49365. +--INI--
  49366. +sqlite.assoc_case=0
  49367. +--SKIPIF--
  49368. +<?php # vim:ft=php
  49369. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49370. +--FILE--
  49371. +<?php
  49372. +include "blankdb_oo.inc";
  49373. +
  49374. +$data = array(
  49375. + "one",
  49376. + "two",
  49377. + "three"
  49378. + );
  49379. +
  49380. +$db->query("CREATE TABLE strings(a VARCHAR)");
  49381. +
  49382. +foreach ($data as $str) {
  49383. + $db->query("INSERT INTO strings VALUES('$str')");
  49384. +}
  49385. +
  49386. +$r = $db->unbufferedQuery("SELECT a from strings");
  49387. +while ($row = $r->fetch(SQLITE_NUM)) {
  49388. + var_dump($row);
  49389. +}
  49390. +echo "DONE!\n";
  49391. +?>
  49392. +--EXPECT--
  49393. +array(1) {
  49394. + [0]=>
  49395. + string(3) "one"
  49396. +}
  49397. +array(1) {
  49398. + [0]=>
  49399. + string(3) "two"
  49400. +}
  49401. +array(1) {
  49402. + [0]=>
  49403. + string(5) "three"
  49404. +}
  49405. +DONE!
  49406. --- /dev/null
  49407. +++ b/ext/sqlite/tests/sqlite_oo_010.phpt
  49408. @@ -0,0 +1,44 @@
  49409. +--TEST--
  49410. +sqlite-oo: fetch all (iterator)
  49411. +--INI--
  49412. +sqlite.assoc_case=0
  49413. +--SKIPIF--
  49414. +<?php # vim:ft=php
  49415. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49416. +--FILE--
  49417. +<?php
  49418. +include "blankdb_oo.inc";
  49419. +
  49420. +$data = array(
  49421. + "one",
  49422. + "two",
  49423. + "three"
  49424. + );
  49425. +
  49426. +$db->query("CREATE TABLE strings(a VARCHAR)");
  49427. +
  49428. +foreach ($data as $str) {
  49429. + $db->query("INSERT INTO strings VALUES('$str')");
  49430. +}
  49431. +
  49432. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  49433. +while ($row = $r->valid()) {
  49434. + var_dump($r->current());
  49435. + $r->next();
  49436. +}
  49437. +echo "DONE!\n";
  49438. +?>
  49439. +--EXPECT--
  49440. +array(1) {
  49441. + [0]=>
  49442. + string(3) "one"
  49443. +}
  49444. +array(1) {
  49445. + [0]=>
  49446. + string(3) "two"
  49447. +}
  49448. +array(1) {
  49449. + [0]=>
  49450. + string(5) "three"
  49451. +}
  49452. +DONE!
  49453. --- /dev/null
  49454. +++ b/ext/sqlite/tests/sqlite_oo_011.phpt
  49455. @@ -0,0 +1,33 @@
  49456. +--TEST--
  49457. +sqlite-oo: returned associative column names
  49458. +--INI--
  49459. +sqlite.assoc_case=0
  49460. +--SKIPIF--
  49461. +<?php # vim:ft=php
  49462. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49463. +--FILE--
  49464. +<?php
  49465. +include "blankdb_oo.inc";
  49466. +
  49467. +$db->query("CREATE TABLE foo (c1 char, c2 char, c3 char)");
  49468. +$db->query("CREATE TABLE bar (c1 char, c2 char, c3 char)");
  49469. +$db->query("INSERT INTO foo VALUES ('1', '2', '3')");
  49470. +$db->query("INSERT INTO bar VALUES ('4', '5', '6')");
  49471. +$r = $db->query("SELECT * from foo, bar", SQLITE_ASSOC);
  49472. +var_dump($r->fetch());
  49473. +?>
  49474. +--EXPECT--
  49475. +array(6) {
  49476. + ["foo.c1"]=>
  49477. + string(1) "1"
  49478. + ["foo.c2"]=>
  49479. + string(1) "2"
  49480. + ["foo.c3"]=>
  49481. + string(1) "3"
  49482. + ["bar.c1"]=>
  49483. + string(1) "4"
  49484. + ["bar.c2"]=>
  49485. + string(1) "5"
  49486. + ["bar.c3"]=>
  49487. + string(1) "6"
  49488. +}
  49489. --- /dev/null
  49490. +++ b/ext/sqlite/tests/sqlite_oo_012.phpt
  49491. @@ -0,0 +1,35 @@
  49492. +--TEST--
  49493. +sqlite-oo: read field names
  49494. +--INI--
  49495. +sqlite.assoc_case=0
  49496. +--SKIPIF--
  49497. +<?php # vim:ft=php
  49498. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49499. +--FILE--
  49500. +<?php
  49501. +include "blankdb_oo.inc";
  49502. +
  49503. +$db->query("CREATE TABLE strings(foo VARCHAR, bar VARCHAR, baz VARCHAR)");
  49504. +
  49505. +echo "Buffered\n";
  49506. +$r = $db->query("SELECT * from strings");
  49507. +for($i=0; $i<$r->numFields(); $i++) {
  49508. + var_dump($r->fieldName($i));
  49509. +}
  49510. +echo "Unbuffered\n";
  49511. +$r = $db->unbufferedQuery("SELECT * from strings");
  49512. +for($i=0; $i<$r->numFields(); $i++) {
  49513. + var_dump($r->fieldName($i));
  49514. +}
  49515. +echo "DONE!\n";
  49516. +?>
  49517. +--EXPECT--
  49518. +Buffered
  49519. +string(3) "foo"
  49520. +string(3) "bar"
  49521. +string(3) "baz"
  49522. +Unbuffered
  49523. +string(3) "foo"
  49524. +string(3) "bar"
  49525. +string(3) "baz"
  49526. +DONE!
  49527. --- /dev/null
  49528. +++ b/ext/sqlite/tests/sqlite_oo_013.phpt
  49529. @@ -0,0 +1,75 @@
  49530. +--TEST--
  49531. +sqlite-oo: fetch column
  49532. +--INI--
  49533. +sqlite.assoc_case=0
  49534. +--SKIPIF--
  49535. +<?php # vim:ft=php
  49536. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49537. +--FILE--
  49538. +<?php
  49539. +include "blankdb_oo.inc";
  49540. +
  49541. +$data = array(
  49542. + array (0 => 'one', 1 => 'two'),
  49543. + array (0 => 'three', 1 => 'four')
  49544. + );
  49545. +
  49546. +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
  49547. +
  49548. +foreach ($data as $str) {
  49549. + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
  49550. +}
  49551. +
  49552. +echo "====BUFFERED====\n";
  49553. +$r = $db->query("SELECT a, b from strings");
  49554. +while ($r->valid()) {
  49555. + var_dump($r->current(SQLITE_NUM));
  49556. + var_dump($r->column(0));
  49557. + var_dump($r->column(1));
  49558. + var_dump($r->column('a'));
  49559. + var_dump($r->column('b'));
  49560. + $r->next();
  49561. +}
  49562. +echo "====UNBUFFERED====\n";
  49563. +$r = $db->unbufferedQuery("SELECT a, b from strings");
  49564. +while ($r->valid()) {
  49565. + var_dump($r->column(0));
  49566. + var_dump($r->column('b'));
  49567. + var_dump($r->column(1));
  49568. + var_dump($r->column('a'));
  49569. + $r->next();
  49570. +}
  49571. +echo "DONE!\n";
  49572. +?>
  49573. +--EXPECT--
  49574. +====BUFFERED====
  49575. +array(2) {
  49576. + [0]=>
  49577. + string(3) "one"
  49578. + [1]=>
  49579. + string(3) "two"
  49580. +}
  49581. +string(3) "one"
  49582. +string(3) "two"
  49583. +string(3) "one"
  49584. +string(3) "two"
  49585. +array(2) {
  49586. + [0]=>
  49587. + string(5) "three"
  49588. + [1]=>
  49589. + string(4) "four"
  49590. +}
  49591. +string(5) "three"
  49592. +string(4) "four"
  49593. +string(5) "three"
  49594. +string(4) "four"
  49595. +====UNBUFFERED====
  49596. +string(3) "one"
  49597. +string(3) "two"
  49598. +NULL
  49599. +NULL
  49600. +string(5) "three"
  49601. +string(4) "four"
  49602. +NULL
  49603. +NULL
  49604. +DONE!
  49605. --- /dev/null
  49606. +++ b/ext/sqlite/tests/sqlite_oo_014.phpt
  49607. @@ -0,0 +1,118 @@
  49608. +--TEST--
  49609. +sqlite-oo: fetch all
  49610. +--INI--
  49611. +sqlite.assoc_case=0
  49612. +--SKIPIF--
  49613. +<?php # vim:ft=php
  49614. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49615. +--FILE--
  49616. +<?php
  49617. +include "blankdb_oo.inc";
  49618. +
  49619. +$data = array(
  49620. + "one",
  49621. + "two",
  49622. + "three"
  49623. + );
  49624. +
  49625. +$db->query("CREATE TABLE strings(a VARCHAR)");
  49626. +
  49627. +foreach ($data as $str) {
  49628. + $db->query("INSERT INTO strings VALUES('$str')");
  49629. +}
  49630. +
  49631. +echo "unbuffered twice\n";
  49632. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  49633. +var_dump($r->fetchAll());
  49634. +var_dump($r->fetchAll());
  49635. +
  49636. +echo "unbuffered with fetch_array\n";
  49637. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  49638. +var_dump($r->fetch());
  49639. +var_dump($r->fetchAll());
  49640. +
  49641. +echo "buffered\n";
  49642. +$r = $db->query("SELECT a from strings", SQLITE_NUM);
  49643. +var_dump($r->fetchAll());
  49644. +var_dump($r->fetch());
  49645. +var_dump($r->fetchAll());
  49646. +
  49647. +echo "DONE!\n";
  49648. +?>
  49649. +--EXPECTF--
  49650. +unbuffered twice
  49651. +array(3) {
  49652. + [0]=>
  49653. + array(1) {
  49654. + [0]=>
  49655. + string(3) "one"
  49656. + }
  49657. + [1]=>
  49658. + array(1) {
  49659. + [0]=>
  49660. + string(3) "two"
  49661. + }
  49662. + [2]=>
  49663. + array(1) {
  49664. + [0]=>
  49665. + string(5) "three"
  49666. + }
  49667. +}
  49668. +
  49669. +Warning: SQLiteUnbuffered::fetchAll(): One or more rowsets were already returned; returning NULL this time in %ssqlite_oo_014.php on line %d
  49670. +array(0) {
  49671. +}
  49672. +unbuffered with fetch_array
  49673. +array(1) {
  49674. + [0]=>
  49675. + string(3) "one"
  49676. +}
  49677. +array(2) {
  49678. + [0]=>
  49679. + array(1) {
  49680. + [0]=>
  49681. + string(3) "two"
  49682. + }
  49683. + [1]=>
  49684. + array(1) {
  49685. + [0]=>
  49686. + string(5) "three"
  49687. + }
  49688. +}
  49689. +buffered
  49690. +array(3) {
  49691. + [0]=>
  49692. + array(1) {
  49693. + [0]=>
  49694. + string(3) "one"
  49695. + }
  49696. + [1]=>
  49697. + array(1) {
  49698. + [0]=>
  49699. + string(3) "two"
  49700. + }
  49701. + [2]=>
  49702. + array(1) {
  49703. + [0]=>
  49704. + string(5) "three"
  49705. + }
  49706. +}
  49707. +bool(false)
  49708. +array(3) {
  49709. + [0]=>
  49710. + array(1) {
  49711. + [0]=>
  49712. + string(3) "one"
  49713. + }
  49714. + [1]=>
  49715. + array(1) {
  49716. + [0]=>
  49717. + string(3) "two"
  49718. + }
  49719. + [2]=>
  49720. + array(1) {
  49721. + [0]=>
  49722. + string(5) "three"
  49723. + }
  49724. +}
  49725. +DONE!
  49726. --- /dev/null
  49727. +++ b/ext/sqlite/tests/sqlite_oo_015.phpt
  49728. @@ -0,0 +1,47 @@
  49729. +--TEST--
  49730. +sqlite-oo: array_query
  49731. +--INI--
  49732. +sqlite.assoc_case=0
  49733. +--SKIPIF--
  49734. +<?php # vim:ft=php
  49735. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49736. +--FILE--
  49737. +<?php
  49738. +include "blankdb_oo.inc";
  49739. +
  49740. +$data = array(
  49741. + "one",
  49742. + "two",
  49743. + "three"
  49744. + );
  49745. +
  49746. +$db->query("CREATE TABLE strings(a VARCHAR)");
  49747. +
  49748. +foreach ($data as $str) {
  49749. + $db->query("INSERT INTO strings VALUES('$str')");
  49750. +}
  49751. +
  49752. +$res = $db->arrayQuery("SELECT a from strings", SQLITE_NUM);
  49753. +var_dump($res);
  49754. +
  49755. +echo "DONE!\n";
  49756. +?>
  49757. +--EXPECTF--
  49758. +array(3) {
  49759. + [0]=>
  49760. + array(1) {
  49761. + [0]=>
  49762. + string(3) "one"
  49763. + }
  49764. + [1]=>
  49765. + array(1) {
  49766. + [0]=>
  49767. + string(3) "two"
  49768. + }
  49769. + [2]=>
  49770. + array(1) {
  49771. + [0]=>
  49772. + string(5) "three"
  49773. + }
  49774. +}
  49775. +DONE!
  49776. --- /dev/null
  49777. +++ b/ext/sqlite/tests/sqlite_oo_016.phpt
  49778. @@ -0,0 +1,42 @@
  49779. +--TEST--
  49780. +sqlite-oo: fetch single
  49781. +--INI--
  49782. +sqlite.assoc_case=0
  49783. +--SKIPIF--
  49784. +<?php # vim:ft=php
  49785. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49786. +--FILE--
  49787. +<?php
  49788. +include "blankdb_oo.inc";
  49789. +
  49790. +$data = array(
  49791. + array (0 => 'one', 1 => 'two'),
  49792. + array (0 => 'three', 1 => 'four')
  49793. + );
  49794. +
  49795. +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
  49796. +
  49797. +foreach ($data as $str) {
  49798. + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
  49799. +}
  49800. +
  49801. +echo "====BUFFERED====\n";
  49802. +$r = $db->query("SELECT a, b from strings");
  49803. +while ($r->valid()) {
  49804. + var_dump($r->fetchSingle());
  49805. +}
  49806. +echo "====UNBUFFERED====\n";
  49807. +$r = $db->unbufferedQuery("SELECT a, b from strings");
  49808. +while ($r->valid()) {
  49809. + var_dump($r->fetchSingle());
  49810. +}
  49811. +echo "DONE!\n";
  49812. +?>
  49813. +--EXPECT--
  49814. +====BUFFERED====
  49815. +string(3) "one"
  49816. +string(5) "three"
  49817. +====UNBUFFERED====
  49818. +string(3) "one"
  49819. +string(5) "three"
  49820. +DONE!
  49821. --- /dev/null
  49822. +++ b/ext/sqlite/tests/sqlite_oo_020.phpt
  49823. @@ -0,0 +1,66 @@
  49824. +--TEST--
  49825. +sqlite-oo: factory and exception
  49826. +--INI--
  49827. +sqlite.assoc_case=0
  49828. +--SKIPIF--
  49829. +<?php # vim:ft=php
  49830. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49831. +--FILE--
  49832. +<?php
  49833. +$dbname = tempnam(dirname(__FILE__), "phpsql");
  49834. +function cleanup() {
  49835. + global $db, $dbname;
  49836. +
  49837. + $db = NULL;
  49838. + unlink($dbname);
  49839. +}
  49840. +register_shutdown_function("cleanup");
  49841. +
  49842. +try {
  49843. + $db = sqlite_factory();
  49844. +} catch(SQLiteException $err) {
  49845. + echo "Message: ".$err->getMessage()."\n";
  49846. + echo "File: ".$err->getFile()."\n";
  49847. + //echo "Line: ".$err->getLine()."\n";
  49848. + //print_r($err->getTrace());
  49849. + //echo "BackTrace: ".$err->getTraceAsString()."\n";
  49850. +}
  49851. +
  49852. +$db = sqlite_factory($dbname);
  49853. +
  49854. +$data = array(
  49855. + array (0 => 'one', 1 => 'two'),
  49856. + array (0 => 'three', 1 => 'four')
  49857. + );
  49858. +
  49859. +$db->query("CREATE TABLE strings(a VARCHAR, b VARCHAR)");
  49860. +
  49861. +foreach ($data as $str) {
  49862. + $db->query("INSERT INTO strings VALUES('${str[0]}','${str[1]}')");
  49863. +}
  49864. +
  49865. +$r = $db->unbufferedQuery("SELECT a, b from strings");
  49866. +while ($r->valid()) {
  49867. + var_dump($r->current(SQLITE_NUM));
  49868. + $r->next();
  49869. +}
  49870. +$r = null;
  49871. +$db = null;
  49872. +echo "DONE!\n";
  49873. +?>
  49874. +--EXPECTF--
  49875. +Message: sqlite_factory() expects at least 1 parameter, 0 given
  49876. +File: %ssqlite_oo_020.php
  49877. +array(2) {
  49878. + [0]=>
  49879. + string(3) "one"
  49880. + [1]=>
  49881. + string(3) "two"
  49882. +}
  49883. +array(2) {
  49884. + [0]=>
  49885. + string(5) "three"
  49886. + [1]=>
  49887. + string(4) "four"
  49888. +}
  49889. +DONE!
  49890. --- /dev/null
  49891. +++ b/ext/sqlite/tests/sqlite_oo_021.phpt
  49892. @@ -0,0 +1,48 @@
  49893. +--TEST--
  49894. +sqlite-oo: single query
  49895. +--SKIPIF--
  49896. +<?php # vim:ft=php
  49897. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49898. +--FILE--
  49899. +<?php
  49900. +include "blankdb_oo.inc";
  49901. +
  49902. +$db->query("CREATE TABLE test_db ( id INTEGER PRIMARY KEY, data VARCHAR(100) )");
  49903. +for ($i = 0; $i < 10; $i++) {
  49904. + $db->query("INSERT INTO test_db (data) VALUES('{$i}data')");
  49905. +}
  49906. +$db->query("INSERT INTO test_db (data) VALUES(NULL)");
  49907. +
  49908. +var_dump($db->singleQuery("SELECT id FROM test_db WHERE id=5"));
  49909. +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id=4"));
  49910. +var_dump($db->singleQuery("SELECT data FROM test_db WHERE id=6"));
  49911. +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id < 5"));
  49912. +var_dump($db->singleQuery("SELECT * FROM test db WHERE id < 4"));
  49913. +var_dump($db->singleQuery("SELECT * FROM test_db WHERE id=999999"));
  49914. +var_dump($db->singleQuery("SELECT id FROM test_db WHERE id=5", FALSE));
  49915. +
  49916. +echo "DONE!\n";
  49917. +?>
  49918. +--EXPECTF--
  49919. +string(1) "5"
  49920. +string(1) "4"
  49921. +string(5) "5data"
  49922. +array(4) {
  49923. + [0]=>
  49924. + string(1) "1"
  49925. + [1]=>
  49926. + string(1) "2"
  49927. + [2]=>
  49928. + string(1) "3"
  49929. + [3]=>
  49930. + string(1) "4"
  49931. +}
  49932. +
  49933. +Warning: SQLiteDatabase::singleQuery(): no such table: test in %s on line %d
  49934. +bool(false)
  49935. +NULL
  49936. +array(1) {
  49937. + [0]=>
  49938. + string(1) "5"
  49939. +}
  49940. +DONE!
  49941. --- /dev/null
  49942. +++ b/ext/sqlite/tests/sqlite_oo_022.phpt
  49943. @@ -0,0 +1,98 @@
  49944. +--TEST--
  49945. +sqlite-oo: sqlite::seek
  49946. +--INI--
  49947. +sqlite.assoc_case=0
  49948. +--SKIPIF--
  49949. +<?php # vim:ft=php
  49950. +if (!extension_loaded("sqlite")) print "skip"; ?>
  49951. +--FILE--
  49952. +<?php
  49953. +include "blankdb_oo.inc";
  49954. +
  49955. +$data = array(
  49956. + "one",
  49957. + "two",
  49958. + "three"
  49959. + );
  49960. +
  49961. +$db->query("CREATE TABLE strings(a)");
  49962. +
  49963. +foreach ($data as $str) {
  49964. + $db->query("INSERT INTO strings VALUES('$str')");
  49965. +}
  49966. +
  49967. +$res = $db->query("SELECT a FROM strings", SQLITE_NUM);
  49968. +for ($idx = -1; $idx < 4; $idx++) {
  49969. + echo "====SEEK:$idx====\n";
  49970. + $res->seek($idx);
  49971. + var_dump($res->current());
  49972. +}
  49973. +echo "====AGAIN====\n";
  49974. +for ($idx = -1; $idx < 4; $idx++) {
  49975. + echo "====SEEK:$idx====\n";
  49976. + $res->seek($idx);
  49977. + var_dump($res->current());
  49978. +}
  49979. +echo "====DONE!====\n";
  49980. +?>
  49981. +--EXPECTF--
  49982. +====SEEK:-1====
  49983. +
  49984. +Warning: SQLiteResult::seek(): row -1 out of range in %ssqlite_oo_022.php on line %d
  49985. +array(1) {
  49986. + [0]=>
  49987. + string(3) "one"
  49988. +}
  49989. +====SEEK:0====
  49990. +array(1) {
  49991. + [0]=>
  49992. + string(3) "one"
  49993. +}
  49994. +====SEEK:1====
  49995. +array(1) {
  49996. + [0]=>
  49997. + string(3) "two"
  49998. +}
  49999. +====SEEK:2====
  50000. +array(1) {
  50001. + [0]=>
  50002. + string(5) "three"
  50003. +}
  50004. +====SEEK:3====
  50005. +
  50006. +Warning: SQLiteResult::seek(): row 3 out of range in %ssqlite_oo_022.php on line %d
  50007. +array(1) {
  50008. + [0]=>
  50009. + string(5) "three"
  50010. +}
  50011. +====AGAIN====
  50012. +====SEEK:-1====
  50013. +
  50014. +Warning: SQLiteResult::seek(): row -1 out of range in %ssqlite_oo_022.php on line %d
  50015. +array(1) {
  50016. + [0]=>
  50017. + string(5) "three"
  50018. +}
  50019. +====SEEK:0====
  50020. +array(1) {
  50021. + [0]=>
  50022. + string(3) "one"
  50023. +}
  50024. +====SEEK:1====
  50025. +array(1) {
  50026. + [0]=>
  50027. + string(3) "two"
  50028. +}
  50029. +====SEEK:2====
  50030. +array(1) {
  50031. + [0]=>
  50032. + string(5) "three"
  50033. +}
  50034. +====SEEK:3====
  50035. +
  50036. +Warning: SQLiteResult::seek(): row 3 out of range in %ssqlite_oo_022.php on line %d
  50037. +array(1) {
  50038. + [0]=>
  50039. + string(5) "three"
  50040. +}
  50041. +====DONE!====
  50042. --- /dev/null
  50043. +++ b/ext/sqlite/tests/sqlite_oo_024.phpt
  50044. @@ -0,0 +1,74 @@
  50045. +--TEST--
  50046. +sqlite-oo: sqlite::fetch_object
  50047. +--INI--
  50048. +sqlite.assoc_case=0
  50049. +--SKIPIF--
  50050. +<?php # vim:ft=php
  50051. +if (!extension_loaded("sqlite")) print "skip"; ?>
  50052. +--FILE--
  50053. +<?php
  50054. +include "blankdb_oo.inc";
  50055. +
  50056. +class class24 {
  50057. + function __construct() {
  50058. + echo __METHOD__ . "\n";
  50059. + }
  50060. +}
  50061. +
  50062. +$data = array(
  50063. + "one",
  50064. + "two",
  50065. + "three"
  50066. + );
  50067. +
  50068. +$db->query("CREATE TABLE strings(a)");
  50069. +
  50070. +foreach ($data as $str) {
  50071. + $db->query("INSERT INTO strings VALUES('$str')");
  50072. +}
  50073. +
  50074. +echo "====class24====\n";
  50075. +$res = $db->query("SELECT a FROM strings", SQLITE_ASSOC);
  50076. +while ($res->valid()) {
  50077. + var_dump($res->fetchObject('class24'));
  50078. +}
  50079. +
  50080. +echo "====stdclass====\n";
  50081. +$res = $db->query("SELECT a FROM strings", SQLITE_ASSOC);
  50082. +while ($res->valid()) {
  50083. + var_dump($res->fetchObject());
  50084. +}
  50085. +
  50086. +echo "====DONE!====\n";
  50087. +?>
  50088. +--EXPECTF--
  50089. +====class24====
  50090. +class24::__construct
  50091. +object(class24)#%d (1) {
  50092. + ["a"]=>
  50093. + string(3) "one"
  50094. +}
  50095. +class24::__construct
  50096. +object(class24)#%d (1) {
  50097. + ["a"]=>
  50098. + string(3) "two"
  50099. +}
  50100. +class24::__construct
  50101. +object(class24)#%d (1) {
  50102. + ["a"]=>
  50103. + string(5) "three"
  50104. +}
  50105. +====stdclass====
  50106. +object(stdClass)#%d (1) {
  50107. + ["a"]=>
  50108. + string(3) "one"
  50109. +}
  50110. +object(stdClass)#%d (1) {
  50111. + ["a"]=>
  50112. + string(3) "two"
  50113. +}
  50114. +object(stdClass)#%d (1) {
  50115. + ["a"]=>
  50116. + string(5) "three"
  50117. +}
  50118. +====DONE!====
  50119. --- /dev/null
  50120. +++ b/ext/sqlite/tests/sqlite_oo_025.phpt
  50121. @@ -0,0 +1,103 @@
  50122. +--TEST--
  50123. +sqlite-oo: sqlite / foreach
  50124. +--INI--
  50125. +sqlite.assoc_case=0
  50126. +--SKIPIF--
  50127. +<?php # vim:ft=php
  50128. +if (!extension_loaded("sqlite")) print "skip";
  50129. +?>
  50130. +--FILE--
  50131. +<?php
  50132. +include "blankdb_oo.inc";
  50133. +
  50134. +$data = array(
  50135. + "one",
  50136. + "two",
  50137. + "three"
  50138. + );
  50139. +
  50140. +$db->query("CREATE TABLE strings(a VARCHAR)");
  50141. +
  50142. +foreach ($data as $str) {
  50143. + $db->query("INSERT INTO strings VALUES('$str')");
  50144. +}
  50145. +
  50146. +echo "====UNBUFFERED====\n";
  50147. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  50148. +//var_dump(class_implements($r));
  50149. +foreach($r as $row) {
  50150. + var_dump($row);
  50151. +}
  50152. +echo "====NO-MORE====\n";
  50153. +foreach($r as $row) {
  50154. + var_dump($row);
  50155. +}
  50156. +echo "====DIRECT====\n";
  50157. +foreach($db->unbufferedQuery("SELECT a from strings", SQLITE_NUM) as $row) {
  50158. + var_dump($row);
  50159. +}
  50160. +echo "====BUFFERED====\n";
  50161. +$r = $db->query("SELECT a from strings", SQLITE_NUM);
  50162. +//var_dump(class_implements($r));
  50163. +foreach($r as $row) {
  50164. + var_dump($row);
  50165. +}
  50166. +foreach($r as $row) {
  50167. + var_dump($row);
  50168. +}
  50169. +echo "DONE!\n";
  50170. +?>
  50171. +--EXPECT--
  50172. +====UNBUFFERED====
  50173. +array(1) {
  50174. + [0]=>
  50175. + string(3) "one"
  50176. +}
  50177. +array(1) {
  50178. + [0]=>
  50179. + string(3) "two"
  50180. +}
  50181. +array(1) {
  50182. + [0]=>
  50183. + string(5) "three"
  50184. +}
  50185. +====NO-MORE====
  50186. +====DIRECT====
  50187. +array(1) {
  50188. + [0]=>
  50189. + string(3) "one"
  50190. +}
  50191. +array(1) {
  50192. + [0]=>
  50193. + string(3) "two"
  50194. +}
  50195. +array(1) {
  50196. + [0]=>
  50197. + string(5) "three"
  50198. +}
  50199. +====BUFFERED====
  50200. +array(1) {
  50201. + [0]=>
  50202. + string(3) "one"
  50203. +}
  50204. +array(1) {
  50205. + [0]=>
  50206. + string(3) "two"
  50207. +}
  50208. +array(1) {
  50209. + [0]=>
  50210. + string(5) "three"
  50211. +}
  50212. +array(1) {
  50213. + [0]=>
  50214. + string(3) "one"
  50215. +}
  50216. +array(1) {
  50217. + [0]=>
  50218. + string(3) "two"
  50219. +}
  50220. +array(1) {
  50221. + [0]=>
  50222. + string(5) "three"
  50223. +}
  50224. +DONE!
  50225. --- /dev/null
  50226. +++ b/ext/sqlite/tests/sqlite_oo_026.phpt
  50227. @@ -0,0 +1,56 @@
  50228. +--TEST--
  50229. +sqlite-oo: unbuffered
  50230. +--INI--
  50231. +sqlite.assoc_case=0
  50232. +--SKIPIF--
  50233. +<?php # vim:ft=php
  50234. +if (!extension_loaded("sqlite")) print "skip";
  50235. +?>
  50236. +--FILE--
  50237. +<?php
  50238. +include "blankdb_oo.inc";
  50239. +
  50240. +$data = array(
  50241. + "one",
  50242. + "two",
  50243. + "three"
  50244. + );
  50245. +
  50246. +$db->query("CREATE TABLE strings(a VARCHAR)");
  50247. +
  50248. +foreach ($data as $str) {
  50249. + $db->query("INSERT INTO strings VALUES('$str')");
  50250. +}
  50251. +
  50252. +echo "====FOREACH====\n";
  50253. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  50254. +foreach($r as $idx => $row) {
  50255. + var_dump($row[0]);
  50256. + var_dump($row[0]);
  50257. +}
  50258. +echo "====FOR====\n";
  50259. +$r = $db->unbufferedQuery("SELECT a from strings", SQLITE_NUM);
  50260. +for(;$r->valid(); $r->next()) {
  50261. + $v = $r->column(0);
  50262. + var_dump($v);
  50263. + $c = $r->column(0);
  50264. + var_dump(is_null($c) || $c==$v);
  50265. +}
  50266. +echo "===DONE===\n";
  50267. +?>
  50268. +--EXPECT--
  50269. +====FOREACH====
  50270. +string(3) "one"
  50271. +string(3) "one"
  50272. +string(3) "two"
  50273. +string(3) "two"
  50274. +string(5) "three"
  50275. +string(5) "three"
  50276. +====FOR====
  50277. +string(3) "one"
  50278. +bool(true)
  50279. +string(3) "two"
  50280. +bool(true)
  50281. +string(5) "three"
  50282. +bool(true)
  50283. +===DONE===
  50284. --- /dev/null
  50285. +++ b/ext/sqlite/tests/sqlite_oo_027.phpt
  50286. @@ -0,0 +1,42 @@
  50287. +--TEST--
  50288. +sqlite-oo: changes
  50289. +--INI--
  50290. +sqlite.assoc_case=0
  50291. +--SKIPIF--
  50292. +<?php # vim:ft=php
  50293. +if (!extension_loaded("sqlite")) print "skip";
  50294. +?>
  50295. +--FILE--
  50296. +<?php
  50297. +include "blankdb_oo.inc";
  50298. +
  50299. +$data = array("one", "two", "three");
  50300. +
  50301. +$db->query("CREATE TABLE strings(a VARCHAR)");
  50302. +
  50303. +foreach ($data as $str) {
  50304. + $db->query("INSERT INTO strings VALUES('$str')");
  50305. + echo $db->changes() . "\n";
  50306. +}
  50307. +
  50308. +$db->query("UPDATE strings SET a='foo' WHERE a!='two'");
  50309. +echo $db->changes() . "\n";
  50310. +
  50311. +$db->query("DELETE FROM strings WHERE 1");
  50312. +echo $db->changes() . "\n";
  50313. +
  50314. +$str = '';
  50315. +foreach ($data as $s) {
  50316. + $str .= "INSERT INTO strings VALUES('".$s."');";
  50317. +}
  50318. +$db->query($str);
  50319. +echo $db->changes() . "\n";
  50320. +
  50321. +?>
  50322. +--EXPECT--
  50323. +1
  50324. +1
  50325. +1
  50326. +2
  50327. +3
  50328. +3
  50329. --- /dev/null
  50330. +++ b/ext/sqlite/tests/sqlite_oo_028.phpt
  50331. @@ -0,0 +1,25 @@
  50332. +--TEST--
  50333. +sqlite-oo: sqlite_fetch_column_types
  50334. +--SKIPIF--
  50335. +<?php # vim:ft=php
  50336. +if (!extension_loaded("sqlite")) print "skip"; ?>
  50337. +--FILE--
  50338. +<?php
  50339. +include "blankdb_oo.inc";
  50340. +
  50341. +$db->query("CREATE TABLE strings(a, b INTEGER, c VARCHAR(10), d)");
  50342. +$db->query("INSERT INTO strings VALUES('1', '2', '3', 'abc')");
  50343. +
  50344. +var_dump($db->fetchColumnTypes("strings"));
  50345. +?>
  50346. +--EXPECT--
  50347. +array(4) {
  50348. + ["a"]=>
  50349. + string(0) ""
  50350. + ["b"]=>
  50351. + string(7) "INTEGER"
  50352. + ["c"]=>
  50353. + string(11) "VARCHAR(10)"
  50354. + ["d"]=>
  50355. + string(0) ""
  50356. +}
  50357. --- /dev/null
  50358. +++ b/ext/sqlite/tests/sqlite_oo_029.phpt
  50359. @@ -0,0 +1,53 @@
  50360. +--TEST--
  50361. +sqlite-oo: call method with $this
  50362. +--SKIPIF--
  50363. +<?php # vim:ft=php
  50364. +if (!extension_loaded("sqlite")) print "skip";
  50365. +?>
  50366. +--FILE--
  50367. +<?php
  50368. +include "blankdb_oo.inc";
  50369. +
  50370. +$db->query("CREATE TABLE strings(key VARCHAR(10), var VARCHAR(10))");
  50371. +$db->query("INSERT INTO strings VALUES('foo', 'foo')");
  50372. +
  50373. +class sqlite_help
  50374. +{
  50375. + function __construct($db){
  50376. + $this->db = $db;
  50377. + $this->db->createFunction('link_keywords', array(&$this, 'linkers'), 1);
  50378. + }
  50379. +
  50380. + function getSingle($key)
  50381. + {
  50382. + return $this->db->singleQuery('SELECT link_keywords(var) FROM strings WHERE key=\''.$key.'\'', 1);
  50383. + }
  50384. +
  50385. + function linkers($str)
  50386. + {
  50387. + $str = str_replace('foo', 'bar', $str);
  50388. + return $str;
  50389. + }
  50390. +
  50391. + function free()
  50392. + {
  50393. + unset($this->db);
  50394. + }
  50395. +
  50396. + function __destruct()
  50397. + {
  50398. + echo "DESTRUCTED\n";
  50399. + }
  50400. +}
  50401. +
  50402. +$obj = new sqlite_help($db);
  50403. +echo $obj->getSingle('foo')."\n";
  50404. +$obj->free();
  50405. +unset($obj);
  50406. +
  50407. +?>
  50408. +===DONE===
  50409. +--EXPECT--
  50410. +bar
  50411. +===DONE===
  50412. +DESTRUCTED
  50413. --- /dev/null
  50414. +++ b/ext/sqlite/tests/sqlite_oo_030.phpt
  50415. @@ -0,0 +1,44 @@
  50416. +--TEST--
  50417. +sqlite-oo: calling static methods
  50418. +--INI--
  50419. +sqlite.assoc_case=0
  50420. +--SKIPIF--
  50421. +<?php # vim:ft=php
  50422. +if (!extension_loaded("sqlite")) print "skip";
  50423. +?>
  50424. +--FILE--
  50425. +<?php
  50426. +
  50427. +require_once('blankdb_oo.inc');
  50428. +
  50429. +class foo {
  50430. + static function bar($param = NULL) {
  50431. + return $param;
  50432. + }
  50433. +}
  50434. +
  50435. +function baz($param = NULL) {
  50436. + return $param;
  50437. +}
  50438. +
  50439. +var_dump($db->singleQuery("select php('baz')", 1));
  50440. +var_dump($db->singleQuery("select php('baz', 1)", 1));
  50441. +var_dump($db->singleQuery("select php('baz', \"PHP\")", 1));
  50442. +var_dump($db->singleQuery("select php('foo::bar')", 1));
  50443. +var_dump($db->singleQuery("select php('foo::bar', 1)", 1));
  50444. +var_dump($db->singleQuery("select php('foo::bar', \"PHP\")", 1));
  50445. +var_dump($db->singleQuery("select php('foo::bar(\"PHP\")')", 1));
  50446. +
  50447. +?>
  50448. +===DONE===
  50449. +--EXPECTF--
  50450. +NULL
  50451. +string(1) "1"
  50452. +string(3) "PHP"
  50453. +NULL
  50454. +string(1) "1"
  50455. +string(3) "PHP"
  50456. +
  50457. +Warning: SQLiteDatabase::singleQuery(): function `foo::bar("PHP")' is not a function name in %ssqlite_oo_030.php on line %d
  50458. +bool(false)
  50459. +===DONE===
  50460. --- /dev/null
  50461. +++ b/ext/sqlite/tests/sqlite_popen_basic.phpt
  50462. @@ -0,0 +1,27 @@
  50463. +--TEST--
  50464. +SQLite: sqlite_popen() basic tests
  50465. +--SKIPIF--
  50466. +<?php if (!extension_loaded("sqlite")) print "skip"; ?>
  50467. +--FILE--
  50468. +<?php
  50469. +/* Prototype : resource sqlite_popen(string filename [, int mode [, string &error_message]])
  50470. + * Description: Opens a persistent handle to a SQLite database. Will create the database if it does not exist.
  50471. + * Source code: ext/sqlite/sqlite.c
  50472. + * Alias to functions:
  50473. +*/
  50474. +
  50475. + $db1 = sqlite_popen(":memory:");
  50476. + $db2 = sqlite_popen(":memory:");
  50477. +
  50478. + var_dump($db1);
  50479. + var_dump($db2);
  50480. +
  50481. + list($resourceId1) = sscanf((string) $db1, "resource(%d) of type (sqlite database (persistent))");
  50482. + list($resourceId2) = sscanf((string) $db2, "resource(%d) of type (sqlite database (persistent))");
  50483. +
  50484. + var_dump($resourceId1 === $resourceId2);
  50485. +?>
  50486. +--EXPECTF--
  50487. +resource(%d) of type (sqlite database (persistent))
  50488. +resource(%d) of type (sqlite database (persistent))
  50489. +bool(true)
  50490. --- /dev/null
  50491. +++ b/ext/sqlite/tests/sqlite_popen_error.phpt
  50492. @@ -0,0 +1,34 @@
  50493. +--TEST--
  50494. +Test sqlite_popen() function : error conditions
  50495. +--SKIPIF--
  50496. +<?php if (!extension_loaded("sqlite")) print "skip sqlite extension not loaded"; ?>
  50497. +--FILE--
  50498. +<?php
  50499. +/* Prototype : resource sqlite_popen(string filename [, int mode [, string &error_message]])
  50500. + * Description: Opens a persistent handle to a SQLite database. Will create the database if it does not exist.
  50501. + * Source code: ext/sqlite/sqlite.c
  50502. + * Alias to functions:
  50503. + */
  50504. +
  50505. +$message = '';
  50506. +
  50507. +echo "*** Testing sqlite_popen() : error conditions ***\n";
  50508. +
  50509. +var_dump( sqlite_popen() );
  50510. +var_dump( sqlite_popen(":memory:", 0666, $message, 'foobar') );
  50511. +var_dump( sqlite_popen("", 0666, $message) );
  50512. +var_dump( $message );
  50513. +
  50514. +?>
  50515. +===DONE===
  50516. +--EXPECTF--
  50517. +*** Testing sqlite_popen() : error conditions ***
  50518. +
  50519. +Warning: sqlite_popen() expects at least 1 parameter, 0 given in %s on line %d
  50520. +NULL
  50521. +
  50522. +Warning: sqlite_popen() expects at most 3 parameters, 4 given in %s on line %d
  50523. +NULL
  50524. +bool(false)
  50525. +NULL
  50526. +===DONE===
  50527. --- /dev/null
  50528. +++ b/ext/sqlite/tests/sqlite_session_001.phpt
  50529. @@ -0,0 +1,46 @@
  50530. +--TEST--
  50531. +sqlite, session storage test
  50532. +--CREDITS--
  50533. +Mats Lindh <mats at lindh.no>
  50534. +#Testfest php.no
  50535. +--INI--
  50536. +session.save_handler = sqlite
  50537. +--SKIPIF--
  50538. +if (!extension_loaded("session"))
  50539. +{
  50540. + die("skip Session module not loaded");
  50541. +}
  50542. +if (!extension_loaded("sqlite"))
  50543. +{
  50544. + die("skip Session module not loaded");
  50545. +}
  50546. +--FILE--
  50547. +<?php
  50548. +/* Description: Tests that sqlite can be used as a session save handler
  50549. +* Source code: ext/sqlite/sess_sqlite.c
  50550. +*/
  50551. +
  50552. +ob_start();
  50553. +session_save_path(__DIR__ . "/sessiondb.sdb");
  50554. +
  50555. +// create the session and set a session value
  50556. +session_start();
  50557. +$_SESSION["test"] = "foo_bar";
  50558. +
  50559. +// close the session and unset the value
  50560. +session_write_close();
  50561. +unset($_SESSION["test"]);
  50562. +var_dump(isset($_SESSION["test"]));
  50563. +
  50564. +// start the session again and check that we have the proper value
  50565. +session_start();
  50566. +var_dump($_SESSION["test"]);
  50567. +ob_end_flush();
  50568. +?>
  50569. +--EXPECTF--
  50570. +bool(false)
  50571. +%unicode|string%(7) "foo_bar"
  50572. +--CLEAN--
  50573. +<?php
  50574. + unlink(__DIR__ . "/sessiondb.sdb")
  50575. +?>
  50576. --- /dev/null
  50577. +++ b/ext/sqlite/tests/sqlite_session_002.phpt
  50578. @@ -0,0 +1,54 @@
  50579. +--TEST--
  50580. +sqlite, session destroy test
  50581. +--CREDITS--
  50582. +Mats Lindh <mats at lindh.no>
  50583. +#Testfest php.no
  50584. +--INI--
  50585. +session.save_handler = sqlite
  50586. +--SKIPIF--
  50587. +if (!extension_loaded("session"))
  50588. +{
  50589. + die("skip Session module not loaded");
  50590. +}
  50591. +if (!extension_loaded("sqlite"))
  50592. +{
  50593. + die("skip sqlite module not loaded");
  50594. +}
  50595. +--FILE--
  50596. +<?php
  50597. +/* Description: Tests that sqlite will destroy a session when used as a session handler
  50598. +* Source code: ext/sqlite/sess_sqlite.c
  50599. +*/
  50600. +ob_start();
  50601. +session_save_path(__DIR__ . "/sessiondb.sdb");
  50602. +
  50603. +// start a session and save a value to it before commiting the session to the database
  50604. +session_start();
  50605. +$_SESSION["test"] = "foo_bar";
  50606. +session_write_close();
  50607. +
  50608. +// remove the session value
  50609. +unset($_SESSION["test"]);
  50610. +var_dump(isset($_SESSION["test"]));
  50611. +
  50612. +// start the session again and destroy it
  50613. +session_start();
  50614. +var_dump($_SESSION["test"]);
  50615. +session_destroy();
  50616. +session_write_close();
  50617. +
  50618. +unset($_SESSION["test"]);
  50619. +
  50620. +// check that the session has been destroyed
  50621. +session_start();
  50622. +var_dump(isset($_SESSION["test"]));
  50623. +ob_end_flush();
  50624. +?>
  50625. +--EXPECTF--
  50626. +bool(false)
  50627. +%unicode|string%(7) "foo_bar"
  50628. +bool(false)
  50629. +--CLEAN--
  50630. +<?php
  50631. + unlink(__DIR__ . "/sessiondb.sdb")
  50632. +?>
  50633. --- /dev/null
  50634. +++ b/ext/sqlite/tests/sqlite_spl_001.phpt
  50635. @@ -0,0 +1,125 @@
  50636. +--TEST--
  50637. +sqlite-spl: Iteration
  50638. +--SKIPIF--
  50639. +<?php # vim:ft=php
  50640. +if (!extension_loaded("sqlite")) print "skip";
  50641. +if (!extension_loaded("spl")) print "skip SPL is not present";
  50642. +?>
  50643. +--FILE--
  50644. +<?php
  50645. +include "blankdb_oo.inc";
  50646. +
  50647. +$db->query("CREATE TABLE menu(id_l int PRIMARY KEY, id_r int UNIQUE, key VARCHAR(10))");
  50648. +$db->query("INSERT INTO menu VALUES( 1, 12, 'A')");
  50649. +$db->query("INSERT INTO menu VALUES( 2, 9, 'B')");
  50650. +$db->query("INSERT INTO menu VALUES(10, 11, 'F')");
  50651. +$db->query("INSERT INTO menu VALUES( 3, 6, 'C')");
  50652. +$db->query("INSERT INTO menu VALUES( 7, 8, 'E')");
  50653. +$db->query("INSERT INTO menu VALUES( 4, 5, 'D')");
  50654. +
  50655. +class SqliteNestedsetElement
  50656. +{
  50657. + protected $id_l;
  50658. + protected $id_r;
  50659. + protected $key;
  50660. +
  50661. + function __construct($db)
  50662. + {
  50663. + $this->db = $db;
  50664. + }
  50665. +
  50666. + function getLeft()
  50667. + {
  50668. + return $this->id_l;
  50669. + }
  50670. +
  50671. + function getRight()
  50672. + {
  50673. + return $this->id_r;
  50674. + }
  50675. +
  50676. + function __toString()
  50677. + {
  50678. + return $this->key;
  50679. + }
  50680. +
  50681. + function key()
  50682. + {
  50683. + return $this->key;
  50684. + }
  50685. +}
  50686. +
  50687. +class SqliteNestedset implements RecursiveIterator
  50688. +{
  50689. + protected $id;
  50690. + protected $id_l;
  50691. + protected $id_r;
  50692. + protected $entry;
  50693. +
  50694. + function __construct($db, $id_l = 1)
  50695. + {
  50696. + $this->db = $db;
  50697. + $this->id_l = $id_l;
  50698. + $this->id_r = $this->db->singleQuery('SELECT id_r FROM menu WHERE id_l='.$id_l, 1);
  50699. + $this->id = $id_l;
  50700. + }
  50701. +
  50702. + function rewind()
  50703. + {
  50704. + $this->id = $this->id_l;
  50705. + $this->fetch();
  50706. + }
  50707. +
  50708. + function valid()
  50709. + {
  50710. + return is_object($this->entry);
  50711. + }
  50712. +
  50713. + function current()
  50714. + {
  50715. + return $this->entry->__toString();
  50716. + }
  50717. +
  50718. + function key()
  50719. + {
  50720. + return $this->entry->key();;
  50721. + }
  50722. +
  50723. + function next()
  50724. + {
  50725. + $this->id = $this->entry->getRight() + 1;
  50726. + $this->fetch();
  50727. + }
  50728. +
  50729. + protected function fetch()
  50730. + {
  50731. + $res = $this->db->unbufferedQuery('SELECT * FROM menu WHERE id_l='.$this->id);
  50732. + $this->entry = $res->fetchObject('SqliteNestedsetElement', array(&$this->db));
  50733. + unset($res);
  50734. + }
  50735. +
  50736. + function hasChildren()
  50737. + {
  50738. + return $this->entry->getLeft() + 1 < $this->entry->getRight();
  50739. + }
  50740. +
  50741. + function getChildren()
  50742. + {
  50743. + return new SqliteNestedset($this->db, $this->entry->getLeft() + 1, $this->entry->getRight() - 1);
  50744. + }
  50745. +}
  50746. +
  50747. +$menu_iterator = new RecursiveIteratorIterator(new SqliteNestedset($db), RecursiveIteratorIterator::SELF_FIRST);
  50748. +foreach($menu_iterator as $entry) {
  50749. + echo $menu_iterator->getDepth() . $entry . "\n";
  50750. +}
  50751. +?>
  50752. +===DONE===
  50753. +--EXPECT--
  50754. +0A
  50755. +1B
  50756. +2C
  50757. +3D
  50758. +2E
  50759. +1F
  50760. +===DONE===
  50761. --- /dev/null
  50762. +++ b/ext/sqlite/tests/sqlite_spl_002.phpt
  50763. @@ -0,0 +1,29 @@
  50764. +--TEST--
  50765. +sqlite-spl: Countable
  50766. +--SKIPIF--
  50767. +<?php # vim:ft=php
  50768. +if (!extension_loaded("sqlite")) print "skip";
  50769. +if (!extension_loaded("spl")) print "skip SPL is not present";
  50770. +?>
  50771. +--FILE--
  50772. +<?php
  50773. +include "blankdb_oo.inc";
  50774. +
  50775. +$db->query("CREATE TABLE menu(id_l int PRIMARY KEY, id_r int UNIQUE, key VARCHAR(10))");
  50776. +$db->query("INSERT INTO menu VALUES( 1, 12, 'A')");
  50777. +$db->query("INSERT INTO menu VALUES( 2, 9, 'B')");
  50778. +$db->query("INSERT INTO menu VALUES(10, 11, 'F')");
  50779. +$db->query("INSERT INTO menu VALUES( 3, 6, 'C')");
  50780. +$db->query("INSERT INTO menu VALUES( 7, 8, 'E')");
  50781. +$db->query("INSERT INTO menu VALUES( 4, 5, 'D')");
  50782. +
  50783. +$res = $db->query("SELECT * from menu");
  50784. +
  50785. +var_dump($res->count());
  50786. +var_dump(count($res));
  50787. +?>
  50788. +===DONE===
  50789. +--EXPECT--
  50790. +int(6)
  50791. +int(6)
  50792. +===DONE===
  50793. --- /dev/null
  50794. +++ b/ext/sqlite/tests/sqlite_spl_003.phpt
  50795. @@ -0,0 +1,28 @@
  50796. +--TEST--
  50797. +sqlite-spl: Exception
  50798. +--SKIPIF--
  50799. +<?php # vim:ft=php
  50800. +if (!extension_loaded("sqlite")) print "skip";
  50801. +if (!extension_loaded("spl")) print "skip SPL is not present";
  50802. +?>
  50803. +--FILE--
  50804. +<?php
  50805. +
  50806. +try
  50807. +{
  50808. + $db = sqlite_factory();
  50809. +}
  50810. +catch(SQLiteException $e)
  50811. +{
  50812. + $parents = class_parents($e);
  50813. + if (array_key_exists('RuntimeException', $parents))
  50814. + {
  50815. + echo "GOOD\n";
  50816. + }
  50817. +}
  50818. +
  50819. +?>
  50820. +===DONE===
  50821. +--EXPECT--
  50822. +GOOD
  50823. +===DONE===
  50824. --- /dev/null
  50825. +++ b/ext/sqlite/TODO
  50826. @@ -0,0 +1,19 @@
  50827. +- Implement a PDO driver, called sqlite2
  50828. +
  50829. +- Transparent binary encoding of return values from PHP callback functions.
  50830. +
  50831. +- Add user-space callback for the authorizer function (this is potentially
  50832. + very slow, so it needs to be implemented carefully).
  50833. +
  50834. +- Add user-space callback to handle busy databases.
  50835. +
  50836. + o Test how robust we are when a user-space function is registered as
  50837. + a callback for a persistent connection in script A, then script B is
  50838. + called that doesn't register the callback but does make use of the
  50839. + function in an SQL query.
  50840. + --> Our test suite doesn't allow us to test persistent connections
  50841. + at this time :/
  50842. +
  50843. +- Use later version of built-in library
  50844. +
  50845. +vim:tw=78